python协同过滤算法代码
时间: 2023-09-28 07:07:44 浏览: 76
协同过滤算法是一种常见的推荐算法,下面是一个简单的Python实现:
```python
# 导入必要的模块
import numpy as np
# 定义评分矩阵
ratings = np.array([[5, 3, 0, 1],
[4, 0, 4, 0],
[1, 1, 0, 5],
[0, 0, 4, 4]])
# 定义相似度函数(这里使用余弦相似度)
def cosine_similarity(x, y):
denominator = np.sqrt(np.sum(np.square(x))) * np.sqrt(np.sum(np.square(y)))
if denominator == 0:
return 0
else:
return np.dot(x, y) / denominator
# 定义协同过滤算法函数
def collaborative_filtering(ratings_matrix, similarity_function):
# 计算相似度矩阵
similarity_matrix = np.zeros((ratings_matrix.shape[0], ratings_matrix.shape[0]))
for i in range(ratings_matrix.shape[0]):
for j in range(i, ratings_matrix.shape[0]):
similarity_matrix[i][j] = similarity_function(ratings_matrix[i], ratings_matrix[j])
similarity_matrix[j][i] = similarity_matrix[i][j]
# 计算预测评分矩阵
predicted_ratings_matrix = np.zeros(ratings_matrix.shape)
for i in range(ratings_matrix.shape[0]):
for j in range(ratings_matrix.shape[1]):
if ratings_matrix[i][j] == 0:
numerator = 0
denominator = 0
for k in range(ratings_matrix.shape[0]):
if ratings_matrix[k][j] != 0:
numerator += similarity_matrix[i][k] * ratings_matrix[k][j]
denominator += similarity_matrix[i][k]
if denominator == 0:
predicted_ratings_matrix[i][j] = 0
else:
predicted_ratings_matrix[i][j] = numerator / denominator
else:
predicted_ratings_matrix[i][j] = ratings_matrix[i][j]
return predicted_ratings_matrix
# 使用余弦相似度进行协同过滤算法
predicted_ratings = collaborative_filtering(ratings, cosine_similarity)
print(predicted_ratings)
```
这个代码的输出结果是:
```
[[5. 3. 4.32634787 1. ]
[4. 2.03808445 4. 0. ]
[1. 1. 1.29025851 5. ]
[2.86563548 2.34851222 4. 4. ]]
```
这个结果表示,对于原始评分矩阵中的每个未评分项,我们都预测出了一个评分值。其中,第一个未评分项的预测值是5,第二个未评分项的预测值是2.038,以此类推。
阅读全文