Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 30 min · revision 2

Lab: Recommendations from Interaction Data with Matrix Factorization

Build an implicit-feedback recommender from a synthetic play log: split by time before a cut-off day, implement and hand-check recall@10 and NDCG@10, write confidence-weighted ALS in NumPy, tune it on a validation window, and show with a bootstrap that it beats a popularity baseline, with a fallback for cold-start users.

Contentsand lesson path

What you will learn

  • Build a collaborative-filtering recommender from implicit feedback with matrix factorization and show, with ranking metrics (recall@k, NDCG) on a time-based split, whether it beats a popularity baseline.

01. Goal and setup

Most recommendation data is implicit feedback: plays, clicks, purchases. Nobody rates anything; you only see what people did. Collaborative filtering learns from that behaviour alone: users who played similar things probably like similar things. In this lab you build the classic collaborative-filtering model for implicit data, matrix factorisation trained with alternating least squares, in about 30 lines of NumPy, and test honestly whether it beats recommending the most popular items.

Honestly means three things. You split the log by time, as production does: train before a cut-off day, test after it. You score both models with recall@10 and NDCG@10, implemented and checked by hand first. And you handle users who arrived after the cut-off, the cold-start problem, explicitly.

The log is synthetic: 1,200 users with hidden tastes, 400 items with very unequal popularity, 130 days. You need: Python 3.12, NumPy 2.5 and pandas 3.1; every script runs in seconds. The factorisation builds on the low-rank ideas in Similarity and Structure.

Project layout at the end of the lab
recs-lab/
├── data/events.csv   written by step 1
├── make_log.py       step 1: generate the interaction log
├── split.py          step 2: time-based split before a cut-off day
├── metrics.py        step 3: recall@k, NDCG@k and a hand check
├── popularity.py     step 4: the popularity baseline
├── als.py            step 5: implicit ALS in NumPy
├── tune.py           step 5: choose alpha on the validation window
└── final.py          step 6: test once, with a cold-start fallback
Terminal
mkdir recs-lab && cd recs-lab
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install "numpy==2.5.*" "pandas==3.1.*"

02. Step 1: Generate the interaction log

Each user and item gets a hidden vector of five tastes. A user picks an item with a probability that grows with the item's popularity and with the match between the two taste vectors. About 12% of users join after day 100 and about 8% of items are released after day 100, so the test period contains genuinely new users and items.

Python · make_log.py
"""Write data/events.csv: one row per play, users with hidden tastes, days 0 to 129."""
from pathlib import Path

import numpy as np
import pandas as pd

rng = np.random.default_rng(0)
N_USERS, N_ITEMS, TASTES, LAST_DAY = 1200, 400, 5, 130

user_taste = rng.normal(0, 1, (N_USERS, TASTES))
item_taste = rng.normal(0, 1, (N_ITEMS, TASTES))
popularity = -1.0 * np.log(rng.permutation(N_ITEMS) + 1)   # Zipf-like popularity
release = np.where(rng.random(N_ITEMS) < 0.08, rng.integers(100, 125, N_ITEMS), 0)
joined = np.where(rng.random(N_USERS) < 0.12, rng.integers(100, 120, N_USERS),
                  rng.integers(0, 60, N_USERS))
activity = np.ceil(rng.lognormal(3.0, 0.6, N_USERS)).astype(int)

rows = []
for u in range(N_USERS):
    logits = popularity + 0.9 * item_taste @ user_taste[u]
    days = np.sort(rng.integers(joined[u], LAST_DAY, activity[u]))
    for day in days:
        p = np.exp(logits - logits.max()) * (release <= day)  # unreleased: no plays
        rows.append((u, rng.choice(N_ITEMS, p=p / p.sum()), day))

events = pd.DataFrame(rows, columns=["user_id", "item_id", "day"])
Path("data").mkdir(exist_ok=True)
events.to_csv("data/events.csv", index=False)
print("events:", len(events), "| users:", events.user_id.nunique(),
      "| items:", events.item_id.nunique())
