协同过滤 Python
时间: 2023-11-05 19:02:13 浏览: 44
协同过滤是一种基于用户行为的推荐算法,常用于个性化推荐系统中。在 Python 中,可以使用 Surprise 库来实现协同过滤算法。下面是一个简单的示例:
```python
from surprise import KNNBasic
from surprise import Dataset
from surprise import Reader
# 加载数据集
reader = Reader(line_format='user item rating', sep=',', rating_scale=(0, 5))
data = Dataset.load_from_file('ratings.csv', reader=reader)
# 定义算法模型
sim_options = {'name': 'cosine',
'user_based': True}
model = KNNBasic(sim_options=sim_options)
# 训练模型并预测
trainset = data.build_full_trainset()
model.fit(trainset)
user_id = '1'
item_id = '1'
rating = '5'
predicted_rating = model.predict(user_id, item_id, float(rating)).est
print(f"User {user_id} 对 Item {item_id} 的预测评分为:{predicted_rating}")
```
在上面的示例中,我们使用 Surprise 库加载了一个评分数据集,并定义了一个基于余弦相似度的 KNN 模型。接着,我们将数据集全部用于训练,并使用模型预测了用户 1 对物品 1 的评分。最后,我们将预测评分输出到控制台。
需要注意的是,在实际应用中,我们需要对数据集进行预处理,例如去除异常值、进行数据归一化等操作,以提高算法的准确性和鲁棒性。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)