58 lines
1.2 KiB
Python
58 lines
1.2 KiB
Python
import numpy as np
|
|
|
|
# Constants for PageRank
|
|
threshold = 1e-13
|
|
beta = 0.85
|
|
|
|
# Spider Trap Network represented as adjacency matrix
|
|
A = [
|
|
[0, 0, 1, 0],
|
|
[1, 0, 0, 0],
|
|
[1, 1, 0, 0],
|
|
[1, 1, 0, 1]
|
|
]
|
|
|
|
# Convert adjacency matrix to a numpy array
|
|
arr = np.array(A, dtype=float)
|
|
|
|
# Calculate summation of columns
|
|
s = []
|
|
for i in range(len(A)):
|
|
s.append(np.sum(arr[:, i]))
|
|
|
|
print("Summation of columns: ", s)
|
|
|
|
# Create the column stochastic probability matrix, M
|
|
M = arr.copy()
|
|
for j in range(len(A)):
|
|
if s[j] != 0: # Prevent division by zero
|
|
M[:, j] = M[:, j] / s[j]
|
|
|
|
print("Column stochastic probability matrix, M:")
|
|
print(M)
|
|
|
|
# Initialize rank vector
|
|
r = (1.0 + np.zeros([len(M), 1])) / len(M)
|
|
print("Initial rank vector:")
|
|
print(r)
|
|
|
|
# Calculate the uniform rank contribution
|
|
uniformR = (1.0 - beta) * r
|
|
r_prev = r.copy()
|
|
|
|
# PageRank iterations
|
|
for i in range(1, 1001):
|
|
print("Iteration: ", i)
|
|
r = beta * np.matmul(M, r_prev) + uniformR
|
|
print("The rank vector: ")
|
|
print(r)
|
|
|
|
diff = np.sum(abs(r - r_prev))
|
|
if diff < threshold:
|
|
break
|
|
r_prev = r.copy()
|
|
|
|
# Display the final rank vector
|
|
print("The final rank vector: ")
|
|
print(r[:, 0])
|