Skip to content
Visual explainer 3h 30m to learn 5 steps

Build a simple recommender and measure it with recall@k and NDCG

Build collaborative and content-based recommenders, handle cold start and compare them with recall@k and NDCG.

By Invicly Tech, , in AI and Machine Learning with Python. About 13 minutes to read.

Topic 18 of 34

In short

A recommender ranks items, such as products or articles, for each user. Collaborative filtering uses what similar users or items did, while content-based methods use item descriptions, and real systems combine them to handle new users and new items. Because the output is a ranked list, you measure it with ranking metrics such as recall@k and NDCG on interactions held out by time.

Think of it like this: Collaborative filtering is a friend saying people who bought this also bought that; content-based filtering is a shop assistant saying this book is by the same author and in the same genre.

Explained simply

A recommender decides what to show each person: which products, films or articles go at the top of their list. It does not predict a single answer. It ranks many options, and only the first few really matter because that is what people see.

The raw material is a log of who did what: user 17 bought item 403, user 22 watched item 9. Put that into a table with users as rows and items as columns and you get the user-item matrix. Almost every cell is empty, because each person touches only a tiny share of all items.

Collaborative filtering fills the gaps using patterns across people. If people who bought a tent also tend to buy a sleeping bag, a new tent buyer gets the sleeping bag. Content-based filtering instead looks at the items themselves, such as genre, author or description, and suggests things similar to what you already liked.

Both have a weak spot called cold start. A brand-new user has no history, so collaborative filtering knows nothing about them. A brand-new item has no buyers yet. Content features, popular items and a few onboarding questions help fill these gaps.

To test a recommender, hide each user's most recent interactions, ask the model for a top 10 list, and count how many hidden items appear. Recall@k counts the hits. NDCG also cares where in the list they appear, rewarding hits near the top.

Press Play on a diagram to walk through it one step at a time.

MapMain recommender approaches
Recommender
  • Popularity baseline
    • Most bought items
    • Works for everyone, personal to no one
  • Collaborative filtering
    • Item-item similarity
    • User-user similarity
    • Matrix factorisation
  • Content-based
    • Item text and tags
    • TF-IDF or embeddings
    • Works for brand-new items
  • Hybrid
    • Blend scores
    • Fall back on cold start
FlowBuilding and testing a recommender
  1. 1
    Log interactions

    user, item, timestamp, signal

  2. 2
    Split by time

    Hold out each user's latest interactions

  3. 3
    Build user-item matrix

    Sparse, from training rows only

  4. 4
    Score and rank

    Top k unseen items per user

  5. 5
    Measure

    recall@k and NDCG@k against the held-out items

SequenceServing a recommendation request
App
Recommender API
Feature store
Model
  1. 1Get top 10 for user 42
    App to Recommender API: Get top 10 for user 42
  2. 2Fetch user history
    Recommender API to Feature store: Fetch user history
  3. 3Return 3 past purchases
    Feature store to Recommender API: Return 3 past purchases
  4. 4Score candidate items
    Recommender API to Model: Score candidate items
  5. 5Return scores
    Model to Recommender API: Return scores
  6. 6Top 10, owned items removed
    Recommender API to App: Top 10, owned items removed

In depth

Building the user-item matrix

Start from an interaction log with user_id, item_id, timestamp and a signal. Explicit feedback, such as star ratings, says how much someone liked something. Implicit feedback, such as clicks, views or purchases, is far more common but only shows what someone did; a missing cell means unknown, not disliked.

Map user and item IDs to consecutive integers, then build a sparse matrix with scipy.sparse.csr_matrix((values, (rows, cols))). With 100,000 users and 50,000 items, a dense matrix would hold 5 billion cells, while a sparse one stores only the few million real interactions. Decide how to weight signals: a purchase might count 3, an add-to-basket 2 and a view 1, or use a log of counts so heavy users do not dominate. Filter very rare users and items, which add noise, and keep a record of the filtering so evaluation stays honest.

  • Implicit: missing does not mean dislike
  • Use csr_matrix for row-wise operations
  • Weight or log-scale repeated interactions
  • Build the matrix from training rows only

Collaborative filtering: neighbours and factors

Item-item collaborative filtering compares item columns. Two items are similar if the same users interacted with both; cosine similarity is the usual measure. A user's score for an item is the sum of its similarity to items they already have. It is simple, explainable (because you bought X) and stable, since item relationships change slowly.

