Sub topic 9
Evaluating recommenders
This chapter assumes you can read basic Python and NumPy, and that you have built a user-item matrix and split interaction data into training and test sets. Here you will score a recommender with error metrics and ranking metrics.
Two questions, two kinds of metric
A recommender can answer two different questions:
- How close are predicted ratings to real ones? This is a rating prediction task. Error metrics such as RMSE measure it.
- Are the items we show near the top the right ones? This is a top-N ranking task. Precision@k, recall@k, and NDCG measure it.
Most products show a ranked list, so ranking metrics usually match the real goal better. Low RMSE does not guarantee a good list.
RMSE for rating prediction
Root mean squared error (RMSE) squares each prediction error, averages the squares, and takes the square root. Large mistakes count more than small ones. Compute it only over ratings that exist in the test set. Do not score missing entries as zeros.
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)))
print(rmse([4, 3, 5], [3.5, 3, 4]))Precision@k and recall@k
For one user, take the top k recommended items and compare them with the user's held-out relevant items. Relevant means the user interacted with the item in the test data, for example rated it 4 or higher.
- Precision@k is the fraction of the k recommendations that are relevant.
- Recall@k is the fraction of all relevant items that appear in the top k.
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
print(precision_recall_at_k([3, 1, 7, 2], [1, 2, 9], k=3))This prints (0.3333333333333333, 0.3333333333333333). Only item 1 is a hit in the top 3. Average both values over all test users to get the final score.
NDCG rewards good ordering
Precision@k ignores the order inside the top k. Normalized discounted cumulative gain (NDCG) gives more credit when relevant items sit higher. Each hit is discounted by 1 / log2(position + 1), and the sum is divided by the best possible sum, so scores fall between 0 and 1.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Recommending items the user already rated in training | Inflated or meaningless scores | Remove training items from the candidate list |
| Treating missing entries as negatives in RMSE | Error is dominated by unobserved cells | Score observed test ratings only |
| Random split of a time-ordered log | Future data leaks into training | Split by time |
| Reporting one number on a tiny test set | Noisy comparison | Average over many users and compare against a popularity baseline |
Offline scores have limits
Test data only contains items users chose to see. An item the model recommends well but that was never shown counts as a miss. Offline metrics therefore favor models that mimic past exposure. Online A/B tests measure the real effect on users, and teams commonly use offline metrics to shortlist models and A/B tests to decide.
Exercise
A user has 4 relevant items in the test set. Your top-5 list contains 2 of them. What are precision@5 and recall@5?
Show answer
Precision@5 = 2/5 = 0.4. Recall@5 = 2/4 = 0.5.
Exercise
Why can a model with lower RMSE still produce worse top-10 lists than a model with higher RMSE?
Show answer
RMSE averages error over all rated items, while a top-10 list depends only on the ordering of the highest-scored items. A model can predict most ratings well yet rank a few key items poorly.