TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › Node Classification with a GCN in PyTorch

Node Classification with a GCN in PyTorch

In many graph problems almost nothing is labelled. A handful of accounts in a payment network are known frauds; a few papers in a citation network have a hand-assigned topic; two members of the karate club are known to lead the two factions. The task is to label everyone else. This is semi-supervised node classification: one graph, a few labelled nodes, and the edges as the main source of information for the rest.

The previous lesson built the GCN layer in NumPy. Here you train a 2-layer GCN in plain PyTorch (no graph library), and compare it honestly with two baselines: an MLP that sees the same node features but no edges, and label propagation, which uses the edges but no features and has no parameters at all.

The setting

All nodes, labelled or not, take part in every forward pass: the unlabelled ones pass messages too. Only the loss is restricted to the labelled nodes:

L=−1∣VL∣∑v∈VLlog⁡softmax⁡(Zv)yv,Z=A^ ReLU⁡(A^XW1) W2,A^=D^−1/2(A+I)D^−1/2L = -\frac{1}{\lvert \mathcal{V}_L \rvert} \sum_{v \in \mathcal{V}_L} \log \operatorname{softmax}(Z_v)_{y_v}, \qquad Z = \hat{A}\, \operatorname{ReLU}(\hat{A} X W_1)\, W_2, \qquad \hat{A} = \hat{D}^{-1/2}(A + I)\hat{D}^{-1/2}

Training is full batch: the whole graph goes through the model in every step, because each node's output depends on its 2-hop neighbourhood. Accuracy is then measured on the nodes whose labels were never used. With so few labels there is no room for a validation set, so every setting below is fixed in advance (the values from the original GCN paper: hidden width 16 to 32, dropout 0.5, Adam with learning rate 0.01 and weight decay 5⋅10−45 \cdot 10^{-4}, 200 epochs) and nothing is tuned on the unlabelled nodes. In a real project you would hold out a few labelled nodes for validation, or use cross-validation over the labels.

Baseline first: label propagation

Label propagation needs no training. Put a one-hot vector on every labelled node and zeros elsewhere, multiply by the normalised adjacency A^\hat{A} again and again, and reset the labelled nodes to their one-hot vectors after each step. Labels diffuse along the edges, and each node takes the class with the most mass. It is the "no features, no parameters" lower bar any GNN has to clear.

python · try it yourself
import numpy as np
import networkx as nx

def norm_adj(A):
    A_hat = A + np.eye(len(A))
    d = A_hat.sum(axis=1)
    return A_hat / np.sqrt(np.outer(d, d))

def label_propagation(A, labels, known, n_classes, steps=50):
    """Spread one-hot labels along the edges; reset the known nodes after every step."""
    S = norm_adj(A)
    Y0 = np.zeros((len(A), n_classes))
    Y0[known, labels[known]] = 1
    Y = Y0.copy()
    for _ in range(steps):
        Y = S @ Y
        Y[known] = Y0[known]                       # clamp the labelled nodes
    return Y.argmax(axis=1)

# Karate club: one labelled member per faction (the instructor 0 and the officer 33).
G = nx.karate_club_graph()
A = nx.to_numpy_array(G, weight=None)
y = np.array([0 if G.nodes[v]["club"] == "Mr. Hi" else 1 for v in G])
known = np.array([0, 33])
unl = np.setdiff1d(np.arange(len(A)), known)
pred = label_propagation(A, y, known, 2)
print(f"karate, label propagation: {int((pred[unl] == y[unl]).sum())}/{len(unl)} unlabelled correct"
      f" = {np.mean(pred[unl] == y[unl]):.3f}")
print("misclassified nodes:", unl[pred[unl] != y[unl]].tolist())

# A seeded stochastic block model: 3 communities of 100, dense inside, sparse between.
sizes, p_in, p_out = [100, 100, 100], 0.06, 0.01
P = [[p_in if i == j else p_out for j in range(3)] for i in range(3)]
G2 = nx.stochastic_block_model(sizes, P, seed=0)
A2 = nx.to_numpy_array(G2, weight=None)
y2 = np.repeat(np.arange(3), 100)
inside = sum(A2[y2 == c][:, y2 == c].sum() for c in range(3)) / 2
print(f"SBM: {len(A2)} nodes, {int(A2.sum() / 2)} edges, {inside / (A2.sum() / 2):.0%} inside a community")
rng = np.random.default_rng(0)
known2 = np.concatenate([rng.choice(np.flatnonzero(y2 == c), 5, replace=False) for c in range(3)])
unl2 = np.setdiff1d(np.arange(300), known2)
pred2 = label_propagation(A2, y2, known2, 3)
print(f"SBM, 5 labels per class, label propagation: {np.mean(pred2[unl2] == y2[unl2]):.3f} on {len(unl2)} unlabelled")
karate, label propagation: 31/32 unlabelled correct = 0.969
misclassified nodes: [8]
SBM: 300 nodes, 1252 edges, 76% inside a community
SBM, 5 labels per class, label propagation: 0.807 on 285 unlabelled

On the karate club, with only the instructor (node 0) and the officer (node 33) labelled, label propagation gets 31 of the 32 other members right (0.969). The one miss, node 8, is connected to both leaders' circles, a member that many analyses of this graph find ambiguous. The second graph is a seeded stochastic block model: 300 nodes in 3 communities of 100, edge probability 0.06 inside a community and 0.01 between, which gives 1252 edges, 76% of them inside a community. With 5 labelled nodes per community, label propagation reaches 0.807 on the 285 others: the communities are noisy enough that edges alone leave about one node in five wrong.

The GCN in plain PyTorch

PyTorch has no GCNConv of its own, and it does not need one: the layer is a Linear followed by a multiplication with A^\hat{A}. For anything bigger than a toy, A^\hat{A} is stored as a sparse matrix: the karate club's has 190 nonzero entries (2⋅782 \cdot 78 edges plus 34 self-loops) out of 1156, and real graphs are far sparser. torch.sparse_coo_tensor builds it from the list of (row, col) index pairs and values, and torch.sparse.mm multiplies it with a dense matrix. The MLP baseline is the same model with the two A^\hat{A} multiplications removed.

The recorded example (CPU) runs both models and label propagation on both graphs. The karate club has no node features, so it uses the identity matrix: each node's feature vector is one-hot, and the first layer learns one 16-dimensional vector per node. The block model gets 16 noisy features per node: a class-dependent mean scaled by 0.4 plus standard normal noise, so the features carry a weak signal.

python · try it yourself
import numpy as np
import networkx as nx
import torch
from torch import nn
import torch.nn.functional as F

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

def norm_adj_sparse(A):
    """D^-1/2 (A + I) D^-1/2 as a sparse COO tensor, built from the edge list."""
    A_hat = A + np.eye(len(A))
    d = A_hat.sum(axis=1)
    rows, cols = np.nonzero(A_hat)
    vals = 1 / np.sqrt(d[rows] * d[cols])
    idx = torch.tensor(np.stack([rows, cols]), dtype=torch.long)
    return torch.sparse_coo_tensor(idx, torch.tensor(vals, dtype=torch.float32), (len(A), len(A)),
                                   check_invariants=True).coalesce()

class GCN(nn.Module):
    def __init__(self, f_in, hidden, classes, p_drop=0.5):
        super().__init__()
        self.lin1, self.lin2 = nn.Linear(f_in, hidden), nn.Linear(hidden, classes)
        self.p = p_drop

    def forward(self, A_norm, X):                  # A_norm: sparse (n, n); X: (n, f_in)
        H = F.relu(torch.sparse.mm(A_norm, self.lin1(F.dropout(X, self.p, self.training))))
        return torch.sparse.mm(A_norm, self.lin2(F.dropout(H, self.p, self.training)))

class MLP(nn.Module):                              # the same model with the edges removed
    def __init__(self, f_in, hidden, classes, p_drop=0.5):
        super().__init__()
        self.lin1, self.lin2 = nn.Linear(f_in, hidden), nn.Linear(hidden, classes)
        self.p = p_drop

    def forward(self, A_norm, X):
        H = F.relu(self.lin1(F.dropout(X, self.p, self.training)))
        return self.lin2(F.dropout(H, self.p, self.training))

