pagerank_python/pageranke.py

50 lines
1.5 KiB
Python

#__author__ = 'admin'
S=[[0,0.5,0,0],[0.3333,0,0,0.5],[0.3333,0,1,0.5],[0.3333,0.5,0,0]]
U=[[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]
f=[0.25,0.25,0.25,0.25]
alpha=0.8
n=len(S)
def multiGeneMatrix(gene,Matrix):
mullist=[[0]*len(Matrix) for row in range(len(Matrix))]
for i in range(0,len(Matrix)):
for j in range(0,len(Matrix)):
mullist[i][j] += Matrix[i][j]*gene
return mullist
def addMatrix(Matrix1,Matrix2):
if len(Matrix1[0])!=len(Matrix2):
print("add error...")
return
addlist=[[0]*len(Matrix1) for row in range(len(Matrix1))]
for i in range(0,len(Matrix1)):
for j in range(0,len(Matrix2)):
addlist[i][j]=Matrix1[i][j]+Matrix2[i][j]
return addlist
def multiMatrixVector(m,v):
rv=list(range(len(v)))
for row in range(0,len(m)):
temp=0
for col in range(0,len(m[1])):
temp+=m[row][col]*v[col]
rv[row]=temp
return rv
f1=multiGeneMatrix(alpha,S)
f2=multiGeneMatrix((1-alpha)/len(S[0]),U)
G=addMatrix(f1,f2)
count=0
while(True):
count=count +1
pr_next=multiMatrixVector(G,f)
print ("count: %s " % count)
print (str(round(pr_next[0],5)) +"\t" + str(round(pr_next[1],5)) + "\t" + str(round(pr_next[2],5)) + "\t" + str(round(pr_next[3],5)))
if round(f[0],5)==round(pr_next[0],5) and round(f[1],5)==round(pr_next[1],5) and round(f[2],5)==round(pr_next[2],5) and round(f[3],5)==round(pr_next[3],5):
break
f=pr_next
print ("Page Rank complete")