Dict没有“定向”属性

时间:2018-11-21 07:32:59

标签: python algorithm graph networkx pagerank

以以下格式将Python中的Pagerank算法库应用于图(JSON)时:

matrix={'1':{'2':23,'4':56},'4':{'2':22,'7':5}}

pr=nx.pagerank(matrix,alpha=0.85)
# -->{from_node:{to_node:edge weight)}

我收到以下错误:

Traceback (most recent call last):
  File "somescriptname.py", line 1, in <module>
  File "<decorator-gen-276>", line 2, in pagerank
  File "/.../site-packages/networkx/utils/decorators.py", line 67, in _not_implemented_for
    terms = {'directed': graph.is_directed(),  
AttributeError: 'dict' object has no attribute 'is_directed'

1 个答案:

答案 0 :(得分:1)

您正在传递字典,但是networkx.pagerank() function并没有字典。从文档中:

  

G (图形)– NetworkX图形。无向图将转换为有向图,每个无向边都有两个有向边。

您可以使用networkx.Graph() to convert your dictionary

G = nx.Graph(matrix)
pr = nx.pagerank(G, alpha=0.85)

演示:

>>> import networkx as nx
>>> matrix = {'1': {'2': 23, '4': 56}, '4': {'2': 22, '7': 5}}
>>> G = nx.Graph(matrix)
>>> nx.pagerank(G, alpha=0.85)
{'1': 0.2459279727012903, '4': 0.36673529905297914, '2': 0.2459279727012903, '7': 0.14140875554444032}