pythonintermediate30 minutes

Build a Movie Recommendation Engine Based on User Ratings

Create a Python mini-project that recommends movies to a user based on their past ratings and similarity to other users' ratings. Implement basic collaborative filtering logic without external libraries.

Challenge prompt

You are given a dataset containing user ratings for various movies. Each entry consists of a user ID, a movie ID, and a rating from 1 to 5. Your task is to build a function that, given a target user ID, recommends the top 3 movies that the user hasn't rated yet, based on movie ratings similarity from other users. Use user-based collaborative filtering: find users similar to the target user by comparing their ratings and aggregate ratings for movies the target user hasn't seen to generate recommendations.

Guidance

  • Create a user-movie ratings matrix from the input list for easier comparison.
  • Calculate similarity between users using a metric like Pearson correlation or cosine similarity based on their common rated movies.
  • Aggregate ratings of similar users to recommend movies not rated by the target user.
  • Return the top 3 movies sorted by predicted rating.

Hints

  • Focus on users who have rated several of the same movies as the target user for better similarity estimates.
  • Normalize ratings if you choose to use Pearson correlation to account for user rating bias.
  • You can handle ties by sorting movies with the same recommendation score by movie ID.

Starter code

def recommend_movies(ratings, target_user_id):
    # ratings: List of tuples (user_id, movie_id, rating)
    # TODO: Implement the recommendation engine
    pass

# Example input:
rating_data = [
    (1, 101, 5), (1, 102, 3), (1, 103, 4),
    (2, 101, 4), (2, 102, 5), (2, 104, 2),
    (3, 101, 2), (3, 103, 5), (3, 104, 4),
    (4, 102, 5), (4, 103, 3), (4, 104, 5)
]

print(recommend_movies(rating_data, 1))

Expected output

[104, 105, 106] # Example output assuming 104 is recommended top, others can vary

Core concepts

collaborative filteringmatrix operationssimilarity metricsdata structures

Challenge a Friend

Send this duel to someone else and see if they can solve it.