Search

Search papers and lessons

Graph Neural Network

Level 3 · 13 min read

A graph neural network learns node features by repeatedly letting each node combine its own features with those of its neighbours, so the result reflects the graph's structure.

On this page

  • Colour = topic mix
  • Discrete math
  • Neural network basics
  • Linear algebra
  • Calculus
  • Architectures
  • Sign in to see your progress

TL;DR

A graph neural network, or GNN, learns a feature vector for every node of a Graph (a set of nodes joined by edges). It does this by repeating one step: each node gathers the features of its neighbours, combines them with its own, and passes the result through a small learned function. After a few rounds, each node's vector reflects the structure around it. For a whole-graph answer, such as "is this molecule toxic?", the node vectors are pooled into one vector and fed to a classifier.

Where you'll see it: predicting properties of molecules in drug discovery, recommending items from user-item graphs, forecasting traffic on road networks, and flagging suspicious accounts in transaction graphs.

Intuition

Judge a node by its neighbourhood

Suppose you want to guess which team an employee belongs to, using only a company's email graph. The employee's own messages say little. Who they write to says a lot: people on the same team talk to each other. So a sensible first step is to summarise each person's contacts, and then let a model learn what those summaries mean. Looking at the contacts' contacts widens the view one more step.

That is the whole idea of a graph neural network. Each node repeatedly looks at its neighbours and updates itself. The graph supplies the structure, and learned functions turn it into numbers.

Why an ordinary network does not fit

A feedforward network expects a fixed-size input in a fixed order. A node in a graph can have one neighbour or two hundred, and the neighbours have no natural order. There is no "left neighbour" to put in position one. So a GNN needs two properties that an ordinary network lacks:

  1. It must accept any number of neighbours.
  2. It must give the same answer whatever order the neighbours are listed in.

The second property is called permutation invariance. A convolutional network avoids the ordering problem because every image pixel has neighbours in fixed positions. A graph has no such grid, so the GNN builds the order-free property in from the start.

One round of message passing

Each round of a GNN follows the same three moves, shown here for one node.

flowchart LR
  N[Neighbour features] --> M[Message: transform each neighbour]
  M --> A[Aggregate: sum, mean or max]
  S[Own features] --> U[Update: combine with the aggregate]
  A --> U
  U --> O[New features for this node]

The messages travel along edges, which is why the scheme is called message passing. Every node does this at the same time. Stacking rounds lets information travel further: one round reaches the direct neighbours, two rounds reach the neighbours' neighbours, and so on. Each step across an edge is called a hop.

The math

The message-passing layer

Let the graph have nodes VV and edges EE. Write N(v)\mathcal{N}(v) for the set of neighbours of node vv, and hv(l)\mathbf{h}_v^{(l)} for the feature vector of node vv after ll layers. The starting features are hv(0)=xv\mathbf{h}_v^{(0)} = \mathbf{x}_v, the raw input for that node.

Definition: Message-passing layer

A message-passing layer computes, for every node vv,

mv(l)=⨁u∈N(v)MSG ⁣(hu(l)),hv(l+1)=UPD ⁣(hv(l),mv(l)),\mathbf{m}_v^{(l)} = \bigoplus_{u \in \mathcal{N}(v)} \mathrm{MSG}\!\left(\mathbf{h}_u^{(l)}\right), \qquad \mathbf{h}_v^{(l+1)} = \mathrm{UPD}\!\left(\mathbf{h}_v^{(l)}, \mathbf{m}_v^{(l)}\right),

where MSG\mathrm{MSG} and UPD\mathrm{UPD} are learned functions, and ⨁\bigoplus is a permutation-invariant aggregator.

Read the first formula as "collect a message from each neighbour, then combine all of them into one vector mv\mathbf{m}_v". The second formula says "combine the node's own vector with that aggregate". The symbol ⨁\bigoplus stands for the aggregation, and MSG\mathrm{MSG} turns each neighbour's features into a message.

Permutation invariance

An aggregator is permutation-invariant when reordering its inputs does not change the output. The three standard choices are:

sum=∑u∈N(v)hu,mean=1∣N(v)∣∑u∈N(v)hu,max=max⁡u∈N(v)hu    (element by element).\mathrm{sum} = \sum_{u \in \mathcal{N}(v)} \mathbf{h}_u, \qquad \mathrm{mean} = \frac{1}{|\mathcal{N}(v)|}\sum_{u \in \mathcal{N}(v)} \mathbf{h}_u, \qquad \mathrm{max} = \max_{u \in \mathcal{N}(v)} \mathbf{h}_u \;\; \text{(element by element)}.

Addition does not care about order, and neither does taking a mean or a maximum. Concatenating the neighbours in the order the file lists them would not be invariant, and that is why it is never used. The three choices differ in one important way. Sum keeps a count of how many neighbours there are. Mean and max throw that count away. The worked examples come back to this.

A concrete instance: mean aggregation

A common and simple layer, in the style of GraphSAGE, is

hv(l+1)=σ ⁣(Wself hv(l)+Wnbr⋅1∣N(v)∣∑u∈N(v)hu(l)).\mathbf{h}_v^{(l+1)} = \sigma\!\left(\mathbf{W}_{\text{self}}\, \mathbf{h}_v^{(l)} + \mathbf{W}_{\text{nbr}} \cdot \frac{1}{|\mathcal{N}(v)|}\sum_{u \in \mathcal{N}(v)} \mathbf{h}_u^{(l)}\right).

Here Wself\mathbf{W}_{\text{self}} and Wnbr\mathbf{W}_{\text{nbr}} are learned weight matrices (see Matrix Multiplication), and σ\sigma is an activation such as ReLU. Each node gets its own features through one weight matrix and the average of its neighbours through another, then the two are added and bent by σ\sigma.

The matrix view

Stack all node vectors as rows of a matrix H(l)H^{(l)}. Use the sum aggregator with identity message and update functions, and suppose the graph's adjacency matrix is AA. Then one round is H(l+1)=(I+A) H(l)H^{(l+1)} = (I + A)\,H^{(l)}, where II is the identity. The II adds each node's own features. The AA adds its neighbours'.

Repeating LL rounds gives (I+A)L(I + A)^L. Entry (v,u)(v, u) of this matrix is positive exactly when uu is at most LL hops from vv. That is the receptive field of a node: the set of nodes whose input can affect its output after LL layers. The graph convolutional network uses the same matrix form, with a normalised version of AA and a learned weight matrix.

Pooling for graph-level outputs

For a whole-graph prediction, such as a molecule's property, the node vectors are combined by a readout:

hG=READOUT ⁣({hv(L):v∈V}).\mathbf{h}_G = \mathrm{READOUT}\!\left(\left\{\mathbf{h}_v^{(L)} : v \in V\right\}\right).

The readout must also be permutation-invariant, so the usual choices are sum, mean and max. The vector hG\mathbf{h}_G then goes into an ordinary classifier, usually ending in a Softmax and trained with Cross-Entropy Loss. The whole network, including every MSG\mathrm{MSG} and UPD\mathrm{UPD}, is trained end to end by Backpropagation.

Learned attention over neighbours

Instead of a fixed average, a graph attention network learns how much each neighbour should count. For node vv and neighbour uu, with W\mathbf{W} a learned matrix and a\mathbf{a} a learned vector,

evu=LeakyReLU ⁣(a⊤[Whv ∥ Whu]),αvu=exp⁡(evu)∑k∈N(v)∪{v}exp⁡(evk),hv(l+1)=σ ⁣(∑u∈N(v)∪{v}αvu Whu).e_{vu} = \mathrm{LeakyReLU}\!\left(\mathbf{a}^\top \left[\mathbf{W}\mathbf{h}_v \,\|\, \mathbf{W}\mathbf{h}_u\right]\right), \qquad \alpha_{vu} = \frac{\exp(e_{vu})}{\sum_{k \in \mathcal{N}(v) \cup \{v\}} \exp(e_{vk})}, \qquad \mathbf{h}_v^{(l+1)} = \sigma\!\left(\sum_{u \in \mathcal{N}(v) \cup \{v\}} \alpha_{vu}\, \mathbf{W}\mathbf{h}_u\right).

Here ∥\| means concatenation (writing two vectors one after the other), LeakyReLU is a ReLU that lets a small fraction of negative values through, and and αvu\alpha_{vu} are attention weights that sum to 1 over the neighbourhood. This is the same attention idea used in transformers, restricted to the edges of the graph.

Worked examples

Example
Tiny: sum aggregation on a path of three nodes

