如何在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中構建一個簡單的推薦系統的詳細內容,更多請關注www.92cms.cn其它相關文章!