TGraphX › Insights › Graph-Level Classification: Architectures and Pooling
← Back to Insights

Graph-Level Classification: Architectures and Pooling

Topic: GNN architectures and learning tasks

Node classification asks about individual nodes. Graph classification asks about entire graphs: given a collection of graphs, predict a label for each one. For node classification, a GNN reads out one representation per node. For graph classification, those per-node representations must first be aggregated into one vector per graph before the final classifier. The choice of aggregation — pooling — has a large effect on what structural information is preserved.

This article covers the task setup, global pooling, a GCN and a GIN classifier, batching with TGraphX's GraphBatch, the built-in classifiers, a training loop with a clean train/validation/test split, cross-validation, and the limits of these models.

Examples tested with TGraphX 1.5.1. The code blocks build on each other, so run them in order.


The Graph Classification Setup

In graph classification, the dataset is a collection of graphs {G_1, G_2, ..., G_M}, each with a label y_i. The labels might be:

  • A molecular property (toxic or non-toxic, soluble or insoluble)
  • A protein function category
  • A social network type
  • A program behavior class (benign or malicious)

Graphs in one dataset have different sizes: G_1 might have 20 nodes and G_2 might have 400. A fixed-size classifier cannot accept variable-size inputs, so a readout (pooling) step is needed.


Prerequisites

You should be comfortable with message passing and PyTorch modules. Install the two packages used below (TGraphX 1.5.1 needs Python 3.10 or later):

bash
pip install tgraphx scikit-learn

For how Graph and GraphBatch store data, see the batching internals guide. To see Graph objects built from images, see the MNIST as a graph tutorial.


Global Pooling

Global pooling maps the node representations {h_1, ..., h_n} of a graph to a single vector. For graph readout with a batch vector, TGraphX provides three functions (not layer classes): global_mean_pool, global_sum_pool and global_max_pool. Each takes the node tensor and a batch vector that says which graph every node belongs to. (There is also a tgraphx.AttentionPooling module, but it works on padded [B, S, D] sets, not on a batch vector.)

python
import torch
from tgraphx import global_mean_pool, global_sum_pool, global_max_pool

x = torch.randn(100, 64)                               # 100 nodes from 5 graphs
batch = torch.repeat_interleave(torch.arange(5), 20)   # [100], dtype long

print(global_mean_pool(x, batch).shape)   # torch.Size([5, 64])
print(global_sum_pool(x, batch).shape)    # torch.Size([5, 64])
print(global_max_pool(x, batch).shape)    # torch.Size([5, 64])

# Graph 0 holds the values {1, 2}; graph 1 holds the same values twice.
h = torch.tensor([[1.0], [2.0], [1.0], [2.0], [1.0], [2.0]])
which = torch.tensor([0, 0, 1, 1, 1, 1])
print(global_mean_pool(h, which).flatten())   # tensor([1.5000, 1.5000])
print(global_max_pool(h, which).flatten())    # tensor([2., 2.])
print(global_sum_pool(h, which).flatten())    # tensor([3., 6.])

Mean pooling averages the node representations, so its scale does not grow with graph size. It cannot distinguish two graphs whose node representations occur in the same proportions.

Sum pooling adds them, so the result depends on how many nodes there are. That helps when the target depends on counts (an additive property, for example), but large graphs produce large values, so normalization inside the network matters.

Max pooling takes the element-wise maximum. It answers "does any node activate this dimension strongly?", which suits labels driven by the presence of a local pattern, and it ignores how often the pattern occurs.


Architecture 1: GCN + Global Mean Pool

A simple baseline is two GCN layers followed by mean pooling. GCNConv works on vector node features [N, D]:

python
import torch.nn as nn
import torch.nn.functional as F
from tgraphx import GCNConv

class GCNGraphClassifier(nn.Module):
    def __init__(self, in_dim, hidden_dim, num_classes):
        super().__init__()
        self.conv1 = GCNConv(in_dim, hidden_dim)
        self.conv2 = GCNConv(hidden_dim, hidden_dim)
        self.classifier = nn.Linear(hidden_dim, num_classes)

    def forward(self, x, edge_index, batch):
        x = F.relu(self.conv1(x, edge_index))
        x = F.relu(self.conv2(x, edge_index))
        x = global_mean_pool(x, batch)     # [B, hidden_dim]
        return self.classifier(x)          # [B, num_classes]

This model is small and quick to try. Its weakness is that GCN's degree-normalized aggregation followed by a mean readout can lose counting information, such as how many neighbors or nodes share a value.


Architecture 2: GIN + Sum Pool

GIN replaces the normalized aggregation with a plain sum followed by an MLP, which is the more expressive choice when telling apart different structures matters (see the GIN architecture article for the theory and its assumptions).

TGraphX's TensorGINLayer expects spatial features [N, C, H, W]. For vector features, add two singleton axes: the layer's 1×1 convolutions then act as an ordinary per-node MLP. The classifier below also follows the GIN paper in reading out after every layer (including the input) and concatenating the results:

python
from tgraphx import TensorGINLayer

class GINGraphClassifier(nn.Module):
    """GIN for vector node features with a sum readout after every layer."""

    def __init__(self, in_dim, hidden_dim, num_classes, num_layers=3, dropout=0.5):
        super().__init__()
        dims = [in_dim] + [hidden_dim] * num_layers
        self.convs = nn.ModuleList(
            TensorGINLayer(dims[i], dims[i + 1], train_eps=True, use_batchnorm=True)
            for i in range(num_layers)
        )
        self.classifier = nn.Sequential(
            nn.Linear(sum(dims), hidden_dim),
            nn.ReLU(),
            nn.Dropout(dropout),
            nn.Linear(hidden_dim, num_classes),
        )

    def forward(self, x, edge_index, batch):
        readouts = [global_sum_pool(x, batch)]
        h = x[:, :, None, None]                 # [N, D] -> [N, D, 1, 1]
        for conv in self.convs:
            h = F.relu(conv(h, edge_index))
            readouts.append(global_sum_pool(h.flatten(1), batch))
        return self.classifier(torch.cat(readouts, dim=1))

The other TGraphX tensor layers (TensorGraphSAGELayer, TensorGATLayer) also require spatial features. For vector features, use the same singleton-axis pattern, or GCNConv / GATv2Conv.


Using GraphBatch for Multiple Graphs

GraphBatch combines variable-size graphs into one large disconnected graph: it concatenates node features, offsets each graph's edge indices, and builds the batch vector. Pass it a list of Graph objects.

python
from tgraphx import Graph, GraphBatch

def random_graph(num_nodes, num_edges, label):
    return Graph(
        node_features=torch.randn(num_nodes, 16),
        edge_index=torch.randint(0, num_nodes, (2, num_edges)),
        graph_label=torch.tensor(label),   # scalar tensor, so labels stack to [B]
    )

batch = GraphBatch([random_graph(20, 60, 0), random_graph(35, 90, 1), random_graph(15, 40, 0)])

print(batch.num_graphs)             # 3
print(batch.node_features.shape)    # torch.Size([70, 16])
print(batch.batch.shape)            # torch.Size([70])
print(batch.graph_labels)           # tensor([0, 1, 0])

for model in (GCNGraphClassifier(16, 32, 2), GINGraphClassifier(16, 32, 2)):
    logits = model(batch.node_features, batch.edge_index, batch.batch)
    print(logits.shape)             # torch.Size([3, 2])

Two details matter here:

  • Give each graph a scalar label, torch.tensor(1). With torch.tensor([1]), graph_labels has shape [B, 1] and CrossEntropyLoss rejects it in a hand-written loop (flattening the labels with .view(-1) also fixes it).
  • Keep edge indices local to each graph (0 .. num_nodes - 1). Graph rejects out-of-range indices, and GraphBatch adds the offsets itself.

Built-In Graph Classifiers

You do not have to write the model yourself. build_model with the task "graph_classification" stacks one layer type, applies a "mean", "sum" or "max" readout after the last layer and adds a linear head. tgraphx.GraphClassifier is a ready-made classifier built on ConvMessagePassing, so it accepts spatial node features only. This article writes its models by hand to use GCNConv (the factory has no "gcn" layer) and to read out after every layer, which neither built-in does.

python
from tgraphx import build_model

factory_model = build_model(
    "graph_classification", layer="linear",      # "linear" is for vector features [N, D]
    in_shape=(16,), hidden_shape=(32,), num_layers=2, num_classes=2, pooling="sum")

logits = factory_model(batch.node_features, batch.edge_index, batch=batch.batch)
print(logits.shape)   # torch.Size([3, 2])

Pass batch= by keyword to either built-in: their third positional argument is edge_features.


Training a Graph Classifier

To have something to learn, the next block builds a synthetic task that can only be solved from structure: every graph is a ring with n // 2 extra edges, and in class 1 all of them start at the same hub node. Node features are a constant 1.

python
from sklearn.model_selection import train_test_split

def make_graph(label, generator):
    n = int(torch.randint(12, 25, (1,), generator=generator))
    ring = torch.arange(n)
    k = n // 2
    if label == 1:                                   # all extra edges share a hub
        perm = torch.randperm(n, generator=generator)
        src, dst = perm[:1].repeat(k), perm[1:k + 1]
    else:                                            # extra edges spread out
        src = torch.randint(0, n, (k,), generator=generator)
        dst = (src + torch.randint(2, n - 1, (k,), generator=generator)) % n
    edge_index = torch.stack([torch.cat([ring, src]), torch.cat([(ring + 1) % n, dst])])
    edge_index = torch.cat([edge_index, edge_index.flip(0)], dim=1)   # undirected
    return Graph(node_features=torch.ones(n, 1), edge_index=edge_index,
                 graph_label=torch.tensor(label))

generator = torch.Generator().manual_seed(0)
graph_dataset = [make_graph(i % 2, generator) for i in range(200)]
labels = [int(g.graph_label) for g in graph_dataset]

# Split by whole graphs, stratified by class: 60% train, 20% validation, 20% test.
train_idx, test_idx = train_test_split(
    list(range(len(labels))), test_size=0.2, stratify=labels, random_state=0)
train_idx, val_idx = train_test_split(
    train_idx, test_size=0.25, stratify=[labels[i] for i in train_idx], random_state=0)

The training loop uses the validation graphs for early stopping, restores the best weights, and touches the test graphs only once:

python
import copy
from tgraphx import GraphLoader
from tgraphx.estimators import EarlyStopping

@torch.no_grad()
def evaluate_graphs(model, graphs):
    model.eval()
    batch = GraphBatch(graphs)
    logits = model(batch.node_features, batch.edge_index, batch.batch)
    loss = F.cross_entropy(logits, batch.graph_labels).item()
    accuracy = (logits.argmax(1) == batch.graph_labels).float().mean().item()
    return loss, accuracy

def train_and_evaluate(train_graphs, val_graphs, test_graphs, seed=0, epochs=30, patience=8):
    torch.manual_seed(seed)
    model = GINGraphClassifier(in_dim=1, hidden_dim=32, num_classes=2)
    optimizer = torch.optim.Adam(model.parameters(), lr=1e-2, weight_decay=1e-4)
    loader = GraphLoader(train_graphs, batch_size=32, shuffle=True, seed=seed)
    stopper = EarlyStopping(patience=patience, mode="min")   # the default mode is "max"

    for epoch in range(epochs):
        model.train()
        for batch in loader:
            optimizer.zero_grad()
            logits = model(batch.node_features, batch.edge_index, batch.batch)
            F.cross_entropy(logits, batch.graph_labels).backward()
            optimizer.step()

        val_loss, _ = evaluate_graphs(model, val_graphs)
        stop = stopper.step(val_loss)
        if stopper.counter == 0:                              # new best validation loss
            best_state = copy.deepcopy(model.state_dict())
        if stop:
            break

    model.load_state_dict(best_state)
    return evaluate_graphs(model, test_graphs)[1]

def pick(indices):
    return [graph_dataset[i] for i in indices]

test_accuracy = train_and_evaluate(pick(train_idx), pick(val_idx), pick(test_idx))
print(f"test accuracy on the synthetic task: {test_accuracy:.3f}")

The number printed here says only that the pipeline learns a toy structural rule; it says nothing about real datasets.

tgraphx.fit(model, train_loader, val_loader, ...) also accepts models with this forward(x, edge_index, batch) signature, but it has no early stopping, which is why the loop is written out.


Cross-Validation for Small Datasets

With a few hundred graphs, a single split gives a noisy estimate, so cross-validation is commonly used. Keep a validation set inside each training fold: if you choose the epoch or hyperparameters by looking at test-fold accuracy, the reported number is optimistically biased.

python
import numpy as np
from sklearn.model_selection import StratifiedKFold

kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
fold_accs = []
for fold, (dev_idx, test_idx) in enumerate(kfold.split(np.zeros(len(labels)), labels)):
    train_idx, val_idx = train_test_split(
        dev_idx, test_size=0.2, stratify=[labels[i] for i in dev_idx], random_state=fold)
    acc = train_and_evaluate(pick(train_idx), pick(val_idx), pick(test_idx), seed=fold)
    fold_accs.append(acc)

print(f"accuracy over {len(fold_accs)} folds: {np.mean(fold_accs):.3f} ± {np.std(fold_accs):.3f}")

