CS224W

Lecture 5 · Tue 10/6 · slides PDF · lecture notes

GNN Augmentation and Training

The input graph is rarely the best computation graph, and a graph dataset can't be split like a pile of images — here is the full training pipeline done right.

25
sectionstick "got it" as you go
21
figuresredrawn from the slides
interactive figuresplay with the ideas
5
self-check questionsplus flashcards
18′
reading time3,983 words, walkthrough aside

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

  • Lecture 4: the GNN layer and the design space whose last two parts are filled in here
  • Lecture 3: the training of a GNN in Lecture 3, now written as a full pipeline
  • Lecture 2: the link-prediction decoder, needed for the edge heads below

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.

\[ \alpha_{vu}=\frac{\exp(e_{vu})}{\sum_{k\in N(v)}\exp(e_{vk})},\qquad \mathbf{h}_v^{(l)}=\sigma\Big(\sum_{u\in N(v)}\alpha_{vu}\,\mathbf{W}^{(l)}\mathbf{h}_u^{(l-1)}\Big) \]

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.

\[ H^{(k+1)}=\sigma\big(D^{-1}A\,H^{(k)}W_k^\top + H^{(k)}B_k^\top\big) \]

Rows of \(H\) are node embeddings; \(D^{-1}A\) averages over neighbours; \(W_k\) transforms the neighbourhood message; \(B_k\) transforms the node itself.

Lecture 2 · Node Embeddings

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.

\[ \mathcal{L}=\sum_{u\in V}\sum_{v\in N_R(u)}\Big[-\log\sigma(\mathbf{z}_u^\top\mathbf{z}_v)-\sum_{i=1}^{k}\log\sigma(-\mathbf{z}_u^\top\mathbf{z}_{n_i})\Big] \]

\(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

GNN training pipeline inputgraphGNNnodeembeddings predictionhead node / edge / graph 1 predictions labels 2 loss metrics 3 trainvalidtest dataset split (transductive vs inductive) 4

How to read it (hover a step)

  1. Prediction head turns embeddings into task outputs — differs for node, edge and graph tasks.
  2. Labels come from external sources (supervised) or from the graph itself (self-supervised: hide an edge, predict a statistic).
  3. Loss (cross-entropy, MSE) trains the model; metrics (accuracy, F1, ROC AUC, RMSE) judge it.
  4. 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:

ProblemFix
No node featuresFeature 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 slowlyAdd virtual nodes / edges
Too dense → message passing too costlySample neighbours
Too large → doesn't fit on a GPUSample subgraphs (scaling GNNs)

Constant vs one-hot features

Constant vs one-hot node features: the trade-off. slide 15 ↗
  • 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".

Why v₁ cannot tell a triangle from a square: identical computation trees. slide 17 ↗
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.
  • Virtual node and neighbour sampling. slide 19 ↗
  • 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)\):

  1. Concatenation + linear: \(\text{Linear}(\text{Concat}(\mathbf{h}_u,\mathbf{h}_v))\), \(2d\to k\). (As in GAT's attention.)
  2. 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.

The issue with global pooling. slide 35 ↗

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.
  • ROC AUC: area under the TPR–FPR curve. slide 52 ↗

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.
  • Transductive vs inductive node classification. slide 61 ↗
  • 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.
  • Transductive link prediction: a growing set of visible edges. slide 69 ↗
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.

Common bug

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

symbolmeaningwhat kind of object
\(\mathbf h_v^{(L)}\)final embedding of node \(v\) after \(L\) layersvector 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 labelclass 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 maxorder-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 negativescounts
\(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

\[ \hat y_v=\mathbf{W}^{(H)}\mathbf{h}_v^{(L)},\qquad \hat y_{uv}=\mathbf{h}_u^{(L)\top}\mathbf{h}_v^{(L)},\qquad \hat y_G=\text{Head}\Big(\text{Pool}\big(\{\mathbf{h}_v^{(L)}:v\in G\}\big)\Big) \]

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.

With numbers. A graph with three nodes and embeddings \((1,2)\), \((3,0)\), \((-1,1)\). Sum pooling: \((3,3)\). Mean: \((1,1)\). Max, coordinate by coordinate: \((3,2)\). The link score of the first two nodes is \(1\cdot3+2\cdot0=3\).

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

\[ \text{CE}(y,\hat{\mathbf y})=-\log\frac{e^{\hat y_{y}}}{\sum_{c=1}^{C}e^{\hat y_c}},\qquad \text{BCE}(y,p)=-\big[y\log p+(1-y)\log(1-p)\big],\qquad \text{MSE}=\frac1N\sum_{i=1}^{N}(y_i-\hat y_i)^2 \]

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.

With numbers. \(y=1\): with \(p=0.9\) the loss is \(-\log0.9=0.105\); with \(p=0.1\) it is \(2.303\), over twenty times larger. Regression targets \((1,2)\) and predictions \((1.5,4)\): \(\text{MSE}=(0.25+4)/2=2.125\).

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

\[ \text{Precision}=\frac{TP}{TP+FP},\qquad \text{Recall}=\frac{TP}{TP+FN},\qquad F_1=\frac{2\,\text{P}\,\text{R}}{\text{P}+\text{R}},\qquad \text{AUC}=\Pr\big(\text{score}(\text{pos})>\text{score}(\text{neg})\big) \]

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.

With numbers. 100 nodes, 12 positive. The model predicts 10 positive, 8 correctly: \(TP=8\), \(FP=2\), \(FN=4\), \(TN=86\). Accuracy \(0.94\), precision \(8/10=0.80\), recall \(8/12=0.67\), \(F_1=2\cdot0.8\cdot0.667/1.467=0.73\).

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

\[ E=E_{\text{train}}\ \cup\ E_{\text{val}}\ \cup\ E_{\text{test}},\qquad E_{\text{train}}=E_{\text{msg}}\cup E_{\text{sup}},\qquad E_{\text{msg}}\cap E_{\text{sup}}=\varnothing \]

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.

With numbers. 1000 edges split 80/10/10. Training: of the 800, say 600 are message edges and 200 are supervision edges (re-drawn every epoch). Validation: messages on 800, predict 100. Test: messages on 900, predict 100. For every positive edge, negatives are node pairs sampled from the non-edges.

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.

  1. Graph manipulation: the input graph is not the computation graph
  2. Feature augmentation: constant vs one-hot features
  3. Structures a GNN cannot see: cycle-count features
  4. Structure augmentation: virtual nodes and neighbour sampling
  5. The training pipeline and node-level prediction heads
  6. Edge-level prediction heads
  7. Graph-level prediction heads and the pooling problem
  8. Where do labels come from? Supervised and self-supervised signals
  9. Loss functions: cross-entropy and MSE
  10. Evaluation metrics: regression, accuracy, precision/recall, ROC AUC
  11. Splitting a graph dataset: transductive vs inductive
  12. Setting up link prediction: message edges and supervision edges

Graph manipulation: the input graph is not the computation graph slides 10-12 ↗

Slides 11–12: reasons to break the assumption that the input graph is the computation graph. slides 11-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 ↗

Slides 13–15: when the graph has no features, invent some. Constants keep the model inductive; one-hot IDs can memorise node-specific information but cannot generalise to new nodes. 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 ↗

Slides 16–18: a message-passing GNN sees only the rooted computation tree; on a triangle, a square and an infinite path that tree is the same binary tree, so v₁ gets the same embedding. Augment with cycle counts. 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 ↗

Structure augmentation: a virtual node makes every pair of nodes two hops apart (slide 19); neighbour sampling draws a random subset of neighbours each pass (slides 20–22, GraphSAGE and PinSage). slides 19-22 ↗

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 ↗

Slides 26–27, the GNN training pipeline. The lecture walks through the boxes after the embeddings: heads, labels, loss, metrics, split. slides 26-27 ↗
Slides 28–29: the same embeddings feed three prediction heads, one per task level. slides 28-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 ↗

Slides 30–32: two edge heads. Concatenate-and-linear handles k classes directly; the dot product scores one relation and needs k trainable matrices for k-way output. 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 ↗

Slides 33–36: graph-level heads pool the node embeddings. Global pooling can collapse different graphs onto the same vector; pool hierarchically instead. slides 33-36 ↗
Slide 36, DiffPool: one GNN computes embeddings, a second computes soft cluster assignments; pool inside each cluster and recurse; the two are trained jointly. slide 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):

  1. Global mean pooling: \(\hat{\mathbf{y}}_G=\mathrm{Mean}(\{\mathbf{h}_v^{(L)}\in\mathbb{R}^d,\ \forall v\in G\})\).
  2. Global max pooling: \(\hat{\mathbf{y}}_G=\mathrm{Max}(\{\mathbf{h}_v^{(L)}\in\mathbb{R}^d,\ \forall v\in G\})\).
  3. 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.

Lecture notes figure, page 29
Figure 5.1 of the notes: DiffPool, hierarchical pooling. The graph is coarsened in stages into clusters, and finally into one vector for graph classification. notes p.29 ↗
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 ↗

Slides 38–41, box (2): where the ground truth comes from. Reduce any task to node, edge or graph labels. 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 ↗

Slides 45–46 with the slide's own numbers: cross entropy for K-way classification, mean squared error for K-way regression. slides 45-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 ↗

Slides 50–52: the confusion matrix behind accuracy, precision, recall and F1, and the ROC curve whose area is threshold-free. slides 50-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 ↗

Slides 58–61: two ways to split a graph. Transductive keeps the whole structure and splits labels; inductive cuts cross-split edges so each split is its own graph. Graph classification is only well defined inductively. slides 58-61 ↗

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 ↗

Slides 64–71: link prediction hides edges twice. First split edges into message and supervision; then, transductively, hold out validation and test supervision edges, letting the GNN see more edges at each later stage. slides 64-71 ↗

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):

  1. At training time: use training message edges to predict training supervision edges.
  2. At validation time: use training message edges and training supervision edges to predict validation edges.
  3. 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.

\[ \hat y_v=\mathbf{W}^{(H)}\mathbf{h}_v^{(L)},\qquad \hat y_{uv}=\mathbf{h}_u^{(L)\top}\mathbf{h}_v^{(L)},\qquad \hat y_G=\text{Pool}\big(\{\mathbf{h}_v^{(L)}:v\in G\}\big) \]

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.

  1. Form all positive–negative pairs: (0.9, 0.7) ✓, (0.9, 0.2) ✓, (0.6, 0.7) ✗, (0.6, 0.2) ✓.
  2. AUC = fraction of pairs where the positive scores higher = 3/4 = 0.75.
  3. 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
Sweep the threshold from \(+\infty\) down. The ROC curve moves up by \(1/P\) at each positive and right by \(1/N\) at each negative.
Hint 2
The area under one upward step, taken at a positive \(i\), is \(\frac1P\times(1-\mathrm{FPR})\) at that moment. What is \(1-\mathrm{FPR}\) when the threshold passes \(s_i^+\)?
Solution
The curve is a staircase. When the threshold passes \(s_i^+\), the curve rises by \(1/P\) while \(\mathrm{FPR}=\#\{j:s_j^->s_i^+\}/N\). The area to the right of this rise, up to \(\mathrm{FPR}=1\), is \(\frac1P\cdot\#\{j:s_j^-\lt s_i^+\}/N\). Summing over positives tiles the region under the curve exactly: \(\mathrm{AUC}=\frac1{PN}\sum_i\#\{j:s_j^-\lt s_i^+\}\). (With ties, a tie counts \(\tfrac12\): the step becomes a diagonal.) \(\square\)

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.

precise statement

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.

where it breaks

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.

second viewpoint

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.

Constant vs one-hot features change what the model isOne-hot node IDs make the GNN as expressive as a lookup table and transductive again (a new node has no slot). Constant features keep it inductive but structure-only. If a dataset has no features, say which choice you made and why.
Split by time on social dataRandom edge splits let the future leak into the past. For retweet or follow prediction: message edges = interactions before \(t_0\), supervision = \([t_0, t_1)\), test = after \(t_1\). This is what OGB and RelBench adopted, and it matches the actual question.
Negatives decide the numberRandom negatives make link prediction easy (most random pairs are obviously unlinked). Report historical negatives (pairs that were linked before) and inductive negatives (pairs involving unseen nodes) separately; EdgeBank, a memorisation baseline, wins on many temporal benchmarks because of this.
Neighbour sampling is not optional on hubsA celebrity account has millions of followers; a full 2-hop neighbourhood does not fit in memory. PyG's 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)

Concise written version of the lectures; the walkthrough above cites it page by page.

assigned Ying et al. — Hierarchical Graph Representation Learning with Differentiable Pooling (DiffPool, NeurIPS 2018)

arXiv:1806.08804 · 11 pages · ~1.5 h
  • 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

Both already on the reading list (L4, L11). Read only the neighbour-sampling parts now.
  • 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)

arXiv:1811.05868 · short workshop paper · 45 min
  • 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

Milestone 11/10 · final report 12/10 · groups of 3 recommended · CA mentor assigned
  1. Real-world application of GNNs with PyG (fraud detection, drug interactions, friend recommendation) → blog post + Colab.
  2. Tutorial on PyG functionality (explainability module, sampling on heterogeneous graphs, GraphGym) → blog post + Colab.
  3. 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?

  1. One-hot node IDs
  2. Constant features or attribute-based features
  3. DeepWalk embeddings
  4. 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)?

  1. Too few layers
  2. Mean aggregation
  3. Both nodes have identical computation trees
  4. 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?

  1. Only the node labels
  2. The nodes and all their edges
  3. The graph into connected components
  4. 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 …

  1. used for message passing and loss
  2. discarded
  3. used only for message passing
  4. used only in the loss, never for message passing

Otherwise the model sees the answer — leakage.

ROC AUC equals …

  1. accuracy at threshold 0.5
  2. the probability a random positive is ranked above a random negative
  3. precision × recall
  4. 1 − FPR

That pairwise-ranking interpretation is why it's threshold-free.

Flashcards (click to flip)

Too sparse / too dense / too large?
Virtual nodes/edges · neighbour sampling · subgraph sampling.
Edge prediction heads
Concat + linear; dot product; k bilinear forms for k-way.
Graph-level heads
Global mean/max/sum pooling; hierarchical pooling (DiffPool); virtual super-node.
Transductive vs inductive
Same graph, split labels vs separate graphs per split.
Message vs supervision edges
Message: fed to the GNN. Supervision: only used as targets in the loss.
Self-supervised signals
Node stats (clustering, PageRank) · hidden links · graph stats.

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.
Philosophy of science · what is a fair test?

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 lectureClassic SNA counterpartWhat carried over, what changed
Transductive vs inductive splitsSampling 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 edgesTie formation studies; the Liben-Nowell & Kleinberg (2003) framing of link prediction on co-authorship networksThe 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 IDsTriad census; cyclic closure; Simmelian tiesCounting 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 everythingTwo-mode "affiliation to the whole"; the global mean fieldA 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.
Bridge idea

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.

For SNA on X/Twitter
  • 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.

Synthetic worlds. The label-aware detector loses 0.25 (reciprocal) and 0.18 (co-amplify) AUC when whole rings are held out, and ends below the label-free model.
Real timestamped networks (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).

namedatasetnodesground truthgood for
bitcoin-otcBitcoin OTC trust (signed, timestamped)5,881edge rating -10..10signed/trust networks, fraud, temporal link prediction
collegemsgUC Irvine college messages1,899—temporal link prediction: random vs time splits
email-eu-temporalEU institution e-mail, timestamped986—temporal motifs, temporal link prediction
mathoverflowMathOverflow interactions24,818—temporal link prediction at medium scale
higgs-activityHiggs boson Twitter: timestamped RT / mention / reply304,691edge kind RT / MT / REreal retweet cascades with timestamps: load as a World (higgs_world)
coraCora citations2,708topic (7)the default GNN benchmark

Frontier 2025–26: what changed since the slides

ICLR 2023 → 2026The evaluation crisis, one front at a time — Platonov et al. found duplicate nodes leaking between train and test in the heterophily benchmarks; EdgeBank (NeurIPS 2022) showed random negatives made dynamic link prediction trivial; GC-Bench found condensed graphs transfer poorly across architectures. The splitting discipline of this lecture is the first line of defence, and the 2025–26 checklist in the Frontiers deck ("honest splits: time-based and community-based, with historical and inductive negatives") is its updated form.sources: arXiv:2302.11640 · arXiv:2207.10128
ICLR 2026TGM: one library for snapshots and streams — A modular temporal-graph library (7.8× faster than DyGLib on average) and T-GRAB (2025), a synthetic benchmark on which 11 temporal methods fail periodic, delayed and long-range patterns, are the infrastructure answer to "how do I split and evaluate a graph that changes".sources: arXiv:2510.07586 · arXiv:2507.10183
NeurIPS 2025Zero-shot temporal transfer (MiNT) and no-memory models (CRAFT) — MiNT pre-trains on many transaction networks and beats per-network models zero-shot on 20 unseen ones; CRAFT does future-link prediction with learnable node identities plus cross-attention, no memory, no aggregation. Both question which parts of the training pipeline of this lecture are load-bearing.sources: arXiv:2406.10426
ICML 2026 spotlightIO-aware GNN layers — Systems work on scaling (IO-aware implementations of GNN layers) continues the neighbour-sampling story of this lecture at the hardware level.
Open question to carrySelf-supervised pre-training is natural when you have billions of edges and few labels. Which pretext signal (link prediction, neighbour matching, masked features) actually transfers to downstream social-science tasks, given that most contrastive objectives reward smoothness and therefore homophily?
Frontiers · the leaderboard measured the protocol · claim, benchmark, critique · the checklist

Words & phrases

TermSimple meaningPersianIn 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?