Predicting Buyer Preferences with PyTorch: A Deep Learning Approach

CK CK 3788 
Created at
Updated at  
1,231 0 0

PyTorch is an open-source machine learning library predominantly used for building and training deep learning models. It provides a flexible, Python-based framework that enables researchers and developers to easily construct neural networks, perform tensor computations, and leverage automatic differentiation for efficient model training and experimentation.

PyTorch supports a vast array of deep learning models spanning diverse domains, encompassing popular architectures for computer vision such as ResNet, VGG, YOLO, U-Net, and Vision Transformers used for image classification, object detection, and segmentation. For natural language processing, models range from recurrent networks like LSTMs and GRUs to advanced Transformer-based architectures including BERT and GPT for tasks like text classification, machine translation, and generation. Furthermore, PyTorch facilitates the development of models for speech recognition, audio processing, tabular data analysis, various generative models such as GANs and VAEs, and complex algorithms within reinforcement learning.

Predicting Buyer Preferences with PyTorch: A Deep Learning Approach

To classify buyer groups based on gender, age, and city for two different products and predict which product a sample buyer might purchase, we can use a classification model in PyTorch. Below is a simplified example that demonstrates how to achieve this. We'll create synthetic data for two products and train a neural network classifier to predict the product based on gender, age, and city.

import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
# Generate synthetic data
np.random.seed(0)
# Sample data: gender (0: male, 1: female), age, city (0: City A, 1: City B)
# For Product 1
product1_data = np.random.randint(0, 2, (1000, 3))  # 1000 samples
# For Product 2
product2_data = np.random.randint(0, 2, (1000, 3))  # 1000 samples
# Define labels: 0 for Product 1, 1 for Product 2
product1_labels = np.zeros((1000,))
product2_labels = np.ones((1000,))
# Combine data and labels
data = np.concatenate([product1_data, product2_data], axis=0)
labels = np.concatenate([product1_labels, product2_labels])
# Convert data and labels to PyTorch tensors
data = torch.tensor(data, dtype=torch.float32)
labels = torch.tensor(labels, dtype=torch.long)
# Define the neural network model
class BuyerClassifier(nn.Module):
    def __init__(self):
        super(BuyerClassifier, self).__init__()
        self.fc1 = nn.Linear(3, 64)  # Input features: gender, age, city
        self.fc2 = nn.Linear(64, 64)
        self.fc3 = nn.Linear(64, 2)   # Output: 2 classes (Product 1 or Product 2)
    def forward(self, x):
        x = torch.relu(self.fc1(x))
        x = torch.relu(self.fc2(x))
        x = self.fc3(x)
        return x
# Initialize the model, loss function, and optimizer
model = BuyerClassifier()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# Train the model
num_epochs = 100
for epoch in range(num_epochs):
    optimizer.zero_grad()
    outputs = model(data)
    loss = criterion(outputs, labels)
    loss.backward()
    optimizer.step()
    if (epoch + 1) % 10 == 0:
        print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')
# Sample data for prediction (gender, age, city)
sample_data = torch.tensor([[1, 35, 0]], dtype=torch.float32)  # Example: Female, 35 years old, City A
# Predict the purchasing product for the sample data
with torch.no_grad():
    model.eval()
    prediction = model(sample_data)
    predicted_class = torch.argmax(prediction).item()
    if predicted_class == 0:
        print("The sample buyer is predicted to purchase Product 1.")
    else:
        print("The sample buyer is predicted to purchase Product 2.")

This code demonstrates a basic example of using PyTorch to classify buyer groups based on gender, age, and city for two different products. It generates synthetic data, defines a neural network classifier, trains the model, and then predicts the purchasing product for a sample buyer based on their demographic information.

 

You may curious if you can use string instead of numeric data for gender and city. Below code shows the example

