逐行分析下面的代码:import random import numpy as np import pandas as pd import math from operator import itemgetter data_path = './ml-latest-small/' data = pd.read_csv(data_path+'ratings.csv') data.head() data.pivot(index='userId', columns='newId', values='rating') trainSet, testSet = {}, {} trainSet_len, testSet_len = 0, 0 pivot = 0.75 for ele in data.itertuples(): user, new, rating = getattr(ele, 'userId'), getattr(ele, 'newId'), getattr(ele, 'rating') if random.random() < pivot: trainSet.setdefault(user, {}) trainSet[user][new] = rating trainSet_len += 1 else: testSet.setdefault(user, {}) testSet[user][new] = rating testSet_len += 1 print('Split trainingSet and testSet success!') print('TrainSet = %s' % trainSet_len) print('TestSet = %s' % testSet_len) new_popular = {} for user, news in trainSet.items(): for new in news: if new not in new_popular: new_popular[new] = 0 new_popular[new] += 1 new_count = len(new_popular) print('Total movie number = %d' % new_count) print('Build user co-rated news matrix ...') new_sim_matrix = {} for user, news in trainSet.items(): for m1 in news: for m2 in news: if m1 == m2: continue new_sim_matrix.setdefault(m1, {}) new_sim_matrix[m1].setdefault(m2, 0) new_sim_matrix[m1][m2] += 1 print('Build user co-rated movies matrix success!') print('Calculating news similarity matrix ...') for m1, related_news in new_sim_matrix.items(): for m2, count in related_news.items(): if new_popular[m1] == 0 or new_popular[m2] == 0: new_sim_matrix[m1][m2] = 0 else: new_sim_matrix[m1][m2] = count / math.sqrt(new_popular[m1] * new_popular[m2]) print('Calculate news similarity matrix success!') k = 20 n = 10 aim_user = 20 rank ={} watched_news = trainSet[aim_user] for new, rating in watched_news.items(): for related_new, w in sorted(new_sim_matrix[new].items(), key=itemgetter(1), reverse=True)[:k]: if related_new in watched_news: continue rank.setdefault(related_new, 0) rank[related_new] += w * float(rating) rec_news = sorted(rank.items(), key=itemgetter(1), reverse=True)[:n] rec_news
时间: 2024-04-28 15:21:34 浏览: 84
line_profiler:适用于Python的逐行分析
这段代码是一个电影推荐系统的实现。下面是对代码的逐行分析:
1. `import random import numpy as np import pandas as pd import math from operator import itemgetter`:导入需要使用的库
2. `data_path = './ml-latest-small/' data = pd.read_csv(data_path+'ratings.csv') data.head()`:读取电影评分数据,将其存储在一个DataFrame中,并输出前5行数据
3. `data.pivot(index='userId', columns='newId', values='rating')`:将数据按照用户ID和电影ID进行重塑,创建一个用户-电影评分的矩阵
4. `trainSet, testSet = {}, {} trainSet_len, testSet_len = 0, 0 pivot = 0.75`:初始化训练集和测试集,并设置训练集占比为0.75
5. `for ele in data.itertuples():`:遍历数据中的每一行
6. `user, new, rating = getattr(ele, 'userId'), getattr(ele, 'newId'), getattr(ele, 'rating')`:获取每一行数据中的用户ID、电影ID和评分
7. `if random.random() < pivot: trainSet.setdefault(user, {}) trainSet[user][new] = rating trainSet_len += 1 else: testSet.setdefault(user, {}) testSet[user][new] = rating testSet_len += 1`:根据训练集占比将数据划分为训练集和测试集,并统计训练集和测试集中的电影数量
8. `print('Split trainingSet and testSet success!') print('TrainSet = %s' % trainSet_len) print('TestSet = %s' % testSet_len)`:输出训练集和测试集的电影数量
9. `new_popular = {} for user, news in trainSet.items(): for new in news: if new not in new_popular: new_popular[new] = 0 new_popular[new] += 1`:统计每部电影的流行度(出现次数)
10. `new_count = len(new_popular) print('Total movie number = %d' % new_count)`:输出电影总数
11. `new_sim_matrix = {} for user, news in trainSet.items(): for m1 in news: for m2 in news: if m1 == m2: continue new_sim_matrix.setdefault(m1, {}) new_sim_matrix[m1].setdefault(m2, 0) new_sim_matrix[m1][m2] += 1`:构建用户-电影协同过滤矩阵,统计每对电影被多少个用户共同观看过
12. `print('Build user co-rated movies matrix success!')`:输出构建协同过滤矩阵成功信息
13. `for m1, related_news in new_sim_matrix.items(): for m2, count in related_news.items(): if new_popular[m1] == 0 or new_popular[m2] == 0: new_sim_matrix[m1][m2] = 0 else: new_sim_matrix[m1][m2] = count / math.sqrt(new_popular[m1] * new_popular[m2])`:计算电影之间的相似度,使用余弦相似度度量
14. `print('Calculate news similarity matrix success!')`:输出计算电影相似度成功信息
15. `k = 20 n = 10 aim_user = 20`:定义参数,包括推荐电影的数量和目标用户ID
16. `rank ={} watched_news = trainSet[aim_user] for new, rating in watched_news.items(): for related_new, w in sorted(new_sim_matrix[new].items(), key=itemgetter(1), reverse=True)[:k]: if related_new in watched_news: continue rank.setdefault(related_new, 0) rank[related_new] += w * float(rating) rec_news = sorted(rank.items(), key=itemgetter(1), reverse=True)[:n]`:为目标用户推荐电影,根据用户观看历史和电影相似度计算推荐度,并将推荐度排序输出前n个推荐电影。
阅读全文