给出协同过滤算法的python代码
时间: 2023-11-12 18:10:36 浏览: 60
协同过滤算法 python脚本
Sure! Here's an example code for collaborative filtering recommendation algorithm in Python:
```python
import numpy as np
import pandas as pd
def collaborative_filtering(data, user_similarity, k):
num_users, num_items = data.shape
predictions = np.zeros((num_users, num_items))
for i in range(num_users):
for j in range(num_items):
if data[i, j] == 0:
similarities = np.argsort(user_similarity[i])[::-1][:k]
predictions[i, j] = np.dot(user_similarity[i][similarities], data[similarities, j]) / np.sum(user_similarity[i][similarities])
return predictions
# Example usage with MovieLens dataset
ratings_data = pd.read_csv("ratings.csv")
movies_data = pd.read_csv("movies.csv")
user_movie_ratings = pd.pivot_table(ratings_data, values='rating', index='userId', columns='movieId')
user_movie_ratings = user_movie_ratings.fillna(0)
# Calculate user similarities using cosine similarity metric
from sklearn.metrics.pairwise import cosine_similarity
user_similarity = cosine_similarity(user_movie_ratings)
# Make recommendations for user with ID 1
user_id = 1
recommendations = collaborative_filtering(user_movie_ratings.to_numpy(), user_similarity, 10)[user_id]
top_recommendations_idx = np.argsort(recommendations)[::-1][:10]
# Get recommended movie titles
top_recommendations = movies_data[movies_data['movieId'].isin(top_recommendations_idx)]['title'].values
print(f"Top recommendations for user {user_id}:")
for movie in top_recommendations:
print(movie)
```
Hope that helps! Let me know if you have any other questions.
阅读全文