Graph ML predicts from things and the ties between them. In a 34-member karate club, a noisy survey answer places 70% of members on the right side, on average. Averaged with their friends' answers, it places 78%; with shuffled friendships, only 58%.
Choose what the predictor may read: a member's own answer, their friends' answers too, or friends from a shuffled club. Then raise the noise. Then we build, piece by piece, the language of graphs, the three kinds of question, and the vote of friends that graph neural networks grow from.
You need a little Python and what a probability is. We build the rest from zero.
Lecture 1, "Introduction", of Stanford CS224W, Machine Learning with Graphs (Fall 2026, Jure Leskovec, with Charilaos Kanatsoulis). Next: Lecture 2, Node Embeddings.
Illustrative toy on real ties. The 34 members, 78 friendships and the final split are Zachary's 1977 karate club data (via NetworkX). The survey answers are invented: each member names the wrong side with the chance you set. "Plus friends" averages a member's answer with their friends' answers (Chapter 8). Averages over 2,000 surveys at 30% noise: 70%, 78% and 58%.
Chapter 0
Find what a list of things throws away, and why relations are data
Two bottles hold the same atoms: two carbons, six hydrogens and one oxygen. One is ethanol, the alcohol in wine, which boils at about 78 °C. The other is dimethyl ether, a gas that boils at about −24 °C. They even have the same number of bonds, eight. Only the wiring differs.
A list of atoms cannot tell these two apart. A model that counts atoms gives both bottles the same answer. The difference is in who bonds to whom: ethanol's oxygen holds a hydrogen, and the ether's oxygen sits between two carbons.
Each circle is an atom and each teal line a bond. Switch molecules and watch the same atoms rewire. Then collapse both into a list.
Real molecules, drawn flat. Boiling points are rounded textbook values. The O–H bond lets ethanol molecules hold each other by hydrogen bonds, which is why it boils so much higher.
That is the lecture's opening claim. A graph is a set of things, the nodes, and a set of ties between pairs of them, the edges. Graphs are a general language for things with relations: molecules, friendships, roads, citations, purchases, proteins. If you model the relations, you predict better.
Why not reuse the deep learning we have? Its tools expect a simple shape. Text is a sequence and an image is a grid, so "the next word" and "the pixel to the left" make sense. A graph has any size, no first node, and no up or left. A program can store ethanol's nine atoms in 9! = 362,880 orders, and every order is the same molecule.
Symptom: a property model gives ethanol and dimethyl ether the same score.
Measure: look at its input. If it is the formula C2H6O or a count of atoms, the two inputs are identical.
Fix: give the model the bonds, as a graph, and use a method that ignores the order of the atoms.
Chapter 1
Write a graph down, store it as a matrix, and read each node's degree off a row
Write a graph as G = (V, E): V is the set of nodes, E the set of edges, and each edge is a pair of nodes. The size of V, written |V|, counts the nodes; the lecture's slides write N.
An edge in an undirected graph has no direction: if Ana is Ben's friend, Ben is Ana's friend. In a directed graph an edge is an arrow: a paper cites another, and the second paper does not cite back. An edge can also carry a weight, such as a road's length.
The adjacency matrix A has one row and one column for each node. The cell in row i and column j holds 1 if there is an edge from i to j, and 0 if not. For an undirected graph, A is symmetric: the cell (i, j) equals the cell (j, i).
Tap a matrix cell, or tap two nodes, to add or remove an edge. The yellow numbers are row sums. Then make the graph directed.
Illustrative six-node graph. In directed mode a cell sets one arrow, from the row's node to the column's node.
How many edges touch a node? That count is the node's degree. Call the degree of node v kv. Each 1 in row v is one edge at v, so add the row:
k-v equals the sum over j of A-v-j.
Go to row v of the matrix A. Add up its cells A-v-j, one for each column j. The total is k-v.
From the device at reset: row C is 1, 1, 0, 1, 0, 0, so k-C = 3. The six degrees are 2, 2, 3, 3, 2, 2. They add to 14, and the graph has 7 edges.
Each edge adds 1 to two rows, so the degrees add to twice the edges: the handshake rule. The hero's karate club has 34 members and 78 friendships:
Σv kv = 2 × |E| = 2 × 78 = 156; average degree = 156 / 34 = 4.59
In a directed graph, a row sum counts arrows going out, the out-degree. A column sum counts arrows coming in, the in-degree.
Symptom: the adjacency matrix of a million-node graph does not fit in memory.
Measure: it has 106 × 106 = 1012 cells, 1 TB at one byte each. With 10 million edges, almost every cell is 0.
Fix: store the edge list: two rows of node ids, one column per edge. At 8 bytes per id that is 2 × 107 × 8 = 160 MB. PyTorch Geometric calls it edge_index, shape [2, number of edges].
Chapter 2
Turn one dataset into different graphs, and fold a two-sided graph onto one side
Data does not arrive as a graph. Someone decides what the nodes are and what the edges are. The lecture's point: that choice decides which questions the graph can answer. Sometimes the choice is obvious, as with atoms and bonds. Often it is not.
Take a movie site's log: five users, five movies, and who rated what. One graph is bipartite: two kinds of node, users and movies, with edges only between the kinds. A user never links to a user directly. Authors and papers, actors and films, recipes and ingredients all have this shape.
A second graph keeps only users. Link two users if they rated a common movie, and give the edge a weight: the number of movies they share. This is the folded network, here a co-rating network. Folding authors and papers this way gives a collaboration network. Call the user-by-movie table B: Bui is 1 if user u rated movie i. Call the folded weight between users u and v Wuv.
Circles are users and squares are movies. Fold onto users: each two-step path user, movie, user becomes one weighted edge. Then fold onto movies.
Illustrative toy ratings. The same table B drives Chapter 5's recommender.
W-u-v equals the sum over i of B-u-i times B-v-i.
For each movie i, multiply B-u-i by B-v-i: the result is 1 only if both users rated it. Add over all movies. The total is W-u-v. As matrices, W = B BT.
From the device: Ana rated Alien, Coco and Dune; Eli rated Alien, Brave and Dune. The products are 1, 0, 0, 1, 0, so W-Ana-Eli = 2. On the diagonal, W-Ana-Ana = 3, the movies Ana rated.
Real data often has many kinds of node and edge. A heterogeneous graph adds a type to every node and a relation to every edge; the lecture writes it G = (V, E, R, T). A biomedical knowledge graph holds edges such as (fulvestrant, Treats, breast neoplasms). Lecture 9 and Lecture 10 build on this.
Symptom: after folding, almost every user links to almost every other.
Measure: a movie rated by m users adds an edge between every pair of them, m(m − 1)/2 edges. A hit with 10,000 raters adds about 50 million.
Fix: keep the bipartite graph and let the model see the movies, or down-weight movies that everyone rated.
Chapter 3
Predict a property of a node, of a pair of nodes, or of a whole graph
Once you have a graph, what can you predict? The lecture sorts the tasks by what gets the answer. At the node level, each node gets a label or a number. Examples: which side a member joins, whether a customer leaves next month, where a residue sits in space. At the edge level (also called link level), a pair of nodes gets a score: will these two connect?
At the graph level, a whole graph or a part of one gets one answer. Is this molecule an antibiotic? How long will this route take? Between the levels sit community detection, which finds tight groups of nodes, and graph generation and evolution, which make or forecast whole graphs.
Pick a task level and see what the model must predict. In Link mode, slide K to keep more of the best-scored pairs.
Real ties (Zachary, 1977). Link mode scores each unlinked pair by its count of shared friends, a simple stand-in for a learned link predictor. The two groups in Community mode are the real split.
Link prediction has a cost that the other levels do not. A model must rank every pair of nodes that is not linked yet. Call the node count N and the edge count |E|. Call the number of candidate pairs P.
P equals N times N minus one, over two, minus the size of E.
Count all pairs of nodes: N times N minus one, halved. Take away the |E| pairs that are already linked. What is left, P, is what the model must rank.
The karate club: N = 34 and |E| = 78. All pairs: 34 × 33 / 2 = 561. So P = 561 − 78 = 483 pairs to rank. A graph with N = 3 billion has about 4.5 × 1018 pairs.
So nobody scores every pair of a big graph. At test time, the lecture's recipe ranks pairs and predicts the top K. In practice a model scores a shortlist from a cheap first stage. The device's top pair is members 3 and 34, who share 6 friends but sit on opposite sides.
Symptom: a link predictor scores well on edges hidden at random, then fails on next month's new links.
Measure: check when each test edge appeared. Hidden edges from the past share friends with the training graph; future edges often do not.
Fix: split by time. The lecture's relational examples attach a timestamp to every label for this reason.
Chapter 4
Build a spatial graph over a protein chain, and see why sequence distance misleads
A protein is a chain of amino acids, called residues. The chain folds into a 3D shape, and the shape decides what the protein does. For 50 years, predicting that shape from the sequence alone was an open problem. AlphaFold 2 (Jumper et al., Nature, 2021) predicts the 3D coordinates of every residue.
That is a node-level task. Each residue is a node, and each gets three numbers out instead of a class. It is node regression. AlphaFold also gives each residue a confidence from 0 to 100, called pLDDT.
Which residues should we link? The lecture's key idea is a spatial graph: link two residues if they are close in space. The paper says the same. It treats structure prediction as "a graph inference problem in 3D space in which the edges of the graph are defined by residues in proximity". Call the distance between residues i and j dij, in ångströms (Å, 10−10 m). Call the cutoff c.
A-i-j equals one if d-i-j is less than c, and zero otherwise.
For each pair of residues, measure the distance d-i-j. If it is under the cutoff c, put a 1 in A-i-j and draw an edge. If not, put a 0.
From the device's toy hairpin: residues 1 and 16 are 15 places apart in the chain but d = 7.6 Å apart in space. With c = 8 Å, A = 1: an edge. Residues 1 and 15 are 8.5 Å apart, so A = 0.
The grey line is the chain; teal lines join residues closer than the cutoff, thicker when they are 4 or more places apart in the chain. Drag the cutoff. Then lay the chain out straight.
Illustrative toy: two straight strands, 3.8 Å between chain neighbours, joined by a two-residue turn. Real proteins are 3D and less tidy.
At 8 Å the toy has 36 edges. Fifteen join chain neighbours. Six join residues 4 or more places apart, and these long-range contacts are what hold the fold. At CASP14, the 2020 blind test, DeepMind reported a median score of 92.4 GDT out of 100 across all targets. The organisers count about 90 as competitive with experiment.
Symptom: a model that reads only a few nearby residues in the sequence cannot place the two strands of a hairpin.
Measure: count contacts with |i − j| of 4 or more. In the toy at 8 Å, 6 of 36 edges; a window of 3 residues sees none of them.
Fix: let every residue reach every other. The spatial graph does that, and AlphaFold keeps a learned representation for every pair of residues.
Chapter 5
Score a user's unseen movies by the paths that reach them, then see what PinSage learned instead
A recommender is link prediction on a bipartite graph. The nodes are users and items; an edge is an interaction, such as a rating or a purchase. "You might also like" means: score the user–item pairs with no edge yet, and show the best.
The simplest score counts paths. Other users who share movies with you vote for the movies they rated. A vote counts as much as the overlap: the folded weight Wuv from Chapter 2. Call the score of movie i for user u sui.
s-u-i equals the sum over v not equal to u of W-u-v times B-v-i.
For each other user v, look up the overlap W-u-v. If v rated movie i, add W-u-v to the score s-u-i. Rank the movies u has not rated by s.
From the device, for Ana: Cy (W = 1), Dee (W = 0) and Eli (W = 2) rated Brave, so s = 1 + 0 + 2 = 3. Cy and Dee rated Elf: s = 1 + 0 = 1. Recommend Brave first.
Pick a user. Blue dots are votes: they leave each user who shares movies with yours and land on movies yours has not rated. Then divide by popularity.
Illustrative toy ratings, the same table as Chapter 2. "Divide by popularity" divides each score by the number of users who rated that movie.
Counting paths breaks at scale and ignores what an item looks like. PinSage (Ying et al., KDD 2018) learns a vector, an embedding zi, for each pin with a graph neural network. Training pulls pins on the same boards close. Cake 1 ends up nearer to cake 2 than to a sweater. Pinterest trained it on 7.5 billion examples, on a graph of 3 billion nodes (pins and boards) and 18 billion edges.
Drug side effects are a second edge task. Decagon (Zitnik et al., 2018) links 645 drugs and 19,085 proteins, with 964 kinds of side effect as edge types. Given two drugs, it predicts which side effects they cause together. The lecture's motivation: 46% of people aged 70 to 79 take more than 5 drugs.
Symptom: every user sees the same few hits.
Measure: a movie that many people rated collects votes from almost every user. For Ben, Brave and Coco both score 2, though three users rated Brave and only two rated Coco.
Fix: divide by popularity (Coco then wins, 1.0 against 0.67), or learn embeddings that use what the items are.
Chapter 6
Pool a graph of any size into one vector that ignores the atom order
In 2020, Stokes et al. (Cell) trained a graph neural network on 2,335 molecules to predict which ones stop E. coli from growing. They scored the Drug Repurposing Hub, about 6,000 molecules, and the model flagged halicin, a molecule unlike known antibiotics. In the lab it killed a wide range of bacteria, including M. tuberculosis, and it cleared two drug-resistant infections in mice.
Each molecule is one graph and gets one answer. Molecules differ in size and have no natural atom order. So the model needs a readout, also called pooling. It turns any number of node vectors into one fixed-size vector, the same for every atom order. Call node v's vector hv and the graph's vector hG.
h-G equals one over the size of V, times the sum over v in V of h-v.
Add up the vectors h-v of all nodes. Divide by the number of nodes. The average is h-G, and renumbering the atoms does not change it.
Let h-v be the atom type as counts of C, H and O. Ethanol: h-G = (2, 6, 1) / 9 = (0.22, 0.67, 0.11). Dimethyl ether gives the same vector. Pooling raw atom types gives back only the formula.
So the node vectors must hold structure before you pool. The device does one round of the classic Weisfeiler–Lehman relabelling: each atom's new label is its type plus the sorted types of its neighbours. Ethanol's oxygen becomes O(CH); the ether's becomes O(CC). The pooled counts now differ.
Labels sit beside each atom. The bars count each label over the whole molecule: solid for ethanol, outlined for the ether. Renumber the atoms and watch what changes.
Real molecules. Round 0 labels are input features (yellow); round 1 labels are computed from neighbours (purple). Bars are counts over 9 atoms, so they are h-G times 9.
Symptom: a model with one linear neighbour-sum layer and mean pooling gives ethanol and dimethyl ether the same score.
Measure: compute the pooled vectors. Each atom's vector is its own type plus its neighbours' types; both molecules pool to (1.11, 1.33, 0.33). A sum, then an average, gives a degree-weighted atom count, and those match.
Fix: a nonlinear update before pooling, such as the relabelling above or a small neural network. Lectures 6 and 7 show how far that can go.
Chapter 7
Describe a node's place in the graph with numbers a person chose
Before graph neural networks, people described each node with numbers they chose, then trained an ordinary classifier on them. The lecture names the usual ones: a node's degree, its importance and position, and the structure around it.
Take the clustering coefficient. Call node v's degree kv and the number of edges among its neighbours ev. Its kv neighbours could have at most kv(kv − 1) / 2 edges among them. Call the share that exist Cv.
C-v equals two e-v over k-v times k-v minus one.
List v's neighbours and count the edges among them: e-v. Divide by the most there could be, k-v times k-v minus one, over two. The share is C-v.
From the device: member 1, the instructor, has k = 16 friends with e = 18 ties among them. C = 2 × 18 / (16 × 15) = 36 / 240 = 0.15. Member 17 has k = 2 friends who are friends: C = 2 × 1 / (2 × 1) = 1.
Node size shows the feature you pick. Tap a member to read all four features as yellow bars, each against the club's largest value.
Real ties (Zachary, 1977). Features computed with NetworkX: betweenness is normalised by the number of node pairs, closeness uses shortest-path hops.
Member 1 has the highest betweenness, 0.44: many shortest paths run through the instructor. Member 34 has one more friend, degree 17, but lower betweenness, 0.30. Member 17, out on the edge, has closeness 0.28: on average it is 3.5 hops from everyone, against 1.76 for member 1.
Symptom: a classifier on hand features cannot separate some members, whatever you train.
Measure: look for members with identical features. Members 13 and 15 both have degree 2 and clustering 1.0, yet they join opposite sides.
Fix: let the model read the neighbours themselves, not a summary of them. That is the next chapter.
Chapter 8
Pass messages along the edges, watch accuracy climb, then watch every node blur into the same value
Hand features need a person to guess what matters. A graph neural network learns its features by message passing: each node collects its neighbours' vectors, combines them with its own, and repeats. The hero ran one round, with nothing learned.
Give each member a number. Their own survey answer is +1 for Mr. Hi's side and −1 for the president's side. Call member v's number after round k hv(k); round 0 is the survey answer. Call v's friends N(v) and their count kv.
h-v at round k equals h-v at round k minus one, plus the sum over u in N of v of h-u at round k minus one, all over k-v plus one.
Each friend u sends its number h-u. Member v adds them to its own number, then divides by k-v plus one. Repeat for every member at once; that is one round.
The hero's survey at 30% noise: member 15 answered +1, which is wrong, and both its friends answered −1. So h = (1 − 1 − 1) / 3 = −0.33: the president's side, fixed. Member 11 answered −1, also wrong, and its 3 friends answered −1, +1 and +1: h = (−1 − 1 + 1 + 1) / 4 = 0, a tie, so it keeps its wrong answer.
After k rounds a member has heard from everyone within k hops. A real GNN layer adds learned weights and a nonlinearity: a matrix Wk times the neighbours' average, plus a matrix Bk times the node's own vector, through a function σ. Lecture 3 builds it.
Fill colour is h: warm is Mr. Hi's side, pink the president's, muddy in between. Red rings are wrong. Play the rounds, or drag them. Then shuffle the friendships.
Illustrative toy on real ties, computed live: the same survey and rule as the hero. Averages over 2,000 surveys at 30% noise: 70% at 0 rounds, 78% at 1 and 81% at 2. Then 69% at 10, 57% at 20 and 51% at 40.
On this survey, accuracy goes from 24 of 34 at round 0 to 28 at round 1 and 30 at round 2. By round 40 every member has the same number and the same side: 17 of 34. The spread of h shrinks from 1.00 to 0.005. That is over-smoothing.
Symptom: accuracy drops as you add layers.
Measure: track the spread of node vectors across the graph after each layer. Here it falls from 1.00 at round 0 to 0.13 at round 10 and 0.005 at round 40.
Fix: use few layers, often 2 or 3, and add skip connections that keep each node's own signal. Lecture 4 covers both.
Chapter 9
Keep the numbers, the code, the two pipelines and the road through CS224W
A graph is nodes and edges, stored as an edge list or an adjacency matrix. You choose what the nodes and edges are, and the choice sets the questions. The questions come at three levels: a node, a pair of nodes, or a whole graph. Hand features describe a node's place; message passing lets the graph compute features itself, until too many rounds blur them together.
| Idea | Rule | This lesson's number |
|---|---|---|
| Degree | kv = row sum of A | karate: degrees add to 2 × 78 = 156 |
| Folding | W = B BT | Ana and Eli share 2 movies |
| Link candidates | P = N(N − 1)/2 − |E| | 483 pairs in the club |
| Spatial graph | edge if d < c | toy hairpin at 8 Å: 36 edges, 6 long-range |
| Path score | sui = Σ Wuv Bvi | Brave 3, Elf 1 for Ana |
| Mean pooling | hG = average of hv | raw atoms: same for both isomers |
| Clustering | Cv = 2ev / (kv(kv − 1)) | member 1: 0.15 |
| Message passing | average of self and friends | 70% → 78% → 81%, then 51% at 40 rounds |
| Pipeline | Steps | Strength | Weakness |
|---|---|---|---|
| Hand features | choose features, compute them, train a standard classifier | readable, little data | a person must guess what matters, per domain |
| Graph neural network | raw graph and node features, rounds of message passing, a prediction head | learns features end to end | needs labels; harder to read; over-smoothing |
The whole lesson in code: the club, a noisy survey, and rounds of friend voting. We ran it.
python import networkx as nx, numpy as np G = nx.karate_club_graph() # 34 members, 78 friendships y = np.array([1 if G.nodes[v]["club"] == "Mr. Hi" else -1 for v in G]) A = nx.to_numpy_array(G, weight=None) # 34 x 34 matrix of 0s and 1s k = A.sum(1) # degrees: row sums assert k.sum() == 2 * G.number_of_edges() # handshake rule: 156 def rounds(A, x, K): h = x.astype(float) for _ in range(K): h = (h + A @ h) / (A.sum(1) + 1) # average of self and friends return h rng = np.random.default_rng(0) x = np.where(rng.random(34) < 0.3, -y, y) # survey: wrong 30% of the time for K in [0, 1, 2, 40]: h = rounds(A, x, K) pred = np.where(np.abs(h) < 1e-12, x, np.sign(h)) # a tie keeps the own answer print(K, (pred == y).sum(), "of 34 right, spread", h.std().round(3))
It prints 24, 24, 26 and 17 of 34 right for 0, 1, 2 and 40 rounds. This survey (NumPy's seed 0) differs from the page's, and here one round fixes one wrong answer and breaks one right one. One survey is noisy; the averages in Chapter 8 come from 2,000. For real work, the course uses PyTorch Geometric. Planetoid(root, name="Cora")[0] loads the Cora citation graph. Its x is [2708, 1433] word features and its y holds 7 classes. Its edge_index is [2, 10556], because each undirected edge is stored both ways.
One limit to carry forward. A message-passing GNN can tell two graphs apart only if the Weisfeiler–Lehman test of Chapter 6 can (Xu et al., ICLR 2019). That paper's GIN reaches the limit. Lectures 6 and 7 work through it.
| Lectures | Topic |
|---|---|
| 2 | Node embeddings: learn zv from random walks |
| 3 to 5 | Graph neural networks, a general perspective, augmentation and training |
| 6 to 8 | Theory of GNNs, powerful graph encoders, graph Transformers |
| 9 to 11 | Heterogeneous graphs, knowledge graphs, GNNs for recommender systems |
| 12 to 13 | Relational deep learning and its advanced architectures: databases as graphs |
| 14 to 17 | Advanced topics, foundation models for knowledge graphs, frontiers in graph AI (LLMs and GNNs, GraphRAG and agents) |
| 18 to 19 | Deep generative models for graphs and the conclusion |
Now teach it: press Present or Teach. Explain why ethanol and dimethyl ether need a graph, what the three task levels are, and why friends' votes help at 1 or 2 rounds and blur at 40. Then go back to the club, set the noise to 40%, and predict whether friends still help before you look.