Recommenders: People Like You Liked This

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

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

  1. Four films.
  2. Ratings out of 5. You have not seen Old Town (0).
  3. The other viewers to compare with.
  4. One distance per viewer.
  5. name is created with the value 'ana'.
  6. Ana vs you, on the three films you have both seen: |5 − 4| + |1 − 2| + |4 − 5| = 3. Very similar taste.
  7. name changes from 'ana' to 'raj'.
  8. Raj vs you: 4 + 4 + 3 = 11. Very different taste.
  9. Python moves to the next item of the loop: for name in others.
  10. The closest viewer: Ana.
  11. The film you have not seen: Old Town.
  12. 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

Best practices

Key takeaways

Check yourself

You rated [5, 2]. A rated [4, 2], B rated [1, 5]. Who is closer?

Answer: A (distance 1). |5 − 4| + |2 − 2| = 1 versus |5 − 1| + |2 − 5| = 7.

Why skip Old Town when comparing tastes?

Answer: You have not rated it, so there is nothing to compare. Only films both people rated say anything about how alike they are.

·

More in Everyday AI