Advanced Topics
Graph Neural Networks — Learning from Connections and Relationships
Explore graph neural networks (GNNs) for learning on structured data with complex relationships. Perfect for social networks, molecular analysis, and recommendation systems.
-
Message Passing — How nodes aggregate information from neighbors
-
Graph Convolutional Networks — The foundational GNN architecture
-
Graph Attention Networks — Learning which connections matter most
"Everything is connected, and those connections are where the real learning happens."
Graph Neural Networks — Complete Guide
GNNs learn from graph-structured data — social networks, molecules, knowledge graphs.
Why GNNs?
Graph Data Structure
Message Passing
Where:
-
= node v's representation
-
= neighbors of v
Message Passing Visualization
GCN (Graph Convolutional Network)
GCN Architecture
GNN Variants
GCN (Graph Convolutional Network):
-
Spectral-based
-
Averaging neighbor features
-
Simple and effective
GraphSAGE:
-
Sample neighbors (scalable)
-
Multiple aggregation functions
-
Inductive (works on new nodes)
GAT (Graph Attention Network):
-
Attention over neighbors
-
Learn which neighbors matter
-
More expressive than GCN
GNN Variants Comparison
Message Passing on a Four-Node Ring
Take the smallest graph worth computing by hand: a ring of four nodes A, B, C, D with edges A–B, B–C, C–D, D–A and a single scalar feature per node — A is 1, B is 2, C is 4, D is 8. With self-loops and mean aggregation, each layer replaces a node's value with the average of itself and its two neighbors.
| Node | Input | After layer 1 | After layer 2 |
|---|---|---|---|
| A | 1.000 | 3.667 | 3.444 |
| B | 2.000 | 2.333 | 3.556 |
| C | 4.000 | 4.667 | 3.778 |
| D | 8.000 | 4.333 | 4.222 |
| Spread (max minus min) | 7.000 | 2.333 | 0.778 |
Two properties fall straight out of the table. The mean never moves: the average of all four nodes is 3.75 before the first layer and 3.75 after it, which is exactly what a normalized mean aggregator preserves. The spread, meanwhile, shrinks by roughly a factor of three every layer, so by layer eight all four nodes sit within rounding distance of 3.75 and a node classifier has nothing left to separate. That is over-smoothing with a number attached: the same aggregation that shares useful information also erases the differences that make nodes classifiable.
import numpy as np
# four-node ring A-B-C-D-A, scalar feature per node
edges = np.array([[0, 1, 1, 2, 2, 3, 3, 0],
[1, 0, 2, 1, 3, 2, 0, 3]])
x = np.array([1.0, 2.0, 4.0, 8.0])
adj = np.eye(x.shape[0]) # self-loops keep a node's own feature
for src, dst in edges.T:
adj[src, dst] = 1.0
norm = adj / adj.sum(axis=1)[:, None] # mean over self plus neighbors
h = x.copy()
for layer in range(1, 9):
h = norm @ h
print(f"layer {layer:2d} mean={h.mean():.3f} spread={h.max() - h.min():.3f}")
Running that script shows the mean pinned at 3.75 while the spread falls from 7.000 to 2.333, 0.778, 0.259, and keeps dividing by three. Use it as a sanity check for any GNN implementation you write: if the mean drifts under mean aggregation, the normalization is wrong.
Aggregation Functions and How Deep to Go
The three aggregation operators answer different questions, and the choice is rarely revisited after the first baseline.
| Aggregation | What it preserves | Use it when | Watch out for |
|---|---|---|---|
| Mean | Scale and degree invariance | Neighbor features are comparable per hop, the usual default | Hub and leaf nodes become hard to tell apart after several layers |
| Sum | Cardinality and subgraph size | The task depends on counting motifs or graph size | Values explode on high-degree nodes without normalization |
| Max | Presence of a salient neighbor | One strong neighbor carries the signal | Discards everything else and is unstable on sparse graphs |
| Attention (GAT) | Learned per-edge weights | Neighbor reliability varies inside the same graph | Extra parameters and memory, still only one hop per layer |
Depth follows the same caution. Each layer widens the receptive field by one hop, so three layers let a node see three hops away — enough for a molecule where an atom's chemical role depends on neighbors three bonds distant. Most public node-classification benchmarks stop improving at two or three layers, and stacking further brings over-smoothing on one side and over-squashing on the other: information from a neighborhood that grows exponentially has to squeeze through a fixed-width vector, so distant evidence arrives as noise. Start with two layers and 64 hidden units, add a third only when the label demonstrably depends on three-hop structure, and when you need longer range reach for jump connections, residual links, or separate heads per hop instead of deeper stacks.
import torch
from torch_geometric.nn import GCNConv
class GCN(torch.nn.Module):
def __init__(self, in_channels, hidden, num_classes):
super().__init__()
self.conv1 = GCNConv(in_channels, hidden)
self.conv2 = GCNConv(hidden, hidden)
self.head = torch.nn.Linear(hidden, num_classes)
def forward(self, x, edge_index):
x = torch.relu(self.conv1(x, edge_index))
x = torch.nn.functional.dropout(x, p=0.5, training=self.training)
x = self.conv2(x, edge_index)
return self.head(x)
model = GCN(data.num_node_features, 64, data.num_classes)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
for epoch in range(200):
model.train()
optimizer.zero_grad()
logits = model(data.x, data.edge_index)
loss = torch.nn.functional.cross_entropy(
logits[data.train_mask], data.y[data.train_mask]
)
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
pred = model(data.x, data.edge_index).argmax(dim=1)
hit = (pred[data.test_mask] == data.y[data.test_mask]).sum()
print(f"test accuracy {int(hit) / int(data.test_mask.sum()):.3f}")
Scaling Training to Graphs That Do Not Fit in Memory
Full-batch training keeps the whole feature matrix and the normalized adjacency on the device. Four million edges at 256 dimensions is already about one billion multiply-adds for the aggregation term in a single forward pass, before the dense layers and before backpropagation, so transductive node classification at that size consumes a high-memory card on its own.
Neighbor sampling replaces the full neighborhood with a fixed fan-out. A two-layer model with fan-out list 10, 10 visits at most 100 sampled neighbors per node instead of every neighbor it has, which turns an unpredictable hub into a bounded mini-batch. Cluster-GCN partitions the graph and trains on one partition at a time; GraphSAINT samples a subgraph per step and rescales the loss to stay unbiased. The practical split: use full-batch below roughly a million edges, switch to sampling above it, and expect a low single-digit accuracy cost for the memory you get back.
The same choice decides whether a model is transductive or inductive. A GCN trained with every node of a fixed graph present at training time is transductive — it has no mechanism for a node that arrives tomorrow, because its embedding was never part of any message-passing step during training. GraphSAGE-style sampling aggregates features rather than stored embeddings, so unseen nodes get scored as soon as their features exist. That distinction decides the architecture for any live graph: fraud rings, new accounts, and freshly published papers all appear after training ends.
Key Takeaways
What to Learn Next
-> Neural Networks Fundamentals — Perceptrons to Deep Learning
Learn about neural networks fundamentals — perceptrons to deep learning.
-> Convolutional Neural Networks — Complete Guide for Vision
Learn about convolutional neural networks — complete guide for vision.
-> Transformers — Attention Is All You Need Complete Guide
Learn about transformers — attention is all you need complete guide.
-> Clustering — K-Means, DBSCAN, Hierarchical Complete Guide
Learn about clustering — k-means, dbscan, hierarchical complete guide.
-> Recommendation Systems — Collaborative and Content-Based Filtering
Learn about recommendation systems — collaborative and content-based filtering.
-> ML System Design — Architecture and Production Patterns
Learn about ml system design — architecture and production patterns.