已有大量用户对若干电影的打分数据,现有某 用户,也看过一些电影并进行过评分,要求根 据已有打分数据为该用户进行推荐。 要求: 代码采用基于用户的协同过滤算法,也就是根 据用户喜好来确定与当前用户最相似的用户 然后再根据最相似用户的喜好为当前用户进行 推荐。 代码采用字典来存放数据,格式为(用户1:(电 影名称1:打分1,电影名称2:打分2....用户2:
时间: 2023-05-27 20:07:39 浏览: 155
代码如下:
ratings = {'User1': {'Movie1': 3, 'Movie2': 4, 'Movie3': 2, 'Movie4': 5},
'User2': {'Movie1': 4, 'Movie2': 3, 'Movie3': 5, 'Movie4': 2},
'User3': {'Movie1': 2, 'Movie2': 5, 'Movie3': 3, 'Movie4': 4},
'User4': {'Movie1': 5, 'Movie2': 2, 'Movie3': 4, 'Movie4': 3}}
def find_similar_users(user, ratings):
similarities = {}
for other_user in ratings:
if other_user != user:
similarity = 0
for movie in ratings[user]:
if movie in ratings[other_user]:
similarity += abs(ratings[user][movie] - ratings[other_user][movie])
similarities[other_user] = similarity
return sorted(similarities.items(), key=lambda x: x[1])
def recommend_movies(user, ratings):
similar_users = find_similar_users(user, ratings)
recommended_movies = {}
for movie in ratings[user]:
for other_user, similarity in similar_users:
if movie not in ratings[other_user]:
if movie not in recommended_movies:
recommended_movies[movie] = similarity
else:
recommended_movies[movie] += similarity
return sorted(recommended_movies.items(), key=lambda x: x[1], reverse=True)
user = 'User1'
recommended_movies = recommend_movies(user, ratings)
print(f"Recommended movies for {user}:")
for movie, similarity in recommended_movies:
print(f"{movie} ({similarity})")
阅读全文