GNN Augmentation and Training

A GNN computes on the graph and the features you give it, and the karate club gives no features. Told only the sides of members 1 and 34, a two-layer GNN fed a constant 1 scores all 34 members 0.50. Fed each member's degree, it places 16 of the other 32. Fed one-hot IDs, it places 31, until you renumber the members: then 8.

Pick an input and press Train. Watch each member's colour move as the loss falls. Then renumber the members and see which input survives. Then we build the rest of the pipeline piece by piece: features, virtual nodes, sampling, heads, losses, metrics and splits.

You need Lecture 3's GCN layer, a little Python and what a probability is. We build the rest from zero.

Lecture 5, "GNN augmentation and training", of Stanford CS224W, Machine Learning with Graphs (Fall 2026, Jure Leskovec, with guest instructor Charilaos Kanatsoulis), slides. Previous: Lecture 4, A General Perspective on GNNs. Next: Lecture 6, Theory of GNNs.

Choose what each member brings

200 steps

Illustrative toy on real ties: Zachary's 34 members and 78 friendships (via NetworkX). The model averages each member with its friends twice (the series' mean layer, no σ), then scores s = z · w + b. It trains in your browser from zero weights: 200 steps of gradient descent at rate 1.0, weight decay 0.001, logistic loss on members 1 and 34 only. There is no randomness, so every run is the same run. A fill's strength shows the confidence; no fill means exactly 0.50.

We divide degree by the largest degree, 17. "Renumber" keeps the trained weights and gives each member another member's ID (one fixed shuffle, seed 7): 8 of 32 here, 15.8 on average over 1,000 shuffles.

Chapter 0

The Input Graph Is Not the Computation Graph

Find the ways a raw graph fails a GNN, and decide what to change before any message moves

Lectures 3 and 4 fed the GNN the graph as it came. Lecture 5 drops that habit. The raw input graph and the graph the GNN computes on can differ, and often they should.

The lecture names the reasons. At the feature level, the graph may have no node features at all: the karate club is 34 members and 78 ties, nothing more. At the structure level, the graph may be too sparse, so messages need many layers to cross it. It may be too dense, so one layer reads thousands of neighbours. Or it may be too large to fit on a GPU.

All of these show in one member's computation graph: the tree of inputs a GNN reads to compute that member. A two-layer GNN reads the member's friends, and each friend's friends. Tap a member.

Read one member's computation graph

The GNN computes the ringed member. Bold rings are its friends; thin rings are friends of friends. The tree below holds every input of two layers. Tap any member, or pick one.

Exact counts on the club. The tree counts every input with repeats, as a GNN computes it: 1 + kv + the sum of the friends' degrees, with no self-edges.

Member 34 has 17 friends. Its two-layer tree holds 83 nodes and reaches 23 of the other 33 members. Member 17 has two friends, a tree of 11 nodes, and reaches only 5 members. A member with ten million followers would need ten million messages in the first layer alone.

So the lecture has two halves. First, change the computation graph: graph augmentation. Then train on it: a prediction head, labels, a loss, metrics and a fair split of the data.

Symptom: one member's vector costs eight times as much as another's, and still sees less of the graph than it needs.

Measure: two-layer trees of 83 nodes (member 34) and 11 nodes (member 17); member 17 hears 5 of 33 members.

Fix: sample a few neighbours for busy nodes (Chapter 3), add a virtual node for sparse regions (Chapter 2), add features where there are none (Chapter 1).

The road

  1. Features: constant, one-hot, and structure the GNN cannot see.
  2. Virtual node: every pair of nodes two hops apart.
  3. Neighbour sampling: read k neighbours, not all.
  4. Prediction heads: a node's answer, an edge's answer.
  5. Pooling: one answer for a whole graph.
  6. Labels and losses: where right answers come from and how a loss scores a miss.
  7. Metrics: accuracy, precision, recall and ROC AUC.
  8. Splits: train, validation and test without leaks.
  9. Showcase: build the pipeline on the club.
  10. Field guide: the numbers, the code and the road ahead.
