Overview
In a graph, a node's neighbours say a lot about it: papers cite papers on the same topic, and fraud accounts link to other fraud accounts. A graph neural network uses this by letting nodes exchange information along the edges. In each layer, every node collects the vectors of its neighbours, combines them with its own, and passes the result through a learned linear map. After one layer a node knows about its direct neighbours, and after two layers about neighbours of neighbours. The three layer types differ only in how the neighbours are combined: a normalised sum (GCN), a plain mean with a separate weight for the node itself (GraphSAGE), or a weighted sum with learned weights (GAT).
A short history
Franco Scarselli, Marco Gori and colleagues defined the graph neural network model in the 2000s, with the main paper appearing in 2009. The field grew quickly after Thomas Kipf and Max Welling published the graph convolutional network in 2017. In the same period GraphSAGE by William Hamilton, Rex Ying and Jure Leskovec added neighbour sampling for large graphs, and graph attention networks by Petar Veličković and colleagues let nodes weigh their neighbours.
How it works
- Represent the graph as an adjacency matrix, for example with
adjacency_from_edges, and give every node a feature vector. - First layer: for each node, aggregate the neighbours' feature vectors according to
layer_typeand apply the layer's weights. - Apply ReLU to get a hidden vector per node.
- Second layer: aggregate the hidden vectors of the neighbours in the same way, giving one score per class for every node.
- Apply softmax and compute the cross-entropy loss on the labelled nodes only.
- Backpropagate through both layers and update with Adam, using the full graph in every step.
Watch out for
- If connected nodes tend to have different labels, averaging over neighbours mixes the classes and hurts. Check that neighbours really are alike before using a GNN.
- Stacking many layers makes all node vectors in a connected region converge to similar values, called over-smoothing. Two layers, as here, is a common choice.
- A node with no edges gets no information from the graph. With GraphSAGE its neighbour mean is a zero vector, so its prediction rests on its own features.
- This template stores the adjacency as a dense matrix and trains full-batch, so memory grows with the square of the node count. It fits graphs of up to a few thousand nodes.
Use cases
When to use it
When the rows are connected and the connections carry signal: citation or social networks, fraud rings, molecules. Typical use is semi-supervised, with a few labelled nodes and many unlabelled ones.
In industry
- Social and content platforms
- Recommendation on a graph of users and items; Pinterest described PinSage, a GraphSAGE-style model, for this purpose in 2018.
- Payments
- Fraud detection: classifying accounts using the accounts, devices and merchants they are connected to.
- Chemistry and pharma
- Predicting properties of molecules by treating atoms as nodes and bonds as edges.
- Mapping
- Travel time estimation over road networks, where each road segment is influenced by its neighbours.
Choosing it: what must hold
- Data with explicit links between entities, stored as nodes and edges.
- Links that carry signal: connected nodes tend to share labels or influence each other.
- Features on the nodes, or enough structure to learn node embeddings.
When to choose something else
| If | Use instead |
|---|---|
| The rows have no meaningful links | An MLP or gradient boosted trees on the row features |
| The graph is a regular grid such as an image | A convolutional network (CNN) |
| The graph is a simple chain such as a sentence or time series | A GRU, an LSTM or a Transformer |
Math foundations
Normalised adjacency (GCN)
Self-loops are added so a node keeps its own features, and each edge is divided by the square roots of both endpoint degrees so that high-degree nodes do not dominate.
GCN layer
Multiplying by replaces each node's row by a weighted sum over itself and its neighbours. then maps it to the new width, as in an ordinary dense layer.
GraphSAGE layer (mean aggregator)
The node's own vector and the mean of its neighbours get separate weights, so the layer can treat the two differently.
GAT attention weights
Each neighbour gets a learned score that depends on both endpoints, and a softmax over the neighbourhood turns the scores into weights that sum to 1.
GAT layer
A weighted sum over the neighbourhood with the learned weights in place of fixed ones, so the node can listen more to some neighbours than others.
Loss on the labelled nodes
Cross-entropy over the nodes whose label is known. Unlabelled nodes still take part in the forward pass, so their features shape the predictions.
Symbols
- adjacency matrix: entry (i, j) is 1 when nodes i and j are connected
- diagonal degree matrix of A + I
- matrix of node vectors at layer l, one row per node
- the vector of node i
- weight matrix of a layer
- activation: ReLU after the first layer
- the set of neighbours of node i
- attention vectors of the GAT layer
- attention weight of neighbour j for node i
- the set of labelled nodes
- predicted probability of the true class of node i
Worked by hand
A path graph of three nodes, 0 to 1 to 2, with one feature each: . Compute one GCN aggregation for nodes 0 and 1. With self-loops the degrees are 2, 3 and 2.
Node 0 started at 1 and is pulled up to 1.72 by its neighbour's value of 3. Node 1 blends all three values. After a second layer node 0 would also feel node 2, which is two hops away.
Visual example
Loading the example.
Try this
- Choose Layer 1, then Layer 2, in the diagram and watch how far the chosen node's view of the graph reaches.
- Raise the feature noise to 2: single nodes become unreadable on their own, yet most are still classified from their neighbours.
- Pick node 1 or node 6, which sit on the bridge between the groups, and compare their weights under GCN and GAT.
Code sample
import numpy as np
from impl import GNN, adjacency_from_edges
from config import GNNConfig
edges = [(0, 1), (1, 2), (0, 2), (3, 4), (4, 5), (3, 5), (2, 3)] # two triangles joined by one edge
A = adjacency_from_edges(6, edges)
X = np.eye(6) # one-hot node features
y = np.array([0, 0, 0, 1, 1, 1])
labelled = np.array([True, False, False, False, False, True]) # only nodes 0 and 5 have labels
net = GNN(GNNConfig(layer_type="gcn", epochs=100)).fit(X, A, y, labelled)
print(net.predict(X, A)) # [0 0 0 1 1 1]Read the implementation (194 lines)
"""GNN: graph neural network for node classification, with GCN, GraphSAGE and GAT layers.
NumPy only, manual backpropagation, dense adjacency matrices (so it suits graphs of up to a few thousand
nodes). The network is two message-passing layers with a ReLU between them and a softmax on top; the loss is
cross-entropy on the labelled nodes only, which is the usual semi-supervised setting.
"""
from __future__ import annotations
import numpy as np
try:
from .config import GNNConfig
except ImportError: # run from the template's own folder
from config import GNNConfig
_SLOPE = 0.2 # negative slope of the LeakyReLU inside GAT attention
def adjacency_from_edges(n_nodes: int, edges, undirected: bool = True) -> np.ndarray:
"""Build a dense 0/1 adjacency matrix (n, n) from (source, target) pairs. A[i, j] = 1: i receives from j."""
A = np.zeros((n_nodes, n_nodes))
for i, j in edges:
A[i, j] = 1.0
if undirected:
A[j, i] = 1.0
return A
def gcn_norm(A: np.ndarray) -> np.ndarray:
"""Symmetric GCN normalisation with self-loops: D^-1/2 (A + I) D^-1/2. A: (n, n) -> (n, n)."""
A_hat = A + np.eye(len(A))
d = 1.0 / np.sqrt(A_hat.sum(axis=1))
return A_hat * d[:, None] * d[None, :]
def mean_norm(A: np.ndarray) -> np.ndarray:
"""Row-normalised adjacency: row i averages over the neighbours of i. Isolated nodes get a zero row."""
deg = A.sum(axis=1, keepdims=True)
return np.divide(A, deg, out=np.zeros_like(A, dtype=float), where=deg > 0)
class GCNLayer:
"""Z = A_norm H W + b (Kipf and Welling)."""
def __init__(self, n_in: int, n_out: int, rng: np.random.Generator) -> None:
self.params = {"W": rng.normal(0.0, np.sqrt(2.0 / (n_in + n_out)), size=(n_in, n_out)), "b": np.zeros(n_out)}
def forward(self, H: np.ndarray, A: np.ndarray) -> np.ndarray:
self.A_norm = gcn_norm(A)
self.AH = self.A_norm @ H
return self.AH @ self.params["W"] + self.params["b"]
def backward(self, dZ: np.ndarray) -> tuple[np.ndarray, dict]:
grads = {"W": self.AH.T @ dZ, "b": dZ.sum(axis=0)}
return self.A_norm.T @ (dZ @ self.params["W"].T), grads
class SAGELayer:
"""GraphSAGE with the mean aggregator: Z = H W_self + mean(neighbours of H) W_neigh + b."""
def __init__(self, n_in: int, n_out: int, rng: np.random.Generator) -> None:
s = np.sqrt(2.0 / (n_in + n_out))
self.params = {"W_self": rng.normal(0.0, s, size=(n_in, n_out)), "W_neigh": rng.normal(0.0, s, size=(n_in, n_out)),
"b": np.zeros(n_out)}
def forward(self, H: np.ndarray, A: np.ndarray) -> np.ndarray:
self.H, self.M = H, mean_norm(A)
self.MH = self.M @ H
return H @ self.params["W_self"] + self.MH @ self.params["W_neigh"] + self.params["b"]
def backward(self, dZ: np.ndarray) -> tuple[np.ndarray, dict]:
grads = {"W_self": self.H.T @ dZ, "W_neigh": self.MH.T @ dZ, "b": dZ.sum(axis=0)}
dH = dZ @ self.params["W_self"].T + self.M.T @ (dZ @ self.params["W_neigh"].T)
return dH, grads
class GATLayer:
"""Single-head graph attention.
P = H W; e_ij = LeakyReLU(P_i . a_src + P_j . a_dst) for j in N(i) and j = i;
alpha_i = softmax over those j; Z_i = sum_j alpha_ij P_j + b.
"""
def __init__(self, n_in: int, n_out: int, rng: np.random.Generator) -> None:
s = np.sqrt(2.0 / (n_in + n_out))
self.params = {"W": rng.normal(0.0, s, size=(n_in, n_out)), "a_src": rng.normal(0.0, s, size=n_out),
"a_dst": rng.normal(0.0, s, size=n_out), "b": np.zeros(n_out)}
def forward(self, H: np.ndarray, A: np.ndarray) -> np.ndarray:
self.H = H
self.mask = (A + np.eye(len(A))) > 0
self.P = H @ self.params["W"]
self.pre = (self.P @ self.params["a_src"])[:, None] + (self.P @ self.params["a_dst"])[None, :]
e = np.where(self.pre > 0, self.pre, _SLOPE * self.pre)
e = np.where(self.mask, e, -np.inf)
e = np.exp(e - e.max(axis=1, keepdims=True))
self.alpha = e / e.sum(axis=1, keepdims=True) # (n, n) attention; zero outside the neighbourhood
return self.alpha @ self.P + self.params["b"]
def backward(self, dZ: np.ndarray) -> tuple[np.ndarray, dict]:
p = self.params
dP = self.alpha.T @ dZ
dalpha = dZ @ self.P.T
de = self.alpha * (dalpha - np.sum(dalpha * self.alpha, axis=1, keepdims=True))
dpre = de * np.where(self.pre > 0, 1.0, _SLOPE)
ds, dt = dpre.sum(axis=1), dpre.sum(axis=0)
dP = dP + np.outer(ds, p["a_src"]) + np.outer(dt, p["a_dst"])
grads = {"W": self.H.T @ dP, "a_src": self.P.T @ ds, "a_dst": self.P.T @ dt, "b": dZ.sum(axis=0)}
return dP @ p["W"].T, grads
_LAYERS = {"gcn": GCNLayer, "sage": SAGELayer, "gat": GATLayer}
def _softmax(z: np.ndarray) -> np.ndarray:
e = np.exp(z - z.max(axis=1, keepdims=True))
return e / e.sum(axis=1, keepdims=True)
class GNN:
"""Two-layer graph network for node classification: layer -> ReLU -> layer -> softmax."""
def __init__(self, config: GNNConfig | None = None) -> None:
self.config = config or GNNConfig()
self.layers: list = []
self.classes_: np.ndarray | None = None
self.loss_history: list[float] = []
def _init_layers(self, n_features: int, n_classes: int) -> None:
rng = np.random.default_rng(self.config.seed)
layer = _LAYERS[self.config.layer_type]
self.layers = [layer(n_features, self.config.hidden_size, rng), layer(self.config.hidden_size, n_classes, rng)]
def forward(self, X: np.ndarray, A: np.ndarray) -> np.ndarray:
"""X: (n, d) node features. A: (n, n) adjacency. Returns logits (n, n_classes)."""
self._hidden_pre = self.layers[0].forward(np.asarray(X, dtype=float), A)
return self.layers[1].forward(np.maximum(self._hidden_pre, 0.0), A)
def loss_and_grads(self, X: np.ndarray, A: np.ndarray, T: np.ndarray, mask: np.ndarray):
"""Cross-entropy over the nodes where `mask` is True, and the gradients of both layers.
T: (n, n_classes) one-hot labels (rows outside the mask are ignored). mask: (n,) bool.
Returns (loss, [grads of layer 0, grads of layer 1]).
"""
P = _softmax(self.forward(X, A))
count = mask.sum()
loss = float(-np.sum(T[mask] * np.log(P[mask] + 1e-12)) / count)
d = np.where(mask[:, None], (P - T) / count, 0.0)
d, g1 = self.layers[1].backward(d)
_, g0 = self.layers[0].backward(d * (self._hidden_pre > 0))
return loss, [g0, g1]
def fit(self, X: np.ndarray, A: np.ndarray, y: np.ndarray, train_mask: np.ndarray | None = None) -> "GNN":
"""Train full-batch with Adam.
X: (n, d) node features. A: (n, n) adjacency, A[i, j] != 0 when node i receives messages from node j.
y: (n,) labels; entries outside `train_mask` are never used for the loss.
train_mask: (n,) bool, the labelled nodes. Default: all nodes.
"""
cfg = self.config
X, A = np.asarray(X, dtype=float), np.asarray(A, dtype=float)
if A.shape != (len(X), len(X)):
raise ValueError(f"A must be ({len(X)}, {len(X)}), got {A.shape}")
mask = np.ones(len(X), dtype=bool) if train_mask is None else np.asarray(train_mask, dtype=bool)
y = np.asarray(y)
self.classes_ = np.unique(y[mask])
T = (y[:, None] == self.classes_[None, :]).astype(float)
self._init_layers(X.shape[1], len(self.classes_))
m = [{k: np.zeros_like(v) for k, v in layer.params.items()} for layer in self.layers]
v = [{k: np.zeros_like(p) for k, p in layer.params.items()} for layer in self.layers]
self.loss_history = []
for step in range(1, cfg.epochs + 1):
loss, grads = self.loss_and_grads(X, A, T, mask)
self.loss_history.append(loss)
for layer, g, mi, vi in zip(self.layers, grads, m, v):
for name in g:
mi[name] = 0.9 * mi[name] + 0.1 * g[name]
vi[name] = 0.999 * vi[name] + 0.001 * g[name] ** 2
layer.params[name] -= cfg.learning_rate * (mi[name] / (1 - 0.9**step)) / (
np.sqrt(vi[name] / (1 - 0.999**step)) + 1e-8)
return self
def predict_proba(self, X: np.ndarray, A: np.ndarray) -> np.ndarray:
"""Class probabilities of every node. Returns (n, n_classes)."""
return _softmax(self.forward(X, np.asarray(A, dtype=float)))
def predict(self, X: np.ndarray, A: np.ndarray) -> np.ndarray:
"""Predicted label of every node. Returns (n,)."""
return self.classes_[self.forward(X, np.asarray(A, dtype=float)).argmax(axis=1)]
def embed(self, X: np.ndarray, A: np.ndarray) -> np.ndarray:
"""Hidden representation of every node after the first layer and ReLU. Returns (n, hidden_size)."""
self.forward(X, np.asarray(A, dtype=float))
return np.maximum(self._hidden_pre, 0.0)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Build the two-triangle graph from the README with adjacency_from_edges and print gcn_norm(A) to see the weights. Fit GNN with labels on nodes 0 and 5 only, for each layer_type in gcn, sage and gat. Compare predict on all six nodes, then remove the bridging edge (2, 3) and repeat.
Check on learning
- In the README example only two of six nodes have labels, yet all six are classified correctly. Where does the information for the other four come from?
A way to think about it
Follow the forward pass: the prediction for a labelled node depends on its neighbours' features through shared weights. Think about what the weights must learn to get the two labelled nodes right.
- Why does GCN add self-loops before normalising? What would a node's new vector lack without them?
A way to think about it
Write out row of with no identity term and see whether appears in it.
- If you stacked ten GCN layers on a small connected graph, what would you expect to happen to the node vectors, and why?
A way to think about it
Each layer is a kind of averaging over neighbours. Consider what repeated averaging does to differences between nodes.
- GAT learns its neighbour weights and GCN fixes them from the degrees. In what kind of graph would you expect the learned weights to matter most?
A way to think about it
Picture a node with nine helpful neighbours and one misleading one, or a graph where some edges are noise.
- A fraud ring connects to many honest accounts to look normal. How does that affect a mean aggregator, and what might help?
A way to think about it
Work out the neighbour mean when one in twenty neighbours is fraudulent. Then consider which layer type can weight neighbours unequally.