Created
September 30, 2012 14:26
-
-
Save melpomene/3806893 to your computer and use it in GitHub Desktop.
PageRank for EDAN55
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# encoding: utf-8 | |
import numpy as np | |
import sys | |
def parse(path): | |
f = open(path, 'r') | |
lines = f.readlines() | |
#init empty | |
n = int(lines[0]) | |
m = np.zeros((n, n)) | |
f = open(path, 'r') | |
first = True | |
for row in f: | |
if first: | |
first = False | |
else: | |
nrs = row.split() | |
i = 0 | |
while i < len(nrs) - 1: | |
m[int(nrs[i])][int(nrs[i+1])] = 1.0 / (len(nrs) / 2.0) | |
i += 2 | |
return m | |
def pagerank_simple(A, iterations): | |
""" Simple pagerank """ | |
p = np.ones(len(A)) | |
Q = np.linalg.matrix_power(A, iterations) | |
print p | |
print Q | |
print p * Q | |
p = np.transpose(p * Q) | |
for i in xrange(len(p)): | |
print str(i) + " PageRank: " + str(p[i]) | |
def pagerank(H, iterations): | |
""" Simple pagerank """ | |
p = np.ones(len(H)) | |
n = len(H) | |
alpha = 0.85 | |
D = [[0 for y in range(n)] for x in range(n)] | |
for i in xrange(len(D)): | |
for j in xrange(len(D)): | |
if sum(H[i]) == 0: | |
D[i][j] = 0 | |
else: | |
#bigger then deg(i) = 0 else 1/n | |
D[i][j] = 1.0 / len(H) | |
P = alpha * ( H + D ) + (1 - alpha) / n * np.ones((n, n)) | |
# CALCULATE pP HERE ! | |
for i in xrange(len(p)): | |
print str(i) + " PageRank: " + str(p[i]) | |
if __name__ == "__main__": | |
if len(sys.argv) == 1: | |
print "Call like: python pagerank.py <nbr of iterations> <test case>" | |
exit() | |
iterations = int(sys.argv[1]) | |
if len(sys.argv) == 2: | |
graph = parse('data/three.txt') | |
else: | |
graph = parse('data/' + sys.argv[2] +".txt") | |
pagerank(graph, iterations) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment