Sub topic 1
How collaborative filtering works
Collaborative filtering (CF) is a way to predict what a user will like by using the behavior of many users. It does not need to know anything about the items themselves. This chapter gives the working model, contrasts CF with content-based recommendation, and lists the common errors. Later chapters build each piece in code.
Prerequisites
This chapter assumes you have:
- Basic Python, including functions and loops.
- Vectors, dot products, and matrices, at the level of "multiply a matrix by a vector".
- Averages and basic statistics, such as mean and the idea of correlation.
- Familiarity with NumPy arrays: indexing, boolean masks, and
np.where.
The core idea
Suppose Ana and Ben both loved the same five films. Ana then loves a sixth film that Ben has not seen. A reasonable guess is that Ben will like it too. CF turns that guess into an algorithm.
The assumption behind it is that people who agreed in the past will tend to agree in the future. The data is a record of who interacted with what, and nothing else. An item is identified only by the pattern of users who touched it.
This leads to two views of the same data:
- User view: find users whose past behavior resembles yours, then recommend what they liked.
- Item view: find items that the same people tend to like together, then recommend items similar to those you already liked.
Both views come from one table, the user-item matrix, which the later chapters cover in detail.
CF versus content-based recommendation
A content-based recommender describes each item by its features, such as genre, director, or text, and builds a profile of what a user likes in those terms. It recommends items whose features match the profile.
| Aspect | Collaborative filtering | Content-based |
|---|---|---|
| Input | Interactions between users and items | Item features plus one user's history |
| Needs item metadata | No | Yes |
| Uses other users' data | Yes | No |
| Can surface surprising items | Yes, if similar users liked them | Rarely, it stays close to known tastes |
| New item with no interactions | Cannot be recommended | Can be recommended from its features |
| New user with no history | Cannot be served | Cannot be served |
CF can recommend things that look unrelated on paper. Two films with different genres may share an audience. The price is that CF is blind to anything without interaction data, which is the cold start problem covered later in this tutorial.
The main families of methods
CF methods fall into two groups.
- Neighborhood methods (also called memory-based) store the matrix and compute predictions from the most similar users or items at query time. They are simple and easy to explain. User-based and item-based CF belong here.
- Model-based methods learn a compact model from the matrix. Matrix factorization is the standard example. It learns a short vector of numbers per user and per item, so that a dot product approximates the rating.
Neighborhood methods are the quickest way to get a working baseline. Factorization usually predicts better on large, sparse data and is cheaper at serving time.
A tiny worked example
Here is a small matrix of ratings from 1 to 5, where 0 means "not rated". Rows are users and columns are items.
import numpy as np
# Rows are users, columns are items. 0 means "not rated".
R = np.array([
[5, 3, 0, 1],
[4, 0, 0, 1],
[1, 1, 0, 5],
[1, 0, 0, 4],
[0, 1, 5, 4],
], dtype=float)
observed = R > 0
sparsity = 1.0 - observed.sum() / R.size
print(f"{observed.sum()} ratings, sparsity = {sparsity:.2f}")The output is 13 ratings, sparsity = 0.35. Users 0 and 1 rate items 0 and 3 in nearly the same way: high on item 0, low on item 3. Users 2 and 3 show the opposite pattern. Item 2 was rated only by user 4. A neighborhood method would see two taste groups, and it would have very little evidence about item 2.
Even this small example shows the central difficulty. Most cells are empty, and predictions must be made from the few that are filled.
Prediction, step by step
Every CF method answers the same question: what score would user u give item i? The steps are:
- Build the matrix from logged interactions.
- Measure how related users to users, or items to items, are. Alternatively, learn latent vectors.
- Combine the evidence into a score for each unseen item.
- Remove items the user already has, sort by score, and return the top N.
Step 3 differs between families. A neighborhood method averages the ratings of similar users or items, weighted by similarity. A factorization method computes a dot product between a user vector and an item vector.
Where the data comes from
The matrix can hold explicit feedback, such as star ratings, or implicit feedback, such as clicks, purchases, and watch time. Implicit data is far more plentiful but noisier, because a click does not mean approval. The next chapter treats the difference in detail. The core idea in this chapter holds for both.
Common errors
These mistakes appear often when people first build a CF system.
- Treating 0 as a real rating. In the example above, 0 means "missing", not "hates it". Inside similarity calculations, zeros pull vectors in misleading ways. Later chapters show how to mask or center the data.
- Recommending items the user already consumed. Always filter known items before ranking.
- Judging quality on the same data used to build the model. A model that memorizes the matrix looks perfect on it. Evaluation needs a split that avoids leakage.
- Expecting CF to work from day one. With a brand-new catalog or user base, there is no signal to learn from.
- Ignoring popularity. Popular items have the most data, so CF tends to recommend them to everyone. That can hide the long tail of niche items.
- Assuming the result explains why. A neighborhood method can say "people like you liked this". A factorization model usually cannot give a reason in human terms.
Limits to keep in mind
CF needs enough overlap between users. If two users share no rated items, no similarity can be computed. Sparse matrices produce noisy estimates from very few shared items. Taste may also change over time, and a plain matrix has no notion of time. The later chapters on cold start, scaling, popularity bias, and hybrid models address each of these.
Summary
CF predicts preferences from patterns in interactions alone. It works from a user-item matrix, either by finding similar neighbors or by learning latent factors. It can surface unexpected items and needs no metadata, but it fails for users and items with no history and tends to favor popular items.
Exercise
A new film is added to the catalog today and nobody has rated it. Can a pure collaborative filtering system recommend it? What would a content-based system do instead?
Show answer
A pure CF system cannot recommend it, because the film has no interactions, so there is no pattern linking it to any user. A content-based system can recommend it right away by matching its features, such as genre or cast, against each user's profile.
Exercise
In the 5x4 example matrix, users 0 and 1 gave similar ratings to items 0 and 3. User 1 has not rated item 1. Which user's ratings would a user-based method rely on most to predict it, and why?
Show answer
User 0. User 0 rated items 0 and 3 almost the same way as user 1 (5 and 1 against 4 and 1), so user 0 is the closest neighbor. User 0 also rated item 1, giving a 3 to base the prediction on.
Exercise
Why is it a mistake to evaluate a CF model on the ratings it was trained on?
Show answer
The model has already seen those ratings, so a model that memorizes them scores well without being able to predict anything new. Evaluation must use held-out interactions the model never saw.