Convert graph from networkx format to dgl

Is it possible to convert a graph already in network format to the dgl format? It contains node and edge attributes.

If not, is there a simple way to create a dgl graph from an adjacency matrix where each non zero entry has the edge weight?

Thanks in advance!

This documentation might help.

Thanks for your reply! This was super useful!

Digging into the documentation you referenced last time, I was able to create the graph using the adjacency matrix directly in dgl :slight_smile: I was wondering what is the best way to add edge features if it is not done automatically (the adjacency matrix has non zero entries corresponding to each edge’s weight but the g.edata from the graph generated using g.from_scipy_sparse_matrix() is empty)

Does the example below help?

import torch
from dgl import DGLGraph
from scipy.sparse import rand

num_nodes = 10
coo_adj = rand(num_nodes, num_nodes, density=0.05, format='coo')
coo_g = DGLGraph(coo_adj)
coo_g.edata['weight'] = torch.tensor(, 1)

Note that the order of edges in DGLGraph follows that of nonzero entries in the coo matrix.

print(coo_adj.row, coo_adj.col)
# [2 4 9 1 3] [4 1 0 1 5]
# (tensor([2, 4, 9, 1, 3]), tensor([4, 1, 0, 1, 5]))

Hey all,

I used to be able to convert the graph directly from networkx, by using DGLGraph.from_networkx ( nx_graph, node_attrs=None, edge_attrs=None). It is deprecated now, and we need to use dgl.from_networkx(nx_graph, node_attrs, edge_attrs).

But now I cannot do it anymore as I got an error says that I cannot transform my edge attribute from my nx_graph to my dgl_graph if my nx_graph is an undirected graph. So, does it means I have to make my nx graph directed before I can use dgl.from_networkx(nx_graph, node_attrs, edge_attrs)?
And maybe out of my curiosity, why you make this change?

DGLError: Expect edge_id_attr_name and edge_attrs to be None when nx_graph is undirected, got None and [‘feat’]

Thanks all

1 Like

The reason we made the change is that it can be ill-defined about whether the edges of both directions should share a same feature. You can either make the graph directed first or convert a graph without edge features first and then manually set the edge features.