Deep Learning for Recommender Systems
Classical collaborative filtering treats recommendation as matrix completion: factorize the user-item interaction matrix into latent factors with matrix factorization or ALS. Deep learning extends this in three directions that matter in production â richer feature handling (side information, text, sequences), flexible architectures (two-tower retrieval, sequence models, neural collaborative filtering), and scalable training objectives (sampled softmax, in-batch negatives) that let you train on billions of interactions rather than the sample that fits in memory.
This lesson follows the industrial pipeline shape: an embedding layer that maps sparse IDs into dense space, a retrieval stage that efficiently shortlists candidates from millions of items, and a ranking stage that scores those candidates with a richer model. You will implement the core pieces, understand the training objectives that make each stage work at scale, and learn the offline and online metrics that actually predict business lift.
What You'll Learn
- 1Embed sparse user and item IDs and handle side features in a recommender network
- 2Train a two-tower retrieval model with in-batch negative sampling
- 3Build a neural collaborative filtering ranker that blends embeddings with matrix-factorization structure
- 4Evaluate with recall at K, NDCG, and calibration rather than RMSE alone
Prerequisites
- !PyTorch or TensorFlow fundamentals
- !Matrix factorization for recommendation
- !Basic ranking metrics familiarity
Embeddings: the shared vocabulary of neural recommenders
Every neural recommender starts with the same primitive: a learnable embedding table that maps each discrete ID to a dense vector. Users who interact with similar items learn similar vectors under the same objective; the embedding dimension controls capacity (32â256 typical). Side features â category, brand, text â get their own embeddings or feature columns, concatenated or pooled with the ID embedding.
import torch
import torch.nn as nn
class FeatureEmbeddings(nn.Module):
"""Embed sparse categorical features and concatenate dense fields."""
def __init__(self, field_dims, embed_dim, dense_dim=0):
super().__init__()
self.embedding = nn.EmbeddingBag(sum(field_dims), embed_dim, mode="sum")
self.offsets = torch.tensor([0] + list(torch.cumsum(
torch.tensor(field_dims[:-1]), dim=0)), dtype=torch.long)
self.input_dim = embed_dim * len(field_dims) + dense_dim
def forward(self, sparse, dense=None):
sparse = sparse + self.offsets.to(sparse.device)
emb = self.embedding(sparse) # (batch, field_dims * embed_dim)
if dense is not None and dense.numel() > 0:
emb = torch.cat([emb, dense], dim=-1)
return emb
# Example: user features [user_id, country, device], item features handled separately
user_fields = [50_000, 50, 8] # vocab sizes
fe = FeatureEmbeddings(user_fields, embed_dim=32, dense_dim=2)
user_sparse = torch.randint(0, 50, (4, 3))
user_dense = torch.randn(4, 2)
print(fe(user_sparse, user_dense).shape) # torch.Size([4, 100])
Two practical notes. Use EmbeddingBag (or sparse gradients with nn.Embedding) so training stays efficient on huge vocabularies â full dense gradients over a 10M-item table will not fit. Initialize embeddings small and regularize with weight decay or dropout; unregularized embeddings overfit spurious interactions fast, especially for head users with few events.
Two-tower retrieval: shortlisting millions of items
When the catalog is too large to score every item, retrieval learns two encoders â a user tower and an item tower â that map to a shared vector space where cosine or dot-product similarity approximates relevance. Train with a softmax over a batch of items: the true item is the positive; every other item in the batch is a negative. This in-batch negative trick gives a free, hard-ish negative set without explicit sampling.
import torch
import torch.nn as nn
import torch.nn.functional as F
class TwoTower(nn.Module):
def __init__(self, user_fields, item_fields, embed_dim, tower_dim=128):
super().__init__()
self.user_emb = FeatureEmbeddings(user_fields, embed_dim)
self.item_emb = FeatureEmbeddings(item_fields, embed_dim)
self.user_tower = nn.Sequential(
nn.Linear(self.user_emb.input_dim, tower_dim), nn.ReLU(),
nn.Linear(tower_dim, 64),
)
self.item_tower = nn.Sequential(
nn.Linear(self.item_emb.input_dim, tower_dim), nn.ReLU(),
nn.Linear(tower_dim, 64),
)
def encode_user(self, user_sparse, user_dense=None):
return F.normalize(self.user_tower(self.user_emb(user_sparse, user_dense)), dim=-1)
def encode_item(self, item_sparse, item_dense=None):
return F.normalize(self.item_tower(self.item_emb(item_sparse, item_dense)), dim=-1)
def forward(self, u_s, u_d, i_s, i_d):
u = self.encode_user(u_s, u_d)
i = self.encode_item(i_s, i_d)
return (u * i).sum(-1) # cosine similarity for normalized towers
def sampled_softmax_loss(scores, temperature=0.05):
"""In-batch softmax: diagonal is the positive pair."""
logits = scores / temperature
labels = torch.arange(logits.size(0), device=logits.device)
return F.cross_entropy(logits, labels)
model = TwoTower(user_fields=[50_000, 50, 8], item_fields=[200_000, 100, 40], embed_dim=32)
u_sparse = torch.randint(0, 50, (16, 3))
i_sparse = torch.randint(0, 100, (16, 3))
scores = model(u_sparse, None, i_sparse, None)
loss = sampled_softmax_loss(scores)
loss.backward()
print(f"loss={loss.item():.4f}")
Temperature matters more than it looks: low temperatures sharpen the softmax and make training focus on the hardest negatives but can destabilize; high temperatures soften and undertrain. Start around 0.05â0.2 and tune. For serving, pre-compute item embeddings offline and index them in an approximate nearest-neighbor store (FAISS, ScaNN, vector databases) so retrieval is a single ANN query rather than a full catalog scan.
Neural collaborative filtering: blending structure and features
Neural collaborative filtering (NCF) generalizes matrix factorization: it keeps the inner product of user and item embeddings (the MF inductive bias) but adds an MLP over the concatenation to learn nonlinear interaction terms that pure MF cannot express. The classic NeuMF architecture trains GMF and MLP towers jointly, but a simpler residual blend is often enough and easier to tune.
import torch
import torch.nn as nn
import torch.nn.functional as F
class NCFRanker(nn.Module):
def __init__(self, n_users, n_items, embed_dim=32, mlp_dims=(64, 32, 16)):
super().__init__()
self.user_emb = nn.Embedding(n_users, embed_dim)
self.item_emb = nn.Embedding(n_items, embed_dim)
self.gmf = nn.Linear(embed_dim, 1)
layers, in_dim = [], embed_dim * 2
for d in mlp_dims:
layers += [nn.Linear(in_dim, d), nn.ReLU(), nn.Dropout(0.2)]
in_dim = d
self.mlp = nn.Sequential(*layers)
self.final = nn.Linear(in_dim + 1, 1)
def forward(self, user_ids, item_ids):
u, i = self.user_emb(user_ids), self.item_emb(item_ids)
gmf_score = self.gmf(u * i) # elementwise product
mlp_out = self.mlp(torch.cat([u, i], dim=-1))
logit = self.final(torch.cat([gmf_score, mlp_out], dim=-1)).squeeze(-1)
return logit
ranker = NCFRanker(n_users=50_000, n_items=200_000)
users = torch.randint(0, 50_000, (256,))
items = torch.randint(0, 200_000, (256,))
labels = torch.randint(0, 2, (256,)).float()
logits = ranker(users, items)
loss = F.binary_cross_entropy_with_logits(logits, labels)
loss.backward()
print(f"BCE loss={loss.item():.4f}")
Pairwise objectives (BPR â Bayesian personalized ranking) often beat pointwise BCE for implicit feedback because they optimize relative order (positive item ranked above negative) rather than absolute click probability. BPR's loss is -log(sigmoid(pos_score - neg_score)); implement it by sampling negatives per positive, or by reusing in-batch items as negatives like the two-tower model.
Training at scale: negatives, sequences, and hard cases
In-batch negatives are efficient but easy: random items the user almost certainly would not have clicked anyway. Hard negatives â items the model currently ranks highly but that are not the target â sharpen the decision boundary and improve retrieval recall on the hardest slice of the catalog. Mine them from an ANN index refreshed periodically, or from the current model's top-K misses.
Sequential models (GRU4Rec, SASRec-style transformers) treat a user's session as a sequence and predict the next item, capturing short-term intent that static embeddings miss â someone searching for a laptop this week is not the same recommender persona as their long-term history suggests. Blend session-based scores with long-term two-tower scores in the ranker for the best of both.
| Objective | Strength | Weakness |
|---|---|---|
| Pointwise BCE | Simple, calibrated probabilities | Weak relative ordering signal |
| BPR (pairwise) | Optimizes ranking directly | Negative sampling sensitive |
| Sampled softmax | Scales to huge catalogs | Temperature tuning required |
| Listwise (approx NDCG) | Direct metric alignment | Complex, unstable at scale |
Cold-start: new users, new items, and sparse signals
New items with no interactions cannot benefit from collaborative signal at all; the embedding row for a freshly created item is either uninitialized or trained on one or two examples. The standard remedy is content-based fallback: encode available side information â title text, category, price band, image features â through the same item tower, so a new item inherits a sensible embedding from its attributes rather than from its interaction history. At serving time, route new items through this content path until they accumulate enough events to trust their collaborative embedding.
New users face the same problem from the other side. Session-based signals â the current browsing or search sequence â carry immediate intent that a cold-start user ID cannot. A practical hybrid scores candidates as a blend of the session-based sequence model and a popularity prior weighted by the user's declared profile features (age band, locale, device) when available, annealing toward pure collaborative scoring as the user's event count grows past a threshold calibrated on historical data.
Sparsity is not limited to genuinely new entities; long-tail users and items with only a handful of interactions produce noisy embeddings that overfit. Weight decay, minimum interaction thresholds before trusting a user's collaborative embedding, and content-feature fallback below that threshold keep predictions stable. Track cold-start slices separately in offline evaluation â a model can look strong overall while failing exactly the slice that dominates the first week of any new product launch.
Evaluation: metrics that predict online lift
Offline RMSE is nearly useless for modern recommenders â predicting a 4.0 versus 4.1 star rating poorly correlates with whether someone clicks. Retrieval is evaluated with recall@K and hit rate@K on held-out interactions (did the true next item appear in the ANN top-K). Ranking is evaluated with NDCG@K and mean average precision, which reward putting the relevant item high in the list, not just anywhere in it.
import numpy as np
def recall_at_k(recommended: list, relevant: set, k: int) -> float:
top_k = recommended[:k]
hits = len(set(top_k) & relevant)
return hits / len(relevant) if relevant else 0.0
def ndcg_at_k(recommended: list, relevant: set, k: int) -> float:
dcg = sum(1.0 / np.log2(i + 2) for i, item in enumerate(recommended[:k])
if item in relevant)
ideal = sum(1.0 / np.log2(i + 2) for i in range(min(len(relevant), k)))
return dcg / ideal if ideal > 0 else 0.0
recs = [10, 20, 30, 40, 50]
rel = {20, 40, 99}
print(f"recall@5={recall_at_k(recs, rel, 5):.3f}") # 2/3 relevant found
print(f"ndcg@5={ndcg_at_k(recs, rel, 5):.3f}")
# Calibration: does the model predict the right click-through rate?
def calibration(predicted: np.ndarray, observed: np.ndarray, bins=10) -> float:
edges = np.quantile(predicted, np.linspace(0, 1, bins + 1))
err = 0.0
for b in range(bins):
mask = (predicted >= edges[b]) & (predicted < edges[b + 1])
if mask.sum() > 0:
err += abs(predicted[mask].mean() - observed[mask].mean()) * mask.sum()
return err / len(predicted)
rng = np.random.default_rng(0)
print(f"calibration err={calibration(rng.random(1000), rng.binomial(1, 0.3, 1000)):.3f}")
Beyond point metrics, check coverage (what fraction of the catalog ever gets recommended â low coverage means popularity collapse), novelty/diversity (are we surfacing the long tail or only blockbusters), and freshness (how quickly new items enter rotation). Online, run interleaving or A/B tests on session length, conversion, and revenue per user â offline gains that do not move these are usually noise or metric gaming.
Common Mistakes
Optimizing RMSE and shipping a model that cannot retrieve relevant items
Fix: Evaluate recall@K/NDCG@K on the retrieval stage and ranking metrics on the ranker; keep RMSE only for explicitly-rated regression tasks.
Using only random in-batch negatives and wondering why retrieval recall plateaus
Fix: Add hard negatives mined from the model's current top-K misses; they teach the embedding space on the boundary where ranking errors matter.
Serving an unregularized embedding model that memorizes head users
Fix: Apply weight decay and dropout to embeddings, and monitor long-tail item coverage â collapse to popularity is the most common production failure.
Forgetting to refresh item embeddings in the ANN index after retraining
Fix: Version the index with the model and rebuild it as part of the same pipeline; stale embeddings silently degrade retrieval quality.
Best Practices
- Start with two-tower retrieval + a lightweight ranker; add sequence models only when session data shows clear short-term intent signal
- Normalize tower outputs and tune softmax temperature; they control retrieval geometry more than tower depth does
- Mine hard negatives periodically from an ANN index refreshed on a schedule aligned with retraining
- Track calibration, coverage, and novelty alongside NDCG to catch popularity collapse early
- Rebuild ANN indexes as an atomic part of every model deployment; serving stale item vectors is a silent quality regression
Interview Questions
Q1: Why use two towers instead of scoring every item with a single network?
Two towers let item embeddings be precomputed and indexed for ANN lookup, turning scoring millions of items into a sublinear search. A monolithic ranker cannot be pre-indexed because scores depend jointly on user and item inputs.
Q2: What are in-batch negatives and what is their main weakness?
Other items in the same training batch treated as negatives, giving free negative samples and efficient softmax computation. The weakness is that most are easy negatives the model already ranks correctly, so the gradient signal is weak on the decision boundary â hence hard-negative mining.
Q3: Why is calibration important for recommenders if ranking metrics look good?
Downstream systems (bidding, quotas, business rules) consume predicted scores as probabilities. A well-ranked but poorly calibrated model breaks those consumers even if NDCG is high, and can distort exploration-exploitation trade-offs.
Key Takeaways
- Embeddings are the foundation; efficient sparse updates (EmbeddingBag, sparse gradients) and regularization are non-negotiable at catalog scale
- Two-tower retrieval with in-batch negative sampling plus an ANN index is the industrial standard for shortlisting millions of items
- NCF blends the MF inductive bias with MLP flexibility; pairwise BPR objectives often beat pointwise BCE for implicit feedback
- Hard negatives, sequence models, and temperature tuning are the main quality levers once the architecture is in place
- Evaluate with recall@K, NDCG@K, calibration, coverage, and freshness â RMSE does not predict clicks; A/B tests decide ship/no-ship