Open In App

Create Homogeneous Graphs using dgl (Deep Graph Library) library

Last Updated : 21 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will create Homogeneous Graphs using dgl (Deep Graph Library) library. Graphs are nothing but collections of Nodes/Vertices and Edges. Also, Edges are nothing but Source nodes to Destination nodes. So all edges can be represented as (U, V) where U and V are nodes.

G = (V, E)

Package Required

pip install dgl

What is Deep Graph Library (DGL) in Python?

The Deep Graph Library (DGL) is a Python open-source library that helps researchers and scientists quickly build, train, and evaluate GNNs on their datasets. It is Framework Agnostic. Build your models with PyTorch, TensorFlow, or Apache MXNet.

Homogeneous Uni-Directed Graphs

Directed graphs are graphs that have directed edges between the nodes. If a directed edge point is from u to v then, v is adjacent to u and u is adjacent to v. In the directed graph edges have directions and are indicated with an arrow on the edge. Creating a uni-directed graph as below:

Create Homogeneous Graphs using dgl (Deep Graph Library) library

 

Example:

The data for constructing a graph, which takes the form of (U, V). (U[i],V[i]) forms the edge with ith in the graph. The allowed data formats are tensor. Each tensor must be a 1D tensor containing node IDs. So that we get the nodes and edges. So here the edges are 0,1 ; 0,2 ; 0,4 ; 1,2 ; 1,3 ; 2,3 ; 2,4 ; 3,4.

Python3




import dgl
import torch
 
# source nodes
u = torch.tensor([0, 0, 0, 1, 1, 2, 2, 3])
# destination nodes
v = torch.tensor([1, 2, 4, 2, 3, 3, 4, 4])
 
# Tuple of tensors is passed as argument
mygraph = dgl.graph((u, v))
 
print(mygraph)


Output:

 

Homogeneous Bi-Directed Graphs

The edges in a bi-directed graph have both end directions attached to them, making them bidirectional. As a result, either direction can be used to traverse the graph. The graph is bidirected since there is an arrow in it. In the given example, it is possible to move through the graph both from node A to node B and vice versa.

Create Homogeneous Graphs using dgl (Deep Graph Library) library

 

Example:

One needs to make edges for both directions in a bidirected graph. In this situation, dgl.to bidirected(), which creates a new graph with edges in both directions, can be useful.

Python3




import dgl
import torch
 
# source nodes
u = torch.tensor([0,0,0,1,1,2,2,3])
# destination nodes
v = torch.tensor([1,2,4,2,3,3,4,4])
 
# Tuple of tensors is the argument passed
mygraph = dgl.graph((u,v))
 
# makes a Uni Directed to Bi Directed By adding reverse edges
mygraph_new = dgl.to_bidirected(mygraph)
 
print(mygraph_new)


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads