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