Skip to content

Module 21

Anurag Prasad edited this page Nov 9, 2026 · 9 revisions

Module 21 — Graph Neural Networks and Graph Convolutional Networks

⬅️ Module 20 · 🗺️ Curriculum · 🏠 Home · Module 22 ➡️

Level: Advanced · Prerequisites: Modules 01 (eigendecomposition), 07, 14 · Time: about 8–9 hours

On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading


Overview and learning goals

Molecules, social networks, road maps, knowledge bases and meshes are graphs: entities (nodes) connected by relations (edges), with no fixed ordering or grid. Graph neural networks (GNNs) generalise convolution and attention to such data by repeatedly letting each node aggregate information from its neighbours (message passing). This module derives the GCN layer from graph signal processing, covers GraphSAGE, GAT and GIN, and explains over-smoothing, expressivity and graph-level readout.

After this module you should be able to:

  • represent graphs with adjacency, degree and Laplacian matrices and state invariance/equivariance requirements;
  • derive the GCN propagation rule with self-loops and symmetric normalisation;
  • write the general message-passing framework and the GraphSAGE, GAT and GIN updates;
  • explain over-smoothing and the Weisfeiler–Lehman expressivity limit; pick pooling and tasks.

Beginner: the big picture

Each node starts with a feature vector. In every layer it asks its neighbours what they know, combines the answers with its own state, and updates. After $K$ layers a node's representation depends on its $K$-hop neighbourhood. Crucially, relabelling the nodes must not change the answer: a GNN must be permutation-equivariant (node outputs permute with the nodes) or, for whole-graph outputs, permutation-invariant.

flowchart LR
    N1["Neighbour h_j"] --> M["Message phi(h_i, h_j, e_ij)"]
    N2["Neighbour h_k"] --> M
    N3["Neighbour h_l"] --> M
    M --> AG["Aggregate: sum / mean / max / attention"]
    S["Self h_i"] --> U["Update psi(h_i, aggregated)"]
    AG --> U
    U --> NEW["New h_i"]
Loading

Core concepts and derivations

Graph notation and tasks

$G=(V,E)$ with adjacency matrix $A\in{0,1}^{n\times n}$, degree matrix $D=\mathrm{diag}(A\mathbf{1})$, node features $X\in\mathbb{R}^{n\times d}$. Tasks: node-level (classify users), edge-level (link prediction, recommendation), graph-level (molecular property). Inductive vs transductive settings (unseen graphs vs a fixed graph).

Permutation equivariance

For a permutation matrix $P$, a layer $F$ is equivariant if $F(PAP^\top,PX)=PF(A,X)$. Sum/mean/max aggregation over neighbours is order-independent, which gives this property automatically; a plain MLP on a flattened adjacency matrix would not.

Graph Laplacian and spectral view

$L=D-A$ is PSD (Module 01) because $\mathbf{x}^\top L\mathbf{x}=\sum_{(i,j)\in E}(x_i-x_j)^2$ — it measures non-smoothness of a node signal. The normalised Laplacian $L_{sym}=I-D^{-1/2}AD^{-1/2}=U\Lambda U^\top$ has eigenvalues in $[0,2]$; the eigenvectors are graph Fourier modes (low eigenvalue = smooth). A spectral filter $g_\theta(L)\mathbf{x}=Ug_\theta(\Lambda)U^\top\mathbf{x}$ is expensive ($O(n^2)$, requires eigendecomposition). ChebNet (Defferrard et al. 2016) uses polynomials of $L$, which are $K$-localised and avoid the eigendecomposition.

GCN: derivation and propagation rule

Kipf & Welling (2017) take a first-order Chebyshev filter ($K=1$) with a single shared parameter, giving $\theta(I+D^{-1/2}AD^{-1/2})\mathbf{x}$. Since $I+D^{-1/2}AD^{-1/2}$ has eigenvalues in $[0,2]$ — repeated application causes exploding/vanishing — they apply the renormalisation trick: $\tilde A=A+I$ (self-loops), $\tilde D=\mathrm{diag}(\tilde A\mathbf{1})$,

$$ H^{(\ell+1)}=\sigma!\Bigl(\hat A,H^{(\ell)}W^{(\ell)}\Bigr),\qquad\hat A=\tilde D^{-1/2}\tilde A\tilde D^{-1/2},\quad\text{i.e.}\quad \mathbf{h}_i'=\sigma\Bigl(\sum_{j\in\mathcal{N}(i)\cup{i}}\frac{1}{\sqrt{\tilde d_i\tilde d_j}}W^\top\mathbf{h}_j\Bigr). $$

Each layer is a feature transform $HW$ (as in an MLP) followed by neighbourhood smoothing $\hat A(\cdot)$. The self-loop lets a node keep its own information; symmetric normalisation stops high-degree nodes from dominating.

Message passing neural networks

General framework (Gilmer et al. 2017):

$$ \mathbf{m}_i^{(\ell)}=\mathrm{AGG}_{j\in\mathcal{N}(i)}\ \phi^{(\ell)}\bigl(\mathbf{h}_i^{(\ell)},\mathbf{h}_j^{(\ell)},\mathbf{e}_{ij}\bigr),\qquad\mathbf{h}_i^{(\ell+1)}=\psi^{(\ell)}\bigl(\mathbf{h}_i^{(\ell)},\mathbf{m}_i^{(\ell)}\bigr). $$

GraphSAGE and neighbourhood sampling

GraphSAGE (Hamilton et al. 2017) learns an inductive aggregator: $\mathbf{h}_i'=\sigma\bigl(W,[\mathbf{h}i,\Vert,\mathrm{AGG}{j\in\mathcal{S}(i)}\mathbf{h}_j]\bigr)$ with mean/LSTM/pooling aggregators over a sampled fixed-size neighbour set $\mathcal{S}(i)$, bounding memory for large graphs (mini-batching without loading the whole graph).

Graph attention networks

GAT (Veličković et al. 2018) learns neighbour weights:

$$ e_{ij}=\mathrm{LeakyReLU}\bigl(\mathbf{a}^\top[W\mathbf{h}_i\Vert W\mathbf{h}_j]\bigr),\quad\alpha_{ij}=\frac{\exp e_{ij}}{\sum_{k\in\mathcal{N}(i)}\exp e_{ik}},\quad\mathbf{h}_i'=\sigma\Bigl(\sum_{j\in\mathcal{N}(i)}\alpha_{ij}W\mathbf{h}_j\Bigr), $$

with multiple heads concatenated/averaged. It is self-attention (Module 14) masked by the graph; a Transformer is a GNN on a complete graph.

Expressivity: GIN and the Weisfeiler–Lehman test

Message-passing GNNs can distinguish graphs no better than the 1-WL colour-refinement test. GIN (Xu et al. 2019) attains this bound with an injective sum aggregator: $\mathbf{h}_i'=\mathrm{MLP}\bigl((1+\epsilon)\mathbf{h}i+\sum{j\in\mathcal{N}(i)}\mathbf{h}_j\bigr)$. Mean/max aggregators lose multiset information (e.g. cannot count neighbours). Higher-order GNNs, positional/structural encodings (Laplacian eigenvectors), and graph Transformers go beyond 1-WL.

Over-smoothing and over-squashing

Repeated $\hat A^K\mathbf{x}$ converges toward the leading eigenspace of $\hat A$ (eigenvalue 1, vector $\propto\tilde D^{1/2}\mathbf{1}$ on a connected graph), so node features become indistinguishable (Li et al. 2018). Remedies: residual/skip connections, normalisation, dropping edges (DropEdge), shallow models with wide neighbourhoods. Over-squashing: information from exponentially many distant nodes must pass through fixed-size vectors along bottlenecks.

Node features before and after repeated GCN propagation (over-smoothing)

Figure 21.1 — Random features on a 30-node ring with one chord, propagated by $\hat A$ (no weights/nonlinearity). Left: features flatten with more layers. Right: their spread (standard deviation) decays geometrically — over-smoothing. Original figure (figures/make_figs_2.py).

Pooling, readout and tasks

For graph-level prediction, readout $\mathbf{h}_G=\mathrm{READOUT}({\mathbf{h}_i})$ must be permutation-invariant: sum, mean, max, attention (Set2Set), or hierarchical pooling (DiffPool, top-$k$). Link prediction scores node pairs, e.g. $\sigma(\mathbf{h}_i^\top\mathbf{h}_j)$. Applications: molecules and drug discovery, recommender systems, traffic and physics simulation, knowledge graphs (relational GCNs).

Worked example

Path graph 1–2–3, $A=\begin{pmatrix}0&1&0\1&0&1\0&1&0\end{pmatrix}$. With self-loops the degrees are $\tilde d=(2,3,2)$, so $\hat A_{11}=\frac12$, $\hat A_{12}=1/\sqrt6=0.408$, $\hat A_{22}=\frac13$, $\hat A_{13}=0$. For scalar features $\mathbf{x}=(1,2,3)$ (take $W=1$):

$(\hat A\mathbf{x})_1=0.5\cdot1+0.408\cdot2=1.316$, $(\hat A\mathbf{x})_2=0.408\cdot1+0.333\cdot2+0.408\cdot3=2.300$, $(\hat A\mathbf{x})_3=0.408\cdot2+0.5\cdot3=2.316$.

Features $(1,2,3)\to(1.32,2.30,2.32)$: the spread has already shrunk — one step of smoothing.

Implementation

import numpy as np

def gcn_layer(A, H, W, act=lambda x: np.maximum(0, x)):
    At = A + np.eye(len(A)); d = At.sum(1)
    Ahat = At / np.sqrt(np.outer(d, d))               # D^{-1/2} (A+I) D^{-1/2}
    return act(Ahat @ H @ W)

A = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0.]])
print(gcn_layer(A, np.array([[1.], [2.], [3.]]), np.array([[1.]])).ravel())   # [1.316 2.300 2.316]
# PyTorch Geometric
from torch_geometric.nn import GCNConv, GATConv, global_mean_pool
conv1, conv2 = GCNConv(in_dim, 64), GCNConv(64, n_classes)
h = conv2(conv1(x, edge_index).relu(), edge_index)        # node classification

Advanced topics

  • Graph Transformers with structural/positional encodings (Laplacian PE, random-walk PE), GraphGPS.
  • Geometric deep learning: equivariance to rotations/translations (E(n)-GNNs, SchNet, tensor-field networks) for molecules and physics; the unifying "5G" blueprint (Bronstein et al. 2021).
  • Heterogeneous and temporal graphs, knowledge-graph embeddings (TransE, R-GCN).
  • Scalability: neighbour sampling, Cluster-GCN, GraphSAINT; precomputed propagation (SGC, SIGN).
  • Self-supervised graph learning (contrastive on graph views, masked node/edge prediction).
  • Oversquashing and rewiring (curvature-based), long-range benchmarks.

Pitfalls and best practices

  • Data leakage in link prediction: leaking test edges into message passing; split edges carefully.
  • Using too many GCN layers (over-smoothing) without residuals.
  • Forgetting self-loops or normalisation (feature scale grows with degree).
  • Evaluating on a single random split of small citation graphs (high variance).
  • Mean aggregation when degree/multiset information matters.

Conceptual questions and answers

Q1. Why must GNN layers be permutation-equivariant?

Node ordering is arbitrary; relabelling nodes must only relabel the outputs. Order-independent aggregation guarantees this.

Q2. Why add self-loops and normalise in GCN?

Self-loops include a node's own features in its update and stabilise the spectrum ($\hat A$'s eigenvalues lie in $(-1,1]$); symmetric normalisation prevents high-degree nodes from dominating sums.

Q3. What is the relation between GAT and a Transformer?

GAT is multi-head attention restricted to graph neighbours; a Transformer applies it over a complete graph of tokens.

Q4. Explain over-smoothing.

Repeated neighbourhood averaging acts like low-pass filtering; with many layers all nodes of a connected component converge to nearly identical features, destroying discriminative information.

Q5. What does 1-WL expressivity mean?

Standard message-passing GNNs cannot distinguish graphs that colour refinement cannot, e.g. some regular graphs; GIN with sum aggregation achieves exactly this bound.

Q6. Why does GraphSAGE sample neighbours?

Neighbourhood size grows exponentially with depth; sampling a fixed number bounds memory/compute per node, enabling mini-batch training and inductive generalisation.

Q7. What property must a graph readout satisfy?

Permutation invariance: sum, mean, max or attention-pooling of node embeddings.

Q8. What does the Laplacian quadratic form $\mathbf{x}^\top L\mathbf{x}$ measure?

$\sum_{(i,j)\in E}(x_i-x_j)^2$: total variation of the signal across edges — small for smooth signals.

Sources and further reading

  • Bruna, J., Zaremba, W., Szlam, A., & LeCun, Y. (2014). Spectral networks and locally connected networks on graphs. ICLR.
  • Defferrard, M., Bresson, X., & Vandergheynst, P. (2016). Convolutional neural networks on graphs with fast localized spectral filtering. NeurIPS.
  • Kipf, T. N., & Welling, M. (2017). Semi-supervised classification with graph convolutional networks. ICLR. arXiv:1609.02907.
  • Gilmer, J., et al. (2017). Neural message passing for quantum chemistry. ICML. arXiv:1704.01212.
  • Hamilton, W., Ying, Z., & Leskovec, J. (2017). Inductive representation learning on large graphs. NeurIPS.
  • Veličković, P., et al. (2018). Graph attention networks. ICLR. arXiv:1710.10903.
  • Xu, K., Hu, W., Leskovec, J., & Jegelka, S. (2019). How powerful are graph neural networks? ICLR. arXiv:1810.00826.
  • Li, Q., Han, Z., & Wu, X.-M. (2018). Deeper insights into graph convolutional networks for semi-supervised learning. AAAI.
  • Morris, C., et al. (2019). Weisfeiler and Leman go neural: higher-order graph neural networks. AAAI.
  • Bronstein, M. M., Bruna, J., Cohen, T., & Veličković, P. (2021). Geometric deep learning: grids, groups, graphs, geodesics, and gauges. arXiv:2104.13478.

⬅️ Module 20 · 🗺️ Curriculum · 🏠 Home · Module 22 ➡️

🎓 Deep Learning Hub

🏠 Home · 🗺️ Curriculum · 🧭 Learning paths

❓ Question bank · 📖 Glossary · 📚 References

Jump to module:

01 02 03 04 05 06 07 08 09 10 11 12

13 14 15 16 17 18 19 20 21 22 23 24

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally