Collaborative Filtering from Scratch in Python

Build a movie recommender from scratch with embedding dot products. Implement EmbeddingDotBias in NumPy, train on MovieLens 100k, and read the embeddings.

Cover Image for Collaborative Filtering from Scratch in Python

You have rated a few movies, and a recommender needs to suggest others you might enjoy. Those few ratings cannot describe your preferences in full, but people with overlapping tastes provide more evidence. Collaborative filtering looks for patterns across that shared rating history. MovieLens lets us hide known ratings and check those predictions against them.

The shared history supports predictions even though 93.7% of the MovieLens matrix is empty. Combining user and movie vectors with rating biases gives validation RMSE 0.91. We build the NumPy model and inspect its movie vectors, relating them to hierarchy embeddings.

In this post, we will build the EmbeddingDotBias model from scratch in NumPy, train it on MovieLens 100k, and then explore the learned embeddings to discover what the model has figured out about movies on its own.

Let's Build It

Click the badge to run this yourself:

Open In Colab

Animation showing movie embeddings evolving during training: movies cluster by genre as the model learns

Here is the complete model. We represent each user and each movie as a learned vector (embedding) plus a bias term, then predict ratings as the dot product of embeddings plus biases:

import numpy as np
import pandas as pd

# Load MovieLens 100k
ratings = pd.read_csv('/tmp/ml-100k/u.data', delimiter='\t',
                       header=None, names=['user_id', 'movie_id', 'rating', 'timestamp'])
movies = pd.read_csv('/tmp/ml-100k/u.item', delimiter='|', encoding='latin-1',
                      header=None, usecols=[0, 1], names=['movie_id', 'title'])
ratings = ratings.merge(movies, on='movie_id')

n_users = ratings['user_id'].max()
n_movies = ratings['movie_id'].max()
print(f"{len(ratings)} ratings, {n_users} users, {n_movies} movies")
print(f"Sparsity: {1 - len(ratings) / (n_users * n_movies):.1%}")

# Train/validation split
np.random.seed(42)
mask = np.random.rand(len(ratings)) < 0.9
train = ratings[mask].reset_index(drop=True)
valid = ratings[~mask].reset_index(drop=True)

class EmbeddingDotBias:
    """Collaborative filtering with embedding dot products and bias terms."""

    def __init__(self, n_users, n_items, n_factors=40, y_range=(0, 5.5)):
        self.y_range = y_range
        scale = 0.01
        # Embeddings: one vector per user and per item
        self.user_emb = np.random.randn(n_users + 1, n_factors) * scale
        self.item_emb = np.random.randn(n_items + 1, n_factors) * scale
        # Biases: one scalar per user and per item
        self.user_bias = np.zeros(n_users + 1)
        self.item_bias = np.zeros(n_items + 1)

    def predict(self, user_ids, item_ids):
        """Predict ratings: dot product of embeddings + biases, clamped to y_range."""
        dot = np.sum(self.user_emb[user_ids] * self.item_emb[item_ids], axis=1)
        pred = dot + self.user_bias[user_ids] + self.item_bias[item_ids]
        # Sigmoid to clamp to y_range (same as fast.ai EmbeddingDotBias)
        pred = self._sigmoid_range(pred)
        return pred

    def _sigmoid_range(self, x):
        lo, hi = self.y_range
        return lo + (hi - lo) * (1 / (1 + np.exp(-x)))

    def _sigmoid_range_grad(self, x):
        lo, hi = self.y_range
        s = 1 / (1 + np.exp(-x))
        return (hi - lo) * s * (1 - s)

    def train_step(self, user_ids, item_ids, ratings, lr=0.01, wd=0.1):
        """One training step with MSE loss, weight decay, and gradient descent."""
        # Forward pass
        dot = np.sum(self.user_emb[user_ids] * self.item_emb[item_ids], axis=1)
        raw = dot + self.user_bias[user_ids] + self.item_bias[item_ids]
        pred = self._sigmoid_range(raw)

        # MSE loss gradient
        error = pred - ratings  # (batch,)
        sig_grad = self._sigmoid_range_grad(raw)
        d_raw = error * sig_grad  # chain rule through sigmoid

        # Gradients for embeddings
        d_user_emb = d_raw[:, None] * self.item_emb[item_ids]
        d_item_emb = d_raw[:, None] * self.user_emb[user_ids]
        d_user_bias = d_raw
        d_item_bias = d_raw

        # Update with weight decay (L2 regularisation on embeddings)
        for uid, d_ue in zip(user_ids, d_user_emb):
            self.user_emb[uid] -= lr * (d_ue + wd * self.user_emb[uid])
        for iid, d_ie in zip(item_ids, d_item_emb):
            self.item_emb[iid] -= lr * (d_ie + wd * self.item_emb[iid])
        for uid, d_ub in zip(user_ids, d_user_bias):
            self.user_bias[uid] -= lr * d_ub
        for iid, d_ib in zip(item_ids, d_item_bias):
            self.item_bias[iid] -= lr * d_ib

        return np.mean(error**2)

