◆ AI All-in-One

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
↗ Plan a path here

Read first

Neural NetworksMatrices and Matrix Multiplication

This leads to

—
The full path from zero — 14 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. Supervised, Unsupervised and Reinforcement Learning
  9. Gradient Descent
  10. Supervised Learning
  11. Linear Regression
  12. The Perceptron
  13. Logistic Regression
  14. Neural Networks
  15. 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:

  1. collects messages from its neighbours (their current vectors, usually transformed by a learned weight matrix),
  2. aggregates them, by summing, averaging or taking the maximum, which works for any number of neighbours,
  3. 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.

A1 B0 C4 D2 A0.5 B1.75 C2 D2 1 · neighbours send messages 2 · every node updates at once one layer node B, mean over itself and its neighbours: new value of B = (0 + 1 + 4 + 2) / 4 = 1.75 a real GNN layer first multiplies each feature vector by learned weights W, and applies a nonlinearity after averaging A: (1 + 0)/2 = 0.5 C: (4 + 0 + 2)/3 = 2 · D: (2 + 0 + 4)/3 = 2
Fig. 1 One round of message passing on a four-node graph, using a plain average. Node B receives the values of its neighbours A, C and D and averages them with its own: (0 + 1 + 4 + 2) / 4 = 1.75. Every node does the same at the same time.

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 kk layers lets information travel kk hops across the graph.

How it works

Graphs as matrices

A graph has nn 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 A\mathbf{A}, an n×nn \times n matrix with Aij=1A_{ij} = 1 if nodes ii and jj are connected and 0 otherwise. The node features are stacked into a matrix X\mathbf{X} 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:

A=[0100101101010110],X=[1042]\mathbf{A} = \begin{bmatrix} 0 & 1 & 0 & 0 \\ 1 & 0 & 1 & 1 \\ 0 & 1 & 0 & 1 \\ 0 & 1 & 1 & 0 \end{bmatrix}, \qquad \mathbf{X} = \begin{bmatrix} 1 \\ 0 \\ 4 \\ 2 \end{bmatrix}

The degree of a node is its number of neighbours: here A has 1, B has 3, C and D have 2 each.

Multiplying AX\mathbf{A}\mathbf{X} adds up each node's neighbours' features. Row B gives 1+4+2=71 + 4 + 2 = 7. 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: (1+0)/2=0.5(1 + 0) / 2 = 0.5
  • B: (0+1+4+2)/4=1.75(0 + 1 + 4 + 2) / 4 = 1.75
  • C: (4+0+2)/3=2(4 + 0 + 2) / 3 = 2
  • D: (2+0+4)/3=2(2 + 0 + 4) / 3 = 2

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:

H(l+1)=σ ⁣(D^−1/2 A^ D^−1/2 H(l) W(l))\mathbf{H}^{(l+1)} = \sigma\!\left(\hat{\mathbf{D}}^{-1/2}\, \hat{\mathbf{A}}\, \hat{\mathbf{D}}^{-1/2}\, \mathbf{H}^{(l)}\, \mathbf{W}^{(l)}\right)
  • H(l)\mathbf{H}^{(l)} holds every node's vector at layer ll, one row per node. H(0)=X\mathbf{H}^{(0)} = \mathbf{X}.
  • A^=A+I\hat{\mathbf{A}} = \mathbf{A} + \mathbf{I} is the adjacency matrix with self-loops added (I\mathbf{I} is the identity matrix).
  • D^\hat{\mathbf{D}} is the diagonal matrix of node degrees in A^\hat{\mathbf{A}}. Multiplying by D^−1/2\hat{\mathbf{D}}^{-1/2} on both sides scales the message from node jj to node ii by 1/didj1/\sqrt{d_i d_j}. Without this, high-degree nodes would get huge sums, and messages from very popular nodes would dominate.
  • W(l)\mathbf{W}^{(l)} is the layer's learned weight matrix, shared by all nodes.
  • σ\sigma 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 W\mathbf{W} and σ\sigma) is 04+14⋅2+44⋅3+24⋅3≈0+0.354+1.155+0.577=2.09\frac{0}{4} + \frac{1}{\sqrt{4 \cdot 2}} + \frac{4}{\sqrt{4 \cdot 3}} + \frac{2}{\sqrt{4 \cdot 3}} \approx 0 + 0.354 + 1.155 + 0.577 = 2.09. 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 kk layers, each node's vector depends on everything within kk hops, its receptive field in graph terms.

v node v after 1 layer v has heard from its direct neighbours after 2 layers … and from their neighbours too k layers = k hops; grey nodesfurther away are not reached yet
Fig. 2 After one GNN layer, node v has gathered information from its direct neighbours (orange). After two layers it also reflects their neighbours (blue). Nodes further away have not reached it yet.

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 ii and neighbour jj it computes a score from their two vectors and normalises the scores over all of ii's neighbours with a softmax:

αij=softmaxj ⁣(LeakyReLU ⁣(a⊤[Whi ∥ Whj])),hi′=σ ⁣(∑jαijWhj)\alpha_{ij} = \text{softmax}_j\!\left(\text{LeakyReLU}\!\left(\mathbf{a}^\top [\mathbf{W}\mathbf{h}_i \,\Vert\, \mathbf{W}\mathbf{h}_j]\right)\right), \qquad \mathbf{h}_i' = \sigma\!\Big(\sum_{j} \alpha_{ij} \mathbf{W}\mathbf{h}_j\Big)

Here ∥\Vert means "join the two vectors end to end" and a\mathbf{a} 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 n×nn \times n 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

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

  1. 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.
  2. 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?
  3. Add a third and fourth GCN layer, then eight. Does accuracy keep improving?

Hint for 1: A becomes (0.5+1.75)/2=1.125(0.5 + 1.75)/2 = 1.125, B becomes (1.75+0.5+2+2)/4=1.5625(1.75 + 0.5 + 2 + 2)/4 = 1.5625, and C and D become (2+1.75+2)/3≈1.92(2 + 1.75 + 2)/3 \approx 1.92. The values are bunching together.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. In a four-node graph with edges A–B, B–C, B–D and C–D, the features are A = 1, B = 0, C = 4, D = 2. After one round of plain averaging over each node and its neighbours (with self-loops), what is B's new value?

  2. You add more and more GCN layers and accuracy starts to fall. What is the likely cause?

  3. Why do GNNs aggregate neighbours with sum, mean or max rather than by concatenating their vectors in order?

  4. You train a GNN to suggest new friendships, but evaluation looks suspiciously perfect. What is the likely mistake?

  5. How does a graph attention network (GAT) differ from a GCN?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

A Gentle Introduction to Graph Neural Networks

Sanchez-Lengeling, Reif, Pearce & Wiltschko (Distill) · 2021 · Beginner · Free

Interactive article that builds up graphs, message passing and GNN design choices with playable diagrams.

Course

Stanford CS224W: Machine Learning with Graphs

Jure Leskovec (Stanford) · Intermediate · Free

The standard university course on graph learning: node embeddings, GNNs, knowledge graphs and recommender systems, with slides and recorded lectures.

Paper

Graph Attention Networks

Veličković et al. · 2017 · Advanced · Free

GAT: neighbours are weighted by learned attention scores instead of a fixed degree-based formula.

Tool

PyTorch Geometric

Matthias Fey and contributors · Intermediate · Free

The most widely used PyTorch library for GNNs: ready-made layers (GCN, GAT, GraphSAGE), datasets and mini-batching for graphs.

Book

Graph Representation Learning

William L. Hamilton · 2020 · Advanced · Free

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