dgl.DGLGraph.from_networkx

DGLGraph.from_networkx(nx_graph, node_attrs=None, edge_attrs=None)[source]

Convert from networkx graph.

If ‘id’ edge attribute exists, the edge will be added follows the edge id order. Otherwise, order is undefined.

Parameters:
  • nx_graph (networkx.DiGraph) – If the node labels of nx_graph are not consecutive integers, its nodes will be relabeled using consecutive integers. The new node ordering will inherit that of sorted(nx_graph.nodes())
  • node_attrs (iterable of str, optional) – The node attributes needs to be copied.
  • edge_attrs (iterable of str, optional) – The edge attributes needs to be copied.

Examples

Note

Here we use pytorch syntax for demo. The general idea applies to other frameworks with minor syntax change (e.g. replace torch.tensor with mxnet.ndarray).

>>> import torch as th
>>> import networkx as nx
>>> nxg = nx.DiGraph()
>>> nxg.add_edge(0, 1, id=0, e1=5, e2=th.zeros(4))
>>> nxg.add_edge(2, 3, id=2, e1=6, e2=th.ones(4))
>>> nxg.add_edge(1, 2, id=1, e1=2, e2=th.full((4,), 2))
>>> g = dgl.DGLGraph()
>>> g.from_networkx(nxg, edge_attrs=['e1', 'e2'])
>>> g.edata['e1']
tensor([5, 2, 6])
>>> g.edata['e2']
tensor([[0., 0., 0., 0.],
        [2., 2., 2., 2.],
        [1., 1., 1., 1.]])