Streaming and shopping sites suggest things by finding people whose tastes match yours. Compare ratings, find the closest viewer, and recommend what they loved.
AI · beginner · 7 min · 12 steps · free
What you'll learn
Compare two people's ratings with a distance
Find the most similar person
Recommend something they rated highly that you have not seen
recommender.py
# Recommend a film: find the viewer whose ratings look most like yours, and suggest what they loved.
films = ["Space Race", "Love Boat", "Robot Wars", "Old Town"]
ratings = {"you": [5, 1, 4, 0], "ana": [4, 2, 5, 5], "raj": [1, 5, 1, 4]} # 0 = not seen
others = ["ana", "raj"]
distances = []
for name in others:
distances.append(sum([abs(a - b) for a, b in zip(ratings["you"][:3], ratings[name][:3])]))
closest = others[distances.index(min(distances))]
unseen = films[ratings["you"].index(0)]
print("try", unseen, "- rated", ratings[closest][films.index(unseen)], "by", closest)
Step by step
Four films.
Ratings out of 5. You have not seen Old Town (0).
The other viewers to compare with.
One distance per viewer.
name is created with the value 'ana'.
Ana vs you, on the three films you have both seen: |5 − 4| + |1 − 2| + |4 − 5| = 3. Very similar taste.
name changes from 'ana' to 'raj'.
Raj vs you: 4 + 4 + 3 = 11. Very different taste.
Python moves to the next item of the loop: for name in others.
The closest viewer: Ana.
The film you have not seen: Old Town.
Ana gave Old Town a 5, so it is recommended to you. Real recommenders compare millions of people, often by turning people and items into embedding vectors, as in the AI course.
Common mistakes
Comparing on items one person has not rated
Recommending only what everyone likes, so suggestions are never personal
Best practices
Compare only items both people have rated
Key takeaways
Collaborative filtering recommends from patterns in ratings.
Find people whose past ratings are close to yours.
Suggest what they liked that you have not seen.
Large systems use embeddings of users and items.
Check yourself
You rated [5, 2]. A rated [4, 2], B rated [1, 5]. Who is closer?