python实现pagerank

import numpy as np
from functools import reduce

# 有向图,[1,2]表示1指向2
edges = [[1, 2], [3, 2], [3, 4], [1, 3], [2, 3], [3, 1], [4, 1]]

feat_len = len(list(reduce(lambda x,y:set(x) | set(y),edges)))

arr = np.zeros(shape=[feat_len,feat_len])

# 统计对于每个节点指向该节点的个数
link_num = np.zeros([1,feat_len])
for x,y in edges:
    arr[x-1][y-1] = 1
    link_num[0][y-1] += 1

arr /= link_num
# 定义初始的pr=0
pr = np.zeros(shape=[feat_len,1])

epoch = 100
d = 0.85
for n in range(epoch):
    pr = (1-d) + arr.dot(pr) * d
    print(pr.reshape(1,-1))

你可能感兴趣的:(python实现pagerank)