Sub topic 9
Evaluating recommenders
This chapter assumes you can write basic Python and NumPy. It also assumes you know how the user-item matrix and the neighborhood and factorization models from earlier chapters produce predicted scores. Here you will learn how to measure whether those scores are any good.
Two questions, two kinds of metric
A recommender can be asked two different questions:
- How close is each predicted rating to the true rating? This is rating prediction, measured with error metrics such as RMSE.
- Are the items at the top of the list the ones the user actually wants? This is top-N recommendation, measured with ranking metrics such as precision@k, recall@k, and NDCG.
The two questions can give different answers. A model can predict ratings with low error and still rank poorly, because ranking only depends on the order of the scores. Most products show a short list, so ranking metrics usually matter more.
Splitting without leakage
Evaluation is only honest if the model never sees the answers. Three split strategies are common:
- Random split of interactions. Hide a random fraction, for example 20%, of all observed ratings. It is simple, but it lets the model train on events that happened after the ones it is tested on.
- Leave-one-out per user. Hold out each user's latest interaction. Every user is tested, and the setup matches the real task of predicting the next item.
- Temporal split. Train on everything before a cutoff date and test on what comes after. This is the closest match to production use.
Leakage usually enters in a few ways:
- Computing item similarities or popularity counts on the full data before splitting.
- Tuning hyperparameters on the test set. Use a separate validation set and touch the test set once.
- Leaving a duplicate or near-duplicate of a test interaction in training, such as the same user-item pair logged twice.
- Letting test items appear in the candidate list as already "seen". Always remove each user's training items before ranking.
Error metrics for rating prediction
RMSE (root mean squared error) is the square root of the average squared difference between predicted and true ratings. MAE (mean absolute error) averages the absolute differences instead. RMSE penalizes large mistakes more heavily.
import numpy as np
def rmse(y_true, y_pred):
y_true = np.asarray(y_true, dtype=float)
y_pred = np.asarray(y_pred, dtype=float)
return float(np.sqrt(np.mean((y_true - y_pred) ** 2)))
def mae(y_true, y_pred):
y_true = np.asarray(y_true, dtype=float)
y_pred = np.asarray(y_pred, dtype=float)
return float(np.mean(np.abs(y_true - y_pred)))
print(round(rmse([4, 3, 5], [3.5, 3.5, 4]), 3)) # 0.707
print(round(mae([4, 3, 5], [3.5, 3.5, 4]), 3)) # 0.667Compute these only on the held-out observed ratings. Never include the zeros that mark missing entries in the matrix. A zero means "unknown", not "the user hated it". Always compare against a baseline, such as predicting the global mean rating, because an RMSE of 0.9 means little without one.
Ranking metrics
For ranking, take each user's held-out relevant items. These are the test items the user interacted with, or rated above a threshold such as 4 stars. Rank all candidate items the user has not seen in training. Then look at the top k.
- Precision@k is the fraction of the top k that are relevant.
- Recall@k is the fraction of the user's relevant items that appear in the top k.
- NDCG@k (normalized discounted cumulative gain) rewards placing relevant items near the top. A hit at rank 1 counts fully, and a hit at rank r counts
1 / log2(r + 1). The sum is divided by the best possible sum, so the score lies between 0 and 1.
Precision and recall ignore the position inside the top k. NDCG does not.
import numpy as np
def precision_recall_at_k(recommended, relevant, k):
top = recommended[:k]
hits = len(set(top) & set(relevant))
precision = hits / k
recall = hits / len(relevant) if len(relevant) > 0 else 0.0
return precision, recall
def ndcg_at_k(recommended, relevant, k):
relevant = set(relevant)
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
rec = [3, 1, 7, 2]
rel = [1, 2, 9]
print(precision_recall_at_k(rec, rel, k=3)) # (0.333..., 0.333...)
print(round(ndcg_at_k(rec, rel, k=3), 3)) # 0.296Here the only hit in the top 3 is item 1, at rank 2. Precision@3 is 1/3, recall@3 is 1/3, and NDCG@3 is lower than 1 because the hit is not at rank 1 and two other relevant items are missing.
Evaluating a whole model
To score a model, compute metrics per user and average over users. Mask each user's training items before ranking, or the model will simply recommend what the user already rated.
import numpy as np
def evaluate_ranking(scores, R_train, test_items, k):
"""scores: users x items predicted scores.
R_train: training matrix, 0 = unobserved.
test_items: dict mapping user index to a set of relevant item ids."""
precisions, recalls = [], []
for u, relevant in test_items.items():
s = scores[u].astype(float).copy()
seen = np.nonzero(R_train[u])[0]
s[seen] = -np.inf # never recommend seen items
ranked = list(np.argsort(-s))
top = ranked[:k]
hits = len(set(top) & relevant)
precisions.append(hits / k)
recalls.append(hits / len(relevant))
return float(np.mean(precisions)), float(np.mean(recalls))
R_train = np.array([[5, 3, 0, 1, 0, 0],
[0, 4, 0, 0, 5, 0]], dtype=float)
scores = np.array([[4.9, 3.0, 3.5, 1.1, 4.0, 0.5],
[2.0, 3.9, 3.0, 0.5, 4.5, 2.5]])
test_items = {0: {2, 5}, 1: {5, 0}}
p, r = evaluate_ranking(scores, R_train, test_items, k=2)
print(f"precision@2={p:.2f} recall@2={r:.2f}") # precision@2=0.50 recall@2=0.50Choosing a metric
| Metric | Question it answers | Watch out for |
|---|---|---|
| RMSE / MAE | How far off are predicted ratings? | Says little about list quality. Needs explicit ratings. |
| Precision@k | How much of the list is useful? | Ignores order inside the list. |
| Recall@k | How many of the user's relevant items did we find? | Capped when a user has more than k relevant items. |
| NDCG@k | Are the best items near the top? | Needs a decision about graded or binary relevance. |
Common errors
- Treating missing as negative. An item the user never saw may still be a good recommendation. Held-out ranking metrics therefore underestimate quality, and they favor models that recommend popular items, since popular items are more likely to appear in test data.
- Comparing metrics across different splits. Numbers from a random split and a temporal split are not comparable. Keep the split fixed when comparing models.
- Ranking against a sample of items. Scoring the relevant item against 100 random items gives much higher numbers than ranking against the full catalog, and it can change which model looks best. Prefer full ranking when the catalog allows it.
- Averaging over interactions instead of users. Heavy users then dominate the result. Average per user first.
- Ignoring users with no test items or no training items. Decide how to handle them and report it. Users with no training history are a cold start case, covered in a later chapter.
- Skipping baselines. Always include a most-popular recommender. It is often hard to beat.
Beyond accuracy
High precision does not guarantee a good product. Teams often also track:
- Coverage: the share of the catalog that ever gets recommended.
- Diversity: how different the items in one list are from each other.
- Novelty: how unfamiliar the recommended items are to the user.
Offline metrics are also only a proxy. The decisive test is an online experiment (an A/B test) that measures real behavior, such as clicks or retention, for users who got the new model versus the old one.
Exercise
A model's top-5 list for a user contains 2 relevant items. The user has 4 relevant items in the test set. What are precision@5 and recall@5? Would NDCG@5 be higher if both hits were at ranks 1 and 2 than at ranks 4 and 5, and why?
Show answer
Precision@5 = 2/5 = 0.4. Recall@5 = 2/4 = 0.5. NDCG@5 would be higher with hits at ranks 1 and 2, because each hit is discounted by 1/log2(rank + 1). Hits near the top contribute more, while precision and recall give the same value in both cases.
Exercise
You compute item-item similarities on the full rating matrix, then hold out 20% of ratings and evaluate. Why are the results too optimistic, and how do you fix it?
Show answer
The similarity matrix was built using the held-out ratings, so the model has indirectly seen the test answers (data leakage). Split first, then compute similarities, item means and any other learned statistics from the training portion only.