Level 3 In-Depth AI · Deep Learning
Graph Neural Networks
Neural networks for data made of things and connections between them, such as molecules, social networks, road maps and citations. Each node repeatedly gathers messages from its neighbours and updates itself.
- Level
- ●●●●● Intermediate
- Reading
- 14 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 14 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 14 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Graph Neural Networks
Read them roughly in this order. See it on the concept map →
Why it matters
A lot of the world's data doesn't fit in a grid or a sequence. A molecule is atoms joined by bonds. A social network is people joined by friendships. A road map is junctions joined by roads. A citation network is papers joined by references. A power grid, a supply chain, a knowledge base and the parts of a 3-D mesh are all the same kind of structure: things and the connections between them. Mathematicians call this a graph.
The networks of earlier chapters expect something rigid: a fixed-length vector, a pixel grid (Convolutional Neural Networks), or an ordered sequence (Recurrent Neural Networks). A graph has none of that. Nodes have different numbers of neighbours, there is no natural "first" node, and the same graph can be drawn and numbered in countless ways. A graph neural network (GNN) is a network built to respect that.
GNNs are used in real systems. Google Maps has used a GNN to predict travel times from the road graph. DeepMind's GraphCast (2023), a GNN running on a mesh covering the globe, produces 10-day weather forecasts that rival traditional numerical models. In 2020, MIT researchers used a message-passing network over molecular graphs to discover a new antibiotic candidate, halicin. Pinterest's PinSage recommended content using a graph of 3 billion nodes and 18 billion edges. Drug discovery, materials science, fraud detection, chip design and Recommender Systems all use them. And a The Transformer can itself be seen as a GNN on a graph where every token connects to every other.
The intuition
Think of how a rumour, or an opinion, spreads through a group of friends. Each round, everyone hears what their friends think and updates their own view. After one round you've been influenced by your direct friends. After two rounds, by your friends' friends, because their views have already reached your friends. After a few rounds, your view reflects your whole neighbourhood of the network.
A GNN does exactly this with vectors. Every node starts with a feature vector: an atom's element, a person's profile, a paper's words. In each layer, every node:
- collects messages from its neighbours (their current vectors, usually transformed by a learned weight matrix),
- aggregates them, by summing, averaging or taking the maximum, which works for any number of neighbours,
- updates its own vector by combining the aggregate with its old value.
This is message passing, the core of nearly every GNN. The same learned weights are used at every node, just as a CNN uses the same filter at every pixel. That's why a GNN can handle graphs of any size and shape.
Key idea A GNN layer lets every node gather information from its neighbours, using the same learned weights everywhere, and update its own vector. Stacking layers lets information travel hops across the graph.
How it works
Graphs as matrices
A graph has nodes and a set of edges, the connections between pairs of nodes. Edges can be directed (A cites B) or undirected (A and B are friends), and they can carry their own features (bond type, road length).
The structure is stored in the adjacency matrix , an matrix with if nodes and are connected and 0 otherwise. The node features are stacked into a matrix with one row per node. For the four-node graph in the figure (edges A–B, B–C, B–D, C–D) and one feature per node:
The degree of a node is its number of neighbours: here A has 1, B has 3, C and D have 2 each.
Multiplying adds up each node's neighbours' features. Row B gives . So "gather from neighbours" is just a matrix multiplication, which GPUs do very fast. Large real graphs are sparse (most pairs are not connected), so libraries store only the list of edges.
Order doesn't matter
The numbering of the nodes is arbitrary. Swap the labels of C and D and it is still the same graph. A sensible model must give the same answers, just reordered. Sum, mean and max all have this property, called permutation invariance: they don't care what order the neighbours come in. A function like "concatenate the neighbours' vectors in order" would not, which is why GNNs never do that.
A worked message-passing step
With a plain average over each node and its neighbours (the figure above):
- A:
- B:
- C:
- D:
The values have been smoothed across the graph. A, which was 1, has moved towards its neighbour B. B has moved towards the larger values around it. Including each node's own value (a self-loop) keeps it from being replaced entirely by its neighbours.
The graph convolutional network (GCN)
Thomas Kipf and Max Welling's graph convolutional network (2016) is the simplest widely used GNN layer. In words: add self-loops, average over neighbours with a careful normalisation, apply a learned linear map, then a nonlinearity:
- holds every node's vector at layer , one row per node. .
- is the adjacency matrix with self-loops added ( is the identity matrix).
- is the diagonal matrix of node degrees in . Multiplying by on both sides scales the message from node to node by . Without this, high-degree nodes would get huge sums, and messages from very popular nodes would dominate.
- is the layer's learned weight matrix, shared by all nodes.
- is a nonlinearity such as ReLU (Activation Functions).
In the four-node example, the degrees with self-loops are 2, 4, 3 and 3. Node B's new value (before and ) is . That is close to the plain average of 1.75. The difference is that messages from low-degree neighbours count a little more.
The name comes from the analogy with images: a CNN filter combines a pixel with its fixed grid of neighbours using shared weights, and a GCN layer combines a node with its variable set of neighbours using shared weights.
Depth = hops
One layer mixes information from direct neighbours. A second layer mixes the already-mixed vectors, so it reaches neighbours of neighbours. After layers, each node's vector depends on everything within hops, its receptive field in graph terms.
Unlike CNNs, GNNs usually stay shallow, often 2 to 4 layers. Stack too many and every node's vector becomes an average of nearly the whole graph, so all nodes start to look alike. This is over-smoothing. Another limit, over-squashing, appears when information from an exponentially growing neighbourhood must squeeze through a few edges into one fixed-size vector.
Attention on graphs (GAT)
A GCN weights each neighbour by a fixed formula based on degrees. The graph attention network (GAT, Veličković and colleagues, 2017) learns how much each neighbour should count, using Attention. For node and neighbour it computes a score from their two vectors and normalises the scores over all of 's neighbours with a softmax:
Here means "join the two vectors end to end" and is a learned vector that scores the pair. A friend who is very similar to you might get weight 0.6 and a distant acquaintance 0.05. As in Transformers, several attention heads are usually run in parallel.
Other designs
- GraphSAGE (Hamilton, Ying and Leskovec, 2017) samples a fixed number of neighbours per node, so it scales to huge graphs and handles new nodes it never saw in training.
- Message passing neural networks (Gilmer and colleagues, 2017) are a general framework in which messages can depend on both endpoints and on edge features such as bond type. They were introduced for predicting the properties of molecules.
- GIN (Xu and colleagues, 2018) showed that summing neighbours, rather than averaging or taking the max, makes a GNN as good at telling graphs apart as the classic Weisfeiler–Lehman test, which is also an upper limit for standard message passing.
What GNNs predict
| Task | Question | Example |
|---|---|---|
| Node classification | What kind of node is this? | Topic of a paper in a citation graph, whether an account is a bot |
| Link prediction | Should there be an edge here? | Friend suggestions, drug–target interactions, recommendations |
| Graph classification or regression | What is this whole graph like? | Is this molecule toxic? What is its solubility? |
For whole-graph tasks, a readout step pools all the node vectors into one, usually by summing or averaging (again permutation invariant), and a normal classifier takes it from there.
In code
A two-layer GCN written from scratch in PyTorch, on a synthetic graph with two communities of 50 nodes each. Links are common inside each community and rare between them. Each node also has a feature vector that is only a very noisy hint of its community. Only 6 of the 100 nodes are labelled, and the task is to classify the other 94. This is semi-supervised node classification, the setting of the original GCN paper.
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(0)
# A graph with two communities of 50 nodes: many links inside, few across
n = 100
community = torch.arange(n) // 50 # the true labels: 0 or 1
same = community[:, None] == community[None, :]
p = torch.where(same, torch.tensor(0.15), torch.tensor(0.01))
A = (torch.rand(n, n) < p).float().triu(1); A = A + A.T # symmetric adjacency matrix
X = F.one_hot(community, 2).float() + 1.5 * torch.randn(n, 2) # node features: very noisy hints
# GCN normalisation: add self-loops, then D^-1/2 (A + I) D^-1/2
A_hat = A + torch.eye(n)
d = A_hat.sum(1)
A_norm = A_hat / torch.sqrt(d[:, None] * d[None, :])
class GCN(nn.Module):
def __init__(self, use_graph):
super().__init__()
self.l1, self.l2, self.use_graph = nn.Linear(2, 16), nn.Linear(16, 2), use_graph
def forward(self, X):
P = A_norm if self.use_graph else torch.eye(n) # "no graph" = ordinary MLP
h = F.relu(P @ self.l1(X)) # layer 1: transform, then average neighbours
return P @ self.l2(h) # layer 2: same again
train_idx = torch.tensor([0, 1, 2, 50, 51, 52]) # only 6 labelled nodes!
test_idx = torch.tensor([i for i in range(n) if i not in train_idx.tolist()])
for use_graph in (False, True):
torch.manual_seed(1)
model = GCN(use_graph)
opt = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
for epoch in range(200):
loss = F.cross_entropy(model(X)[train_idx], community[train_idx])
opt.zero_grad(); loss.backward(); opt.step()
acc = (model(X)[test_idx].argmax(1) == community[test_idx]).float().mean().item()
print(f"{'GCN' if use_graph else 'MLP (no edges)'}: accuracy on the 94 unlabelled nodes {acc:.3f}")
print("edges:", int(A.sum().item() / 2), " inside communities:", int((A * same).sum().item() / 2))
# MLP (no edges): accuracy on the 94 unlabelled nodes 0.670
# GCN: accuracy on the 94 unlabelled nodes 0.947
# edges: 378 inside communities: 347
Exactly the same model, with and without the two A_norm @ multiplications. Looking at each node alone, the noisy features give 67%. Averaging over neighbours, most of which share the node's community, cancels much of the noise: 95%.
For real projects, use a library that handles sparse graphs, batching of many small graphs and dozens of layer types. PyTorch Geometric is the most popular. Its GCNConv layer does the normalisation and sparse multiplication for you. Not run here, since it needs pip install torch_geometric:
import torch
import torch.nn.functional as F
from torch_geometric.nn import GCNConv
class GCN(torch.nn.Module):
def __init__(self, in_dim, hidden, classes):
super().__init__()
self.conv1 = GCNConv(in_dim, hidden)
self.conv2 = GCNConv(hidden, classes)
def forward(self, x, edge_index): # edge_index: 2 x num_edges tensor of (source, target) pairs
x = F.relu(self.conv1(x, edge_index))
return self.conv2(x, edge_index)
Common pitfalls
- Over-smoothing from too many layers. If accuracy drops as you add layers, you are probably averaging away the differences between nodes. Two or three layers is a good default. Residual Connections and normalisation help if you need more.
- Forgetting self-loops or normalisation. Without self-loops a node forgets its own features. Without degree normalisation, high-degree hubs blow up the scale of their vectors.
- Leaking edges in link prediction. If the edges you want to predict are still in the graph the model sees during training, it can simply look them up. Remove test edges from the message-passing graph.
- Assuming neighbours are similar. GCNs work best when connected nodes tend to share labels (homophily, as in our communities). In graphs where connections join different kinds of nodes, such as buyers and sellers, plain averaging can hurt. Attention or keeping a node's own vector separate helps.
- Treating a big graph like a small one. A dense adjacency matrix for a million nodes needs a trillion entries. Use sparse edge lists and neighbour sampling (GraphSAGE-style) or mini-batching of subgraphs.
Watch out In node classification, training and test nodes live in the same graph and pass messages to each other. Information about test nodes' features (though not their labels) flows into training. That is fine for the semi-supervised setting, but it means results don't automatically carry over to new, unseen graphs. Evaluate on separate graphs if that is how you will use the model.
Where it leads
- Attention and The Transformer: self-attention is message passing on a fully connected graph, with attention weights as learned edge strengths.
- Recommender Systems: user–item graphs and link prediction.
- Word Embeddings: node embeddings such as DeepWalk and node2vec apply skip-gram to random walks on a graph.
- Self-Supervised Learning: graph models are often pretrained by masking node features or contrasting views of a graph.
- Convolutional Neural Networks: the special case where the graph is a regular grid of pixels.
A bit of history
Neural networks on graphs go back to Marco Gori, Franco Scarselli and colleagues, who proposed "The Graph Neural Network Model" in the mid-2000s (journal version 2009). Their model passed messages until the node states stopped changing. In 2013–2016, Joan Bruna, Michaël Defferrard and others defined convolutions on graphs through spectral graph theory. Kipf and Welling simplified this in 2016 into the GCN, a short formula that was fast and effective and set off an explosion of interest. GraphSAGE, the message-passing framework of Gilmer and colleagues, and graph attention networks followed in 2017. Libraries such as PyTorch Geometric and DGL (2019) made GNNs routine. In 2021 Michael Bronstein, Joan Bruna, Taco Cohen and Petar Veličković described CNNs, GNNs and Transformers as instances of one framework, "geometric deep learning", built on the symmetries of the data.
Try it
- By hand: run a second round of plain averaging on the four-node example, starting from 0.5, 1.75, 2, 2. What happens to the spread of the values? This is over-smoothing in miniature.
- In the code, change the cross-community link probability from 0.01 to 0.10, so the graph no longer matches the communities. What happens to the GCN's advantage?
- Add a third and fourth GCN layer, then eight. Does accuracy keep improving?
Hint for 1: A becomes , B becomes , and C and D become . The values are bunching together.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
A Gentle Introduction to Graph Neural Networks
Interactive article that builds up graphs, message passing and GNN design choices with playable diagrams.
Stanford CS224W: Machine Learning with Graphs
The standard university course on graph learning: node embeddings, GNNs, knowledge graphs and recommender systems, with slides and recorded lectures.
Semi-Supervised Classification with Graph Convolutional Networks
The simple graph convolution that launched modern graph neural networks.
Graph Attention Networks
GAT: neighbours are weighted by learned attention scores instead of a fixed degree-based formula.
Neural Message Passing for Quantum Chemistry
Unified many GNNs as message passing neural networks and applied them to predicting molecular properties.
PyTorch Geometric
The most widely used PyTorch library for GNNs: ready-made layers (GCN, GAT, GraphSAGE), datasets and mini-batching for graphs.
Graph Representation Learning
A concise textbook on node embeddings, GNNs and generative graph models; a free pre-publication PDF is on the site.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/graph-neural-networks.md