Graph Neural Networks

How neural networks learn from graphs: message passing, a GCN trained on Zachary’s karate club, over-smoothing, permutation invariance and graph attention.

Advanced lesson, about 35 minutes, with interactive demos and a quiz.

What you will learn

Data shaped like a network

A molecule is atoms joined by bonds. A city is junctions joined by roads. A social network is people joined by friendships, and science is papers joined by citations. None of these is a grid of pixels or a sentence of words. Graph neural networks are the models built for them. They have been used to estimate arrival times in Google Maps, to recommend pins on Pinterest, to forecast global weather and to find a new antibiotic candidate.

What is it?

A graph neural network (GNN) learns from data given as a graph: a set of nodes, the edges between them, and a feature vector on each node (and sometimes on each edge). It produces a vector for every node that summarises the node and its surroundings, and from those vectors it predicts something about nodes, edges or the whole graph. The name goes back to work by Marco Gori, Franco Scarselli and colleagues in the mid-2000s, set out in full in their 2009 paper on the graph neural network model.

How does it work?

Every node repeatedly collects the vectors of its neighbours, combines them with its own, and updates. After one round a node knows about its direct neighbours; after two, about their neighbours too. The same small network is used at every node, so the model works on graphs of any size and shape.

Why not a grid or a sequence?

An image is a regular graphEvery pixel away from the border has exactly 8 neighbours in fixed positions (up-left, up, ...). A convolution can give each position its own weight.A sentence is a pathEvery word except the first and last has one word before it and one after. Order is meaningful, so a model can read left to right.A graph has neitherOne atom has 1 neighbour, another 4. Neighbours have no “left” or “first”, and the numbering of nodes is arbitrary.So the model must not care about orderA GNN treats a node’s neighbours as an unordered set, and gives the same answer however the nodes are numbered.

Why does it matter?

A great deal of valuable data is relational: who buys what, which protein binds which, which account pays which. Flattening it into a table throws the structure away. GNNs keep it, and they generalise the convolution of CNNs and, as you will see near the end, the attention of transformers.

Key takeaways

  • A GNN learns from nodes, edges and node features, producing a vector for every node.
  • Nodes repeatedly combine their neighbours’ vectors with their own, using the same weights everywhere.
  • Graphs have varying numbers of unordered neighbours and arbitrary node numbering, which grids and sequences do not.

A graph as two matrices

To compute on a graph, write it as numbers: one matrix for who is connected to whom, one for what each node is like.

What is it?

The adjacency matrix A of a graph with n nodes is an n × n table with Aᵢⱼ = 1 if nodes i and j are connected and 0 otherwise. For an undirected graph it is symmetric. The feature matrix X has one row per node: for an atom, its element and charge; for a paper, the words it uses; for a person, their profile. The number of neighbours of node i, its degree dᵢ, is the sum of row i of A.

How does it work?

Multiplying by A does the neighbourhood bookkeeping in one step: row i of A·X is the sum of the feature vectors of node i’s neighbours. Large real graphs are usually sparse, with far more zeros than ones, so graph libraries store the list of edges rather than the full matrix.

Why does it matter?

The matrix view hides a trap. Renumber the nodes and A changes: its rows and columns are shuffled, although the graph is the same. A model that reads A as a fixed-length vector would see a different input. Everything a GNN does is built so that this renumbering cannot change its answer, which the permutation section below tests directly.

Key takeaways

  • The adjacency matrix A records the edges; the feature matrix X holds one vector per node.
  • Row i of A·X is the sum of node i’s neighbours’ features; degrees are the row sums of A.
  • The node numbering is arbitrary, so the same graph has many adjacency matrices.

Message passing: aggregate, then update

Almost every graph neural network is one idea repeated: each node listens to its neighbours, then updates itself.

What is it?

In a message-passing layer, every node gathers messages from its neighbours, aggregates them with an operation that ignores their order (sum, mean or max), and updates its own vector from the result and its previous vector. Gilmer and colleagues showed that at least eight earlier graph networks can be written in this form.

mᵥ = AGGREGATE( hᵤ : u ∈ N(v) )
hᵥ(k+1) = UPDATE( hᵥ(k), mᵥ )

hᵥ is node v’s vector at layer k, N(v) its neighbours. The update is usually a small neural network with learned weights, shared by all nodes.

How does it work?

The demo strips the layer to its core, with no learned weights: the update is just the aggregate of the node and its neighbours. With the mean, node 4, whose only neighbour is node 3, becomes the average of two vectors. A real layer then multiplies the result by a learned weight matrix and applies a nonlinearity, but the flow of information along the edges is exactly what you see here.

Watch the colours spread: after one round each node is a blend of its neighbourhood, after a few rounds features have travelled across the graph. With Sum, node 3, the hub, grows to [1.6, 2.4] in one round while node 4 reaches [0, 1.4]. Sum keeps information about how many neighbours there were, which mean and max lose: Xu and colleagues showed that sum can tell apart neighbourhoods that the other two confuse. Mean keeps every node on the same scale, which helps when degrees vary wildly.

Why does it matter?

Because the same aggregate and update run at every node, the number of weights does not depend on the size of the graph. A model trained on molecules of 20 atoms can be applied to one of 60, and a model trained on one city’s roads can run on another’s. That weight sharing is the graph version of a convolution sliding the same filter over every pixel.

Key takeaways

  • A message-passing layer aggregates neighbours’ vectors with an order-free operation, then updates each node.
  • The same weights are shared by every node, so one model fits graphs of any size.
  • Sum keeps degree information; mean and normalised sums keep vectors on a common scale.

The graph convolutional network

The GCN of Kipf and Welling is message passing in its simplest learned form: one degree-weighted sum over each neighbourhood and one weight matrix per layer. Its cost grows linearly with the number of edges, and it works with very few labels.

What is it?

A graph convolutional network layer adds a self-loop to every node, sums over the node and its neighbours with weights 1/√((dᵢ + 1)(dⱼ + 1)), multiplies by a learned weight matrix and applies a nonlinearity (Kipf & Welling). The symmetric normalisation keeps vectors from growing with degree, and lets a well-connected neighbour count for less than a neighbour that is connected to only a few nodes.

H(k+1) = σ( D̃^−½ Ã D̃^−½ H(k) W(k) )

à = A + I adds self-loops; D̃ is the diagonal matrix of Ã’s row sums (degrees + 1); W is learned; σ is ReLU between layers and softmax at the output.

How does it work?

The demo below trains a real two-layer GCN, with 16 hidden units and the Adam optimiser, on the karate club studied by Zachary: 34 members of a karate club and the 78 friendships among them, recorded as pairs of members who interacted outside the club. After a dispute between the instructor (member 0, called “Mr. Hi” in the study) and the club’s administrator (member 33), the instructor left to start a new club and the members split between the two. The data labels the two sides “Mr. Hi” and “Officer”. Each member’s only input feature is a one-hot vector that says which member it is, nothing about their club. Only the clubs of the ringed members are given; the loss is computed on them alone. This is semi-supervised node classification: predict the labels of every other node.

With members 0 and 33 labelled, the GCN reaches 31 of 32 (97%) for each of the 20 sets of starting weights we tried, after anywhere from 3 to 63 epochs. The one member it gets wrong is member 8: three of its five friends are in the other club, yet it joined Mr. Hi’s. Label only one member and the model has no reason to predict the other club at all. The model without edges averages about 50% over the same starting weights, however long it trains: the friendships carry all the information.

Why does it matter?

Labels are expensive and graphs are cheap: a citation network comes with its citations, a social network with its friendships. On the Cora citation graph, Kipf and Welling trained on the labels of 140 of its 2,708 papers and classified 81.5% of 1,000 test papers correctly; a plain network on the same word vectors, ignoring the citations, reached 55.1%. The method relies on homophily, the tendency of connected nodes to share labels. On graphs where neighbours tend to differ (for example buyers and sellers, or predators and prey), popular graph networks can do worse than a model that ignores the graph (Zhu et al.).

Key takeaways

  • A GCN layer is a degree-weighted sum over each node and its neighbours, then a learned weight matrix and a nonlinearity.
  • In semi-supervised node classification the loss uses a few labelled nodes, and the graph spreads their information to the rest.
  • It works when neighbours tend to share labels (homophily).

Depth: receptive fields and over-smoothing

More layers let information travel further. Too many, and every node ends up saying the same thing.

What is it?

After k message-passing layers, a node’s vector depends on exactly the nodes within k hops: its receptive field. Deeper models see further, but repeated averaging also blurs. Over-smoothing is what happens when it goes too far: the vectors of all nodes in a connected graph come to point the same way and can no longer be told apart. Li, Han and Wu showed that the GCN’s propagation step is a special form of Laplacian smoothing, which is why stacking many GCN layers risks exactly this.

How does it work?

