Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Recommendation Engine

Build collaborative filtering from scratch — the algorithm behind 'customers also bought' and your Netflix row — using cosine similarity to find your taste-twins and recommend what they loved that you haven't seen.

Advanced 4 steps 150 XP ~55 min

How it works in the real world

Collaborative filtering makes a bet: people who agreed in the past will agree again. No genres, no tags, just ratings.

  1. Represent — every user is a sparse vector of item ratings.
  2. Compare — cosine similarity measures the angle between two users, so it captures taste rather than how generously someone rates.
  3. Neighbour — rank everyone by similarity to the target user.
  4. Recommend — score unseen items by each neighbour's rating weighted by similarity.

This is the algorithm that won early recommender competitions, and it still underpins production systems. You'll implement it with nothing but math.

Build progress0 / 4 steps
1

Explore the ratings matrix

Print how many users and distinct items exist, then one line per user (alphabetical) with how many items they rated and their average to two decimals.

Blank · autosaved
PYstep_1.py
Run your code to check this step…
2

Cosine similarity

Write cosine(a, b): dot product over shared items, divided by the product of both vectors' magnitudes. Print ana's similarity to each other user, 3 decimals.

Blank · autosaved
PYstep_2.py
Run your code to check this step…
3

Rank the neighbours

Sort every other user by similarity to ana, most similar first, breaking ties by name. Print the ranked list.

Blank · autosaved
PYstep_3.py
Run your code to check this step…
4

Recommend what to watch

For every item ana hasn't rated, sum similarity * neighbour_rating across all positively-similar users. Print the recommendations, best first, 3 decimals.

Blank · autosaved
PYstep_4.py
Run your code to check this step…
Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path