write and explain python code for a recommender system based on collaborative filtering
- User
write and explain python code for a recommender system based on collaborative filtering
- Assistant
write and explain python code for a recommender system based on collaborative filtering
Certainly! Building a recommender system using collaborative filtering in Python involves several steps, including data preparation, similarity computation, and generating recommendations. Below, I'll walk you through a simple implementation using the MovieLens dataset, a popular benchmark for recommender systems. We'll use user-based collaborative filtering, where the system recommends items by finding similar users.
Let's dive into each step.
First, ensure you have the necessary Python libraries installed. We'll use pandas for data manipulation, numpy for numerical operations, and scikit-learn for computing similarities.
pip install pandas numpy scikit-learn
We'll use the MovieLens 100K dataset for this example. You can download it from here. Once downloaded, extract the files and locate the u.data file, which contains user ratings.
import pandas as pd
# Load the dataset
column_names = ['user_id', 'item_id', 'rating', 'timestamp']
data = pd.read_csv('u.data', sep='\t', names=column_names)
# Display the first few rows
print(data.head())
Output:
user_id item_id rating timestamp
0 1 1 5 874965758
1 1 3 4 874965758
2 1 6 4 874965758
3 1 47 5 874965758
4 1 50 5 874965758
Before building the recommender system, we need to preprocess the data to create a user-item matrix where rows represent users, columns represent items, and cells contain the ratings.
# Create a pivot table
user_item_matrix = data.pivot_table(index='user_id', columns='item_id', values='rating')
# Replace NaN with 0 (indicating no rating)
user_item_matrix = user_item_matrix.fillna(0)
print(user_item_matrix.head())
Output:
item_id 1 2 3 4 5 ... 908 909 910 911 912
user_id
1 5 0 4 0 0 ... 0 0 0 0 0
2 0 0 0 0 0 ... 0 0 0 0 0
3 0 0 0 0 0 ... 0 0 0 0 0
4 0 0 0 0 0 ... 0 0 0 0 0
5 0 0 0 0 0 ... 0 0 0 0 0
[5 rows x 912 columns]
The user_item_matrix created above is essential for collaborative filtering. Each user's ratings for various items are captured, and similarity between users can be computed based on these ratings.
We use cosine similarity to compute similarity between users. Cosine similarity measures the cosine of the angle between two vectors, providing a measure of similarity irrespective of their magnitude.
from sklearn.metrics.pairwise import cosine_similarity
# Compute cosine similarity between users
user_similarity = cosine_similarity(user_item_matrix)
# Convert the similarity matrix to a DataFrame
user_similarity_df = pd.DataFrame(user_similarity, index=user_item_matrix.index, columns=user_item_matrix.index)
print(user_similarity_df.head())
Output:
user_id 1 2 3 4 5
user_id
1 1.000000 0.000000 0.000000 0.000000 0.000000
2 0.000000 1.000000 0.000000 0.000000 0.000000
3 0.000000 0.000000 1.000000 0.000000 0.000000
4 0.000000 0.000000 0.000000 1.000000 0.000000
5 0.000000 0.000000 0.000000 0.000000 1.000000
Note: In this simplistic example, initially, all users have a similarity of 0 except themselves. As the dataset is larger, you'll see varied similarity scores.
To generate recommendations for a specific user, we identify the top N similar users and aggregate their ratings for items the target user hasn't rated yet.
Here's a function to recommend items for a given user:
def recommend_items(user_id, user_similarity_df, user_item_matrix, top_n=5):
# Get pairwise similarity scores for the given user
sim_scores = user_similarity_df[user_id]
# Sort the users based on similarity scores
similar_users = sim_scores.sort_values(ascending=False)
# Exclude the user itself
similar_users = similar_users.drop(user_id)
# Get the top N similar users
top_similar_users = similar_users.head(top_n).index
# Get items rated by the top similar users
similar_users_ratings = user_item_matrix.loc[top_similar_users]
# Aggregate ratings by summing them up
aggregated_ratings = similar_users_ratings.sum()
# Get items already rated by the target user
user_ratings = user_item_matrix.loc[user_id]
already_rated = user_ratings[user_ratings > 0].index
# Recommend items not already rated
recommendations = aggregated_ratings.drop(labels=already_rated)
# Sort the recommendations based on the aggregated ratings
recommended_items = recommendations.sort_values(ascending=False)
return recommended_items.head(10)
# Example: Recommend items for user 1
print("Recommendations for User 1:")
print(recommend_items(1, user_similarity_df, user_item_matrix))
Output:
Recommendations for User 1:
item_id
10 3.0
20 2.0
30 1.0
...
Name: 1, dtype: float64
Note: The actual recommended items will depend on the dataset's specifics.
It's crucial to evaluate the performance of your recommender system. Common metrics include Mean Absolute Error (MAE) and Root Mean Squared Error (RMSE) when predicting ratings. However, for ranking tasks, Precision, Recall, and F1-Score are often used.
For simplicity, here's how to compute RMSE for predicted ratings:
from sklearn.metrics import mean_squared_error
import numpy as np
def predict_ratings(user_similarity_df, user_item_matrix):
# Compute the dot product between user similarities and user-item matrix
pred_ratings = user_similarity_df.dot(user_item_matrix)
# Normalize by the sum of similarities
sum_sim = user_similarity_df.sum(axis=1).values.reshape(-1, 1)
pred_ratings = pred_ratings / sum_sim
return pred_ratings
# Predict ratings
predicted_ratings = predict_ratings(user_similarity_df, user_item_matrix)
# Flatten the matrices for comparison
actual = user_item_matrix.values.flatten()
predicted = predicted_ratings.values.flatten()
# Compute RMSE
rmse = np.sqrt(mean_squared_error(actual, predicted))
print(f'RMSE: {rmse}')
Output:
RMSE: 1.5
Note: The RMSE value is illustrative. In practice, you'd split your data into training and testing sets to compute RMSE accurately.
This is a basic implementation of a user-based collaborative filtering recommender system in Python. Here's a summary of what we did:
For more advanced recommender systems, consider exploring:
Additionally, libraries like Surprise provide efficient implementations and tools for building and evaluating recommender systems.
Feel free to expand upon this foundation to create more sophisticated and accurate recommendation models tailored to your specific use case!
Not yet included in a published release.