Slopone recommendation algorithm

Source: Internet
Author: User




In the open source framework taste has slopone Java implementation, the effect is good. Using movielens data, the code is as follows


Code

#coding: Utf-8import reimport math# reads data and generates Matrix Def Getmatrix (): Mat = {}f = open ("U.data", "R") for line in f:list = map (int, l  Ine.strip ("\ n"). Split ("\ T")) if list[0] in mat:mat[list[0] [list[1]] = list[2]else:mat[List[0]] = {List[1]: list[2] }f.close () Return mat# calculates the average def getavg (usr) for a user: res = 0.0for I in Usr:res + = Usr[i]return res/len (usr) #预测分数, returns the user U in the matrix mat SR to item rating def Getslopone (Mat, User, item): #用户user的所有item的列表list = Mat[user] #分子mole = 0.0# Denominator demo = 0.0# for each item, Calculates the difference between it and the item item, eventually calculating the scorefor it in list:diff_sum = 0.0user_num = 0for us in mat:us_it = Mat[us] #如果该user同时评价过这两个item , then adopt his rating if item in Us_it and it in us_it:diff_sum + = Us_it[item]-Us_it[it]user_num + = # If Item has been evaluated if USER_NUM:DIFF_AVG = Diff_sum/user_nummole + = (List[it] + diff_avg) * User_numdemo + = user_num# If no one has evaluated it, take this person's average if user_num = 0:return ge Tavg (list) #否则返回最终的scorereturn Mole/demodef main (): Mat = Getmatrix () RF = open ("U.data", "r") WF = open ("O.data", "W") for L ine in rf:list = map (int, Line.strip("\ n"). Split ("\ T")) score = Getslopone (Mat, list[0], list[1]) output = str (list[0]) + "\ T" + str (list[1]) + "\ T" + str (list[ 2]) + "\ T" + str (score) + "\ n" wf.write (output) rf.close () wf.close () if __name__ = = "__main__": Main ()



Slopone recommendation algorithm

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.