Created
February 13, 2011 18:37
-
-
Save mikejs/824935 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
def pagerank(matrix, d_factor=0.85): | |
""" | |
Calculate the pagerank vector of a given adjacency matrix (using | |
the power method). | |
:param matrix: an adjacency matrix | |
:param d_factor: the damping factor | |
""" | |
size = len(matrix) | |
epsilon = 0.0001 | |
matrix = matrix.copy() | |
# Divide each column by its number of outgoing links | |
for i in xrange(0, size): | |
col_sum = matrix[:,i].sum() | |
if col_sum: | |
matrix[:,i] /= col_sum | |
e = ((1.0 - d_factor) / size) * numpy.ones((size, size)) | |
matrix = d_factor * matrix + e | |
result = numpy.ones(size) / size | |
prev = numpy.ones(size) / size | |
iteration = 0 | |
while True: | |
result = numpy.dot(matrix, result) | |
result /= result.sum() | |
diff = numpy.abs(result - prev).sum() | |
print "Iteration %d, change %f" % (iteration, diff) | |
if diff < epsilon: | |
break | |
prev = result | |
iteration += 1 | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment