Recommendation Engines: Collaborative to Hybrid
Every major content and commerce platform runs a recommender: Netflix on the home page, Amazon in "customers also bought", Spotify in Discover Weekly. At its core the problem is deceptively simple â predict how a user would rate or engage with an item they have not yet seen, then serve the top-N predictions. The engineering difficulty comes from sparsity (each user interacts with a tiny fraction of the catalog), cold start (new users and items have no history), and the constant tension between accuracy and diversity.
This lesson builds the classic stack from scratch in Python: user-based and item-based collaborative filtering, matrix factorization via SVD and alternating least squares (ALS), content-based filtering from item features, and a hybrid that blends them. You will also learn the evaluation discipline that separates an offline metric from a business result.
What You'll Learn
- 1Explain collaborative filtering and the cold-start problem
- 2Implement user-based and item-based CF with cosine similarity
- 3Factorize the user-item matrix with truncated SVD and ALS
- 4Blend collaborative and content-based signals in a hybrid recommender
Prerequisites
- !pandas and NumPy
- !scikit-learn for cosine similarity and train/test splitting
- !Basic linear algebra: matrices, SVD intuition
The prediction problem
A recommender starts from an interaction matrix: users on rows, items on columns, cells holding ratings, clicks, or watch time. Most cells are empty â a typical catalog has less than 1% observed entries. The algorithms below differ mainly in how they fill those gaps.
Three families dominate. Collaborative filtering uses only the interaction matrix: users who agreed in the past will agree again. Content-based filtering uses item metadata: if you liked one thriller, recommend other thrillers. Hybrid methods combine both, which is what production systems do because each family fails where the other succeeds â collaborative filtering collapses for new users, content-based cannot discover taste beyond an item's declared features.
| Method | Signal used | Cold-start OK? | Scales to | Main weakness |
|---|---|---|---|---|
| User-based CF | Interaction matrix | No (needs history) | 10k users | Slow to update, user drift |
| Item-based CF | Interaction matrix | Partially (new items via features) | 100k items | Catalog churn |
| Matrix factorization (SVD/ALS) | Interaction matrix | No | Millions of users à items | Needs careful regularization |
| Content-based | Item metadata + history | Yes for new items | Any catalog | Over-specialization, echo chamber |
| Hybrid | Both | Best coverage | Production scale | Complexity, weight tuning |
Generating and inspecting interaction data
Before choosing an algorithm, look at the data: rating distributions are skewed toward extremes, activity is power-law distributed (a few power users generate most interactions), and sparsity is the default state.
import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.decomposition import TruncatedSVD
from scipy.sparse import csr_matrix
rng = np.random.default_rng(42)
n_users, n_items, n_factors = 500, 300, 8
# Latent structure: ratings = user preferences x item qualities + noise
U = rng.normal(0, 0.6, (n_users, n_factors))
V = rng.normal(0, 0.6, (n_items, n_factors))
dense = U @ V.T + rng.normal(0, 0.15, (n_users, n_items))
dense = np.clip(dense * 2 + 3.2, 1, 5)
# Observe only 20% of cells (realistic sparsity)
mask = rng.random((n_users, n_items)) < 0.20
rows, cols = np.where(mask)
interactions = pd.DataFrame({
"user_id": rows,
"item_id": cols,
"rating": dense[rows, cols].round(2),
})
print(f"Interactions: {len(interactions):,}")
print(f"Sparsity: {1 - len(interactions) / (n_users * n_items):.1%}")
print(interactions["rating"].describe())
print(interactions.groupby("user_id").size().describe())
Note the sparsity figure: at 20% observed, a matrix factorization already has enough signal. Real platforms run at 0.1% or lower, which is why regularization and implicit-feedback methods matter more than raw model capacity.
User-based collaborative filtering
User-based CF finds the k most similar users to the target, restricts to those who rated the candidate item, and computes a similarity-weighted average of their ratings, often mean-centered so generous raters do not dominate.
class UserBasedCF:
def __init__(self, k=25):
self.k = k
def fit(self, df):
self.R = df.pivot_table(index="user_id", columns="item_id",
values="rating").fillna(0)
self.sim = cosine_similarity(self.R)
np.fill_diagonal(self.sim, 0)
self.user_mean = self.R.mean(axis=1).values
self.user_ids = list(self.R.index)
self.item_ids = list(self.R.columns)
return self
def predict(self, user_id, item_id):
if user_id not in self.user_ids or item_id not in self.item_ids:
return float(self.R.values.mean())
u = self.user_ids.index(user_id)
col = self.R[item_id].values
raters = np.where(col > 0)[0]
if len(raters) == 0:
return float(self.user_mean[u])
sims = self.sim[u, raters]
top = np.argsort(sims)[-self.k:]
top_raters, top_sims = raters[top], sims[top]
if np.abs(top_sims).sum() == 0:
return float(self.user_mean[u])
pred = self.user_mean[u] + np.sum(
top_sims * (col[top_raters] - self.user_mean[top_raters])
) / np.abs(top_sims).sum()
return float(np.clip(pred, 1, 5))
ubcf = UserBasedCF(k=25).fit(interactions)
print(f"User-based CF, user 7 item 12: {ubcf.predict(7, 12):.2f}")
User-based CF updates poorly: every new rating changes a user's similarity to everyone. Item-based CF is usually preferred in production because the item-item similarity matrix changes more slowly, which allows caching.
Item-based collaborative filtering and matrix factorization
Item-based CF mirrors the user approach over the transposed matrix: find items similar to those the user already rated, and predict from their ratings of those neighbors. Matrix factorization takes a different route â decompose the matrix into low-rank user and item latent factors whose dot product approximates every observed rating.
class ItemBasedCF:
def __init__(self, k=25):
self.k = k
def fit(self, df):
self.R = df.pivot_table(index="user_id", columns="item_id",
values="rating").fillna(0)
self.sim = cosine_similarity(self.R.T)
np.fill_diagonal(self.sim, 0)
self.user_ids = list(self.R.index)
self.item_ids = list(self.R.columns)
return self
def predict(self, user_id, item_id):
if user_id not in self.user_ids or item_id not in self.item_ids:
return float(self.R.values.mean())
i = self.item_ids.index(item_id)
row = self.R.loc[user_id].values
liked = np.where(row > 0)[0]
if len(liked) == 0:
return float(self.R.values.mean())
sims = self.sim[i, liked]
top = np.argsort(sims)[-self.k:]
if np.abs(sims[top]).sum() == 0:
return float(self.R.values.mean())
pred = np.sum(sims[top] * row[liked[top]]) / np.abs(sims[top]).sum()
return float(np.clip(pred, 1, 5))
class SVDRecommender:
def __init__(self, n_factors=20):
self.n_factors = n_factors
def fit(self, df):
self.R = df.pivot_table(index="user_id", columns="item_id",
values="rating").fillna(0)
self.user_ids = list(self.R.index)
self.item_ids = list(self.R.columns)
self.svd = TruncatedSVD(n_components=self.n_factors, random_state=42)
self.Uf = self.svd.fit_transform(self.R)
self.Vf = self.svd.components_.T
self.global_mean = float(self.R.values[self.R.values > 0].mean())
self.P = self.Uf @ self.Vf.T + self.global_mean
return self
def recommend(self, user_id, n=10):
u = self.user_ids.index(user_id)
scores = self.P[u].copy()
scores[self.R.iloc[u].values > 0] = -np.inf # drop already-seen items
top = np.argsort(scores)[::-1][:n]
return [(self.item_ids[i], float(scores[i])) for i in top]
mf = SVDRecommender(n_factors=20).fit(interactions)
print("Top 5 for user 7:", mf.recommend(7, n=5))
Truncated SVD fills every empty cell, which is both its power and a hazard: the model confidently predicts for items no similar user has seen. In practice, blend the factor reconstruction with the observed-entry mean and add a popularity prior for sparse regions of the matrix.
Alternating least squares for scale
ALS is the workhorse for large implicit-feedback datasets. It holds item factors fixed, solves a small ridge-regression system per user, then holds user factors fixed and solves per item, iterating until convergence. The per-user solves are independent, so ALS parallelizes cleanly â the reason Spark's MLlib made it the default.
class ALS:
def __init__(self, n_factors=20, reg=0.1, n_iter=15):
self.n_factors, self.reg, self.n_iter = n_factors, reg, n_iter
def fit(self, df):
R = df.pivot_table(index="user_id", columns="item_id",
values="rating").fillna(0).values
n_users, n_items = R.shape
mask = (R > 0).astype(float)
self.U = rng.normal(0, 0.1, (n_users, self.n_factors))
self.V = rng.normal(0, 0.1, (n_items, self.n_factors))
eye = self.reg * np.eye(self.n_factors)
for _ in range(self.n_iter):
for u in range(n_users):
idx = np.where(mask[u] > 0)[0]
if len(idx) == 0:
continue
VtV = self.V[idx].T @ self.V[idx] + eye
self.U[u] = np.linalg.solve(VtV, self.V[idx].T @ R[u, idx])
for i in range(n_items):
idx = np.where(mask[:, i] > 0)[0]
if len(idx) == 0:
continue
UtU = self.U[idx].T @ self.U[idx] + eye
self.V[i] = np.linalg.solve(UtU, self.U[idx].T @ R[idx, i])
self.P = self.U @ self.V.T
return self
def predict(self, user_idx, item_idx):
return float(np.clip(self.P[user_idx, item_idx], 1, 5))
als = ALS(n_factors=20, reg=0.1, n_iter=15).fit(interactions)
print(f"ALS prediction (0, 5): {als.predict(0, 5):.2f}")
For implicit feedback (views, clicks, dwell time), replace the binary mask with confidence weights: observed interactions get confidence 1 + alpha * r, unobserved get zero, and the optimizer minimizes confidence-weighted squared error with respect to a preference vector. That is the iALS / implicit library recipe used widely in industry.
Content-based and hybrid recommenders
Content-based filtering scores an item by its similarity to items the user already liked, using feature vectors â genres, TF-IDF over descriptions, learned embeddings. It handles cold-start items naturally: a new movie with genre features can be recommended before anyone rates it. Its failure mode is over-specialization: the system can only recommend things that look like what the user has already seen.
class ContentBasedRecommender:
def __init__(self):
pass
def fit(self, item_features, df):
self.F = item_features # index aligned with item ids
self.sim = cosine_similarity(self.F)
np.fill_diagonal(self.sim, 0)
self.item_ids = list(self.F.index)
self.ratings = df
return self
def predict(self, user_id, item_id):
history = self.ratings[self.ratings["user_id"] == user_id]
if item_id not in self.item_ids or history.empty:
return 3.0
i = self.item_ids.index(item_id)
weights, scores = [], []
for _, row in history.iterrows():
if row["item_id"] in self.item_ids:
j = self.item_ids.index(row["item_id"])
weights.append(self.sim[i, j])
scores.append(row["rating"])
if np.abs(weights).sum() == 0:
return 3.0
return float(np.average(scores, weights=weights))
# Synthetic genre features for the catalog
item_features = pd.DataFrame(
rng.normal(0, 1, (n_items, 12)),
index=list(range(n_items)),
columns=[f"feat_{k}" for k in range(12)],
)
cb = ContentBasedRecommender().fit(item_features, interactions)
print(f"Content-based (0, 5): {cb.predict(0, 5):.2f}")
class HybridRecommender:
def __init__(self, cf_model, cb_model, w_cf=0.7):
self.cf, self.cb, self.w_cf = cf_model, cb_model, w_cf
def predict(self, user_id, item_id):
cf = self.cf.predict(user_id, item_id) if hasattr(self.cf, "predict") else 3.0
cb = self.cb.predict(user_id, item_id)
return float(self.w_cf * cf + (1 - self.w_cf) * cb)
hybrid = HybridRecommender(mf if hasattr(mf, "predict") else ubcf, cb, w_cf=0.7)
print(f"Hybrid (0, 5): {hybrid.predict(0, 5):.2f}")
Hybrid weighting is a modeling decision with a product flavor. Weight collaborative filtering higher for active users with rich history; shift toward content-based for sparse users and new items. A learned meta-model over both score vectors (plus context like time of day and device) is the production pattern at large platforms.
Offline evaluation that predicts online results
Randomly splitting observed ratings measures how well you reconstruct held-out entries â necessary, but not sufficient. Three evaluation upgrades matter. First, temporal splits: train on interactions before time T, test after; random splits leak future preferences into training. Second, ranking metrics (NDCG@K, MAP@K, recall@K) over rating metrics like RMSE, because the product surface is a top-N list, not a predicted star value. Third, coverage and novelty guards: a recommender that only surfaces blockbuster items can score well on RMSE while making the catalog feel tiny.
from sklearn.model_selection import train_test_split
train, test = train_test_split(interactions, test_size=0.2, random_state=42)
mf_eval = SVDRecommender(n_factors=20).fit(train)
preds, actuals = [], []
for _, row in test.iterrows():
u = mf_eval.user_ids.index(row["user_id"]) if row["user_id"] in mf_eval.user_ids else None
i = mf_eval.item_ids.index(row["item_id"]) if row["item_id"] in mf_eval.item_ids else None
if u is None or i is None:
continue
preds.append(np.clip(mf_eval.P[u, i], 1, 5))
actuals.append(row["rating"])
rmse = np.sqrt(np.mean((np.array(preds) - np.array(actuals)) ** 2))
mae = np.mean(np.abs(np.array(preds) - np.array(actuals)))
print(f"RMSE={rmse:.4f} MAE={mae:.4f} (n={len(preds)})")
Always pair offline numbers with an online A/B test before shipping. Offline RMSE improvements of 0.01 frequently fail to move click-through rate, while diversity and freshness changes that barely move RMSE can materially improve engagement. Beyond the headline metric, watch guardrail metrics during the experiment: session length, revenue per user, and the fraction of users who see zero relevant recommendations (an empty-state rate that spikes when a model over-specializes). Interleaving, which blends two rankers' results for the same query and measures preference at the click level, converges faster than a standard A/B test and is the better tool when the change is a ranking tweak rather than a whole new model. Log the model version, the candidate-generation config, and the retraining data snapshot with every experiment so a surprising result can be traced to its exact inputs.
Common Mistakes
Filling the matrix with zeros and treating missing ratings as dislike
Fix: Distinguish unobserved from disliked; use masked factorization or confidence-weighted iALS so absent entries do not drag predictions toward zero.
Evaluating with a random split on time-series interaction data
Fix: Split temporally; random splits leak future behavior into training and inflate every metric.
Optimizing only RMSE and shipping a recommender that surfaces ten near-identical popular items
Fix: Track catalog coverage, average item popularity, and intra-list diversity alongside accuracy metrics.
Ignoring cold start until launch day
Fix: Plan content-based fallbacks for new items and onboarding preference collection for new users before the first traffic arrives.
Best Practices
- Start with item-based CF or SVD as the offline baseline; graduate to ALS/iALS at scale
- Use temporal evaluation splits and ranking metrics (NDCG@K, recall@K) that match the product surface
- Cache item-item similarities and refresh asynchronously â they change slowly relative to requests
- Blend content-based scores for cold-start users and items, weighted by confidence in the collaborative signal
- Run online A/B tests for every model change; offline gains are necessary, not sufficient
Interview Questions
Q1: Why is item-based CF often preferred over user-based CF in production?
Item-item similarity is more stable than user-user similarity because catalogs change slower than user behavior, so the similarity matrix can be cached and updated in batch rather than recomputed per request.
Q2: How does ALS handle implicit feedback like clicks?
Confidence-weighted iALS replaces observed/unobserved with a confidence value (for example 1 + alpha times click count), minimizes confidence-weighted squared error against a preference vector, and alternates closed-form ridge solves for user and item factors.
Q3: What is the cold-start problem and how do hybrids mitigate it?
New users have no interaction history and new items have no ratings, so collaborative filtering returns nothing useful. Content-based features and popularity priors provide usable rankings until enough collaborative signal accumulates.
Key Takeaways
- Collaborative filtering exploits agreement structure in the interaction matrix; matrix factorization compresses it into latent factors that generalize across sparse cells
- ALS scales to millions of users and items because per-entity solves are independent and cacheable
- Content-based filtering solves cold-start for items but over-specializes without collaborative diversity
- Hybrid weighting â collaborative for known users, content for sparse ones â is the production default
- Evaluate with temporal splits and ranking metrics, then validate every change with an online A/B test