I’m a new learner about python and there are some problems when I try to repeat the example provided in a guide book. This example is about recommendation algorithm. This example is trying to implement an item list which stores the users having rated the particular item.
this is the codes(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: the data format of ‘train’ is a dictionary and like {UserId1:{ItemId1:Ratings1,ItemId2,Rating2,...},...}
The problem I met is that
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'
I don’t know how to improve it and hope someone would help me!
Thanks a lot!!
The main issue is that you are defining a new dictionary (
N = dict()), and then iterating through yourusers, trying to create a dictionary key based on a given user. That part is fine, but the issue arises when you do this:Assigning a value to the dictionary is fine, but look at the right side – you are trying to assign to
N[u]the value ofN[u] + 1, whenN[u]doesn’t exist yet (hence the error). I’m not 100% sure what the overall goal is (so this may be misguided), but if your aim is to increment a number based on how many times a user occurs, you could use adefaultdict, which is created with a type as an argument (here anint). This means that if the key is not found (as in your error above), the default value is based on the type you declared (here0):Alternatively, you could use a normal dictionary but with the
getmethod, which returns a value if it is found but returns a default if not (a default that you can specify yourself):