我是 python 的新学习者,当我尝试重复指南中提供的示例时会出现一些问题。这个例子是关于推荐算法的。此示例试图实现一个项目列表,该列表存储对特定项目进行评分的用户。这是代码(python 2.7)
def UserSimilarity(train):
#build inverse table for item_users
item_users=dict()
for u,items in train.items():
for i in items.keys():
if i not in item_users:
item_users[i]=set()
item_users[i].add(u)
#calculate co-rated items between users
C=dict()
N=dict()
for i, users in item_users.items():
print i,users
#print N[u]
for u in users:
N[u]=N[u]+1
print N[u]
for v in users:
print C[u][v]
if u==v:
continue
C[u][v]=C[u][v]+1
#calculate finial similarity matrix W
W=dict()
for u, related_users in C.items():
for v, cuv in related_users.items():
W[u][v]=cuv/math.sqrt(N[u]*N[v])
return W
ps: 'train' 的数据格式是字典之类的{UserId1:{ItemId1:Ratings1,ItemId2,Rating2,...},...}
我遇到的问题是
Traceback (most recent call last):
File "D:\Users\Administrator\workspace\GroupLens\src\test3.py", line 82, in <module>
UserSimilarity(train_dic)
File "D:\Users\Administrator\workspace\GroupLens\src\test3.py", line 66, in UserSimilarity
N[u]=N[u]+1
KeyError: '3'
我不知道如何改进它,希望有人能帮助我!非常感谢!!