forked from piskvorky/gensim
/
pagerank_weighted.py
64 lines (47 loc) · 1.82 KB
/
pagerank_weighted.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
from numpy import empty as empty_matrix
from scipy.sparse import csr_matrix
from scipy.sparse.linalg import eigs
from six.moves import xrange
try:
from numpy import VisibleDeprecationWarning
import warnings
warnings.filterwarnings("ignore", category=VisibleDeprecationWarning)
except ImportError:
pass
def pagerank_weighted(graph, damping=0.85):
adjacency_matrix = build_adjacency_matrix(graph)
probability_matrix = build_probability_matrix(graph)
pagerank_matrix = damping * adjacency_matrix.todense() + (1 - damping) * probability_matrix
vals, vecs = eigs(pagerank_matrix.T, k=1) # TODO raise an error if matrix has complex eigenvectors?
return process_results(graph, vecs.real)
def build_adjacency_matrix(graph):
row = []
col = []
data = []
nodes = graph.nodes()
length = len(nodes)
for i in xrange(length):
current_node = nodes[i]
neighbors_sum = sum(graph.edge_weight((current_node, neighbor)) for neighbor in graph.neighbors(current_node))
for j in xrange(length):
edge_weight = float(graph.edge_weight((current_node, nodes[j])))
if i != j and edge_weight != 0.0:
row.append(i)
col.append(j)
data.append(edge_weight / neighbors_sum)
return csr_matrix((data, (row, col)), shape=(length, length))
def build_probability_matrix(graph):
dimension = len(graph.nodes())
matrix = empty_matrix((dimension, dimension))
probability = 1.0 / float(dimension)
matrix.fill(probability)
return matrix
def process_results(graph, vecs):
scores = {}
for i, node in enumerate(graph.nodes()):
scores[node] = abs(vecs[i, :])
return scores