Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Open In Colab Open In Kaggle

AI artwork for GNN, inspired by Vincent van Gogh and Rembrandt's styles

Figure: An AI artwork on GNN and weather forcasting created by GPT4, 2024

This notebook is designed to be run on Google Colab and we highly recommend clicking on the Google Colab badge above.

  1. To start, we will load a classic graph in network science, the Karate Club Network. Then we will offer the basic tutorial for NetworkX before exploring multiple graph statistics.

  2. With the help of the PyTorch Geometric tutorial, we will then work together to transform the graph structure into a PyTorch tensor, enabling machine learning applications.

  3. And we will finish the first learning algorithm on graphs: a node embedding model. For simplicity, our model here is simpler than classical algorithms applied in the research, such as DeepWalk or node2vec. But it’s still rewarding and challenging, as we will write it from scratch via PyTorch.

  4. Finally, we will implement one of the simplest GNN operators, the Graph Convolutional Networks (Kipf et al. (2017)). We hope you can use this 3-layers GCN to learn embeddings that will be useful to classify each node into its community within the Karate Club Network.

8.2.1 Graph Basics

To start, we will load a classic graph in network science, the Karate Club Network. We will explore multiple graph statistics for that graph.

NetworkX Tutorial

NetworkX is one of the most frequently used Python packages to create, manipulate, and mine graphs.

This tutorial is adapted from jdwittenauer’s NetworkX notebook.

You can explore more NetworkX functions through its documentation.

Setup