def fit(model, A_norm, X, y, known, epochs=200):
    torch.manual_seed(0)
    opt = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
    for _ in range(epochs):                         # full batch: the whole graph every step
        model.train()
        loss = F.cross_entropy(model(A_norm, X)[known], y[known])   # loss on labelled nodes only
        opt.zero_grad(); loss.backward(); opt.step()
    model.eval()
    with torch.no_grad():
        return model(A_norm, X).argmax(1)

def label_propagation(A, labels, known, n_classes, steps=50):
    A_hat = A + np.eye(len(A)); d = A_hat.sum(axis=1)
    S = A_hat / np.sqrt(np.outer(d, d))
    Y0 = np.zeros((len(A), n_classes)); Y0[known, labels[known]] = 1
    Y = Y0.copy()
    for _ in range(steps):
        Y = S @ Y; Y[known] = Y0[known]
    return Y.argmax(axis=1)

def report(name, A, X, y, known, hidden):
    unl = np.setdiff1d(np.arange(len(A)), known)
    A_norm, Xt, yt = norm_adj_sparse(A).to(device), torch.tensor(X, dtype=torch.float32).to(device), torch.tensor(y).to(device)
    kt = torch.tensor(known)
    accs = {}
    for label, Model in (("MLP (no edges)", MLP), ("GCN", GCN)):
        torch.manual_seed(0)
        pred = fit(Model(X.shape[1], hidden, int(y.max()) + 1).to(device), A_norm, Xt, yt, kt).cpu().numpy()
        accs[label] = np.mean(pred[unl] == y[unl])
    accs["label propagation"] = np.mean(label_propagation(A, y, known, int(y.max()) + 1)[unl] == y[unl])
    print(f"{name} ({len(unl)} unlabelled nodes): " + ", ".join(f"{k} {v:.3f}" for k, v in accs.items()))

# 1. Karate club: no node features, so X = identity (one learnable vector per node); 1 label per faction.
G = nx.karate_club_graph()
A = nx.to_numpy_array(G, weight=None)
y = np.array([0 if G.nodes[v]["club"] == "Mr. Hi" else 1 for v in G])
A_sp = norm_adj_sparse(A)
A_hat = A + np.eye(34); d = A_hat.sum(1)
dense = torch.tensor(A_hat / np.sqrt(np.outer(d, d)), dtype=torch.float32)
print("device:", device, " sparse entries:", A_sp._nnz(), "of", 34 * 34,
      " sparse == dense:", torch.allclose(A_sp.to_dense(), dense))
report("karate, X = I, labels on nodes 0 and 33", A, np.eye(34), y, np.array([0, 33]), hidden=16)

# 2. Stochastic block model with weak, noisy node features; 5 labels per class.
P = [[0.06 if i == j else 0.01 for j in range(3)] for i in range(3)]
G2 = nx.stochastic_block_model([100, 100, 100], P, seed=0)
A2 = nx.to_numpy_array(G2, weight=None)
y2 = np.repeat(np.arange(3), 100)
rng = np.random.default_rng(0)
known2 = np.concatenate([rng.choice(np.flatnonzero(y2 == c), 5, replace=False) for c in range(3)])
means = rng.normal(0, 1, size=(3, 16))
X2 = 0.4 * means[y2] + rng.normal(0, 1, size=(300, 16))      # class signal buried in noise
report("SBM, 16 noisy features, 5 labels per class", A2, X2, y2, known2, hidden=32)
device: cpu  sparse entries: 190 of 1156  sparse == dense: True
karate, X = I, labels on nodes 0 and 33 (32 unlabelled nodes): MLP (no edges) 0.500, GCN 0.969, label propagation 0.969
SBM, 16 noisy features, 5 labels per class (285 unlabelled nodes): MLP (no edges) 0.537, GCN 0.937, label propagation 0.807
Graph (unlabelled nodes) MLP, no edges label propagation GCN
karate, 2 labels (32) 0.500 0.969 0.969
block model, 15 labels (285) 0.537 0.807 0.937
  • Karate: the MLP gets 0.500, exactly chance. With identity features, an unlabelled node's one-hot input feeds weights that receive no gradient from the loss (only weight decay), so the MLP knows nothing about it. The GCN mixes each node's vector with its neighbours' and reaches 0.969, the same as label propagation: with no features, the structure is all there is, and both exploit it equally.
  • Block model: the features alone give the MLP 0.537 (chance is 0.333): there is a signal, but 15 labelled examples in 16 noisy dimensions are not enough. The edges alone give label propagation 0.807. The GCN uses both and reaches 0.937: averaging a node's features with its neighbours' (mostly from the same community) cancels much of the noise. This is where GNNs earn their keep: informative features and informative edges.

One run, one seed, one choice of labelled nodes: differences of a couple of points between methods would need repeated runs with other seeds and other labelled sets before you trust them. The gaps here (0.5 vs 0.969, 0.537 vs 0.807 vs 0.937) are large enough not to depend on that.

Graph libraries

For real work, use a library that handles sparse message passing, batching and data sets:

  • PyTorch Geometric (PyG): layers such as GCNConv, SAGEConv and GATConv take node features x and an edge_index tensor of shape (2, num_edges); graphs live in a Data object; global_mean_pool(x, batch) does the readout; neighbour-sampling loaders train on graphs too large for one forward pass.
  • DGL (Deep Graph Library): the same ideas around a graph object with message and reduce functions; it supports PyTorch and other back ends.

Neither is installed in this course's environment, so the examples use plain PyTorch; the layers above are what GCNConv computes (with details that vary by version, such as optional normalisation and bias placement). Read the documentation of the version you install.

Mini-batching graphs and graph-level tasks

Many tasks have a label per graph, not per node: is this molecule toxic, which class of protein is this. A model then needs a readout (or graph pooling) that turns the node vectors of one graph into one vector: sum, mean or max over the nodes, all permutation invariant. A classifier head sits on top of that vector.

Batching works differently from images. Graphs have different sizes, so they cannot be stacked into one tensor. Instead, the graphs of a mini-batch are put side by side as one big disconnected graph: a block-diagonal adjacency matrix (in a library, the edge lists concatenated with shifted node indices) and a batch vector that records which graph each node belongs to. Message passing cannot cross between blocks, so every graph is processed exactly as if it were alone, and the readout sums or averages by batch.

adjacency of the batch (10 x 10) 0 0 0 1 1 1 2 2 2 2 batch: graph id of each node graph 0: path, 3 nodes graph 1: triangle, 3 nodes graph 2: star, 4 nodes filled cell = edge; outside the blocks everything is 0: no messages between graphs readout: mean of each graph's nodes
python · try it yourself
import numpy as np
import networkx as nx

def norm_adj(A):
    A_hat = A + np.eye(len(A))
    d = A_hat.sum(axis=1)
    return A_hat / np.sqrt(np.outer(d, d))

graphs = [nx.path_graph(3), nx.cycle_graph(3), nx.star_graph(3)]    # 3, 3 and 4 nodes
rng = np.random.default_rng(0)
feats = [rng.normal(size=(g.number_of_nodes(), 2)) for g in graphs]
W = rng.normal(size=(2, 4))

# Mini-batch = one big disconnected graph: block-diagonal adjacency + a "batch" vector.
sizes = [g.number_of_nodes() for g in graphs]
n = sum(sizes)
A = np.zeros((n, n))
start = 0
for g, s in zip(graphs, sizes):
    A[start:start + s, start:start + s] = nx.to_numpy_array(g, weight=None)
    start += s
X = np.concatenate(feats)
batch = np.repeat(np.arange(len(graphs)), sizes)                    # graph id of every node
print("batch vector:", batch.tolist())

H = np.maximum(0, norm_adj(A) @ X @ W)                              # one GCN layer on the whole batch

# Readout: mean of the node vectors of each graph (a scatter-add, then divide by the counts).
pooled = np.zeros((len(graphs), H.shape[1]))
np.add.at(pooled, batch, H)
pooled /= np.bincount(batch)[:, None]
print("graph embeddings:", pooled.shape)

# The same graphs one by one give the same result: no messages cross between blocks.
one_by_one = np.stack([np.maximum(0, norm_adj(nx.to_numpy_array(g, weight=None)) @ x @ W).mean(axis=0)
                       for g, x in zip(graphs, feats)])
