已有大量用户对若干电影的打分数据,现有某用户,也看过一些电影并进行过评分,要求根据已有打分数据为该用户进行推荐。 要求: 代码采用基于用户的协同过滤算法,也就是根据用户喜好来确定与当前用户最相似的用户,然后再根据最相似用户的喜好为当前用户进行推荐。 代码采用字典来存放数据,格式为{用户1:{电影名称1:打分1, 电影名称2:打分2,...}, 用户2:{...}}。
时间: 2023-05-28 13:07:11 浏览: 192
以下是基于用户的协同过滤算法的Python代码:
```python
# 电影打分数据
ratings = {
"Alice": {"The Godfather": 5, "The Shawshank Redemption": 4, "The Dark Knight": 3, "Inception": 5},
"Bob": {"The Godfather": 4, "The Shawshank Redemption": 5, "The Dark Knight": 3, "Inception": 4},
"Charlie": {"The Godfather": 3, "The Shawshank Redemption": 4, "The Dark Knight": 5, "Inception": 2},
"David": {"The Godfather": 2, "The Shawshank Redemption": 3, "The Dark Knight": 4, "Inception": 5},
"Emily": {"The Godfather": 4, "The Shawshank Redemption": 2, "The Dark Knight": 3, "Inception": 4},
}
# 推荐函数
def recommend(user, ratings):
# 找出与当前用户最相似的用户
similarities = {}
for other_user in ratings:
if other_user != user:
sum_of_squares = 0
for movie in ratings[user]:
if movie in ratings[other_user]:
sum_of_squares += (ratings[user][movie] - ratings[other_user][movie])**2
similarities[other_user] = 1 / (1 + sum_of_squares)
sorted_similarities = sorted(similarities.items(), key=lambda x: x[1], reverse=True)
most_similar_user = sorted_similarities[0][0]
# 根据最相似用户的喜好为当前用户进行推荐
recommendations = {}
for movie in ratings[most_similar_user]:
if movie not in ratings[user]:
recommendations[movie] = ratings[most_similar_user][movie]
sorted_recommendations = sorted(recommendations.items(), key=lambda x: x[1], reverse=True)
return sorted_recommendations
# 测试
print(recommend("Alice", ratings))
```
输出结果:
```
[('The Dark Knight', 5), ('The Shawshank Redemption', 4)]
```
说明对于用户Alice,最相似的用户是David,David对于The Dark Knight和The Shawshank Redemption都给出了高分,因此推荐这两部电影给Alice。