# Train
model = EmbeddingDotBias(n_users, n_movies, n_factors=40)
train_users = train['user_id'].values
train_items = train['movie_id'].values
train_ratings = train['rating'].values.astype(np.float32)
valid_users = valid['user_id'].values
valid_items = valid['movie_id'].values
valid_ratings = valid['rating'].values.astype(np.float32)

losses = []
for epoch in range(50):
    # Shuffle training data
    idx = np.random.permutation(len(train))
    epoch_loss = 0
    # Mini-batch training
    bs = 512
    for start in range(0, len(train), bs):
        batch = idx[start:start+bs]
        loss = model.train_step(train_users[batch], train_items[batch],
                                train_ratings[batch], lr=0.01, wd=0.1)
        epoch_loss += loss * len(batch)

    train_mse = epoch_loss / len(train)
    valid_pred = model.predict(valid_users, valid_items)
    valid_mse = np.mean((valid_pred - valid_ratings)**2)
    losses.append((train_mse, valid_mse))
    if epoch < 5 or (epoch + 1) % 10 == 0:
        print(f"Epoch {epoch+1:2d}: train MSE={train_mse:.4f}, valid MSE={valid_mse:.4f}")
Epoch  1: train MSE=1.0471, valid MSE=0.9190
Epoch  2: train MSE=0.8911, valid MSE=0.8982
Epoch  5: train MSE=0.8580, valid MSE=0.8848
Epoch 10: train MSE=0.8499, valid MSE=0.8834
Epoch 20: train MSE=0.8050, valid MSE=0.8587
Epoch 30: train MSE=0.7127, valid MSE=0.8325
Epoch 40: train MSE=0.6039, valid MSE=0.8202
Epoch 50: train MSE=0.5208, valid MSE=0.8245

Training and validation MSE over 50 epochs

Our from-scratch model achieves a validation MSE of 0.82 (RMSE 0.91), matching the Librec benchmark on this dataset. The train-valid gap after epoch 40 suggests the model is starting to overfit, which is where weight decay earns its keep.

What Just Happened?

Embeddings Are Just Lookup Tables

An embedding is a learnable matrix where each row corresponds to one entity (a user or a movie). When we "embed" user 42, we look up row 42. That is the entire operation: an array index.

# An embedding for 5 users in 3-dimensional space
user_embeddings = np.random.randn(5, 3)

# "Embed" user 2: just a lookup
user_2_vector = user_embeddings[2]
print(f"User 2 embedding: {user_2_vector}")

This is mathematically equivalent to multiplying a one-hot vector by the embedding matrix. If user 2 is represented as [0, 0, 1, 0, 0], then the matrix multiplication one_hot @ embedding_matrix selects row 2. The fast.ai notebook makes this connection explicit: "Embedding means: an array look-up, and this is mathematically equivalent to multiplying a matrix with a one-hot encoded matrix."

The Dot Product: Measuring Similarity

The model predicts a rating as the dot product of the user and movie embeddings. Two vectors with a high dot product point in similar directions in the embedding space, which means the model thinks this user will like this movie.

# User who likes action movies
user_vec = np.array([0.8, 0.1, -0.3])

# Two movies
action_movie = np.array([0.9, 0.2, -0.2])  # similar direction
romance_movie = np.array([-0.1, 0.7, 0.5])  # different direction

print(f"Action dot product:  {np.dot(user_vec, action_movie):.2f}")  # high = likes
print(f"Romance dot product: {np.dot(user_vec, romance_movie):.2f}")  # low = meh
Action dot product:  0.80
Romance dot product: 0.14

Why Bias Terms Matter

Not all movies are created equal. "The Shawshank Redemption" has a higher average rating than "Barb Wire" regardless of who is watching. Similarly, some users are generous raters (giving 4-5 stars to everything) while others are harsh (mostly 2-3 stars).

