The one-line mental model
Recommendation is missing-value prediction on a userβitem matrix: collaborative filtering fills gaps from behavior patterns, content-based methods fill them from item features, and matrix factorization learns a low-dimensional geometry that does both at once.
You will be able to:
- Construct a userβitem interaction matrix and measure its sparsity
- Implement user-based and item-based nearest-neighbor recommenders
- Factor the ratings matrix with SVD and reconstruct predictions
- Evaluate with Precision@K, Recall@K, and NDCG instead of RMSE alone
Prerequisites
- !Pandas pivot tables
- !Cosine similarity and dot products
- !Train/test thinking for supervised models
What You'll Learn
- 1Explain the cold-start problem and which family of methods suffers from it
- 2Compute user and item similarity on sparse matrices
- 3Reconstruct ratings from latent factors and biases
- 4Split evaluation data in a way that mimics real recommendation traffic
The matrix you are really filling
Every recommender starts from the same object: a matrix whose rows are users, columns are items, and cells are interactions β explicit ratings, implicit clicks, or purchases. On real platforms the matrix is over 99% empty; the task is to score the empty cells you have not observed and surface the highest ones.
| Approach | Signal used | Strength | Weakness |
|---|---|---|---|
| User-based CF | Similar users' behavior | Captures taste shifts | User profiles churn; expensive at scale |
| Item-based CF | Similar items' co-interactions | Stable item similarity | Struggles with new items |
| Matrix factorization | Latent factors over all data | Compact, accurate at scale | Cold start remains |
| Content-based | Item attributes | Works for new items | Serendude; feature engineering heavy |
| Hybrid | Blends the above | Best of families | Complexity in serving |
Explicit feedback (1β5 stars) gives a dense-enough signal to regress on; implicit feedback (views, dwell, skips) is far more abundant and must be converted into preferences, typically by treating every observed event as positive and sampling unobserved events as negatives.
User-based and item-based collaborative filtering
The nearest-neighbor family computes similarity between rows (users) or columns (items) of the interaction matrix, then predicts a missing cell as a similarity-weighted average of the neighbors who did observe it. Item-based CF is usually preferred in production because catalogs change more slowly than user bases, so the similarity matrix can be precomputed and cached.
import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
rng = np.random.default_rng(42)
n_users, n_items = 200, 80
rows = rng.integers(0, n_users, 1500)
cols = rng.integers(0, n_items, 1500)
vals = rng.integers(1, 6, 1500).astype(float)
ratings = pd.DataFrame({"user_id": rows, "item_id": cols, "rating": vals})
ratings = ratings.drop_duplicates(["user_id", "item_id"], keep="first")
ui = ratings.pivot_table(index="user_id", columns="item_id",
values="rating").fillna(0)
sparsity = 1 - len(ratings) / (ui.shape[0] * ui.shape[1])
print(f"Matrix {ui.shape}, sparsity={sparsity:.1%}")
user_sim = pd.DataFrame(cosine_similarity(ui), index=ui.index,
columns=ui.index)
def predict_user_based(user_id, item_id, k=10):
if item_id not in ui.columns:
return ui.loc[user_id].mean()
rated = ui.loc[user_id] > 0
candidates = ui.index[ui[item_id] > 0].difference([user_id])
if len(candidates) == 0:
return ui[item_id].mean()
sims = user_sim.loc[user_id, candidates].nlargest(k)
weights = sims.values
values = ui.loc[sims.index, item_id].values
return float(np.dot(weights, values) / (np.abs(weights).sum() + 1e-9))
print("Prediction for (user 3, item 12):",
round(predict_user_based(3, 12), 3))
Two details matter in production: normalize by the absolute sum of similarities so opposing signs do not blow up the denominator, and fall back to the item or global mean when no neighbor has observed the target β an unguarded division there is a classic source of NaN predictions in dashboards.
Matrix factorization with SVD
Factorization assumes the ratings matrix is approximately low rank: each user and each item is described by a small vector of latent factors, and the predicted rating is a dot product plus biases. Truncated SVD on a mean-centered matrix is the classical closed-form approach; stochastic gradient descent (as in the Surprise library or a hand-rolled optimizer) handles missing cells and regularization more gracefully.
from scipy.sparse.linalg import svds
class SVDRecommender:
def __init__(self, n_factors=20):
self.n_factors = n_factors
def fit(self, user_item: pd.DataFrame):
self.user_ids = user_item.index
self.item_ids = user_item.columns
matrix = user_item.values.astype(float)
self.global_mean = matrix[matrix > 0].mean()
user_means = np.where(matrix.sum(1) > 0,
matrix.sum(1) / (matrix > 0).sum(1),
self.global_mean)
centered = np.where(matrix > 0, matrix - user_means[:, None], 0)
k = min(self.n_factors, min(centered.shape) - 1)
u, s, vt = svds(centered, k=k)
order = np.argsort(-s)
self.U, self.S, self.Vt = u[:, order], s[order], vt[order]
self.user_means = user_means
return self
def predict(self, user_id, item_id):
ui = self.user_ids.get_loc(user_id)
ii = self.item_ids.get_loc(item_id)
score = (self.user_means[ui]
+ self.U[ui] @ np.diag(self.S) @ self.Vt[:, ii])
return float(np.clip(score, 1, 5))
def recommend(self, user_id, rated_items, n=10):
ui = self.user_ids.get_loc(user_id)
scores = (self.user_means[ui]
+ self.U[ui] @ np.diag(self.S) @ self.Vt)
mask = np.isin(self.item_ids.values, list(rated_items))
scores = np.where(mask, -np.inf, scores)
top = np.argsort(-scores)[:n]
return list(zip(self.item_ids[top], scores[top].round(3)))
model = SVDRecommender(n_factors=15).fit(ui)
sample_user = ui.index[0]
rated = ui.columns[ui.loc[sample_user] > 0]
print(model.recommend(sample_user, rated, n=5))
SVD's latent factors are not inherently interpretable β factor 7 is not "science fiction affinity" unless you probe it by looking at the items with extreme loadings. That probe is worth doing before presenting factors to product managers.
Content-based filtering from item attributes
When item metadata exists β categories, tags, free-text descriptions β you can recommend by similarity in feature space. TF-IDF over description text is the classic baseline: it down-weights terms that appear everywhere and keeps discriminative vocabulary.
Content-based systems are also the natural home for business rules that collaborative filtering cannot express: new items must be recommendable before they have interactions, certain categories must be surfaced for contractual reasons, and recently added attributes (size, color, compatibility) should influence ranking immediately. Building a content-based channel alongside the collaborative one gives you a fallback when behavioral data is sparse and a lever for exploration β blending the two scores with a tunable weight is the standard hybrid pattern, and the weight itself becomes a hyperparameter you can tune with offline ranking metrics or online experiments.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
items = pd.DataFrame({
"item_id": [101, 102, 103, 104, 105],
"title": ["Intro to Statistics", "Bayesian Methods",
"Deep Learning Cookbook", "Data Visualization Handbook",
"Practical Linear Algebra"],
"tags": ["stats math beginner", "stats bayesian math",
"ml deep learning python", "viz design charts",
"math linear algebra geometry"],
})
tfidf = TfidfVectorizer(stop_words="english")
tag_matrix = tfidf.fit_transform(items["tags"])
sim = linear_kernel(tag_matrix, tag_matrix)
def content_recommend(item_id, n=3):
idx = items.index[items["item_id"] == item_id][0]
scores = list(enumerate(sim[idx]))
scores = sorted(scores, key=lambda t: t[1], reverse=True)[1:n + 1]
return items.iloc[[i for i, _ in scores]][["item_id", "title"]]
print(content_recommend(101))
Content-based systems never suffer item cold start β a new item with metadata is recommendable immediately β but they trap users in a bubble of already-preferred genres. Hybrids that blend content scores with collaborative scores mitigate both failure modes.
Evaluation that matches the product surface
RMSE on held-out ratings measures rating prediction; users do not see ratings, they see a ranked list. Ranking metrics β Precision@K (fraction of the top K that are relevant), Recall@K, and NDCG (which rewards placing relevant items higher) β are the ones to optimize. The split strategy also matters: leave-one-out per user or temporal splits mimic production far better than a random cell mask that leaks future interactions.
from sklearn.model_selection import train_test_split
def precision_at_k(predicted, relevant, k=10):
top = predicted[:k]
return len(set(top) & set(relevant)) / k
def recall_at_k(predicted, relevant, k=10):
if not relevant:
return 0.0
return len(set(predicted[:k]) & set(relevant)) / len(relevant)
def ndcg_at_k(predicted, relevant, k=10):
gains = [1.0 if p in set(relevant) else 0.0 for p in predicted[:k]]
dcg = sum(g / np.log2(i + 2) for i, g in enumerate(gains))
ideal = sorted(gains, reverse=True)
idcg = sum(g / np.log2(i + 2) for i, g in enumerate(ideal))
return dcg / idcg if idcg > 0 else 0.0
train, test = train_test_split(ratings, test_size=0.2, random_state=42)
train_ui = train.pivot_table(index="user_id", columns="item_id",
values="rating").reindex(columns=ui.columns).fillna(0)
rec_model = SVDRecommender(n_factors=15).fit(train_ui)
precisions, recalls, ndcgs = [], [], []
for uid in test["user_id"].unique()[:50]:
relevant = test.loc[test["user_id"] == uid, "item_id"].tolist()
rated = train_ui.columns[train_ui.loc[uid] > 0] if uid in train_ui.index else []
preds = [i for i, _ in rec_model.recommend(uid, rated, n=10)]
precisions.append(precision_at_k(preds, relevant))
recalls.append(recall_at_k(preds, relevant))
ndcgs.append(ndcg_at_k(preds, relevant))
print(f"Precision@10={np.mean(precisions):.3f} "
f"Recall@10={np.mean(recalls):.3f} NDCG@10={np.mean(ndcgs):.3f}")
Pair offline metrics with an online A/B test before shipping β offline lists can look strong while the live UI suffers from position bias or stale features.
Cold start and the path to production
New users have no history; new items have no interactions. Content features and onboarding preferences cover the user side; content similarity and exploration bonuses cover the item side. In production you will also need a candidate-generation stage (retrieve hundreds of plausible items cheaply) followed by a ranking stage (score them with a heavier model), plus diversity injection so the list is not ten near-duplicates of the same product.
The two-stage architecture is not optional at scale: scoring every item in a million-item catalog with a deep ranking model on every request is prohibitively expensive, so candidate generation (often a lightweight collaborative or embedding-based retriever) narrows the field to a few hundred, which the ranker then orders precisely. Diversity injection β via maximal marginal relevance or simple category quotas β prevents the degenerate outcome where the top ten results are interchangeable. Serving latency budgets also matter: a recommender that is 2% more accurate but 200ms slower will lose in an A/B test almost every time, because users feel delay more acutely than they feel marginal relevance gains.