Why can the graph a GNN computes on differ from the input graph?

Chapter 1

Give Every Node Something to Say

Choose a constant, a one-hot ID or a structure feature, and find what each one can tell apart

A GNN needs an input vector xv for every node, but many graphs come as an adjacency matrix alone. The lecture gives two standard fillers. A constant feature gives every node the same input, 1. A one-hot ID gives node v a vector of zeros with a single 1 in slot v, so 34 members need 34 numbers each.

QuestionConstant 1One-hot ID
Can it tell nodes apart?Only through the structureYes: each node has its own slot
Does it work on new nodes?Yes: a new node also gets 1No: a new ID has no trained weight
Cost per node1 number|V| numbers
Use it forAny graph, new nodes laterSmall graphs, no new nodes

The hero shows the trade. One-hot IDs place 31 of 32 members, because each member has its own weight. Renumber the members and the same weights point at the wrong people: 8 of 32. Constant inputs give everyone 0.50, because our layer averages, and an average of 1s is 1.

A layer that sums does better. Call v's vector after one layer hv(1), its neighbours N(v) and its degree kv. Every input is 1:

Say it aloud

h-v at layer one equals the sum over u in N of v of h-u at layer zero, which equals k-v.

hv(1)
h-v at layer one node v's value after one summing layer.
Σu∈N(v)
the sum over u in N of v add one term for each neighbour u of v.
hu(0)
h-u at layer zero neighbour u's input: the constant 1.
kv
k-v v's degree: how many neighbours it has.
In plain words

Every neighbour u sends its input, 1. Node v adds them. So h-v after one layer is v's degree k-v.

With numbers

Member 34 has 17 friends, so h after one layer is 17. Member 12 has one friend and gets 1. The sum turned a blank input into structure.

Some structure never arrives. In a triangle and in a square, every node has degree 2. A node's computation tree is then the same binary tree in both, so no message-passing GNN can tell which cycle it sits in.

Feed two nodes the same tree

v1 sits in a triangle (left) and in a square (right). Below each is v1's computation tree. Add layers, then switch the input to the cycle-count feature.

3 layers

Exact arithmetic with summing layers and W = 1. The cycle code is the lecture's: slot 3 holds 1 for a 3-cycle, slot 4 for a 4-cycle, counting slots from 0.

The fix is a hand-built structure feature added to xv. The lecture's cycle code is [0, 0, 0, 1, 0, 0] for a 3-cycle and [0, 0, 0, 0, 1, 0] for a 4-cycle. Degree, clustering coefficient and PageRank work the same way. Lecture 6 proves why message passing misses them, and Lecture 7 returns to feature augmentation.

Symptom: two nodes in different structures get the same vector.

Measure: v1 holds 2, 4, 8 and 16 after one to four layers, in the triangle and in the square alike.

Fix: add the structure as an input feature: 8 × c3 against 8 × c4 after three layers.

The Code Lab builds a two-column feature matrix, degree and clustering coefficient, on a 10-node graph.

You train on some molecules and must predict for new ones. Which input fits?

Chapter 2

Put Every Node Two Hops Apart

Join one extra node to all the others, so messages cross a sparse graph in two layers

In a sparse graph, two nodes can sit far apart. The lecture's example has two nodes at shortest-path distance 10. A GNN with fewer than 10 layers never lets one hear the other, and stacking 10 layers over-smooths, as Lecture 4 showed.

The lecture's fix is a virtual node: one extra node joined to every node in the graph. Any node A now reaches any node B through it, A to virtual node to B. Every pair is at most 2 hops apart. The virtual node has no label and is never predicted. It is a relay, and the GNN learns its vector like any other.

Take the sparsest graph there is: a chain of 8 nodes, numbered 0 to 7 as in the Code Lab.

Add a virtual node to a chain

Numbers under the nodes are hops from the ringed source. Shaded nodes are the ones the source hears within the chosen number of layers. Tap a source, then switch on the virtual node.

2 layers

