import numpy as np
M = np.array([[0,1,1,0],
[1,0,0,0],
[0,1,0,1],
[1,0,0,0]],dtype = float)
# 1.定义转移矩阵
def move_matrix(m):
num = m.sum(axis = 0) # 统计每一列的总数,也就是网页的链接数
return m/num # 返回建立的转移矩阵
# 2.定义V矩阵,初始的PR值
def V(c):
pr = np.ones((c.shape[0],1),dtype=float)/len(c) # 初始化PR值矩阵
return pr
# 3.迭代计算pagerank值
def PR(p,m,v):
i = 0
while 1:
v1 = p*np.dot(m,v) + (1-p) * v
if np.abs((v-v1).all()) < 0.001:
break
else:
v = v1
i += 1
if i==30:break
print('求pr值迭代%d次'%(i))
return v
# 4.测试
M1 = move_matrix(M)
V1 = V(M1)
a = 0.85
print('最后迭代网页PR值结果为:\n',PR(a,M1,V1))