Graph Neural Networks: Message Passing
Some data is neither a grid nor a sequence. Molecules are atoms joined by bonds; a social network is people joined by friendships; a road map is junctions joined by roads; a citation network is papers joined by references. The useful information is in the connections as much as in the items. A CNN needs a fixed grid of neighbours and an RNN needs an order, and a graph has neither: a node can have 1 neighbour or 1000, and there is no "first" node.
Graph neural networks (GNNs) handle this with one idea, message passing: every node collects vectors from its neighbours, combines them with a function that does not care how many there are or in which order they come, and updates its own vector. Stack such layers and each node's vector depends on its -hop neighbourhood. This lesson builds the pieces in NumPy on a classic small graph; the next lesson trains a GCN in PyTorch.
A graph as two matrices
A graph with nodes is stored as an adjacency matrix , with when there is an edge between and (symmetric for an undirected graph), and a node feature matrix , one row per node. Real libraries store the edges as a list of index pairs instead of a dense , because large graphs are sparse; the math is the same.
The running example is Zachary's karate club: 34 members of a university karate club in the 1970s, with an edge between two members who interacted outside the club. The club later split into two factions, one following the instructor ("Mr. Hi", node 0) and one the club officer (node 33). NetworkX ships it as nx.karate_club_graph(), with each member's faction in the club node attribute.
import numpy as np
import networkx as nx
G = nx.karate_club_graph()
A = nx.to_numpy_array(G, weight=None) # 0/1 adjacency; weight=None ignores edge weights
n = len(A)
labels = np.array([0 if G.nodes[v]["club"] == "Mr. Hi" else 1 for v in G])
deg = A.sum(axis=1)
print(f"{n} nodes, {int(A.sum() / 2)} edges, symmetric: {np.array_equal(A, A.T)}")
print("degrees: min", int(deg.min()), "max", int(deg.max()), " node 0 neighbours:", np.flatnonzero(A[0]).tolist())
print("faction sizes:", np.bincount(labels).tolist())
# Node features: here 2 simple ones, the degree (scaled) and a constant 1.
X = np.stack([deg / deg.max(), np.ones(n)], axis=1) # (n, 2)
# One round of message passing = aggregate the neighbours, then update.
sum_msgs = A @ X # row v: sum of v's neighbours' features
mean_msgs = (A @ X) / deg[:, None] # row v: their mean
loop_sum = sum(X[u] for u in G.neighbors(0))
print("node 0, sum by loop:", np.round(loop_sum, 3).tolist(), " by A @ X:", np.round(sum_msgs[0], 3).tolist())
print("node 0, mean of neighbours:", np.round(mean_msgs[0], 3).tolist())
rng = np.random.default_rng(0)
W_self, W_nbr = rng.normal(size=(2, 4)), rng.normal(size=(2, 4))
H = np.maximum(0, X @ W_self + mean_msgs @ W_nbr) # update: combine self and neighbours
print("new node states:", H.shape)34 nodes, 78 edges, symmetric: True
degrees: min 1 max 17 node 0 neighbours: [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 17, 19, 21, 31]
faction sizes: [17, 17]
node 0, sum by loop: [4.059, 16.0] by A @ X: [4.059, 16.0]
node 0, mean of neighbours: [0.254, 1.0]
new node states: (34, 4)
The graph has 34 nodes and 78 edges, degrees from 1 to 17, and two factions of 17. nx.to_numpy_array is called with weight=None: this version of the graph stores interaction counts as edge weights, and without the argument you would get those counts, not 0/1. The key identity is in the middle: the matrix product is "sum over neighbours", row by row, so the loop over node 0's 16 neighbours and (A @ X)[0] give the same vector, and dividing by the degree gives the mean.
Message passing
One message-passing layer computes, for every node with neighbourhood :
The aggregator must be a function of a set: sum, mean, max, or a weighted sum with learned weights. The weights are shared by all nodes, exactly like a convolution kernel is shared by all pixels; a GNN layer is a convolution whose "neighbourhood" is read from instead of being a fixed 3 3 window. The update in the first example (H = ...) was this formula with the mean aggregator.
Permutation equivariance
Node numbers are arbitrary: renumbering the members of the club must not change what the model says about each member. With a permutation matrix , renumbering maps and . A layer is permutation equivariant if
(the outputs are renumbered the same way and are otherwise identical), and a graph-level output is permutation invariant if . Message passing is equivariant because , and summing or averaging over all nodes (a readout) is invariant. An MLP on the flattened feature matrix is neither: it gives node 0's features a different weight from node 5's.
The GCN layer
The graph convolutional network (GCN, Kipf and Welling, 2017) is the simplest widely used message-passing layer. It adds a self-loop to every node (so a node keeps its own features), and normalises symmetrically by the degrees counted with that self-loop:
Entry of the normalised matrix is for every edge and self-loop. Without normalisation a hub with 17 neighbours would get a sum 17 times larger than a leaf's, and repeated layers would blow up or shrink the scale. The symmetric version keeps the matrix symmetric with eigenvalues in , so repeated application neither explodes nor vanishes. (The mean, , also works; the symmetric form additionally down-weights messages from hubs.)
import numpy as np
import networkx as nx
G = nx.karate_club_graph()
A = nx.to_numpy_array(G, weight=None)
n = len(A)
def gcn_norm(A):
A_hat = A + np.eye(len(A)) # self-loops: a node keeps its own features
d = A_hat.sum(axis=1)
D_inv_sqrt = np.diag(1 / np.sqrt(d))
return D_inv_sqrt @ A_hat @ D_inv_sqrt # D^-1/2 (A + I) D^-1/2
def gcn_layer(A_norm, H, W, act=True):
out = A_norm @ H @ W # aggregate (A_norm), then transform (W)
return np.maximum(0, out) if act else out
rng = np.random.default_rng(0)
X = rng.normal(size=(n, 5)) # random node features
W1, W2 = rng.normal(size=(5, 8)), rng.normal(size=(8, 3))
A_norm = gcn_norm(A)
print("A_norm symmetric:", np.allclose(A_norm, A_norm.T), " eigenvalues in", np.round(np.linalg.eigvalsh(A_norm)[[0, -1]], 3).tolist())
print("A_norm[0, 0] = 1/17 =", round(A_norm[0, 0], 4), " A_norm[0, 1] =", round(A_norm[0, 1], 4),
"= 1/sqrt(17 * 10) =", round(1 / np.sqrt(17 * 10), 4))
def model(A, X):
An = gcn_norm(A)
return gcn_layer(An, gcn_layer(An, X, W1), W2, act=False) # (n, 3): one vector per node
# Relabel the nodes with a random permutation matrix P.
perm = rng.permutation(n)
P = np.eye(n)[perm]
A_p, X_p = P @ A @ P.T, P @ X
out, out_p = model(A, X), model(A_p, X_p)
print("node outputs equivariant, f(PAP^T, PX) == P f(A, X):", np.allclose(out_p, P @ out))
print("graph readout invariant, sum and mean:", np.allclose(out_p.sum(0), out.sum(0)), np.allclose(out_p.mean(0), out.mean(0)))
# A plain MLP on the flattened features is not.
W_flat = rng.normal(size=(n * 5, 3))
print("MLP on flattened X invariant:", np.allclose(X_p.reshape(-1) @ W_flat, X.reshape(-1) @ W_flat))A_norm symmetric: True eigenvalues in [-0.42, 1.0]
A_norm[0, 0] = 1/17 = 0.0588 A_norm[0, 1] = 0.0767 = 1/sqrt(17 * 10) = 0.0767
node outputs equivariant, f(PAP^T, PX) == P f(A, X): True
graph readout invariant, sum and mean: True True
MLP on flattened X invariant: False
Node 0 has 16 neighbours, so and its self-weight is ; node 1 has , so the weight between them is . The eigenvalues lie between and exactly 1. The permutation test passes for the 2-layer GCN's node outputs and for the sum and mean readouts, and fails, as it should, for an MLP on the flattened features.
Over-smoothing: why GNNs are shallow
Each GCN layer averages a node with its neighbours. Do it many times and every node becomes the same average: the information that distinguishes nodes is smoothed away. Mathematically, converges to the projection onto its top eigenvector (eigenvalue 1), so after many layers every node's vector is the same vector times .
The example starts from random features (no faction information at all) and propagates them times without any weights, the bare averaging that every GCN layer contains. It tracks the mean cosine similarity between nodes, how well the two factions can be told apart (leave-one-out nearest faction mean, so 0.5 is chance), and the share of the feature energy that lies along the eigenvector .
import numpy as np
import networkx as nx
G = nx.karate_club_graph()
A = nx.to_numpy_array(G, weight=None)
n = len(A)
labels = np.array([0 if G.nodes[v]["club"] == "Mr. Hi" else 1 for v in G])
A_hat = A + np.eye(n)
d = A_hat.sum(axis=1)
A_norm = A_hat / np.sqrt(np.outer(d, d)) # D^-1/2 (A + I) D^-1/2, elementwise
rng = np.random.default_rng(0)
H = rng.normal(size=(n, 16)) # random features: no faction information yet
v = np.sqrt(d) / np.linalg.norm(np.sqrt(d)) # top eigenvector of A_norm (eigenvalue 1)
def mean_cosine(H):
U = H / np.linalg.norm(H, axis=1, keepdims=True)
S = U @ U.T
return (S.sum() - n) / (n * (n - 1)) # average over pairs of distinct nodes
def centroid_accuracy(H): # leave-one-out nearest faction mean
correct = 0
for i in range(n):
keep = np.arange(n) != i
mu = [H[keep & (labels == c)].mean(0) for c in (0, 1)]
correct += int(np.argmin([np.linalg.norm(H[i] - m) for m in mu]) == labels[i])
return correct / n
print(" k mean cosine faction accuracy share of energy on v")
for k in (0, 1, 2, 4, 8, 16, 32, 64):
Hk = np.linalg.matrix_power(A_norm, k) @ H
on_v = np.linalg.norm(np.outer(v, v @ Hk)) ** 2 / np.linalg.norm(Hk) ** 2
print(f"{k:2d} {mean_cosine(Hk):11.3f} {centroid_accuracy(Hk):16.3f} {on_v:20.3f}") k mean cosine faction accuracy share of energy on v
0 0.010 0.471 0.040
1 0.166 0.941 0.218
2 0.405 0.941 0.440
4 0.652 0.941 0.682
8 0.849 0.941 0.870
16 0.973 0.853 0.977
32 0.999 0.559 0.999
64 1.000 0.529 1.000
At the random features are useless (0.471, chance level). One round of averaging lifts the faction accuracy to 0.941: neighbours tend to be in the same faction, so averaging over neighbourhoods writes the community structure into the features. It stays at 0.941 up to 8 rounds, then the smoothing wins: 0.853 at 16, 0.559 at 32 and 0.529 at 64, where the mean cosine similarity is 1.000 and all the energy lies on . This is why typical GNNs have 2 to 4 layers, unlike CNNs with 50. Remedies for deeper models include residual connections, normalisation layers designed for graphs, and jumping-knowledge connections that feed every layer's output to the head.
Two variants: GraphSAGE and GAT
GraphSAGE (2017) made two changes aimed at large graphs. It concatenates the node's own vector with the mean (or max, or LSTM) of its neighbours, , then normalises to unit length. And it samples a fixed number of neighbours per node, so the cost per node is bounded even for hubs with millions of edges. Because the weights act on features, not on node identities, a trained model applies to nodes and graphs it has never seen (inductive learning).
GAT (graph attention network, 2018) replaces the fixed weights with learned attention over the neighbourhood: a score for every edge, a softmax over , and . It is attention with the adjacency matrix as the mask, and usually with several heads. The scoring is "additive" (a vector on a concatenation) rather than a dot product.
import numpy as np
import networkx as nx
G = nx.karate_club_graph()
A = nx.to_numpy_array(G, weight=None)
n = len(A)
rng = np.random.default_rng(0)
H = rng.normal(size=(n, 4))
# GraphSAGE, mean aggregator: concatenate self and neighbour mean, transform, L2-normalise.
def sage_layer(A, H, W, sample=None, rng=None):
out = np.zeros((len(A), W.shape[1]))
for v in range(len(A)):
nbrs = np.flatnonzero(A[v])
if sample is not None and len(nbrs) > sample:
nbrs = rng.choice(nbrs, size=sample, replace=False) # neighbour sampling
z = np.concatenate([H[v], H[nbrs].mean(axis=0)]) @ W
z = np.maximum(0, z)
out[v] = z / (np.linalg.norm(z) + 1e-12)
return out
W_sage = rng.normal(0, 0.5, size=(8, 6)) # (2 * 4) -> 6, independent of the graph size
full = sage_layer(A, H, W_sage)
sampled = sage_layer(A, H, W_sage, sample=5, rng=np.random.default_rng(1))
busy = A.sum(axis=1) > 5 # nodes that actually got sampled
print("SAGE output:", full.shape, f" {int(busy.sum())} nodes with > 5 neighbours;"
f" mean cosine full vs sampled: {np.mean(np.sum(full[busy] * sampled[busy], axis=1)):.3f}")
# GAT: attention over the neighbourhood (and the node itself), scores from a small vector a.
def gat_layer(A, H, W, a, slope=0.2):
Z = H @ W # (n, F)
F = Z.shape[1]
e = (Z @ a[:F])[:, None] + (Z @ a[F:])[None, :] # e[v, u] = a^T [z_v || z_u]
e = np.where(e > 0, e, slope * e) # LeakyReLU
mask = (A + np.eye(len(A))) > 0
e = np.where(mask, e, -np.inf) # only edges (and self-loops) take part
alpha = np.exp(e - e.max(axis=1, keepdims=True))
alpha /= alpha.sum(axis=1, keepdims=True)
return alpha @ Z, alpha
W_gat, a = rng.normal(0, 0.5, size=(4, 6)), rng.normal(0, 0.5, size=12)
out, alpha = gat_layer(A, H, W_gat, a)
nb = [0] + np.flatnonzero(A[0]).tolist()[:5]
print("GAT weights of node 0 on itself and 5 neighbours:", np.round(alpha[0, nb], 3).tolist())
print("rows sum to 1:", np.allclose(alpha.sum(axis=1), 1), " weight on non-edges:", float(alpha[0, 9]))
d = A.sum(axis=1) + 1
print("GCN's fixed weights for the same pairs:", np.round(1 / np.sqrt(d[0] * d[nb]), 3).tolist())SAGE output: (34, 6) 7 nodes with > 5 neighbours; mean cosine full vs sampled: 0.845
GAT weights of node 0 on itself and 5 neighbours: [0.019, 0.019, 0.017, 0.213, 0.017, 0.155]
rows sum to 1: True weight on non-edges: 0.0
GCN's fixed weights for the same pairs: [0.059, 0.077, 0.073, 0.092, 0.121, 0.108]
The SAGE layer's weight matrix is whatever the number of nodes. For the 7 nodes with more than 5 neighbours, the output computed from 5 sampled neighbours has a mean cosine similarity of 0.845 with the full-neighbourhood output: an approximation that gets better with more samples and pays off when degrees are in the thousands. GAT's weights for node 0 are learned and uneven (0.213 and 0.155 on two of the five neighbours shown, under 0.02 on the others), while the GCN weights for the same pairs are fixed by the degrees. In both, the masked softmax gives exactly 0 to non-edges and every row sums to 1.
Pitfalls
- Weighted adjacency by accident.
nx.to_numpy_array(G)returns edge weights when the graph has them (the karate club does). Passweight=Nonefor 0/1, or use the weights on purpose. - Forgetting the self-loops. Without , a node's new vector ignores its own features, and an isolated node gets a zero row (and a division by zero in the normalisation).
- Directed graphs. is then not symmetric, and you must decide whether messages flow along or against the edges (or both, by adding ). Libraries differ in their convention for edge lists
(source, target). - Too many layers. More than a handful of plain GCN layers usually hurts, as the over-smoothing table shows. Try 2 first.
- Dense adjacency on big graphs. entries: fine for 34 nodes, impossible for a million. Use sparse matrices or edge lists with scatter operations (what PyTorch Geometric and DGL do).
- A NetworkX function that needs SciPy (for example
nx.pagerankornx.to_scipy_sparse_array): in the browser playground,import scipyfirst.
Practice
- Which nodes does node 0's output depend on after 2 GCN layers? Compute the count with
A.
Answer
All nodes within 2 hops, itself included: the nonzero entries of row 0 of . int(((np.linalg.matrix_power(A + np.eye(34), 2))[0] > 0).sum()) counts them.
- Show that the sum aggregator is permutation equivariant but a "concatenate the neighbours in index order" aggregator is not.
Answer
The sum over a set does not depend on the order of its elements, so . Concatenation in index order gives a different vector when the indices are renumbered (and has a different length for different degrees), so a renumbered graph changes the output beyond reordering it.
- In the over-smoothing example, replace the symmetric normalisation by the mean . What do the rows converge to now?
Answer
is a random-walk matrix whose rows sum to 1; its powers converge (for a connected, non-bipartite graph) to a matrix whose rows are all equal to the stationary distribution. So every node's vector converges to exactly the same vector: a weighted average of all initial features, with weights proportional to .
- Why can GraphSAGE embed a new member who joins the club, while a model that learned one free vector per node (an embedding table indexed by node id) cannot?
Answer
GraphSAGE's parameters act on features and neighbourhood summaries, so a new node with features and edges gets an embedding from the same weights. A per-node embedding table has no row for the new id; it is transductive and must be retrained.
Test yourself
With a 0/1 adjacency matrix and features , what is row of ?
- The features of node
- The sum of the features of 's neighbours
- The mean of all node features
- The degree of
In the GCN normalisation , what is the entry for an edge between nodes with degrees 16 and 9?
Renumbering the nodes (, ) should change a node-level GNN's output how?
- Not at all
- The rows are permuted the same way, values otherwise unchanged
- Unpredictably
- Only the first row changes
In the karate-club experiment, what happened to the faction accuracy from 1 to 64 rounds of averaging?
- It kept rising
- It rose to 0.941 after one round, stayed there to 8, then fell to near chance
- It stayed at chance
- It was 1.0 throughout
What does GAT learn that GCN fixes in advance?
- The adjacency matrix
- The weight each neighbour's message gets, through attention over the neighbourhood
- The number of layers
- The node labels