Build a Product Recommender: TensorFlow for E-Commerce — Blog Post

# Build a Product Recommender with TensorFlow: From Zero to E-Commerce Hero

Imagine this: A customer lands on your online store for the first time. They browse for five seconds, see a pair of wireless headphones, and click. Within seconds, your system suggests three other products—a charging case, a portable DAC, and noise-isolating ear tips. The customer adds all three to their cart. Your conversion rate just jumped 40%.

This isn't magic. It's a product recommender system powered by TensorFlow. And in this blog post, I'm going to show you exactly how to build one.

Recommendation engines are the silent workhorses behind Amazon's 35% of revenue, Netflix's 80% of watched content, and Spotify's uncanny ability to find your next favorite song. But here's the truth: most e-commerce platforms still rely on basic “customers also bought” rules. They're missing out on millions in potential revenue.

The good news? You don't need a team of PhDs to build a world-class recommender. With TensorFlow, a solid dataset, and the right approach, you can create a system that learns user preferences, handles new products, and scales with your business.

In this guide, I'll walk you through the complete journey—from setting up your environment to deploying a REST API that powers real-time recommendations. By the end, you'll have a fully functional engine you can plug into any online store.

## Section 1: Understanding the Two Pillars of Recommendation

Before we write a single line of code, we need to understand the fundamental problem: how do you predict what a user will like when you have millions of products and thousands of users?

The answer comes in two flavors: **collaborative filtering** and **content-based filtering**. Think of them as the yin and yang of recommendation systems.

### Collaborative Filtering: The Wisdom of Crowds

Collaborative filtering operates on a simple principle: users who agreed in the past will agree in the future. If Alice bought three sci-fi books and Bob bought two of the same three, the system predicts Bob will like the third one Alice bought.

The beauty of collaborative filtering is that it doesn't need to understand what a “sci-fi book” is. It only needs user-item interactions—ratings, purchases, clicks. It discovers patterns automatically.

**Real-world example:** Amazon's “Frequently bought together” section is pure collaborative filtering. When you buy a laptop, thousands of other customers bought a mouse with it. The system doesn't know why—it just knows the pattern exists.

### Content-Based Filtering: Understanding What Things Are

Content-based filtering takes a different approach. Instead of looking at user behavior, it looks at product features. If a user liked a horror movie starring Nicolas Cage, the system finds other horror movies or other Nicolas Cage movies.

This approach requires feature engineering—you need to extract meaningful attributes from your products. For books, that might be genre, author, and page count. For electronics, it could be brand, price range, and specifications.

**Real-world example:** Spotify's “Recommended for you” radio uses content-based features like genre, tempo, and acoustic properties to find songs similar to your current playlist.

### The Hybrid Advantage

Here's the kicker: the best systems combine both approaches. Pure collaborative filtering suffers from the **cold-start problem**—it can't recommend new products with no interaction history. Pure content-based filtering can't discover unexpected connections (like the fact that people who buy diapers also buy beer).

A hybrid system uses collaborative filtering for established products and content-based features to handle new items. We'll build exactly this in Section 4.

## Section 2: Building a Collaborative Filtering Model with Matrix Factorization

Let's get our hands dirty. We'll start with the most powerful technique for collaborative filtering: **matrix factorization**.

### The Core Idea

Imagine you have a matrix where rows are users, columns are products, and each cell contains a rating (1-5 stars). Most cells are empty—users have only rated a tiny fraction of products. This is the **sparsity problem**.

Matrix factorization decomposes this sparse matrix into two dense matrices:
– A **user matrix** (users × latent factors)
– A **product matrix** (products × latent factors)

Latent factors are hidden features the model learns automatically—like “how much does this user like action movies?” or “how premium is this product?”

### Step-by-Step Implementation with TensorFlow

Let's use the classic MovieLens dataset (but the same code works for Amazon product reviews or any e-commerce data).

“`python
import tensorflow as tf
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split

# Load your dataset (here we use MovieLens format)
ratings = pd.read_csv(‘ratings.csv')
users = ratings[‘userId'].unique()
products = ratings[‘movieId'].unique()

# Create user and product lookup tables
user_ids = {uid: i for i, uid in enumerate(users)}
product_ids = {pid: i for i, pid in enumerate(products)}

# Map to indices
ratings[‘user_idx'] = ratings[‘userId'].map(user_ids)
ratings[‘product_idx'] = ratings[‘movieId'].map(product_ids)

# Split data
train, test = train_test_split(ratings, test_size=0.2, random_state=42)

# Build the model
class MatrixFactorization(tf.keras.Model):
def __init__(self, n_users, n_products, n_factors=50):
super().__init__()
self.user_embedding = tf.keras.layers.Embedding(n_users, n_factors)
self.product_embedding = tf.keras.layers.Embedding(n_products, n_factors)
self.user_bias = tf.keras.layers.Embedding(n_users, 1)
self.product_bias = tf.keras.layers.Embedding(n_products, 1)

def call(self, inputs):
user, product = inputs
user_vec = self.user_embedding(user)
product_vec = self.product_embedding(product)
user_b = self.user_bias(user)
product_b = self.product_bias(product)

# Dot product + biases
interaction = tf.reduce_sum(user_vec * product_vec, axis=1, keepdims=True)
return interaction + user_b + product_b

# Instantiate and compile
n_users = len(users)
n_products = len(products)
model = MatrixFactorization(n_users, n_products, n_factors=50)
model.compile(optimizer='adam', loss='mse')

# Train
history = model.fit(
[train[‘user_idx'].values, train[‘product_idx'].values],
train[‘rating'].values,
batch_size=256,
epochs=10,
validation_split=0.1
)
“`

**What just happened?** We created embeddings that map each user and product to a 50-dimensional vector. The model learns these vectors by minimizing the difference between predicted and actual ratings. After training, the dot product of a user vector and product vector gives us the predicted rating.

### Evaluating Performance

We use RMSE (Root Mean Square Error) to measure how far our predictions are from actual ratings:

“`python
predictions = model.predict([test[‘user_idx'].values, test[‘product_idx'].values])
rmse = np.sqrt(np.mean((predictions.flatten() – test[‘rating'].values) ** 2))
print(f”Test RMSE: {rmse:.4f}”)
“`

A good RMSE on MovieLens is around 0.85-0.95 (on a 5-point scale). But RMSE isn't everything—in e-commerce, **ranking metrics** matter more. We care about whether the top-10 recommendations are relevant, not whether we perfectly predict a 4.2 vs 4.3 rating.

## Section 3: Building a Content-Based Model with Product Features

Now let's tackle the cold-start problem. When a new product arrives with zero ratings, collaborative filtering fails. Content-based filtering saves the day.

### Feature Engineering for E-Commerce

For an electronics store, product features might include:
– Category (laptop, phone, accessory)
– Brand (Apple, Samsung, Sony)
– Price range (budget, mid-range, premium)
– Specifications (RAM, storage, screen size)
– Text descriptions (product title, reviews)

We need to convert these into numerical vectors. Let's use a simplified example with Amazon electronics:

“`python
# Sample product data
products = pd.DataFrame({
‘product_id': [101, 102, 103, 104],
‘title': [‘Wireless Headphones', ‘Laptop Stand', ‘USB-C Hub', ‘Mechanical Keyboard'],
‘category': [‘audio', ‘accessories', ‘accessories', ‘peripherals'],
‘brand': [‘Sony', ‘AmazonBasics', ‘Anker', ‘Logitech'],
‘price': [150, 35, 45, 120]
})

# One-hot encode categorical features
from sklearn.preprocessing import OneHotEncoder, StandardScaler

cat_features = [‘category', ‘brand']
ohe = OneHotEncoder(sparse_output=False)
cat_encoded = ohe.fit_transform(products[cat_features])

# Normalize numerical features
scaler = StandardScaler()
price_scaled = scaler.fit_transform(products[[‘price']])

# Combine into feature matrix
import numpy as np

soundicon

STAY AHEAD OF THE AI REVOLUTION

Be the first to get AI tool reviews, automation guides, and insider strategies to build wealth with smart technology.

We don’t spam! Read our privacy policy for more info.

Guitarist

Get the AI Edge, Weekly

The tools, tutorials, and trends that actually pay — no hype.

Featured on
Listed on DevTool.ioListed on SaaSHubFeatured on FoundrList