In [1]:
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
Creating a network:
In [2]:
size = 10
np.random.seed(0)
A = np.random.choice((0, 1), size=(size, size))
A
Out[2]:
Normalise the matrix to make it a stochastic matrix.
In [3]:
row_sums = A.sum(axis=1)
M = A / row_sums[:, np.newaxis]
np.round(M, 2)
Out[3]:
Create a graph from the network.
In [4]:
G = nx.from_numpy_array(M, create_using=nx.DiGraph())
In [5]:
plt.figure()
nx.draw(G)
plt.savefig("graph.pdf")
Directly compute the pagerank:
In [6]:
nx.pagerank(G, alpha=1)
Out[6]:
Raise the matrix to a large power.
In [7]:
np.round(np.linalg.matrix_power(M, 2000000), 2)
Out[7]:
Explain how this corresponds to an eigenvalue problem.
In [8]:
e_values, e_vectors = np.linalg.eig(M.T)
np.real(np.round(e_vectors[:,0] / sum(e_vectors[:,0]), 2))
Out[8]: