27  Lab 8: Multiple-Instance Learning, Deep Sets, and GNNs

From bags of digits to graphs of molecules.

Author

Noel Danz

Keep the concepts chapter open. In that chapter we asked which changes to an input should change its prediction. Here we will turn that question into tests, then use those tests when we build models. Predict the result of each comparison before running it.

Exercise Approx. time
1. Investigate permutations 15 min
2. Pool bags of digits 45 min
3. Go from bags to graphs 20 min
4. Implement message passing 40 min
5. Compare molecular predictors 60 min
6. Explore depth and expressivity (optional) 30 min

27.1 Setup

Run the Python blocks in order in a notebook. Complete the functions marked Your Task before running the blocks that use them. The chapter and lab can be run independently. The lab uses NumPy, Matplotlib, and PyTorch and is sized for CPU.

  • Digits. Save mnist.npz next to your notebook and set USE_MNIST = True. The same file can be used in the concepts chapter.
  • Molecules. Download Open Graph Benchmark’s preprocessed Tox21 archive. Unzip it next to your notebook so that tox21/raw/ and tox21/split/scaffold/ are available. Leave the individual CSV files compressed and set USE_TOX21 = True.

Both switches default to the offline examples. The digit substitute is a set of noisy schematic digit images. The graph substitute is a set of labeled paths with synthetic node and edge attributes. Use it to debug and explore the ablation if you do not have the archive. Report which data you used with your results.

import numpy as np
import matplotlib.pyplot as plt
import torch
from torch import nn

USE_MNIST = False
USE_TOX21 = False
torch.set_num_threads(2)

27.2 Investigate permutations

Recall the definitions of permutation invariance and equivariance. Here the rows of x enumerate the instances in a bag and the columns enumerate their features. A permutation p gives the old row index at each new row position, so x[p] permutes the instances.

rng = torch.Generator().manual_seed(8)
x = torch.randn(6, 3, generator=rng)
W = torch.randn(3, 4, generator=rng)
functions = {
    "sum": lambda x: x.sum(dim=0),
    "center": lambda x: x - x.mean(dim=0),
    "first": lambda x: x[0],
    "linear": lambda x: x @ W,
    "cumulative sum": lambda x: x.cumsum(dim=0),
    "pairwise inner products": lambda x: x @ x.T,
}
def check_invariance(f,x,p):
    pass

def check_row_equivariance(f,x,p):
    pass

27.2.1 Your Task

  1. For each function, predict what happens to its output under a permutation of the rows.
  2. Implement check_invariance(f, x, p) and check_row_equivariance(f, x, p) using torch.allclose. The row-equivariance check applies when the output has one row per instance. Test several permutations and two different input tensors. Find a counterexample for one of the functions that depends on order.
  3. Inspect x @ x.T. What do its two axes index? Work out how both axes should change and implement a check for this behavior. Try applying the same change to an adjacency matrix in Exercise 3.
  4. Can the same row-valued function be both invariant and equivariant? Give an example or explain why you think this cannot happen. What can a failing test tell you that a passing test cannot?

27.3 Pool bags of digits

We will use four rules to label bags of digit images. The image labels let us construct the bags and inspect them later. During training the model receives images, the padding mask, and the bag label.

Rule Give the bag label 1 if…
Standard It contains at least one 7.
Presence-based It contains at least one 7 and at least one 9.
Threshold-based It contains at least three 7s.
Count-based It contains either two or three 7s.
def bag_label(digits, rule="standard"):
    if rule == "standard":
        pass
    else:
        pass
    return 0

27.3.1 Your Task

Implement bag_label(digits, rule) for a one-dimensional array of digit labels. Use rule names "standard", "presence", "threshold", and "count". Make a table of the four labels for the bag [7, 1, 7, 9], then check that your function agrees. What happens to those labels if you duplicate every instance in the bag?

27.3.2 Provided data and training code

The data helper draws the same number of bags in each class at each bag size. It samples images without replacement within each bag and uses disjoint image pools for training, validation, and testing. This amounts to a controlled experiment where bag size alone does not predict the class.

def schematic_digits(seed, per_digit):
    segments = [
        np.s_[3:6, 8:20], np.s_[5:14, 19:22], np.s_[14:23, 19:22],
        np.s_[22:25, 8:20], np.s_[14:23, 6:9], np.s_[5:14, 6:9],
        np.s_[12:15, 8:20],
    ]
    patterns = ("abcdef", "bc", "abdeg", "abcdg", "bcfg",
                "acdfg", "acdefg", "abc", "abcdefg", "abcdfg")
    templates = np.zeros((10, 28, 28), dtype=np.float32)
    for digit, pattern in enumerate(patterns):
        for segment in pattern:
            templates[digit][segments[ord(segment) - ord("a")]] = 0.85
    labels = np.repeat(np.arange(10), per_digit)
    rng = np.random.default_rng(seed)
    images = templates[labels] + rng.normal(0, 0.14, (len(labels), 28, 28))
    return images.clip(0, 1).astype(np.float32), labels

def digit_splits(use_mnist):
    if use_mnist:
        with np.load("mnist.npz") as mnist:
            images, labels = mnist["x_train"], mnist["y_train"]
            test = (mnist["x_test"], mnist["y_test"])
        order = np.random.default_rng(8).permutation(len(labels))
        train, valid = order[5000:], order[:5000]
        return (images[train], labels[train]), (images[valid], labels[valid]), test
    return tuple(schematic_digits(seed, 250) for seed in (8, 9, 10))

def make_bags(split, rule, sizes, per_class, seed):
    images, digits = split
    rng = np.random.default_rng(seed)
    examples = []

    for size in sizes:
        counts = [0, 0]
        max_attempts = 1000 * per_class

        for _ in range(max_attempts):
            if min(counts) >= per_class:
                break

            ids = rng.choice(len(digits), size=size, replace=False)
            label = int(bag_label(digits[ids], rule))

            if counts[label] < per_class:
                bag = torch.as_tensor(images[ids], dtype=torch.float32)

                if images.dtype == np.uint8:
                    bag = bag / 255

                examples.append((bag, float(label)))
                counts[label] += 1

        if min(counts) < per_class:
            raise RuntimeError(
                f"Could not generate balanced bags for "
                f"rule={rule}, size={size}. "
                f"Generated class counts: {counts}. "
                f"Check your implementation of bag_label()."
            )

    return examples

def collate_bags(examples):
    bags, labels = zip(*examples)
    lengths = torch.tensor([len(bag) for bag in bags])
    x = nn.utils.rnn.pad_sequence(bags, batch_first=True)
    mask = torch.arange(x.shape[1])[None, :] < lengths[:, None]
    return (x, mask), torch.tensor(labels, dtype=torch.float32)

def make_loader(examples, collate, shuffle=False, seed=8):
    return torch.utils.data.DataLoader(
        examples, batch_size=32, shuffle=shuffle, collate_fn=collate,
        generator=torch.Generator().manual_seed(seed),
    )

@torch.no_grad()
def predict(model, loader):
    model.eval()
    scores, targets = [], []
    for inputs, y in loader:
        scores.append(model(*inputs))
        targets.append(y)
    return torch.cat(scores), torch.cat(targets)

def fit(model, train_loader, valid_loader, epochs, lr=0.002):
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)
    loss_fn = nn.BCEWithLogitsLoss()
    best_loss = float("inf")
    best_state = None
    for _ in range(epochs):
        model.train()
        for inputs, y in train_loader:
            optimizer.zero_grad()
            loss = loss_fn(model(*inputs), y)
            loss.backward()
            optimizer.step()
        scores, targets = predict(model, valid_loader)
        valid_loss = loss_fn(scores, targets).item()
        if valid_loss < best_loss:
            best_loss = valid_loss
            best_state = {name: value.detach().clone()
                          for name, value in model.state_dict().items()}
    model.load_state_dict(best_state)
    return model

def make_digit_encoder():
    return nn.Sequential(
        nn.Conv2d(1, 8, kernel_size=5, stride=2), nn.ReLU(),
        nn.MaxPool2d(2), nn.Flatten(), nn.Linear(8 * 6 * 6, 16), nn.ReLU(),
    )

digit_train, digit_valid, digit_test = digit_splits(USE_MNIST)

27.3.3 Your Task

Complete the model below. Reshape the tensor so the CNN sees batch * instances grayscale images, then restore the bag axis before pooling. The model should output one logit per bag. The chapter implementation has the same pooling step with a different encoder.

class DigitDeepSets(nn.Module):
    def __init__(self, pooling):
        super().__init__()
        self.encoder = make_digit_encoder()
        self.predictor = nn.Sequential(nn.Linear(16, 16), nn.ReLU(), nn.Linear(16, 1))
        self.pooling = pooling

    def forward(self, x, mask):
        # x: (batch, instances, height, width); mask: (batch, instances)
        raise NotImplementedError("Encode instances, pool the valid entries, and predict.")

Exploration:

  1. Test a batch of two bags with different lengths. Permute the image slots and their masks together. Then change the values in the padded slots. Check both perturbations with all three pooling rules. Why would merely padding with zeros sometimes produce the wrong result?
  2. Predict which pooling rules could represent each of the four labels if the digit encoder were perfect. Use bags of different sizes. Construct two bags that have different labels under the count-based rule and that mean and max pooling would be unable to distinguish, regardless of the instance encoder.
  3. Run the comparison below for the standard and count-based tasks with sum, mean, and max. Start with a short run to check the code. For a longer run, fix the training budget before looking at the test results. The presence and threshold rules are optional additional comparisons.
  4. Compare accuracy on test bags within the training size range and on larger test bags. Separately, duplicate every instance in a single test bag and inspect the pooled representation and bag logit before and after duplication. Compare with your earlier calculation of the true labels.
def accuracy(model, loader):
    scores, y = predict(model, loader)
    return ((scores >= 0) == y.bool()).float().mean().item()

def compare_digit_pooling(rule, epochs=8):
    train = make_bags(digit_train, rule, range(4, 9), per_class=60, seed=20)
    valid = make_bags(digit_valid, rule, range(4, 9), per_class=20, seed=21)
    same = make_bags(digit_test, rule, range(4, 9), per_class=20, seed=22)
    larger = make_bags(digit_test, rule, range(9, 17), per_class=15, seed=23)
    for pooling in ("sum", "mean", "max"):
        torch.manual_seed(8)
        model = fit(
            DigitDeepSets(pooling),
            make_loader(train, collate_bags, shuffle=True),
            make_loader(valid, collate_bags),
            epochs=epochs,
        )
        print(rule, pooling, round(accuracy(model, make_loader(same, collate_bags)), 3),
              round(accuracy(model, make_loader(larger, collate_bags)), 3))

for rule in ("standard", "count"):
    compare_digit_pooling(rule)
NoteAsk yourself

Sum can preserve a count in the pooled representation. Does that guarantee that the trained predictor will extrapolate to the larger range? Use your observations to explain the difference between what a pooling operation can preserve and what a trained network actually uses.

27.3.4 Try attention pooling (optional)

Give each embedding one score using a shared nn.Linear(16, 1). Set the scores of padded entries to \(-\infty\) before applying softmax over instances. Replace the sum, mean, or max in your model with the weighted sum. Check that permuting the instances also permutes their weights, and that the bag representation stays the same. What happens to the representation when you duplicate every instance, and which of the four rules would this make difficult to learn?

27.4 Go from bags to graphs

Recall the ethanol and dimethyl ether example from the concepts chapter. Here we will use only the heavy atoms as graph nodes. For both molecules we use the same ordering [C, C, O]. The column for attached hydrogens, when supplied, counts the hydrogens we omit as explicit nodes.

def directed_edges(bonds):
    # One input pair per undirected bond. 
    # Return a source and destination row.
    pairs = torch.as_tensor(bonds, dtype=torch.long).reshape(-1, 2).T
    return torch.cat((pairs, pairs.flip(0)), dim=1)

z = torch.tensor([6, 6, 8])
ethanol_edges = directed_edges([(0, 1), (1, 2)])
ether_edges = directed_edges([(0, 2), (1, 2)])
attached_h_ethanol = torch.tensor([3, 2, 1])
attached_h_ether = torch.tensor([3, 3, 0])

27.4.1 Your Task

  1. Compute an atom histogram and a bag of node feature vectors for each molecule. Compare first using just atomic number, then after including the attached-hydrogen count. In which representation can you identify the neighbors of an atom?
  2. Implement permute_graph(x, edge_index, p) returning the permuted features and edge list. As in Exercise 1, new row i corresponds to old row p[i]. Which map must you use to change an old endpoint into its new index? Try a permutation of three nodes that differs from its inverse.
  3. Construct each adjacency matrix with A[dst, src] = 1. Verify that the reordered graph has adjacency A[p][:, p] and that its degree vector follows p. If edge attributes are stored in the same order as edge columns, what should happen to them when you relabel the endpoints? What if you also reorder the edge columns?

27.5 Implement message passing

Use the worked example to check your implementation. Each edge column contains a sender and a receiver. We use two columns per undirected edge and leave out self-loops for this exercise.

h_path = torch.arange(1, 5, dtype=torch.float32).unsqueeze(1)
path_edges = directed_edges([(0, 1), (1, 2), (2, 3)])

def aggregate_sum(h, edge_index):
    # Return one row per node, including nodes with no incoming messages.
    raise NotImplementedError("Sum the incoming node features.")
  1. Implement aggregate_sum. Start by gathering the sender’s embedding for each edge. You can use a loop to check your reasoning, then replace the loop with index_add_. Its three arguments are the dimension to add along, the destination indices, and the tensor of messages. Check the aggregate for the path and for a graph with an isolated node or no edges.
  2. Complete SimpleGIN below, with fixed \(\epsilon=0\). Where is the current node embedding added? Why would adding it again through a self-loop change the result?
  3. Test the layer using permute_graph. Check that the node embeddings follow the permutation. Then sum those embeddings and check that the graph representation is unchanged. Try separately reordering the edge columns.
def mlp(in_dim, out_dim, hidden=32):
    return nn.Sequential(nn.Linear(in_dim, hidden), nn.ReLU(), nn.Linear(hidden, out_dim))

