如何在Python中建立一個簡單的推薦系統
推薦系統是為了幫助人們發現和選擇他們可能感興趣的物品而設計的。 Python提供了豐富的函式庫和工具,可以幫助我們建立一個簡單但有效的推薦系統。本文將介紹如何使用Python建立一個基於使用者的協同過濾推薦系統,並提供具體的程式碼範例。
協同過濾是一種推薦系統的常見演算法,它基於使用者的行為歷史資料來推斷使用者之間的相似性,然後利用這些相似性來預測和推薦物品。我們將使用MovieLens資料集,它包含了一組使用者對電影的評分資料。首先,我們需要安裝所需的函式庫:
pip install pandas scikit-learn
接下來,我們將匯入所需的函式庫並載入MovieLens資料集:
import pandas as pd from sklearn.model_selection import train_test_split # 加载数据集 data = pd.read_csv('ratings.csv')
該資料集包含userId
、movieId
和rating
三列,分別表示使用者ID、電影ID和評分。接下來,我們將資料集拆分為訓練集和測試集:
train_data, test_data = train_test_split(data, test_size=0.2, random_state=42)
現在,我們可以建立推薦系統了。這裡我們將使用用戶間的餘弦相似度作為相似度度量指標。我們將創建兩個字典來儲存使用者和電影的相似度分數:
# 计算用户之间的相似度 def calculate_similarity(train_data): similarity = dict() for user in train_data['userId'].unique(): similarity[user] = dict() user_ratings = train_data[train_data['userId'] == user] for movie in user_ratings['movieId'].unique(): similarity[user][movie] = 1.0 return similarity # 计算用户之间的相似度得分 def calculate_similarity_score(train_data, similarity): for user1 in similarity.keys(): for user2 in similarity.keys(): if user1 != user2: user1_ratings = train_data[train_data['userId'] == user1] user2_ratings = train_data[train_data['userId'] == user2] num_ratings = 0 sum_of_squares = 0 for movie in user1_ratings['movieId'].unique(): if movie in user2_ratings['movieId'].unique(): num_ratings += 1 rating1 = user1_ratings[user1_ratings['movieId'] == movie]['rating'].values[0] rating2 = user2_ratings[user2_ratings['movieId'] == movie]['rating'].values[0] sum_of_squares += (rating1 - rating2) ** 2 similarity[user1][user2] = 1 / (1 + (sum_of_squares / num_ratings) ** 0.5) return similarity # 计算电影之间的相似度得分 def calculate_movie_similarity_score(train_data, similarity): movie_similarity = dict() for user in similarity.keys(): for movie in train_data[train_data['userId'] == user]['movieId'].unique(): if movie not in movie_similarity.keys(): movie_similarity[movie] = dict() for other_movie in train_data[train_data['userId'] == user]['movieId'].unique(): if movie != other_movie: movie_similarity[movie][other_movie] = similarity[user][other_user] return movie_similarity # 构建推荐系统 def build_recommendation_system(train_data, similarity, movie_similarity): recommendations = dict() for user in train_data['userId'].unique(): user_ratings = train_data[train_data['userId'] == user] recommendations[user] = dict() for movie in train_data['movieId'].unique(): if movie not in user_ratings['movieId'].unique(): rating = 0 num_movies = 0 for other_user in similarity[user].keys(): if movie in train_data[train_data['userId'] == other_user]['movieId'].unique(): rating += similarity[user][other_user] * train_data[(train_data['userId'] == other_user) & (train_data['movieId'] == movie)]['rating'].values[0] num_movies += 1 if num_movies > 0: recommendations[user][movie] = rating / num_movies return recommendations # 计算评价指标 def calculate_metrics(recommendations, test_data): num_users = 0 sum_of_squared_error = 0 for user in recommendations.keys(): if user in test_data['userId'].unique(): num_users += 1 for movie in recommendations[user].keys(): if movie in test_data[test_data['userId'] == user]['movieId'].unique(): predicted_rating = recommendations[user][movie] actual_rating = test_data[(test_data['userId'] == user) & (test_data['movieId'] == movie)]['rating'].values[0] sum_of_squared_error += (predicted_rating - actual_rating) ** 2 rmse = (sum_of_squared_error / num_users) ** 0.5 return rmse # 计算用户之间的相似度 similarity = calculate_similarity(train_data) # 计算用户之间的相似度得分 similarity = calculate_similarity_score(train_data, similarity) # 计算电影之间的相似度得分 movie_similarity = calculate_movie_similarity_score(train_data, similarity) # 构建推荐系统 recommendations = build_recommendation_system(train_data, similarity, movie_similarity) # 计算评价指标 rmse = calculate_metrics(recommendations, test_data)
最後,我們可以輸出推薦系統的結果和評價指標:
print(recommendations) print('RMSE:', rmse)
透過上述程式碼範例,我們在Python中成功建構了一個基於使用者的協同過濾推薦系統,並計算了其評估指標。當然,這只是一個簡單的範例,實際的推薦系統需要更複雜的演算法和更大規模的資料集來獲得更準確的建議結果。
總結一下,Python提供了強大的函式庫和工具來建立推薦系統,我們可以使用協同過濾演算法來推斷使用者之間的相似性,並根據這些相似性來進行推薦。希望本文能幫助讀者理解如何在Python中建立一個簡單但有效的推薦系統,並為進一步探索推薦系統的領域提供了一些想法。
以上是如何在Python中建立一個簡單的推薦系統的詳細內容。更多資訊請關注PHP中文網其他相關文章!