Ten folds are common for the small TU benchmark datasets (MUTAG, PROTEINS, IMDB-BINARY); five are used here to keep the run short. Report the mean and standard deviation together with the seeds and the split protocol, never only the best fold. If several graphs come from the same source (the same molecule scaffold, patient or video), keep them in the same fold with a grouped splitter. Group the inner train/validation split as well (for example with scikit-learn's GroupShuffleSplit): the train_test_split call above ignores groups, so one source could land in both training and validation and bias early stopping.


Architecture Comparison

Architecture Readout What to keep in mind
GCN + mean pool Mean Small baseline; normalized aggregation and mean readout lose counts
GCN + sum pool Sum Output scale grows with graph size
GIN + sum pool Sum Can match the 1-WL test only if its functions are injective; never exceeds it
GIN with per-layer readout Sum per layer, concatenated Multi-scale representation; wider classifier input
Hierarchical (DiffPool, SAGPool, MinCutPool) Learned coarsening Not shipped in TGraphX 1.5.1

No row is best in general. Compare on your data with the same split and tuning budget, and include a structure-agnostic baseline (for example, sum-pool the raw node features and feed an MLP) to check that the graph structure is actually being used.


Handling Graphs Without Node Features

Some datasets contain only topology. A Graph still needs node features, so you create them. A constant works with sum aggregation (the first GIN layer then sees each node's degree). For mean-style aggregation, an explicit degree feature is often added:

python
def with_degree_features(edge_index, num_nodes, graph_label=None):
    """Node feature = in-degree (equal to degree when both directions are stored)."""
    degree = torch.bincount(edge_index[1], minlength=num_nodes).float()
    return Graph(node_features=degree.unsqueeze(1), edge_index=edge_index,
                 graph_label=graph_label)

g = graph_dataset[0]
print(with_degree_features(g.edge_index, g.num_nodes, g.graph_label).feature_shape)  # (1,)

Pass the real num_nodes: inferring it from edge_index.max() + 1 silently drops isolated nodes at the end of the index range.

Positional encodings are another option. TGraphX provides Laplacian eigenvectors in tgraphx.mining:

python
from tgraphx.mining import laplacian_eigvec_positional_encoding

pe = laplacian_eigvec_positional_encoding(g.edge_index, g.num_nodes, k=4)
print(pe.shape == (g.num_nodes, 4))   # True
features = torch.cat([g.node_features, pe], dim=1)

Eigenvectors are only defined up to sign (and up to rotation when eigenvalues repeat), so a model can pick up on arbitrary choices; random sign flipping during training is a common remedy.

Weisfeiler-Lehman (WL) colors are sometimes suggested as features too, with two caveats. They are computed by the same refinement that bounds message-passing GNNs, so they do not push a GNN past 1-WL. And in TGraphX 1.5.1, weisfeiler_lehman_labels numbers its colors separately on each call, so the ids are not comparable across graphs; the same limitation affects wl_graph_features and wl_kernel_matrix. For cross-graph WL features, use one shared color dictionary for the whole dataset.


Limitations and Honest Notes

Message passing has a ceiling. With identical node features, a 6-cycle and two disjoint triangles look the same to any standard message-passing GNN, because every node sees exactly two neighbors at every depth:

python
def undirected_graph(pairs):
    e = torch.tensor(pairs).t()
    return Graph(node_features=torch.ones(6, 1),
                 edge_index=torch.cat([e, e.flip(0)], dim=1),
                 graph_label=torch.tensor(0))

hexagon = undirected_graph([(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)])
triangles = undirected_graph([(0, 1), (1, 2), (2, 0), (3, 4), (4, 5), (5, 3)])
pair = GraphBatch([hexagon, triangles])

torch.manual_seed(0)
gin = GINGraphClassifier(in_dim=1, hidden_dim=16, num_classes=2).eval()
with torch.no_grad():
    out = gin(pair.node_features, pair.edge_index, pair.batch)
print(torch.allclose(out[0], out[1]))   # True

Global pooling is lossy. The readout sees only the collection of final node representations, not how those nodes are wired together. Whatever structure matters has to be encoded into the node representations first.

Hierarchical pooling is not included. TGraphX 1.5.1 does not ship DiffPool (Ying et al., NeurIPS 2018), SAGPool (Lee et al., ICML 2019) or MinCutPool (Bianchi et al., ICML 2020). PyTorch Geometric provides dense_diff_pool, SAGPooling and dense_mincut_pool if you need them.

Batch normalization depends on the batch. use_batchnorm=True computes statistics over all nodes in the batch, so they change with which graphs are drawn together and are noisy for very small batches. A per-node or per-graph normalization is an alternative.


Connecting Graph Classification to Research

Expressiveness results for GNNs are usually stated at the graph level: which pairs of graphs can a model map to different representations? Xu et al. ("How Powerful are Graph Neural Networks?", ICLR 2019) showed that message-passing GNNs are at most as powerful as the 1-WL test, and that GIN can reach that bound under injectivity assumptions. Higher expressiveness does not by itself mean higher test accuracy.

Evaluation protocol matters at least as much. Errica et al. ("A Fair Comparison of Graph Neural Networks for Graph Classification", ICLR 2020) re-evaluated several GNNs with separate model selection and model assessment and found that, on some datasets, structure-agnostic baselines were competitive with them.


Related Guides