print("batched == one by one:", np.allclose(pooled, one_by_one))
print("embedding of the star graph:", np.round(pooled[2], 3).tolist())
batch vector: [0, 0, 0, 1, 1, 1, 2, 2, 2, 2]
graph embeddings: (3, 4)
batched == one by one: True
embedding of the star graph: [0.142, 0.0, 0.757, 0.0]

The batch of a path, a triangle and a 4-node star becomes one 10-node graph; the batch vector [0, 0, 0, 1, 1, 1, 2, 2, 2, 2] drives the mean pooling (a scatter-add with np.add.at, which is global_mean_pool in PyG), and the result is identical to processing the graphs one at a time.

Pitfalls

  • Evaluating on the labelled nodes. Their labels were in the loss; accuracy on them says nothing. Report accuracy on the unlabelled nodes only, and say how many there are.
  • Tuning on the nodes you report on. With few labels the temptation is to pick epochs, width and dropout by looking at the "test" nodes. Fix the settings in advance or keep separate validation nodes.
  • An MLP baseline with no features. With identity features and no edges, the MLP is chance by construction (as on the karate club); say so instead of presenting it as a fair fight. The block model is the fairer comparison.
  • Leaking through the graph. In transductive training the unlabelled nodes' features are visible during training (that is allowed and expected); their labels must not be used anywhere, including in feature engineering such as "fraction of neighbours that are fraud".
  • Dense A^\hat{A} for big graphs. n2n^2 floats: 4 TB for a million nodes. Use sparse tensors or a graph library.
  • Batching graphs without shifting the node indices. Concatenated edge lists must add each graph's node offset; otherwise all graphs' edges point at the first graph's nodes.

Practice

  1. In the karate example, label two members per faction instead of one (for example nodes 0, 1 and 32, 33). Which lines change, and what should you expect?
Answer

Only the known array: np.array([0, 1, 32, 33]). Accuracy is then measured on 30 nodes. Running it gives 0.967 for both the GCN and label propagation (29 of 30) and 0.500 for the MLP: the structure was already strong enough with one label per faction.

  1. Why does the MLP in the karate example score exactly 0.500?
Answer

Each unlabelled node's input is a one-hot vector that selects a column of the first weight matrix nobody trains (it gets no gradient from the loss, only weight decay). Its prediction is driven by the small random initial weights and the biases, which carry no information about the node, so it lands on chance: 16 of 32 here.

  1. Replace torch.sparse.mm(A_norm, ...) by the mean aggregator D^−1(A+I)\hat{D}^{-1}(A + I). What changes in norm_adj_sparse?
Answer

The values become 1 / d[rows] instead of 1 / np.sqrt(d[rows] * d[cols]): each row is divided by its own degree, so the matrix is no longer symmetric but every row sums to 1.

  1. You have 10,000 molecules, each a graph of 10 to 40 atoms, and a toxicity label per molecule. Sketch the model and the batching.
Answer

Node features = atom type (and charge, etc.), optionally edge features = bond type. A few message-passing layers (GCN, GIN or GAT), then a readout (sum or mean per molecule, by the batch vector), then an MLP head with a sigmoid output and binary cross-entropy. Batch, say, 64 molecules at a time as one block-diagonal graph; split train, validation and test by molecule (better: by molecular scaffold, so similar molecules do not land on both sides).

Test yourself

In semi-supervised node classification with a GCN, which nodes go through the forward pass?

  1. Only the labelled nodes
  2. All nodes; the loss uses only the labelled ones
  3. Only the unlabelled nodes
  4. A random half of the nodes

On the block model, the MLP scored 0.537, label propagation 0.807 and the GCN 0.937. What explains the GCN's lead?

  1. It has more parameters than the MLP
  2. It combines the weak feature signal with the community structure in the edges
  3. It was evaluated on the labelled nodes
  4. Label propagation is broken

How is a mini-batch of graphs of different sizes usually formed?

  1. Pad every graph to the largest size
  2. As one disconnected graph with a block-diagonal adjacency and a batch vector
  3. One graph per step only
  4. By resizing the graphs like images

For a graph-level label (for example, molecule toxicity), what turns node vectors into one graph vector?

  1. A causal mask
  2. A readout such as the sum, mean or max over the graph's nodes
  3. The degree matrix
  4. Label propagation