Skip to content
ImagineWorld

Deep Learning Models for Graphs

node_idnode-book_applied-deep-learning-on-graphs_chapter-04-deep-learning-models-for-graphs
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num4
chapter_titleDeep Learning Models for Graphs
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 4 — Deep Learning Models for Graphs

Section titled “Chapter 4 — Deep Learning Models for Graphs”

In recent years, the field of machine learning has witnessed a paradigm shift with the emergence of graph neural networks (GNNs) as powerful tools for addressing prediction tasks on graph-structured data. Here, we’ll delve into the transformative potential of GNNs, highlighting their role as optimizable transformations capable of handling diverse graph attributes, such as nodes, edges, and global context while preserving crucial graph symmetries, particularly permutation invariances.

The foundation of GNNs lies in the message-passing neural network (MPNN) framework. Through this framework, GNNs leverage a sophisticated mechanism for information exchange and aggregation across graph structures, enabling the model to capture intricate relationships and dependencies within the data.

One distinctive feature of GNNs is their adherence to a graph-in, graph-out architecture. This means that the model accepts a graph as input, equipped with information embedded in its nodes, edges, and global context. This inherent structure aligns with many real-world problems where data exhibits complex relationships and dependencies best represented as graphs.

GNNs excel in their ability to perform a progressive embedding transformation on the input graph without altering its connectivity. This progressive transformation ensures that the model refines its understanding of the underlying patterns and structures within the data, contributing to enhanced predictive capabilities.

We’ll cover the following topics in this chapter:

  • Message passing in graphs
  • Decoding GNNs
  • Graph convolutional networks (GCNs)
  • Graph Sample and Aggregation (GraphSAGE)
  • Graph attention networks (GATs)

Unlike traditional neural networks, GNNs need to account for the inherent structure of the graph, allowing nodes to exchange information and update their representations based on their local neighborhoods. This core mechanism is achieved through message passing, a process of iteratively passing messages between nodes and aggregating information from their neighbors.

GNNs operate on graph-structured data and use a message-passing mechanism to update node representations based on information from neighboring nodes. Let’s delve into the mathematical explanation of message passing in GNNs.

Consider an undirected graph G=(V,E)G=(V,E), where VV is the set of nodes andEE is the set of edges. Each node vv in VVhas an associated feature vector xvx_{v}. The goal of a GNN is to learn a representation hvh_{v} for each node vv that captures information from its neighborhood.

The basic message-passing operation in a GNN can be broken down into a series of steps:

  1. Aggregation of messages:
    1. For each node vv, gather information from its neighbors.
    2. Let N(v)N(v) represent the set of neighbors of node vv. The aggregated message mvm_{v} for node vv is computed by aggregating information from its neighbors:
mv=aggregate({hu:uϵN(v)})m_{v}=aggregate(\{h_{u}:uϵN(v)\})

The aggregation function can vary (e.g., sum, mean, or attention-weighted sum).

  1. UPDATE function:
    1. Update the node representation hvh_{v} based on the aggregated message mvm_{v} and the current node representation hvh_{v}.
    2. The UPDATE function updateupdate(∙∙) is a neural network layer that takes the aggregated message and the current node representation as input and produces the updated representation:

hv′h_{v}^{'} = update(hv,mv)update(h_{v},m_{v})

The UPDATE function typically involves a neural network layer with learnable parameters.

These steps are iteratively applied for a fixed number of times or until convergence to refine the node representations. The overall process can be expressed in a few equations:

mv=aggregate(hu:u∈N(v))m_{v}=aggregate(h_{u}:u\in N(v)) hv′=update(hv,mv)h_{v}^{'}=update(h_{v,}m_{v})

These equations capture the essence of the message-passing mechanism in a GNN. The specific choices for the aggregation function, UPDATE function, and the number of iterations depend on the architecture of the GNN (e.g., GraphSAGE, GCN, gated graph neural networks (GGNNs), etc.).

For instance, in a simple GraphSAGE formulation, the aggregation function might be a mean operation, and the UPDATE function might be a simple neural network layer:

mv=1∣N(v)∣∑uϵN(v)hum_{v}=\frac{1}{|N(v)|}\sum _{_{uϵN(v)}^{}}h_{u} hv′=σ(W⋅concat(hv,mv))h_{v}^{'}=σ(W\cdot concat(h_{v},m_{v}))

Here, σσ is an activation function, WW is a learnable weight matrix, and concat(⋅)concat(\cdot ) is the concatenation operation.

Figure 4.1 – Message passing in graphs

Figure 4.1 – Message passing in graphs

Through these iterative steps, message passing enables nodes to learn representations that capture not only their own intrinsic features but also the information from their connected neighbors and the overall structure of the graph. This allows GNNs to effectively model complex relationships and dependencies within graph-structured data.

Now, let’s try to understand how to formally define a GNN.

A GNN is a neural network architecture designed to operate on graph-structured data. It learns a function that maps a graph and its associated features to a set of node-level, edge-level, or graph-level outputs. The following is a formal mathematical definition of a GNN.

Given a graph G=(V,E)G=(V,E), where VV is the set of nodes and EE is the set of edges, let X∈R∣V∣×dX\in R^{|V|\times d} be the node feature matrix, where each row xv∈Rdx_{v}\in R^{d}represents the features of node v ∈ Vv\,\in \,V.

A GNN is a function fθ:G×R∣V∣×d→R∣V∣×d′f_{θ}:G\times R^{|V|\times d}\to R^{|V|\times d^{'}} parameterized by learnable weights θθ, which maps the graph GG and its node features XX to a new set of node representations H∈R∣V∣×d′H\in R^{|V|\times d^{'}}, where d′d^{'} is the dimensionality of the output node representations.

The function fθf_{θ} is computed through a series of message passing and aggregation steps, typically organized into LL layers. At each layer l∈{1,…,L}l\in \{1,\ldots ,L\}, the node representations are updated as follows:

hvl=UPDATE(l)(hvl−1,AGG(l)({hul−1:u∈N(v)}))h_{v}^{l}=UPDATE^{(l)}(h_{v}^{l-1},AGG^{(l)}(\{h_{u}^{l-1}:u\in N(v)\}))

Let’s break this down:

  • hv(l)ϵRdlh_{v}^{(l)}ϵR^{d_{l}} is the representation of node vv at layerl,l, with hv0=xvh_{v}^{0}=x_{v}. Here, R(dl)R^{(d_{l})} represents a real-valued vector space of dimension dld_{l}.
  • The UPDATE function UPDATEl: R(dl−1) X R(dl) →  R(dl) UPDATE^{l}:\,R^{(d_{l-1})}\,Χ\,R^{(d_{l})\,}\to \,\,R^{(d_{l})\,} is a learnable function that updates the node representation based on its previous representation and the aggregated messages from its neighbors.
  • The aggregation (AGG) function AGG(l):Rdl−1∗→RdlAGG^{(l)}:R^{d_{l-1}*}\to R^{d_{l}} is a permutation-invariant aggregation function that combines the representations of the neighboring nodes. Common choices include sum, mean, and max.
  • N(v)N(v) denotes the set of neighbors of node vv in the graph GG.

AfterLL layers of message passing and aggregation, the final node representations are given by H=hvLH=h_{v}^{L} for all v∈Vv\in V.

The UPDATE function is typically implemented as neural networks, such as multi-layer perceptrons (MLPs) or attention mechanisms, with learnable parameters.

For graph-level tasks, a READOUT function is applied to the final node representations to obtain a graph-level representation:

hG=READOUT({hvL:v∈V})h_{G}=READOUT(\{h_{v}^{L}:v\in V\})

Here, READOUT is a permutation-invariant function that aggregates the node representations into a single vector, such as sum, mean, or a more complex pooling operation.

The graph-level representationhGh_{G} can then be used for downstream tasks, such as graph classification or regression.

This is a general formulation of GNNs, and there are many specific architectures that fall under this framework, such as GCNs, GraphSAGE, GATs, and MPNNs, each with their own variations of the UPDATE, AGG, and READOUT functions.

Let’s understand how graph learning borrows the concept of convolution networks and leverages it to extract learnings from a graph.

GCNs are a specific type of GNN that extend the concept of convolution to graph-structured data. GCNs learn node representations by aggregating information from neighboring nodes, allowing for the capture of both node features and graph structure.

In a GCN, the graph convolution operation at layer ll is defined as follows:

H(l+1)=σ(D−12AD12H(l)W(l))H^{(l+1)}=σ(D^{-\frac{1}{2}}AD^{\frac{1}{2}}H^{(l)}W^{(l)})

Let’s break this down:

  • H(l)∈R∣V∣×dlH^{(l)}\in R^{|V|\times d_{l}} is the matrix of node representations at layer ll, with H(0)=XH(0)=X (input node features).
  • A^=A+I\hat{A}=A+I is the adjacency matrix AA with added self-loops, where II is the identity matrix.
  • D^\hat{D} is the diagonal degree matrix of A^\hat{A}, with D^ii=∑jA^ij\hat{D}_{ii}=\sum _{j}\hat{A}_{ij}.
  • W(l)∈Rdlxdl+1​​W^{(l)}\in R^{d_{l}xd_{l+1}}​​ is a learnable weight matrix for layer ll.
  • σ(⋅)σ(\cdot ) is a non-linear activation function, such as the rectified linear unit (ReLU) function or sigmoid function.

The term D−12AD12D^{-\frac{1}{2}}AD^{\frac{1}{2}} is the symmetrically normalized adjacency matrix, which ensures that the scale of the node representations remains consistent across layers.

Imagine a citation network, where each node stands for a scientific paper and each edge represents a citation connecting two papers. Each paper has a feature vector representing its content (e.g., bag-of-words). A GCN can be used to classify the papers into different categories (e.g., computer science, physics, biology) by learning node representations that capture both the content and the citation structure of the network.

Building on our mathematical understanding of the GCN, let’s look at a piece of sample code leveraging PyG:

import torch
import torch.nn.functional as F
from torch_geometric.datasets import Planetoid
from torch_geometric.nn import GCNConv
# Load the Cora dataset
dataset = Planetoid(root='data/Cora', name='Cora')

For this example, we import the necessary libraries and load the Cora dataset using the Planetoid class from PyG. The Cora dataset is a citation network dataset, where nodes represent scientific papers and edges represent citations between papers. The dataset contains 2,708 nodes, 10,556 edges, and 7 classes representing different research areas:

# Get the graph data
data = dataset[0]
# Print some statistics about the graph
print(f'Number of nodes: {data.num_nodes}')
print(f'Number of edges: {data.num_edges}')
print(f'Number of features: {data.num_features}')
print(f'Number of classes: {dataset.num_classes}')

Here, we access the graph data using dataset[0]. We then print some statistics about the graph, including the number of nodes, edges, features, and classes:

Number of nodes: 2708
Number of edges: 10556
Number of features: 1433
Number of classes: 7

Now that we understand what the data looks like, let’s put down the building blocks of the model:

# Define the GCN model
class GCN(torch.nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels):
super(GCN, self).__init__()
self.conv1 = GCNConv(in_channels, hidden_channels)
self.conv2 = GCNConv(hidden_channels, out_channels)
def forward(self, x, edge_index):
x = self.conv1(x, edge_index)
x = F.relu(x)
x = F.dropout(x, training=self.training)
x = self.conv2(x, edge_index)
return F.log_softmax(x, dim=1)

Next, we define the GCN model. The model consists of two GCN layers (GCNConv) with a hidden layer in between. The __init__ method initializes the layers with the specified input, hidden, and output dimensions. The forward method defines the forward pass of the model, where x and edge_index are passed through the GCN layers. ReLU activation and dropout are applied after the first layer, and log-softmax is applied to the output of the second layer:

# Set the model parameters
in_channels = dataset.num_node_features
hidden_channels = 16
out_channels = dataset.num_classes
# Create an instance of the GCN model
model = GCN(in_channels, hidden_channels, out_channels)

Here, we set the model parameters based on the dataset. The input dimension (in_channels) is set to the number of node features in the dataset, the hidden dimension (hidden_channels) is set to 16, and the output dimension (out_channels) is set to the number of classes in the dataset. We then create an instance of the GCN model with these parameters:

# Define the optimizer and loss function
optimizer = torch.optim.Adam(
model.parameters(), lr=0.01, weight_decay=5e-4)
criterion = torch.nn.NLLLoss()
# Train the model
model.train()
for epoch in range(200):
optimizer.zero_grad()
out = model(data.x, data.edge_index)
loss = criterion(out[data.train_mask],
data.y[data.train_mask])
loss.backward()
optimizer.step()

In this part, we define the optimizer (Adam) and the loss function (negative log-likelihood loss (NLLLoss)) for training the model. We set the learning rate to 0.01 and the weight decay to 5e-4.

We then train the model for 200 epochs. In each epoch, we do the following:

  1. Zero the gradients of the optimizer.

  2. Perform a forward pass of the model on the node features and edge index.

  3. Compute the loss using the model’s output and the ground truth labels for the training nodes (specified by data.train_mask).

  4. Perform a backward pass to compute the gradients.

  5. Update the model parameters using the optimizer:

    # Evaluate the model
    model.eval()
    _, pred = model(data.x, data.edge_index).max(dim=1)
    correct = float(pred[data.test_mask].eq(
    data.y[data.test_mask]).sum().item())
    accuracy = correct / data.test_mask.sum().item()
    print(f'Accuracy: {accuracy:.4f}')

    Accuracy: 0.8000

Finally, we evaluate the trained model on the test set. We set the model to evaluation mode using model.eval(). We perform a forward pass on the entire graph and obtain the predicted class labels using max(dim=1). We then compute the accuracy by comparing the predicted labels with the ground truth labels for the test nodes (specified by data.test_mask).

This code provides a basic implementation of GCN using PyG on the Cora dataset.

Make sure you have PyG installed before running this code. You can install it using pip install torch-geometric.

Overall, this code creates an instance of the GCN model, trains it on the Cora dataset using the specified hyperparameters (hidden units, learning rate, epochs), and evaluates the trained model on the test set to measure its performance in terms of accuracy.

GCNs can be utilized to learn and perform tasks at different levels in a graph. The following can be performed with GCNs:

  • Node-level tasks: GCNs can be used for node classification, where the goal is to predict the label of each node in the graph. This is demonstrated in the previous example, where the GCN is used to classify nodes in the Cora citation network.
  • Edge-level tasks: GCNs can be adapted for edge prediction or link prediction tasks, where the goal is to predict the existence or attributes of edges in the graph. To do this, the node representations learned by the GCN can be used to compute edge scores or probabilities.
  • Graph-level tasks: GCNs can be used for graph classification or regression tasks, where the goal is to predict a label or a continuous value for an entire graph. To achieve this, a pooling operation (e.g., global mean pooling or global max pooling) is applied to the node representations learned by the GCN to obtain a graph-level representation, which is then fed into a classifier or regressor.

GCNs are a powerful and widely used type of GNN that can effectively learn node representations by incorporating both node features and graph structure. They have shown strong performance on various graph-based tasks and can be adapted for node-level, edge-level, and graph-level problems.

Over time, many optimizations over vanilla GCNs have been proposed and utilized in the industry. One such optimization, especially for scaling the graph learning process, is GraphSAGE.

GraphSAGE introduces a scalable and adaptive approach to graph representation learning, addressing some limitations of GCN and enhancing scalability. At its core, GraphSAGE employs a neighborhood sampling and aggregation strategy, diverging from the fixed-weight aggregation mechanism of GCN.

In GraphSAGE, the process of learning node representations involves iteratively sampling and aggregating information from local neighborhoods. Let G=(V,E)G=(V,E) be a graph with nodes VV and edges EE, and filf_{i}^{l} denote the embedding of node ii at layer ll. The update rule for GraphSAGE can be expressed as follows:

fil+1​=Aggregate({fjl​,∀j∈SampleNeighbors(i)})f_{i}^{l+1}​=Aggregate(\{f_{j}^{l}​,\forall j\in SampleNeighbors(i)\})

Here, SampleNeighbors(i)SampleNeighbors(i) represents a dynamically sampled subset of neighbors for node ii at each iteration. This adaptability allows GraphSAGE to scale more efficiently compared to GCN, especially in scenarios where the graph is large or when computational resources are limited, maintaining scalability.

The structure for PyG code remains the same as for the GCN; we will just be using the GraphSAGE module from torch_geometric.nn.

To modify the previous code to use GraphSAGE instead of GCN, you need to make a few changes. Here are the lines you need to update:

  1. Replace the import statement for GCNConv with SAGEConv:

    from torch_geometric.nn import SAGEConv
  2. Update the GCN model class to use SAGEConv layers instead of GCNConv:

    # Define the GraphSAGE model
    class GraphSAGE(torch.nn.Module):
    def __init__(self, in_channels, hidden_channels,
    out_channels):
    super(GraphSAGE, self).__init__()
    self.conv1 = SAGEConv(in_channels, hidden_channels)
    self.conv2 = SAGEConv(hidden_channels, out_channels)
    def forward(self, x, edge_index):
    x = self.conv1(x, edge_index)
    x = F.relu(x)
    x = F.dropout(x, training=self.training)
    x = self.conv2(x, edge_index)
    return F.log_softmax(x, dim=1)
  3. Update the model creation line to use the GraphSAGE model instead of GCN:

    # Create an instance of the GraphSAGE model
    model = GraphSAGE(in_channels, hidden_channels, out_channels)

With these changes, the code will now use the GraphSAGE model instead of GCN. The rest of the code, including loading the dataset, training, and evaluation, remains the same.

Figure 4.2 – GraphSAGE network leveraging neighborhood sampling

Figure 4.2 – GraphSAGE network leveraging neighborhood sampling

At times, it is a good idea to assign different weights to neighbors based on their relevance to a particular node. We will now look at GATs, which borrow the concept of attention from language models.

GATs are an extension of GCNs that incorporate an attention mechanism to assign different weights to neighboring nodes based on their relevance. While GCNs apply a fixed aggregation function to combine the features of neighboring nodes, GATs allow for a more flexible and adaptive approach by learning the importance of each neighbor during the aggregation process. The core of GATs is the attention network.

An attention network, often referred to as an attention mechanism or attention model, is a powerful concept in machine learning and artificial intelligence, particularly in the field of neural networks. It’s inspired by how human attention works – focusing on specific parts of input data while processing information.

An attention mechanism allows the model to dynamically focus on different parts of the input data, assigning varying degrees of importance or attention to each part. This enables the model to weigh the relevance of different inputs when making predictions or decisions.

Attention networks are commonly used in tasks involving sequential data, such as natural language processing (NLP) tasks such as machine translation, text summarization, and sentiment analysis. In these tasks, the model needs to process sequences of words or tokens and understand the contextual relationships between them. By using attention mechanisms, the model can effectively capture long-range dependencies and attend to relevant parts of the input sequence.

Here’s how an attention mechanism is leveraged in graph learning:

  • In GATs, the attention mechanism is used to compute attention coefficients between a node and its neighbors.
  • Attention coefficients represent the importance of each neighbor’s features to the target node.
  • The attention mechanism is typically implemented using an MLP or a single-layer neural network.
  • Attention coefficients are computed based on the learned weights of the attention mechanism and the features of the target node and its neighbors.

Let’s look at how we can compute the attention coefficient in a graph setting.

For each node, the attention coefficients are computed for all its neighbors. The attention coefficient between node ii and its neighbor jjis calculated as follows:

αij=exp⁡(LeakyReLU(WT⋅[hi∥hj]))(∑k=1nexp⁡(LeakyReLU(WT⋅[hi∣hk])))α_{ij}=\frac{\exp (LeakyReLU(W^{T}\cdot [h_{i}\|h_{j}]))}{(\sum _{k=1}^{n}\exp (LeakyReLU(W^{T}\cdot [h_{i}|h_{k}])))}
  • ∥\| is the concatenation operation, and LeakyReLULeakyReLU is the leaky ReLU activation function.
  • hih_{i} and hjh_{j} are the learned node embeddings for nodes ii and jj, respectively.
  • WW is a learnable attention weight vector that is shared across all nodes.

The attention coefficients are normalized using the softmax function to ensure they sum up to 1 for each node.

Now that we understand how to compute attention coefficients, let’s see how these are utilized in the aggregation step of a GNN.

Once the attention coefficients are computed, the features of the neighboring nodes are aggregated using a weighted sum.

The aggregated features for node ii are calculated as follows:

hi′=σ(∑jϵNiαij∗hj)h_{i}^{'}=σ(\sum _{jϵN_{i}}^{}α_{ij}*h_{j})

Here,σσ is a non-linear activation function, such as ReLU. The aggregated features hi′h_{i}^{'} represent the updated representation of nodeii after considering the importance of its neighbors.

  Figure 4.3 – Multi-head attention (with K = 3 heads) by node 1 on its neighborhood

Figure 4.3 – Multi-head attention (with K = 3 heads) by node 1 on its neighborhood

To capture multiple aspects of the relationships between two nodes, we can leverage the concept of multi-head attention.

In GNNs, multi-head attention can be applied to learn representations of nodes as an extension of vanilla attention. Each “head” can be seen as a different perspective or attention mechanism applied to a node’s neighborhood. By running multiple heads in parallel, the GNN can capture diverse aspects of the node’s local graph structure and feature space. This allows the model to aggregate information from neighboring nodes in multiple ways, enhancing its ability to learn informative node representations that incorporate various patterns and relationships within the graph.

There are several notable aspects to keep in mind for multi-head attention:

  • GATs can employ multi-head attention to capture different aspects of the node relationships.
  • In multi-head attention, multiple attention mechanisms are used in parallel, each with its own set of learnable parameters.
  • The output features from each attention head are concatenated or averaged to obtain the final node representations.
  • Multi-head attention allows the model to learn diverse patterns and capture different types of dependencies between nodes.

At times, a single attention layer might be unable to capture complex relationships in a graph. Stacking multiple layers can help improve the learning space.

We can also use multiple GAT layers, similar to GCNs:

  • Like GCNs, GAT layers can be stacked to capture higher-order dependencies and learn more abstract representations of the graph.
  • In each layer, the updated node representations from the previous layer serve as input to the next layer.
  • The final node representations obtained after multiple GAT layers can be used for downstream tasks such as node classification or graph classification.

GATs seamlessly combine the advantages of an adaptive receptive field and an interpretable attention mechanism, making them powerful tools for processing graph-structured data. The adaptive receptive field of GATs allows nodes to dynamically adjust their focus on relevant neighbors during information aggregation. Importantly, GATs provide interpretable attention coefficients, enabling a clear understanding of the model’s decision-making process. The transparency in attention weights allows for intuitive insights into which neighbors contribute significantly to a node’s representation, fostering interpretability and facilitating model debugging.

This combination of adaptability and interpretability makes GATs effective in capturing fine-grained local information while maintaining a global perspective, contributing to their success in various graph-based tasks.

Let’s look at the model code for GAT:

class GAT(torch.nn.Module):
def __init__(self, in_channels, hidden_channels,
out_channels, heads=8, dropout=0.6):
super(GAT, self).__init__()
self.conv1 = GATConv(
in_channels, hidden_channels,
heads=heads, dropout=dropout)
self.conv2 = GATConv(
hidden_channels * heads, out_channels,
heads=1, dropout=dropout)
def forward(self, x, edge_index):
x = self.conv1(x, edge_index)
x = F.elu(x)
x = F.dropout(x, training=self.training)
x = self.conv2(x, edge_index)
return F.log_softmax(x, dim=1)

In this code, the GAT model class is defined using two GATConv layers. The first layer has multiple attention heads specified by the heads parameter, while the second layer has a single attention head. The activation function used is the exponential linear unit (ELU) function.

Note that in the __init__ method of the GAT class, we multiply hidden_channels by heads when specifying the input channels for the second GATConv layer. This is because the output of the first layer has hidden_channels * heads dimensions due to the multiple attention heads.

In this chapter, we provided a comprehensive overview of graph-based deep learning models, starting with the fundamental concept of message passing and then delving into specific GNN architectures such as GCNs, GraphSAGE, and GATs.

Graph-based models rely on message passing, a key operation where nodes exchange information with neighbors to update their representations. GCNs perform convolutions on graphs, aggregating neighboring node information to learn node representations. GraphSAGE efficiently generates embeddings for large-scale graphs through neighborhood sampling. GATs integrate attention mechanisms, enabling nodes to assign varying importance weights to neighbors during message passing. These techniques enhance the capacity of graph-based models to capture complex relationships and patterns within data structures.

Building upon the foundational understanding of prevalent graph learning algorithms, we’ll explore the contemporary challenges confronting GNNs in the upcoming chapter.