Exact hop counts. "Pairs within 2 hops" counts ordered pairs of real nodes, each node with itself included: 64 in all, as in the Code Lab.

Without the virtual node, nodes 0 and 7 are 7 hops apart, and only 34 of the 64 ordered pairs are within 2 hops (53%). With the virtual node, all 64 are (100%). Joining it to node 0 alone does nothing for the real nodes: still 34 of 64. A path through it needs two real nodes joined to it.

The cost is one node and one edge per node. The risk is fast mixing: every node hears everyone after two layers, so averaging layers smooth sooner. On the club, Lecture 4's averaging toy collapses by layer 7 with a virtual node instead of layer 19.

Symptom: a two-layer GNN never lets node 0 hear node 7.

Measure: 7 hops apart; 34 of 64 pairs within 2 hops.

Fix: a virtual node joined to every node: 2 hops, 64 of 64. Keep the depth low afterwards.

The Code Lab wires the virtual node and counts the pairs within two hops.

A virtual node is joined to every real node. What is the largest hop distance between two real nodes now?

Chapter 3

Read a Few Neighbours, Not All

Sample k neighbours per layer, so the cost stops growing with degree while the average stays right on average

Dense graphs have the opposite problem: a busy node reads every neighbour in every layer. PinSage ran on a Pinterest graph of 3 billion nodes (pins and boards) and 18 billion edges, where full trees are out of the question.

The lecture's fix is neighbour sampling: in each layer, take messages from k random neighbours only, and draw new ones next time. GraphSAGE uses two layers with k = 25, then 10.

Does a sample give the right answer? Call the full set of v's neighbours N(v), its size d, and the sampled set S(v), of size k. Each neighbour u holds a value hu. The sampled mean is:

Say it aloud

h-bar-v equals one over k times the sum over u in S of v of h-u.

h̄v
h-bar-v the mean v receives from its sample.
1/k
one over k divide by the sample size k.
Σu∈S(v)
the sum over u in S of v add one term for each sampled neighbour; this step skips the other d minus k.
hu
h-u neighbour u's value from the layer before.
In plain words

Draw k of v's d neighbours at random. Add their values h-u and divide by k. That is h-bar-v. Each neighbour has the same chance, so on average h-bar-v equals the full mean.

With numbers

Member 34 has d = 17 friends whose survey answers (+1 or −1) add to −7: the full mean is −0.41. A sample of k = 5 answering +1, −1, −1, −1, +1 gives h-bar = −1/5 = −0.20.

How far does one sample stray? Call σ2 the spread of the d values around their mean. Sampling without repeats gives:

Say it aloud

The variance of h-bar-v equals sigma squared over k, times d minus k over d minus one.

Var(h̄v)
the variance of h-bar-v how much the sampled mean swings from draw to draw, squared.
σ2
sigma squared the spread of the neighbours' values: the average squared distance from their mean.
k
k the sample size. Doubling it halves the first factor.
(d − k) / (d − 1)
d minus k over d minus one the finite-population factor: 0 when k = d, because then the sample is the whole set.
In plain words

Take the spread sigma squared of the neighbours, divide by the sample size k, and shrink it by d minus k over d minus one. The square root is the typical miss of one sample.

With numbers

Member 34: σ2 = 1 − 0.412 = 0.830 and d = 17. At k = 5: 0.830/5 × 12/16 = 0.125, a typical miss of ±0.35. At k = 10: ±0.19. At k = 17: 0. A 20,000-draw simulation agrees.

Sample member 34's friends

Blue edges carry this sample's messages. Below, the purple dot is this sample's mean and the grey tick is the full mean. Set k, then resample, or draw 200 at once.

k = 5

Illustrative: the series' fixed survey on the real club, sampled without repeats (seeded). Grey band: ± one typical miss. Tree: each sampled friend samples min(k, its degree).

With sampling, a two-layer tree holds at most 1 + k + k2 nodes, whatever the degrees: 276 for GraphSAGE's 25 and 10. The cost still grows as k to the power of the layer count.

Symptom: a node's vector jumps from one training step to the next.

Measure: at k = 3, member 34's sampled mean misses by ±0.49 and has the wrong sign in about 1 draw in 5.

Fix: raise k for busy nodes, or sample the neighbours that matter most: PinSage keeps the nodes that short random walks from v visit most often.

Why does uniform neighbour sampling give a sensible mean?

Chapter 4

Turn Vectors Into Answers

Read one node's vector with a matrix, and an edge's two vectors with a concatenation or a dot product

The augmented graph goes through the GNN. Out comes one vector per node, hv, with d numbers each. A task wants something else: a class, a number, a yes or no. The prediction head is the last layer that turns vectors into that answer. Different task levels need different heads.

For a node task with k outputs, call the head's matrix W(H), with k rows and d columns:

Say it aloud

y-hat-v equals W-H times h-v.

ŷv
y-hat-v the prediction for node v: k numbers.
W(H)
W-H the head's weight matrix, k by d, learned with the GNN.
hv
h-v node v's vector from the last GNN layer: d numbers.
In plain words

Multiply v's vector h-v by the head's matrix W-H. Each row gives one output. For classes, a softmax turns the k outputs into probabilities.

With numbers

With made-up numbers: h-v = (1.0, 0.5) and W-H rows (2, −1) and (−1, 2). Then y-hat = (1.5, 0.0), and the softmax gives 0.82 for class A and 0.18 for class B.

An edge task reads two vectors. The lecture gives two heads. Concatenation plus linear stacks hu and hv into 2d numbers and multiplies by a learned matrix. The dot product multiplies the two vectors entry by entry and adds:

Say it aloud

y-hat-u-v equals h-u transpose times h-v.

ŷuv
y-hat-u-v one score for the pair u, v: high means "linked".
(hu)T
h-u transpose u's vector laid on its side, so the product is a single number.
hv
h-v v's vector.
In plain words

Multiply each entry of h-u by the same entry of h-v and add the products. Vectors that point the same way score high. Swapping u and v gives the same score.

With numbers

With made-up numbers: h-u = (1.0, 0.5), h-v = (0.8, −0.2). The score is 0.8 − 0.1 = 0.70, and the sigmoid makes it a link probability of 0.67.

Read two vectors with three heads

The purple arrows are hu and hv. Drag their tips. Pick a head, then press Swap to exchange u and v.

Illustrative weights: the node head's rows are (2, −1) and (−1, 2); the concatenation head's vector is a = (0.5, 1, −1, 0.5). A real GNN learns them.

Swap the pair. The dot product stays at 0.70. Concatenation plus linear gives 0.10 for (u, v) and −0.55 for (v, u), because u's numbers meet a's first half and v's meet its second. For k kinds of edge, the lecture learns k matrices W(1) to W(k). It scores (hu)T W(i) hv for each and stacks the k scores.

Symptom: a link model says "u follows v" exactly as often as "v follows u".

Measure: the dot product gives 0.70 both ways; concatenation gives 0.10 and −0.55.

Fix: use concatenation plus linear, or a non-symmetric W(i), for directed relations; keep the dot product for symmetric ones like friendship.

Which edge head can score u → v differently from v → u?

Chapter 5

One Answer for a Whole Graph

Pool every node vector into one, and find what mean, max and sum each throw away

A graph task, such as the drug likeness of a molecule, needs one answer per graph. The head must read every node vector at once. The lecture notes that this is the aggregation of Lecture 4, run over the whole graph. Call the graph's prediction ŷG:

Say it aloud

y-hat-G equals the Sum of the set of h-v, for v in G.

ŷG
y-hat-G the pooled vector of graph G, read by a final linear layer.
Sum
Sum global sum pooling. Swap in Mean (divide by the node count) or Max (the largest value in each slot).
hv
h-v node v's final vector.
v ∈ G
v in G every node of the graph, once each.
In plain words

Collect every node's vector h-v. Add them slot by slot. The total is y-hat-G. Mean divides it by the node count; Max keeps the biggest value in each slot.

With numbers

The lecture's toy, one number per node: G1 holds −1, −2, 0, 1, 2, so its sum is 0. G2 holds −10, −20, 0, 10, 20, so its sum is also 0. Two different graphs, one prediction.

Pool two graphs and compare

Each node shows its final value (purple). The boxes below hold each graph's pooled output. A red frame means the two graphs get the same answer. Try every rule on every pair.

Illustrative values. The super node here applies ReLU to each node's value before adding, one setting a learned super node can reach; a trained one learns its own weights.

Every fixed rule has a blind spot. Sum and mean give 0 for both of the lecture's graphs. Max tells them apart (2 against 20) but gives 2 for {0, 0, 0, 2} and for {2, 2, 2, 2}. Mean gives 1 for two nodes holding 1 and for four. These rules work well on small graphs; on large ones, more is lost in the pool.

The lecture's fix is a virtual super node joined to every node, the Chapter 2 node used as a readout. The GNN learns what the super node collects, and its vector is the graph's vector. With ReLU before the sum, the lecture's pair pools to 3 and 30. An earlier answer, DiffPool (Ying et al., NeurIPS 2018), learns soft clusters of nodes and pools in stages.

Symptom: two very different graphs get the same prediction.

Measure: {−1, −2, 0, 1, 2} and {−10, −20, 0, 10, 20} both pool to 0 under sum and mean.

Fix: a virtual super node that learns its readout (3 against 30 in the device), or hierarchical pooling.

The Code Lab pools a 10-atom molecule with one toxic group, where the mean waters the signal down.

Node values {−1, −2, 0, 1, 2} and {−10, −20, 0, 10, 20}. Which pooling tells the two graphs apart?

Chapter 6

Say What Right Means

Take labels from outside or from the graph itself, then score each prediction with cross-entropy or squared error

A loss compares predictions with labels, so first ask where the labels come from. Supervised labels come from outside the graph: a paper's subject area in a citation network, whether a transaction edge is fraud, a molecule's drug likeness from a lab. The lecture's advice: reduce your task to node, edge or graph labels, because those are easy to work with.

Sometimes there is only the graph. Then the graph makes the labels. Predict a node's clustering coefficient or PageRank, hide an edge and predict whether it exists, or predict whether two graphs are isomorphic. The lecture calls this self-supervised learning, another name for unsupervised learning on graphs. It still has a target; nobody had to label it.

For k classes, call the label y, a one-hot vector with a 1 at the true class, and the prediction ŷ, the k probabilities after a softmax. The lecture's classification loss is cross-entropy:

Say it aloud

CE of y and y-hat equals minus the sum over j from one to k of y-j times log of y-hat-j.

CE(y, ŷ)
CE of y and y-hat the cross-entropy loss for one node, edge or graph.
−Σj=1k
minus the sum over j from one to k one term per class, then flip the sign so the loss is positive.
yj
y-j the label's entry for class j: 1 for the true class, 0 for the rest.
log ŷj
log of y-hat-j the natural log of the predicted probability of class j.
In plain words

Every y-j is 0 except the true class, so only one term is left. The loss is minus the log of the probability y-hat gives the true class. The total loss adds this over all N training points.

With numbers

The lecture's example: label (0, 0, 1, 0, 0), prediction (0.1, 0.3, 0.4, 0.1, 0.1). CE = −log 0.4 = 0.92. At 0.9 on the true class it would be 0.11; at 0.01 it would be 4.61.

For regression the lecture uses mean squared error, also called the L2 loss: subtract each prediction from its target, square, and add over the k targets.

targets (1.4, 2.3, 1.0, 0.5, 0.6), predictions (0.9, 2.8, 2.0, 0.3, 0.8): 0.25 + 0.25 + 1.00 + 0.04 + 0.04 = 1.58 (PyTorch's MSELoss averages instead: 0.316)

Grade one prediction

Classification: slide the probability on the true class (warm) and watch the loss move along its curve. Regression: move prediction 3 and watch its square grow.

0.40

The lecture's numbers. Moving the true-class probability rescales the other four so the five still add to 1.

Symptom: one bad target steers the whole regression.

Measure: the miss of 1.0 on target 3 contributes 1.00 of the 1.58 total, 63%.

Fix: check that label first; if outliers are real, report or train on the mean absolute error, which grows linearly.

The true class gets probability 0.4. What is the cross-entropy, and which other probabilities does it read?

Chapter 7

Measure Success Two Ways

Count right answers at one threshold, then rank every pair with ROC AUC

The loss trains the model; a metric reports how well it does. The lecture uses standard ones from scikit-learn. For regression: the root mean square error (the square root of the average squared miss) and the mean absolute error (the average size of the miss). For several classes: accuracy, the share of argmax predictions that match the label.

Binary tasks need more care, because a score becomes a yes or no only at a threshold, usually 0.5. Count four outcomes: true positives TP, false positives FP, false negatives FN and true negatives TN. Precision P = TP/(TP + FP) is the share of yes answers that are right. Recall R = TP/(TP + FN) is the share of real positives found. One number joins them:

Say it aloud

F-one equals two P R over P plus R.

F1
F-one the harmonic mean of precision and recall, from 0 to 1.
2
two scales the result so that P = R gives F1 = P.
P
P precision: TP over TP plus FP.
R
R recall: TP over TP plus FN.
P + R
P plus R the sum below the line; if either is near 0, F1 is near 0.
R
R recall again, in the sum.
In plain words

Multiply P by R, double it, and divide by P plus R. F1 is high only when both are high.

With numbers

The hero's one-hot model at threshold 0.5, with Mr. Hi's side as positive: TP 15, FP 0, FN 1, TN 16. P = 15/15 = 1.00, R = 15/16 = 0.94, so F1 = 2 × 1.00 × 0.94 / 1.94 = 0.97.

Every threshold gives a different P and R. The ROC curve plots the true positive rate (recall) against the false positive rate, FP/(FP + TN), as the threshold sweeps from 1 to 0. The ROC AUC is the area under it: the chance that a random positive scores above a random negative. A coin scores 0.5.

Slide the threshold

Each dot is one of the 32 unlabelled members at its predicted chance of Mr. Hi's side, filled by its true side. Dots right of the line are called "Mr. Hi". Slide the threshold and watch the counts and the ROC point.

0.50

Scores from the hero's trained models, not the renumbered ones. 16 of the 32 unlabelled members are on Mr. Hi's side.

The one-hot model ranks perfectly: AUC 1.00. Every Mr. Hi member outscores every president member. Yet at 0.5 it misplaces member 9, whose score is 0.43. At 0.40 every member is right. The degree model scores AUC 0.57, close to a coin, and no threshold rescues it.

Symptom: a model looks perfect on one metric and useless on another.

Measure: the degree model at threshold 0.40 calls all 32 members "Mr. Hi": recall 1.00, precision 0.50, accuracy 0.50.

Fix: report precision and recall together, or F1, plus ROC AUC, which no threshold can game.

What does ROC AUC measure?

Chapter 8

Split Without Leaking

Hide labels for nodes, whole graphs for graphs, and edges twice for links

The training set fits the weights, the validation set picks settings, the test set is for the final report. A random split repeats over seeds and averages. Images split easily: image 5 does not change the prediction for image 1. In a graph, node 5 passes messages to node 1, so it does.

In the transductive setting, every split sees the whole graph, and you split only the labels. This works for node and edge tasks. In the inductive setting, you cut the edges between splits, so each split is its own graph and the model must work on graphs it never saw. Graph classification allows only this one.

Link prediction is harder, because edges are both input and label. The lecture splits them twice: into message edges, which carry messages, and supervision edges, which the model must predict; then into training, validation and test. The default transductive split has four kinds of edge, and the message graph grows:

  1. Training: training message edges predict the training supervision edges.
  2. Validation: both kinds of training edge predict the validation edges.
  3. Test: those plus the validation edges predict the test edges.

It grows because a trained model knows its supervision edges and should use them.

Split the club's ties for link prediction

Teal edges carry messages at this stage. Solid blue edges are the edges the model predicts; dotted blue pairs are non-edges the model samples. Grey dashes wait for a later stage. Step through the stages, then leak the predicted edges.

Illustrative, untrained score: two rounds of mean aggregation of one-hot IDs over the current message edges, then hu · hv. One seeded 46 / 16 / 8 / 8 split. Over 200 random splits: AUC 0.74 honest, 0.90 leaked.

On this split, the honest test AUC is 0.64. Leak the 8 test edges into the message graph and it jumps to 0.78, with no learning. Each leaked edge ties its two endpoints together, so their vectors overlap.

The loss for link prediction scores the supervision edges as positives and needs negatives too. Call a pair's score suv = hu · hv, the sigmoid σ, the positive pairs E+ and the sampled non-edges E−:

Say it aloud

L equals minus the sum over u-v in E-plus of log sigma of s-u-v, minus the sum over u-v in E-minus of log of one minus sigma of s-u-v.

L
L the link loss: binary cross-entropy over pairs.
−Σ(u,v)∈E+
minus the sum over u-v in E-plus one term per supervision edge, label 1.
log σ(suv)
log sigma of s-u-v the log of the predicted chance that the pair is linked.
−Σ(u,v)∈E−
minus the sum over u-v in E-minus one term per sampled non-edge, label 0.
log(1 − σ(suv))
log of one minus sigma of s-u-v the log of the predicted chance that the pair is not linked.
In plain words

For each real edge, add minus the log of its link chance. For each sampled non-edge, add minus the log of its no-link chance. Without the second sum, the model wins by calling every pair linked.

With numbers

With made-up scores: an edge at s = 2.0 (σ 0.88) costs 0.13; a non-edge at s = 1.0 (σ 0.73) costs −log 0.27 = 1.31. L = 1.44, and the non-edge drives the gradient.

Symptom: a link predictor scores far better offline than in use.

Measure: with the test edges in the message graph, an untrained score's AUC rises from 0.74 to 0.90 (average of 200 splits).

Fix: keep every edge you predict out of the message graph at that stage; PyG and GraphGym implement the lecture's split.

The Code Lab drops the negative term and shows the collapse.

In a transductive link split, why must the test edges stay out of the message graph at test time?

Chapter 9

Build the Pipeline on the Club

Pick the features, the depth and the graph, train, then test on the same club and on a renumbered one

Now put the whole pipeline in your hands. The features are Chapter 1, the virtual node Chapter 2, the head and loss Chapters 4 and 6, the metrics Chapter 7. "Renumbered" tests the trained model on the same club with the IDs shuffled: the inductive question in miniature.

Build and test a pipeline

Pick an input and a depth, choose the graph, then train. Switch the test to the renumbered club and see which inputs keep their score.

6 layers

Illustrative toy on real ties, the hero's model with your settings: K averaging layers, a logistic head, 200 steps of gradient descent from zero on members 1 and 34. Degree + clustering is two inputs per member: degree over 17 and the clustering coefficient. The virtual node takes part in the averaging and is never scored.

Three things to find. First, one-hot IDs place 31 at every depth from 1 to 6, and 0 at depth 0. With no graph, only members 1 and 34 have any weight. Renumbered, the same models fall to between 5 and 8 of 32.

Second, degree and clustering never care about the numbering. At two layers they place 17 of 32; at six layers, 30, with AUC 1.00. Six rounds of averaging turn two local numbers into a regional signal that happens to split this club. Third, the virtual node is not free: at six layers it drops that model from 30 to 16, because every member then hears everyone.

Renumbering drops the one-hot model to chance but leaves degree + clustering unchanged. Why?

Chapter 10

Field Guide

Keep the pipeline, the numbers, the code and the road to Lecture 6

The input graph is raw material. Add features where there are none: constants, one-hot IDs, or structure a GNN cannot compute, like cycle counts. Add a virtual node where the graph is sparse, and sample neighbours where it is dense. Then train. Pick a head for nodes, edges or graphs. Take labels from outside or from the graph, and score misses with cross-entropy or squared error. Report a threshold-free metric too, on a split that never shows the model its own answers.

IdeaRuleThis lesson's number
Featuresconstant, one-hot, structurehero: all 0.50, 16, 31 of 32; renumbered one-hot 8
Constant + sumhv(1) = kvmember 34: 17
Cyclessame tree in a triangle and a square2, 4, 8, 16 in both
Virtual nodejoined to every nodechain: 7 hops → 2; 34 → 64 of 64 pairs
Samplingσ2/k × (d − k)/(d − 1)member 34, k = 5: ±0.35; tree ≤ 1 + k + k2
Edge headsconcat + linear; hu · hv0.10 vs −0.55 swapped; 0.70 both ways
Poolingmean, max, sum; super nodesum 0 and 0; super node 3 and 30
Loss−log ŷtrue; squared errorCE 0.92; MSE 1.58
MetricsF1 = 2PR/(P + R); ROC AUCF1 0.97; AUC 1.00 one-hot, 0.57 degree
Link splitmessage vs supervision; growing graphAUC 0.74 honest, 0.90 leaked (200 splits)

The hero in NumPy: two averaging layers, a logistic head and 200 steps of gradient descent. We ran it; it prints the hero's numbers.

python
import networkx as nx, numpy as np
G = nx.karate_club_graph(); n = 34
A = nx.to_numpy_array(G, nodelist=range(n), weight=None)
y = np.array([1 if G.nodes[v]["club"] == "Mr. Hi" else 0 for v in range(n)])
P = (A + np.eye(n)) / (A + np.eye(n)).sum(1, keepdims=True)   # mean over self and friends
lab = [0, 33]                                                  # members 1 and 34
test = [v for v in range(n) if v not in lab]
feats = {"constant": np.ones((n, 1)),
         "degree":   A.sum(1, keepdims=True) / A.sum(1).max(),
         "one-hot":  np.eye(n)}
for name, X in feats.items():
    Z = P @ P @ X                                              # two averaging layers
    w, b = np.zeros(X.shape[1]), 0.0
    for step in range(200):                                    # gradient descent on the logistic loss
        p = 1 / (1 + np.exp(-(Z[lab] @ w + b)))
        g = p - y[lab]
        w -= 1.0 * (Z[lab].T @ g / 2 + 1e-3 * w); b -= 1.0 * g.mean()
    s = Z @ w + b
    right = sum((s[v] > 0) == y[v] for v in test if abs(s[v]) > 1e-9)
    print(name, right, "of 32")
# constant 0 of 32 / degree 16 of 32 / one-hot 31 of 32

For real work, PyTorch Geometric has each piece: NeighborLoader for sampling, global_mean_pool, global_max_pool and global_add_pool for readouts, the VirtualNode transform, and RandomLinkSplit for the message and supervision edges. GraphGym runs the whole pipeline.

The road through CS224W, Fall 2026

LecturesTopic
3 and 4Graph neural networks and a general perspective on GNNs: the layers this lesson trains
5GNN augmentation and training: this lesson
6 and 7Theory of GNNs and designing powerful graph encoders: why the triangle and the square look alike, and what fixes it
11GNNs for recommender systems: link prediction at scale

Keep going

Read next

The habit. Before you pick a layer, ask four questions. What does each node bring? Can messages reach where they must? Which head, label and loss fit the task? Does any test answer leak into the graph the model sees?
Which order does the lecture's pipeline follow?

Now teach it: press Present or Teach. Explain why a constant input leaves the club undecided and what a virtual node and neighbour sampling each fix. Then say which head fits which task, and how a leaked test edge flatters a link predictor. Then go back to the club, pick one-hot IDs, and say what renumbering will do before you press it.

GNN Augmentation and Training · Stanford CS224W, Lecture 5
Previous: A General Perspective on GNNs · Next: Theory of GNNs · Course site · Back to Gleams