Consider the following toy networkx graph:
import networkx as nx
G = nx.DiGraph()
G.add_edges_from([(0, 1), (1, 2), (2, 3)])
G.nodes[0]["weight"] = 0
G.nodes[1]["weight"] = 10
G.nodes[2]["weight"] = 20
G.nodes[3]["weight"] = 30
I would like to use that in dgl but I am not sure how to read in the node weights. I attempted:
import dgl
dgl.from_networkx(G, node_attrs="weight")
but that gives:
File ~/venv/lib/python3.8/site-packages/dgl/convert.py:1279, 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: 'w'
What is the right way to do this?
From the dgl doc here, it looks like node_attrs
should be a list of attribute names. So if you change dgl.from_networkx(G, node_attrs="weight")
to
dgl.from_networkx(G, node_attrs=["weight"])
, you will get the result you want.
See code below:
import networkx as nx
import dgl
G = nx.DiGraph()
G.add_edges_from([(0, 1), (1, 2), (2, 3)])
G.nodes[0]["weight"] = 0
G.nodes[1]["weight"] = 10
G.nodes[2]["weight"] = 20
G.nodes[3]["weight"] = 30
dgl.from_networkx(G, node_attrs=["weight"])
And output:
Graph(num_nodes=4, num_edges=3,
ndata_schemes={'weight': Scheme(shape=(), dtype=torch.int64)}
edata_schemes={})