Skip to main content

Chapter 16 demo: Recommending movies

Read Chapter 16 · Download notebook (.ipynb)

Predict: Does predicting ratings accurately guarantee useful recommendations?

Setup and data

Construct a utility matrix, compare rating predictors, and inspect recommendations.

Run cells in order with the repository’s Python environment selected as the kernel. From the repository root, start Jupyter with uv run --locked jupyter lab, then open book/demo-chapter-16-recommender-systems.ipynb. Data paths work from either the repository root or book/. If using a downloaded notebook separately, place its required files in a data/ folder beside it.

Use data/toy_ratings.csv and data/toy_movie_feats.csv, included in the repository. Dense tables are used for this small teaching example; larger systems usually require sparse representations.

Class route: Begin with missing ratings and baselines, then compare content-based predictions and discuss what rating error leaves out.

Pause at prediction and discussion questions before revealing results. Rendered pages show saved outputs; controls that depend on a running Python kernel require Jupyter. General environment and download guidance is on the Demos page.

from pathlib import Path

import numpy as np
import pandas as pd
from IPython.display import display
from sklearn.impute import KNNImputer
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split

DATA_DIR = Path("data") if Path("data").is_dir() else Path("book/data")
RANDOM_STATE = 42
pd.set_option("display.max_colwidth", None)

for filename in ["toy_ratings.csv", "toy_movie_feats.csv"]:
    if not (DATA_DIR / filename).is_file():
        raise FileNotFoundError(f"Required data file: {(DATA_DIR / filename).resolve()}")

1. Inspect ratings and construct the utility matrix

Each row in the source data is one observed rating. We want one row per user and one column per movie, with NaN for unknown ratings.

Predict: What would change if we treated an unknown rating as zero?

ratings = pd.read_csv(DATA_DIR / "toy_ratings.csv")
ratings.head()
user_id movie_id rating
0 Sam Lion King 4
1 Sam Jerry Maguire 4
2 Sam Roman Holidays 5
3 Sam Downfall 1
4 Eva Titanic 2
utility = ratings.pivot(index="user_id", columns="movie_id", values="rating")
users = utility.index
movies = utility.columns

display(utility)
print(f"{len(ratings)} ratings from {len(users)} users for {len(movies)} movies")
print(f"Observed fraction: {utility.notna().to_numpy().mean():.1%}")
movie_id A Beautiful Mind Bambi Cast Away Downfall Inception Jerry Maguire Lion King Malcolm x Man on Wire Roman Holidays The Social Dilemma Titanic
user_id
Eva NaN NaN NaN NaN 4.0 1.0 NaN NaN 5.0 NaN 5.0 2.0
Jim NaN NaN NaN NaN NaN NaN 3.0 4.0 5.0 NaN 5.0 2.0
Pat 3.0 4.0 3.0 2.0 NaN 5.0 4.0 NaN NaN NaN NaN 3.0
Sam NaN NaN NaN 1.0 NaN 4.0 4.0 NaN NaN 5.0 NaN NaN
21 ratings from 4 users for 12 movies
Observed fraction: 43.8%

Inspect: Rows are users, columns are movies, and the labels preserve their identities. We will keep this order in every prediction table.

Reveal explanation: missing versus zero

An unknown rating gives no evidence of dislike. Replacing it with zero invents a rating and changes averages and distances. Keep missing entries distinct from observed ratings.

2. Hold out ratings and define evaluation

  • Split the observed ratings, then build train and validation tables with the same user/movie axes.
  • Only the locations of observed entries differ. Validation ratings are hidden during fitting.
  • This random split evaluates missing ratings for this toy catalog; it does not simulate future interactions or guarantee training ratings for every user/movie.

Predict: Can a user appear in both tables without leaking their validation ratings?

train_ratings, valid_ratings = train_test_split(
    ratings, test_size=0.2, random_state=RANDOM_STATE
)


def make_utility(rating_rows):
    """Place observed ratings on the fixed user/movie axes."""
    return rating_rows.pivot(
        index="user_id", columns="movie_id", values="rating"
    ).reindex(index=users, columns=movies)


train_utility = make_utility(train_ratings)
valid_utility = make_utility(valid_ratings)
print(f"Train: {len(train_ratings)} ratings; validation: {len(valid_ratings)} ratings")
print(f"Both tables have shape {train_utility.shape}")
display(train_utility)
display(valid_utility)
Train: 16 ratings; validation: 5 ratings
Both tables have shape (4, 12)
movie_id A Beautiful Mind Bambi Cast Away Downfall Inception Jerry Maguire Lion King Malcolm x Man on Wire Roman Holidays The Social Dilemma Titanic
user_id
Eva NaN NaN NaN NaN 4.0 1.0 NaN NaN 5.0 NaN NaN 2.0
Jim NaN NaN NaN NaN NaN NaN NaN 4.0 5.0 NaN 5.0 2.0
Pat NaN 4.0 3.0 2.0 NaN 5.0 4.0 NaN NaN NaN NaN 3.0
Sam NaN NaN NaN 1.0 NaN NaN NaN NaN NaN 5.0 NaN NaN
movie_id A Beautiful Mind Bambi Cast Away Downfall Inception Jerry Maguire Lion King Malcolm x Man on Wire Roman Holidays The Social Dilemma Titanic
user_id
Eva NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 5.0 NaN
Jim NaN NaN NaN NaN NaN NaN 3.0 NaN NaN NaN NaN NaN
Pat 3.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
Sam NaN NaN NaN NaN NaN 4.0 4.0 NaN NaN NaN NaN NaN

Score only observed ratings

RMSE measures rating error in the original rating units; lower is better. Each score uses only the entries observed in its own split. All predictions must be finite so models are compared on the same held-out ratings.

def rmse(predictions, observed):
    """Score predictions only where the target rating is known."""
    aligned = predictions.loc[observed.index, observed.columns].to_numpy()
    if not np.isfinite(aligned).all():
        raise ValueError("Provide finite predictions for every user/movie pair.")
    actual = observed.to_numpy()
    mask = np.isfinite(actual)
    return np.sqrt(np.mean((aligned[mask] - actual[mask]) ** 2))


def evaluate(predictions, name):
    return {
        "Model": name,
        "Train RMSE": rmse(predictions, train_utility),
        "Validation RMSE": rmse(predictions, valid_utility),
    }


results = []

3. Compare simple baselines

Global-average baseline

Predict the mean training rating for every user/movie pair. This also gives us a fallback for users with no training ratings.

Predict: What information about individual taste does this baseline ignore?

global_mean = train_ratings["rating"].mean()
global_predictions = pd.DataFrame(global_mean, index=users, columns=movies)
results.append(evaluate(global_predictions, "Global average"))
display(pd.DataFrame(results).set_index("Model"))
Train RMSE Validation RMSE
Model
Global average 1.412832 0.831508

K-nearest neighbours imputation

  • Treat users as rows and movies as features: fill missing ratings using ratings from similar users.
  • Distances use the movies with ratings available in both rows, with an adjustment for missing coordinates.
  • With keep_empty_features=True, scikit-learn fills completely empty columns with zero; we replace those columns with the training global mean instead.
  • Observed training ratings are preserved by imputation. Training RMSE will be zero and does not measure generalization.

Predict: What makes neighbours unreliable when two users have few movies in common?

imputer = KNNImputer(n_neighbors=2, keep_empty_features=True)
knn_predictions = pd.DataFrame(
    imputer.fit_transform(train_utility), index=users, columns=movies
)
empty_movies = train_utility.columns[train_utility.isna().all()]
knn_predictions.loc[:, empty_movies] = global_mean
results.append(evaluate(knn_predictions, "KNN imputation"))
display(knn_predictions)
display(pd.DataFrame(results).set_index("Model"))
movie_id A Beautiful Mind Bambi Cast Away Downfall Inception Jerry Maguire Lion King Malcolm x Man on Wire Roman Holidays The Social Dilemma Titanic
user_id
Eva 3.4375 4.0 3.0 2.0 4.0 1.0 4.0 4.0 5.0 5.0 5.0 2.0
Jim 3.4375 4.0 3.0 2.0 4.0 3.0 4.0 4.0 5.0 5.0 5.0 2.0
Pat 3.4375 4.0 3.0 2.0 4.0 5.0 4.0 4.0 5.0 5.0 5.0 3.0
Sam 3.4375 4.0 3.0 1.0 4.0 5.0 4.0 4.0 5.0 5.0 5.0 3.0
Train RMSE Validation RMSE
Model
Global average 1.412832 0.831508
KNN imputation 0.000000 0.662028

Discuss: Why does zero training RMSE here provide no evidence that KNN will recommend well?

Reveal explanation

KNN imputation copies the supplied ratings and only predicts missing entries. The validation ratings were missing during fitting, so their RMSE is the useful comparison. Sparse overlap and users with no history remain challenges.

4. Use movie features to model one user’s taste

Content-based filtering uses known item features to predict a user’s preferences. Here, each movie has binary genre indicators, and each user gets a separate regression model.

  • Features X: genres of movies the user rated in training.
  • Target y: that user’s training ratings.
  • Prediction: apply their model to other movies’ features.

Predict: Can this approach score a new movie if its genre features are available?

movie_features = pd.read_csv(DATA_DIR / "toy_movie_feats.csv", index_col=0)
# Align features explicitly with the utility matrix's movie columns.
movie_features = movie_features.loc[movies]
movie_features
Action Romance Drama Comedy Children Documentary
movie_id
A Beautiful Mind 0 1 1 0 0 0
Bambi 0 0 1 0 1 0
Cast Away 0 1 1 0 0 0
Downfall 0 0 0 0 0 1
Inception 1 0 1 0 0 0
Jerry Maguire 0 1 1 1 0 0
Lion King 0 0 1 0 1 0
Malcolm x 0 0 0 0 0 1
Man on Wire 0 0 0 0 0 1
Roman Holidays 0 1 1 1 0 0
The Social Dilemma 0 0 0 0 0 1
Titanic 0 1 1 0 0 0

Build Pat’s training profile

Select Pat’s observed training ratings, then use movie labels to select the matching feature rows. Different users can have different numbers of training examples, but the genre columns stay the same.

def user_training_data(user):
    """Return aligned movie features and observed training ratings for one user."""
    y = train_utility.loc[user].dropna()
    X = movie_features.loc[y.index]
    return X, y


pat_X, pat_y = user_training_data("Pat")
display(pat_X.assign(rating=pat_y))
print(f"X shape: {pat_X.shape}; y shape: {pat_y.shape}")
Action Romance Drama Comedy Children Documentary rating
movie_id
Bambi 0 0 1 0 1 0 4.0
Cast Away 0 1 1 0 0 0 3.0
Downfall 0 0 0 0 0 1 2.0
Jerry Maguire 0 1 1 1 0 0 5.0
Lion King 0 0 1 0 1 0 4.0
Titanic 0 1 1 0 0 0 3.0
X shape: (6, 6); y shape: (6,)

Fit a Ridge model and inspect its coefficients

Ridge fits genre weights and an intercept. A positive coefficient increases the prediction when that genre is present, holding the other indicators fixed. With so few ratings and overlapping genres, these weights are only a rough illustration of taste.

def fit_user_model(user):
    """Fit a fresh Ridge model, or use the global baseline for an unseen user."""
    X, y = user_training_data(user)
    if y.empty:
        return None
    return Ridge(alpha=1.0).fit(X, y)


def predict_user(model, features):
    """Predict from item features, with a training-only cold-start fallback."""
    if model is None:
        return np.full(len(features), global_mean)
    return model.predict(features)


pat_model = fit_user_model("Pat")
if pat_model is not None:
    display(pd.Series(pat_model.coef_, index=movie_features.columns, name="Pat's coefficients"))
    print(f"Intercept: {pat_model.intercept_:.2f}")
Action         0.000000
Romance        0.027778
Drama          0.453704
Comedy         0.805556
Children       0.425926
Documentary   -0.453704
Name: Pat's coefficients, dtype: float64
Intercept: 2.91

Compare Pat and Eva on the same movies

Reuse the same fitting function for Eva, with her own training ratings. The model instances are separate.

Predict: Will identical movie features produce identical predictions for these two users?

eva_X, eva_y = user_training_data("Eva")
display(eva_X.assign(rating=eva_y))
eva_model = fit_user_model("Eva")

movies_to_compare = ["Roman Holidays", "Malcolm x"]
comparison = movie_features.loc[movies_to_compare].copy()
comparison["Pat's predicted rating"] = predict_user(pat_model, comparison[movie_features.columns])
comparison["Eva's predicted rating"] = predict_user(eva_model, comparison[movie_features.columns])
comparison
Action Romance Drama Comedy Children Documentary rating
movie_id
Inception 1 0 1 0 0 0 4.0
Jerry Maguire 0 1 1 1 0 0 1.0
Man on Wire 0 0 0 0 0 1 5.0
Titanic 0 1 1 0 0 0 2.0
Action Romance Drama Comedy Children Documentary Pat's predicted rating Eva's predicted rating
movie_id
Roman Holidays 0 1 1 1 0 0 4.194444 1.651163
Malcolm x 0 0 0 0 0 1 2.453704 4.418605

