A recommendation system with Python takes less code than most people expect. The hard part is knowing whether it works: a recommender that looks clever can lose to the simple rule “show what is popular”. This tutorial builds three recommenders on real movie ratings, tests them against a popularity baseline on held-out data, and reports where the gains are large and where they are close to noise. Everything ran on 21 November 2026 with Python 3.13, NumPy 2.5.5, SciPy 1.18.1 and pandas 3.0.5.
The data: ratings tweeted by real users
MovieTweetings collects ratings that people post on Twitter after watching a movie on IMDb (for example “I rated X 8/10”). The version we downloaded has 921,398 ratings from 71,707 users on 38,013 movies, on a 0 to 10 scale with a mean of 7.31. It is a real, public file, but note the bias: people who tweet ratings are not a random sample of viewers, and they mostly rate films they liked.
Most users rate only a handful of movies, which makes the matrix extremely sparse. We keep users and movies with at least 20 ratings (repeating the filter, because removing one changes the other). That leaves 593,400 ratings from 8,576 users on 4,779 movies, a matrix that is 1.4% filled.
The split matters more than the algorithm. We hold out each user’s most recent rating as the test case and train on everything earlier. A random split would let the model peek at future behaviour.
import numpy as np, pandas as pd, scipy.sparse as sp
from scipy.sparse.linalg import svds
BASE = "https://raw.githubusercontent.com/sidooms/MovieTweetings/master/latest/"
ratings = pd.read_csv(BASE + "ratings.dat", sep="::", engine="python",
names=["user", "movie", "rating", "time"])
movies = pd.read_csv(BASE + "movies.dat", sep="::", engine="python",
names=["movie", "title", "genres"]).set_index("movie")
print(len(ratings), "ratings,", ratings.user.nunique(), "users,", ratings.movie.nunique(), "movies")
# keep users and movies with at least 20 ratings (repeat, because each filter affects the other)
for _ in range(3):
n = ratings.user.value_counts(); ratings = ratings[ratings.user.isin(n[n >= 20].index)]
n = ratings.movie.value_counts(); ratings = ratings[ratings.movie.isin(n[n >= 20].index)]
users = {u: k for k, u in enumerate(ratings.user.unique())}
items = {m: k for k, m in enumerate(ratings.movie.unique())}
ratings = ratings.assign(u=ratings.user.map(users), i=ratings.movie.map(items)).sort_values(["u", "time"])
print(len(ratings), "ratings,", len(users), "users,", len(items), "movies")
test = ratings.groupby("u").tail(1) # each user's most recent rating
train = ratings.drop(test.index)
nu, ni = len(users), len(items)
R = sp.csr_matrix((train.rating.astype(float), (train.u, train.i)), shape=(nu, ni))
B = sp.csr_matrix((np.ones(len(train)), (train.u, train.i)), shape=(nu, ni)) # who rated what
print(len(train), "train,", len(test), "test; density", round(B.nnz / (nu * ni), 4))921398 ratings, 71707 users, 38013 movies
593400 ratings, 8576 users, 4779 movies
584824 train, 8576 test; density 0.0143Predicting the rating: biases do most of the work
The classic task is to predict the number a user would give. We start with the average rating, then add a damped per-movie average (so a movie with two ratings is pulled toward the global mean), then a per-user offset (some people rate everything high), and finally a 40-factor SVD fitted on what is left over. The metric is RMSE on the 8,576 held-out ratings, in rating points.
mu = train.rating.mean()
def rmse(pred): return np.sqrt(np.mean((test.rating.values - pred) ** 2))
count = np.asarray(B.sum(0)).ravel(); total = np.asarray(R.sum(0)).ravel()
item_bias = (total + 10 * mu) / (count + 10) - mu # damped item average
ucount = np.asarray(B.sum(1)).ravel(); utotal = np.asarray(R.sum(1)).ravel()
user_bias = (utotal + 10 * mu) / (ucount + 10) - mu
print("RMSE global mean", round(rmse(mu), 3))
print("RMSE + item bias", round(rmse(mu + item_bias[test.i.values]), 3))
bias_pred = mu + item_bias[test.i.values] + user_bias[test.u.values]
print("RMSE + user bias", round(rmse(np.clip(bias_pred, 0, 10)), 3))
coo = R.tocoo()
resid = sp.csr_matrix((coo.data - (mu + item_bias[coo.col] + user_bias[coo.row]), (coo.row, coo.col)), shape=(nu, ni))
U, S, Vt = svds(resid, k=40)
pred = bias_pred + np.einsum("ij,ij->i", U[test.u.values] * S, Vt.T[test.i.values])
print("RMSE + SVD on residuals", round(rmse(np.clip(pred, 0, 10)), 3))RMSE global mean 1.82
RMSE + item bias 1.61
RMSE + user bias 1.483
RMSE + SVD on residuals 1.474Item and user averages cut the error from 1.82 to 1.48. The SVD adds only 0.009 more. On this data, the personalised “taste” part of the model contributes very little to rating accuracy, which is a common finding: most of the signal is that some movies are liked and some people are generous. If someone tells you their recommender is “personalised”, ask how much of its accuracy survives once you subtract those biases.
Ranking: what a recommendation system with Python shows users
A real recommender shows a short list, so ranking matters more than rating error. We use a standard shortcut: for each test user, score the held-out movie together with 100 random movies that user has not rated, and count a hit if the held-out movie lands in the top 10. A random scorer would score 9.9% (10 out of 101). We use the first 3,000 users to keep it quick.
Baseline: the most popular movies
This scorer ranks every movie by the number of training ratings. No personalisation at all.
Item-based collaborative filtering
Two movies are similar when the same people rated both. We compute the cosine similarity between movie columns of the rated/not-rated matrix, keep each movie’s 50 nearest neighbours, and score a candidate by summing its similarity to the movies the user has already rated.
Matrix factorisation (SVD)
Truncated SVD compresses the user-by-movie matrix into 40 hidden factors. A user and a movie are each a point in that space, and the score is how well they line up. See the SciPy svds documentation for the details.
rng = np.random.default_rng(0)
def hit_rate(score_user, n_users=3000, N=10):
hits = 0
for u, i in zip(test.u.values[:n_users], test.i.values[:n_users]):
seen = set(B[u].indices)
pool = [c for c in rng.choice(ni, 200, replace=False) if c not in seen and c != i][:100]
s = score_user(u)[[i] + pool]
hits += (s > s[0]).sum() < N
return hits / n_users
print("random baseline", round(10 / 101, 3))
print("most popular", round(hit_rate(lambda u: count), 3))
sim = (B.T @ B).toarray().astype(float) # co-rating counts
d = np.sqrt(np.diag(sim)); sim = sim / np.outer(d, d); np.fill_diagonal(sim, 0) # cosine
top = np.argpartition(-sim, 50, axis=1)[:, :50] # keep 50 neighbours per movie
knn = np.zeros_like(sim); r = np.arange(ni)[:, None]; knn[r, top] = sim[r, top]
print("item-based kNN", round(hit_rate(lambda u: knn @ B[u].toarray().ravel()), 3))
U, S, Vt = svds(B.astype(float), k=40)
print("SVD, 40 factors", round(hit_rate(lambda u: (U[u] * S) @ Vt), 3))random baseline 0.099
most popular 0.522
item-based kNN 0.584
SVD, 40 factors 0.594
Two things stand out. First, “most popular” is a very strong baseline: it finds the held-out movie in the top 10 for 52.2% of users, more than five times random. Any recommender you build has to beat this, and it should be the first thing you report. Second, personalisation helps, but modestly: item-based kNN adds 6.2 points and SVD adds 7.2. With 3,000 test users, a hit rate has a standard error of about 0.9 points, so the 1-point gap between kNN and SVD is not strong evidence that one is better. The gap to the popularity baseline is.
One caution about this protocol. Sampling 100 random candidates makes the task easier than ranking all 4,779 movies, and research on recommender evaluation has shown that sampled metrics can change the order of models. Treat the absolute numbers as comparisons between methods, not as promises about production performance.
Do the recommendations look sensible?
Numbers aside, always look at some output. Here are the five movies most similar to Inception (2010) by cosine similarity of who rated them:
inv = {k: m for m, k in items.items()}
def similar(title, n=5):
mid = movies.index[movies.title == title][0]; j = items[mid]
return [(movies.title[inv[k]], round(sim[j, k], 3)) for k in np.argsort(-sim[j])[:n]]
print(similar("Inception (2010)"))[('Fight Club (1999)', 0.266), ('Forrest Gump (1994)', 0.264), ('The Prestige (2006)', 0.26),
('Se7en (1995)', 0.253), ('The Dark Knight (2008)', 0.253)]The Prestige and The Dark Knight are the same director, and Fight Club and Se7en are plausible. Forrest Gump is the sign of a popularity effect: cosine on binary data favours movies that almost everybody rated. A common fix is to divide by item popularity or to use a different similarity, and it is worth testing on your own data.
Limits of this recommender
- Cold start. A new user or movie has no ratings, so none of these models can score it. 11.5% of the held-out movies had fewer than 50 training ratings, and those are the hardest cases.
- Offline is not online. A 59.4% hit rate on a sampled test says nothing about whether people click. Only an A/B test measures that.
- Biased data. Users who tweet ratings skew toward popular, recent films, so popularity looks even stronger here than it would on a general audience.
To go further, add content features such as genre, which helps with cold start, or train a model with implicit feedback weights. If you want to serve your model to an app, see how to deploy a machine learning model with Flask, and for the evaluation habits used here read building a model with scikit-learn and exploratory data analysis in Python.
FAQ
What is the simplest recommendation system I can build in Python?
Rank items by popularity. It needs one line of pandas, and in this test it already found the held-out movie in the top 10 for 52.2% of users.
What is the difference between collaborative filtering and matrix factorisation?
Item-based collaborative filtering scores an item by its similarity to items the user already rated. Matrix factorisation learns a small number of hidden factors for every user and item and scores by how well they match. Here they ended within one point of each other.
Do I need a library like Surprise or LightFM?
No. This tutorial uses only NumPy, SciPy and pandas. Libraries help with larger data, implicit-feedback training and ready-made evaluation, but they are not needed to learn the ideas.
How should I evaluate a recommender?
Split by time, compare against a popularity baseline, report ranking metrics rather than only rating error, and confirm with an online A/B test before trusting any offline number.
