26  Lesson 8: Multiple-Intance Learning, Deep Sets, and GNNs

Learning over (multi-)sets, sometimes using relationships.

Author

Noel Danz

26.1 Starting points and learning outcomes

You already know MLPs, gradients, minibatches, and binary cross-entropy from earlier weeks. From CNNs, retain the idea of shared operations at many locations. In this chapter, the locations no longer need to lie on a regular grid. New ideas are permutation-invariance, -equivariance, bag-level supervision, and message passing.

  • W08-01: Understand the concepts of permutation-invariance and -equivariance.
  • W08-02: Implement and explore different bag aggregations.
  • W08-03: Express computations over graphs as message, aggregation, and update operations.
  • W08-04: Explore expressivity in Multi-Instance Learning settings.

26.2 Motivating Task Examples

Before we start to dive into the material, let us consider the following data-task pairs:

    • Data: Patches extracted from a single image taken by a driving car. Each patch contains one already identified traffic-sign.
    • Task: Predict the currently active speed limit, given information on the last speed limit changing traffic sign encountered.
    • Data: A satellite image with a size much bigger than a GPUs memory, cut up into smaller patches.
    • Task: Identify if the satellite image contains a forest fire.
    • Data: A satellite image of a field, cut into smaller patches.
    • Task: Identify if at least 65% of the crop is ready for harvest.
    • Data: A satellite image of a city, cut into smaller patches.
    • Task: Identify if the area has at least 30% of greenery, but not above 80%, to identify “green” neighbourhoods without marking recreational parks or courts (soccer, tennis,…).
    • Data: A whole slide microscopy image, cut up into smaller patches.
    • Task: Identify if there is cancer present in the overall sample.
    • Data: Molecular Data describing the molecular makeup, structure and attributes of compounds.
    • Task: Identify which compounds are toxic w.r.t. which mechanisms of toxicity.
    • Data: Point cloud data collected from scanning 3D objects.
    • Task: Annotate each point cloud with the correct object label from a known set.
    • Data: Point cloud data collected by scanning the ground flying over with a plane.
    • Task: Segment sections of the cloud depending on type of the object (e.g., tree, house, road,…)
NoteYour Task

For each of the above example tasks, consider why it might be challenging to solve with the approaches we have encountered so far (Regression, MLPs, CNNs, UNets.)

How would you currently approach solving each of them?

26.3 Multi Instance Learning (MIL)

Several of these datasets are examples of multiple-instance learning (MIL) problems: a training example is a bag of instances, with one target for the bag. We observe that target in training, while the labels of individual instances, if there are any, are generally unknown. A bag may contain repeated feature vectors; mathematically, it is a multiset. We will often say “set” when referring to its lack of order, while usually retaining multiplicities.

In this section of the chapter we will build a common language for these types of problems and understand their unique assumptions about the data. We will then introduce the idea of permutation-invariance and permutation-equivariance, which we will make use of for the two approaches for solving MIL tasks we explore in depth.

If we constrain the task-description from above to binary-classification we can formulate MIL as: \[ \begin{aligned} B &= \{(x_1,y_1),...,(x_n,y_n)\} \\ c(B) &= 1-\prod_{i=1}^n{1-y_i} \end{aligned} \] which we will refer to as the “standard MI assumption”.

Notice that this assumes that a bag is considered to have class \(c=1\) if at least one instance \((x_i,y_i)\) is present that is of the positive class \(c=1\). Furthermore note that this formulation does not consider the order of the elements for the classification decision – this is central to MIL tasks.

Weidmann describes useful generalizations of the standard MI assumption in Two-Level Classification for Generalized Multi-Instance Data (2003). Each step allows a more general labeling rule: standard \(\subset\) presence-based \(\subset\) threshold-based \(\subset\) count-based.

Let \(C_R\) be the set of required instance classes, and let \(\#(B,c_i)\) denote how many instances in bag \(B\) belong to class \(c_i\). We allow an unbounded upper limit, \(u_i=\infty\), to recover a rule with only a lower bound.

Presence-based MIL is then formulated as \[ c(B) = 1 \iff \forall c_i\in C_R:\#(B,c_i)\geq 1, \]

threshold based MIL as \[ c(B) = 1 \iff \forall c_i\in C_R:\#(B,c_i)\geq l_i, \] with \(l_i\in L\) the set of associated lower-bounds on counts, and lastly count-based MIL as \[ c(B) = 1 \iff \forall c_i\in C_R:l_i \leq \#(B,c_i)\leq u_i, \] with \(u_i\in U\) the set of associated upper-bounds on counts.

NoteYour Task

Reconsider the introduced data-task pairs at the beginning of the chapter. Reflect on which type of MIL they represent.

Take note which ones are currently not well represented by the MIL types we introduced so far.

26.3.1 Permutation Invariance and Equivariance

One natural consequence of the structure of multiple instance learning is the need for invariance of the output under changing input ordering.

To illustrate this, let us construct bags of MNIST digit images and formulate some exploratory MIL problems using them:

X_train, y_train = load_mnist(train=True)
X_bags, y_bags = sample_bags(X_train, y_train, k=4, n_bags=1000, seed=42)

Each of our bags has cardinality \(k=4\) and is stored as a NumPy array of shape \((k,28,28)\), containing \(k\) (randomly selected) MNIST instances.

Assume that our first task is to decide if a bag contains at least one image showing the digit \(7\):

Three examples from BaggedMNIST, showing sets of digits. Sets (a),(b) are equal up to ordering. (c) differs.
(a) positive
Three examples from BaggedMNIST, showing sets of digits. Sets (a),(b) are equal up to ordering. (c) differs.
(b) positive
Three examples from BaggedMNIST, showing sets of digits. Sets (a),(b) are equal up to ordering. (c) differs.
(c) negative
Figure 26.1: Three examples from BaggedMNIST. (a),(b) are equal up to ordering. (c) differs.

in this case we would expect (a) and (b) to both have the positive label, even if the ordering of the instances has changed between the two. (c) is of the negative class accordingly, as it contains no 7-digit. Under out task, the two inputs (a),(b) are therefore identical, and our model should therefore produce the same prediction for both of them.

NoteYour Task

Consider the following questions:

  1. Does a standard MLP guarantee that it produces the same prediction for both (a) and (b)?
  2. What about a CNN, can it generally guarantee the same prediction for both (a) and (b)?

If yes: How would it do so?
If not: How can we ensure this behaviour in this task?

When considering the above questions, we might conclude that, no, MLPs and CNNs do not guarantee the same predictions for both (a) and (b) in the general case. Both MLPs and CNNs assume that their input is ordered, which, while true for our representation as a 3D-tensor, is not true for the underlying mathematical object it represents.

Notice that this is an example for the difference between representation of the data and structure of the data, with structure referring to the underlying attributes of the data itself.

We will consider reordering of instances as applying a permutation to some canonical representation (e.g., a sorted multiset of MNIST instances, or a arbitrarily but stable label identifying the instance): \[ \begin{aligned} X &= (x_1,...,x_n),\\ \pi X &= (x_{\pi(1)},..., x_{\pi(n)}) \end{aligned} \] where \(X\) is a bag, and \(\pi\in S_n\) refers to one such permutation.

NoteYour Task

If we now have any such set \(X\) and a permutation \(\pi\) the central question becomes:

How should a function \(f: X \mapsto \{0,1\}\) behave when we permute its input?

We will consider two particularly interesting answers:

  1. the output should not change at all
  2. the output should be permuted identically

If we have a function that does not change its output when the input is permuted we consider it to be permutation-invariant: \[ \forall \pi \in S_n: f(\pi X) = f(X) \]

Examples of permutation invariant functions are: \[ \begin{aligned} f(X) &= \sum_{i=1}^n{x_i}, \\ f(X) &= \frac{1}{n}\sum_{i=1}^n{x_i} \\ f(X) &= \max_{i=1,...,n}{x_i}, \end{aligned} \] which are the element-sum, mean, and max operators respectively.

Note that this is exactly the property we require for bag-level predictions in MIL problems.

If we have a function that changes its output according to the permutation of the input, we consider it to be permutation-equivariant: \[ f(\pi X) = \pi f(X) \]

You can think of this as if we would predict each MNIST instance in our bag individually, recording if it is in fact a digit \(7\). When we reorder the instances, we do not want the output vector to remain unchanged. Instead we want the predictions to be reordered accordingly.

The above idea in a more general form is also the example we would like to give \[ f(X) = (\phi(x_1),...\phi(x_n)), \] where for our example \(\phi\) might be an MLP or CNN.

Importantly, and slightly counterintuitively, equivariance does not imply that instances must be processed independently. For example, \[ f(X)_i = x_i - \frac{1}{n}\sum_{j=1}^n{x_j} \] is also permutation equivariant, despite every output depending on every input.

We encountered the same distinction in CNNs. A stride-one convolution on a regular grid is translation equivariant away from boundary effects. A shift in the input produces a corresponding shift in its feature map, and a global pooling operation can make the prediction invariant to that shift. Here we are asking what happens under an arbitrary permutation of the instances.

In Lab Exercise 1 we will test these properties numerically and consider an output whose rows and columns both follow the permutation. In the next section of this chapter we will find an answer to the question:

Can we construct a neural network that is permutation invariant by design, regardless of its learned parameters?

26.4 Deep Sets arxiv (NIPS 2017)

flowchart LR
    yh["$$\hat{y}$$"]
    agg["Aggregation $$\sum$$"]
    subgraph "Invariant"
        agg-->rho[$$\rho$$]
        rho-->yh
    end
    subgraph "Equivariant"
        x1[$$x_1$$] --> phi1[$$\phi$$] --> h1[$$h_1$$]-->agg
        x2[$$x_2$$] --> phi2[$$\phi$$] --> h2[$$h_2$$]-->agg
        x3["$$x_{...}$$"] --> phi3[$$\phi$$] --> h3["$$h_{...}$$"]-->agg
        xn[$$x_n$$] --> phin[$$\phi$$] --> hn[$$h_n$$]-->agg
    end
Figure 26.2: Diagram of a DeepSet architecture.

In Figure 26.2 we see the general structure of a DeepSet architecture. Notice that the structure can be composed into three distinct stages:

  1. Instance encoding: a shared, permutation equivariant transformation \(\phi\)
  2. Aggregation: a permutation invariant operation, such as summation.
  3. Bag prediction: a function \(\rho\) operating on the aggregated representation.

Translating this into a functional formulation directly leads to the DeepSet architecture: \[ f(X) = \rho(\bigoplus_{x\in X}{\phi(x)}), \] with \(\oplus\) referring to any permutation invariant operation such as element-sum. Since every instance uses the same \(\phi\), reordering the \(x_i\) simply reorders the encoded vectors. The aggregation gives the same input to \(\rho\) in either order.

Let us explore the choices for aggregation functions in a bit more detail here. Consider the three multisets: \[ X_1 = \{1,2\}, X_2 = \{1,1,2,2\}, X_3 = \{2,2\}, \]

Applying the three aggregation functions from Section 26.3.1:

Aggregation \(X_1\) \(X_2\) \(X_3\)
Sum 3 6 4
Mean 1.5 1.5 2
Max 2 2 2
NoteYour Task

Consider in which situations the three pooling operations fail to differentiate between multisets.

NoteYour Task

Consider the tasks from the introduction of the chapter. Which different abstract tasks can we identify? Which aggregation would be the most natural for solving the task?

Let us assume for the moment that \(\phi\) can identify the relevant instance classes, for example by assigning a separate feature to each digit.

What the task asks for A natural aggregation
Is at least one instance of a class present? Max over the feature for that class
Are several required classes present? Max separately for each class, followed by a predictor that combines the features
How many instances of a class are present? Sum of the corresponding indicators
What fraction of instances belong to a class? Mean of the corresponding indicators
Is a count within lower and upper bounds? Sum, followed by a predictor that checks both bounds

If every bag has the same size, sum and mean differ by a constant factor. With varying bag sizes, duplicating every instance doubles the sum and leaves the mean and max unchanged. Which of these properties would you want for the crop or greenery example? We will use this duplication test in Lab Exercise 2.

We can also distinguish MIL models by what they aggregate.

  • Instance-based MIL. Predict a scalar score for each instance, then pool the scores. For the standard MI assumption, a max makes the highest-scoring instance determine the bag score.
  • Embedding-based MIL. Encode each instance as a vector \(h_i\), pool the vectors, then predict from the pooled representation. The Deep Sets model in Figure 26.2 follows this pattern.
  • Attention-based MIL. Learn how to weight the instance embeddings before pooling. One option is to score each embedding with the same function \(s\), then form \[ a_i = \frac{\exp(s(h_i))}{\sum_{j=1}^n \exp(s(h_j))}, \qquad z = \sum_{i=1}^n a_i h_i, \qquad \hat y = \rho(z). \] If we permute the instances, each weight moves with its embedding and \(z\) stays the same. Even in a negative bag the weights sum to one, so an instance can receive a large weight without being a positive instance. The bag label supervises \(\hat y\) alone.

The attention formulation above is one form of embedding-based MIL, with learned weights in its pooling operation. In the optional attention exercise, we will see how padding affects those weights. Ilse, Tomczak & Welling (2018)

The central insight from this is that we are no longer hoping that the network becomes independent of the input order in training, we are encoding the symmetry of the problem into the architecture itself.

One nice additional property of this architecture is that the bags of instances can be of varying cardinality, without changes to the network.

When we batch bags of different sizes into one tensor, we can pad each bag up to the longest one in the batch. We then need a mask indicating which entries belong to the bag. Padding can affect every pooling rule. Even an all-zero input can produce a nonzero embedding when \(\phi\) has a bias term. Therefore the mask should be applied in the aggregation step.

NoteYour Task

Consider the tasks from the introduction again and note which task requires which property, reasoning through why some need invariance, and others equivariance.

Additionally consider which of the tasks could still be difficult to reliably solve and why.

26.4.1 Minimal Implementation

Let us return to our bags of digit images. The input has shape \((\text{batch}, \text{instances}, 28, 28)\). We first flatten each image and use the same \(\phi\) to encode it. The pooling operation removes the instance dimension, and \(\rho\) returns one logit per bag.

import torch
from torch import nn

class DeepSets(nn.Module):
    def __init__(self, phi, rho, pooling="sum"):
        super().__init__()
        self.phi = phi
        self.rho = rho
        self.pooling = pooling

    def forward(self, x, mask):
        # x: (batch, instances, height, width); mask: (batch, instances)
        h = self.phi(x.flatten(start_dim=2))
        valid = mask.unsqueeze(-1)

        if self.pooling == "max":
            pooled = h.masked_fill(~valid, -torch.inf).amax(dim=1)
        elif self.pooling in ("sum", "mean"):
            pooled = h.masked_fill(~valid, 0).sum(dim=1)
            if self.pooling == "mean":
                pooled = pooled / mask.sum(dim=1, keepdim=True)
        else:
            raise ValueError(f"Unknown pooling: {self.pooling}")

        return self.rho(pooled).squeeze(-1)

Here we assume that every bag has at least one valid instance. Sum uses zero for a masked entry, mean divides by the number of valid entries, and max uses \(-\infty\) so that a padded entry cannot outscore a real one.

x = torch.as_tensor(X_bags[np.newaxis, 0,:,:], dtype=torch.float32) # a positive bag
x = torch.cat((x, torch.zeros_like(x[:, :1])), dim=1)
mask = torch.tensor([[True, True, True, True, False]])
p = torch.tensor([4, 2, 0, 3, 1])

torch.manual_seed(8)
phi = nn.Sequential(nn.Linear(28 * 28, 16), nn.ReLU())
rho = nn.Linear(16, 1)

for pooling in ("sum", "mean", "max"):
    model = DeepSets(phi, rho, pooling)
    with torch.no_grad():
        torch.testing.assert_close(
            model(x, mask), model(x[:, p], mask[:, p])
        )
        torch.testing.assert_close(
            model(x, mask), model(x[:, :4], mask[:, :4])
        )

We can check both properties before training the network. In Lab>Exercise 2 we will use this structure with different bag-labeling rules, then see what changes when the test bags are larger than any of the training bags.

26.4.2 On the expressivity of DeepSets

Recall that we can process an arbitrary number of instances, learn representations of individual instances and make permutation invariant predictions.

Let us consider the following situation, you want to optimize a network such that it can represent molecules and predict some attribute about them.

As an example we will compare what any DeepSet Model would predict for two specific molecules: ethanol and dimethyl ether.

Ethanol C1 C C2 C C1--C2 H1 H C1--H1 H2 H C1--H2 H3 H C1--H3 O O C2--O H4 H C2--H4 H5 H C2--H5 H6 H O--H6
(a) Ethanol (CH3-CH2-OH)
DimethylEther C1 C O O C1--O H1 H C1--H1 H2 H C1--H2 H3 H C1--H3 C2 C C2--O H4 H C2--H4 H5 H C2--H5 H6 H C2--H6
(b) Dimethylether (CH3-O-CH3)
Figure 26.3: The two molecules serving as our example.

If we represent our molecules from Figure 26.3 as bags of atoms we obtain representations:

Ethanol:        C,C,O,H,H,H,H,H,H
Dimethyl ether: C,C,O,H,H,H,H,H,H

Applying the same DeepSet model to both of them we get: \[ y = \rho(2\phi(C) + \phi(O) + 6\phi(H)) \]

which is an identical output for both molecules, even though they have fundamentally different chemical and physical properties.

The problem here is not the expressivity of our DeepSet model, but the information contained in our representation:

We know shich atoms are present, but not how they are connected.

We can make the link to atom counts more precise. Let \(n_Z\) count atoms with atomic number \(Z\). If this is the only feature that \(\phi\) sees, then \[ \sum_{i\in V} \phi(Z_i) = \sum_Z n_Z\,\phi(Z). \] Learning \(\phi\) amounts to learning a linear transformation of the atom histogram before applying \(\rho\). Choosing \(\phi\) to be a one-hot encoding recovers the histogram itself. Learned embeddings may change how easily we fit a predictor, but they cannot distinguish two molecules with the same histogram. Adding atom features such as the number of attached hydrogens gives the model different inputs. The question then becomes which relationships we want to supply directly. We will compare these representations in Lab Exercise 3.

26.5 Graph Neural Networks (GNNs)

So far, we have represented our inputs as collections of objects: \[ X = \{x_1,...,x_n\} \] We now extend this representation by introducing relationships between objects.

\[ G = (V,E); V = \{1,..,n\}; E \subseteq V \times V \]

Each Node \(v \in V\) has an associated feature vector \(x_v \in \mathbb{R}^d\). Optionally, each edge \((u,v)\in E\) can have an associated feature vector \(e_{uv} \in \mathbb{R}^m\), as well as each graph \(g\in \mathbb{R}^k\).

Some definitions:

  1. The adjacency matrix \(A\in \{0, 1\}^{n \times n}\) denotes which nodes have a connection between them.
  2. The Neighborhood \(\mathcal{N}(i) = \{j: (i,j)\in E\}\), returns the set of nodes \(\{j_1,..., j_m\}\) connected to node \(i\).
  3. If \(\forall u,v \in V: (u,v)\in E \implies (v,u)\in E\), we consider the graph to be undirected, otherwise the graph is directed.

Graphs, just like sets, do not have an intrinsic ordering of their nodes. However, when we permute the nodes, we must also permute their relationships. Given a node feature matrix \(X\in \mathbb{R}^{n \times d}\), an adjacency matrix \(A \in \mathbb{R}^{n\times n}\) and a permutation matrix \(P\), we obtain: \[ X' = PX; A' = PAP^\top. \]

We can also think of this as relabeling the nodes of the graph, without changing the underlying described structure.

With this notion in mind we can extend our definitions of permutation-invariance and permutation-equivariance to graphs as well: \[ \begin{aligned} f(PX, PAP^\top) = f(X,A) \\ f(PX, PAP^\top) = Pf(X,A) \end{aligned} \] Where invariance would be required for graph-level predictions, while equivariance would be required for node-level predictions.

In DeepSets, we aggregate information across the entire set, producing a global representation. Suppose we no want to update each instance using information from the entire set instead: \[ h_i = \psi(x_i, \sum_{j=1}^n{\phi(x_j)}) \] This function would be a permutation equivariant set-to-set transformation. Each instance “receives information” about the entire collection while retaining its own identity.

But with graphs we are not necessarily interested in sharing information between all set members equally, instead we would like the information sharing to be restricted to instances that are directly related to each other – by aggregating over the neighborhood of each node: \[ h_i = \psi(x_i, \sum_{j\in \mathcal{N}(i)}{\phi(x_j)}) \]

What we have constructed now is a simple graph neural network layer.

The key insight to note is that each node applies a DeepSet like aggregation to its immediate neighborhood.

The neighborhood is an unordered collection of instances and from DeepSets we already know how to process these in an permutation invariant manner. The key insight also explains why GNNs can operate on grpahs of varying size and nodes with varying amounts of neighbors.

26.5.1 Message Passing Networks (MPNNs)

Many graph neural network architectures can be understood in the message passing framework, in which each layer \(\ell\) performs three operations.

  1. Message Construction \[ m_{ij} = \phi(h_i, h_j, e_{ij}) \]
  2. Message Aggregation \[ m_i = \bigoplus_{j\in \mathcal{N}(i)}{m_{ij}} \]
  3. Node Update \[ h_i^{(\ell+1)} = \psi(h_i, m_i) \]
flowchart LR
    subgraph nd1["Node Update"]
        direction TB
        h(($$h_i$$))
        psi($$\psi$$)
        hp(($$h_i'$$))
    end

    agg($$\bigoplus$$)
    j1(($$j_1$$))
    phi1($$\phi$$)
    j2(("$$j_{...}$$"))
    phi2($$\phi$$)
    jn(($$j_n$$))
    phin($$\phi$$)
    

    j1-->phi1-->agg
    j2-->phi2-->agg
    jn-->phin-->agg

    agg--"to $$\ \psi$$"-->nd1
    h-->psi
    psi-->hp
Figure 26.4: Schematic architecture of a Graph Neural Network.

Here \(m_{ij}\) is the message received by \(i\) from \(j\), and \(e_{ji}\) is the feature of the edge from \(j\) to \(i\). All messages in one layer use the representations from the start of that layer. If we relabel the graph, the messages arriving at a node move with its incident edges. Shared message and update functions and the permutation invariant aggregation therefore make the layer permutation equivariant.

26.5.2 A worked numerical example.

G a 1 b 2 a--b c 3 b--c d 4 c--d
Figure 26.5: Simple Graph for Numerical Example.

Consider the graph of a path \(1-2-3-4\) with scalar node features \(h^{(0)}=(1,2,3,4)^\top\) (see Figure 26.5). We will use the simplest message we can send, the sender’s feature itself: \[ m_{ij}=h_j, \qquad m_i=\sum_{j\in\mathcal N(i)}m_{ij}, \qquad h_i'=h_i+m_i. \]

Node \(i\) Old feature \(h_i\) Incoming messages Sum \(m_i\) New feature \(h_i'\)
1 1 2 from node 2 2 3
2 2 1 from node 1, 3 from node 3 4 6
3 3 2 from node 2, 4 from node 4 6 9
4 4 3 from node 3 3 7

When we update node 2, the message from node 1 is \(1\). Node 1’s updated value of \(3\) is first available in the next layer. If we reverse the enumeration to \((4,3,2,1)\) and relabel the edges accordingly, the output becomes \((7,9,6,3)^\top\).

NoteYour Task

Compute the second layer by hand. Which input features can now affect the representation of node 1? What would change if we updated nodes in place as we visited them?

You will implement this aggregation and test it under relabeling in Lab Exercise 4.

The pooling step is the one we already know from Deep Sets. The difference is where we apply it and what we do with the result.

Step Deep Sets Message passing
Transform Encode each instance Construct a message for each incoming edge
Aggregate Pool over the entire bag Pool over one node’s neighbors
Update Predict from the bag representation Combine the aggregate with the node’s current representation

A single Deep Sets aggregation produces one representation per bag. A message-passing layer carries out the local aggregation for every node and produces one representation per node.

26.5.2.1 Stacking layers

Just as in a CNN, stacking layers increases the receptive field. After one layer, node 1 in our path can use node 2’s feature. After two layers, node 2 can pass information about node 3 to node 1. Generally after \(L\) local layers, a node can depend on features at most \(L\) edges away.

What happens if we repeatedly average each node with its neighbors? We can try this on the same path, after adding self-loops so that each node includes its own feature in the average.

A = np.array([[0, 1, 0, 0],
              [1, 0, 1, 0],
              [0, 1, 0, 1],
              [0, 0, 1, 0]], dtype=float)
A_self = A + np.eye(len(A))
average = A_self / A_self.sum(axis=1, keepdims=True)
h = np.arange(1, 5, dtype=float)
variances = [h.var()]

for _ in range(20):
    h = average @ h
    variances.append(h.var())

fig, ax = plt.subplots(figsize=(5,2.5))
ax.plot(variances)
ax.set_xlabel("Layer")
ax.set_ylabel("Variance across nodes")
plt.show()

Variance across Nodes vs. Model Depth. Variance decreases with depth.

The receptive field grows, but the node values approach one another. This illustrates a common problem in GNNs: oversmoothing, where repeated mixing makes node representations hard to distinguish. Layer depth lets information travel farther. How much of it remains usable depends on the updates. In the optional lab extension, you will change the strength of each averaging step.

26.5.2.2 From node representations to a graph prediction

Suppose our task is to predict one property of the whole molecule. After message passing we have a bag of node embeddings. We can apply an invariant pooling operation to that bag, just as in Figure 26.2: \[ h_i^{(0)}=x_i, \qquad h_i^{(\ell+1)}=\operatorname{MPNN}_{\ell}(h^{(\ell)},G)_i, \qquad \hat y=\rho\left(\bigoplus_{i\in V} h_i^{(L)}\right). \]

Relabeling the graph permutes the node embeddings, so the final pooling step gives the same prediction. With no messages between distinct nodes, the node transformations reduce to a shared function of \(x_i\) and we recover exactly the DeepSets pattern. For a node-level task, such as segmenting a point cloud, we can instead apply a shared prediction head to each \(h_i^{(L)}\).

26.5.2.3 Choices for messages, aggregation, and updates

Let us compare a few ways to define the three operations. We omit layer indices on the right-hand side.

Layer What is aggregated? How is the node updated?
GIN Sum of neighbor embeddings \(h_j\) Add \((1+\epsilon)h_i\) to the sum and apply an MLP
GCN Sum over neighbors and the node itself, with weights \(1/\sqrt{\tilde d_i\tilde d_j}\), where \(\tilde d_i\) includes the self-loop Apply a shared linear map and a nonlinearity
GraphSAGE (mean) Mean over neighbors, which may be sampled Concatenate the mean with \(h_i\), then apply a shared linear map and a nonlinearity
GINE Sum of \(\operatorname{ReLU}(h_j + b(e_{ji}))\), where \(b\) encodes the bond in the same feature space as \(h_j\) Use the GIN update on that sum

The worked numerical example uses the aggregation of GIN with \(\epsilon=0\) and an identity in place of the MLP. GINE lets two neighbors with identical node features send different messages if the edges information differ. As further reading, Graph Attention Networks learn how to weight the messages within each neighborhood, using a softmax over the neighbors of the receiving node.

26.5.2.4 On the expressivity of message passing

Consider a cycle of six nodes and two disconnected triangles: \[ 1-2-3-4-5-6-1 \qquad\text{and}\qquad (1-2-3-1),\ (4-5-6-4). \]

Can a standard local message-passing network distinguish them if every node starts with the same features and all edges have identical features? At the first layer, each node receives two identical messages. Every node therefore gets the same updated embedding, in both graphs. The same argument applies again at every layer. A graph readout receives six copies of the same embedding for either graph and gives the same result.

This is an example of the limitation captured by the 1-dimensional Weisfeiler–Leman (1-WL) test, which also updates node descriptions from multisets of neighboring descriptions. Adding a feature such as the number of triangles through each node changes the input to message passing. Try both cases in the optional lab extension.

26.6 Ablation Experiments

Model Atomic number Rich atom features Connectivity Bond features
1. Atom histogram + MLP ✓
2. DeepSets ✓
3. DeepSets (rich) ✓ ✓
4. GIN ✓ ✓
5. GIN (rich) ✓ ✓ ✓
6. GINE (rich) ✓ ✓ ✓ ✓

The ablation changes one part of an experimental setup to investigate what it contributes. Each row in the table above specifies what the model can use. Let us turn some pairs of rows into concrete research questions.

Comparison Question
1 → 2 Does learning atom embeddings help us fit a predictor from atom counts?
2 → 3 What do additional atom features contribute to a set model?
2 → 4 What happens when we use connectivity with atomic number as the only initial node feature?
3 → 5 What does explicit connectivity add when the atom features already include quantities derived from bonds, such as degree?
4 → 5 What do richer atom features contribute to a model that also sees connectivity?
5 → 6 Does using bond attributes in the messages improve prediction?

In Lab Exercise 5, we will make these comparisons on one target with fixed training, validation, and test sets. Keep the training budget and evaluation procedure comparable, and record parameter counts. If a comparison changes the message function or model capacity along with its inputs, consider those changes when interpreting the result.

26.7 What have we learned to preserve?

Problem Unit of prediction Structure to preserve
Set or bag classification One label per collection Invariance to instance enumeration, plus task-relevant multiplicity
Instance or node prediction One output per object Equivariance: outputs follow their objects
Graph classification One label per graph Invariance to joint relabeling of features and edges

Keep data, architecture, objective, and evaluation separate. MIL describes where supervision is available. Deep Sets describes a way to respect unordered inputs. Message passing describes how representations use relationships. A graph-level classifier may still have only one label for the whole graph.

For a real slide dataset, split at the independent patient or case level before fitting encoders or pooling models, and keep related slides together. Splitting tiles from one case across training and validation would not estimate generalization to new cases. Site and acquisition shifts require their own evaluation design; neither invariance nor attention removes those shifts automatically.

26.7.1 Knowledge check

  1. Which output should remain identical after a shuffle, and which should follow the shuffle?
  2. What information does mean pooling lose when every instance is duplicated?
  3. Why does one bag label not provide instance labels?
  4. Why can attention assign high weight to an instance in a negative bag?
  5. What must move when graph nodes are relabeled?
  6. Why is node variance a useful diagnostic for repeated averaging but not a complete measure of GNN quality?