Defaulting to user installation because normal site-packages is not writeable
Collecting scipy
  Downloading scipy-1.18.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.metadata (62 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 0.0/62.4 kB ? eta -:--:--
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 62.4/62.4 kB 4.8 MB/s eta 0:00:00
Collecting networkx
  Downloading networkx-3.7-py3-none-any.whl.metadata (6.7 kB)
Collecting numpy<2.8,>=2.0.0 (from scipy)
  Downloading numpy-2.5.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.metadata (6.6 kB)
Downloading scipy-1.18.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (35.3 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 0.0/35.3 MB ? eta -:--:--
   ━━━━━━━╸━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 6.7/35.3 MB 203.9 MB/s eta 0:00:01
   ━━━━━━━━━━━━━━━━━━━━━╺━━━━━━━━━━━━━━━━━━ 18.9/35.3 MB 169.6 MB/s eta 0:00:01
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╺━━━━━━━━━ 26.9/35.3 MB 236.0 MB/s eta 0:00:01
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸ 35.3/35.3 MB 249.8 MB/s eta 0:00:01
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 35.3/35.3 MB 120.8 MB/s eta 0:00:0000:01
Downloading networkx-3.7-py3-none-any.whl (2.1 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.1/2.1 MB 161.5 MB/s eta 0:00:00
Downloading numpy-2.5.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (16.7 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 0.0/16.7 MB ? eta -:--:--
   ━━━━━━━━━━━━━━━━━━╸━━━━━━━━━━━━━━━━━━━━━ 7.9/16.7 MB 236.3 MB/s eta 0:00:01
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 16.7/16.7 MB 152.3 MB/s eta 0:00:00a 0:00:01
Installing collected packages: numpy, networkx, scipy
Successfully installed networkx-3.7 numpy-2.5.3 scipy-1.18.1
Graph

NetworkX provides several classes to store different types of graphs, such as directed and undirected graphs. It also provides classes to create multigraphs (both directed and undirected).

For more information, please refer to NetworkX graph types.

False
True
{'Name': 'Bar'}
Node

Nodes (with attributes) can be easily added to NetworkX graphs.

Node 0 has the attributes {'feature': 5, 'label': 0}
NodeDataView({0: {'feature': 5, 'label': 0}})
(0, {'feature': 5, 'label': 0})
(1, {'feature': 1, 'label': 1})
(2, {'feature': 2, 'label': 2})
G has 3 nodes
Edge

Similar to nodes, edges (with attributes) can also be easily added to NetworkX graphs.

Edge (0, 1) has the attributes {'weight': 0.5}
(0, 1)
(0, 2)
(1, 2)
G has 3 edges
Graph Visualization

NetworkX also provides tooling to conventiently visualize graphs.

<Figure size 640x480 with 1 Axes>
Node Degree and Neighbor
Node 1 has degree 2
Node 1 has neighbor 0
Node 1 has neighbor 2
Other Functionalities

NetworkX also provides plenty of useful methods to study graphs. Here is an example of getting the PageRank value of nodes (we will implement PageRank ourselves later in this notebook).

{0: 0.17857162031103999, 1: 0.32142837968896, 2: 0.32142837968896, 3: 0.17857162031103999}
<Figure size 640x480 with 1 Axes>

Exercise 1

Zachary’s karate club network

The Karate Club Network is a graph which describes a social network of 34 members of a karate club and documents links between members who interacted outside the club.

<Figure size 640x480 with 1 Axes>
Question 1: What is the average degree of the karate club network?
Average degree of karate club network is 0
Question 2: What is the average clustering coefficient of the karate club network?
Average clustering coefficient of karate club network is 0
Question 3: What is the PageRank value for node 0 (node with id 0) after one PageRank iteration?

Page Rank measures importance of nodes in a graph using the link structure of the web. A “vote” from an important page is worth more. Specifically, if a page ii with importance rir_i has did_i out-links, then each link gets ridi\frac{r_i}{d_i} votes. Thus, the importance of a Page jj, represented as rjr_j is the sum of the votes on its in links.

rj=∑i→jridi,r_j = \sum_{i \rightarrow j} \frac{r_i}{d_i},

where did_i is the out degree of node ii.

The PageRank algorithm (used by Google) outputs a probability distribution which represent the likelihood of a random surfer clicking on links will arrive at any particular page. At each time step, the random surfer has two options

  • With prob. β\beta, follow a link at random

  • With prob. 1−β1- \beta, jump to a random page

Thus, the importance of a particular page is calculated with the following PageRank equation:

rj=∑i→jβridi+(1−β)1Nr_j = \sum_{i \rightarrow j} \beta \frac{r_i}{d_i} + (1 - \beta) \frac{1}{N}

Please complete the code block by implementing the above PageRank equation for node 0.

Note: You can refer to more information from Stanford CS224W’s PageRank slides

The PageRank value for node 0 after one iteration is 0
Question 4: What is the (raw) closeness centrality for the karate club network node 5?

The equation for closeness centrality is c(v)=1∑u≠vshortest path length between u and vc(v) = \frac{1}{\sum_{u \neq v}\text{shortest path length between } u \text{ and } v}

The node 5 has closeness centrality 0

8.2.2 Graph to Tensor

We will then work together to transform the graph GG into a PyTorch tensor, so that we can perform machine learning over the graph.

PyTorch Geometric Tutorial

PyTorch Geometric (PyG) is an extension library for PyTorch. It provides useful primitives to develop Graph Deep Learning models, including various graph neural network layers and a large number of benchmark datasets.

Don’t worry if you don’t understand some concepts such as GCNConv, as it may not be immediately useful depending on your exact objectives.

This tutorial is adapted from PyG’s own “Introduction: Hands-on Graph Neural Networks” Colab by Matthias Fey.

You can explore more PyG functions through its documentation.

PyTorch has version 2.14.0+cu130
Installing dependencies

Execute the cell below to install PyTorch Geometric -- in case of issues, more information can be found on PyG’s installation page. Since PyG 2.3, the base package works standalone with just PyTorch, so no separate torch-scatter/torch-sparse wheels are needed for this notebook.

PyTorch tensor basics

Recently, deep learning on graphs has emerged to one of the hottest research fields in the deep learning community. Here, Graph Neural Networks (GNNs) aim to generalize classical deep learning concepts to irregular structured data (in contrast to images or texts) and to enable neural networks to reason about objects and their relations.

This tutorial will introduce you to some fundamental concepts regarding deep learning on graphs via Graph Neural Networks based on the PyTorch Geometric (PyG) library. PyTorch Geometric is an extension library to the popular deep learning framework PyTorch, and consists of various methods and utilities to ease the implementation of Graph Neural Networks.

We can generate PyTorch tensor with all zeros, ones or random values.

tensor([[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]])
tensor([[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]])
tensor([[0.1184, 0.2349, 0.1193, 0.4605],
        [0.3441, 0.8413, 0.3622, 0.9266],
        [0.6594, 0.3176, 0.3243, 0.0545]])
torch.Size([3, 4])

PyTorch tensor contains elements for a single data type, the dtype.

torch.float32
torch.int64
Dataset

Following Kipf et al. (2017), let’s dive into the world of GNNs by looking at a simple graph-structured and previous example that we used, the well-known Zachary’s karate club network. Here, we are interested in detecting communities that arise from the member’s interaction.

PyTorch Geometric provides an easy access to the dataset via the torch_geometric.datasets subpackage:

After initializing the KarateClub dataset, we first can inspect some of its properties. For example, we can see that this dataset holds exactly one graph, and that each node in this dataset is assigned a 34-dimensional feature vector (which uniquely describes the members of the karate club). Furthermore, the graph holds exactly 4 classes, which represent the community each node belongs to.

Let’s now look at the underlying graph in more detail:

Data

Each graph in PyTorch Geometric is represented by a single Data object, which holds all the information to describe its graph representation. We can print the data object anytime via print(data) to receive a short summary about its attributes and their shapes:

We can see that this data object holds 4 attributes: (1) The edge_index property holds the information about the graph connectivity, i.e., a tuple of source and destination node indices for each edge. PyG further refers to (2) node features as x (each of the 34 nodes is assigned a 34-dim feature vector), and to (3) node labels as y (each node is assigned to exactly one class). (4) There also exists an additional attribute called train_mask, which describes for which nodes we already know their community assigments. In total, we are only aware of the ground-truth labels of 4 nodes (one for each community), and the task is to infer the community assignment for the remaining nodes.

The data object also provides some utility functions to infer some basic properties of the underlying graph. For example, we can easily infer whether there exists isolated nodes in the graph (i.e. there exists no edge to any node), whether the graph contains self-loops (i.e., (v,v)∈E(v, v) \in \mathbb{E}), or whether the graph is undirected (i.e., for each edge (v,w)∈E(v, w) \in \mathbb{E} there also exists the edge (w,v)∈E(w, v) \in \mathbb{E}).

Edge Index

Next we’ll print the edge_index of our graph:

By printing edge_index, we can further understand how PyG represents graph connectivity internally. We can see that for each edge, edge_index holds a tuple of two node indices, where the first value describes the node index of the source node and the second value describes the node index of the destination node of an edge.

This representation is known as the COO format (coordinate format) commonly used for representing sparse matrices. Instead of holding the adjacency information in a dense representation A∈{0,1}∣V∣×∣V∣\mathbf{A} \in \{ 0, 1 \}^{|\mathbb{V}| \times |\mathbb{V}|}, PyG represents graphs sparsely, which refers to only holding the coordinates/values for which entries in A\mathbf{A} are non-zero.

We can further visualize the graph by converting it to the networkx library format, which implements, in addition to graph manipulation functionalities, powerful tools for visualization:

Exercise 2

Question 5: Get the edge list of the karate club network and transform it into torch.LongTensor. What is the torch.sum value of pos_edge_index tensor?
The pos_edge_index tensor has shape torch.Size([0])
The pos_edge_index tensor has sum value 0.0
Question 6: Please implement following function that samples negative edges. Then answer which edges (edge_1 to edge_5) are the negative edges in the karate club network?

“Negative” edges refer to the edges/links that do not exist in the graph. The term “negative” is borrowed from “negative sampling” in link prediction. It has nothing to do with the edge weights.

For example, given an edge (src, dst), you should check that neither (src, dst) nor (dst, src) are edges in the Graph. If these hold true, then it is a negative edge.

The neg_edge_index tensor has shape torch.Size([0])

8.2.3 Node Embedding Learning

Now, we will train our first learning algorithm on graphs: a node embedding model.

Setup

2.14.0+cu130

To write our own node embedding learning methods, we’ll heavily use the nn.Embedding module in PyTorch. Let’s see how to use nn.Embedding:

Sample embedding layer: Embedding(4, 8)

We can select items from the embedding matrix, by using Tensor indices

tensor([[-0.2403,  1.9851, -1.2138, -0.4394, -1.9430,  0.1105,  0.8507, -0.4609]],
       grad_fn=<EmbeddingBackward0>)
tensor([[-0.2403,  1.9851, -1.2138, -0.4394, -1.9430,  0.1105,  0.8507, -0.4609],
        [ 0.8211, -0.5164, -0.6000,  0.2412,  2.1013, -0.3248,  0.2221, -0.3931]],
       grad_fn=<EmbeddingBackward0>)
torch.Size([4, 8])
tensor([[1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.]], grad_fn=<EmbeddingBackward0>)

Exercise 3

Question 7: Following the below requirements, please create the node embedding matrix

Now, it’s your time to create node embedding matrix for the graph we have!

  • We want to have 16 dimensional vector for each node in the karate club network.

  • We want to initalize the matrix under uniform distribution, in the range of [0,1)[0, 1). We suggest you using torch.rand.

Question 8: Visualize the initial node embeddings

One good way to understand an embedding matrix, is to visualize it in a 2D space. Here, we have implemented an embedding visualization function for you. We first do PCA to reduce the dimensionality of embeddings to a 2D space. Then we visualize each point, colored by the community it belongs to.

Question 9: Training the embedding! What is the best performance you can get?

We want to optimize our embeddings for the task of classifying edges as positive or negative. Given an edge and the embeddings for each node, the dot product of the embeddings, followed by a sigmoid, should give us the likelihood of that edge being either positive (output of sigmoid > 0.5) or negative (output of sigmoid < 0.5).

Note that we’re using the functions you wrote in the previous questions, as well as the variables initialized in previous cells. If you’re running into issues, make sure your answers to questions 1-6 are correct.

Visualize the final node embeddings

Visualize your final embedding here! You can visually compare the figure with the previous embedding figure. After training, you should observe that the two classes are more evidently separated. This is a great sanitity check for your implementation as well.

8.2.4 Implementing Graph Neural Networks (GNNs)

After learning about PyG’s data handling, it’s time to implement our first Graph Neural Network!

For this, we will use one of the most simple GNN operators, the GCN layer (Kipf et al. (2017)).

PyG implements this layer via GCNConv, which can be executed by passing in the node feature representation x and the COO graph connectivity representation edge_index.

What is the output of a GNN?

The goal of a GNN is to take an input graph G=(V,E)G = (\mathbb{V}, \mathbb{E}) where each node vi∈Vv_i \in \mathbb{V} has an input feature vector Xi(0)X_i^{(0)}. What we want to learn is a function f→V×Rdf \to \mathbb{V} \times \mathbb{R}^d, a function that takes in a node and its feature vector, as well as the graph structure, and outputs an embedding, a vector that represents that node in a way that’s useful to our downstream task. Once we’ve mapped nodes and their initial features to their learned embeddings, we can use those embeddings to do a variety of different tasks including node-level, edge-level, or graph-level regression/classification.

In this notebook, we want to learn embeddings that will be useful to classify each node into its community.

With this, we are ready to create our first Graph Neural Network by defining our network architecture in a torch.nn.Module class:

Here, we first initialize all of our building blocks in __init__ and define the computation flow of our network in forward. We first define and stack three graph convolution layers. Each layer corresponds to aggregating information from each node’s 1-hop neighborhood (its direct neighbors), but when we compose the layers together, we are able to aggregate information from each node’s 3-hop neighborhood (all nodes up to 3 “hops” away).

In addition, the GCNConv layers reduce the node feature dimensionality to 2, i.e., 34→4→4→234 \rightarrow 4 \rightarrow 4 \rightarrow 2. Each GCNConv layer is enhanced by a tanh non-linearity.

After that, we apply a single linear transformation (torch.nn.Linear) that acts as a classifier to map our nodes to 1 out of the 4 classes/communities.

We return both the output of the final classifier as well as the final node embeddings produced by our GNN. We proceed to initialize our final model via GCN(), and printing our model produces a summary of all its used sub-modules.

Remarkably, even before training the weights of our model, the model produces an embedding of nodes that closely resembles the community-structure of the graph. Nodes of the same color (community) are already closely clustered together in embedding space, although the weights of our model are initialized completely at random, and we have not yet performed any training so far!

This leads to the conclusion that GNNs introduce a strong inductive bias, leading to similar embeddings for nodes that are close to each other in the input graph.

Exercise 4

Question 10: Training GCN on the Karate Club Network! What is the best performance you can receive?

Let’s now train our model! We will make use of a semi-supervised or transductive learning procedure: we simply train against a few labeled examples (data.train_mask selects the 4 labeled nodes, one for each community), but are allowed to make use of the complete input graph data.edge_index. This can be seen as a somewhat extreme case of semi-supervised learning, with very few labels available.

Training our model is very similar to any other PyTorch model. In addition to defining our network architecture, we define a loss criterion (here, CrossEntropyLoss) and initialize a stochastic gradient optimizer (here, Adam). After that, we perform multiple rounds of optimization, where each round consists of a forward and backward pass to compute the gradients of our model parameters w.r.t. to the loss derived from the forward pass. If you are not new to PyTorch, this scheme should appear familiar to you.

Complete the marked section of the training loop below to also track validation accuracy on the non-training nodes (~data.train_mask).

As one can see, our 3-layer GCN model manages to separate the communities pretty well and classify most of the nodes correctly.

Furthermore, we did this all with a few lines of code, thanks to the PyTorch Geometric library which helped us out with data handling and GNN implementations.