Load properties from networkx graph

What is the correct way to copy node attributes from a networkx graph? I’m trying this:

import networkx as nx
from networkx.readwrite import json_graph
from dgl import DGLGraph

g = nx.Graph(id='graph')
g.add_node('A', A='xxx')
g.add_node('B', A='yyy')
g.add_edge('A', 'B')

x = DGLGraph()
x.from_networkx(g, node_attrs=['A'])

But it returns:
ValueError: too many dimensions ‘str’

According to the docs it should be possible: https://docs.dgl.ai/en/0.4.x/generated/dgl.DGLGraph.from_networkx.html?highlight=from_networkx

Thank you

I think you need to use tensors for node features. An example like below should work

import networkx as nx
import torch
from networkx.readwrite import json_graph
from dgl import DGLGraph

g = nx.Graph(id='graph')
g.add_node('A', A=torch.zeros(1, 1))
g.add_node('B', A=torch.ones(1, 1))
g.add_edge('A', 'B')

x = DGLGraph()
x.from_networkx(g, node_attrs=['A'])
2 Likes

Thanks @mufeili you’re right indeed, you’ve already saved me twice in 3 days!

1 Like