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]))