While converting Graph from Networkx to Dgl error

1.2k views Asked by At

When I want to convert my networkx Graph to dgl library I get this error

KeyError                                  Traceback (most recent call last)

<ipython-input-140-ee8cede61bf4> in <module>()
---> 12 dgl.from_networkx(DiGraphNN, node_attrs=['name'], edge_attrs=['weight'])

/usr/local/lib/python3.7/dist-packages/dgl/convert.py in from_networkx(nx_graph, node_attrs, edge_attrs, edge_id_attr_name, idtype, device)
   1277         for nid in range(g.number_of_nodes()):
   1278             for attr in node_attrs:
-> 1279                 attr_dict[attr].append(nx_graph.nodes[nid][attr])
   1280         for attr in node_attrs:
   1281             g.ndata[attr] = F.copy_to(_batcher(attr_dict[attr]), g.device)

KeyError: 'name' 

'name' represents node feature in here and I have data structure like this

[(-1, {'name': 11}), (20940, {'name': 11}), (-2, {'name': 11}), (-3, {'name': 11}), (-6, {'name': 11}), (-10, {'name': 11}), (-11, {'name': 11}), (-12, {'name': 11}), (-14, {'name': 11})]

I don't understand why it can't access to name feature of Graph.

from networkx.classes import digraph
import dgl
from dgl.data import DGLDataset

# dG = dgl.DGLGraph()
dgl.from_networkx(DiGraphNN, node_attrs=['name'], edge_attrs=['weight'])

Do you have any suggestion?

1

There are 1 answers

0
Ani On BEST ANSWER

I was trying different things in different two days. I couldn't solve in this function directly but I have workarounds and I have suspicion why it is not working.

What can cause to this problem:

  1. If some nodes doesn't have this feature
  2. Maybe edges have different nodes which doesn't appear in nodes list so It adds automatically These are my suspicions I don't know a lot about Dgl for now.

How I fixed this:

dG = dgl.from_networkx(DiGraphNN)
dG.ndata['name'] = torch.randn(6, 3)
dG.edata['weight'] = torch.randn(5, 4)

So I created Graph without features and after I added features to Graph in DGL. It is just example you have to add features in the length of nodes or edges.

Documentation