---恢復內容開始---算法
算法步驟:ui
1.計算用戶類似度spa
def item_user(self,data): iu = dict() groups = data.groupby([1]) for item,group in groups: iu[item]=set(group.ix[:,0]) return iu
def user_item(self,data): ui = dict() groups = data.groupby([0]) for item,group in groups: ui[item]=set(group.ix[:,1]) return ui
3.遍歷列表iu上的每個商品,計算類似度code
def similarityMatrix(self): matrix=dict() N = dict() for item,users in self.iu.items(): add = 1.0/(1+math.log(len(users))) for v in users: if v not in N: N[v] = 1 else: N[v] += 1 for u in users: if v==u: continue if v not in matrix: matrix[v] = dict(); if u not in matrix[v]: matrix[v][u] = 0; matrix[v][u]+=add; for v in matrix.keys(): for u in matrix[v].keys(): matrix[v][u] /= math.sqrt(N[u]*N[v]) matrix[v] = sorted(matrix[v].items(),lambda x,y:cmp(x[1],y[1]),reverse=True); return matrix
4.推薦blog
def getRecommend(self,user): userItem=self.ui[user] simiusers=self.simiMatrix[user] rank = dict() for i in range(len(simiusers)): if i>=self.k: break for item in self.ui[simiusers[i][0]]: if item in userItem: continue if item not in rank: rank[item]=0 rank[item]+=simiusers[i][1]*1 rank = sorted(rank.items(),lambda x,y:cmp(x[1],y[1]),reverse=True)[0:self.k]; return [ele[0] for ele in rank]
---恢復內容結束---get