Graph Neural Networks (GNN)

Graph neural networks learn from data whose structure is a graph — nodes connected by edges — rather than a grid (images) or a sequence (text). Molecules, social and citation networks, road maps, knowledge graphs, transaction networks and recommender interaction graphs all fit this shape. A GNN computes a vector representation for every node by repeatedly exchanging and aggregating information with its neighbors, so each embedding reflects both the node's own features and its local graph structure. The two most widely used layer types, GCN and GAT, each have their own deep-dive page.

This page sits under Deep Learning (DL).

Graph Convolutional Networks (GCN)

Symmetric-normalized neighbor averaging, Â H W, derived from spectral graph convolution.

Graph Attention Networks (GAT)

Learned, per-edge attention weights over neighbors with multi-head aggregation.

Self-Attention

A Transformer is attention over a fully connected graph of tokens — the link between GNNs and Transformers.


1. Graph Data and Representation

Graph G = (V, E) as Matrices A and X 12345 Adjacency A (5x5) 0 1 1 0 01 0 0 1 01 0 0 1 00 1 1 0 10 0 0 1 0 Features X (5 x d) In practice A is stored sparse, as an edge list: edge_index = [[1,1,2,3,4],[2,3,4,4,5]] (+ reverse edges)

A graph has a node set V and edge set E. Each node carries a feature vector (atom type, user profile, paper bag-of-words), stacked into X ∈ RN×d; edges may carry features too (bond type, transaction amount). Structure is the adjacency matrix A, which for real graphs is extremely sparse, so libraries store an edge list (COO format, edge_index of shape 2×|E|). Two properties shape everything else: graphs have no natural node ordering, and node degree varies widely. A GNN must therefore be permutation equivariant — relabeling nodes should relabel outputs identically — and must handle any number of neighbors.

2. Message Passing

One Message-Passing Layer for Node v u1u2u3 MESSAGEm = φ(h_u, h_v, e_uv) AGGREGATEsum / mean / max / attn UPDATEψ(h_v, agg) h_v' h_v(k+1) = ψ( h_v(k), AGG{ φ(h_v(k), h_u(k), e_uv) : u in N(v) } ) AGG must be permutation invariant; weights φ, ψ are shared by all nodes.

Almost every GNN fits the message passing framework (Gilmer et al., 2017). In each layer, every node collects messages from its neighbors, combines them with a permutation-invariant aggregator, and updates its own embedding with a small neural network. Weights are shared across nodes, exactly as convolution kernels are shared across pixels, so the model works on graphs of any size. After k layers a node's embedding depends on its k-hop neighborhood — the graph analogue of a receptive field. Most practical models use 2–4 layers.

Choice of aggregator matters: sum preserves degree information (important for counting substructures in molecules), mean normalizes it away (robust on graphs with highly varied degrees), max picks out salient neighbors, and attention learns per-neighbor weights.

3. Node, Edge and Graph Tasks

Three Prediction Levels Node levelclassify a node (fraud user) Edge levelpredict a missing link Graph levelreadout: is molecule toxic?

4. Layer Types

LayerAggregationNotes
GCNDegree-normalized sum with self-loopSimple, fast, strong baseline; fixed neighbor weights
GraphSAGEMean / max / LSTM over sampled neighbors, concatenated with selfNeighbor sampling scales to very large graphs; inductive
GATLearned attention weights per edgeHandles noisy or heterogeneous neighborhoods
GINSum followed by MLPAs expressive as the 1-WL test; good for graph classification
MPNN / edge-conditionedMessages depend on edge featuresChemistry, physics simulations
R-GCN / HGTSeparate weights per relation or node typeKnowledge graphs, heterogeneous graphs
Graph TransformersAttention over all nodes plus structural encodingsLong-range interactions; quadratic cost

5. PyTorch Geometric Example

Node classification on the Cora citation graph (2,708 papers, 7 topics) with a two-layer GCN. Swapping GCNConv for SAGEConv or GATConv is a one-line change.

import torch
import torch.nn.functional as F
from torch_geometric.datasets import Planetoid      # pip install torch_geometric
from torch_geometric.nn import GCNConv

data = Planetoid(root="data", name="Cora")[0]
print(data)   # Data(x=[2708, 1433], edge_index=[2, 10556], y=[2708], train_mask=..., ...)

class GNN(torch.nn.Module):
    def __init__(self, d_in, d_hid, n_cls):
        super().__init__()
        self.conv1 = GCNConv(d_in, d_hid)
        self.conv2 = GCNConv(d_hid, n_cls)
    def forward(self, x, edge_index):
        x = F.dropout(x, p=0.5, training=self.training)
        x = F.relu(self.conv1(x, edge_index))
        x = F.dropout(x, p=0.5, training=self.training)
        return self.conv2(x, edge_index)

model = GNN(data.num_features, 16, int(data.y.max()) + 1)
opt = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)

for epoch in range(200):
    model.train(); opt.zero_grad()
    out = model(data.x, data.edge_index)                 # full-graph forward
    F.cross_entropy(out[data.train_mask], data.y[data.train_mask]).backward()
    opt.step()

model.eval()
pred = model(data.x, data.edge_index).argmax(1)
acc = (pred[data.test_mask] == data.y[data.test_mask]).float().mean()
print(f"test accuracy {acc:.3f}")

For graph-level tasks, batch many small graphs with torch_geometric.loader.DataLoader and apply global_mean_pool(x, batch) before the classifier. DGL is the main alternative library.

6. Limits: Over-smoothing, Expressivity, Scale

7. Common Pitfalls

Graph Convolutional Networks (GCN)gnn Graph Attention Networks (GAT)gnn Convolutional Neural Networks (CNN)Sectionconvolution on a grid graph Self-Attentiontransformers Deep Learning (DL)Section