class SimpleGIN(nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.update = mlp(dim, dim)

    def forward(self, h, edge_index):
        raise NotImplementedError("Combine self features with incoming messages.")

layer = SimpleGIN(dim=1)
p = torch.tensor([2, 0, 3, 1])
h_perm, edges_perm = permute_graph(h_path, path_edges, p)
with torch.no_grad():
    before = layer(h_path, path_edges)
    after = layer(h_perm, edges_perm)
    torch.testing.assert_close(after, before[p])
    torch.testing.assert_close(after.sum(dim=0), before.sum(dim=0))

Stacking two layers lets a node receive information from up to two hops away. In the next exercise you will use those node embeddings to predict one label per graph.

27.6 Compare molecular predictors

We will train on one assay from Tox21. A graph label in this exercise is an assay outcome for the entire compound. When using the offline data, the same code predicts a synthetic rule on paths using the position of one node type and its incident edge attributes.

27.6.1 Inspect the features

Each example contains (atom, edge_index, bond, y). The rows of atom index nodes. The first column stores the atomic-number category (the OGB code is \(Z-1\) for known elements), and the remaining columns include, among other features, degree, hydrogen count, and whether the atom is in a ring. The rows of bond follow the columns in edge_index, with one row per directed edge. The categorical values become one-hot vectors or learned embeddings.

The loader uses column 0 of OGB’s graph-label table, drops examples missing that label, and keeps the provided scaffold split. The split groups compounds by their structural framework. The layout and the feature definitions are documented by Open Graph Benchmark and in the OGB feature schema.

ATOM_DIMS = (119, 5, 12, 12, 10, 6, 6, 2, 2)
BOND_DIMS = (5, 6, 2)

def load_tox21(root="tox21", task=0):
    def raw(name, dtype=int):
        return np.loadtxt(f"{root}/raw/{name}.csv.gz", delimiter=",", dtype=dtype, ndmin=2)

    atoms, edges, bonds = raw("node-feat"), raw("edge"), raw("edge-feat")
    node_offsets = np.r_[0, raw("num-node-list").ravel().cumsum()]
    edge_offsets = np.r_[0, raw("num-edge-list").ravel().cumsum()]
    labels = np.genfromtxt(f"{root}/raw/graph-label.csv.gz",
                           delimiter=",", dtype=float, ndmin=2)[:, task]

    def load_split(name):
        indices = np.loadtxt(f"{root}/split/scaffold/{name}.csv.gz",
                             delimiter=",", dtype=int, ndmin=1)
        examples = []
        for i in indices:
            if not np.isfinite(labels[i]):
                continue
            node_slice = slice(node_offsets[i], node_offsets[i + 1])
            edge_slice = slice(edge_offsets[i], edge_offsets[i + 1])
            atom = torch.as_tensor(atoms[node_slice], dtype=torch.long)
            edge_index = directed_edges(edges[edge_slice])
            bond = torch.as_tensor(bonds[edge_slice], dtype=torch.long)
            bond = torch.cat((bond, bond), dim=0)
            examples.append((atom, edge_index, bond, float(labels[i])))
        return examples

    return tuple(load_split(name) for name in ("train", "valid", "test"))

def synthetic_graphs(count, seed):
    rng = np.random.default_rng(seed)
    examples = []
    for _ in range(count):
        n = int(rng.integers(5, 10))
        oxygen_at_end = bool(rng.integers(2))
        oxygen = 0 if oxygen_at_end else int(rng.integers(1, n - 1))
        special_bond = int(rng.integers(2))
        atom = torch.zeros((n, len(ATOM_DIMS)), dtype=torch.long)
        atom[:, 0] = 5
        atom[oxygen, 0] = 7
        atom[:, 2] = 2
        atom[[0, -1], 2] = 1
        edges = directed_edges([(i, i + 1) for i in range(n - 1)])
        bond = torch.zeros((2 * (n - 1), len(BOND_DIMS)), dtype=torch.long)
        adjacent = max(0, oxygen - 1)
        bond[[adjacent, adjacent + n - 1], 0] = special_bond
        y = float(oxygen_at_end and special_bond)
        examples.append((atom, edges, bond, y))
    return examples

graph_train, graph_valid, graph_test = (
    load_tox21() if USE_TOX21 else
    (synthetic_graphs(600, 30), synthetic_graphs(200, 31), synthetic_graphs(200, 32))
)

atom, edge_index, bond, y = graph_train[0]
print(atom.shape, edge_index.shape, bond.shape, y)
print(atom[:3], edge_index[:, :3], bond[:3])
torch.Size([5, 9]) torch.Size([2, 8]) torch.Size([8, 3]) 0.0
tensor([[5, 0, 1, 0, 0, 0, 0, 0, 0],
        [5, 0, 2, 0, 0, 0, 0, 0, 0],
        [5, 0, 2, 0, 0, 0, 0, 0, 0]]) tensor([[0, 1, 2],
        [1, 2, 3]]) tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])

Pick a few examples and check the meanings of the shapes. What could a set model infer from the atom feature columns already? Which information still requires knowing which atoms share a bond?

27.6.2 Assemble the graph predictors

We batch graphs by concatenating their node lists and shifting the edge indices so the graphs stay disconnected. graph_id[i] identifies the graph containing node i. Write sum_graphs to sum the representations of the nodes in each graph. You can use the same indexed accumulation as for incoming edges, with graph_id as the destination index.