5. Predict for all users and compare validation error

Reuse Pat’s and Eva’s models and fit one model for each remaining user. Predict every user/movie pair, then score only the held-out entries.

Ridge predictions are not constrained to the rating scale. We leave them unclipped for this demonstration.

models = {"Pat": pat_model, "Eva": eva_model}
content_predictions = pd.DataFrame(index=users, columns=movies, dtype=float)
for user in users:
    if user not in models:
        models[user] = fit_user_model(user)
    content_predictions.loc[user] = predict_user(models[user], movie_features)

results.append(evaluate(content_predictions, "Content-based Ridge"))
display(content_predictions)
display(pd.DataFrame(results).set_index("Model").round(3))
movie_id A Beautiful Mind Bambi Cast Away Downfall Inception Jerry Maguire Lion King Malcolm x Man on Wire Roman Holidays The Social Dilemma Titanic
user_id
Eva 2.302326 3.255814 2.302326 4.418605 3.627907 1.651163 3.255814 4.418605 4.418605 1.651163 4.418605 2.302326
Jim 2.615385 3.230769 2.615385 4.461538 3.230769 2.615385 3.230769 4.461538 4.461538 2.615385 4.461538 2.615385
Pat 3.388889 3.787037 3.388889 2.453704 3.361111 4.194444 3.787037 2.453704 2.453704 4.194444 2.453704 3.388889
Sam 3.666667 3.000000 3.666667 1.666667 3.000000 4.333333 3.000000 1.666667 1.666667 4.333333 1.666667 3.666667
Train RMSE Validation RMSE
Model
Global average 1.413 0.832
KNN imputation 0.000 0.662
Content-based Ridge 0.518 0.575

Inspect: Which method has the lowest validation RMSE? This is a very small validation sample, so the ordering is not strong evidence about which method works best generally.

Reveal explanation: content and cold starts
  • A new movie can be scored using its genre features and an existing user’s model.
  • A new user has no ratings to fit their own model; here the fallback is the global training mean.
  • More useful features, more ratings, and regularization tuning may improve predictions. Any tuning must use training data and a suitable validation design.
  • Models based only on rating patterns are commonly called collaborative filtering; that approach is beyond this demo’s scope.

Turn predictions into recommendations

Sort a user’s predicted ratings and exclude movies they already rated. For this offline example, we exclude only training movies: validation movies must remain candidates because their ratings were hidden from the model. In a deployed system, exclude all items already seen at recommendation time.

def recommend(user, predictions, n=3):
    unseen_in_training = train_utility.loc[user].isna()
    return (
        predictions.loc[user, unseen_in_training]
        .sort_values(ascending=False)
        .head(n)
        .rename("Predicted rating")
        .to_frame()
    )


recommend("Pat", content_predictions)
Predicted rating
movie_id
Roman Holidays 4.194444
A Beautiful Mind 3.388889
Inception 3.361111

6. Check your interpretation

Select all statements that are true:

  • A. Training and validation utility matrices have the same shape in this demo.
  • B. Zero training RMSE from KNN imputation guarantees accurate recommendations.
  • C. Each user’s Ridge model uses the same genre columns but may use a different number of training rows.
  • D. A new movie with known genre features can be scored for a user with a fitted model.
  • E. A user with no validation ratings prevents us from computing RMSE over other users’ validation ratings.
Reveal answers

A, C, and D. KNN preserves observed entries, so its training error is not a generalization measure. A user with no validation ratings contributes no entries to the overall validation RMSE; their individual validation RMSE is undefined.

7. Beyond rating error

Discuss: Would you prefer three nearly identical recommendations with slightly higher predicted ratings, or a more varied list?

  • Ranking: RMSE measures rating accuracy; it does not directly measure whether the top suggestions are useful.
  • Diversity and freshness: include variety and opportunities to discover unfamiliar items.
  • Trust: explain why an item was suggested and respond to feedback.
  • Timing and persistence: a useful suggestion can become irrelevant after a purchase or repeated dismissal.
  • Impact: consider whether recommendations narrow exposure or reinforce harmful patterns.

Offline rating error is one piece of evaluation. The useful recommendation depends on the user’s goals and context.