Skip to content

Commit f12b472

Browse files
committed
Page Rank and exemple
1 parent c94c1d9 commit f12b472

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

Ranking Page/PageRank/PageRank.py

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#!/usr/bin/env python
2+
# coding: utf-8
3+
4+
#Author: fabiovini08
5+
6+
import os
7+
import numpy as np
8+
9+
10+
# Creates an adjacency matrix from a file
11+
12+
#File format: A .txt file where the first line has a number N that
13+
# represents the #nodes and the following lines have numbers
14+
# pairs X Y that represents the edge X -> Y
15+
def read_graph(filename):
16+
f = open(filename,'r+')
17+
lines = f.readlines()
18+
f.close();
19+
N = int(lines.pop(0))
20+
M = np.zeros([N,N])
21+
for l in lines:
22+
i,j = l.split()
23+
i = int(i)
24+
j = int(j)
25+
26+
M[i,j] = 1
27+
i = 0
28+
return M
29+
30+
# absorbing node treatment
31+
def dumping_fac(M,fac = 0.15):
32+
A = (1-fac)*M + fac * 1/M.shape[0] * np.ones(M.shape)
33+
return A
34+
35+
# No link page treatment
36+
def mat_norm(M):
37+
for c in (M.T):
38+
s = np.sum(c)
39+
if s == 0:
40+
c = np.ones([1,N]) * 1/N
41+
else:
42+
c = 1/np.sum(c) * c
43+
c.reshape([10,1])
44+
M[:,i] = c;
45+
i = i+1
46+
return M
47+
48+
#Compute the relevance of each page
49+
def page_rank(M, tol = 0.001, nIter = 500):
50+
# Returns the vector v where each position has a value of relevance
51+
# of the respective node
52+
53+
M = mat_norm(M)
54+
M = dumping_fac(M)
55+
N = M.shape[0]
56+
v = np.ones([N,1]) * 1/N
57+
for i in range(nIter):
58+
v1 = M.dot(v)
59+
err = np.linalg.norm(v-v1,2)
60+
v = v1
61+
if err < tol:
62+
numI = i
63+
break
64+
return v, numI
65+
66+
## Algorith Test
67+
68+
M = read_graph('graph.txt')
69+
print(M)
70+
A = dumping_fac(M)
71+
print(A)
72+
v, it = page_rank(A)
73+
print(v)
74+
val = max(v)
75+
print(val, it)
76+

Ranking Page/PageRank/graph.txt

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
10
2+
0 2
3+
0 4
4+
0 3
5+
2 3
6+
3 1
7+
4 2
8+
6 0
9+
8 7
10+
9 5
11+
8 9

0 commit comments

Comments
 (0)