You are on page 1of 2

LAB # 8

COLLABORATIVE FILTERING
OBJECTIVE
Implementing collaborative filtering for a recommender system.

Lab Tasks:

For the given dataset, build a recommender system using item based collaborative filtering,
which recommends movies for a selected user. If we enter a user name into the recommender,
the recommender is supposed to return the list of recommended movies which have the highest
predicted ratings. Use Nearest Neighbors to calculate the distance between movies by using the
cosine similarity.
Code:
from sklearn.neighbors import NearestNeighbors
import numpy as np

# Hardcoded ratings data (user-item interactions)


# Replace this with your actual dataset
ratings = np.array([
[5, 4, 0, 0, 1],
[0, 5, 4, 0, 2],
[1, 0, 5, 4, 0],
[0, 0, 0, 5, 4],
[2, 0, 1, 0, 5]
])

# Convert the ratings data to a sparse matrix


sparse_ratings = np.array(ratings)
sparse_ratings_sparse = sparse_ratings.astype(bool).astype(int)

# Compute cosine similarity between movies


model = NearestNeighbors(metric='cosine', algorithm='brute')
model.fit(sparse_ratings_sparse)
def recommend_movies(user_id, num_recommendations=3):
# Get the ratings of the selected user
user_ratings = sparse_ratings[user_id - 1].reshape(1, -1)

# Find the nearest neighbors for the user's ratings


distances, indices = model.kneighbors(user_ratings, n_neighbors=num_recommendations+1)

# Exclude the user's own movie (first entry) from recommendations


indices = indices.squeeze()[1:]
distances = distances.squeeze()[1:]

# Calculate predicted ratings for recommended movies


predicted_ratings = 1 - distances # Convert cosine distances to ratings

return indices + 1, predicted_ratings # Adding 1 to match movie IDs (assuming movies are
indexed from 1)

# Example usage: Recommend movies for user with ID '3'


user_id = 3
recommended_movie_ids, predicted_ratings = recommend_movies(user_id)
print("Recommended Movie IDs:", recommended_movie_ids)
print("Predicted Ratings:", predicted_ratings)
Output:

You might also like