Filling Missing Ratings: Item Means, Not User Means

Recommender SystemsMedium+15 XP+15

Filling Missing Ratings: Item Means, Not User Means

A ratings matrix is mostly holes — a typical user has rated a tiny fraction of the catalogue. Many algorithms (plain matrix multiplication, PCA, a dense neural layer) can't run on holes at all, so the simplest first move is to fill each one with that item's average rating.

Task: write impute_ratings(matrix) returning the filled matrix, every filled value rounded to 4 decimal places.

  • matrix is a list of rows, one per user, one column per item. None means unrated.
  • Fill each None with the mean of its column — the average rating that item received from the users who did rate it.
  • If a column has no ratings at all, fall back to the global mean across every known rating in the matrix. An item nobody has rated has no average of its own, and leaving the hole or writing zero would both be worse than saying "assume it's typical".
  • Values already present stay exactly as they are.
  • At least one rating exists somewhere, so the global mean always exists.

Filling by item rather than by user is the deliberate choice here. An item's mean captures something real and shared — a universally loved film has a high average — while a user's mean says only how generous they are, which carries no information about the specific item you're guessing.

What to be wary of: these filled values are invented, and nothing downstream can tell them apart from real ratings. The matrix now looks dense and confident when it isn't, so a model trained on it will be most certain exactly where it knows least. That's why serious systems prefer methods that work on the observed entries only — matrix factorisation trained on the known ratings alone, rather than on a filled-in matrix.

weightrows that arrive later

Two rows have no weight. A model cannot take an empty cell, so something has to go there.

Examples

matrix = [[5, None], [3, 2]]
returns [[5, 2.0], [3, 2]]
matrix = [[None, 4], [2, None]]
returns [[2.0, 4], [2, 4.0]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run