counts = events.item_id.value_counts()
print("share of plays on the top 10% of items:",
      round(counts.iloc[: N_ITEMS // 10].sum() / len(events), 3))
Terminal
python make_log.py
Expected output
events: 29592 | users: 1200 | items: 398
share of plays on the top 10% of items: 0.589

The top 10% of items receive 58.9% of all plays. That popularity skew is typical of real catalogues, and it is why "recommend the bestsellers" is a hard baseline to beat.

03. Step 2: Split by time, before a cut-off day

A random split would let the model train on plays from day 120 and predict plays from day 90, using trends and items from the future. A time-based split avoids that. time_split(cut, end) builds the training matrix R from days before cut (R[u, i] counts user u's plays of item i) and keeps as test targets the items each user played in [cut, end) for the first time; re-recommending an item a user already plays is rarely useful. Days 80 to 99 form a validation window for choosing settings, and days 100 to 129 the test window, used once.

Python · split.py
import numpy as np
import pandas as pd

N_USERS, N_ITEMS = 1200, 400


def time_split(cut, end):
    """Train on days before `cut`; test on new user-item pairs in [cut, end)."""
    events = pd.read_csv("data/events.csv")
    train = events[events.day < cut]
    test = events[(events.day >= cut) & (events.day < end)]
    R = np.zeros((N_USERS, N_ITEMS))                  # plays per user and item
    np.add.at(R, (train.user_id, train.item_id), 1)
    test = test[R[test.user_id, test.item_id] == 0]   # items new to that user
    relevant = test.groupby("user_id").item_id.apply(set).to_dict()
    return R, relevant


if __name__ == "__main__":
    for name, cut, end in [("validation", 80, 100), ("test", 100, 130)]:
        R, relevant = time_split(cut, end)
        cold = [u for u in relevant if R[u].sum() == 0]
        unseen = {i for items in relevant.values() for i in items if R[:, i].sum() == 0}
        print(f"{name:10} train days < {cut}: {int(R.sum())} plays, "
              f"{int((R > 0).sum())} user-item pairs")
        print(f"{'':10} users to evaluate {len(relevant)}, "
              f"cold-start users {len(cold)}, items with no train plays {len(unseen)}")
Terminal
python split.py
Expected output
validation train days < 80: 12634 plays, 8860 user-item pairs
           users to evaluate 962, cold-start users 1, items with no train plays 1
test       train days < 100: 18135 plays, 11762 user-item pairs
           users to evaluate 1138, cold-start users 135, items with no train plays 38

The test window has 1,138 users to evaluate, and 135 of them have no plays before day 100: they are cold-start users. 38 items in the test targets had no plays at all before the cut-off. The training matrix is sparse: 11,762 user-item pairs out of 480,000 possible, about 2.5%.

04. Step 3: Implement recall@k and NDCG@k, and check them by hand

Both metrics compare the top k of a ranked list with the items the user actually went on to play. Recall@k is the share of those relevant items that appear in the top k, regardless of position. NDCG@k (normalised discounted cumulative gain) also rewards position: a hit at rank r earns 1 / log2(r + 1), so rank 1 earns 1, rank 2 earns 0.631 and rank 4 earns 0.431, and the total is divided by the best possible total for that user. Metric code is easy to get subtly wrong, so test it on an example you can check by hand. evaluate averages both over users after removing each user's already-played items.

Python · metrics.py
import numpy as np


def recall_at_k(ranked, relevant, k=10):
    """Share of the relevant items that appear in the top k."""
    hits = len(set(ranked[:k]) & relevant)
    return hits / len(relevant)


def ndcg_at_k(ranked, relevant, k=10):
    """Discounted gain of the hits in the top k, divided by the best possible."""
    dcg = sum(1 / np.log2(rank + 2) for rank, item in enumerate(ranked[:k])
              if item in relevant)
    ideal = sum(1 / np.log2(rank + 2) for rank in range(min(len(relevant), k)))
    return dcg / ideal


def evaluate(score, R, relevant, users, k=10, per_user=False):
    """Mean recall@k and NDCG@k; `score(u)` returns one score per item."""
    recalls, ndcgs = [], []
    for u in users:
        s = score(u).astype(float)
        s[R[u] > 0] = -np.inf                     # never recommend what they played
        ranked = list(np.argsort(-s, kind="stable")[:k])
        recalls.append(recall_at_k(ranked, relevant[u], k))
        ndcgs.append(ndcg_at_k(ranked, relevant[u], k))
    if per_user:
        return np.array(recalls), np.array(ndcgs)
    return np.mean(recalls), np.mean(ndcgs)


if __name__ == "__main__":
    relevant = {1, 5, 7}
    early, late = [1, 5, 3, 4, 9], [3, 1, 4, 5, 9]   # same two hits, different ranks
    for name, ranked in [("hits at ranks 1, 2", early), ("hits at ranks 2, 4", late)]:
        print(f"{name}: recall@5 {recall_at_k(ranked, relevant, 5):.3f}, "
              f"NDCG@5 {ndcg_at_k(ranked, relevant, 5):.3f}")
    # by hand: DCG = 1/log2(3) + 1/log2(5); ideal = 1 + 1/log2(3) + 1/log2(4)
    by_hand = (1 / np.log2(3) + 1 / np.log2(5)) / (1 + 1 / np.log2(3) + 1 / np.log2(4))
    assert np.isclose(ndcg_at_k(late, relevant, 5), by_hand)
    assert recall_at_k(early, relevant, 5) == 2 / 3
    print("hand-checked values: OK")
Terminal
python metrics.py
Expected output
hits at ranks 1, 2: recall@5 0.667, NDCG@5 0.765
hits at ranks 2, 4: recall@5 0.667, NDCG@5 0.498
hand-checked values: OK

Check the second line by hand. Items 1 and 5 are hits at ranks 2 and 4: DCG = 0.631 + 0.431 = 1.062. With three relevant items the ideal list has hits at ranks 1 to 3, worth 1 + 0.631 + 0.5 = 2.131, and 1.062 / 2.131 = 0.498. Both lists find two of three relevant items, so recall@5 is equal, but hits at the top earn a higher NDCG.

05. Step 4: The popularity baseline

The baseline ranks items by how many distinct users played them before the cut-off, the same list for everyone except that each user's already-played items are removed. Warm users, those with at least one training play, are the fair comparison for a collaborative model.

Python · popularity.py
from metrics import evaluate
from split import time_split

R, relevant = time_split(80, 100)                 # validation window
warm = [u for u in relevant if R[u].sum() > 0]
popularity = (R > 0).sum(axis=0)                  # distinct users per item
print("most popular items:", popularity.argsort()[::-1][:5].tolist())
print("users who played them:", sorted(popularity.tolist(), reverse=True)[:5])
recall, ndcg = evaluate(lambda u: popularity, R, relevant, warm)
print(f"popularity on {len(warm)} warm validation users: "
      f"recall@10 {recall:.3f}, NDCG@10 {ndcg:.3f}")
Terminal
python popularity.py
Expected output
most popular items: [330, 175, 98, 234, 48]
users who played them: [448, 314, 252, 241, 169]
popularity on 961 warm validation users: recall@10 0.201, NDCG@10 0.154

On the validation window, popularity reaches recall@10 0.201: a fifth of what warm users went on to play was in the global top 10. Any personalised model has to clear that number.

06. Step 5: Implicit matrix factorisation with ALS

Matrix factorisation gives each user a vector x_u and each item a vector y_i of length 16, and scores a pair by the dot product x_u · y_i. For implicit data, Hu, Koren and Volinsky (2008) split each play count r_ui into a preference p_ui, 1 if the user played the item and 0 otherwise, and a confidence c_ui = 1 + α·r_ui. A missing pair keeps confidence 1: the user may never have seen the item, so that 0 is weak evidence. Dropping missing pairs altogether would fail: with only 1s left to fit, a model that scores every pair as 1 is perfect. A pair played 10 times with α = 2 gets confidence 21. Training minimises the sum over all pairs of c_ui (p_ui − x_u · y_i)², plus reg times the squared length of every vector.

With the item vectors fixed, each user's vector has an exact least-squares solution, and vice versa, so alternating least squares (ALS) solves for all users, then all items, and repeats. Every missing pair has c = 1, so the shared part YᵀY is computed once per half-step and only each user's observed items are added. tune.py picks α on the validation window.

Python · als.py
import numpy as np


def fit_als(R, factors=16, alpha=2.0, reg=20.0, iters=10, seed=0):
    """Implicit ALS (Hu, Koren and Volinsky, 2008) on a dense plays matrix R.

    Preference p = 1 where R > 0, else 0. Confidence c = 1 + alpha * R, so every
    missing pair still counts as a weak 0 with confidence 1.
    """
    rng = np.random.default_rng(seed)
    X = rng.normal(0, 0.01, (R.shape[0], factors))   # user factors
    Y = rng.normal(0, 0.01, (R.shape[1], factors))   # item factors
    for _ in range(iters):
        X = _solve(R, Y, alpha, reg)       # users, with item factors fixed
        Y = _solve(R.T, X, alpha, reg)     # items, with user factors fixed
    return X, Y


def _solve(R, F, alpha, reg):
    """For each row r: minimise sum_j c_rj (p_rj - x . f_j)^2 + reg * |x|^2."""
    FtF = F.T @ F                          # the c = 1 part, shared by every row
    eye = reg * np.eye(F.shape[1])
    out = np.zeros((R.shape[0], F.shape[1]))
    for r in range(R.shape[0]):
        idx = np.flatnonzero(R[r])         # only observed pairs have c > 1
        if idx.size == 0:
            continue                       # no data: leave the factors at zero
        c, Fi = 1 + alpha * R[r, idx], F[idx]
        A = FtF + (Fi.T * (c - 1)) @ Fi + eye
        out[r] = np.linalg.solve(A, Fi.T @ c)        # p = 1 on observed pairs
    return out
Python · tune.py
from als import fit_als
from metrics import evaluate
from split import time_split

R, relevant = time_split(80, 100)                 # tune on validation, not test
warm = [u for u in relevant if R[u].sum() > 0]
print("alpha  recall@10  NDCG@10")
for alpha in [0, 2, 5, 20]:
    X, Y = fit_als(R, alpha=alpha)
    recall, ndcg = evaluate(lambda u: Y @ X[u], R, relevant, warm)
    print(f"{alpha:5d} {recall:10.3f} {ndcg:8.3f}")
Terminal
python tune.py
Expected output
alpha  recall@10  NDCG@10
    0      0.207    0.157
    2      0.346    0.256
    5      0.338    0.248
   20      0.309    0.227

With α = 0 every pair gets the same confidence, and the model barely beats popularity (0.207 against 0.201). α = 2 lifts recall@10 to 0.346, and larger values lose ground again. α is therefore a setting to tune, as are the number of factors and reg, always on the validation window, never on the test window. The original paper found α = 40 worked well on its TV-viewing data, so the best value depends on the data. Choose α = 2 for the final run.

07. Step 6: Test once, with a cold-start fallback

Now refit on all plays before day 100 and evaluate once on days 100 to 129. Cold-start users have no training plays, so ALS never updates their vectors, which stay at zero. hybrid gives them the popularity list instead. The script also runs a paired bootstrap over warm users, resampling users and comparing both models on the same users each time, to check that the gain is larger than noise.

Python · final.py
import numpy as np

from als import fit_als
from metrics import evaluate
from split import time_split

R, relevant = time_split(100, 130)                # fit once on all days before 100
warm = [u for u in relevant if R[u].sum() > 0]
cold = [u for u in relevant if R[u].sum() == 0]   # joined after the cut-off
popularity = (R > 0).sum(axis=0)
X, Y = fit_als(R, alpha=2)


def hybrid(u):
    """ALS for users with history, popularity for cold-start users."""
    return Y @ X[u] if R[u].sum() > 0 else popularity


rows = [("popularity", "warm", lambda u: popularity, warm),
        ("ALS", "warm", lambda u: Y @ X[u], warm),
        ("ALS, no fallback", "cold", lambda u: Y @ X[u], cold),
        ("popularity", "cold", lambda u: popularity, cold),
        ("popularity", "all", lambda u: popularity, warm + cold),
        ("ALS + fallback", "all", hybrid, warm + cold)]
print(f"{'model':17} {'users':>11}  recall@10  NDCG@10")
for name, group, score, users in rows:
    recall, ndcg = evaluate(score, R, relevant, users)
    print(f"{name:17} {group:>5} {len(users):5d} {recall:10.3f} {ndcg:8.3f}")

# paired bootstrap over warm users: is the recall gain more than noise?
als_r, _ = evaluate(lambda u: Y @ X[u], R, relevant, warm, per_user=True)
pop_r, _ = evaluate(lambda u: popularity, R, relevant, warm, per_user=True)
rng = np.random.default_rng(0)
draws = rng.integers(0, len(warm), (2000, len(warm)))
gain = (als_r[draws] - pop_r[draws]).mean(axis=1)
print(f"recall@10 gain, warm users: {np.mean(als_r - pop_r):.3f} "
      f"(95% bootstrap interval {np.percentile(gain, 2.5):.3f} to "
      f"{np.percentile(gain, 97.5):.3f})")

new_items = sum(len([i for i in s if R[:, i].sum() == 0]) for s in relevant.values())
total = sum(len(s) for s in relevant.values())
print(f"test pairs on items with no plays before day 100: {new_items / total:.1%}")
Terminal
python final.py
Expected output
model                   users  recall@10  NDCG@10
popularity         warm  1003      0.147    0.124
ALS                warm  1003      0.278    0.224
ALS, no fallback   cold   135      0.020    0.029
popularity         cold   135      0.201    0.320
popularity          all  1138      0.153    0.148
ALS + fallback      all  1138      0.269    0.235
recall@10 gain, warm users: 0.132 (95% bootstrap interval 0.115 to 0.149)
test pairs on items with no plays before day 100: 16.0%

On warm users, ALS nearly doubles recall@10 (0.278 against 0.147) and NDCG@10 (0.224 against 0.124), and the 95% bootstrap interval for the recall gain, 0.115 to 0.149, is far from zero. Scores are lower than on validation, which is normal: the test window is longer and contains new items. ALS without a fallback is useless for cold users (recall 0.020): every item scores zero, so it recommends items 0 to 9. With the popularity fallback the whole population gets 0.269 against 0.153.

One limit remains: 16.0% of test pairs involve items with no plays before day 100. Neither model can rank those items, so they cap the recall of both. Real systems cover new items with content features, such as genre or text embeddings, or by giving new releases some exposure on purpose.

At scale, recommenders usually work in two stages. A two-tower model trains one neural network for users and one for items, each producing a vector whose dot product scores the pair. Item vectors are computed ahead of time, so a nearest-neighbour index retrieves a few hundred candidates per user quickly, and the towers can use features, which helps with cold start. A heavier re-ranking model then orders the candidates. The evaluation habits from this lab carry over unchanged.

08. Check your understanding

Practice check · 3 questions

Reading the recommender results

Answer from the code and the numbers you produced in the lab.

Q1. In step 6, ALS without a fallback reaches recall@10 of only 0.020 for the 135 cold-start users. What is it actually recommending to them?
Q2. In step 6, 16.0% of the test pairs involve items with no plays before day 100. How do those pairs affect the comparison between the two models?
Q3. In `tune.py`, validation recall@10 falls from 0.346 at α = 2 to 0.309 at α = 20. What does the larger α most likely do to the model?
Practice only: not graded, not saved, not evidence.

09. Apply it: stretch tasks

  1. Tune more than α. On the validation window, try 8, 16 and 32 factors and three values of reg, then rerun final.py once with the best setting.
  2. A stronger baseline. Rank items by plays in the 14 days before the cut-off and check how much of ALS's margin remains.
  3. Practice project. On your own interaction log, report recall@10 and NDCG@10 for popularity and matrix factorisation trained before a cut-off date, with a bootstrap interval for the difference, and say how you handle cold-start users and items.

10. Review prompt

Without looking back, explain why a recommender is evaluated on a time-based split; what preference and confidence mean in implicit matrix factorisation and what α controls; how recall@k and NDCG@k differ, and how to check them by hand; why a popularity baseline is hard to beat; what happens to cold-start users and new items in a factorisation model; and what a two-tower model adds.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check