Skip to content

Instantly share code, notes, and snippets.

@yvki
Created April 18, 2024 07:49
Show Gist options
  • Save yvki/72b5ec06a1d428709c7240c16be571b5 to your computer and use it in GitHub Desktop.
Save yvki/72b5ec06a1d428709c7240c16be571b5 to your computer and use it in GitHub Desktop.
Sample Movie πŸ“½οΈ Recommendation System πŸ”’ using Cosine Similarity βš™οΈ
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
# Sample ratings matrix for 5 movies by 5 users
ratings = np.array([
# [Movie 1, Movie 2, Movie 3, Movie 4, Movie 5]
[5, 3, 4, 4, 0], # User 1
[3, 1, 2, 3, 3], # User 2
[4, 3, 4, 3, 5], # User 3
[3, 3, 1, 5, 4], # User 4
[1, 5, 5, 2, 1] # User 5
])
# Calculate cosine similarity between users
similarities = cosine_similarity(ratings)
# Rating prediction function for a user and item
def predict_rating(user_index, item_index):
# Initialize variables for prediction
weighted_sum = 0
similarity_sum = 0
# Iterate over all users
for i in range(len(ratings)):
# Exclude the user itself and users who have not rated the item
if i!= user_index and ratings[i][item_index]!= 0:
# Find the set of items rated by both users
common_items = np.nonzero(ratings[user_index] * ratings[i])[0]
# Adjust similarity and calculate weighted sum for common items
if len(common_items) > 0:
adjusted_similarity = similarities[user_index][i]
weighted_sum += ratings[i][item_index] * adjusted_similarity
similarity_sum += adjusted_similarity
# Predict the rating using weighted average
if similarity_sum!= 0:
predicted_rating = weighted_sum / similarity_sum
else:
predicted_rating = 0
return predicted_rating
# Predict rating in sample matrix for user index 0, item index 4
predicted_rating = predict_rating(0, 4)
print("Predicted rating for User 1 on Movie 1:", round(predicted_rating,2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment