Skip to content

Instantly share code, notes, and snippets.

@nkt1546789
Last active July 4, 2016 08:56
Show Gist options
  • Save nkt1546789/f5a8f3c5bb4445d141fe7dd03a84bcd1 to your computer and use it in GitHub Desktop.
Save nkt1546789/f5a8f3c5bb4445d141fe7dd03a84bcd1 to your computer and use it in GitHub Desktop.
For ranking vertices of a graph like pagerank and textrank.
import numpy as np
from copy import deepcopy
class GraphRanker(object):
def __init__(self, d=0.85, tol=1e-6, max_iters=200):
self.d = d
self.tol = tol
self.max_iters = max_iters
def fit(self, A):
"""
A: adjacency matrix
"""
n = A.shape[0]
A = A / A.sum(axis=1)
A[np.isnan(A)] = 0.0
f = np.ones((n, 1))
for _ in xrange(self.max_iters):
f_prev = f.copy()
f = (1-self.d) + self.d*A.T.dot(f)
diff = np.max(np.abs(f-f_prev))
if diff < self.tol:
print "converged", _
break
self.scores = np.asarray(f).ravel()
return self
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment