numpy 在python中实现简单PageRank的困难(结果与实际PageRank分数不同)

zqdjd7g9  于 2023-11-18  发布在  Python
关注(0)|答案(1)|浏览(111)

代码如下:

import networkx, numpy.matlib, numpy.linalg

nodes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
edges = [(1, 3, 1), (1, 9, 1), (2, 9, 1), (2, 10, 1), (3, 7, 1), (3, 9, 1), (4, 2, 1), (4, 8, 1), (4, 10, 1), (5, 6, 1), (5, 8, 1), (6, 1, 1), (6, 5, 1), (6, 8, 1), (6, 10, 1), (7, 1, 1), (7, 9, 1), (8, 5, 1), (8, 6, 1), (8, 7, 1), (9, 4, 1), (9, 8, 1), (10, 7, 1)]

DG = networkx.DiGraph()
DG.add_weighted_edges_from(edges)

pr = networkx.pagerank(DG)
for n in nodes:
    print(n, pr[n])

A = networkx.adjacency_matrix(DG, nodes).todense()
stochasticA = A / A.sum(axis = 0)

d = 0.85
epsilon = 1e-6
M = d * stochasticA + (1 - d) / len(nodes)
old_page_rank_vector = numpy.matlib.ones((len(nodes), 1)) / len(nodes)
new_page_rank_vector = M * old_page_rank_vector
while (numpy.linalg.norm(old_page_rank_vector - new_page_rank_vector) > epsilon):
    old_page_rank_vector = new_page_rank_vector
    new_page_rank_vector = M * old_page_rank_vector

page_rank_vector = new_page_rank_vector/sum(new_page_rank_vector)
print(page_rank_vector)

字符串
运行此代码后可以看到,networkx实现给出的结果与我的代码计算的结果不同。
有人能帮我找出我的错误吗?
谢谢你,谢谢

eagi6jfj

eagi6jfj1#

A = networkx.adjacency_matrix(DG, nodes).todense()更改为A = numpy.transpose(networkx.adjacency_matrix(DG, nodes).todense())可以工作。
我设法误解了一些东西,好吧,没有转置矩阵。

相关问题