Take the path 1−2−31 - 2 - 3. Node 1 is joined only to node 2, node 2 to nodes 1 and 3, and node 3 only to node 2. The starting features are x1=1x_1 = 1, x2=2x_2 = 2, x3=3x_3 = 3. Use the sum rule: each node's new value is its own value plus the sum of its neighbours' values.

  1. Node 1 has neighbour 2, so h1′=1+2=3h_1' = 1 + 2 = 3.
  2. Node 2 has neighbours 1 and 3, so h2′=2+(1+3)=6h_2' = 2 + (1 + 3) = 6.
  3. Node 3 has neighbour 2, so h3′=3+2=5h_3' = 3 + 2 = 5.
  4. Second round, using the new values (3,6,5)(3, 6, 5): node 1 becomes 3+6=93 + 6 = 9, node 2 becomes 6+(3+5)=146 + (3 + 5) = 14, and node 3 becomes 5+6=115 + 6 = 11.

Interpretation: after one round, each node knows its direct neighbours. After two rounds, node 1 has a value of 9 that includes node 2's features after its first update, and node 2's first update included node 3. So node 1 has been influenced by node 3 even though they are not adjacent. In matrix form, the first round is (I+A)x(I+A)x and the second is (I+A)2x(I+A)^2 x, and the entry (1,3)(1, 3) of (I+A)2(I+A)^2 is 1, which is nonzero.

Example
Standard: one mean-aggregation layer and a graph readout

Use the same path 1−2−31 - 2 - 3 with scalar features x1=4x_1 = 4, x2=0x_2 = 0, x3=2x_3 = 2. Take Wself=0.5\mathbf{W}_{\text{self}} = 0.5, Wnbr=1\mathbf{W}_{\text{nbr}} = 1, and σ=ReLU\sigma = \mathrm{ReLU}. Each node is a single number, so the matrices are scalars.

  1. Node 1 has one neighbour, with feature 0. Its mean is 0, so h1=ReLU(0.5×4+1×0)=2h_1 = \mathrm{ReLU}(0.5 \times 4 + 1 \times 0) = 2.
  2. Node 2 has neighbours 1 and 3, with features 4 and 2. Their mean is (4+2)/2=3(4 + 2)/2 = 3. So h2=ReLU(0.5×0+1×3)=3h_2 = \mathrm{ReLU}(0.5 \times 0 + 1 \times 3) = 3.
  3. Node 3 has one neighbour, with feature 0. So h3=ReLU(0.5×2+1×0)=1h_3 = \mathrm{ReLU}(0.5 \times 2 + 1 \times 0) = 1.
  4. For a whole-graph value, take the mean of the node outputs: (2+3+1)/3=2(2 + 3 + 1)/3 = 2.

Interpretation: node 2, the middle of the path, ends up highest because it sees two neighbours with large features. The readout gives one number for the whole graph, and it does not change if the nodes are relabelled, because the mean does not depend on order.

Example
Realistic: why mean aggregation can miss a fraud ring

A payments graph has accounts as nodes, joined when they transact. A feature of 1 marks a neighbour already flagged as fraudulent, and 0 marks a clean neighbour. Three accounts look like this.

  • Account A has one neighbour, and it is flagged: the values are 11.
  • Account B has three neighbours, all flagged: the values are 1,1,11, 1, 1.
  • Account C has four neighbours, two of them flagged: the values are 1,1,0,01, 1, 0, 0.
  1. Mean aggregation: A gets 11, B gets 11, C gets (1+1+0+0)/4=0.5(1+1+0+0)/4 = 0.5.
  2. Sum aggregation: A gets 11, B gets 33, C gets 22.
  3. With mean, A and B look identical, even though B has three flagged contacts and A has one. The mean has thrown away the count.
  4. With sum, B's signal is three times A's, and C's is clearly between them.

Interpretation: the mean measures how contaminated a neighbourhood is, and the sum measures how much contamination there is. In a fraud setting, both matter. A practical fix is to keep the sum, or to concatenate the degree (the number of neighbours) to the mean. Sum has a cost too: on hub accounts with thousands of contacts, the sum can grow large, so it is often normalised or passed through a learned layer.

Tradeoffs and failure modes

A GNN is a good fit when the connections carry information. It is a poor fit when they do not, or when the answer depends on something far away in the graph.