import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
# Generate synthetic data
np.random.seed(0)
# Sample data: gender (male, female), age, city (City_A, City_B)
# For Product 1
product1_data = np.random.choice(['male', 'female'], (1000, 1))  # 1000 samples
product1_data = np.hstack((product1_data, np.random.randint(18, 65, (1000, 1))))
product1_data = np.hstack((product1_data, np.random.choice(['City_A', 'City_B'], (1000, 1))))
# For Product 2
product2_data = np.random.choice(['male', 'female'], (1000, 1))  # 1000 samples
product2_data = np.hstack((product2_data, np.random.randint(18, 65, (1000, 1))))
product2_data = np.hstack((product2_data, np.random.choice(['City_A', 'City_B'], (1000, 1))))
# Define labels: 0 for Product 1, 1 for Product 2
product1_labels = np.zeros((1000,))
product2_labels = np.ones((1000,))
# Combine data and labels
data = np.concatenate([product1_data, product2_data], axis=0)
labels = np.concatenate([product1_labels, product2_labels])
# Convert string data to numeric using one-hot encoding
data_encoded = np.zeros((data.shape[0], 4))
for i, row in enumerate(data):
    if row[0] == 'male':
        data_encoded[i, 0] = 1
    else:
        data_encoded[i, 1] = 1
    data_encoded[i, 2] = row[1] / 100  # Normalize age to range [0, 1]
    if row[2] == 'City_A':
        data_encoded[i, 3] = 1
    else:
        data_encoded[i, 4] = 1
# Convert data and labels to PyTorch tensors
data = torch.tensor(data_encoded, dtype=torch.float32)
labels = torch.tensor(labels, dtype=torch.long)
# Define the neural network model
class BuyerClassifier(nn.Module):
    def __init__(self):
        super(BuyerClassifier, self).__init__()
        self.fc1 = nn.Linear(4, 64)  # Input features: gender, age, city
        self.fc2 = nn.Linear(64, 64)
        self.fc3 = nn.Linear(64, 2)   # Output: 2 classes (Product 1 or Product 2)
    def forward(self, x):
        x = torch.relu(self.fc1(x))
        x = torch.relu(self.fc2(x))
        x = self.fc3(x)
        return x
# Initialize the model, loss function, and optimizer
model = BuyerClassifier()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# Train the model
num_epochs = 100
for epoch in range(num_epochs):
    optimizer.zero_grad()
    outputs = model(data)
    loss = criterion(outputs, labels)
    loss.backward()
    optimizer.step()
    if (epoch + 1) % 10 == 0:
        print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')
# Sample data for prediction (gender, age, city)
sample_data = torch.tensor([[0, 35 / 100, 1]], dtype=torch.float32)  # Example: Male, 35 years old, City B
# Predict the purchasing product for the sample data
with torch.no_grad():
    model.eval()
    prediction = model(sample_data)
    predicted_class = torch.argmax(prediction).item()
    if predicted_class == 0:
        print("The sample buyer is predicted to purchase Product 1.")
    else:
        print("The sample buyer is predicted to purchase Product 2.")


In the modified code, the main difference lies in how we handle the string data for gender and city attributes:

Data Generation: Instead of generating numeric data directly, we generate string data for gender ('male' or 'female') and city ('City_A' or 'City_B').

Data Encoding: We encode the string data into numeric representations using one-hot encoding. Each categorical variable (gender and city) is represented by a binary vector, where each element indicates the presence or absence of a category.

Model Input Size: Since we're using one-hot encoding, the input size of the neural network model changes accordingly. We now have 4 input features instead of 3: gender_male, gender_female, age (normalized), and city.

Sample Data Encoding: When providing sample data for prediction, we encode it in the same way as the training data, converting string values to their corresponding numeric representations.

Other than these differences related to handling string data and encoding, the overall structure of the code, including data generation, model definition, training, and prediction, remains similar to the original code.
 