def collate_graphs(examples):
    atoms, edges, bonds, targets = zip(*examples)
    sizes = torch.tensor([len(nodes) for nodes in atoms])
    offsets = torch.cat((sizes.new_zeros(1), sizes.cumsum(0)[:-1]))
    edge_index = torch.cat([edge + start for edge, start in zip(edges, offsets)], dim=1)
    graph_id = torch.repeat_interleave(torch.arange(len(atoms)), sizes)
    return (torch.cat(atoms), edge_index, torch.cat(bonds), graph_id, len(atoms)), torch.tensor(
        targets, dtype=torch.float32
    )

def sum_graphs(h, graph_id, n_graphs):
    raise NotImplementedError("Return one sum per graph in the batch.")

class CategoricalEncoder(nn.Module):
    def __init__(self, sizes, dim):
        super().__init__()
        self.embeddings = nn.ModuleList([nn.Embedding(size, dim) for size in sizes])

    def forward(self, features):
        return torch.stack([emb(features[:, i])
                            for i, emb in enumerate(self.embeddings)]).sum(dim=0)

class EdgeGIN(nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.encode_bond = CategoricalEncoder(BOND_DIMS, dim)
        self.update = mlp(dim, dim)

    def forward(self, h, edge_index, bond):
        src, dst = edge_index
        messages = (h[src] + self.encode_bond(bond)).relu()
        incoming = torch.zeros_like(h).index_add_(0, dst, messages)
        return self.update(h + incoming)

class GraphClassifier(nn.Module):
    def __init__(self, kind, rich=False, dim=32):
        super().__init__()
        self.kind = kind
        if kind == "histogram":
            self.predictor = mlp(ATOM_DIMS[0], 1)
        else:
            self.encode_atom = CategoricalEncoder(ATOM_DIMS if rich else ATOM_DIMS[:1], dim)
            self.predictor = mlp(dim, 1)
        if kind == "gin":
            self.layers = nn.ModuleList([SimpleGIN(dim), SimpleGIN(dim)])
        elif kind == "gine":
            self.layers = nn.ModuleList([EdgeGIN(dim), EdgeGIN(dim)])

    def forward(self, atom, edge_index, bond, graph_id, n_graphs):
        if self.kind == "histogram":
            h = nn.functional.one_hot(atom[:, 0], num_classes=ATOM_DIMS[0]).float()
        else:
            h = self.encode_atom(atom)
        if self.kind == "gin":
            for layer in self.layers:
                h = layer(h, edge_index).relu()
        elif self.kind == "gine":
            for layer in self.layers:
                h = layer(h, edge_index, bond).relu()
        pooled = sum_graphs(h, graph_id, n_graphs)
        return self.predictor(pooled).squeeze(-1)

27.6.3 Your Task

  1. Test sum_graphs on two graphs with different numbers of nodes. Check that predicting on both graphs in one batch agrees with predicting on each independently. Use different graph sizes and swap their order in the batch.
  2. Choose a prediction for each comparison in the ablation table. In particular, what do you expect when comparing Deep Sets and GIN with atomic number as their only node feature? What might change when both models receive rich atom features?
  3. Run the ablation below. Compare Deep Sets and GIN with atomic number first, then Deep Sets (rich) and GIN (rich). If time permits, include the histogram and GINE rows. Keep the same splits and epoch budget across the models you compare. The best validation loss selects the checkpoint for each model.
  4. Record test ROC-AUC, average precision (AP), parameter count, and approximate training time. AP is sensitive to the prevalence of positives, so record that prevalence as a point of comparison. For a short run, interpret differences alongside the training budget and the number of test positives.
def ranking_metrics(scores, targets):
    scores, targets = scores.numpy(), targets.numpy()
    order = np.argsort(-scores)
    scores, targets = scores[order], targets[order]
    positives = targets.sum()
    negatives = len(targets) - positives
    if positives == 0 or negatives == 0:
        raise ValueError("ROC-AUC requires at least one example of each class.")

    # Read precision and recall after admitting every example at a tied score.
    group_ends = np.r_[np.flatnonzero(scores[:-1] != scores[1:]), len(scores) - 1]
    tp = np.r_[0.0, targets.cumsum()[group_ends]]
    fp = np.r_[0.0, group_ends + 1] - tp
    recall, fpr = tp / positives, fp / negatives
    precision = tp[1:] / (tp[1:] + fp[1:])
    auc = (np.diff(fpr) * (recall[:-1] + recall[1:]) / 2).sum()
    ap = (np.diff(recall) * precision).sum()
    return float(auc), float(ap)

variants = {
    "Histogram + MLP": ("histogram", False),
    "Deep Sets": ("deepsets", False),
    "Deep Sets (rich)": ("deepsets", True),
    "GIN": ("gin", False),
    "GIN (rich)": ("gin", True),
    "GINE (rich)": ("gine", True),
}

def run_ablation(names, epochs=8):
    valid_loader = make_loader(graph_valid, collate_graphs)
    test_loader = make_loader(graph_test, collate_graphs)
    print(f"Test prevalence: {np.mean([example[-1] for example in graph_test]):.3f}")
    models = {}
    for name in names:
        print(f"Training {name}...", flush=True)
        torch.manual_seed(8)
        model = GraphClassifier(*variants[name])
        train_loader = make_loader(graph_train, collate_graphs, shuffle=True)
        fit(model, train_loader, valid_loader, epochs=epochs)
        auc, ap = ranking_metrics(*predict(model, test_loader))
        params = sum(p.numel() for p in model.parameters() if p.requires_grad)
        print(f"{name:18s}  ROC-AUC={auc:.3f}  AP={ap:.3f}  parameters={params}")
        models[name] = model
    return models

models = run_ablation(["Deep Sets", "GIN", "Deep Sets (rich)", "GIN (rich)"])
Model Test ROC-AUC Test AP Parameters Approx. training time
Histogram + MLP
Deep Sets
Deep Sets (rich)
GIN
GIN (rich)
GINE (rich)

27.6.4 Interpret your results

  1. Compare learned atomic-number embeddings with the histogram. Which distinctions between molecules can both representations preserve?
  2. Pick one contrast where you changed which atom features were available and one where you added message passing. For each, explain what the comparison tells you and which other changes could account for the observed difference. Consider model size and features derived from connectivity.
  3. GINE changes the message function as well as using bond features. How would you design a comparison that keeps the message function fixed and changes only the information it receives? If your change improves AP but lowers ROC-AUC, what should you inspect before deciding which model suits your goal?
  4. [Optional] Evaluate a trained GIN again with all edges removed from every test graph, including the corresponding bond rows. Keep the node features and trained weights fixed. Explain what this tells you about the model’s sensitivity to the change and how the perturbed inputs differ from the training graphs.

27.7 Explore depth and expressivity

This extension uses the layer from Exercise 4 and needs no training.

27.7.1 Your Task

  1. Build the six-cycle and the pair of triangles discussed in the concepts chapter. Start with the same scalar feature at each node. At each of 1, 2, 4, and 8 layers, record the sum of the node embeddings for both graphs. At a given depth, use the same parameters in both runs. Explain your observations by following the three steps of message passing.
  2. Using an adjacency matrix, compute the triangle count at each node. Hint: In a simple undirected graph, the diagonal of \(A^3\) counts closed walks of length three. How many does a single triangle contribute per node? Use this count as an initial feature and run the comparison again. Why does the new feature respect relabeling?
  3. Build a path with six nodes. Assign different initial features, add self-loops and implement repeated averaging. Record the variance across nodes after each step and plot it against depth. Repeat for \(\alpha=1\), \(0.5\), and \(0.1\) in the update below.

\[ H^{(\ell+1)}=(1-\alpha)H^{(\ell)} + \alpha D_{\mathrm{self}}^{-1}(A+I)H^{(\ell)}, \qquad (D_{\mathrm{self}})_{ii}=\sum_j(A+I)_{ij}. \]

What changes about the rate of smoothing? Can a smaller positive \(\alpha\) stop the smoothing altogether on this path? How far can information travel after three layers, and can you tell that from the variance alone?