SituationProblemBetter choice
Many layers on a well-connected graphNode vectors become nearly identical (over-smoothing)Fewer layers, or residual connections that keep each node's own signal
Information must cross a long path through a bottleneckDistant signals are squeezed through a few edges (over-squashing)Rewire extra edges, or use attention over more nodes
Mean aggregation with degree-sensitive labelsNodes with different neighbour counts look the sameSum aggregation, or add the degree as a feature
Very large graphsThe number of nodes within LL hops explodesSample a fixed number of neighbours per node (GraphSAGE style)
Neighbours tend to differ from the node (heterophily)Averaging over neighbours blurs the very contrast the task needsKeep the node's own features separate, or use attention to pick out useful neighbours
Answer depends on the whole graph at onceThe receptive field is only LL hopsGlobal readout or a model with global attention

Two failure modes deserve a closer look. Over-smoothing happens because each layer averages a node with its neighbours, and after enough rounds every node holds nearly the same average. Over-squashing happens because the receptive field grows with LL, but the information passes through fixed-size vectors, so a long chain of nodes must squeeze many signals into one. Both are reasons to keep GNNs shallow, which is why most practical models use two to four layers.

Also remember that message passing only sees the structure you give it. If the edges are wrong, such as a citation graph built from incomplete references, the model learns from the wrong neighbourhood without any warning.

History

Early work by Marco Gori, Gabriele Monfardini and Franco Scarselli in the mid-2000s set out a neural model that learns on graph-structured data. Scarselli and colleagues published the formal graph neural network model in 2009. Their model repeatedly updated node states until they settled, a different route from the fixed layers used today.

Interest grew in the mid-2010s as researchers defined convolution-like operations on graphs, first through the graph's Laplacian and then directly over neighbours. Gilmer and colleagues then unified many of these methods under the message-passing framework used in this lesson, and demonstrated it on predicting quantum-chemical properties of molecules in 2017. The same year, Hamilton, Ying and Leskovec introduced GraphSAGE, which made the approach scale to large graphs by sampling neighbours. Veličković and colleagues brought attention over neighbours in 2017 and 2018 with the graph attention network. Xu and colleagues showed in 2019 that sum aggregation with a suitable learned function can tell apart neighbourhoods that mean and max cannot, which explained why the choice of aggregator matters.

It caught on because most real data is relational. Molecules, social networks, road maps and transaction records are all graphs, and a model that respects their structure learns from fewer labels and generalises better than one that flattens the graph into a table.

Recap

A graph neural network turns a graph into node vectors by repeating a message-passing layer. Each layer gathers messages from neighbours with a permutation-invariant aggregator, combines them with the node's own features, and applies a learned function. After LL layers a node reflects its LL-hop neighbourhood, and a readout pools the node vectors for graph-level answers. The mean, sum and max aggregators differ in whether they keep a count of neighbours. Variants such as the graph convolutional network fix the aggregation to a normalised average, and graph attention learns the weights.

Check yourself

QuestionWhy must a GNN's aggregation function be permutation-invariant?Show answer

A node's neighbours form a set with no natural order, and the same graph can list them in any order. If the output depended on the order, the same graph would get different predictions depending on how it was stored. Sum, mean and max give the same answer for any ordering, so the layer depends only on which neighbours are present and their features.

QuestionUsing the path 1−2−31 - 2 - 3 with features 1,2,31, 2, 3 and the sum rule from the first worked example, what is node 3's value after two rounds?Show answer

After one round node 3 has value 5 and node 2 has value 6. In the second round node 3 takes its own value plus its neighbour's, so 5+6=115 + 6 = 11.

QuestionA task needs the two ends of a 30-node chain to influence each other's predictions. Why can a three-layer GNN not do this? Answer in terms of receptive fields.Show answer

A node with three layers sees only nodes within three hops. The two ends of a 30-node chain are 29 hops apart, so neither end's output can depend on the other's features. Adding layers widens the receptive field, but it also invites over-smoothing and over-squashing, so the usual remedy is a different structure or a global readout rather than simply stacking more layers.

QuestionA model for a social network predicts the same class for every node after twenty layers, and the node vectors are almost identical. Name the likely cause and two changes you would try.Show answer

The likely cause is over-smoothing: repeated averaging with neighbours has pushed all node vectors towards a common value. Two changes to try are reducing the number of layers, and adding residual connections so each node keeps its own features. Using a sum aggregator or adding degree features can also help if neighbour counts carry information.

Sources