BasicGraph Neural Networks

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

NameGraph Neural Network
Year introduced2009
ResearchersFranco Scarselli, Marco Gori, Ah Chung Tsoi, Markus Hagenbuchner, Gabriele Monfardini
Original paperThe graph neural network model DOI
Data typeGraphs
DomainsRecommender systems, Fraud detection, Scientific computing, Social network analysis, Learning on graph data
Computational costRoughly proportional to the number of edges, $O(|E|d)$ per layer.
Data sizeFrom 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

  1. 2009

    Scarselli and colleagues introduced the original GNN model, based on the fixed point of a transition function. [ref]

  2. 2017

    Gilmer and colleagues unified the models under the message passing framework (MPNN). [ref]

  3. 2021

    A comprehensive survey of GNN types and their applications. [ref]

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$.

Example: In a bank transaction network, a new account that deals often with fraudulent accounts will get a representation close to theirs after two layers, even if its individual features look normal.

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

ComponentRole
InputA graph $G=(V,E)$ and node features $X\in\mathbb{R}^{N\times d}$
Message FunctionComputes a message for each edge
AggregationSum/mean/max, unaffected by order
Update FunctionCombines the aggregated message with the previous state
ReadoutGlobal pooling when classifying the whole graph
Loss FunctionCross-entropy for nodes or graphs

Equations

1. The message passing framework

$$m_v^{(t+1)}=\sum_{u\in\mathcal{N}(v)} M_t\!\left(h_v^{(t)},h_u^{(t)},e_{uv}\right),\qquad h_v^{(t+1)}=U_t\!\left(h_v^{(t)},m_v^{(t+1)}\right)$$

Symbols
$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
Dimensions
$h_v\in\mathbb{R}^{d}$
Numerical example
A node with two neighbours whose representations are $(1,0)$ and $(0,2)$, with an identity message: $m_v=(1,2)$.
Relation to the architecture
This is the general form that GCN, GAT, GIN and others specialise.

2. Graph readout

$$h_G=R\!\left(\{h_v^{(T)}\mid v\in V\}\right)$$

Symbols
$R$An order-invariant aggregation function
Dimensions
$h_G\in\mathbb{R}^{d}$
Numerical example
The mean of the representations of three nodes $(1,1),(3,1),(2,4)$ is $(2,2)$.
Relation to the architecture
Used to classify a molecule or a whole graph.

How it works, step by step

  1. Each node's state is initialised with its features.
  2. A message is computed on each edge.
  3. Each node gathers its neighbours' messages.
  4. The state is updated with a learned function.
  5. The steps repeat L times.
  6. 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

DomainUse
Learning on graph dataClassifying nodes, links and whole graphs.
Recommender systemsRecommender systems that represent users and items as a bipartite graph.
Scientific computingPredicting molecular properties in computational chemistry.
Fraud detectionFraud detection in financial transaction networks.
Social network analysisSocial 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.

Python (PyTorch)
# 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

Related architectures

Basic2017

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 Neural Networks

Intermediate2018

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.

Graph Neural Networks

Basic2017

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 Neural Networks

Intermediate2019

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 Neural Networks

Advanced2020

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…

Graph Neural NetworksSpecialized ArchitecturesTransformer Architectures

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

  1. Concept

    Why do GNNs use aggregation functions such as sum or mean?

  2. Concept

    After 3 message passing layers, what is the farthest distance from which information reaches the node?

  3. Concept

    What is meant by over-smoothing?

References

  1. 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

    DOIAutomatically verified via Crossref – 2026-11-20

  2. 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

    arXivAutomatically verified via OpenAlex/arXiv – 2026-11-20

  3. 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

    DOIAutomatically verified via Crossref – 2026-11-20