User-user filtering does the same with rows, but there are usually many more users than items and their tastes shift, so it scales worse. Matrix factorisation learns a short vector for every user and every item so that their dot product approximates the matrix. TruncatedSVD in scikit-learn gives a quick version on a sparse matrix; dedicated libraries implement alternating least squares for implicit data. Factor models generalise better on sparse data but are harder to explain. Whichever you use, remove items the user already has before taking the top k.

CompareThree collaborative filtering styles
Item-item
  • Cosine similarity between item columns
  • Easy to explain
  • Stable over time
  • Popular default
User-user
  • Similarity between user rows
  • Many users makes it slow
  • Tastes drift quickly
  • Rarely used alone
Matrix factorisation
  • Short vectors per user and item
  • Handles sparsity well
  • Harder to explain
  • TruncatedSVD or ALS

Content-based similarity and cold start

Content-based methods describe each item with features: title and description text turned into TF-IDF vectors with TfidfVectorizer, tags as one-hot columns, or embeddings from a text model. A user profile is the average vector of items they liked, and recommendations are the items closest to that profile by cosine similarity. A new item can be recommended the moment its description exists.

Cold start needs a plan for each case. New items: use content similarity, or reserve a few slots for fresh items so they can collect interactions. New users: show popular items, perhaps within a region or category, ask two or three onboarding questions, or use context such as the page they arrived on. A hybrid blends scores, for example 0.7 x collaborative + 0.3 x content, shifting weight towards collaborative as history grows.

  • New item: content features or fresh-item slots
  • New user: popularity, onboarding, context
  • Hybrid: blend scores by amount of history

Measuring with recall@k and NDCG

Split by time: for each user, hold out their most recent interactions as the test set and train on everything earlier. Random splits leak future behaviour. For each test user, rank all items they have not yet interacted with in training, take the top k, and compare with the held-out items.

Recall@k is hits in the top k divided by the number of held-out items (some definitions divide by the smaller of k and that number). NDCG@k discounts each hit by its position: DCG adds relevance / log2(rank + 1), and dividing by the best possible DCG gives a value between 0 and 1. A hit at rank 1 counts fully; a hit at rank 3 counts half. scikit-learn's ndcg_score takes 2D arrays of true relevance and scores and has a k argument. Average per user, report the popularity baseline beside every model, and remember offline gains are a guide; an A/B test decides.

FlowComputing NDCG@3 for one user
  1. Step 1
    Ranked list

    Items A, B, C; only B is relevant

  2. Step 2
    DCG

    1 / log2(2 + 1) = 0.63

  3. Step 3
    Ideal DCG

    B at rank 1: 1 / log2(2) = 1.0

  4. Step 4
    NDCG

    0.63 / 1.0 = 0.63

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Build a user-item matrix~40m
  2. 2
    Try collaborative filtering~40m
  3. 3
    Try content-based similarity~40m
  4. 4
    Handle cold start~40m
  5. 5
    Measure recall@k and NDCG~40m

Key points

  • Always compare against a popularity baseline; it is surprisingly hard to beat.
  • The user-item matrix is mostly empty, so store it as a sparse matrix.
  • Cold start means no history: new users need popular or onboarding-based picks, new items need content features.
  • Remove items the user already interacted with before ranking, unless repeats are the point.
  • recall@k asks how many held-out items you found; NDCG@k also rewards putting them near the top.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity

# rows = users, cols = items, 1 = purchased
R = np.array([[1, 1, 0, 0, 1],
              [1, 0, 1, 0, 0],
              [0, 1, 0, 1, 1],
              [1, 1, 0, 0, 0]])
item_sim = cosine_similarity(R.T)
np.fill_diagonal(item_sim, 0)
scores = R @ item_sim           # sum of similarity to items each user has
scores[R > 0] = -np.inf         # do not recommend what they already have
print(np.argsort(-scores, axis=1)[:, :2])  # top 2 items per user

Item-item collaborative filtering in a few lines.

Item-item recommender against a popularity baseline

Use a synthetic log of 2,000 users and 300 items. Step 1: hold out each user's last purchase. Step 2: build a sparse user-item matrix from the remaining rows. Step 3: compute item-item cosine similarity and score each user's unseen items. Step 4: build the popularity baseline by ranking items by total purchases. Step 5: compute recall@10 for both. With real taste structure in the data, item-item should beat popularity; if it does not, check the split and the removal of owned items before tuning anything.

