Graph Neural Network (GNN)
A family of models that learn a representation for each node by exchanging messages with its neighbours along the edges, combining node features with graph structure.
Overview
| Name | Graph Neural Network |
|---|---|
| Year introduced | 2009 |
| Researchers | Franco Scarselli, Marco Gori, Ah Chung Tsoi, Markus Hagenbuchner, Gabriele Monfardini |
| Original paper | The graph neural network model DOI |
| Data type | Graphs |
| Domains | Recommender systems, Fraud detection, Scientific computing, Social network analysis, Learning on graph data |
| Computational cost | Roughly proportional to the number of edges, $O(|E|d)$ per layer. |
| Data size | From one large graph (node classification) to thousands of small graphs (molecules). |
Problem it solves
Relational data (molecules, social networks, transactions) is neither a regular grid like an image nor a sequence like text, and its nodes have no fixed order.
Background and evolution
What came before: Multilayer Perceptron, Recursive Neural Networks
Core idea
In each layer, the node gathers messages from its neighbours with an aggregation function that is unaffected by the neighbours' order (sum, mean or max), then updates its representation. After $L$ layers the node's representation contains information from its neighbourhood up to distance $L$.
Interactive diagram
A simplified illustrative diagram with the dimensions of a small example, not a drawing matching every detail of the original implementation. Click any layer to see its role, dimensions and mathematical operation.
Select a layer in the diagram.
Components
| Component | Role |
|---|---|
| Input | A graph $G=(V,E)$ and node features $X\in\mathbb{R}^{N\times d}$ |
| Message Function | Computes a message for each edge |
| Aggregation | Sum/mean/max, unaffected by order |
| Update Function | Combines the aggregated message with the previous state |
| Readout | Global pooling when classifying the whole graph |
| Loss Function | Cross-entropy for nodes or graphs |
Equations
1. The message passing framework
| $h_v^{(t)}$ | Representation of node v at layer t |
| $\mathcal{N}(v)$ | Neighbours of v |
| $M_t$ | Message function |
| $U_t$ | Update function |
| $e_{uv}$ | Edge features |
2. Graph readout
| $R$ | An order-invariant aggregation function |
How it works, step by step
- Each node's state is initialised with its features.
- A message is computed on each edge.
- Each node gathers its neighbours' messages.
- The state is updated with a learned function.
- The steps repeat L times.
- A classifier is applied to the nodes or to the graph readout.
Strengths and limitations
Strengths
- It exploits the relational structure directly.
- Unaffected by node numbering (equivariant).
- Works on graphs of different sizes.
Limitations
- Over-smoothing as layers increase.
- Over-squashing of long-range relationships.
- Discriminative power bounded by the Weisfeiler–Lehman test for most models.
When to use it, and when not?
Good for
- Data with explicit relationships between entities.
Not suited for
- Data without clear relationships; building an artificial graph may add no information.
Applications
| Domain | Use |
|---|---|
| Learning on graph data | Classifying nodes, links and whole graphs. |
| Recommender systems | Recommender systems that represent users and items as a bipartite graph. |
| Scientific computing | Predicting molecular properties in computational chemistry. |
| Fraud detection | Fraud detection in financial transaction networks. |
| Social network analysis | Social network analysis and community detection. |
PyTorch code
A simplified teaching code sample that runs on small synthetic data, covering: imports, model definition, data, forward pass, loss, optimizer, training loop, evaluation and inference. It is not the paper's full implementation.
# Message Passing GNN (a simplified MPNN)
# A simplified educational example in PyTorch (not the paper's full original implementation): small synthetic data,
# runs on the CPU in seconds. The numbers it prints belong to this example only.
# 1) Import the libraries
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(0)
# 2) Define the model
class MPNNLayer(nn.Module):
"""Message = MLP(h_u, h_v), sum aggregation, update with a GRUCell."""
def __init__(self, d):
super().__init__()
self.msg = nn.Sequential(nn.Linear(2 * d, d), nn.ReLU())
self.upd = nn.GRUCell(d, d)
def forward(self, h, A):
src, dst = A.nonzero(as_tuple=True) # edges u→v
m = self.msg(torch.cat([h[src], h[dst]], dim=1)) # a message for each edge
agg = torch.zeros_like(h).index_add_(0, dst, m) # Σ of the incoming messages
return self.upd(agg, h)
class MPNN(nn.Module):
def __init__(self, d_in, d=32, n_classes=3, L=2):
super().__init__()
self.inp = nn.Linear(d_in, d)
self.layers = nn.ModuleList([MPNNLayer(d) for _ in range(L)])
self.out = nn.Linear(d, n_classes)
def forward(self, X, A):
h = torch.relu(self.inp(X))
for layer in self.layers:
h = layer(h, A)
return self.out(h)
# 3) Prepare the data
# A synthetic graph from a stochastic block model (SBM): 3 communities, more links inside than between
N, C, D = 150, 3, 8
y = torch.arange(N) % C
P = torch.where(y[:, None] == y[None, :], 0.12, 0.01)
A = (torch.rand(N, N) < P).float().triu(1); A = A + A.T # a symmetric adjacency matrix without loops
X = torch.randn(N, D) + 0.6 * F.one_hot(y, D).float() # weak-signal features; the structure helps
idx = torch.randperm(N); train_idx, test_idx = idx[:45], idx[45:] # only 30% labelled (semi-supervised)
model = MPNN(D)
# 4) Loss function and optimizer
loss_fn = nn.CrossEntropyLoss()
opt = torch.optim.Adam(model.parameters(), lr=1e-2, weight_decay=5e-4)
# 5) Training loop (full-batch: the whole graph at each step, with the loss on the labelled nodes only)
for epoch in range(80):
model.train()
out = model(X, A) # forward pass for all nodes
loss = loss_fn(out[train_idx], y[train_idx])
opt.zero_grad(); loss.backward(); opt.step()
if epoch % 20 == 0:
print(f"epoch {epoch:3d} loss={loss.item():.4f}")
# 6) Evaluation on the unlabelled nodes
model.eval()
with torch.no_grad():
pred = model(X, A).argmax(1)
print(f"test accuracy = {(pred[test_idx] == y[test_idx]).float().mean().item():.3f}")
# 7) Inference: the class of node 0
print("node 0 predicted community:", pred[0].item(), " true:", y[0].item())
This code was run on 2026-11-20 in 3.1 seconds (PyTorch (CPU), Python 3 – local build machine).
Sample output:
test accuracy = 0.800
Trainable parameters in the example: model = 17,219.
These results are for small synthetic data and few epochs, and only prove that the code runs; do not compare them with published results.
Try it and go deeper
- Graph Network Explorer
- Graph Neural Networks Lab Another section of the site
Related architectures
Graph Convolutional Network
Graph Convolutional Network (GCN)
A simple graph layer that takes a normalised average of the representations of a node and its neighbours and then applies a shared linear transformation; it is a first-o…
Graph Attention Network
Graph Attention Network (GAT)
It replaces GCN's fixed weights with learned attention coefficients for each edge, so each node decides how important each neighbour is, with multiple attention heads.
GraphSAGE
GraphSAGE
An inductive framework that learns aggregation functions over a sampled neighbourhood, so it can compute representations for new nodes the network did not see during tra…
Graph Isomorphism Network
Graph Isomorphism Network (GIN)
A GNN designed to reach the discriminative power of the Weisfeiler–Lehman test (1-WL), using sum aggregation and an MLP in the update.
Graph Transformer
Graph Transformer (GT)
Applying self-attention to the nodes of a graph with positional or structural encodings (such as Laplacian eigenvectors) so the model knows the graph's structure, going…
No results match the filters.
Research ideas
- Study over-squashing in financial transaction graphs and propose graph rewiring.
- Compare MPNN with Graph Transformers on small molecular graphs with statistical significance tests.
Starting suggestions, not confirmed research gaps; review the recent literature before adopting them.
Test your understanding
Why do GNNs use aggregation functions such as sum or mean?
Why? Nodes in a graph have no natural order, so the result must be the same for any order.
After 3 message passing layers, what is the farthest distance from which information reaches the node?
Why? Each layer widens the neighbourhood by one hop.
What is meant by over-smoothing?
Why? Repeated aggregation resembles diffusion, so it draws the representations together.
References
Scarselli, F., Gori, M., Tsoi, A. C., Hagenbuchner, M., & Monfardini, G. (2009). The graph neural network model. IEEE Transactions on Neural Networks, 20(1), 61–80. https://doi.org/10.1109/TNN.2008.2005605
Gilmer, J., Schoenholz, S. S., Riley, P. F., Vinyals, O., & Dahl, G. E. (2017). Neural message passing for quantum chemistry. International Conference on Machine Learning (ICML), PMLR 70, 1263–1272. https://arxiv.org/abs/1704.01212
Wu, Z., Pan, S., Chen, F., Long, G., Zhang, C., & Yu, P. S. (2021). A comprehensive survey on graph neural networks. IEEE Transactions on Neural Networks and Learning Systems, 32(1), 4–24. https://doi.org/10.1109/TNNLS.2020.2978386
