User-based collaborative filtering algorithm:
- Find a user collection similar to the target user
- Find items in this collection that the user likes but the target user has not heard
#encoding: Utf-8from Similarity import personfrom Sort import select_sortfile=open (' User_bookmark ', ' R ') Filew=open (' User_bookrecommend ', ' W ') #加载训练集trainSet ={}while true:line=file.readline (). Strip () if not line:break Userid,itemi D=line.split ("::") Trainset.setdefault (userid,[]) trainset[userid].append (itemId) # Calculates the similarity, ordering, of each user and all other users, Get the top n users with the highest similarity, # in calculating the similarity of each user * Item preference value (set the preference value to 1 if there is no rating here) for V in Trainset.keys (): v2u={} k={} for u in Trainset.keys ( ): If U!=v:sim=person (Trainset[v],trainset[u]) V2u.setdefault (U,sim) Keys,values=select_sort (v 2u) S=v for I in range (len (values) -3,len (values)): s=s+ "::" +keys[i]+ "" +str (Values[i]) K.setdefault (keys [I],values[i]) rank={} rki=1 Interacted_items=trainset[v] for k,simk in K.items (): For I in Trainset[k] : If I in Interacted_items:continue rvi=rki*simk rank.setdefault (I,rvi) S1=v _keys,_values=select_sort (rank) For I in range (rank) -6,len: #s1 =s1+_keys[i]+ "" +str (_values[i]) + "::" s1=s1+ "::" +_keys[i] P rint S1 filew.write (s1+ ' \ n ') from math import sqrtdef person (item_a,item_b): If Len (item_a) ==0 or Len (item_b) ==0: return 0; Else:sum=0 for I in range (len (item_a)): for J in Range (Len (item_b)): if Item_a[i] ==ITEM_B[J]: sum=sum+1 if Sum==0:return 0 else:sim=sum/sqrt (len (i Tem_a) *len (Item_b)) return sim
User-based collaborative filtering algorithm (USERCF)