User-based collaborative filtering algorithm (USERCF)

Source: Internet
Author: User

User-based collaborative filtering algorithm:

    1. Find a user collection similar to the target user
    2. 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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.