pagerank的源代码如下:
#coding=utf-8
S=[[0.25,0,0,0],[0.25,0,0,1],[0.25,0.5,0,0],[0.25,0.5,1,0]] #转移矩阵
M=[0.25,0.25,0.25,0.25] #初始矩阵
alpha=0.85 # 阻尼系数
def vmat(mat, vector):
if len(mat[0]) != len(vector):
print "can’t cacl mat*vector !"
return
res = [0.0 for i in range(len(mat))]
for i in range(0, len(mat)):
for j in range(0, len(mat[1])):
res[i] += float(mat[i][j] * vector[j])
return res
def avector(a, vector):
res = [0.0 for i in range(len(vector))]
for i in range(len(vector)):
res[i] = float(vector[i] * a)
return res
def addvector(vector1, vector2):
if len(vector1) != len(vector2):
print "can’t add vector !"
return
res = [0.0 for i in range(len(vector1))]
for i in range(len(vector1)):
res[i] = float(vector1[i] + vector2[i])
return res
def pagerank(S, M, alpha):
v = vmat(S, M)
av = avector(alpha, v)
random = avector(1 - alpha, M)
add = addvector(av, random)
return add
if __name__ == '__main__':
add = pagerank(S, M, alpha)
new_add = add
flag = True
while(flag):
flag = False
new_add = pagerank(S, add, alpha)
print new_add
for i in range(len(add)):
if round(new_add[i], 5) != round(add[i], 5):
flag = True
add = new_add
print new_add
最终结果如下: