Before you start: review of the earlier sessions
The thread so far. Sessions 3–5 complete the first GNN block: the layer, the design choices, and how to actually train and evaluate. From here the course asks what these models can and cannot represent.
What this session takes from earlier ones
Those sessions in one minute each
Lecture 4 · A General Perspective on GNNs
A GNN layer is "message, then order-free aggregation (including yourself)"; architectures differ in how neighbours are weighted, and depth must be matched to the receptive field you need because too many layers smooth everything into one vector.
GCN is the special case \(\alpha_{vu}=1/|N(v)|\) (fixed); GAT learns \(e_{vu}=a(\mathbf{W}\mathbf{h}_u,\mathbf{W}\mathbf{h}_v)\).
Lecture 3 · Graph Neural Networks
A GNN layer = for every node, combine its own vector with an order-free aggregate of its neighbours' vectors, using weights shared across all nodes; stacking K layers lets information travel K hops.
Rows of \(H\) are node embeddings; \(D^{-1}A\) averages over neighbours; \(W_k\) transforms the neighbourhood message; \(B_k\) transforms the node itself.
Define similarity by co-occurrence on short random walks, then learn one vector per node so that dot products reproduce it — fast with negative sampling, but just a lookup table.
\(N_R(u)\): multiset of nodes visited by walks from \(u\) under strategy \(R\) (uniform for DeepWalk, \(p,q\)-biased for node2vec); \(n_i\): negatives sampled ∝ degree; \(\sigma\): sigmoid.
Warm-up: answer these before you read on
Why add MLP layers before and after message passing? from Lecture 4
Pre-processing encodes rich input features (text, images); post-processing lets the model reason over the embedding, e.g. for graph classification, without adding more hops.
What does the self-loop (or the B matrix) do in the GCN layer? from Lecture 3
It keeps the node's own previous vector in the update, so a node does not forget its own features while absorbing its neighbours'.
Give the three limits of shallow embeddings. from Lecture 2
No parameter sharing (one vector per node), no use of node features, and no embedding for nodes unseen at training time (transductive).
Where does GAT put its parameters that GCN does not have? from Lecture 4
In the attention mechanism: a learned function of the pair (node, neighbour) that produces the aggregation weights, instead of fixed degree-based weights.
More questions from every session you have reached, with spaced repetition: the cumulative review.
In short
Two practical questions finish the GNN design space. First: what graph do we actually compute on? Real graphs may lack features, be too sparse (messages travel slowly), too dense (hubs with millions of neighbours), or too large for a GPU. So we augment features (constants, one-hot IDs, cycle counts), add virtual nodes, and sample neighbours.
Second: how do we train and evaluate? A pipeline goes graph → GNN → embeddings → prediction head → predictions, compared to labels by a loss and judged by metrics. Heads differ for node, edge and graph tasks; labels come from outside (supervised) or from the graph itself (self-supervised).
The subtle part is splitting. Nodes are not independent: a test node's features flow into a training node's embedding through message passing. Hence two regimes — transductive (one graph, split only the labels) and inductive (separate graphs) — and, for link prediction, a careful split into message edges and supervision edges.
The first part of the slides announces the course project (three tracks: application, PyG tutorial, research implementation) — summarised under Homework.
The picture: the GNN training pipeline
How to read it (hover a step)
- Prediction head turns embeddings into task outputs — differs for node, edge and graph tasks.
- Labels come from external sources (supervised) or from the graph itself (self-supervised: hide an edge, predict a statistic).
- Loss (cross-entropy, MSE) trains the model; metrics (accuracy, F1, ROC AUC, RMSE) judge it.
- Dataset split: the hardest part on graphs, because data points are connected.
1 · Graph manipulation: input graph ≠ computation graph
So far we assumed the raw graph is the computation graph. Reasons to break that assumption:
| Problem | Fix |
|---|---|
| No node features | Feature augmentation: constant, one-hot ID, structural features (Lecture 7) |
| Structure the GNN can't see (e.g. cycle length) | Add hand-computed features (cycle counts, degree, clustering coefficient) |
| Too sparse → messages travel slowly | Add virtual nodes / edges |
| Too dense → message passing too costly | Sample neighbours |
| Too large → doesn't fit on a GPU | Sample subgraphs (scaling GNNs) |
Constant vs one-hot features
- Constant (all 1s): medium expressiveness (the GNN still sees structure), fully inductive, 1-D and cheap. Use for any graph, especially when new nodes appear.
- One-hot ID: high expressiveness (node-specific info can be memorised), but not inductive (a new ID is unknown), \(|V|\)-dimensional. Use for small, fixed graphs.
Structures a GNN can't learn: cycles
Can a GNN tell whether \(v_1\) lies on a 3-cycle or a 4-cycle? No. Every node has degree 2, so \(v_1\)'s computation graph is the same infinite binary tree in both — and also on an infinitely long path. Fix: give each node its cycle-count vector as a feature, e.g. \([0,0,0,1,0,0]\) for "on a 3-cycle".
Before Lecture 6: what exactly is the GNN unable to distinguish, in one sentence?
A message-passing GNN can only distinguish two nodes if their rooted computation trees (unrolled neighbourhoods with features) differ. Nodes in regular graphs with identical features all have identical trees. Lecture 6 formalises this as the 1-WL test; Lecture 7 adds identity and position information to escape it.
Virtual nodes and neighbour sampling
- Virtual node connected to every node: any two nodes become at most 2 hops apart (was 10 in a long sparse chain). Greatly improves message passing in sparse graphs, and also serves as a graph-level readout.
- Neighbour sampling (GraphSAGE, PinSage): each time, pick a random subset of neighbours (e.g. 2 of A's neighbours). Different samples each epoch; in expectation the embedding matches full aggregation, at a fraction of the cost. "In practice it works great."
2 · Prediction heads
Node-level: \(\hat{\mathbf{y}}_v=\mathbf{W}^{(H)}\mathbf{h}_v^{(L)}\), with \(\mathbf{W}^{(H)}\in\mathbb{R}^{k\times d}\) for \(k\)-way classification or regression.
Edge-level \(\hat{\mathbf{y}}_{uv}=\text{Head}_{\text{edge}}(\mathbf{h}_u,\mathbf{h}_v)\):
- Concatenation + linear: \(\text{Linear}(\text{Concat}(\mathbf{h}_u,\mathbf{h}_v))\), \(2d\to k\). (As in GAT's attention.)
- Dot product: \(\mathbf{h}_u^\top\mathbf{h}_v\) — only 1-way (edge exists?). For \(k\)-way, use \(k\) bilinear forms \(\mathbf{h}_u^\top\mathbf{W}^{(i)}\mathbf{h}_v\) and concatenate (like multi-head attention).
Graph-level: \(\text{Head}_{\text{graph}}\) is like AGG in a layer — global mean, max or sum pooling. Fine for small graphs, but lossy for large ones.
Graph \(G_1\) has 1-D node embeddings \(\{-1,-2,0,1,2\}\), \(G_2\) has \(\{-10,-20,0,10,20\}\). What does global sum pooling output? Mean? Max?
Sum: 0 and 0. Mean: 0 and 0. Max: 2 vs 20 — max separates them here, but you can easily build counterexamples for max too. Any single global statistic throws information away. Remedies: hierarchical pooling (aggregate within clusters, then aggregate clusters — DiffPool, the optional reading) or a virtual super-node that learns how to summarise the graph.
3 · Labels, losses and metrics
Where does ground truth come from?
- Supervised (external): node labels (paper subject in a citation network), edge labels (fraudulent transaction), graph labels (drug-likeness of a molecule).
- Self-supervised (from the graph): node statistics (clustering coefficient, PageRank), link prediction (hide an edge, predict it), graph statistics (are two graphs isomorphic?). No external labels needed.
- Advice: reduce your task to node / edge / graph labels — e.g. treat "which cluster a node belongs to" as a node label.
Loss
Classification: cross-entropy \(\text{CE}(\mathbf{y},\hat{\mathbf{y}})=-\sum_j y_j\log\hat y_j\) on softmax outputs. Regression: MSE \(\sum_j(y_j-\hat y_j)^2\). Sum over the \(N\) training points.
Metrics (use sklearn)
- Regression: RMSE \(\sqrt{\frac1N\sum(y-\hat y)^2}\), MAE \(\frac1N\sum|y-\hat y|\).
- Multi-class: accuracy. Binary: accuracy, precision \(TP/(TP+FP)\), recall \(TP/(TP+FN)\), F1 \(=2PR/(P+R)\) — all depend on a threshold (0.5).
- ROC AUC: threshold-free. ROC plots TPR vs FPR as the threshold varies; AUC = probability that a random positive is scored above a random negative. Random classifier = 0.5.
4 · Splitting graph datasets
Images are independent: image 5 doesn't affect the prediction for image 1. Nodes are not: node 5 participates in message passing and changes node 1's embedding. Options:
- Transductive: the whole graph is visible in all splits; only the labels are split. Train with nodes 1–2's labels, validate on 3–4's, all embeddings computed on the full graph. Only for node/edge tasks.
- Inductive: cut the edges between splits → independent graphs. Each split sees only its own graph; the model must generalise to unseen graphs. Works for node/edge/graph tasks. Graph classification is only well defined inductively.
Fixed split vs random split: with random splits, report the mean over several seeds.
Link prediction: split edges twice
Link prediction is self-supervised: we must create labels by hiding edges. Step 1: label edges as message edges (used for message passing) or supervision edges (used only in the loss; never fed to the GNN). Step 2: split into train/val/test.
- Inductive: separate graphs per split, each with its own message + supervision edges.
- Transductive (the default in papers): one graph, four edge types. Train: training message edges → predict training supervision edges. Validate: training message + training supervision edges → predict validation edges. Test: all of those + validation edges → predict test edges.
Why does the visible edge set grow from training to validation to test?
After training, the supervision edges are known facts; a real deployed model would use them for message passing. Leaving them out at validation time would handicap the model unrealistically. The ordering also guarantees the model never passes messages along the very edge it's asked to predict — which would be leakage.
Forgetting to remove supervision edges from edge_index during training: the GNN then "predicts" edges it can see in its own neighbourhood, and validation AUC looks spectacular. PyG's RandomLinkSplit handles this (and negative sampling) for you.
The mathematics, step by step
This session is about everything around the layers: how the final embeddings become predictions, which loss and which metric to use, and how to split a graph without letting test information leak. The formulas are short; the care is in what is summed over.
Symbols used in this session
| symbol | meaning | what kind of object |
|---|---|---|
| \(\mathbf h_v^{(L)}\) | final embedding of node \(v\) after \(L\) layers | vector in \(\mathbb R^d\) |
| \(\hat y\) | the model's prediction (for a node, a pair of nodes or a graph) | class scores or a real number |
| \(y\) | the true label | class index or real number |
| \(\mathbf W^{(H)}\) | weights of the prediction head | \(C\times d\) matrix |
| \(\text{Pool}\) | combines all node embeddings of a graph into one vector: sum, mean or max | order-free function |
| \(p\) | predicted probability of the positive class, \(p=\sigma(\hat y)\) | number in \((0,1)\) |
| \(TP, FP, FN, TN\) | true positives, false positives, false negatives, true negatives | counts |
| \(E_{\text{msg}},\ E_{\text{sup}}\) | message edges (used for message passing) and supervision edges (used as labels) | disjoint sets of edges |
1Prediction heads for the three task levels
In words. For a node: apply one linear map to its embedding. For a pair: take the dot product of the two embeddings. For a whole graph: pool all node embeddings into one vector and apply a head to it.
Why it has this form. A GNN always ends with one vector per node; a head only has to reduce those to the shape of the label. A node label needs \(C\) scores, hence a \(C\times d\) matrix. A link label is one number for two nodes; the dot product is the cheapest symmetric choice (an alternative is a linear layer on the concatenation \([\mathbf h_u\Vert\mathbf h_v]\), which is not symmetric). A graph label needs a function of a set of vectors that ignores their order, which is what pooling provides.
Watch out. Global pooling can erase differences: the node values \(\{-1,-2,0,1,2\}\) and \(\{-10,-20,0,10,20\}\) both sum to 0. Hierarchical pooling (pool small groups first, apply a non-linearity, then pool again) keeps them apart.
2The loss: cross-entropy and squared error
In words. Classification: minus the log of the probability the model gives to the true class. Two classes: the same, written with a single probability \(p\). Regression: the average squared difference.
Why it has this form. Cross-entropy is the negative log-likelihood of the labels under the model's probabilities, so minimising it is maximum likelihood; it punishes confident mistakes heavily. BCE is CE with \(C=2\): when \(y=1\) only \(-\log p\) remains, when \(y=0\) only \(-\log(1-p)\). MSE is the negative log-likelihood under Gaussian noise; squaring makes large errors count much more than small ones.
Watch out. The loss is what is optimised, the metric is what is reported. Accuracy cannot be optimised directly because it is flat almost everywhere (its gradient is zero).
3Metrics for classification
In words. Precision: of the items predicted positive, how many are. Recall: of the true positives, how many were found. \(F_1\): their harmonic mean. ROC AUC: the chance that a random positive is scored above a random negative.
Why it has this form. Accuracy \((TP+TN)/N\) is misleading when classes are unbalanced: predicting 'negative' for everyone is 99% accurate if 1% are positive. Precision and recall look only at the positive class from two sides. The harmonic mean is low if either is low, so \(F_1\) cannot be gamed by sacrificing one. Precision, recall and \(F_1\) depend on the threshold that turns a score into a decision; AUC does not, because it only uses the ranking of the scores.
Watch out. An AUC of 0.5 is chance, not 0. In link prediction negatives vastly outnumber positives, so ranking metrics (Hits@K, MRR) are preferred there.
4Splitting edges for link prediction
In words. Cut the edges into training, validation and test edges. Inside training, some edges carry messages and the others are hidden and used as the positives the model must predict.
Why it has this form. In link prediction an edge is both input (messages travel along it) and label. If an edge is used for message passing while the model is asked whether it exists, the answer leaks: the two endpoints have just exchanged information. So the edge being predicted must be absent from the graph the GNN sees. At validation time the model may see all training edges and predicts the validation edges; at test time it sees training and validation edges and predicts the test edges. More structure becomes visible at each stage, as it would for a deployed model.
Watch out. For an undirected graph stored as two directed edges, both directions of an edge must go to the same side of the split; otherwise the reverse edge gives the answer away.
Check yourself
Questions from the lecture, in order. Answer each one in your head (or on paper) before you open it. If one stumps you, follow the link to the walkthrough block it comes from.
Check yourself: in a bipartite user–item graph, what does the \((u,u')\) entry of \(A^2\) count? show answer
The number of items that users \(u\) and \(u'\) have in common.
from Graph manipulation: the input graph is not the computation graph
Check yourself: a 2-layer GNN, constant features. Does \(v_1\) on a triangle get the same embedding as a node in the middle of a long path? show answer
Yes — both see a node with 2 neighbours, each with 2 neighbours.
from Structures a GNN cannot see: cycle-count features
Check yourself: a virtual node connected to everyone in a social graph with 1 million nodes. What new cost problem does it create? show answer
The virtual node has degree 1 million — it is itself a super-dense hub, so you may need to sample its neighbours too.
from Structure augmentation: virtual nodes and neighbour sampling
Check yourself: why is a linear head usually enough? show answer
The GNN layers already did the non-linear work; the head only has to read the answer out of the embedding. If not, add post-processing MLP layers, as in Lecture 4.
from The training pipeline and node-level prediction heads
Check yourself: in the toy example, does mean pooling help? show answer
Max pooling? (Mean gives 0 and 0 — no. Max gives 2 and 20 — yes here, but it is easy to build cases where max fails, e.g. \(\{0,2\}\) vs \(\{0,0,2\}\).)
from Graph-level prediction heads and the pooling problem
Check yourself: compute the MSE for the slide's example. show answer
Differences 0.5, −0.5, −1.0, 0.2, −0.2; squares 0.25+0.25+1.0+0.04+0.04 = 1.58.
from Loss functions: cross-entropy and MSE
Check yourself: positives scored 0.9 and 0.6, negatives 0.7 and 0.2. AUC? show answer
Of the 4 positive–negative pairs, 3 are ordered correctly, so AUC = 0.75.
from Evaluation metrics: regression, accuracy, precision/recall, ROC AUC
Check yourself: in the transductive setting the GNN sees the features of the test nodes during training. Is that cheating? show answer
No: it never sees their labels. It is the realistic scenario of a single network where you know everyone's profile but only some labels.
from Splitting a graph dataset: transductive vs inductive
Check yourself: why can we not use validation edges for message passing at validation time? show answer
They are the answers. Message passing along them would leak the label into the embeddings.
from Setting up link prediction: message edges and supervision edges
Lecture walkthrough reference · slide by slide · opens on demand
The whole lecture in order, grouped by topic. Every drawing on the slides is redrawn here as a clean figure (click the step buttons where a figure has them), the heading of each block links to the matching pages of the official PDF, and the Review section after the walkthrough ties this session to the earlier ones. Read this and you do not need the deck.
- Graph manipulation: the input graph is not the computation graph
- Feature augmentation: constant vs one-hot features
- Structures a GNN cannot see: cycle-count features
- Structure augmentation: virtual nodes and neighbour sampling
- The training pipeline and node-level prediction heads
- Edge-level prediction heads
- Graph-level prediction heads and the pooling problem
- Where do labels come from? Supervised and self-supervised signals
- Loss functions: cross-entropy and MSE
- Evaluation metrics: regression, accuracy, precision/recall, ROC AUC
- Splitting a graph dataset: transductive vs inductive
- Setting up link prediction: message edges and supervision edges
Graph manipulation: the input graph is not the computation graph slides 10-12 ↗
Lecture 4 built a general GNN framework with five parts: (1) message, (2) aggregation, (3) layer connectivity, (4) graph augmentation, (5) learning objective. This lecture covers parts 4 and 5. Slide 10 shows the framework figure again (You, Ying and Leskovec, "Design Space of Graph Neural Networks", NeurIPS 2020), now highlighting part (4), graph manipulation. Its idea in one line: raw input graph \(\neq\) computational graph. There are two kinds of manipulation: graph feature augmentation and graph structure manipulation.
Slide 11: so far we assumed raw input graph = computational graph. Reasons to break this assumption:
- Feature level: the input graph lacks features → use feature augmentation.
- Structure level:
- the graph is too sparse → message passing is inefficient (information needs many hops to travel);
- the graph is too dense → message passing is too costly (a hub must aggregate a huge number of messages);
- the graph is too large → the computational graph does not fit into a GPU.
- More generally: it is just unlikely that the input graph happens to be the optimal computation graph for embeddings. The graph was recorded for some other reason (who follows whom, which atoms bond), not designed for message passing.
Slide 12 pairs each problem with a fix:
- Graph feature manipulation: input graph lacks features → feature augmentation (covered more in Lecture 7).
- Graph structure manipulation: too sparse → add virtual nodes / edges; too dense → sample neighbours when doing message passing; too large → sample subgraphs to compute embeddings (covered later in the lecture "Scaling up GNNs").
Check yourself: in a bipartite user–item graph, what does the \((u,u')\) entry of \(A^2\) count? show answer
The number of items that users \(u\) and \(u'\) have in common.
Feature augmentation: constant vs one-hot features slides 13-15 ↗
Why do we need feature augmentation? Reason (1) (slides 13–14): the input graph does not have node features. This is common when we only have the adjacency matrix. A GNN needs some vector \(\mathbf{h}_v^{(0)}\) at each node to start message passing, so we must invent one. Two standard approaches:
- (a) Assign constant values to nodes (slide 13). The figure shows a small graph with the value 1 written next to every node.
- (b) Assign unique IDs to nodes (slide 14), and convert the IDs into one-hot vectors. In the figure the graph has 6 nodes, so the total number of IDs is 6; the node with ID = 5 gets the one-hot vector \([0,0,0,0,1,0]\).
Slide 15 compares the two in a table:
- Expressive power. Constant: medium — all the nodes are identical, but the GNN can still learn from the graph structure (for example, with sum aggregation a node can learn its degree). One-hot: high — each node has a unique ID, so node-specific information can be stored.
- Inductive learning (generalise to unseen nodes). Constant: high — simple to generalise to new nodes: assign them the constant feature, then apply the GNN. One-hot: low — new nodes bring new IDs, and the GNN does not know how to embed unseen IDs.
- Computational cost. Constant: low — only a 1-dimensional feature. One-hot: high — a \(|V|\)-dimensional feature, which cannot be applied to large graphs.
- Use cases. Constant: any graph, inductive settings (generalise to new nodes). One-hot: small graphs, transductive settings (no new nodes).
Intuition: one-hot IDs make the first GNN layer \(\mathbf{W}\mathbf{h}_v^{(0)}\) pick out one column of \(\mathbf{W}\) per node — so each node gets its own free trainable vector, exactly like the shallow embeddings of Lecture 3 (DeepWalk, node2vec). That explains both the high expressiveness and the failure to generalise.
Structures a GNN cannot see: cycle-count features slides 16-18 ↗
Reason (2) for feature augmentation (slide 16): certain structures are hard to learn by a GNN. Example: the cycle-count feature. Can a GNN learn the length of the cycle that node \(v_1\) lies on? The figure shows \(v_1\) on a triangle (cycle of length 3) and \(v_1\) on a square (cycle of length 4). The answer: unfortunately, no.
Slide 17 explains why. \(v_1\) cannot tell which graph it lives in, because all the nodes in both graphs have degree 2. Unroll the computational graph of \(v_1\): it has 2 children, each child has 2 children, and so on — the same binary tree in both cases (all nodes have the same feature, so the tree carries no other information). The slide adds a third case: \(v_1\) on a cycle of infinite length (an infinite path, drawn as a line with dots at both ends) gives the same binary tree too. So a message-passing GNN maps \(v_1\) to the same embedding in all three graphs.
Slide 18 gives the fix (from You, Gomes-Selman, Ying and Leskovec, "Identity-aware Graph Neural Networks", AAAI 2021): use the cycle count as an augmented node feature. The feature vector counts cycles by length, starting from length 0. For \(v_1\) on the triangle the vector is \([0,0,0,1,0,0]\) (a 1 at position 3); for \(v_1\) on the square it is \([0,0,0,0,1,0]\) (a 1 at position 4). Now the two nodes have different input features, so the GNN can separate them.
Other augmented features in the same spirit: node degree, clustering coefficient, PageRank, centrality — any of the hand-crafted features from Lecture 1 can be appended to \(\mathbf{x}_v\).
This is a preview of Lecture 6: a message-passing GNN can only distinguish nodes whose rooted computation trees differ. Hand-computed structural features are one way to break that ceiling; Lecture 7 shows others.
Check yourself: a 2-layer GNN, constant features. Does \(v_1\) on a triangle get the same embedding as a node in the middle of a long path? show answer
Yes — both see a node with 2 neighbours, each with 2 neighbours.
Structure augmentation: virtual nodes and neighbour sampling slides 19-23 ↗
Augmenting sparse graphs (slide 19). Besides virtual edges, we can add a virtual node that connects to all the nodes in the graph. Suppose two nodes in a sparse graph have shortest-path distance 10. After adding the virtual node, all pairs of nodes are at distance at most 2 (node A – virtual node – node B). Benefit: this greatly improves message passing in sparse graphs. The figure shows a small graph with one extra grey node above it, joined to every original node.
Neighbour sampling for dense graphs (slide 20; Hamilton et al., "Inductive Representation Learning on Large Graphs", NeurIPS 2017 — GraphSAGE). Our approach so far: all the neighbours are used for message passing. Problem: dense or large graphs and high-degree nodes make this expensive. New idea: (randomly) determine a node's neighbourhood for message passing. The figure shows target node A in the input graph and its computation tree with every neighbour present.
- Slide 21: for example, randomly choose 2 neighbours to pass messages. Only nodes \(B\) and \(D\) pass a message to \(A\); the other branches are crossed out in red in both the graph and the tree.
- Slide 22: next time we compute the embeddings, we can sample different neighbours — now only \(C\) and \(D\) pass a message to \(A\). (Sampling also happens at the second level of the tree.)
- Slide 23 (Ying et al., "Graph Convolutional Neural Networks for Web-Scale Recommender Systems", KDD 2018 — PinSage): in expectation we get embeddings similar to the case where all the neighbours are used. Benefit: a large reduction in computational cost. "And in practice it works great!"
Why "in expectation"? With mean aggregation, the mean of a uniformly random subset of neighbours is an unbiased estimate of the mean over all neighbours. Each epoch sees a different sample, so the noise averages out during training, much like mini-batch SGD.
Check yourself: a virtual node connected to everyone in a social graph with 1 million nodes. What new cost problem does it create? show answer
The virtual node has degree 1 million — it is itself a super-dense hub, so you may need to sample its neighbours too.
The training pipeline and node-level prediction heads slides 25-29 ↗
Slide 25 returns to the framework figure, now highlighting part (5), the learning objective. Next question: how do we train a GNN?
Slide 26 draws the full GNN training pipeline as a row of boxes: Input graph → Graph Neural Network → Node embeddings → Prediction head → Predictions; the predictions are compared with the Labels by a Loss function (for training) and by Evaluation metrics (for judging the model). So far we have covered the first three boxes (shown inside a dashed frame). The output of a GNN is a set of node embeddings \(\{\mathbf{h}_v^{(L)},\ \forall v\in G\}\). The rest of the lecture walks through the other boxes in order: (1) prediction heads, (2) labels, (3) loss, (4) metrics, (5) dataset split.
Slide 27 highlights box (1): different prediction heads for node-level, edge-level and graph-level tasks. Slide 28: the idea is that different task levels require different prediction heads. The figure shows one graph with three arrows: node-level prediction (one node), edge-level prediction (a pair of nodes) and graph-level prediction (the whole graph).
Node-level prediction (slide 29): we can make a prediction directly from the node embeddings. After GNN computation we have \(d\)-dimensional embeddings \(\{\mathbf{h}_v^{(L)}\in\mathbb{R}^d,\ \forall v\in G\}\). Suppose we want a \(k\)-way prediction: classification among \(k\) categories, or regression on \(k\) targets. Then
\[ \hat{\mathbf{y}}_v=\mathrm{Head}_{\text{node}}\big(\mathbf{h}_v^{(L)}\big)=\mathbf{W}^{(H)}\mathbf{h}_v^{(L)},\qquad \mathbf{W}^{(H)}\in\mathbb{R}^{k\times d}. \]\(\mathbf{W}^{(H)}\) maps the embedding \(\mathbf{h}_v^{(L)}\in\mathbb{R}^d\) to \(\hat{\mathbf{y}}_v\in\mathbb{R}^k\), so that we can compute the loss. For classification, a softmax is then applied (see the loss block).
Check yourself: why is a linear head usually enough? show answer
The GNN layers already did the non-linear work; the head only has to read the answer out of the embedding. If not, add post-processing MLP layers, as in Lecture 4.
Edge-level prediction heads slides 30-32 ↗
Edge-level prediction (slide 30): make a prediction from pairs of node embeddings. For a \(k\)-way prediction,
\[ \hat{\mathbf{y}}_{uv}=\mathrm{Head}_{\text{edge}}\big(\mathbf{h}_u^{(L)},\mathbf{h}_v^{(L)}\big). \]The figure marks two nodes \(u\) and \(v\) with a question mark between them. What are the options for \(\mathrm{Head}_{\text{edge}}\)?
(1) Concatenation + Linear (slide 31). We have seen this in graph attention (the attention mechanism of GAT in Lecture 4):
\[ \hat{\mathbf{y}}_{uv}=\mathrm{Linear}\big(\mathrm{Concat}(\mathbf{h}_u^{(L)},\mathbf{h}_v^{(L)})\big). \]Here \(\mathrm{Linear}(\cdot)\) maps the \(2d\)-dimensional concatenated vector to a \(k\)-dimensional output (\(k\)-way prediction). The figure stacks the two embedding bars, then a Linear box, then \(\hat y_{uv}\).
(2) Dot product (slide 32):
\[ \hat{y}_{uv}=\big(\mathbf{h}_u^{(L)}\big)^{\!\top}\mathbf{h}_v^{(L)}. \]This only gives a 1-way prediction (a single number), e.g. link prediction: does an edge exist? To get a \(k\)-way prediction, do something similar to multi-head attention: introduce trainable matrices \(\mathbf{W}^{(1)},\dots,\mathbf{W}^{(k)}\) and compute one bilinear score per head,
\[ \hat{y}_{uv}^{(i)}=\big(\mathbf{h}_u^{(L)}\big)^{\!\top}\mathbf{W}^{(i)}\mathbf{h}_v^{(L)},\quad i=1,\dots,k,\qquad \hat{\mathbf{y}}_{uv}=\mathrm{Concat}\big(\hat{y}_{uv}^{(1)},\dots,\hat{y}_{uv}^{(k)}\big)\in\mathbb{R}^k. \]A difference worth noticing: the plain dot product is symmetric (\(\hat y_{uv}=\hat y_{vu}\)), which suits undirected friendship. Concat + linear and a non-symmetric \(\mathbf{W}\) can be asymmetric, which suits directed relations like "follows".
Graph-level prediction heads and the pooling problem slides 33-36 ↗
Graph-level prediction (slide 33): make a prediction using all the node embeddings in the graph. For \(k\)-way prediction,
\[ \hat{\mathbf{y}}_G=\mathrm{Head}_{\text{graph}}\big(\{\mathbf{h}_v^{(L)}\in\mathbb{R}^d,\ \forall v\in G\}\big). \]\(\mathrm{Head}_{\text{graph}}(\cdot)\) is similar to \(\mathrm{AGG}(\cdot)\) in a GNN layer: it turns a set of vectors into one vector. The figure puts the whole graph under one aggregation box, next to the message/aggregation picture of a GNN layer.
Options (slide 34; the citation is Xu, Hu, Leskovec and Jegelka, "How Powerful Are Graph Neural Networks?", ICLR 2019 — the GIN paper of Lecture 6):
- Global mean pooling: \(\hat{\mathbf{y}}_G=\mathrm{Mean}(\{\mathbf{h}_v^{(L)}\in\mathbb{R}^d,\ \forall v\in G\})\).
- Global max pooling: \(\hat{\mathbf{y}}_G=\mathrm{Max}(\{\mathbf{h}_v^{(L)}\in\mathbb{R}^d,\ \forall v\in G\})\).
- Global sum pooling: \(\hat{\mathbf{y}}_G=\mathrm{Sum}(\{\mathbf{h}_v^{(L)}\in\mathbb{R}^d,\ \forall v\in G\})\).
These options work great for small graphs. Can we do better for large graphs?
Slide 35 shows the issue: global pooling over a (large) graph loses information. Toy example with 1-dimensional node embeddings:
- \(G_1\): \(\{-1,-2,0,1,2\}\); \(G_2\): \(\{-10,-20,0,10,20\}\).
- Clearly \(G_1\) and \(G_2\) have very different node embeddings, so their structures should be different.
- Global sum pooling: \(\hat y_{G_1}=\mathrm{Sum}(\{-1,-2,0,1,2\})=0\) and \(\hat y_{G_2}=\mathrm{Sum}(\{-10,-20,0,10,20\})=0\). We cannot differentiate \(G_1\) and \(G_2\)!
Slide 36 gives this year's fix: to embed a graph, add a virtual super node that connects to all the nodes in the graph (the figure shows a grey node above the graph, linked to every node). Then the graph embedding is the embedding of the super node. Benefit: the GNN learns how to encode the entire input graph, instead of using a fixed pooling rule.
Check yourself: in the toy example, does mean pooling help? show answer
Max pooling? (Mean gives 0 and 0 — no. Max gives 2 and 20 — yes here, but it is easy to build cases where max fails, e.g. \(\{0,2\}\) vs \(\{0,0,2\}\).)
Where do labels come from? Supervised and self-supervised signals slides 38-41 ↗
Slide 38 highlights box (2) of the pipeline: where does the ground truth come from? Supervised labels or unsupervised signals.
Slide 39:
- Supervised learning on graphs: labels come from external sources, e.g. predict the drug likeness of a molecular graph.
- Unsupervised learning on graphs: signals come from the graphs themselves, e.g. link prediction: predict whether two nodes are connected.
- Sometimes the difference is blurry. We still have "supervision" in unsupervised learning, e.g. train a GNN to predict the node clustering coefficient. An alternative name for "unsupervised" here is "self-supervised".
Supervised labels come from the specific use case (slide 40):
- Node labels \(y_v\): in a citation network, which subject area a node belongs to.
- Edge labels \(y_{uv}\): in a transaction network, whether an edge is fraudulent.
- Graph labels \(y_G\): among molecular graphs, the drug likeness of the graphs.
Advice: reduce your task to node / edge / graph labels, since they are easy to work with. For example, if we know that some nodes form a cluster, we can treat the cluster a node belongs to as a node label.
Unsupervised (self-supervised) signals (slide 41). The problem: sometimes we only have a graph, without any external labels. The solution: find supervision signals within the graph. For example, let the GNN predict:
- Node level \(y_v\): node statistics such as clustering coefficient or PageRank.
- Edge level \(y_{uv}\): link prediction — hide the edge between two nodes and predict whether there should be a link.
- Graph level \(y_G\): graph statistics, for example predict whether two graphs are isomorphic.
These tasks do not require any external labels.
Why would you train a GNN to predict PageRank, which you could just compute? Because the goal is not the prediction itself but the embeddings it forces the GNN to learn — a form of pre-training. The learned weights can then be fine-tuned on a task with few real labels.
Loss functions: cross-entropy and MSE slides 42-46 ↗
Slide 42 highlights box (3): how do we compute the final loss? Classification loss or regression loss.
Setting (slide 43): we have \(N\) data points, each a node, edge or graph. Node level: prediction \(\hat{\mathbf{y}}_v^{(i)}\), label \(\mathbf{y}_v^{(i)}\); edge level: \(\hat{\mathbf{y}}_{uv}^{(i)}\), \(\mathbf{y}_{uv}^{(i)}\); graph level: \(\hat{\mathbf{y}}_G^{(i)}\), \(\mathbf{y}_G^{(i)}\). From now on, \(\hat{\mathbf{y}}^{(i)}\) and \(\mathbf{y}^{(i)}\) refer to predictions and labels at any level.
Slide 44: classification — labels \(\mathbf{y}^{(i)}\) have discrete values (e.g. which category a node belongs to). Regression — labels have continuous values (e.g. the drug likeness of a molecular graph). GNNs can be applied to both settings; the differences are the loss function and the evaluation metrics.
Classification loss (slide 45). Cross-entropy (CE) is a very common loss for classification. For a \(K\)-way prediction on the \(i\)-th data point:
\[ \mathrm{CE}\big(\mathbf{y}^{(i)},\hat{\mathbf{y}}^{(i)}\big)=-\sum_{j=1}^{K}\mathbf{y}_j^{(i)}\log\big(\hat{\mathbf{y}}_j^{(i)}\big), \]where \(\mathbf{y}^{(i)}\in\mathbb{R}^K\) is the one-hot label encoding (the slide's example: \([0,0,1,0,0]\)) and \(\hat{\mathbf{y}}^{(i)}\in\mathbb{R}^K\) is the prediction after \(\mathrm{Softmax}(\cdot)\) (example: \([0.1,0.3,0.4,0.1,0.1]\)). Total loss over all \(N\) training examples: \(\mathrm{Loss}=\sum_{i=1}^N\mathrm{CE}(\mathbf{y}^{(i)},\hat{\mathbf{y}}^{(i)})\).
With a one-hot label only one term survives: CE is \(-\log\) of the probability given to the correct class. In the slide's example that is \(-\log 0.4\approx 0.92\). A perfect prediction (probability 1) gives loss 0.
Regression loss (slide 46). We often use Mean Squared Error (MSE), also called L2 loss. For a \(K\)-way regression on data point \(i\):
\[ \mathrm{MSE}\big(\mathbf{y}^{(i)},\hat{\mathbf{y}}^{(i)}\big)=\sum_{j=1}^{K}\big(\mathbf{y}_j^{(i)}-\hat{\mathbf{y}}_j^{(i)}\big)^2, \]where \(\mathbf{y}^{(i)}\in\mathbb{R}^k\) is the real-valued vector of targets (example: \([1.4,2.3,1.0,0.5,0.6]\)) and \(\hat{\mathbf{y}}^{(i)}\in\mathbb{R}^k\) the real-valued vector of predictions (example: \([0.9,2.8,2.0,0.3,0.8]\)). Total loss: \(\mathrm{Loss}=\sum_{i=1}^N\mathrm{MSE}(\mathbf{y}^{(i)},\hat{\mathbf{y}}^{(i)})\).
Check yourself: compute the MSE for the slide's example. show answer
Differences 0.5, −0.5, −1.0, 0.2, −0.2; squares 0.25+0.25+1.0+0.04+0.04 = 1.58.
Evaluation metrics: regression, accuracy, precision/recall, ROC AUC slides 47-52 ↗
Slide 47 highlights box (4): how do we measure the success of a GNN? Accuracy, ROC AUC. Slide 48: we use standard evaluation metrics (the content is in any ML course); in practice we use sklearn. Suppose we make predictions for \(N\) data points.
Regression (slide 48):
\[ \mathrm{RMSE}=\sqrt{\sum_{i=1}^{N}\frac{\big(\mathbf{y}^{(i)}-\hat{\mathbf{y}}^{(i)}\big)^2}{N}},\qquad \mathrm{MAE}=\frac{\sum_{i=1}^{N}\big|\mathbf{y}^{(i)}-\hat{\mathbf{y}}^{(i)}\big|}{N}. \]Classification (slide 49). (1) Multi-class: simply report the accuracy, \(\frac1N\sum_{i}\mathbb{1}\big[\arg\max(\hat{\mathbf{y}}^{(i)})=\mathbf{y}^{(i)}\big]\). (2) Binary: some metrics are sensitive to the classification threshold — accuracy, precision / recall (if predictions lie in \([0,1]\), we use 0.5 as the threshold). One metric is agnostic to the threshold: ROC AUC.
Slide 50 defines them with the confusion matrix (rows: predicted positive / negative; columns: actually positive / negative; cells TP, FP, FN, TN):
\[ \text{Accuracy}=\frac{TP+TN}{TP+TN+FP+FN}=\frac{TP+TN}{|\text{Dataset}|},\quad P=\frac{TP}{TP+FP},\quad R=\frac{TP}{TP+FN},\quad F1=\frac{2PR}{P+R}. \]The slide links to sklearn's classification report, which prints all of these per class.
ROC curve (slide 51): it captures the trade-off between TPR and FPR as the classification threshold is varied for a binary classifier, where \(\mathrm{TPR}=\mathrm{Recall}=\frac{TP}{TP+FN}\) and \(\mathrm{FPR}=\frac{FP}{FP+TN}\). The plot (from Wikipedia) has FPR on the x-axis and TPR on the y-axis, both from 0 to 1, with a few classifiers drawn as staircase curves above the diagonal. The dashed diagonal is the performance of a random classifier.
ROC AUC (slide 52): the area under the ROC curve. Intuition: the probability that the classifier ranks a randomly chosen positive instance higher than a randomly chosen negative one. A random classifier gets 0.5, a perfect ranking gets 1.
Why does the threshold not matter? Sweeping the threshold from high to low traces the whole curve; AUC summarises all thresholds at once and depends only on the ordering of the scores. That makes it natural for link prediction, where we care whether true edges are ranked above non-edges.
Check yourself: positives scored 0.9 and 0.6, negatives 0.7 and 0.2. AUC? show answer
Of the 4 positive–negative pairs, 3 are ordered correctly, so AUC = 0.75.
Splitting a graph dataset: transductive vs inductive slides 54-62 ↗
Slide 54 highlights box (5): how do we split the dataset into train / validation / test sets?
Fixed split vs random split (slide 55). Fixed split: split the dataset once. The training set is used for optimising GNN parameters; the validation set for developing the model and hyperparameters; the test set is held out until we report final performance. A concern: sometimes we cannot guarantee that the test set will really be held out. Random split: randomly split the dataset into training / validation / test, and report the average performance over different random seeds.
Why splitting graphs is special. Slide 56: for an image dataset each data point is an image, and the data points are independent — image 5 will not affect our prediction on image 1. The figure assigns nodes 1, 2 to training, 3, 4 to validation and 5, 6 to test, with no edges between them. Slide 57: splitting a graph dataset is different. In node classification each data point is a node, and the data points are not independent: node 5 will affect our prediction on node 1, because it participates in message passing and so affects node 1's embedding. The figure is the same six nodes, now joined by edges. What are our options?
- Solution 1: transductive setting (slide 58). The input graph can be observed in all the dataset splits; we only split the (node) labels. At training time we compute embeddings using the entire graph and train using the labels of nodes 1 and 2. At validation time we compute embeddings using the entire graph and evaluate on the labels of nodes 3 and 4.
- Solution 2: inductive setting (slide 59). We break the edges between splits to get multiple graphs. Now we have 3 independent graphs, and node 5 no longer affects our prediction on node 1. At training time we compute embeddings using the graph over nodes 1 and 2 and train using their labels; at validation time we compute embeddings using the graph over nodes 3 and 4 and evaluate on their labels.
Slide 60 summarises. Transductive: training / validation / test sets are on the same graph; the dataset consists of one graph; the entire graph can be observed in all splits, only the labels are split; applicable only to node / edge prediction tasks. Inductive: the splits are on different graphs; the dataset consists of multiple graphs; each split can only observe the graph(s) within it, and a successful model must generalise to unseen graphs; applicable to node / edge / graph tasks.
Examples. Slide 61, node classification: transductive — all the splits observe the entire graph structure but only the labels of their own nodes (one graph with nodes coloured by split); inductive — with a dataset of 3 graphs, each split contains an independent graph. Slide 62, graph classification: only the inductive setting is well defined, because we have to test on unseen graphs. With a dataset of 5 graphs, each split contains independent graph(s) (the figure: 3 graphs for training, 1 for validation, 1 for test).
Check yourself: in the transductive setting the GNN sees the features of the test nodes during training. Is that cheating? show answer
No: it never sees their labels. It is the realistic scenario of a single network where you know everyone's profile but only some labels.
Setting up link prediction: message edges and supervision edges slides 63-72 ↗
Slide 63: the goal of link prediction is to predict missing edges. Setting it up is tricky. Link prediction is an unsupervised / self-supervised task: we need to create the labels and dataset splits on our own. Concretely, we hide some edges from the GNN and let the GNN predict whether those edges exist. The figure: the original graph (5 nodes); the input graph to the GNN, with two edges removed; the predictions made by the GNN, with question marks on the hidden edges.
For link prediction we split edges twice.
Step 1 (slide 64): assign 2 types of edges in the original graph.
- Message edges: used for GNN message passing.
- Supervision edges: used for computing objectives.
After step 1, only message edges remain in the graph. Supervision edges are used as supervision for the edge predictions made by the model; they are not fed into the GNN. (In the figure, black edges are message edges, orange ones are supervision edges.)
Step 2: split edges into train / validation / test.
- Option 1: inductive link prediction split (slides 65–66). Suppose we have a dataset of 3 graphs \(G_1,G_2,G_3\). Each inductive split contains an independent graph: \(G_1\) training, \(G_2\) validation, \(G_3\) test. In each split, each graph has 2 types of edges: message edges + supervision edges. Supervision edges are not input to the GNN.
- Option 2: transductive link prediction split (slides 67–70). This is the default setting when people talk about link prediction. Suppose we have a dataset of 1 graph. By definition of "transductive", the entire graph can be observed in all splits. But since edges are both part of the graph structure and the supervision, we must hold out validation / test edges; and to train, we further hold out supervision edges for the training set.
The exact settings (slide 69):
- At training time: use training message edges to predict training supervision edges.
- At validation time: use training message edges and training supervision edges to predict validation edges.
- At test time: use training message edges, training supervision edges and validation edges to predict test edges.
Why a growing number of edges (slide 70)? After training, the supervision edges are known to the GNN. Therefore an ideal model should use the supervision edges in message passing at validation time. The same applies at test time.
Slide 71 summarises: the original graph is split into a graph with 4 types of edges — training message edges, training supervision edges, validation edges and test edges. Note: link prediction settings are tricky and complex, and you may find papers that do link prediction differently. Luckily, PyG and GraphGym fully support it. Slide 72 closes with the full pipeline figure, now including the dataset-split box (a row of small graphs above the pipeline). Implementation resource: GraphGym further implements the full pipeline to facilitate GNN design.
The most common bug: forgetting to remove the supervision edges from the graph during training. The GNN then passes messages along the very edge it must predict, the task becomes trivial, and the scores look excellent but mean nothing.
Check yourself: why can we not use validation edges for message passing at validation time? show answer
They are the answers. Message passing along them would leak the label into the embeddings.
Not shown (no new content): slides 1,2,3,4,5,6,7,8,9,24,37,53 — title page, announcements, course-project logistics (project types, deadlines, groups) and section-divider title pages.
Review: what to keep from this session
Carried forward. Lecture 6 uses the "predict a structural property" idea as an expressiveness test; Lecture 11 reuses the link-prediction split for recommendation; Lecture 19 shows the pipeline figure again as the frame for the design-space study.
Quick self-check
When would you add a virtual node?
When the graph is too sparse for messages to travel, e.g. long chains; the virtual node connects to everything, so any two nodes are two hops apart.
Why can you not simply split nodes at random for link prediction?
Edges used for message passing must not also be the edges you are predicting; otherwise the model sees the answer. Message, supervision, validation and test edges are kept apart.
What is the difference between a transductive and an inductive split?
Transductive: one graph, all nodes visible, only labels are split. Inductive: separate graphs (or subgraphs) for training and test, so test nodes are never seen.
Key idea
Choose the computation graph deliberately (features, virtual nodes, sampling), pick the head that matches the task level, and split so that information from validation/test can never leak into training through message passing.
Worked example: ROC AUC by counting pairs
A link predictor scores two true edges (positives) and two non-edges (negatives): positives 0.9, 0.6; negatives 0.7, 0.2.
- Form all positive–negative pairs: (0.9, 0.7) ✓, (0.9, 0.2) ✓, (0.6, 0.7) ✗, (0.6, 0.2) ✓.
- AUC = fraction of pairs where the positive scores higher = 3/4 = 0.75.
- Accuracy at threshold 0.5: predict edge for 0.9, 0.6, 0.7 → 2 TP, 1 FP, 1 TN → accuracy 0.75, precision 0.67, recall 1.0. Move the threshold to 0.65 and accuracy becomes 1.0 — but AUC doesn't change. That's why AUC is the default for link prediction.
Strictly speaking: for very imbalanced link prediction (millions of non-edges per edge), ranking metrics like Hits@K and MRR (used by OGB) are more informative than AUC — Lectures 10–11.
In code (PyG)
import torch_geometric.transforms as T
split = T.RandomLinkSplit(num_val=0.1, num_test=0.1, is_undirected=True,
add_negative_train_samples=False, disjoint_train_ratio=0.3)
train_data, val_data, test_data = split(data)
# train_data.edge_index -> message edges
# train_data.edge_label_index, edge_label -> supervision edges (+ negatives)
from torch_geometric.loader import NeighborLoader # neighbour sampling
loader = NeighborLoader(data, num_neighbors=[25, 10], batch_size=512, input_nodes=data.train_mask)
Proof workshop: ROC AUC is a pair-counting probability
One problem in olympiad style. Give it fifteen minutes on paper before you open the first hint; the hints are graded, so open them one at a time.
Problem. A classifier scores \(P\) positives and \(N\) negatives (assume no ties). Prove that the area under the ROC curve equals \(\frac1{PN}\#\{(i,j):s_i^+>s_j^-\}\), the probability that a random positive outscores a random negative.
Hint 1
Hint 2
Solution
Why it matters. AUC is a ranking quantity: it does not care about calibration, and it depends on which negatives you compare against. In link prediction, random non-edges are easy negatives, so AUC can look excellent while the model fails on the hard negatives that matter. This is EdgeBank's point (Lecture 5 frontier), and the reason to report hard-negative or historical-negative metrics.
Sharper lens: what the estimators and metrics actually estimate
Not on the slides. Three or four points where the lecture rounds something off: the exact statement, a second way to see it, and where it stops being true. Each is short and has a pointer for going further.
Neighbour sampling is unbiased for one linear layer only
"In expectation the embedding matches full aggregation" holds for the sampled mean itself: \(\mathbb E\big[\tfrac1{|S|}\sum_{u\in S}\mathbf h_u\big]=\tfrac1{|N(v)|}\sum_{u\in N(v)}\mathbf h_u\). Apply a non-linearity and it stops: \(\mathbb E[\sigma(\cdot)]\ne\sigma(\mathbb E[\cdot])\), and the gap compounds through the layers, so both embeddings and gradients are biased, with variance growing as the fan-out shrinks (Chen, Zhu and Song 2018, who reduce it with stored "historical" activations). Training tolerates this well; evaluation should not inherit it. Compute validation and test embeddings with the full neighbourhood, layer by layer over the whole graph (the inference pattern in PyG's examples), or your reported number depends on a random seed in the loader.
AUC 0.99 can mean "ranked ten-thousandth"
By the proof workshop, \(1-\mathrm{AUC}\) is the fraction of negatives that outrank a typical positive. Link prediction is extremely imbalanced: a graph with \(10^6\) candidate non-edges per true edge and \(\mathrm{AUC}=0.99\) places a typical true edge behind \(0.01\times10^6=10^4\) non-edges. Its precision in the top 100 can be zero. AUC is insensitive to the only region a recommender or an analyst ever looks at, the top of the list.
This is the arithmetic behind the move to Hits@K and MRR (OGB), and behind the finding that the choice of negatives decides the ranking of methods: with hard negatives sampled near each positive, the simple heuristics of Lecture 20 return to the top of several leaderboards (Li et al., NeurIPS 2023, the HeaRT protocol). Report a top-heavy metric, and say how the negatives were drawn.
A virtual node is global attention through one vector
A virtual node receives the sum of all node states and broadcasts one vector back. That is a single, uniform attention head over the whole graph: every pair of nodes can now communicate in two hops, but everything they say to each other passes through \(d\) numbers. Cai et al. (ICML 2023) made the relation exact: an MPNN with a virtual node can approximate a self-attention layer, but needs width that grows with the graph. So the virtual node fixes reach cheaply, in \(O(n)\) instead of \(O(n^2)\), and replaces many small bottlenecks by one large one. Try it in Lecture 4's interactive figure: choose "+ a virtual node" and the far side of the graph arrives in a handful of layers instead of dozens, while two nodes on the same side still become indistinguishable after about four.
Lab: hands-on and practical tips
Try it live. In the Graph Explorer: change the labelled share and the split on Cora and see a link-prediction split leak through the degrees. Each lesson has predict-then-check questions.
notebook · L05 augmentation & training covers feature augmentation, virtual nodes, a hand-written neighbour sampler, prediction heads, AUC by pair counting, and RandomLinkSplit with a leakage demonstration.
NeighborLoader(num_neighbors=[15, 10]) caps the fan-out; the cost is \(M\cdot H^K\) node computations per batch (Lecture 20 compares it with Cluster-GCN).Readings & lookup guide
lecture notes CS224W course notes (Leni Aniva, Autumn 2024 — in your course folder)
- Ch. 5 — GNN augmentation and training (pp. 28–30)
assigned Ying et al. — Hierarchical Graph Representation Learning with Differentiable Pooling (DiffPool, NeurIPS 2018)
- Problem it solves: the "global pooling loses information" issue from §2 above.
- Read: §3.2 — two GNNs per level: one computes embeddings \(Z\), one computes a soft cluster-assignment matrix \(S\) (softmax over clusters); then \(X'=S^\top Z\), \(A'=S^\top AS\). That pair of equations is the paper.
- Note: the auxiliary link-prediction loss and entropy regulariser (§3.3) — needed to make \(S\) sensible.
- Look up later: the \(O(n^2)\) memory of dense \(S\) — why later work (SAGPool, MinCutPool) exists.
useful Hamilton et al. 2017 (GraphSAGE) §3.1 and Ying et al. 2018 (PinSage) §3
- PinSage samples neighbours by random-walk importance instead of uniformly — a neat bridge between Lecture 2 and this lecture.
evaluation hygiene Shchur et al. — Pitfalls of Graph Neural Network Evaluation (2018)
- Shows that GNN rankings flip under different random splits — the empirical reason behind "report the mean over seeds".
Homework, Colabs & the course project
Course project (30%) proposal due Tue 10/20
- Real-world application of GNNs with PyG (fraud detection, drug interactions, friend recommendation) → blog post + Colab.
- Tutorial on PyG functionality (explainability module, sampling on heterogeneous graphs, GraphGym) → blog post + Colab.
- Implementation of recent research → PR to PyG contrib + short blog post (more demanding; best with PyTorch fluency).
Good projects get published on the course's Medium page. Idea for you: a PyG tutorial on heterogeneous social graphs (users–tweets–hashtags) with RandomLinkSplit for retweet prediction — it directly reuses this lecture.
Homework 1 due Thu 10/15
Q1.5 (over-smoothing) and Q1.6 (BFS) relate to this lecture's discussion of computation graphs. Full overview on the Lecture 4 page.
Colab 2 (out Thu 10/8, due 10/22)
Expect node- and graph-level prediction heads and OGB evaluators — the pipeline in the picture above, in code. Details on the Lecture 6 page.
Self-check
New users join your social network every minute. Which node features keep the GNN inductive?
- One-hot node IDs
- Constant features or attribute-based features
- DeepWalk embeddings
- Learned per-node free vectors
IDs and free vectors don't exist for unseen nodes; constants/attributes do.
Why can't a plain message-passing GNN tell a node on a 3-cycle from one on a 4-cycle (constant features)?
- Too few layers
- Mean aggregation
- Both nodes have identical computation trees
- Over-smoothing
All degrees are 2 → the same binary tree at every depth, for any aggregator.
In transductive node classification, what is split between train/val/test?
- Only the node labels
- The nodes and all their edges
- The graph into connected components
- The feature dimensions
The full graph is observed in all splits; only which labels are used differs.
During training for link prediction, supervision edges should be …
- used for message passing and loss
- discarded
- used only for message passing
- used only in the loss, never for message passing
Otherwise the model sees the answer — leakage.
ROC AUC equals …
- accuracy at threshold 0.5
- the probability a random positive is ranked above a random negative
- precision × recall
- 1 − FPR
That pairwise-ranking interpretation is why it's threshold-free.
Flashcards (click to flip)
History & the bigger picture
- Planetoid splits (Yang et al. 2016) — the fixed 20-labels-per-class splits of Cora/Citeseer/Pubmed that a whole generation of GNN papers tuned to. Later work (Shchur 2018) showed how fragile those conclusions were.
- 2018 — PinSage at Pinterest: neighbour sampling + producer–consumer minibatching on 3 billion nodes. Sampling made GNNs industrial.
- 2019–2020 — Cluster-GCN, GraphSAINT: sample subgraphs rather than neighbourhoods. 2020 — OGB (Open Graph Benchmark): standard large datasets, realistic splits (by time, by molecular scaffold) and official evaluators.
The transductive/inductive distinction is an epistemological one: does the model predict or merely interpolate within a world it has already seen? Splitting by time (train on the past, test on the future) is the honest version for social data — and it's what OGB and RelBench (Lecture 12) adopted. Random splits on a social graph quietly let the future leak into the past.
Classic SNA bridge
| In this lecture | Classic SNA counterpart | What carried over, what changed |
|---|---|---|
| Transductive vs inductive splits | Sampling in network surveys: snowball, respondent-driven, boundary specification (Laumann et al. 1983) | SNA worried about which nodes are in the study at all; graph ML worries about which labels and edges the model may see. Both are versions of the boundary-specification problem. |
| Link prediction with message vs supervision edges | Tie formation studies; the Liben-Nowell & Kleinberg (2003) framing of link prediction on co-authorship networks | The classical framing already used temporal splits (train on years before \(t\), predict new collaborations). GNN link prediction added a second split inside the training period. |
| Feature augmentation: cycle counts, node IDs | Triad census; cyclic closure; Simmelian ties | Counting small cycles was the heart of structural sociology (Holland & Leinhardt 1970s). GNNs cannot count them (Lecture 6), so the augmentation re-imports the triad census as a feature. |
| Virtual node connecting everything | Two-mode "affiliation to the whole"; the global mean field | A virtual node is a mean-field shortcut: every node sees the global average in one hop, the way a mean-field opinion model treats the population. |
| ROC AUC = P(positive outscores negative) | Quadratic assignment procedure (QAP) and permutation tests for dyadic hypotheses (Krackhardt 1987) | Dyads are not independent, which is why SNA invented permutation tests. AUC on held-out edges is a prediction metric, not a test of a dyadic hypothesis; keep the two questions apart. |
Run the same link-prediction model with three negative-sampling schemes (uniform, degree-matched, historical) on a reply graph. Then run a QAP regression on the same dyadic variables. If the model's AUC ranking of features disagrees with the QAP coefficients, you have a concrete example of how negatives, not features, drive a graph-ML conclusion.
Go deeper in the SNA course. The twelve-unit course on social network analysis in this repository gives the classic side of this lecture in full, with labs and real-data analyses: Unit 9 · Beyond pairwise: higher-order, temporal, multilayer (splitting data in time instead of at random); Unit 10 · Causality, interference & graph ML (splits and leakage: the experimental-design problems of graph ML).
Connecting to your research
Running project. Section L05 · honest splits of notebooks/project/retweet_thread.py applies this lecture to one synthetic X world with coordinated rings, the same graph across the whole course.
Research extension. experiments/honest-splits (hypotheses written before running): a random node split overestimates a label-aware bot detector by 0.18–0.25 AUC against holding out whole rings, and the label features make the honest number worse; random edge splits overestimate link prediction by 0.12–0.14.
- Split by time for retweet/follow prediction: message edges = interactions before \(t_0\), supervision = interactions in \([t_0,t_1)\). This avoids leakage and matches the real question ("who will engage next?").
- Self-supervised pre-training is natural: you have billions of edges but few labels (bots, stances). Pre-train on link prediction, then fine-tune a node head.
- Hubs: celebrity accounts have millions of followers — neighbour sampling is not optional. Consider importance sampling (PinSage-style) so that rare but informative neighbours aren't drowned out.
From the experiments: results and datasets
Generated by scripts/sync_guides.py from the experiments' committed results and the dataset catalogue; rerun it (make sync-guides) after an experiment changes.
honest-splits
Question. How much does a random split overestimate a detector, on synthetic rings and on real temporal networks? experiment folder ↗
Verdicts (hypotheses written before running): H1 refuted, H2 supported, H3 refuted, H4 refuted, H5 supported; H6 refuted, H7 supported.
gl.datasets). Random − temporal: collegemsg +0.127, email-eu-temporal +0.048, bitcoin-otc +0.041, mathoverflow +0.045, higgs-activity -0.011. On Higgs 55% of randomly hidden pairs are cold start (most retweeters act once), so the two protocols ask different questions there.Datasets for this session
From the repo's catalogue (gl.datasets; the full list with sources and licences is in data/README.md). Load one with gl.datasets.graph(name), temporal(name) or node_data(name).
| name | dataset | nodes | ground truth | good for |
|---|---|---|---|---|
bitcoin-otc | Bitcoin OTC trust (signed, timestamped) | 5,881 | edge rating -10..10 | signed/trust networks, fraud, temporal link prediction |
collegemsg | UC Irvine college messages | 1,899 | — | temporal link prediction: random vs time splits |
email-eu-temporal | EU institution e-mail, timestamped | 986 | — | temporal motifs, temporal link prediction |
mathoverflow | MathOverflow interactions | 24,818 | — | temporal link prediction at medium scale |
higgs-activity | Higgs boson Twitter: timestamped RT / mention / reply | 304,691 | edge kind RT / MT / RE | real retweet cascades with timestamps: load as a World (higgs_world) |
cora | Cora citations | 2,708 | topic (7) | the default GNN benchmark |
Frontier 2025–26: what changed since the slides
Frontiers · the leaderboard measured the protocol · claim, benchmark, critique · the checklist
Words & phrases
| Term | Simple meaning | Persian | In context |
|---|---|---|---|
| subtleadj. | not obvious; easy to miss | ظریف، نامحسوس | "The subtle part is splitting" |
| leakagen. | (ML) when information about the test answers accidentally enters training | نشت داده | "which would be leakage" |
| augmentationn. | changing the input graph (adding features, nodes or edges) to make computation easier or better | تقویت (افزونش) داده | "feature augmentation with node degrees" |
| mini-batchn. | a small subset of the training examples used for one gradient step | دسته کوچک | "sample a mini-batch of 32 target nodes" |
| stratifiedadj. | split so that every part keeps the same class proportions | طبقهبندیشده (لایهای) | "stratified 5-fold cross-validation" |
| held-outadj. | kept aside during training and used only for evaluation | کنارگذاشته | "AUC on held-out edges" |
Go deeper
- Next: Lecture 6 — the theory behind "a GNN can't count cycles": expressive power and the Weisfeiler–Lehman test.
- Scaling: Chiang et al. 2019 (Cluster-GCN) and Zeng et al. 2020 (GraphSAINT) — the subgraph-sampling family.
- Open question: self-supervised objectives on graphs (contrastive: DGI, GraphCL; generative: GraphMAE) — which signal actually transfers to downstream social-science tasks?