CS224W

Lecture 1 · Tue 9/22 · slides PDF · lecture notes

Introduction — Machine Learning with Graphs

Why so much of the world's data is a graph, why ordinary deep learning chokes on it, and the three kinds of questions we ask of graphs.

25
sectionstick "got it" as you go
28
figuresredrawn from the slides
interactive figuresplay with the ideas
5
self-check questionsplus flashcards
20′
reading time4,391 words, walkthrough aside

Before you start: the background this course assumes

The thread so far. Session 1 fixes the vocabulary (nodes, edges, tasks, representations) that every later lecture assumes without restating.

What this session takes from earlier ones

  • This is the first session, so nothing from earlier lectures. Useful background: basic linear algebra (matrices, eigenvectors), probability, and the idea of a neural network trained by gradient descent.

The background this course assumes, one card each

Linear algebra: a matrix acts on a vector

A matrix is a table of numbers; multiplying it by a vector mixes the vector's entries row by row. The whole course writes graphs this way: one row and one column per node.

\[(A\mathbf x)_i=\sum_{j=1}^{n}A_{ij}\,x_j\]

\(A\) is an \(n\times n\) matrix, \(\mathbf x\) a vector with \(n\) entries, \(A_{ij}\) the entry in row \(i\), column \(j\). If \(A_{ij}=1\) exactly when \(j\) is a neighbour of \(i\), then \((A\mathbf x)_i\) is the sum of \(x\) over the neighbours of \(i\).

Eigenvectors: directions a matrix only stretches

An eigenvector keeps its direction when the matrix is applied; the eigenvalue is the stretch factor. They appear in PageRank (Lecture 2's random walks), spectral features (Lecture 7) and over-smoothing.

\[A\mathbf v=\lambda\mathbf v,\qquad \mathbf v\neq \mathbf 0\]

\(\mathbf v\) is the eigenvector, the number \(\lambda\) its eigenvalue. A symmetric \(n\times n\) matrix has \(n\) real eigenvalues and eigenvectors that are perpendicular to each other.

Probability: turning scores into probabilities

A model outputs one real score per class. The softmax makes the scores positive and makes them sum to one; the cross-entropy loss is small when the true class gets a high probability.

\[p_c=\frac{e^{s_c}}{\sum_{k=1}^{C}e^{s_k}},\qquad \mathcal L=-\log p_{y}\]

\(s_c\) is the score of class \(c\), \(C\) the number of classes, \(y\) the true class. With two classes the softmax is the sigmoid \(\sigma(s)=1/(1+e^{-s})\).

Calculus: learning is walking downhill

Training changes the parameters a little in the direction that lowers the loss fastest; the gradient is that direction, and the chain rule computes it layer by layer (backpropagation).

\[\theta\leftarrow\theta-\eta\,\nabla_\theta\mathcal L(\theta)\]

\(\theta\) is all the parameters, \(\mathcal L\) the loss, \(\nabla_\theta\mathcal L\) the vector of its partial derivatives, \(\eta>0\) the learning rate (step size).

A neural network layer

One layer multiplies its input by a weight matrix, adds a bias and applies a simple non-linear function to every entry. A graph neural network (Lecture 3) is this, with a step that mixes neighbours added.

\[\mathbf h=\sigma(W\mathbf x+\mathbf b),\qquad \text{ReLU}(z)=\max(0,z)\]

\(\mathbf x\in\mathbb R^{d}\) is the input, \(W\in\mathbb R^{d'\times d}\) the weights, \(\mathbf b\in\mathbb R^{d'}\) the bias, \(\sigma\) the non-linearity applied entry by entry, \(\mathbf h\in\mathbb R^{d'}\) the output.

Warm-up: answer these before you read on

A graph has edges 1–2 and 2–3. Write its adjacency matrix \(A\) and compute \(A\mathbf x\) for \(\mathbf x=(1,2,3)\).

\(A\) has ones at (1,2), (2,1), (2,3), (3,2) and zeros elsewhere. \(A\mathbf x=(2,\ 1+3,\ 2)=(2,4,2)\): each node receives the sum of its neighbours' values.

Scores \((2,0)\) for two classes: what probabilities does the softmax give, and what is the loss if the first class is the true one?

\(p_1=e^2/(e^2+1)\approx0.88\), \(p_2\approx0.12\). The loss is \(-\log 0.88\approx0.13\); had the second class been true it would be \(-\log 0.12\approx2.13\).

For \(\mathcal L(\theta)=(\theta-3)^2\), start at \(\theta=0\) with learning rate \(\eta=0.25\). Where are you after one step of gradient descent?

The derivative is \(2(\theta-3)=-6\) at \(\theta=0\), so \(\theta\leftarrow0-0.25\cdot(-6)=1.5\): halfway to the minimum at 3.

Why does a network need a non-linearity such as ReLU between its layers?

Without it two layers collapse into one: \(W_2(W_1\mathbf x)=(W_2W_1)\mathbf x\) is again a single matrix, so the network could only learn linear functions.

In short

Most interesting data is not a list of independent rows. People follow people, drugs bind proteins, customers buy products, atoms bond to atoms. A graph — nodes plus edges — is the most general way to write that down, and this course is about learning directly from it.

The obstacle: today's deep-learning toolbox was built for grids (images) and sequences (text). Graphs have no fixed size, no "top-left corner", and no natural order of nodes. So we need models that respect that structure instead of fighting it.

Almost every graph ML problem boils down to one of three questions: predict something about a node, about a pair of nodes (a link), or about a whole (sub)graph. Lecture 1 is the map; the rest of the course builds the vehicles.

This page covers the "why graphs" argument, how to choose a graph representation, and the task taxonomy with real applications. Course logistics are summarised at the end.

The picture: three levels of prediction

Node-, link-, subgraph- and graph-level tasks on one graph "toxic?" one label 4 3 ? 2 ? bot or human? 1

How to read it (hover a step)

  1. Node-level: predict a property of one node (is this account a bot? what is this protein's function? will this customer churn?).
  2. Link-level: predict whether an edge exists or will appear between two nodes (recommendations, drug–drug side effects, knowledge-graph completion).
  3. Subgraph / community level: find or label groups of nodes (communities, a route segment cluster, a functional module).
  4. Graph-level: one prediction for a whole graph (is this molecule an antibiotic? what is the travel time along this route?) — plus graph generation: produce a new graph.

1 · Why graphs? Why is it hard?

The slides open with a parade of domains — event graphs, food webs, the London Underground, social and citation networks, the Internet, neurons, knowledge graphs, molecules, 3D meshes, code. The point is not the zoo itself but the claim behind it: graphs are a general language for entities with relations. Many of these are natural graphs (the network is the object: a social network) and others are graphs as representation (we choose to model a molecule or a 3D shape as one).

The three "graphs everywhere" slides, as one gallery: natural networks (social, Internet, neurons) and graphs chosen as a representation (scene graphs, code, meshes) share one language. slides 23-25 ↗

A newer and very practical member of the zoo: relational databases. Each table row is a node; each foreign key is an edge. "Users", "Sales", "Products" become a heterogeneous graph. This idea comes back in Lectures 12–13 (Relational Deep Learning) — and it is arguably where graph ML has the largest economic footprint, because most enterprise data lives in databases.

A relational database is a graph: every row becomes a node, every primary-key/foreign-key reference an edge. Users who bought the same product are two hops apart through the sales rows. slides 26-27 ↗

Why can't we just use a CNN or a Transformer?

Why not flatten the adjacency matrix \(A\) and feed it into an MLP?

Three problems. (1) Size: \(A\) is \(n\times n\), and \(n\) changes from graph to graph, so the input layer has no fixed width. (2) Order: relabel the nodes and you get a different matrix \(PAP^\top\) for the same graph, so the MLP would give different answers for identical inputs. (3) Scale: real graphs have millions of nodes; \(n^2\) inputs is hopeless. Any good graph model must be permutation invariant/equivariant and work for any size. Lecture 3 builds exactly that.

Grid neighbourhood vs graph neighbourhood Image (grid) NWNNEWESWSSE always 8 neighbours, fixed order 1 Graph ??? 3 neighbours here, 1 or 1000 elsewhere; no "left" 2
  1. A convolution filter on an image knows which neighbour is "north". It can assign each position its own weight because the layout is fixed.
  2. A node's neighbours are a set (in fact a multiset of features) of variable size with no canonical order. Any operator we design must treat them symmetrically — sum, mean, max, attention. This single constraint shapes the whole course.

2 · Choosing a graph representation

Before any model: what are the nodes, and what are the edges? The slides stress that this choice decides which questions you can even ask. Sometimes it is unambiguous (a road network). Often it is not: in a Twitter dataset, are edges "follows", "retweets", "replies", or "co-used the same hashtag"? Each choice produces a different graph — and a different science.

Vocabulary you need

  • Objects / entities → nodes \(V\), \(N=|V|\)
  • Interactions / links → edges \(E\), \(|E|\)
  • Undirected (friendship, co-authorship) vs directed (follows, citations, phone calls)
  • Other attributes: weights (call frequency), types (friend / co-worker), properties (timestamp, sign)
  • Heterogeneous graph \(G=(V,E,R,T)\): nodes have types \(T(v)\), edges carry relation types \(r\in R\), e.g. \((\text{fulvestrant}, \textit{treats}, \text{breast neoplasm})\).

Bipartite graphs and "folding"

Bipartite graph and its folded projection. slide 40 ↗

A bipartite graph has two disjoint node sets \(U, V\) and every edge goes across: authors→papers, actors→movies, users→items, recipes→ingredients. You can fold (project) it onto one side: two authors are linked if they co-wrote a paper. This is how co-authorship and co-rating networks are born — and it silently throws information away (a 10-author paper becomes a 10-clique).

If \(B\) is the \(|U|\times|V|\) incidence matrix of a bipartite graph, what matrix gives the folded network on \(U\)?

\(B B^\top\). Entry \((i,j)\) is \(\sum_k B_{ik}B_{jk}\) = number of shared neighbours (e.g. papers co-authored). The diagonal holds each node's degree. Folding onto \(V\) is \(B^\top B\). See the worked example below.

3 · Applications by task level

Node level

Characterise a node by its structure and position (degree, how many shortest paths pass through it, the small patterns around it) and by its features — then predict a label. Two showcase examples:

  • User churn on a relational database. Labels with timestamps are attached to user nodes; the GNN sees the user's purchases and the products' other buyers.
  • User churn: time-stamped labels on the relational graph. slide 47 ↗
  • AlphaFold (protein folding). Predict each amino acid's 3D coordinates from the sequence alone. Key idea: a spatial graph — nodes are amino acids (residues), edges connect residues that are close in space; the model iteratively refines this graph. It won part of the 2024 Nobel Prize in Chemistry.

Link level

Predict missing, unknown or future links. At test time you rank all non-connected pairs and output the top-\(K\).

  • Recommender systems (PinSage at Pinterest). Learn embeddings \(z_i\) so that related pins are close: \(d(z_{\text{cake1}}, z_{\text{cake2}}) < d(z_{\text{cake1}}, z_{\text{sweater}})\). Lecture 11 goes deep.
  • Polypharmacy side effects (Decagon). 46% of people aged 70–79 take more than five drugs. Nodes: drugs and proteins; edges: interactions, typed by side effect. Query: will Simvastatin + Ciprofloxacin together break down muscle tissue? Several top-ranked de novo predictions were later backed by case reports.
  • Decagon: typed drug–drug edges are side effects. slide 57 ↗

Graph level

  • Traffic / ETA (Google Maps). Road segments are nodes; the GNN predicts travel time over a "super-segment" subgraph.
  • Antibiotic discovery (Stokes et al., Cell 2020). Molecules are graphs (atoms, bonds); a graph classifier screened ~108 candidates and found halicin, structurally unlike known antibiotics.
  • Physics simulation & weather (GraphCast). Particles or mesh cells are nodes; the model predicts how the graph evolves — an encode–process–decode loop of message passing.
Context · why industry cares

Notice who appears on these slides: Pinterest, Google Maps, DeepMind, pharma. Graph ML moved from a niche to infrastructure because relational data is where commercial value concentrates (who buys what, who talks to whom). The same tools that recommend recipes can map influence or dissent — the representation is politically neutral, its uses are not. Keep that double edge in mind when you work on social networks.

The mathematics, step by step

This session has little algebra, but the four objects below are the alphabet of every later lecture. Each card gives the formula, how to say it in a sentence, why it is true, and a check on one small graph: four nodes with edges 1–2, 1–3, 2–3 and 3–4 (a triangle with a tail).

Symbols used in this session

symbolmeaningwhat kind of object
\(G=(V,E)\)a graph: a set of nodes and a set of edgesa pair of sets
\(n=|V|,\ m=|E|\)number of nodes, number of edgeswhole numbers
\(A\)adjacency matrix: \(A_{ij}=1\) if there is an edge between \(i\) and \(j\), else 0\(n\times n\) matrix; symmetric when the graph is undirected
\(N(v)\)the neighbours of node \(v\)a set of nodes
\(d_v\)degree of \(v\): how many neighbours it has, \(d_v=|N(v)|\)whole number
\(X\)node features: row \(v\) is the feature vector \(\mathbf x_v\) of node \(v\)\(n\times d\) matrix
\(P\)permutation matrix: one 1 in every row and column; multiplying by it renumbers the nodes\(n\times n\) matrix with \(P^\top P=I\)
\(B\)biadjacency matrix of a bipartite graph: \(B_{ui}=1\) if left node \(u\) is linked to right node \(i\)\(|U|\times|I|\) matrix

1The adjacency matrix and the degree

\[ d_i=\sum_{j=1}^{n}A_{ij},\qquad \sum_{i=1}^{n}d_i=2m \]

In words. The degree of a node is the sum of its row in \(A\). Add up all the degrees and you get twice the number of edges.

Why it has this form. Row \(i\) of \(A\) has a 1 for each neighbour of \(i\), so summing the row counts the neighbours. Every edge \(\{i,j\}\) puts two ones into the matrix, \(A_{ij}\) and \(A_{ji}\), so it is counted once in \(d_i\) and once in \(d_j\): the total is \(2m\) (the handshake lemma). The average degree is therefore \(2m/n\).

With numbers. For the triangle with a tail, \[A=\begin{pmatrix}0&1&1&0\\1&0&1&0\\1&1&0&1\\0&0&1&0\end{pmatrix},\qquad (d_1,d_2,d_3,d_4)=(2,2,3,1).\] The degrees sum to \(8=2\cdot4\) edges; the average degree is \(8/4=2\).

Watch out. In a directed graph \(A\) is not symmetric: row sums are out-degrees, column sums are in-degrees, and each edge is counted once in each, so both sum to \(m\), not \(2m\).

2Powers of the adjacency matrix count walks

\[ (A^k)_{ij}=\#\{\text{walks of length } k \text{ from } i \text{ to } j\},\qquad \#\text{triangles}=\tfrac16\,\mathrm{tr}(A^3) \]

In words. Multiply \(A\) by itself \(k\) times; entry \((i,j)\) of the result is the number of ways to go from \(i\) to \(j\) in exactly \(k\) steps along edges (a walk may revisit nodes).

Why it has this form. For \(k=2\): \((A^2)_{ij}=\sum_{l}A_{il}A_{lj}\). The term for \(l\) is 1 exactly when both \(i\!-\!l\) and \(l\!-\!j\) are edges, so the sum counts the middle nodes \(l\), that is, the two-step walks. The same argument, one step at a time, gives any \(k\) (induction). A triangle through \(i\) is a closed walk of length 3; each triangle is counted 6 times in \(\mathrm{tr}(A^3)=\sum_i(A^3)_{ii}\) (3 starting nodes × 2 directions).

With numbers. \((A^2)_{14}=1\): the only two-step walk from 1 to 4 is 1→3→4. \((A^2)_{11}=2=d_1\): out and back along each of node 1's two edges. \((A^3)_{11}=2\) (1→2→3→1 and 1→3→2→1), likewise for nodes 2 and 3, and \((A^3)_{44}=0\); so \(\mathrm{tr}(A^3)=6\) and there is \(6/6=1\) triangle.

Watch out. A walk is not a path: 1→3→1 is a walk of length 2. Counts of walks grow quickly with \(k\) and are dominated by high-degree nodes.

3Invariance and equivariance to renumbering

\[ \text{invariant: } f(PAP^\top,PX)=f(A,X)\qquad\quad \text{equivariant: } f(PAP^\top,PX)=P\,f(A,X) \]

In words. Renumbering the nodes must not change a prediction about the whole graph (invariant), and it must only reorder, in the same way, a prediction made for every node (equivariant).

Why it has this form. Node numbers are an accident of storage: the same graph can be written with \(n!\) different matrices. If node \(i\) is renamed \(\pi(i)\), the features become \(PX\) (rows reordered) and the adjacency matrix becomes \(PAP^\top\) (rows and columns reordered). A model that gave different answers for \(A\) and \(PAP^\top\) would be learning the numbering, not the graph.

With numbers. Take \(f(A)=A\mathbf 1\), the degree vector \((2,2,3,1)\). Swap the names of nodes 1 and 4: the new degree vector is \((1,2,3,2)\), the same numbers in the swapped order, so the degree is equivariant. The number of edges \(\tfrac12\mathbf 1^\top A\mathbf 1=4\) does not change at all, so it is invariant. The entry \(A_{12}\) is neither: it is 1 before the swap and 0 after (nodes 4 and 2 are not linked).

Watch out. An ordinary neural network applied to the flattened matrix \(A\) is neither invariant nor equivariant; this is the reason graph models are built from sums over neighbours (Lecture 3).

4Projecting a bipartite graph

\[ (BB^\top)_{uv}=\sum_{i}B_{ui}B_{vi}=\#\{\text{right nodes linked to both } u \text{ and } v\} \]

In words. Multiply the biadjacency matrix by its transpose: entry \((u,v)\) counts what two left nodes have in common, and the diagonal entry \((u,u)\) is the degree of \(u\).

Why it has this form. \(B_{ui}B_{vi}\) is 1 only when item \(i\) is linked to both \(u\) and \(v\); summing over items counts the shared ones. Putting an edge between \(u\) and \(v\) whenever this count is positive gives the projection onto the left side; \(B^\top B\) does the same for the right side.

With numbers. Three people and four papers, \[B=\begin{pmatrix}1&1&0&0\\1&1&1&0\\0&0&1&1\end{pmatrix}\ (\text{rows: Ali, Sara, Reza}),\qquad BB^\top=\begin{pmatrix}2&2&0\\2&3&1\\0&1&2\end{pmatrix}.\] Ali and Sara share 2 papers, Sara and Reza share 1, Ali and Reza none; the diagonal says they wrote 2, 3 and 2 papers.

Watch out. The projection loses information: three people who all wrote one paper together and three people who wrote three papers in pairs give the same projected triangle.

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 the Users–Sales–Products graph, what is the shortest path between two users who bought the same product? show answer

User – sale – product – sale – user: length 4.

from Why graphs: a general language for relations

Check yourself: why can't we simply flatten the adjacency matrix into a vector and feed it to an MLP? show answer

The size changes from graph to graph, and reordering the nodes permutes the rows and columns, so the same graph gives many different input vectors.

from Why deep learning on graphs is hard

Check yourself: why does adding proteins help predict a drug–drug edge? show answer

Two drugs that target proteins which interact with each other may interfere, even if that drug pair was never observed together.

from Link-level example: drug side effects

Check yourself: for fraud detection, would you predict on a node (one account), a link (a transaction), or a subgraph (a ring of accounts)? show answer

Each choice is valid and leads to a different model.

from Summary: ML in the language of graphs

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. What the course covers
  2. Why graphs: a general language for relations
  3. Why deep learning on graphs is hard
  4. Graph components: one language, many domains
  5. Heterogeneous graphs
  6. Choosing a representation: directed, undirected, bipartite
  7. The task taxonomy
  8. Node-level tasks and node structure
  9. Node-level example: protein folding with AlphaFold
  10. Link prediction and recommender systems
  11. Link-level example: drug side effects
  12. Graph-level example: traffic and travel time
  13. Graph-level examples: drugs, physics, weather
  14. Summary: ML in the language of graphs

What the course covers slides 3,5,6 ↗

Slide 3 is the map of the whole quarter. The course is about machine learning and representation learning for graph data, and it moves through these families of methods:

  • Node embeddings: DeepWalk, node2vec (lecture 2).
  • Graph neural networks (GNNs): GCN, GraphSAGE, GAT and their design space.
  • Graph Transformers.
  • Knowledge graphs and reasoning: TransE and related embedding models.
  • Generative models for graphs: GraphRNN.
  • Relational Deep Learning (RDL): learning directly on relational databases.
  • GNNs + LLMs, and applications in biomedicine, science and technology.

Slide 5 sets expectations: the course is self-contained and no single topic is hard by itself, but the breadth is what makes it hard. Useful background: machine learning, algorithms and graph theory, probability and statistics, linear algebra, and Python programming (PyTorch is a plus).

Slide 6 names the tools. The main library is PyG (PyTorch Geometric), a library for GNNs. GraphGym is a platform for designing GNNs: modular GNN implementations, simple hyperparameter tuning and flexible customization. For classical network analytics the slide also lists SNAP.PY and NetworkX.

For your SNA work: NetworkX/SNAP compute classical statistics (degree, centrality, clustering) that later reappear as hand-made features; PyG is where the learned versions live.

Why graphs: a general language for relations slides 22-27 ↗

The three "graphs everywhere" slides, as one gallery: natural networks (social, Internet, neurons) and graphs chosen as a representation (scene graphs, code, meshes) share one language. slides 23-25 ↗
A relational database is a graph: every row becomes a node, every primary-key/foreign-key reference an edge. Users who bought the same product are two hops apart through the sales rows. slides 26-27 ↗

Slide 22 states the thesis of the course: graphs are a general language for describing and analyzing entities with relations or interactions. Whenever the interesting information is in how things connect, a graph is the natural data structure.

Slides 23–25 are a gallery of domains that are naturally graphs:

  • Slide 23: event graphs, computer networks, disease pathways, food webs (who eats whom), particle networks, and underground (metro) networks such as the London Underground map.
  • Slide 24: social networks, economic networks, communication networks, citation networks, the Internet, and networks of neurons.
  • Slide 25: knowledge graphs, gene regulatory networks, scene graphs (objects in an image and their relations), code graphs, molecules (atoms and bonds) and 3D shapes (meshes).

The gallery mixes two kinds of graphs. Some are natural networks, where the graph is the system (social networks, the Internet, neurons). Others are graphs as a representation, where we choose to describe data as a graph (scene graphs, code, 3D meshes).

Slide 26 adds an important new member: relational databases are graphs. It shows database schemas from commerce, finance and clinical trials, each made of many tables linked by primary/foreign keys. Slide 27 shows the idea of Relational Deep Learning: three tables (Users, Sales, Products) become a graph. Each row is a node; each foreign-key reference (a sale points to a user and a product) is an edge. So a person on the left, the sales in the middle and the products (a shirt, shoes, sunglasses) on the right form one connected graph. The RelBench benchmark (relbench.stanford.edu) is built on this idea. This matters because most of the world's business data sits in such databases.

Check yourself: in the Users–Sales–Products graph, what is the shortest path between two users who bought the same product? show answer

User – sale – product – sale – user: length 4.

Why deep learning on graphs is hard slides 28-33 ↗

The deep learning toolbox is built for grids and sequences. A graph has no fixed neighbourhood size, no reference point and no canonical ordering, so convolutions and positional indices do not transfer. slides 29-31 ↗
Slide 33: among the 50 most frequent keywords of ICLR 2023 submissions, "graph neural network" ranks fourth, just ahead of "transformer". slide 33 ↗

Slide 28 gives the main motivation: complex domains have a rich relational structure, which can be represented as a relational graph. By explicitly modeling relationships we get better performance. The main question of the course is: how do we take advantage of relational structure for better prediction?

Slides 29–30 describe the modern deep learning toolbox. It is built for simple data types: images are fixed-size 2D grids (processed by convolutional networks), and text and speech are 1D sequences (processed by sequence models). Slide 30 shows audio signals, text and an image (the Mona Lisa) as examples of sequences and grids.

Slide 31 explains why graphs do not fit this toolbox. Networks are complex:

  • Arbitrary size and complex topology. There is no spatial locality like in grids. A pixel always has the same 8 neighbours; a node can have 1 neighbour or a million.
  • No fixed node ordering or reference point. There is no "top-left corner" and no "first word". Any ordering of the nodes is arbitrary, so a model must give the same answer for every ordering (this idea becomes permutation invariance/equivariance in later lectures).
  • Often dynamic and with multimodal features. Graphs change over time, and nodes can carry text, images or numbers.

Slide 32 asks how we can build neural networks that are much more broadly applicable, and answers: graphs are the new frontier of deep learning. Slide 33 supports this with a bar chart of the 50 most frequent keywords at ICLR 2023: "graph neural network" is highlighted in fourth place, after reinforcement learning, deep learning and representation learning, and just ahead of "transformer".

Check yourself: why can't we simply flatten the adjacency matrix into a vector and feed it to an MLP? show answer

The size changes from graph to graph, and reordering the nodes permutes the rows and columns, so the same graph gives many different input vectors.

Graph components: one language, many domains slides 35 ↗

Four domains, one graph: a triangle plus a pendant node. Once the data is written as nodes and edges, the same algorithm serves actors, friends and proteins. slide 35 ↗

Slide 35 shows four graphs that look different but have exactly the same structure: actors linked by the movies they played in together, people linked by relations (friend, brothers, co-worker), proteins linked by interactions, and an abstract graph on nodes 1–4. All four have \(|N| = 4\) nodes and \(|E| = 4\) edges: a triangle (1, 2, 3) plus a pendant node 4 attached to node 2.

The vocabulary:

  • Objects: nodes, vertices, written \(N\) (or \(V\)).
  • Interactions: links, edges, written \(E\).
  • System: network, graph, written \(G(N, E)\).

The point of the slide is abstraction. Once a domain is written as a graph, the same mathematics and the same algorithms apply to movies, friendships and proteins. A method that predicts a missing friendship can, in principle, predict a missing protein interaction.

Heterogeneous graphs slides 36-37 ↗

Heterogeneous graphs G = (V, E, R, T): every edge is a typed triple (head, relation, tail) and every node has a type. Squares are the example nodes named on the slide. slide 37 ↗

Slide 36 defines a heterogeneous graph as

\[ G = (V, E, R, T) \]
  • nodes with node types: \(v_i \in V\);
  • edges with relation types: \((v_i, r, v_j) \in E\);
  • a node type \(T(v_i)\) for each node;
  • a set of relation types, \(r \in R\).

Nodes and edges can also carry attributes (features). So an edge is a triple: head node, relation, tail node. This triple form returns in the knowledge-graph lectures.

Slide 37 gives two examples that are naturally heterogeneous:

  • Biomedical knowledge graphs. Example node: Migraine. Example edge: (fulvestrant, Treats, Breast Neoplasms). Example node type: Protein. Example relation type: Causes.
  • Academic graphs. Example node: ICML. Example edge: (GraphSAGE, NeurIPS), i.e., a paper published at a venue. Example node type: Author. Example relation type: pubYear.

The Users–Sales–Products graph from slide 27 is heterogeneous too: three node types and two relation types.

Choosing a representation: directed, undirected, bipartite slides 38-40 ↗

Undirected versus directed links. Links can also carry weights, properties, types and attributes. slide 39 ↗
A bipartite graph (every edge crosses between U and V) and its folded projection: two authors are linked when they share a paper. Folding loses information: one 3-author paper and three 2-author papers fold to the same triangle. slide 40 ↗

Slide 38 asks the modeling question that comes before any learning: how do we build the graph? What are the nodes, and what are the edges? The choice of representation determines whether we can use networks successfully:

  • In some cases there is a unique, unambiguous representation (for example, atoms and bonds).
  • In other cases the representation is not unique at all.
  • The way you assign links determines the kind of question you can study. Linking people who emailed each other gives a different network, and answers different questions, than linking people who work at the same company.

Slide 39 contrasts the two basic edge types. In an undirected graph, links are symmetrical and reciprocal (collaboration, friendship on Facebook). In a directed graph, every link has a direction (phone calls, following on Twitter/X). The figure shows an undirected graph and a directed graph with arrows. Other things a link can carry: weights, properties, types and attributes.

Slide 40 defines a bipartite graph: its nodes split into two disjoint sets \(U\) and \(V\) so that every link connects a node in \(U\) to a node in \(V\). Hence \(U\) and \(V\) are independent sets (no edges inside them). The figure shows nodes A–E on the left (\(U\)) and green nodes on the right (\(V\)). Examples: authors-to-papers (authored), actors-to-movies (appeared in), users-to-movies (rated), recipes-to-ingredients (contain).

A bipartite graph can be folded (projected) onto one side: connect two nodes of \(U\) if they share at least one neighbour in \(V\). Folding author–paper gives an author collaboration network; folding user–movie ratings gives a movie co-rating network.

Folding loses information: three authors on one paper and three pairwise two-author papers give the same triangle after folding. Keep this in mind when you build co-retweet or co-hashtag networks from X/Twitter data.

The task taxonomy slides 42-43 ↗

One graph, four levels of prediction. Click through: a node property, an edge that may exist, a dense group of nodes, and a property of the whole graph. slides 42-43 ↗

Slide 42 shows one graph with the four levels at which we can ask questions:

  • Node level: a property of one node.
  • Edge level: a property of a pair of nodes, usually whether a link exists or will form.
  • Community (subgraph) level: a property of a group of nodes, such as a dense cluster.
  • Graph level: one prediction for a whole graph, and also graph generation (produce a new graph).

Slide 43 reviews the three classic tasks on a small graph with nodes A–H: node-level prediction (the "?" next to node B), link-level prediction (the dashed "?" between A and B), and graph-level prediction (a "?" for the whole graph, circled). The rest of the lecture gives real applications of each level.

Lecture notes figure, page 7
Notes Figure 0.1: the input graph (left) and the computation graph of target node A (right). Information from neighbours of neighbours flows into A. notes p.7 ↗

Node-level tasks and node structure slides 45-47 ↗

Node classification is semi-supervised: labelled and unlabelled nodes live in the same graph, and the model fills in the grey ones. slide 45 ↗
The three ingredients of node structure that the slide lists: degree, position (here betweenness: E sits on every path between the two halves) and local substructures. slide 46 ↗
User churn as a node-level task on the Users–Sales–Products graph: labels are time-stamped, so each training example may only see transactions from before its own date. slide 47 ↗

Slide 45 shows node classification: some nodes are labelled (green or red), others are unknown (grey with "?"). A machine learning model fills in the missing labels. This is semi-supervised: the labelled and unlabelled nodes live in the same graph.

Slide 46 says what a node-level model must capture: the structure and position of a node in the network. Examples:

  • node degree;
  • node importance and position, e.g., the number of shortest paths passing through a node, or its average shortest-path length to other nodes;
  • substructures around the node.

Slide 47 is a business example: user churn. Training labels with timestamps are attached to the Users–Sales–Products graph. Each user has a history like "May '23: Churn, June '23: Active", and sales carry amounts ($15, $20, $80). The task is to predict whether a user will churn (stop buying) next month. Because labels have times, training must use only information from before each label's time.

Lecture notes figure, page 9
Notes Figure 1.3: clustering coefficient of the blue node \(v\) with 4 neighbours: 6 of 6 neighbour pairs linked (\(e_v = 1\)), 3 of 6 (\(e_v = 0.5\)), none (\(e_v = 0\)). notes p.9 ↗

Node-level example: protein folding with AlphaFold slides 48-51 ↗

AlphaFold as a node-level graph problem: amino acids are nodes, the chain gives one set of edges, and the learned pair representation is a dense "who is near whom" graph. The output is a 3D coordinate per node. slide 51 ↗

Slide 48 states the protein folding problem: computationally predict a protein's 3D structure from its amino-acid sequence alone. As a node-level task: for each node (amino acid), predict its 3D coordinates. The figure overlays experimental structures (green) with computational predictions (blue) for two targets (T1037 and T1049); they almost coincide.

Slide 49 shows the impact: a bar chart in which DeepMind's AlphaFold scores far above earlier methods in the protein-structure competition, plus news headlines saying it "could change the world of biological science" and asking whether AI has "solved" biology's protein-folding problem. Slide 50 shows the 2024 Nobel Prize in Chemistry, awarded to David Baker, Demis Hassabis and John Jumper for protein design and protein-structure prediction.

Slide 51 gives the key idea that makes it a graph problem: a spatial graph.

  • Nodes: amino acids (residues) in the protein sequence.
  • Edges: proximity between residues.

The architecture diagram passes information between a sequence-like representation (from a multiple sequence alignment, MSA) and a residue–residue pair representation, refines both over many blocks, and outputs the 3D structure. The pair representation is essentially a learned, dense "who is near whom" graph.

Why a graph? Two residues far apart in the sequence can be close in space, and it is these spatial contacts that determine the shape. A sequence model sees only the chain; a graph can represent the folded contacts directly.

Link prediction and recommender systems slides 53-55 ↗

Link prediction: which of the missing edges (dashed) will appear? At test time all unlinked pairs are scored and the top K become predictions. slide 53 ↗
A recommender system is link prediction on a bipartite user–item graph: the recommendations are the edges the model expects next. slide 54 ↗
PinSage: pins and boards form a bipartite graph; a pin's embedding z is computed from its neighbourhood tree so that related pins (cake, cake) end up closer than unrelated ones (cake, sweater). slide 55 ↗

Slide 53 defines link prediction: predict new, missing or unknown links based on the existing links. At test time, node pairs with no existing link are ranked, and the top \(K\) pairs are predicted as links. So the task is a prediction for a pair of nodes; the figure shows two dashed "?" edges, between A and B and between C and E.

Slide 54 applies it to recommender systems. Users interact with items: they watch movies, buy merchandise, listen to music.

  • Nodes: users and items (a bipartite graph).
  • Edges: user–item interactions.
  • Goal: recommend items a user might like; the red dashed arrows ("You might also like") are predicted new edges.

Slide 55 is the industrial case PinSage (Ying et al., KDD 2018) at Pinterest. Task: recommend related pins. Given a query pin (a cake), another cake is a successful recommendation and a sweater is a bad one. The learning task is to learn node embeddings \(z_i\) so that

\[ d(z_{\text{cake1}}, z_{\text{cake2}}) \lt d(z_{\text{cake1}}, z_{\text{sweater}}). \]

Related nodes should be close in the embedding space. The bottom of the slide shows the pin–board bipartite graph (pins on top, boards below) and the computation tree that aggregates a pin's neighbourhood into its embedding \(z\). This is exactly the "learn embeddings, then compare distances" idea of lecture 2.

Link-level example: drug side effects slides 56-58 ↗

Decagon's graph (Zitnik et al. 2018): drugs, proteins, and drug–drug edges whose type is the side effect. Predicting a typed edge (c, r, d) is multi-relational link prediction; the protein paths explain pairs never seen together. slide 57 ↗
rankdrug cdrug dside effect revidence
1PyrimethamineAliskirensarcomaStage et al. 2015
2TigecyclineBimatoprostautonomic neuropathy–
3OmeprazoleDacarbazinetelangiectases–
4TolcaponePyrimethaminebreast disorderBicker et al. 2017
5MinoxidilParicalcitolcluster headache–
6OmeprazoleAmoxicillinrenal tubular acidosisRusso et al. 2016
7AnagrelideAzelaic acidcerebral thrombosis–
8AtorvastatinAmlodipinemuscle inflammationBanakh et al. 2017
9AliskirenTioconazolebreast inflammationParving et al. 2012
10EstradiolNadololendometriosis–

Slide 58: the ten top-ranked de novo predictions; five were later supported by the literature.

Slide 56 motivates polypharmacy: many patients take multiple drugs to treat complex or co-existing diseases. 46% of people aged 70–79 take more than 5 drugs, and many patients take more than 20 drugs to treat heart disease, depression, insomnia, etc. Drug combinations can cause side effects that neither drug causes alone. Task: given a pair of drugs, predict their adverse side effects; the cartoon shows a probability for each possible side effect (30%, 65%).

Slide 57 shows the graph (Zitnik et al., Bioinformatics 2018):

  • Nodes: drugs (triangles) and proteins (circles).
  • Edges: interactions: protein–protein, drug–protein (a drug targets a protein), and drug–drug edges whose type is the side effect (e.g., \(r_1\) gastrointestinal bleeding, \(r_2\) bradycardia).

So this is a heterogeneous, multi-relational link prediction problem: predict a typed edge \((c, r, d)\). Example query: how likely is it that Simvastatin and Ciprofloxacin, taken together, break down muscle tissue?

Slide 58 shows the model's top-10 de novo predictions (pairs not in the training data), with drug \(c\), drug \(d\) and side effect \(r\). Five of the ten (ranks 1, 4, 6, 8, 9) were later supported by evidence in the medical literature, e.g., rank 1 Pyrimethamine + Aliskiren → sarcoma (Stage et al. 2015) and rank 8 Atorvastatin + Amlodipine → muscle inflammation (Banakh et al. 2017). A case report at the bottom describes severe rhabdomyolysis (muscle breakdown) due to a presumed interaction between atorvastatin and amlodipine.

Check yourself: why does adding proteins help predict a drug–drug edge? show answer

Two drugs that target proteins which interact with each other may interfere, even if that drug pair was never observed together.

Graph-level example: traffic and travel time slides 60-63 ↗

A road network as a graph. The route is a subgraph, so ETA is a subgraph-level prediction; "supersegments" group adjacent segments that share traffic. slide 62 ↗
DeepMind's ETA pipeline in Google Maps: supersegments become the training data of a GNN whose ETA predictions rank the candidate routes. slide 63 ↗

Slide 60 defines the graph-level task: make a prediction for an entire graph or for a subgraph of it.

Slide 61 shows the use case: a Google Maps route between two places in the San Francisco Bay Area, with an estimated travel time. Slide 62 shows how the road network becomes a graph:

  • Nodes: road segments.
  • Edges: connectivity between road segments.
  • Prediction: estimated time of arrival (ETA) for a route from A to B.

The route is a subgraph, so the ETA is a subgraph-level prediction. Each node carries features (small bar charts in the figure, e.g., current traffic on that segment).

Slide 63 shows DeepMind's pipeline used in Google Maps: anonymised travel data is analysed into supersegments (groups of adjacent road segments with shared traffic); these form training data for a graph neural network; its predictions rank candidate routes (from the Google Maps routing system, A→B) by ETA, and the result is surfaced in the Google Maps app and API.

Why a graph? Traffic spreads: a jam on one segment slows its neighbours a few minutes later. A model that passes information along road connections can capture this.

Graph-level examples: drugs, physics, weather slides 64-68 ↗

Antibiotic discovery as graph classification (Stokes et al. 2020): molecules are graphs, a message-passing model trained on about ten thousand of them screens a pool of up to a hundred million. slides 64-65 ↗
The learned simulator (Sanchez-Gonzalez et al. 2020): encode particles into a graph, pass messages M times, decode each particle's dynamics, and roll the next state back in. slide 67 ↗
GraphCast: the same encode–process–decode pattern for weather. Coarse mesh edges carry information across the globe in one step. slide 68 ↗

Drug discovery (slides 64–65). Antibiotics are small molecular graphs: nodes are atoms and edges are chemical bonds (slide 64 shows β-lactam structures such as penicillin, and bacteria on agar plates). Stokes et al. (Cell 2020) trained a GNN graph classification model to predict which molecules inhibit bacterial growth, then used it to rank a pool of candidates. Slide 65's figure shows the pipeline: a directed message-passing neural network builds bond vectors by summing and concatenating neighbouring bond vectors; it is trained on about \(10^4\) molecules; predictions are validated in the lab with iterative re-training; and the model can screen a chemical landscape of up to \(10^8\) molecules or more. For comparison, conventional lab screening handles about \(10^5\)–\(10^6\) molecules with a 1–3% hit rate.

Physics simulation (slides 66–67). Sanchez-Gonzalez et al. (ICML 2020) treat a physical system as a graph: nodes are particles and edges are interactions between nearby particles. Slide 66 shows learned simulations of water, sand and goop. Slide 67 frames it as a graph evolution task: predict how a graph will evolve over time. A learned simulator \(s_\theta\) maps state \(X^{t_0}\) to the next state again and again. Inside, an encoder builds a graph \(G^0\) (connect nearby particles), a processor applies \(M\) rounds of message passing \(G^0 \to G^1 \to \dots \to G^M\), and a decoder reads out each particle's dynamics (e.g., acceleration) \(y_i\).

Weather forecasting (slide 68). DeepMind's GraphCast uses the same encode–process–decode pattern. The input is the current weather state on a latitude–longitude grid. The encoder maps it onto a multi-resolution icosahedral mesh over the globe (meshes \(M^0\) to \(M^6\), from coarse to fine); the processor does message passing on all mesh levels simultaneously, so coarse edges carry information over long distances; the decoder maps back to the grid to get the next state \(\hat X^{t+1}\). Applying it repeatedly rolls out a forecast \(\hat X^{t+T}\).

Physics and weather are really "predict the next graph state", so they also involve node-level outputs at every step. The slides group them as graph-level because the whole system is one object.

Summary: ML in the language of graphs slides 69 ↗

Slide 69: business questions on the Users–Sales–Products graph are node-, link- or subgraph-level predictions. slide 69 ↗

Slide 69 closes the loop with the Users–Sales–Products database from slide 27. Typical business problems map directly onto graph tasks:

  • Node-level: churn, lifetime value, next best action.
  • Link-level: product affinity, recommendations.
  • Graph-level: fraud, money laundering.

The main lessons of lecture 1: graphs are a general language for relational data; standard deep learning does not fit them because of arbitrary size, no node ordering and dynamic, multimodal features; the representation (what are nodes, what are edges, directed or not, typed or not, bipartite or folded) is a modeling choice that decides which questions you can answer; and almost every application is a node-, link- or (sub)graph-level prediction.

Check yourself: for fraud detection, would you predict on a node (one account), a link (a transaction), or a subgraph (a ring of accounts)? show answer

Each choice is valid and leads to a different model.

Not shown (no new content): slides 1,2,4,7-21,34,41,44,52,59 — title slides, course schedule and logistics (staff, grading, deadlines, honor code, Colabs), section dividers.

Review: what to keep from this session

Carried forward. Lecture 2 replaces hand-made node features by learned embeddings; Lecture 3 makes the embedding a neural network over the neighbourhood. Both reuse the three task levels and the adjacency-matrix view.

Quick self-check

Name the three task levels and one concrete example of each.

Node level (classify a protein's function), link level (recommend a product to a user), graph level (predict a molecule's toxicity).

Why does a convolution on an image not transfer directly to a graph?

A pixel has a fixed set of neighbours in a fixed order (a 3×3 window); a graph node has a variable number of neighbours and no canonical order, so a fixed filter cannot be slid over it.

What is the difference between a directed and an undirected graph in the adjacency matrix?

An undirected graph has a symmetric adjacency matrix; a directed graph does not.

Key idea

A graph model must work for any number of nodes and give the same answer no matter how the nodes are numbered — everything else is a design choice about what the nodes and edges mean.

\[ G = (V, E, R, T), \qquad (v_i, r, v_j)\in E,\; r\in R,\; T(v_i)\ \text{= node type} \]

A homogeneous graph is the special case \(|R| = |T| = 1\). Permutation: relabelling nodes with a permutation matrix \(P\) turns \(A\) into \(PAP^\top\); a graph-level model \(f\) must satisfy \(f(PAP^\top, PX) = f(A, X)\).

Worked example: folding a user–movie graph

Three users rate four movies. \(B_{u,m}=1\) if user \(u\) rated movie \(m\):

\[ B = \begin{pmatrix} 1 & 1 & 0 & 0\\ 1 & 1 & 1 & 0\\ 0 & 0 & 1 & 1 \end{pmatrix}\quad(\text{rows: Ali, Sara, Reza})\]
  1. User–user (co-rating) network: \(BB^\top = \begin{pmatrix} 2&2&0\\2&3&1\\0&1&2\end{pmatrix}\). Ali–Sara share 2 movies, Sara–Reza 1, Ali–Reza 0.
  2. Diagonal = how many movies each user rated (their degree in the bipartite graph).
  3. Movie–movie network: \(B^\top B\); movies 1 and 2 are co-rated by 2 users — a classic item-to-item recommendation signal.
  4. What is lost: from \(BB^\top\) alone you cannot tell which movies were shared. That's why Lecture 11 keeps the bipartite graph and runs GNNs on it directly.

Strictly speaking: folding a weighted or very popular "hub" (a blockbuster seen by everyone) creates a dense, uninformative clique; practitioners down-weight by degree (e.g. \(1/\log \deg\)) — the same intuition reappears as degree normalisation in GCNs.

Proof workshop: Folding a bipartite graph manufactures cliques

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. Let \(B\) be a bipartite graph between users \(U\) and movies \(M\), and let movie \(m\) have \(d_m\) users. The folded graph \(G\) on \(U\) joins two users when they share at least one movie. Prove that (a) the users of each movie form a clique in \(G\); (b) \(|E(G)|\le\sum_{m}\binom{d_m}{2}\), with equality if and only if no two users share two or more movies.

Hint 1
Count pairs \((\{u,u'\},m)\) where \(m\) is a movie both \(u\) and \(u'\) watched, in two ways.
Hint 2
Grouped by movie, the count is \(\sum_m\binom{d_m}{2}\). Grouped by user pair, each pair contributes the number of movies it shares.
Solution
(a) Any two users of \(m\) share \(m\), so they are adjacent in \(G\). (b) Let \(c(u,u')\) be the number of movies shared by \(u,u'\). Double counting gives \(\sum_m\binom{d_m}{2}=\sum_{\{u,u'\}}c(u,u')\). An edge of \(G\) is exactly a pair with \(c\ge1\), so \(|E(G)|=\sum_{\{u,u'\}}\mathbf 1[c\ge1]\le\sum c(u,u')\), with equality iff every pair has \(c\le1\). \(\square\)

Why it matters. A projected network is a union of cliques, one per item, so its clustering coefficient is high by construction. Newman, Strogatz & Watts (2001) showed that much of the "high clustering" reported for collaboration networks is this artefact. Before reading triangles in a co-retweet or co-hashtag graph as social closure, compare against the folding of a randomised bipartite graph with the same degrees.

Sharper lens: what "no canonical order" really costs

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

Almost every graph has no symmetry at all, and still no cheap canonical order

There are \(2^{\binom n2}\) labelled graphs on \(n\) nodes. Erdős and Rényi (1963) proved that almost all of them are asymmetric (the only automorphism is the identity), so a typical graph has exactly \(n!\) different adjacency matrices and the number of unlabelled graphs is \(\sim 2^{\binom n2}/n!\). The lecture's "\(n!\) orderings" is the typical case, not the worst case.

So why not sort the nodes into one canonical order and then use an MLP? Because computing a canonical form is at least as hard as graph isomorphism, which has a quasi-polynomial algorithm (Babai 2015) but no known polynomial one, and every cheap rule (sort by degree, by PageRank) breaks on ties and jumps discontinuously when one edge changes. That is the real reason the course builds invariant functions and never canonical inputs. Lecture 6 shows what the cheap invariant functions give up in return.

second viewpoint

A graph is the special case "one binary relation"

The slides call graphs "a general language". The general object is a relational structure: a set of entities with relations of any arity. A simple graph is one symmetric binary relation; a heterogeneous graph is several binary relations (Lecture 9); a database row with three foreign keys is a ternary relation (Lectures 12 and 13, where the junction table has to be turned back into a node); a group chat or a co-authored paper is a hyperedge.

Choosing a graph is therefore a claim that pairwise ties are enough. The proof workshop on this page shows one way the claim fails (folding manufactures cliques). When the phenomenon is a group event, keep the bipartite or hypergraph form. This is also why finite model theory, the logic of relational structures, keeps turning out to be the right language for what GNNs can express (Lecture 6).

since the slides

The applications slide, three years on

Proteins. AlphaFold 3 (Abramson et al., Nature 2024) replaced AlphaFold 2's rotation-equivariant structure module with a diffusion model that has no built-in rotational symmetry and learns it from randomly rotated training examples. The spatial-graph view of the molecule survived; the hand-built symmetry did not. Keep this next to Lecture 3's symmetry principle and Lecture 21's equivariant networks: built-in symmetry is a strong prior for small data and an optional one at scale.

Weather. GraphCast (Science 2023) was followed by GenCast (Nature 2024), a diffusion model on the same icosahedral mesh that produces ensembles and beat the ECMWF ensemble on 97% of 1,320 evaluated targets. Antibiotics. After halicin came abaucin (2023) and a new structural class found with an explainable GNN (Wong et al., Nature 2024), where the explanation, a substructure, was the scientific result (Lecture 21).

Lab: hands-on and practical tips

Try it live. In the Graph Explorer: measure a Facebook network against random graphs, score the karate club seven ways and run cascades on it. Each lesson has predict-then-check questions.

notebook · L01 introduction builds a graph from raw records, converts it to edge_index, folds a bipartite graph and sets up the three task levels.

Undirected means both directionstorch.tensor(list(G.edges())).t() stores each friendship once. Message passing only follows stored directions, so half of every tie silently disappears; in the notebook Mr Hi (node 0) ends up with in-degree 0. Use to_undirected(edge_index) and check is_undirected.
Decide the representation before the modelWrite down the question first ("will A retweet B?", "is this account automated?"), then pick directed vs undirected, weighted vs binary, bipartite vs folded. Folding destroys who the shared neighbour was (see the folding figure above), and a 3-author paper becomes a clique that looks like strong ties.
Test the null modelBefore claiming "hubs" or "scale-free", sample an Erdős–Rényi or configuration-model graph with the same size and degree sequence and compare. Broido & Clauset (2019) found strongly scale-free networks are rare across about 1,000 real networks.
Keep a tiny toy graphEvery notebook in this repo starts from a 4–10 node example you can verify by hand. Do the same in your own projects: a model that cannot reproduce a hand computation on a toy graph is not ready for a million nodes.

Course logistics (2026)

  • Grade: 3 written homeworks 20% · 5 Colabs 15% · exam 35% · project 30%.
  • Homeworks are 10–20 h each: theory + algorithm design + math. Colabs are 3–5 h, hands-on PyG.
  • Tools: PyG (PyTorch Geometric), GraphGym; NetworkX / SNAP.py for classic network analysis.
  • Exam (Fall 2026): Wed 11/18, 6–8 pm, in person, closed book, homework-style questions.
  • Prerequisites: ML, algorithms & graph theory, probability, linear algebra, Python. "No single topic is hard; the breadth is what makes it hard."

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.

Lecture 1 has no assigned papers. Use this lecture to set up your three reference books — they cover different layers of the same subject:

start here Hamilton, Graph Representation Learning (2020)

Free PDF · cs.mcgill.ca/~wlh/grl_book · ~140 pages, dense and modern
  • Ch. 1 (Introduction) — the same task taxonomy as this lecture, with cleaner notation. 30 min.
  • Ch. 2 (Background & traditional approaches) — node/graph statistics, kernels, neighbourhood overlap. Read before Lecture 2.
  • Look-up later: Ch. 3 (embeddings) ↔ L2, Ch. 5–7 (GNNs) ↔ L3–L7, Ch. 4 (multi-relational) ↔ L9–L10, Ch. 8–9 (generation) ↔ L18.

for SNA intuition Easley & Kleinberg, Networks, Crowds, and Markets (2010)

Free · cornell.edu/networks-book · social-science flavour, almost no ML
  • Ch. 2 (Graphs) and Ch. 3 (Strong and weak ties) — triadic closure, bridges, the Granovetter story. These are the structural ideas GNNs later learn implicitly.

for network science Barabási, Network Science (2016)

Free · networksciencebook.com · interactive figures
  • Ch. 2 (Graph theory) — degree, adjacency, bipartite graphs, paths, clustering. Quick refresher in one hour.

Also: community course notes covering all lectures: CS224w.pdf. Lecture videos: Canvas (enrolled students only); older public recordings (Fall 2019 / 2021) exist on YouTube under "Stanford CS224W".

Homework & Colabs connected to this lecture

Colab 0 — Graph basics with NetworkX and PyG not graded

Released Thu 9/24 · open in Google Drive / Colab ↗ · local copy: course folder

A warm-up notebook: build and draw graphs in NetworkX, then load a PyG dataset and inspect a Data object (x, edge_index, y, masks) and write a tiny GCN. Goal: get fluent with the edge_index (2 × |E|) format that every later Colab uses.

Colab 1 — Node embeddings due Thu 10/8

open in Google Drive / Colab ↗ · covers Lectures 1–4

In past offerings: classic statistics on Zachary's Karate Club (average degree, clustering coefficient, PageRank, closeness centrality) → convert the graph to tensors → sample negative edges → train an nn.Embedding with a logistic edge-classification loss and visualise the result. Lecture 1 gives you the vocabulary; Lecture 2 is the core.

The Colabs are Google-Drive notebooks; this cloud session could not download them, so open them via the links (File → Save a copy in Drive).

Self-check

Which property must a graph-level model have that an image CNN does not need?

  1. Translation invariance
  2. Fixed input size
  3. Invariance to the numbering of nodes
  4. A softmax output

Relabelling nodes gives \(PAP^\top\) — the same graph. The output must not change. Images have a canonical pixel order, graphs don't.

Predicting whether two drugs taken together cause a side effect is a …

  1. node-level task
  2. link-level task
  3. graph-level task
  4. community detection task

It's a prediction about a pair of nodes (and the relation type = the side effect) — link prediction on a heterogeneous graph.

Antibiotic discovery in Stokes et al. (2020) treats each molecule as …

  1. a node in a molecule-similarity graph
  2. an edge between proteins
  3. a sequence of SMILES characters only
  4. a whole graph to be classified

Atoms = nodes, bonds = edges; the GNN outputs one score per molecule → graph classification.

Folding an authors–papers bipartite graph onto authors gives …

  1. a co-authorship network with weights = number of shared papers
  2. a citation network
  3. a directed author→paper graph
  4. the same graph with fewer edges and no information loss

\(BB^\top\) counts shared papers. Information about which papers is lost, so (4) is wrong.

In AlphaFold's "spatial graph", edges represent …

  1. covalent bonds between atoms
  2. proximity between residues
  3. evolutionary ancestry
  4. sequence order only

Nodes are amino acids; edges connect residues close in 3D space, refined iteratively.

Flashcards (click to flip)

Three reasons graphs are hard for standard DL
Arbitrary size & topology; no fixed node order / reference point; often dynamic with multimodal features.
Heterogeneous graph
\(G=(V,E,R,T)\): typed nodes \(T(v)\), typed edges \((v_i,r,v_j)\).
Bipartite graph
Two disjoint node sets; every edge crosses between them (users–items).
Link prediction at test time
Rank all unconnected node pairs by score, predict the top-K.
Relational database as a graph
Rows → nodes, foreign keys → edges, tables → node types.
Graph-level example
Molecule property prediction; ETA for a route; physics simulation (graph evolution).

History & the bigger picture

  • 1736 — Euler, Königsberg bridges. Graph theory begins by throwing away geometry and keeping only who connects to whom.
  • 1930s — Jacob Moreno's sociograms. The birth of social network analysis: drawing friendships in a school class to explain runaways. Your field's ancestor.
  • 1973 — Granovetter, "The strength of weak ties". Structure (bridges) predicts outcomes (finding jobs) — the first convincing "position in the network matters" result.
  • 1998 — PageRank; Watts–Strogatz small worlds. 1999 — Barabási–Albert scale-free networks. Network science goes mainstream.
  • 2005–2009 — Gori & Scarselli, "The Graph Neural Network Model". First GNN, a recurrent fixed-point model. Ahead of its time; little compute.
  • 2014 — DeepWalk brings word2vec to graphs (Lecture 2). 2017 — GCN, GraphSAGE, GAT, MPNN (Lectures 3–4). 2020s — graph transformers, foundation models, LLM + graph (Lectures 8, 14–17).
Philosophy · relations first

Graph ML quietly takes a philosophical stance: an entity is (largely) what its relations make it. This echoes structuralism (Saussure: a word's meaning comes from its differences with other words), structural realism in philosophy of science (what science really captures is structure), and, in social theory, the relational sociology of Simmel and later Emirbayer's "Manifesto for a Relational Sociology" (1997). When a GNN represents a person purely by aggregating their neighbours, it operationalises that thesis — and inherits its blind spots (what about the inner life not visible in ties?).

Classic SNA bridge

In this lectureClassic SNA counterpartWhat carried over, what changed
Graph = nodes + edges as a "general language"Moreno's sociograms (1934); the "sociomatrix" of Forsyth & Katz (1946)Same object. SNA always drew the adjacency matrix; graph ML made it an input tensor and let the model, not the analyst, decide which structural features matter.
Node / link / graph-level tasksCentrality (node), tie prediction and homophily (dyad), network comparison and the triad census (whole network)The three levels are Wasserman & Faust's levels of analysis under new names. What is new is learning the features instead of computing them (Lecture 2 onward).
Heterogeneous graphs \(G=(V,E,R,T)\)Multiplex and multimodal networks; affiliation (two-mode) networksTwo-mode networks were folded by hand for decades (Breiger 1974, "The duality of persons and groups"). Heterogeneous GNNs (Lecture 9) keep the modes and learn a weight per relation instead of folding.
Permutation invarianceRelabelling never changed a sociogram; "structural" properties by definitionSNA took invariance for granted because its statistics were invariant. Deep learning on tensors is not, so Lecture 3 has to build invariance into the architecture.
"Networks are complex: arbitrary size, no fixed order, dynamic, multimodal"The same complaint, from the other side: statistical models for networks (p*, ERGMs) are hard precisely because ties are dependentDependence between ties is the shared difficulty. ERGMs model it with a global likelihood; GNNs model it with local message passing and never write the likelihood down.
Bridge idea

Take one classical SNA study you know (for example a Granovetter-style weak-ties analysis on a retweet graph). Rewrite its question at the three levels of this lecture: which node-level, link-level and graph-level prediction would test it? That translation exercise is the fastest way to see which parts of the course your research actually needs.

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 1 · Ties, triads & the roots of SNA (the graph vocabulary and the three levels of analysis, as graph ML states them); Unit 4 · Random graphs & small worlds (why graphs are hard inputs: no order, no fixed size); Unit 7 · Cascades, contagion & influence (spreading on a graph as a first example of why structure matters).

Connecting to your research

Running project. Section L01 · Which graph? of notebooks/project/retweet_thread.py applies this lecture to one synthetic X world with coordinated rings, the same graph across the whole course.

For SNA on X/Twitter
  • Node-level: bot detection, stance / ideology inference, influencer identification.
  • Link-level: follow/retweet prediction; "who will engage with this narrative next?".
  • Graph-level: classify retweet cascades (organic vs coordinated), predict virality from the early cascade graph.
  • Representation choice is the research question: a heterogeneous graph (users, tweets, hashtags, URLs; relations follows/retweets/mentions/uses) vs. several folded homogeneous graphs. Write down which questions each choice makes answerable before you build anything.

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.

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
karateZachary's karate club34club after the split (2)community detection, the course's running toy graph
davisDavis Southern Women32bipartite: women / eventsbipartite projection (folding)
florentineFlorentine families15—centrality: why the Medici won (betweenness)
dolphinsDoubtful Sound dolphins62—a small animal social network that split in two
footballNCAA college football 2000115conference (12)community detection with ground truth; node embeddings recover conferences
polblogsUS political blogs 20041,490leaning: liberal / conservativepolarisation, homophily, the classic SBM / spectral benchmark
ego-facebookFacebook ego networks (combined)4,039—friendship structure: high clustering, triangles, motifs
email-eu-coreEU research institution e-mail1,005department (42)community detection and node classification with ground truth
higgs-retweetHiggs boson Twitter: retweet graph256,491—who retweeted whom around one event (weights = retweets)

Frontier 2025–26: what changed since the slides

What changed since the slides were written, from the Graph Learning Atlas (710 papers from NeurIPS 2025, ICLR 2026 and ICML 2026) and the Frontiers deck.

2025–26The field audited itself — The defining pattern of the period is self-audit: tuned classic GNNs match graph transformers, "universal statements" about over-smoothing and heterophily were refuted by formal counterexamples, non-prior-fitted foundation models lose to tuned GNNs, and graph unlearning was found "not yet practical". The lecture's promise that "explicitly modelling relationships gives better performance" now comes with a rule: run a tuned baseline first.
ICLR 2026 oralLLMs act on graphs instead of reading them — Finkelshtein et al. ("Actions Speak Louder than Prompts") ran a large-scale study: letting an LLM write and run code over the graph beats serialising the graph into the prompt, and the gain is largest on long-text or high-degree graphs. The three task levels of this lecture are still the right vocabulary; what changed is who executes the combinatorics.sources: arXiv:2509.18487
ICML 2026Generality comes from priors, not scale — GraphPFN trains on millions of synthetic graphs (SBM, preferential attachment, causal models) and infers by one forward pass; the Relational Transformer transfers zero-shot across database schemas. Both succeed where a shared invariance exists, and the slide-1 claim that "graphs are a general language" is exactly what makes the search for a shared graph vocabulary hard.sources: arXiv:2509.21489 · arXiv:2510.06377
AtlasWhere the 710 papers went — The largest clusters are graphs for science (74 papers), architectures and spectral methods (57), expressivity theory (56) and foundation models (49). Social networks, opinion dynamics and information ecosystems form a 44-paper cluster with two orals, which is the lecture's "social networks" bullet turned into a research front.
Open question to carryWhen does explicitly modelling relationships fail? Heterophilous graphs (neighbours unlike each other) and the Shalizi–Thomas confound (homophily and influence are observationally indistinguishable) are the two standard answers; both reappear in later lectures.
Frontiers deck · the 2025–26 picture · the deep era timeline · Atlas map

Words & phrases

TermSimple meaningPersianIn context
boil down tophraseto be, in the end, basically just this one thingدر اصل خلاصه شدن به"every problem boils down to one of three questions"
churnn./v.(business) when a customer stops using a product or serviceریزش مشتری"will this customer churn?"
multisetn.a set in which the same element may appear several timesچندمجموعه"a multiset of features"
residuen.(biochemistry) one amino acid unit inside a protein chainباقی‌مانده (آمینواسیدی)"nodes are amino acids (residues)"
polypharmacyn.a patient taking many different medicines at the same timeچنددارویی"polypharmacy side effects"
de novoadj. (Latin)new, from scratch; not previously known or recordedاز نو، کاملاً جدید"top-ranked de novo predictions"
heterogeneousadj.made of different kinds of things; a heterogeneous graph has several node or edge typesناهمگن"a heterogeneous graph of users, posts and hashtags"
bipartiteadj.with nodes split into two groups so that every edge goes between the groupsدوبخشی"the user–movie graph is bipartite"
adjacency matrixn.the n×n table whose (i, j) entry says whether nodes i and j are linkedماتریس مجاورت"store the graph as a sparse adjacency matrix"
sparseadj.mostly zeros or mostly missing; most pairs of nodes are not linkedتُنُک"real graphs are sparse: |E| is far below n²"

Go deeper

  • Next: Lecture 2 — how to turn each node into a vector without hand-crafted features (DeepWalk, node2vec).
  • Classic: Granovetter (1973), "The Strength of Weak Ties" — 15 pages that every graph-ML person working on social data should know.
  • Open question: the slides say "by explicitly modelling relationships we achieve better performance". When does that fail? (Hint: heterophilous graphs, where neighbours are unlike each other — a recurring theme later.)