Bias terms capture these baseline tendencies. The prediction becomes:

r^ui=uu⋅mi+bu+bi\hat{r}_{ui} = \mathbf{u}_u \cdot \mathbf{m}_i + b_u + b_i

Where uu\mathbf{u}_u is the user embedding, mi\mathbf{m}_i is the movie embedding, bub_u is the user bias, and bib_i is the movie bias. The fast.ai notebook shows that adding bias reduces RMSE from 0.39 to 0.32 on the sample dataset.

The Sigmoid Clamp

Ratings in MovieLens are integers from 1 to 5. Without any clamping, the dot product plus biases can produce any real number. The fast.ai EmbeddingDotBias applies a sigmoid scaled to the rating range [0, 5.5]:

r^=rmin⁡+(rmax⁡−rmin⁡)⋅σ(raw prediction)\hat{r} = r_{\min} + (r_{\max} - r_{\min}) \cdot \sigma(\text{raw prediction})

This keeps predictions in a sensible range without hard clipping, which would kill gradients.

Exploring the Learned Embeddings

The most fascinating part of collaborative filtering is what the embeddings learn on their own, with no genre labels or metadata provided.

Movie Biases: Best and Worst Films

The movie bias bib_i captures inherent quality: how much a movie is liked regardless of personal taste.

# Get top movies by number of ratings
rating_counts = ratings.groupby('movie_id')['rating'].count()
top_movie_ids = rating_counts.sort_values(ascending=False).head(200).index.values

# Get bias and mean rating for top movies
movie_titles = movies.set_index('movie_id')['title']
movie_data = []
for mid in top_movie_ids:
    bias = model.item_bias[mid]
    mean_rating = ratings[ratings['movie_id'] == mid]['rating'].mean()
    movie_data.append((bias, movie_titles.get(mid, f'Movie {mid}'), mean_rating))

# Highest bias (best movies)
print("Highest bias (universally liked):")
for bias, title, mean in sorted(movie_data, key=lambda x: x[0], reverse=True)[:10]:
    print(f"  {bias:+.3f}  {mean:.2f}★  {title}")

print("\nLowest bias (universally disliked):")
for bias, title, mean in sorted(movie_data, key=lambda x: x[0])[:10]:
    print(f"  {bias:+.3f}  {mean:.2f}★  {title}")

Bar chart showing the 10 highest and 10 lowest movie biases

The bias learns what you would expect: critically acclaimed films like "Schindler's List" and "The Shawshank Redemption" get high positive biases, while poorly received films get negative biases.

PCA on Embeddings: Discovering Latent Dimensions

Each movie has a 40-dimensional embedding. We can project these down to 2 dimensions using PCA to see what structure the model has learned:

from sklearn.decomposition import PCA

# Get embeddings for top-rated movies
top_embs = model.item_emb[top_movie_ids]
pca = PCA(n_components=2)
coords = pca.fit_transform(top_embs)

# Plot
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(12, 10))
ax.scatter(coords[:, 0], coords[:, 1], alpha=0.3)
for i, mid in enumerate(top_movie_ids[:50]):
    ax.annotate(movie_titles.get(mid, ''), (coords[i, 0], coords[i, 1]),
                fontsize=7, alpha=0.8)
ax.set_xlabel('PC1'); ax.set_ylabel('PC2')
ax.set_title('Movie Embeddings (PCA, top 200 movies)')
plt.show()

PCA scatter plot of movie embeddings showing clusters: action/sci-fi on one side, drama/romance on the other

Without any genre information, the model has learned to separate movies along meaningful dimensions. The first principal component often separates mainstream blockbusters from indie/art films. The second component often captures a genre axis (action/sci-fi vs drama/romance). The fast.ai notebook applies this same PCA analysis and finds that the learned factors align with interpretable movie properties.

The Sparsity Problem

Our rating matrix has 943 users and 1,682 movies, but only 100,000 of the 1.59 million possible entries are filled. That is 93.7% missing data.

Sparsity visualization: a small sample of the user-item matrix showing mostly empty cells with scattered ratings

This extreme sparsity is why collaborative filtering uses low-rank factorisation rather than trying to fill the matrix directly. By compressing each user and movie into a 40-dimensional embedding, we force the model to find shared patterns rather than memorising individual ratings.

Going Deeper

Matrix Factorisation: The Mathematical View

