基于用户的协同过滤算法代码
时间: 2023-10-20 20:20:10 浏览: 22
以下是基于用户的协同过滤算法的 Python 代码:
```python
import numpy as np
# 创建用户-物品矩阵,0表示未评分
ratings = np.array([
[4, 0, 3, 5, 0],
[0, 3, 0, 0, 2],
[0, 4, 2, 0, 0],
[5, 0, 0, 2, 3],
[0, 0, 4, 3, 0]
])
# 计算用户相似度
def user_similarity(ratings):
# 计算每个用户的评分平均值
mean_ratings = np.mean(ratings, axis=1)
# 用户-物品矩阵减去评分平均值
centered_ratings = ratings - mean_ratings[:, np.newaxis]
# 计算用户相似度
user_similarity = np.dot(centered_ratings, centered_ratings.T) / np.sqrt(np.sum(centered_ratings**2, axis=1)[:, np.newaxis] * np.sum(centered_ratings**2, axis=1))
return user_similarity
# 预测用户对物品的评分
def predict(ratings, user_similarity):
# 计算每个用户的评分平均值
mean_ratings = np.mean(ratings, axis=1)
# 用户-物品矩阵减去评分平均值
centered_ratings = ratings - mean_ratings[:, np.newaxis]
# 预测每个用户对每个物品的评分
pred_ratings = mean_ratings[:, np.newaxis] + np.dot(user_similarity, centered_ratings) / np.sum(np.abs(user_similarity), axis=1)[:, np.newaxis]
return pred_ratings
# 测试
user_sim = user_similarity(ratings)
print(user_sim)
pred_ratings = predict(ratings, user_sim)
print(pred_ratings)
```
其中,变量 `ratings` 表示用户-物品矩阵,变量 `user_sim` 表示用户相似度矩阵,变量 `pred_ratings` 表示预测的用户-物品评分矩阵。可以根据不同的需求调整输入输出格式和参数。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)