#!/usr/bin/env python
import random
”’
items => {’12’:’PHP’,’1203′:’Storm’,’123′:’Ubuntu’}
items_pool => [12,32,121,324,532,123,53,1203,429,2932]
user_items => {‘1010’:[12,1203,123,429]}
”’
def RandomSelectNagativeSample(items):
ret = dict()
for i in items.keys():
ret[i] = 1
n = 0
for i in range(0,len(items)*3):
item = items_pool[random.randint(0,len(items_pool)-1)]
if item in ret:
continue
ret[item] = 0
n += 1
if n > len(items):
break
return ret
def InitModel(user_items,F):
P = dict()
Q = dict()
for u in user_items.keys():
if u not in P:
P[u] = {}
for f in range(0,F):
P[u][f] = 1
items = user_items.values()
itemLen = len(items[0])
i = 0
while i< itemLen:
ii = items[0][i]
if ii not in Q:
Q[ii] = {}
for f in range(0,F):
Q[ii][f] = 1
i += 1
return [P,Q]
def LatentFactorModel(user_items,F,N,alpha,lambda1):
[P,Q] = InitModel(user_items,F)
for setup in range(0,N):
for user,items in user_items.items():
samples = RandomSelectNagativeSample(items)
for item,rui in samples.items():
eui = rui – Predict(user,item)
for f in range(0,F):
P[user][f] += alpha * (eui * Q[item][f] – lambda1 * P[user][f])
Q[item][f] += alpha * (eui * P[user][f] – lambda1 * Q[item][f])
alpha *= 0.9
return [P,Q]
def Recommend(user,P,Q):
rank = dict()
for f,puf in P[user].items():
for i,pfi in Q[f].items():
if i not in rank:
rank[i] += puf * qfi
return rank
def PersonalRank(G,alpha,root,maxsetup):
rank = dict()
#rank = {x:0 for x in G.keys()}
rank = rank.fromkeys(G.keys(),0)
rank[root] = 1
for k in range(maxsetup):
tmp = dict()
#tmp = {x:0 for x in G.keys()}
tmp = tmp.fromkeys(G.keys(),0)
for i,ri in G.items():
for j,wij in ri.items():
if j not in tmp:
tmp[j] = 0
tmp[j] += alpha * rank[i]/(1.0*len(ri))
if j == root:
tmp[j] += 1 – alpha
rank = tmp
print ‘iter:’ + str(k) + “\t”,
for key,value in rank.items():
print “%s:%.3f,\t” % (key,value),
return rank
if __name__ == ‘__main__’:
G = {‘A’:{‘a’:1,’c’:1},
‘B’:{‘a’:1,’b’:1,’c’:1,’d’:1},
‘C’:{‘c’:1,’d’:1},
‘a’:{‘A’:1,’B’:1},
‘b’:{‘B’:1},
‘c’:{‘A’:1,’B’:1,’C’:1},
‘d’:{‘B’:1,’C’:1}}
PersonalRank(G,0.85,’A’,20)
”’
#items_pool = {’12’:’PHP’,’32’:’Nginx’,’121′:’Apache’,’324′:’Erlang’,’532′:’Linux’,’123′:’Ubuntu’,’53’:’Java’,’1203′:’Storm’,’429′:’Kafka’,’2932′:’Flume’}
items_pool = [12,32,121,324,532,123,53,1203,429,2932]
items = {’12’:’PHP’,’1203′:’Storm’,’123′:’Ubuntu’}
user_items = {‘1010’:[12,1203,123,429]}
#print RandomSelectNagativeSample(items)
print InitModel(user_items,4)
”’