Collaborative filtering with embeddings is equivalent to matrix factorisation. If RR is the rating matrix (users x movies), we approximate it as:

R≈U⋅MT+bu1T+1bmTR \approx U \cdot M^T + b_u \mathbf{1}^T + \mathbf{1} b_m^T

Where UU is the user embedding matrix (users x factors), MM is the movie embedding matrix (movies x factors), and bub_u, bmb_m are bias vectors. This is closely related to SVD, with the key difference that we only optimise on observed entries (not the entire matrix).

The number of factors (n_factors=40 in our model) controls the rank of the approximation. More factors capture more nuanced preferences but risk overfitting. The fast.ai notebook uses n_factors=40 with weight decay wd=0.1 for regularisation.

Weight Decay Is Critical

Without weight decay, the model quickly overfits: it memorises the training ratings but fails on validation. The fast.ai notebook emphasises this: "from empirical experiments, he usually sets lambda (weight decay) to be 0.1."

Weight decay penalises large embedding values, encouraging the model to find compact, generalisable representations. As we covered in the optimisers post, this is equivalent to L2 regularisation on the embedding parameters.

The Cold Start Problem

The fast.ai notebook flags this directly: "This is in practice difficult to use, as it has a cold start problem. When you want this to work well the most is when a new user or movie enters the picture, however then you don't have enough data to learn that info."

For a new user with zero ratings, we have no information to learn their embedding. Common solutions include:

  • Content-based fallback: Use movie metadata (genre, director, year) when collaborative data is sparse
  • Onboarding quiz: Ask new users to rate a few well-known items (the Netflix approach)
  • Hybrid models: Combine collaborative and content-based signals in a single model
  • Default embedding: Initialise new users/items to the average embedding

From Dot Products to Neural Networks

Our EmbeddingDotBias is a linear model: the prediction is a dot product (plus biases) of the embeddings. A natural extension is to concatenate the embeddings and pass them through a neural network:

# Linear: dot product + bias
pred = np.dot(user_emb, movie_emb) + user_bias + movie_bias

# Neural: concatenate embeddings, pass through MLP
combined = np.concatenate([user_emb, movie_emb])
pred = neural_network(combined)

The neural approach can capture non-linear interactions (e.g., "users who like both action AND comedy tend to rate this movie higher") but needs more data and is harder to interpret. For most recommendation tasks, the dot product model is a surprisingly strong baseline.

Where This Comes From

The Netflix Prize (2006-2009)

Modern collaborative filtering was catalysed by the Netflix Prize, a competition offering $1 million to anyone who could improve Netflix's recommendation system by 10%. The competition ran from 2006 to 2009 and attracted thousands of teams.

"We're quite curious, really. To the tune of one million dollars." -- Netflix Prize announcement

The winning solution by team BellKor's Pragmatic Chaos used an ensemble of hundreds of models, but the core technique was matrix factorisation with latent factors, the same approach we implemented here. Simon Funk's influential blog post during the competition popularised the stochastic gradient descent approach to matrix factorisation that we used.

Koren, Bell & Volinsky (2009)

The definitive academic treatment is "Matrix Factorization Techniques for Recommender Systems" by Yehuda Koren, Robert Bell, and Chris Volinsky (2009), published in IEEE Computer after the Netflix Prize concluded.

"Matrix factorization models map both users and items to a joint latent factor space of dimensionality f, such that user-item interactions are modeled as inner products in that space." -- Koren, Bell & Volinsky (2009)

They introduced the bias terms we implemented (user and item biases) and temporal dynamics (preferences change over time). The paper remains one of the most cited works in recommendation systems.

Embeddings Beyond Recommendations

The embedding concept has spread far beyond collaborative filtering:

  • Word2Vec (Mikolov et al., 2013): Words as vectors, where similar words have similar embeddings
  • Transformers: Token embeddings and positional embeddings are the input representation
  • Graph Neural Networks: Node embeddings capture graph structure
  • Entity Embeddings for Tabular Data (Guo & Berkhahn, 2016): Categorical features as learned vectors, which the fast.ai tabular model uses extensively

Further Reading

Interactive Tools

  • Eigenvalue, Eigenvector & SVD Visualizer: Matrix factorisation is truncated SVD in disguise. Edit a matrix and step through the U·Σ·Vᵀ decomposition to see how singular values rank the directions a recommender keeps when it compresses the rating matrix.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions