An account can look ordinary when you inspect its transactions alone, yet become suspicious when you see the accounts it is connected to. Those connections give a fraud model information that a row of features can miss. Graph neural networks let a prediction use that surrounding structure. The usefulness of the connections still needs testing, because linked accounts may have quite different roles and labels.
Using connections can hurt when neighbours have different labels. On our fraud graph, the graph-blind MLP scores F1 0.78 against the GCN's 0.31. We build message passing and compare it with a graph where labels align, testing how averaging neighbours can weaken a useful signal.
By the end of this post you will have built a graph convolutional network from scratch in NumPy, with the message passing and the backpropagation written out by hand. You will train it to near-perfect accuracy on a friendly graph, then watch the exact same code collapse on a fraud graph, and you will understand precisely why, through three ideas that every practitioner should know before reaching for a GNN: homophily, over-smoothing, and the trap of the aggregate metric.
Let's Build It
Click the badge to open the interactive notebook:
A graph convolutional network (GCN) is two matrix multiplies wrapped around one special operation: propagation across the graph. Here is the whole model. S is the normalised adjacency matrix (we build it in a moment), X holds the node features, and W1, W2 are the only learnable weights.
import numpy as np
def relu(x): return np.maximum(x, 0.0)
def softmax(z):
e = np.exp(z - z.max(1, keepdims=True))
return e / e.sum(1, keepdims=True)
class GCN:
def __init__(self, in_dim, hidden, out_dim, seed=0):
rng = np.random.default_rng(seed)
self.W1 = rng.normal(0, np.sqrt(2 / (in_dim + hidden)), (in_dim, hidden))
self.W2 = rng.normal(0, np.sqrt(2 / (hidden + out_dim)), (hidden, out_dim))
def forward(self, S, X):
self.SX = S @ X # 1. mix each node with its neighbours
self.A1 = relu(self.SX @ self.W1) # 2. transform, non-linearity
self.SA1 = S @ self.A1 # 3. mix again (now 2 hops away)
self.Z2 = self.SA1 @ self.W2 # 4. transform to class logits
return softmax(self.Z2)
That is the entire forward pass of a two-layer GCN. Two layers means each node's final embedding has absorbed information from up to two hops away. Train it on a graph where neighbours tend to share a label and watch the two classes pull apart in the model's internal representation:

# X: node features (N, F), A: adjacency (N, N), y: labels, train_mask: who is labelled
S = normalise_adjacency(A)
net = GCN(in_dim=X.shape[1], hidden=16, out_dim=2)
net.fit(S, X, y, train_mask, epochs=200, lr=0.01)
acc = (net.predict(S, X)[test_mask] == y[test_mask]).mean()
print(f"test accuracy: {acc:.3f}") # -> test accuracy: 1.000
On a graph where 85% of edges connect same-class nodes, this two-layer network classifies every held-out node correctly while seeing only 20 labelled nodes per class. The graph is clean by design, and that perfect score is the promise of GNNs in its purest form: structure does most of the work. It is also exactly what we are about to break. Now let us understand what each line is doing.
What Just Happened?
A graph is just two matrices
To a GCN, a graph is a pair (X, A). The feature matrix is : one row of features per node, exactly like any tabular dataset. The adjacency matrix is : if an edge connects node and node , and 0 otherwise. Everything a GCN knows about structure lives in .
The single new operation, compared with an ordinary neural network, is the multiply S @ X. Multiplying the feature matrix by an adjacency-like matrix replaces each node's row with a combination of its neighbours' rows. That one line is message passing: every node sends its current features to its neighbours, and every node aggregates what it receives.
Message, aggregate, update
The framework underneath every GNN has three steps, repeated once per layer:
- Message. Each node prepares what it will send. In a plain GCN the message is just the node's current feature vector.
- Aggregate. Each node combines the messages from its neighbours. The GCN uses a weighted sum (the weights come from
S); other architectures use mean or max. - Update. Each node transforms the aggregated result through learned weights and a non-linearity to get its new representation.
Stack of these and signal travels hops. After one layer a node knows about its immediate neighbours; after two, about neighbours of neighbours. This animation makes the reach concrete, one node listening further out with each layer:

This is also the precise sense in which a GCN generalises a convolutional network. A CNN slides a fixed kernel over a grid, mixing each pixel with its grid neighbours. A graph has no grid and no fixed neighbour count, so a GCN replaces the kernel with "average over whoever is connected to you." Same idea, irregular domain. If the grid-based version is unfamiliar, the 2D convolution visualizer shows the operation a GCN is generalising.
Why the adjacency matrix needs normalising
You cannot use the raw adjacency for propagation. Two problems: a node does not include itself in a plain , so it forgets its own features; and high-degree nodes accumulate huge sums while low-degree nodes get tiny ones, which blows up the scale. Kipf and Welling fixed both with the symmetric-normalised adjacency:
Adding the identity gives every node a self-loop so it keeps its own message. The degree-matrix terms on each side rescale by the square root of the degree at both endpoints of an edge, so the aggregation is a weighted average rather than a raw sum. In code it is four lines:
def normalise_adjacency(A):
A_tilde = A + np.eye(A.shape[0]) # add self-loops
deg = A_tilde.sum(1) # degree of each node
d_inv_sqrt = 1.0 / np.sqrt(deg)
return d_inv_sqrt[:, None] * A_tilde * d_inv_sqrt[None, :]
This is the S in the model. It is computed once and never changes during training, which is why the GCN has only two weight matrices to learn.
Learning the weights by hand
We train with masked cross-entropy: only the labelled nodes contribute to the loss, but every node still participates in propagation. Because the forward pass is just matmuls, ReLU and softmax, the gradients follow from the chain rule. With symmetric (so ), the backward pass for the two weight matrices is compact:
def backward(self, S, P, y, train_mask, class_w):
n = P.shape[0]
onehot = np.zeros_like(P); onehot[np.arange(n), y] = 1.0
w = class_w[y] * train_mask # per-node weight, 0 off the train set
dZ2 = (P - onehot) * (w[:, None] / w.sum())
dW2 = self.SA1.T @ dZ2 # Z2 = (S A1) W2
dA1 = S @ dZ2 @ self.W2.T # back through the second propagation
dZ1 = dA1 * (self.SX @ self.W1 > 0) # ReLU gradient
dW1 = self.SX.T @ dZ1 # Z1 = (S X) W1
return dW1, dW2
A finite-difference check on this against the loss gives a maximum relative error around , so the hand-derived gradients are correct. The class_w term is a per-class weight that will matter a lot once we get to imbalanced data. Plug these gradients into Adam and the network in the Quick Win trains itself.
Going Deeper
The homophily assumption
The 99.6% accuracy hid an assumption so deep it is easy to miss: neighbours tend to share your label. Networks scientists call this homophily, and the GCN is built on it. Averaging your neighbours' features only helps if those neighbours look like you. When they do not, averaging mixes in the wrong signal.
The left panel below is a homophilic graph: the two classes form clean clusters because edges stay within a class. The right panel is heterophilic: edges cross between classes, and the structure is a tangle.

To measure the effect we built graphs across the full homophily range and compared the GCN against an MLP that uses the identical architecture but ignores the graph (we set S = I, so there is no propagation). The result is not the steady decline you might expect. It is a U:

Read the shape carefully, because it overturns the usual "GNNs hate heterophily" slogan. The GCN crushes the MLP when homophily is high, near 1.0 accuracy versus the MLP's flat 0.93. It also wins at very low homophily, where the graph is consistently heterophilic. Why? A two-layer GCN looks two hops out, and the friend of my enemy is my enemy, so a consistently heterophilic graph becomes homophilic at two hops. The model recovers.
The danger zone is the middle, homophily around 0.5. There the graph carries no class signal at all: a neighbour is a coin flip, and averaging coin flips just adds noise to features that were perfectly usable on their own. The GCN falls to 0.70 while the graph-blind MLP sits unbothered at 0.93. The lesson Zhu and co-authors drew in their 2020 study is the precise version of this: it is not heterophily that hurts a GCN, it is low neighbourhood informativeness, and the worst case is the uninformative middle.
Over-smoothing: why you cannot just add layers
If two layers reach two hops, surely more layers reach further and help? They do the opposite. Each propagation step pulls every node a little closer to the average of its neighbours. Repeat it enough and all nodes converge to nearly the same vector, regardless of class. The signal you wanted to spread gets smoothed into mush. This is over-smoothing.
It is visible without any training. Take the features, apply the propagation over and over, and measure the Dirichlet energy, a number that captures how different connected nodes still are. It decays toward zero:

The left panel is the pure phenomenon: after eight rounds of propagation, connected nodes are more than two hundred times less distinguishable than they started. The right panel is the practical consequence: trained GCNs hold their accuracy up to a point, then fall off a cliff as propagation washes out the very features the classifier needs. This is why almost every successful GCN in production has just two or three layers. If you need information from further away, the fix is not depth, it is residual or "jumping knowledge" connections that let later layers see the un-smoothed early representations.
Transductive, inductive, and attention
Our GCN is transductive: it needs the whole graph, including the test nodes, present at training time, because is the entire adjacency matrix. That is fine for a fixed citation network but useless if new accounts arrive every minute. GraphSAGE (Hamilton and co-authors, 2017) makes GNNs inductive by learning aggregator functions and sampling a fixed number of neighbours, so the model generalises to nodes and graphs it never saw during training. It is the version you deploy.
A second extension swaps the fixed averaging weights for learned ones. The Graph Attention Network (Veličković and co-authors, 2018) lets each node decide how much to weight each neighbour through an attention mechanism, the same idea that powers transformers. When some neighbours are informative and others are noise, learned attention beats a flat average.
Why your fraud GNN underperforms
Now we can diagnose the Reddit thread. We built a transaction graph with the two properties real fraud data has. It is imbalanced: only 8% of nodes are fraud. And the fraud is heterophilic in a way the aggregate hides. Look at the two homophily numbers:
- Global edge homophily: 0.77. Looks healthy. A GCN should love this graph.
- Fraud-node neighbour purity: 0.01. Almost every neighbour of a fraud node is legitimate.
The global number is dominated by the 92% of nodes that are legit and well-clustered. It completely masks the minority class, where the structure is poison: fraudsters deliberately transact with legitimate accounts to blend in, so averaging a fraud node with its neighbours smooths it straight into the legitimate population. We trained four models and scored them on the fraud class, where accuracy is meaningless (predict "all legit" and you score 92%) and recall, precision and F1 are what matter:

The story in the bars:
- The graph-blind MLP reaches F1 0.78. The node features alone carry the signal.
- The vanilla GCN drops to F1 0.31. Adding message passing made the model worse than ignoring the graph, because propagation averaged the fraud signal away.
- GCN plus class weights, the obvious first fix for imbalance, collapses to F1 0.11. Telling a model that cannot separate the classes to care twelve times more about fraud just makes it scream "fraud" at everything: recall 1.0, precision 0.06. Weighting a broken representation does not fix the representation.
- Ego-separated plus class weights recovers to F1 0.77. The fix that works keeps each node's own features separate from its aggregated neighbours instead of blending them, then lets the model learn that, here, the neighbours are a distraction.
The headline for any fraud project: a GNN is not automatically better than a tabular model, and on heterophilic, imbalanced graphs a vanilla GCN is often worse. Always benchmark a graph-blind baseline first. If class imbalance and heterophily are both present, reach for heterophily-aware architectures, neighbour sampling, and ego-neighbour separation, not just a deeper GCN.
When not to use a GNN
Skip the graph when the edges carry no label signal (the danger-zone middle), when the useful information is already in the node features, or when your structure is heterophilic and you have not adopted an architecture designed for it. A GNN earns its complexity only when the graph tells you something the features alone do not.
Where This Comes From
The line from "neural network" to "graph neural network" runs through a handful of papers, each adding one idea.
Kipf and Welling (2017), "Semi-Supervised Classification with Graph Convolutional Networks", is the canonical reference and the model we built. They derived the symmetric-normalised propagation rule as a first-order approximation to spectral graph convolutions, then showed a two-layer version beats the prior state of the art on citation networks while staying simple enough to fit in a few lines.
"We introduce a simple and well-behaved layer-wise propagation rule for neural network models which operate directly on graphs and show how it can be motivated from a first-order approximation of spectral graph convolutions." (Kipf and Welling, 2017)
Gilmer and co-authors (2017), "Neural Message Passing for Quantum Chemistry", gave the unifying framework. They showed that GCNs, and most GNN variants since, are special cases of one message-aggregate-update template, which is the mental model we used throughout.
Hamilton, Ying and Leskovec (2017), GraphSAGE, made GNNs inductive through neighbour sampling and learned aggregators, the change that lets the model handle new nodes without retraining.
Veličković and co-authors (2018), Graph Attention Networks, replaced the fixed averaging weights with learned attention over neighbours.
Zhu and co-authors (2020), "Beyond Homophily in Graph Neural Networks", is the paper behind our U-shaped curve and the fraud diagnosis. They identified homophily as the hidden assumption in standard GNNs and proposed the ego-neighbour separation we used as the recovery fix.
For the full treatment, William Hamilton's free book Graph Representation Learning (2020) is the standard text, and the Kipf and Welling paper is short and readable. The closest cousin on this blog is GraphRAG, which uses graph structure to organise documents for retrieval rather than to classify nodes, two different ways graphs meet machine learning.
Interactive Tools
- 2D Convolution Visualizer: See the grid-based convolution that a GCN generalises to irregular graph neighbourhoods
- Classification Metrics Calculator: Turn fraud predictions into precision, recall, and F1, the metrics that expose what accuracy hides on imbalanced data
- Markov Chain Simulator: Repeated multiplication by a normalised adjacency is a diffusion on the graph; watch how propagation spreads and eventually averages out
Related Posts
- Convolutional Neural Networks from Scratch: The grid-based ancestor; a GCN is convolution generalised from pixels to arbitrary graph neighbourhoods
- SMOTE vs Class Weights: Imbalanced Classification: The other half of why fraud GNNs underperform, and why class weights alone backfire
- Collaborative Filtering from Scratch in Python: Learned node embeddings in a simpler setting; the representation a GCN builds layer by layer
- GraphRAG in Python: Knowledge Graphs for Document QA: The knowledge-graph cousin, where graph structure organises retrieval instead of classifying nodes
- Backpropagation from First Principles: The hand-derived gradients behind the GCN's backward pass
- Hamiltonian Neural Networks: Another architecture that bakes structure into the network (message passing here, conservation of energy there)






