Graph Neural Networks
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Many datasets are not tables, images or sequences but graphs: social networks, molecules, road networks, citation networks, knowledge graphs, interactions between users and products. A graph neural network (GNN) is a neural network that takes the graph structure as part of its input and learns representations of nodes, edges or whole graphs. This page is a short introduction: the data model, the message-passing idea that unifies most GNNs, the graph convolutional network, the main variants, the pitfalls, and the practical tooling.
The code targets Python 3.13 and PyTorch 2.15, and the library discussion targets PyTorch Geometric (PyG) 2.8. Examples were run on Python 3.13 with PyTorch 2.15 (CPU) and PyG 2.8.1 on 2026-11-01. The first example uses only PyTorch, so it runs without any graph library; the second shows the PyG equivalent. Background: Neural Network Fundamentals, Backpropagation & Automatic Differentiation and Math for Machine Learning for the matrix notation.
Graphs as data
A graph \(G = (V, E)\) has nodes \(V\) and edges \(E\). In machine learning it usually comes with:
-
Node features \(X \in \mathbb{R}^{ n \times d }\): one feature vector per node (a user profile, an atom type, a text embedding).
-
The adjacency matrix \(A \in \{0, 1\}^{ n \times n }\), where \(A_{ij} = 1\) if there is an edge from \(i\) to \(j\). Real graphs are sparse, so the structure is stored as an edge list or as a sparse matrix.
-
Optional edge features (a bond type, a transaction amount) and edge weights.
-
Optional labels at the node, edge or graph level.
Graphs can be directed or undirected, weighted or not, homogeneous (one node and edge type) or heterogeneous (several types, as in a knowledge graph). A graph is not a grid: nodes have no canonical order and a varying number of neighbours, so a convolution with a fixed-size kernel does not apply. A model must therefore be permutation equivariant (relabelling the nodes permutes the node outputs the same way) and, for graph-level outputs, permutation invariant.
The common task types are:
| Task | Example |
|---|---|
Node-level |
Classify papers in a citation network; detect fraudulent accounts; predict a protein’s function. |
Edge-level (link prediction) |
Recommend friends or products; predict missing facts in a knowledge graph; predict drug-target interactions. |
Graph-level |
Predict a molecule’s property; classify a program or a document structure. |
Generation |
Design molecules or networks (related to generative models). |
If the data is a table with relations expressed as foreign keys, a graph view is only worth the extra machinery when the relations carry signal that hand-built features (counts of neighbours, graph statistics such as degree or PageRank) do not. Try those features with a gradient-boosting model first, as in Tabular Data & Gradient Boosting.
Message passing
Almost every GNN is an instance of the message-passing framework. Each layer updates a node’s representation from the representations of its neighbours in three steps:
-
Message: each neighbour \(j\) of node \(i\) produces a message, possibly using the edge features.
-
Aggregate: the messages are combined with a permutation-invariant function (sum, mean, max or an attention-weighted sum).
-
Update: the node combines the aggregated message with its own previous state, usually through a learned transformation and a nonlinearity.
\[h_i^{ (k+1) } = \phi\left(h_i^{ (k) }, \; \bigoplus_{j \in \mathcal{N}(i)} \psi\left(h_i^{ (k) }, h_j^{ (k) }, e_{ij}\right)\right)\]
Here \(h_i^{ (k) }\) is the representation of node \(i\) after \(k\) layers, \(\mathcal{N}(i)\) is its neighbourhood, \(\bigoplus\) is the aggregation, and \(\psi\) and \(\phi\) are learned functions.
After one layer a node knows its 1-hop neighbourhood; after \(k\) layers, its \(k\)-hop neighbourhood (its receptive field). The number of layers is therefore the number of hops of context, and it is typically small (2 to 4). This is the graph analogue of the receptive field of a CNN (see Convolutional Neural Networks). A transformer is the special case where every token is connected to every other one (see Attention & Transformers).
The expressive power of message-passing GNNs is bounded by the Weisfeiler-Leman (1-WL) graph isomorphism test: two non-isomorphic graphs that 1-WL cannot tell apart receive the same representation. Sum aggregation is more expressive than mean or max (this is the argument behind GIN, the Graph Isomorphism Network), and richer models add positional or structural encodings.
Graph convolutional networks
The graph convolutional network (GCN) of Kipf and Welling is the simplest widely used GNN. With the self-loop-augmented adjacency \(\tilde{A} = A + I\) and its degree matrix \(\tilde{D}\), one layer computes:
\[H^{ (k+1) } = \sigma\left(\tilde{D}^{ -1/2 } \tilde{A} \tilde{D}^{ -1/2 } H^{ (k) } W^{ (k) }\right)\]
Reading the formula: \(H^{ (k) } W^{ (k) }\) is an ordinary linear layer applied to every node; multiplying by the normalised adjacency averages each node with its neighbours (and itself, thanks to the self-loop), weighting each neighbour by the inverse square root of the degrees so that high-degree nodes do not dominate. Stacking two layers with a ReLU between them and a softmax at the end gives the classic node-classification model.
The example is a full GCN in plain PyTorch, using a dense normalised adjacency so that it is easy to read. It trains on a small synthetic two-community graph (a stochastic block model) in a semi-supervised way: only a few nodes have labels, but every node takes part in the forward pass, so the unlabelled nodes contribute through the graph.
import torch
from torch import nn
import torch.nn.functional as F
torch.manual_seed(0)
# --- a synthetic graph: two communities of 40 nodes, dense inside, sparse between ---
n_per, n = 40, 80
labels = torch.tensor([0] * n_per + [1] * n_per)
same = labels[:, None] == labels[None, :]
prob = torch.where(same, torch.tensor(0.15), torch.tensor(0.01))
A = (torch.rand(n, n) < prob).float()
A = torch.triu(A, diagonal=1)
A = A + A.T # undirected, no self-loops yet
# weak node features: a noisy one-hot of the true class
X = F.one_hot(labels, 2).float() + 1.5 * torch.randn(n, 2)
def normalize_adjacency(A: torch.Tensor) -> torch.Tensor:
"""D^-1/2 (A + I) D^-1/2"""
A_hat = A + torch.eye(A.size(0))
deg = A_hat.sum(dim=1)
d_inv_sqrt = deg.pow(-0.5)
return d_inv_sqrt[:, None] * A_hat * d_inv_sqrt[None, :]
class GCNLayer(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
self.lin = nn.Linear(in_dim, out_dim)
def forward(self, A_norm, H):
return A_norm @ self.lin(H) # transform, then aggregate over neighbours
class GCN(nn.Module):
def __init__(self, in_dim, hidden, n_classes, dropout=0.5):
super().__init__()
self.l1 = GCNLayer(in_dim, hidden)
self.l2 = GCNLayer(hidden, n_classes)
self.dropout = dropout
def forward(self, A_norm, X):
h = F.relu(self.l1(A_norm, X))
h = F.dropout(h, p=self.dropout, training=self.training)
return self.l2(A_norm, h) # logits per node
A_norm = normalize_adjacency(A)
# semi-supervised split: 5 labelled nodes per class, the rest unlabelled
train_mask = torch.zeros(n, dtype=torch.bool)
train_mask[:5] = True
train_mask[n_per:n_per + 5] = True
test_mask = ~train_mask
model = GCN(in_dim=2, hidden=16, n_classes=2)
opt = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
for epoch in range(200):
model.train()
out = model(A_norm, X)
loss = F.cross_entropy(out[train_mask], labels[train_mask])
opt.zero_grad()
loss.backward()
opt.step()
model.eval()
with torch.no_grad():
pred = model(A_norm, X).argmax(dim=1)
print("train acc:", (pred[train_mask] == labels[train_mask]).float().mean().item())
print("test acc: ", (pred[test_mask] == labels[test_mask]).float().mean().item())
Source: Kipf and Welling: Semi-Supervised Classification with Graph Convolutional Networks and PyG: Introduction by Example (the same model written with PyG). Nothing here depends on external data, and the dense matrix product scales as \(n^2\), which is only acceptable for graphs of a few thousand nodes.
Because the test nodes are in the graph during training, this is transductive learning: the model never sees their labels but does see their features and edges. Inductive learning, where the model must generalise to nodes or graphs not seen at training time, needs a model that does not depend on the specific adjacency matrix, such as GraphSAGE or GAT below.
Variants
| Model | Idea | When to consider it |
|---|---|---|
GCN |
Symmetric-normalised neighbourhood averaging. |
A strong first baseline for homophilous graphs (neighbours tend to share labels). |
GraphSAGE |
Samples a fixed number of neighbours and aggregates them (mean, max or LSTM), concatenating with the node’s own state. Trains on mini-batches of sampled sub-graphs. |
Large graphs that do not fit in memory; inductive settings. |
GAT (graph attention) |
Learns an attention weight per edge instead of using fixed degree-based weights. |
When neighbours differ in importance; gives some interpretability through attention weights. |
GIN |
Sum aggregation followed by an MLP, as expressive as 1-WL. |
Graph-level tasks such as molecule property prediction. |
Edge-aware and relational models (R-GCN, GINE, message-passing networks with edge features) |
Messages depend on edge type or features. |
Knowledge graphs, molecules with bond types. |
Graph transformers |
Full or sparse attention over nodes with positional and structural encodings. |
When long-range interactions matter and the graph is small enough. |
For graph-level tasks a readout turns node representations into a single vector: sum, mean or max over nodes, or a learned attention pooling. For knowledge graphs, link prediction is often done with embedding models that score a triple (head, relation, tail), and graph-based retrieval for LLM applications is discussed in GraphRAG & Knowledge Graph Construction and Graph-Powered Recommendations.
Pitfalls
-
Over-smoothing. Each averaging layer makes neighbouring nodes more alike; after many layers, node representations converge and become indistinguishable. This is why GNNs are usually shallow, unlike CNNs. Residual connections, normalisation layers, jumping knowledge (concatenating the outputs of all layers) and dropping edges reduce the effect.
-
Over-squashing. Information from an exponentially growing neighbourhood must pass through fixed-size vectors, so long-range dependencies are lost through bottleneck edges. Graph rewiring and graph transformers target this.
-
Heterophily. GCN assumes connected nodes are similar. On graphs where neighbours tend to have different labels (some fraud or dating networks), a plain GCN can do worse than an MLP that ignores the edges. Always include a no-graph MLP baseline.
-
Evaluation leakage. In a transductive setting, features and edges of test nodes are visible during training, which is legitimate, but their labels must not be. For link prediction, the test edges must be removed from the message-passing graph; for temporal graphs, split by time, not at random (see Problem Framing & ML Projects and Model Evaluation & Validation).
-
Scale. Full-batch training stores the whole graph and all intermediate activations. For large graphs use neighbour sampling (GraphSAGE style), cluster-based sampling or sub-graph batching.
-
Hub nodes and degree bias. A few very high-degree nodes dominate sum aggregation; use normalisation or sampling.
-
Class imbalance and tiny label sets. Typical benchmark settings have a few dozen labelled nodes; results on those benchmarks, such as Cora, are small-sample and sensitive to the split. Use several seeds and the standard splits, and report the spread.
Tooling
PyTorch Geometric (PyG) is the most widely used library for GNNs on PyTorch. Version 2.8 is the one targeted here. It provides graph data structures (torch_geometric.data.Data with x, edge_index, edge_attr and y), mini-batching of many small graphs into one disconnected graph, datasets (Planetoid/Cora, TUDataset, OGB wrappers, molecular datasets), over a hundred convolution layers (GCNConv, SAGEConv, GATConv, GINConv, and others) and samplers for large graphs. It is installed with pip.
pip install torch_geometric
Optional extension packages (pyg-lib, torch-scatter, torch-sparse, torch-cluster) accelerate some operations and have wheels tied to a specific PyTorch and CUDA version; the core layers work without them on recent PyTorch. Check the installation page for the combination matching your PyTorch version before installing them.
import torch
import torch.nn.functional as F
from torch_geometric.datasets import Planetoid
from torch_geometric.nn import GCNConv
dataset = Planetoid(root="data/Planetoid", name="Cora")
data = dataset[0] # one graph: x, edge_index, y and boolean masks
class GCN(torch.nn.Module):
def __init__(self, in_dim, hidden, n_classes):
super().__init__()
self.conv1 = GCNConv(in_dim, hidden)
self.conv2 = GCNConv(hidden, n_classes)
def forward(self, x, edge_index):
x = F.relu(self.conv1(x, edge_index))
x = F.dropout(x, p=0.5, training=self.training)
return self.conv2(x, edge_index)
device = torch.accelerator.current_accelerator() or torch.device("cpu")
model = GCN(dataset.num_features, 16, dataset.num_classes).to(device)
data = data.to(device)
opt = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
for epoch in range(200):
model.train()
out = model(data.x, data.edge_index)
loss = F.cross_entropy(out[data.train_mask], data.y[data.train_mask])
opt.zero_grad()
loss.backward()
opt.step()
model.eval()
pred = model(data.x, data.edge_index).argmax(dim=1)
acc = (pred[data.test_mask] == data.y[data.test_mask]).float().mean()
print(f"test accuracy: {acc:.3f}")
Source: PyG: Introduction by Example.
Other libraries exist: the Deep Graph Library (DGL) for several backends, Spektral for Keras, and the TensorFlow GNN library. In 2026 the PyTorch ecosystem has the largest community and PyG is the default choice; consult the status of each project before adopting it for a long-lived system.
For a sense of how graph structure enters applications built around language models, such as retrieval from a knowledge graph, see GraphRAG & Knowledge Graph Construction; graph databases themselves are covered in Property Graph Model.
Common mistakes
-
Using a GNN when the graph carries no extra signal: always compare with an MLP on the node features and with a gradient-boosting model that has hand-built graph statistics.
-
Stacking many layers and losing accuracy to over-smoothing.
-
Forgetting self-loops or normalisation in a hand-written GCN, so node scale depends on degree.
-
Splitting nodes at random on a temporal or leakage-prone graph; for link prediction, leaving the test edges in the message-passing graph.
-
Reporting a single run on a small benchmark split.
-
Densifying a large adjacency matrix; use sparse formats or
edge_index.