Tags Age Artificial Intelligence Buyer Preferences City Classification Customer Segmentation Data Science Deep Learning E-commerce Gender Machine Learning Neural Networks Predictive Analytics Product Classification PyTorch Facebook X
Comments 0
Similar posts
  1. PyTorch example to Forcast Stock Price based on 10 days Dataset
    651
  2. Mastering Ad Budget Throttling: Static, PID, and ML Strategies
    316
  3. Ad Impression Forecasting (aka Ad Inventory Forecasting): Architecting for Scale, Speed, and Accuracy
    327
  4. AI-Powered Ad Fraud Detection: Architectural Strategies
    331
  5. Brand Safety: AI-Driven Content Moderation on AWS
    710
  6. Milvus & FAISS: Decoding Their ML Synergy
    276
  7. TikTok's Recommendation System - Monolith
    286
  8. FAISS Already Does ANN... So Why Do Top Teams Still Pay for SageMaker?
    307
  9. Machine Learning Models for Ad Detection from a Video Stream
    185
  10. Image Embeddings for Vector Databases
    241
  11. Building a MCP server in PHP
    627
  12. Vector Databases: From Embeddings to Application
    310
  13. Building a Video Content Recommendation System with Amazon SageMaker
    521
  14. Python ML Technologies used for the target Segmentation
    376
  15. TensorRT for LLMs: Speed, Scale, and Why Startups Choose It Over TensorFlow
    459
  16. Coding Revolution with Claude Code & MoAI ADK(Agent Development Kit)
    726
  17. Demystifying FAISS: Your Guide to ANN(Approximate Nearest Neighbor) Search
    314
  18. Is PyTorch Dead? Deep Learning's Enduring Role Beyond LLMs & Essential Skills
    691
  19. Netflix's Recommendation System
    412
  20. Arm Kernel DNNs: Powering Efficient AI at the Edge
    221
  21. Autonomous Vehicle Machine Learning (AV ML): An Architectural Review
    395
  22. Why AI-DLC is the New Paradigm for Development?
    325
  23. Designing an Enterprise ML Experiment Tracking and Reproducibility Platform: System Requirements and Architecture
    302
  24. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    252
  25. Forecasting with Linear Regression and KNN Regression in Python
    920
  26. Forecasting the Weather with PyTorch: A Beginner's Guide to Temperature Prediction
    1,430
  27. Checkout service architecture in AWS for e-commerce website
    11,007
  28. Reinforcement Learning–Based Methods for CTR Improvement based on Recommendation System
    262
  29. YouTube's Recommendation System
    258
  30. Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python
    1,154
  1. Implementing Text To Speech / Audio with Python3 and pyttsx3
    354
  2. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    559
  3. Python Simplified Assignment Operators
    533
  4. Trackback module used for Python Threading debugging
    840
  5. Python Flask with simple HTML files to server web pages along with API
    926
  6. Python Flask web server tutorial from the scratch
    618
  7. Simple Web Server based in Python
    368
  8. Thread Implementation in Python
    507
  9. A shell script that activates a Python virtual environment and then runs a specific Python script
    741
  10. Learning about Python Multiprocessing Technique
    591
  11. Simple Example to get the total number of records in BigQuery with Python
    665
  12. Using BigQuery in Python
    407
  13. Python Web Programming based on Django from the Scratch
    366
  14. Flink with Python: Core Concepts, Kafka Integration, and Architectural Trade-offs
    184
  15. How do I determine the client IP type in Python - IPv4 or IPv6
    760
  16. PyTorch example to Forcast Stock Price based on 10 days Dataset
    651
  17. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,067
  18. Dynamic DNS Made Easy: Building a Python-Based Solution
    793
  19. Milvus & FAISS: Decoding Their ML Synergy
    276
  20. Save clustering result (aka dictionary) in JSON and Reuse loaded result
    376
  21. Forecasting with Linear Regression and KNN Regression in Python
    920
  22. Forecasting the Weather with PyTorch: A Beginner's Guide to Temperature Prediction
    1,430
  23. Uvicorn, Gunicorn: Proving Your Production Prowess
    395
  24. Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python
    1,154
  25. Harnessing the Power of Random Forest Algorithm in Python
    657
  26. Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python
    630
  27. Mastering Random Forest Regression: A Comprehensive Guide with Python Examples
    1,093
  28. Simple Python Clustering Example based on the high school students' score
    339
  29. Getting Started with PyTorch: A Beginner's Guide to Building Your First Neural Network
    799
  30. Memory Problems with Python Arrays? Discover Dask Array
    321
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,709
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    85
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    197
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    232
  17. The Concept of Scaffolding in AI Agents
    221
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    575
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    252
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    326
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252