Member 0 sees 17 members after one layer, itself included, and all 34 after three, while member 16, out on the edge, needs five. Paths in this club are short: after three layers every member sees at least 18 of the 34, and 29 on average. To see over-smoothing in isolation, the next demo gives every member a one-hot vector, so that all 34 start out completely different, and applies GCN propagation over and over with no weights.

The best range here is 2 to 4 rounds. The similarity between members climbs steadily: about 0.5 after 3 rounds, 0.88 after 10, 0.99 after 22. The lean towards the right club survives until about round 25 and has gone by round 38. A trained GCN has learned weights and nonlinearities between its rounds, but depth still hurts: on citation graphs, Kipf and Welling got their best results with two or three layers, and found models deeper than seven layers hard to train without residual connections, which carry each node’s earlier vector forward.

Why does it matter?

Depth in a GNN does not work like depth in an image CNN, where residual networks with up to 152 layers train well. If a task needs information from far away, such as two atoms at opposite ends of a long molecule, adding layers runs into over-smoothing, and squeezing a huge receptive field into one fixed-size vector loses detail as well. Remedies include residual and jumping-knowledge connections, normalisation layers, and attention across the whole graph, which lets a node reach distant nodes directly.

Key takeaways

  • After k layers a node’s vector depends exactly on the nodes within k hops.
  • Repeated averaging makes all node vectors point the same way: over-smoothing.
  • Shallow GNNs of two or three layers often work best; residual connections help deeper ones train.

Node, edge and graph tasks, and why order must not matter

The node vectors a GNN produces are the raw material. What you predict from them decides the last step.

What is it?

Node-levelPredict something for each node from its final vector: the topic of a paper, the club of a member, the travel time on a road segment when segments are the nodes.Edge-levelCombine the vectors of two nodes, for example by a dot product or a small network: will these two users connect, does this drug interact with that one?Graph-levelA readout pools all node vectors into one, then predicts for the whole graph: is this molecule toxic, how soluble is it?

How does it work?

Two properties make this safe. Message-passing layers are permutation-equivariant: renumber the nodes and the output vectors are renumbered the same way, each staying with its node. A readout such as sum, mean or max is permutation-invariant: it gives the same answer for any order of its inputs. Equivariant layers followed by an invariant readout give a graph-level model that cannot be fooled by the numbering.

Why does it matter?

A graph has n! numberings: over 3.6 million for just 10 nodes. A model that is not invariant would have to learn the same answer for all of them from data. Building the symmetry into the architecture means it never has to: every numbering gives the same answer by construction.

Key takeaways

  • Node tasks use each node’s vector, edge tasks combine two, graph tasks pool all of them with a readout.
  • Message passing is permutation-equivariant; sum, mean and max readouts are permutation-invariant.
  • Building the symmetry in means the model never has to learn it from data.

Attention on graphs, and the link to transformers

A GCN weighs every neighbour by degree alone. Attention lets each node decide which neighbours matter.

What is it?

A graph attention network (GAT) computes a score for each edge from the features of its two nodes, turns the scores of a node’s neighbours into weights with a softmax, and takes the weighted average (Veličković et al.). Several attention heads run in parallel, as in a transformer.

eᵢⱼ = LeakyReLU( aᵀ [W hᵢ ‖ W hⱼ] )
αᵢⱼ = softmaxⱼ( eᵢⱼ ), hᵢ′ = σ( Σⱼ αᵢⱼ W hⱼ )

W is a shared weight matrix, a a learned vector, ‖ joins two vectors; the softmax runs over j in N(i) and i itself.

How does it work?

Let every node attend to every other node, in other words run GAT on the complete graph, and you have the core of a transformer’s self-attention: a weighted average over all tokens, with weights computed from their vectors. A transformer is a graph network on a graph where everything is connected, with position encodings to say where each token sits. The graph tells a GAT whom it may listen to; a transformer listens to every token (or, in a language model, every earlier token) and learns whom to ignore. The scoring functions differ in detail (GAT adds the two nodes’ terms, a transformer takes a dot product of a query and a key), but the shape of the computation is the same.

Why does it matter?

Attention helps where neighbours are not equally informative, and it links graph networks to transformers. Models called graph transformers use both: GraphGPS, for example, combines message passing along the real edges with attention across every pair of nodes.

The Attention Mechanism lab shows query-key attention over the words of a sentence, the complete-graph case.

Key takeaways

  • GAT learns neighbour weights from features with a softmax over each neighbourhood.
  • Self-attention in a transformer is attention on a complete graph of tokens.
  • GCN weights depend only on the graph; attention weights depend on the data.

Where graph networks are used

The ideas in this lesson, scaled up, have been deployed in products and used in published scientific work.

What is it?

Drug discoveryA directed message-passing network, trained on 2,335 molecules tested against E. coli, ranked compounds in chemical libraries for antibacterial activity. It flagged halicin, structurally unlike conventional antibiotics, which then treated two kinds of infection in mice (Stokes et al.).Arrival timesA GNN whose nodes are road segments was deployed in Google Maps to predict travel times. Compared with the previous system, the authors report over 40% fewer estimates with an error above a set threshold in cities such as Sydney.RecommendationsPinSage builds on GraphSAGE and samples each node’s neighbourhood with random walks. It was trained on a Pinterest graph of 3 billion pins and boards and 18 billion edges.ScienceGraphCast forecasts global weather by message passing on a mesh that covers the Earth. The authors of AlphaFold 2 describe protein structure prediction as inference on a graph whose edges join residues that are close in space.

How does it work?

A graph the size of Pinterest’s is far too big for a full-batch GCN that touches every node at every step. GraphSAGE samples a fixed number of neighbours per node per layer and learns how to aggregate them, so a training step costs the same however popular a node is, and the trained model applies to nodes added after training (Hamilton et al.). Edges can carry features too, such as bond types in molecules, and message-passing layers can feed them into the messages.

Why does it matter?

Graphs are how a lot of the world’s data is already shaped, and GNNs let a model use that shape instead of discarding it. Their limits are worth knowing too: over-smoothing, difficulty with long-range dependencies, and reliance on homophily. AlphaFold is better described as graph-inspired than as a plain GNN: its Evoformer keeps a vector for every pair of residues, which its authors interpret as the edges of a graph, and updates them with attention and “triangle” updates.

Recommender Systems: how user-item graphs and embeddings turn into suggestions.

Key takeaways

  • GNNs have been used for molecules, road networks, recommendations and weather; AlphaFold’s design is graph-inspired.
  • Neighbour sampling, as in GraphSAGE and PinSage, lets them scale to billions of edges and apply to new nodes.
  • Their main limits are over-smoothing, long-range dependencies and reliance on homophily.

Check your understanding

Six situations where graphs come up. Each asks you to apply an idea, not just recall it.

Question 1 of 6

A team predicts whether a molecule is toxic. They store each molecule as its adjacency matrix, padded to 50 atoms, flatten it and train an ordinary neural network. On a held-out set, the same molecules written with their atoms in a different order get different predictions. What is going wrong, and what is the standard fix?

Next, see attention over a sentence in the Attention Mechanism lab, or how graphs of users and items drive recommender systems.

References

The papers behind the methods, datasets and applications in this lesson.

