“Learners who took this course also liked…” is a recommender system at work. One of the simplest and most useful kinds is item-based collaborative filtering: two items are similar if the same people rate them in a similar way. This lesson builds one from scratch with pandas and scikit-learn, then measures whether it beats a simple baseline.
In this lesson you will learn
- How a user-item rating matrix is laid out
- Measuring item similarity with cosine similarity
- Predicting a missing rating from similar items
- Testing a recommender by hiding known ratings
- Common problems: cold start, sparsity and popularity bias
You should know pandas DataFrames and k-nearest neighbors, which uses the same “look at similar things” idea.
The Rating Matrix
A recommender starts from a table with one row per user and one column per item. Each cell holds a rating, or nothing if the user has not rated that item. Real tables are mostly empty: a learner may rate 10 courses out of thousands.
There are two main families of methods:
- Content-based: recommend items whose description is similar to what the user liked, such as courses with the same tags.
- Collaborative filtering: use only the ratings. If the people who liked course A also liked course B, the two courses are related, whatever their topic.
Item-Based Filtering on a Small Example
import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
# Ratings from 1 to 5; 0 means "not rated yet"
ratings = pd.DataFrame(
[[5, 4, 0, 1, 0],
[4, 5, 1, 0, 2],
[1, 0, 5, 4, 5],
[0, 1, 4, 5, 4],
[5, 0, 0, 2, 1]],
index=["Rina", "Tamim", "Nadia", "Arif", "Sumi"],
columns=["Python Basics", "Pandas", "Photoshop", "Illustrator", "Figma"])
sim = pd.DataFrame(cosine_similarity(ratings.T),
index=ratings.columns, columns=ratings.columns)
print("Course similarity:")
print(sim.round(2))
def predict(user, item):
rated = ratings.loc[user] > 0
w = sim.loc[item, rated]
return (w * ratings.loc[user, rated]).sum() / w.sum()
for item in ratings.columns[ratings.loc["Sumi"] == 0]:
print(f"Sumi's predicted rating for {item}: {predict('Sumi', item):.2f}")
Output
Course similarity:
Python Basics Pandas Photoshop Illustrator Figma
Python Basics 1.00 0.75 0.17 0.34 0.32
Pandas 0.75 1.00 0.21 0.20 0.32
Photoshop 0.17 0.21 1.00 0.91 0.98
Illustrator 0.34 0.20 0.91 1.00 0.91
Figma 0.32 0.32 0.98 0.91 1.00
Sumi's predicted rating for Pandas: 3.52
Sumi's predicted rating for Photoshop: 1.77
ratings.Tturns courses into rows, socosine_similaritycompares courses with each other. Cosine similarity measures how closely two rating columns point in the same direction: 1 means identical patterns, 0 means no overlap.- The table splits into two families. Python Basics and Pandas are similar (0.75). Photoshop, Illustrator and Figma are all very similar to each other (0.91 to 0.98). Nobody told the code these were “programming” and “design” courses; it learned this from the ratings.
- To predict Sumi’s rating for a course,
predicttakes the courses she has rated and averages her ratings, weighted by how similar each one is to the target course. - Sumi gave Python Basics a 5 and the design courses low marks, so Pandas is predicted at 3.52 and Photoshop at only 1.77. Pandas is the one to recommend.
In this small example, 0 means “not rated” but cosine similarity treats it as a real zero. That is acceptable for a demo, but the next example handles it properly.
Does It Actually Work?
To test a recommender, hide some ratings you know, predict them, and compare. The next example uses 300 learners and 40 courses, where each learner has rated about a quarter of the courses.
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
# 300 learners, 40 courses; tastes come from 3 hidden interests
rng = np.random.default_rng(1)
users, items = 300, 40
taste = rng.normal(0, 1, (users, 3))
style = rng.normal(0, 1, (items, 3))
true = np.clip(3 + taste @ style.T * 0.7 + rng.normal(0, 0.5, (users, items)), 1, 5)
R = np.where(rng.random((users, items)) < 0.25, true.round(), 0) # 25% rated
# Hide 10% of the known ratings to test on
known = np.argwhere(R > 0)
test = known[rng.random(len(known)) < 0.10]
train = R.copy()
train[test[:, 0], test[:, 1]] = 0
print("Train ratings:", (train > 0).sum(), "| test ratings:", len(test))
mask = train > 0
item_mean = train.sum(0) / mask.sum(0)
centred = np.where(mask, train - item_mean, 0) # remove each course's average
sim = cosine_similarity(centred.T)
np.fill_diagonal(sim, 0)
def predict(u, i, k=10):
rated = np.flatnonzero(mask[u])
top = rated[np.argsort(sim[i, rated])[::-1][:k]]
w = np.clip(sim[i, top], 0, None)
if w.sum() == 0:
return item_mean[i]
return item_mean[i] + (w * centred[u, top]).sum() / w.sum()
actual = R[test[:, 0], test[:, 1]]
base = item_mean[test[:, 1]]
cf = np.array([predict(u, i) for u, i in test])
rmse = lambda p: np.sqrt(((p - actual) ** 2).mean())
print(f"RMSE, course average only : {rmse(base):.3f}")
print(f"RMSE, item-based CF (k=10): {rmse(cf):.3f}")
u = 0
unseen = np.flatnonzero(~mask[u])
scores = [predict(u, i) for i in unseen]
top3 = unseen[np.argsort(scores)[::-1][:3]]
print("Top 3 courses for learner 0:", top3, np.sort(scores)[::-1][:3].round(2))
Output
Train ratings: 2739 | test ratings: 272
RMSE, course average only : 1.140
RMSE, item-based CF (k=10): 0.990
Top 3 courses for learner 0: [18 9 25] [3.54 3.52 3.48]
- About 10% of the known ratings (272) are hidden and used as the test set.
- Mean-centring: each course’s average is subtracted before computing similarity. Some courses are rated high by everyone; centring makes similarity reflect agreement in taste rather than general popularity. Unrated cells become 0, which now means “average” instead of “terrible”.
- For each prediction, only the
k=10most similar courses the learner has rated are used, and negative similarities are ignored. - The baseline predicts every rating as the course’s average and has an RMSE of 1.140. Collaborative filtering lowers it to 0.990, so knowing what similar courses a learner liked does help.
- To recommend, predict every course the learner has not rated and show the top three.
Always compare against a simple baseline like the course average. A recommender that cannot beat it is not worth its complexity.
Real-World Problems
| Problem | What happens | Common fix |
|---|---|---|
| Cold start | A new user or item has no ratings, so there is nothing to compare | Show popular items, or use content-based features |
| Sparsity | Two items share very few raters, so their similarity is noisy | Require a minimum number of shared raters; shrink small-sample similarities |
| Popularity bias | Popular items get recommended more, so they get rated more | Mix in less-known items on purpose |
| Scale | Millions of items make a full similarity table too big | Keep only the top neighbours per item; use matrix factorization |
Common Mistakes
- Treating missing ratings as zero without centring, so “not seen” looks like “hated”.
- Testing on ratings used to build the similarity table. Hide the test ratings before computing anything.
- Recommending items the user already has. Filter out rated or purchased items.
- Judging only by RMSE. Users see a short top-N list, so measures like precision at 5 often matter more.
Practice Exercises
Exercise 1. In rec1.py, find the course most similar to Figma, excluding Figma itself.
Show answer
print(sim["Figma"].drop("Figma").idxmax())
# Photoshop
Exercise 2. In rec2.py, compute the RMSE for k=5 and k=20. Which is better?
Show answer
for k in [5, 20]:
p = np.array([predict(u, i, k) for u, i in test])
print(k, round(rmse(p), 3))
Small k relies on very few courses and is noisy; large k includes weakly related courses. On this data k=5, 10 and 20 all give an RMSE of about 0.99, so the choice hardly matters here. On real data the differences are often larger, so tune k on a separate validation set.
Frequently Asked Questions
Item-based or user-based?
User-based filtering finds similar users instead of similar items. Item-based is usually more stable, because an item’s audience changes slowly while a user’s history is short and changes fast. There are also usually fewer items than users.
What is matrix factorization?
It squeezes the rating matrix into a few hidden factors per user and per item, such as “likes design” or “likes coding”. A rating is predicted by combining the user’s and item’s factors. It handles sparse data well and was popularized by the Netflix Prize competition.
Can I use clicks instead of star ratings?
Yes. Clicks, views and purchases are called implicit feedback. They are far more plentiful than ratings, but a missing click does not mean dislike, so evaluation needs care.
Summary
- Item-based filtering scores items by how similar their rating patterns are.
- Cosine similarity on mean-centred ratings measures that similarity.
- A prediction is a similarity-weighted average of the user’s own ratings.
- Test by hiding known ratings, and always beat a simple baseline.