python
import numpy as np
from scipy.sparse import csr_matrix
from sklearn.metrics.pairwise import cosine_similarity

# train: DataFrame of (user, item) ints; test_item: last item per user
R = csr_matrix((np.ones(len(train)), (train.user, train.item)))
sim = cosine_similarity(R.T, dense_output=False)
sim.setdiag(0)
scores = (R @ sim).toarray()
scores[R.toarray() > 0] = -np.inf
top10 = np.argsort(-scores, axis=1)[:, :10]
recall = np.mean([test_item[u] in top10[u] for u in test_item.index])
print("item-item recall@10:", round(recall, 3))

Recall@k and NDCG@k by hand and with scikit-learn

One user has held-out items B and E. The model ranks A, B, C, D, E. Step 1: recall@3 is 1 / 2 = 0.5, because only B is in the top 3. Step 2: DCG@5 is 1 / log2(3) + 1 / log2(6) = 0.631 + 0.387 = 1.018. Step 3: the ideal list puts both relevant items first: 1 + 1 / log2(3) = 1.631. Step 4: NDCG@5 = 1.018 / 1.631 = 0.62. Step 5: confirm with ndcg_score, which expects 2D arrays: one row per user.

python
import numpy as np
from sklearn.metrics import ndcg_score

# items A..E; true relevance and model scores for one user
y_true = np.array([[0, 1, 0, 0, 1]])
y_score = np.array([[0.9, 0.8, 0.7, 0.6, 0.5]])
print(round(ndcg_score(y_true, y_score, k=5), 3))   # about 0.624

top3 = np.argsort(-y_score[0])[:3]
recall_at_3 = y_true[0, top3].sum() / y_true[0].sum()
print(recall_at_3)  # 0.5

Quick reference

  • Store interactions as scipy.sparse.csr_matrix, built from training rows only
  • Item-item CF: cosine_similarity(R.T), score = R @ sim, then drop owned items
  • Split by time: hold out each user's latest interactions
  • recall@k = relevant items in top k / relevant held-out items
  • NDCG discount: 1 / log2(rank + 1); rank 1 counts 1, rank 3 counts 0.5
  • sklearn ndcg_score(y_true, y_score, k=10) expects 2D arrays
  • Cold start: content features for new items, popularity or onboarding for new users
  • Always report a popularity baseline next to every model

Common mistakes

  • Splitting interactions randomly, so the model learns from purchases made after the ones it is tested on.
  • Leaving already-purchased items in the ranking, which inflates offline scores and annoys users.
  • Judging a recommender by rating error when the product shows a ranked list.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1In implicit feedback data, what does an empty cell in the user-item matrix mean?

Question 2

2Which approach can recommend a product added to the catalogue five minutes ago?

Question 3

3A user has 5 held-out items and 3 appear in the top 10. What is recall@10?

Question 4

4Why should you split recommender data by time rather than randomly?

Question 5

5Lists X and Y have the same recall@10, but X puts its hits at ranks 1 and 2 while Y puts them at 9 and 10. Which metric separates them?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    For a user whose relevant items are {3, 7} and whose ranked list is [7, 1, 4, 3, 9], compute recall@3 and recall@5 by hand and in Python.

  2. Exercise 2medium

    Build a content-based recommender for six short item descriptions using TfidfVectorizer and cosine similarity, and print the two most similar items to item 0.

  3. Exercise 3hard

    Design an evaluation for a shop with 50,000 users where 30 percent of test users are new. Compare item-item CF, popularity and a hybrid, and explain how you report results.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Why not just predict star ratings and sort by them?
Rating error measures the wrong thing for a ranked list, and most real data is implicit, with no ratings at all. Ranking metrics such as recall@k and NDCG match what users see.
Is popularity really a fair baseline?
Yes, and it is often strong because popular items are popular for a reason. A personalised model that cannot beat it offline is not worth its extra complexity.
Do I need deep learning for recommendations?
Not to start. Item-item similarity, matrix factorisation and good cold-start rules cover many real systems; deep models help mainly at very large scale or with rich content and context.
How do I avoid recommending the same few items to everyone?
Measure catalogue coverage and diversity alongside accuracy, and add rules such as limiting items per category or reserving slots for less popular or new items.

Go deeper

ShareXLinkedInWhatsApp