编写代码设计一个根据已有电影数据的用户评分,对某用户进行最感兴趣电影的推荐。 (1)首先需要生成数据模拟(也可以使用真实数据)多人对多个电影的打分(1-6 分)。 默认10个用户,总共15部电影。每个用户至少评3部,最多10部电影。 (2)然后根据这些数据对某用户 A 进行推荐。推荐规则为:在已有数据中选择与该用户 A 的爱好最相似的用户 B,然后从最相似的用户 B 已看过但用户 A 还没看过的电影中选择用户 B 打分最高的电影推荐给用户 A。 相似度的计算标准为:1)两个用户共同打分过的电影越多,越相似;2)两个用户对共同打分的电影的打分越接近,越相似。 (3)使用tkinter实现GUI编程。
时间: 2024-02-18 22:04:54 浏览: 137
以下是 Python 代码实现,其中使用了 Pandas 库来处理数据,使用 tkinter 库来实现 GUI。
```python
import pandas as pd
import tkinter as tk
# 生成模拟数据
users = ['User' + str(i+1) for i in range(10)]
movies = ['Movie' + str(i+1) for i in range(15)]
ratings = pd.DataFrame(columns=['User', 'Movie', 'Rating'])
for user in users:
num_movies = 3 + int(7 * random.random()) # 每个用户至少评3部,最多评10部电影
user_movies = random.sample(movies, num_movies)
for movie in user_movies:
rating = random.randint(1, 6) # 评分范围为1-6
ratings = ratings.append({'User': user, 'Movie': movie, 'Rating': rating}, ignore_index=True)
# 计算用户之间的相似度
def similarity(user1, user2):
shared_movies = set(ratings[ratings['User'] == user1]['Movie']).intersection(set(ratings[ratings['User'] == user2]['Movie']))
if len(shared_movies) == 0:
return 0
else:
diff_sum = 0
for movie in shared_movies:
user1_rating = ratings[(ratings['User'] == user1) & (ratings['Movie'] == movie)]['Rating'].values[0]
user2_rating = ratings[(ratings['User'] == user2) & (ratings['Movie'] == movie)]['Rating'].values[0]
diff_sum += abs(user1_rating - user2_rating)
return 1 / (1 + diff_sum / len(shared_movies))
# 找到与目标用户最相似的用户
def find_similar_user(target_user):
similarities = [(user, similarity(target_user, user)) for user in users if user != target_user]
similarities = sorted(similarities, key=lambda x: x[1], reverse=True)
return similarities[0][0]
# 根据相似用户的评分推荐电影
def recommend_movie(target_user):
similar_user = find_similar_user(target_user)
target_movies = set(ratings[ratings['User'] == target_user]['Movie'])
similar_movies = set(ratings[ratings['User'] == similar_user]['Movie'])
recommend_movies = similar_movies - target_movies
if len(recommend_movies) == 0:
return 'No recommendation available.'
else:
recommend_ratings = [(movie, ratings[(ratings['User'] == similar_user) & (ratings['Movie'] == movie)]['Rating'].values[0]) for movie in recommend_movies]
recommend_ratings = sorted(recommend_ratings, key=lambda x: x[1], reverse=True)
return recommend_ratings[0][0]
# GUI实现
def recommend():
target_user = entry.get()
if target_user not in users:
result_label['text'] = 'Invalid user.'
else:
movie = recommend_movie(target_user)
result_label['text'] = 'Recommended movie for ' + target_user + ': ' + movie
window = tk.Tk()
window.title('Movie Recommender')
window.geometry('300x200')
label1 = tk.Label(window, text='Enter user name:')
label1.pack()
entry = tk.Entry(window)
entry.pack()
button = tk.Button(window, text='Recommend', command=recommend)
button.pack()
result_label = tk.Label(window, text='')
result_label.pack()
window.mainloop()
```
运行这段代码后,会弹出一个 GUI 窗口,用户可在其中输入目标用户的用户名,点击“Recommend”按钮后程序会计算出推荐电影并在窗口中显示结果。
阅读全文