-1

While applying the Pagerank algorithm Library in Python to a graph (JSON) in the following format:

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

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

I am receiving the following error:

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'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Drool
  • 119
  • 1
  • 7

1 Answers1

2

You are passing in a dictionary, but the networkx.pagerank() function doesn't take a dictionary. From the documentation:

G (graph) – A NetworkX graph. Undirected graphs will be converted to a directed graph with two directed edges for each undirected edge.

You can use networkx.Graph() to convert your dictionary:

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

Demo:

>>> 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}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks @martijin! two quick questions: 1. How does Graph() converts a dict to graph. As Json itself is a graph where there are from _nodes and to_nodes specified. 2. Pagerank formula confirmation: is it PF=(1-d)/N + d* (Sum of pageranks of incoming links)/N or PF=(1-d)+ d* (Sum of pageranks of incoming links)/N – Drool Nov 21 '18 at 17:27
  • @Anik: see the linked documentation, there are several options to convert existing dictionary data structures to a graph. When you call `nx.Graph()`, then the [`to_networkx_graph()` function](https://networkx.github.io/documentation/latest/reference/generated)/networkx.convert.to_networkx_graph.html#networkx.convert.to_networkx_graph) is used; your sample is a simple dictionary mapping `nodeid` to a set of edges, each edge another `nodeid` and weight value. – Martijn Pieters Nov 21 '18 at 17:44
  • @Anik: I have no idea what the formula used is. – Martijn Pieters Nov 21 '18 at 17:45