References

  1. [1]

    The Graph Neural Network Model(opens in a new tab)

    Franco Scarselli, Marco Gori, Ah Chung Tsoi, Markus Hagenbuchner & Gabriele Monfardini, 2009

    IEEE Transactions on Neural Networks 20(1), 61–80. The full account of the graph neural network model, after conference papers by the same group from the mid-2000s: each node’s state is updated from its neighbours’ states, iterated until it reaches a fixed point.

  2. [2]

    Neural Message Passing for Quantum Chemistry(opens in a new tab)

    Justin Gilmer, Samuel S. Schoenholz, Patrick F. Riley, Oriol Vinyals & George E. Dahl, 2017

    ICML 2017, Proceedings of Machine Learning Research 70, 1263–1272. Describes at least eight earlier graph networks in one message-passing framework (message, update and readout functions) and predicts quantum-chemical properties of molecules.

  3. [3]

    How Powerful are Graph Neural Networks?(opens in a new tab)

    Keyulu Xu, Weihua Hu, Jure Leskovec & Stefanie Jegelka, 2019

    ICLR 2019. Compares sum, mean and max aggregation: sum can tell apart neighbourhoods that mean and max confuse. Introduces the Graph Isomorphism Network (GIN).

  4. [4]

    Semi-Supervised Classification with Graph Convolutional Networks(opens in a new tab)

    Thomas N. Kipf & Max Welling, 2017

    ICLR 2017. The GCN layer H′ = σ(D̃^−½ Ã D̃^−½ H W) with self-loops and symmetric normalisation, trained on a few labelled nodes of citation graphs (81.5% test accuracy on Cora with 140 labels). Appendix B tests depth: two or three layers work best.

  5. [5]

    An Information Flow Model for Conflict and Fission in Small Groups(opens in a new tab)

    Wayne W. Zachary, 1977

    Journal of Anthropological Research 33(4), 452–473. The ties among 34 members of a karate club that split in two after a dispute between its instructor and its administrator. The lesson uses the 78-edge version distributed with NetworkX.

  6. [6]

    Beyond Homophily in Graph Neural Networks: Current Limitations and Effective Designs(opens in a new tab)

    Jiong Zhu, Yujun Yan, Lingxiao Zhao, Mark Heimann, Leman Akoglu & Danai Koutra, 2020

    NeurIPS 2020. On graphs where connected nodes tend to differ (heterophily), many popular GNNs are outperformed by models that ignore the graph, such as multilayer perceptrons.

  7. [7]

    Deeper Insights into Graph Convolutional Networks for Semi-Supervised Learning(opens in a new tab)

    Qimai Li, Zhichao Han & Xiao-Ming Wu, 2018

    AAAI 2018, Proceedings of the AAAI Conference on Artificial Intelligence 32(1). Shows that the graph convolution of the GCN is a special form of Laplacian smoothing, which raises the concern of over-smoothing with many layers. Also at arxiv.org/abs/1801.07606.

  8. [8]

    Graph Attention Networks(opens in a new tab)

    Petar Veličković, Guillem Cucurull, Arantxa Casanova, Adriana Romero, Pietro Liò & Yoshua Bengio, 2018

    ICLR 2018. Replaces fixed neighbour weights with attention coefficients computed from the features of each pair of connected nodes (the neighbourhood includes the node itself), using several heads.

  9. [9]

    Recipe for a General, Powerful, Scalable Graph Transformer(opens in a new tab)

    Ladislav Rampášek, Mikhail Galkin, Vijay Prakash Dwivedi, Anh Tuan Luu, Guy Wolf & Dominique Beaini, 2022

    NeurIPS 2022. GraphGPS: each layer combines local message passing along the real edges with global attention over all pairs of nodes.

  10. [10]

    A Deep Learning Approach to Antibiotic Discovery(opens in a new tab)

    Jonathan M. Stokes, Kevin Yang, Kyle Swanson et al., 2020

    Cell 180(4), 688–702.e13. A directed message-passing neural network trained on 2,335 molecules screened against E. coli ranked compounds in chemical libraries and flagged halicin, from the Drug Repurposing Hub, structurally divergent from conventional antibiotics. Halicin treated C. difficile and pan-resistant A. baumannii infections in mice.

  11. [11]

    ETA Prediction with Graph Neural Networks in Google Maps(opens in a new tab)

    Austin Derrow-Pinion, Jennifer She, David Wong et al., 2021

    CIKM 2021, 3767–3776 (also arxiv.org/abs/2108.11482). A GNN whose nodes are road segments, deployed in Google Maps; compared with the previous production system, negative ETA outcomes (errors above a threshold) fell by over 40% in cities such as Sydney.

  12. [12]

    Graph Convolutional Neural Networks for Web-Scale Recommender Systems(opens in a new tab)

    Rex Ying, Ruining He, Kaifeng Chen, Pong Eksombatchai, William L. Hamilton & Jure Leskovec, 2018

    KDD 2018, 974–983 (also arxiv.org/abs/1806.01973). PinSage builds on GraphSAGE and samples neighbourhoods with random walks; it was trained at Pinterest on 7.5 billion examples on a graph of 3 billion pins and boards and 18 billion edges.

  13. [13]

    Learning skillful medium-range global weather forecasting(opens in a new tab)

    Remi Lam, Alvaro Sanchez-Gonzalez, Matthew Willson et al., 2023

    Science 382(6677), 1416–1421. GraphCast: graph neural networks in an encode-process-decode configuration that pass messages on a multi-scale mesh covering the globe, trained on 39 years (1979–2017) of ERA5 reanalysis data.

  14. [14]

    Highly accurate protein structure prediction with AlphaFold(opens in a new tab)

    John Jumper, Richard Evans, Alexander Pritzel et al., 2021

    Nature 596(7873), 583–589. Its Evoformer keeps a representation for every pair of residues and updates it with attention and “triangle” updates; the authors view structure prediction as graph inference in 3D space, with edges defined by residues in proximity.

  15. [15]

    Inductive Representation Learning on Large Graphs(opens in a new tab)

    William L. Hamilton, Rex Ying & Jure Leskovec, 2017

    NIPS 2017 (now NeurIPS), Advances in Neural Information Processing Systems 30. GraphSAGE: samples a fixed-size set of neighbours per node and learns aggregation functions, so the cost of each batch is fixed and the model applies to nodes it never saw in training.

Related