Module contents
Stage 2 of 8Advanced 90 min

GCN, node classification and oversmoothing

Implement Kipf and Welling's GCN on the custom core, reproduce its Cora result with the original protocol and several seeds, and study what happens as layers are stacked: representations converge and accuracy falls. Measure oversmoothing with Dirichlet energy and test residual connections and normalizations that mitigate it.

After this lesson you can

  • Derive the GCN layer as a first-order approximation of a spectral filter.
  • Reproduce published Cora accuracy with mean and deviation over 10 seeds.
  • Measure oversmoothing with Dirichlet energy as a function of depth.
  • Evaluate residuals and pair normalization as mitigations.

Before you start

How often should you mix neighbors?

With only 20 labeled articles per class in Cora, a network can use words and links to propagate information. One layer sees immediate neighbors; two can combine information two hops away. But adding steps does not guarantee improvement: repeatedly applying the same operator attenuates some differences between nodes. Before attributing an accuracy drop to that phenomenon, distinguish linear propagation from a network trained with weights and activations.

The figure shows actual propagation on the full Cora graph, without training. We project original features and their propagated versions onto the same two PCA axes, fitted once to initial attributes without labels. The first 50 nodes by index of each of two classes are shown; other nodes participate in propagation even though not plotted. Scale stays fixed. Energy uses all nodes and dimensions, not only visible points.

InteractivePropagation changes representations
  • Class 0
  • Class 1
PCA 1 horizontal · PCA 2 vertical · fixed scale
0
Dirichlet energy / initial norm²0.61665
Increase depth. The projection has fixed axes and energy is calculated in all dimensions; the figure shows only two classes and is not a trained GCN.

Distance between points in this projection does not determine separability in the full space. There are also multiple connected components and persistent modes depend on degree. Therefore “all points become equal” is not a general claim; we will see the exact limit and a measurement with a classifier.

From Chebyshev to GCN

Assume an undirected graph with nonnegative weights, adjacency A\mat{A} without initial loops, and positive degrees for the spectral derivation. With L=I−D−1/2AD−1/2\mat{L}=\mat{I}-\mat{D}^{-1/2}\mat{A}\mat{D}^{-1/2}, a first-order polynomial spectral filter is θ0I+θ1L~\theta_0\mat{I}+\theta_1\tilde{\mat{L}}, where L~=2L/λmax⁡−I\tilde{\mat{L}}=2\mat{L}/\lambda_{\max}-\mat{I}. Approximating λmax⁡\lambda_{\max} by 2, L~≈−D−1/2AD−1/2\tilde{\mat{L}}\approx-\mat{D}^{-1/2}\mat{A}\mat{D}^{-1/2}. Tying coefficients as θ0=−θ1=θ\theta_0=-\theta_1=\theta gives

θ(I+D−1/2AD−1/2).\theta\left(\mat{I}+\mat{D}^{-1/2}\mat{A}\mat{D}^{-1/2}\right).

The operator has an eigenvalue-2 mode per component and its powers can amplify it. The GCN from scratch uses the substitution proposed by Kipf and Welling: add a weight-one loop to every node, recompute degrees, and define

A~=A+I,d~i=∑jA~ij,S=D~−1/2A~D~−1/2,H(ℓ+1)=σ(SH(ℓ)W(ℓ)).\tilde{\mat{A}}=\mat{A}+\mat{I},\quad \tilde{d}_i=\sum_j\tilde A_{ij},\quad \mat{S}=\tilde{\mat{D}}^{-1/2}\tilde{\mat{A}}\tilde{\mat{D}}^{-1/2},\quad \mat{H}^{(\ell+1)}=\sigma(\mat{S}\mat{H}^{(\ell)}\mat{W}^{(\ell)}).

Renormalization changes degrees and is not an algebraic equality with the previous filter. The cell implements each COO column as a source-to-destination message weighted 1/d~jd~i1/\sqrt{\tilde d_j\tilde d_i} and accumulates it using the previous lesson’s scatter. An isolated node retains its own signal through its loop. Loops are not added twice.

For z=D~−1/2x\vb{z}=\tilde{\mat{D}}^{-1/2}\vb{x}, quadratic forms x⊤(I∓S)x\vb{x}\T(\mat{I}\mp\mat{S})\vb{x} are sums of terms proportional to (zi∓zj)2(z_i\mp z_j)^2 over directed edges. The first is nonnegative; the second is positive for every x≠0\vb{x}\ne0 because each node has a positive loop. By symmetry, eigenvalues of S\mat{S} lie in (−1,1](-1,1]. The vector D~1/21\tilde{\mat{D}}^{1/2}\vb{1} has eigenvalue 1 in each connected component. The spectral theorem thus gives convergence of Sk\mat{S}^k to the projector onto those modes, not necessarily the unweighted constant vector.

What energy measures

The oversmoothing diagnostic here uses energy normalized by the initial signal norm:

Ek=tr⁡(Xk⊤(I−S)Xk)∥X0∥F2,Xk=SkX0.E_k=\frac{\operatorname{tr}(\mat{X}_k\T(\mat{I}-\mat{S})\mat{X}_k)}{\norm{\mat{X}_0}_F^2},\qquad \mat{X}_k=\mat{S}^k\mat{X}_0.

For a mode of S\mat{S} with eigenvalue λ\lambda, its contribution to EkE_k is multiplied by (1−λ)λ2k(1-\lambda)\lambda^{2k}. Since ∣λ∣≤1|\lambda|\le1, energy does not increase with kk. A negative eigenvalue changes its component’s sign at each step, but its contribution to this energy depends on magnitude. In a network with learned matrices, activations, residual connections, or normalization, this monotonicity is no longer guaranteed. Low energy is also insufficient to conclude that the classifier lost accuracy: later scaling can amplify small differences.

The figure was generated with full Cora, row-normalized attributes, two-component PCA fitted once on initial attributes, and propagation Sk\mat{S}^k. In this run E0=0.6166527E_0=0.6166527 and E20=0.0005022E_{20}=0.0005022. The cell below reconstructs these values and the 100 points without downloading report artifacts. The point sample is not selected by outcome, and PCA is fitted transductively without labels.

Laboratory: implementation and comparison

Semi-supervised node classification uses all graph features and edges during propagation, but only 140 training labels in the loss. The public split has 500 validation nodes and 1000 test nodes. Stopping and checkpoint selection use validation; test is evaluated afterwards. This is transductive evaluation, not measurement of future nodes and links absent during training.

You need local PyTorch and PyTorch Geometric. Input rows are normalized; use a 16-unit hidden layer, dropout 0.5, Adam with rate 0.01, penalty 5⋅10−45\cdot10^{-4} on the first matrix, and up to 200 epochs. The paper uses a ten-epoch stopping window; here we also restore the observed minimum validation loss, so we do not claim exact protocol identity. First compare the layer with GCNConv by copying the same weights and bias.

[ ]Cora and edge normalizationLocal GPU
import copy
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torch_geometric.datasets import Planetoid
from torch_geometric.transforms import NormalizeFeatures
from torch_geometric.nn import GCNConv

torch.set_num_threads(4)
root = Path.home() / '.cache' / 'oryon' / 'datasets' / 'Planetoid'
data = Planetoid(str(root), 'Cora', split='public', transform=NormalizeFeatures())[0]
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
data = data.to(device)

def normalized_edges(edge, n):
    src, dst = edge
    keep = src != dst
    loops = torch.arange(n, device=edge.device)
    src = torch.cat((src[keep], loops)); dst = torch.cat((dst[keep], loops))
    degree = torch.bincount(dst, minlength=n).to(torch.float32)
    return torch.stack((src, dst)), degree[src].rsqrt() * degree[dst].rsqrt()

edges, norm = normalized_edges(data.edge_index, data.num_nodes)
class Conv(nn.Module):
    def __init__(self, a, b):
        super().__init__()
        self.lin = nn.Linear(a, b, bias=False)
        self.bias = nn.Parameter(torch.zeros(b))
        nn.init.xavier_uniform_(self.lin.weight)
    def forward(self, x):
        h = self.lin(x); src, dst = edges
        out = h.new_zeros((len(x), h.shape[1]))
        out.index_add_(0, dst, h[src] * norm[:, None])
        return out + self.bias

torch.manual_seed(0)
conv = Conv(data.num_node_features, 16).to(device)
ref = GCNConv(data.num_node_features, 16).to(device)
with torch.no_grad():
    ref.lin.weight.copy_(conv.lin.weight); ref.bias.copy_(conv.bias)
    delta = (conv(data.x) - ref(data.x, data.edge_index)).abs().max().item()
print('dispositivo', device, 'error máximo PyG', delta)
assert delta < 1e-5
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The normalized_edges contract assumes symmetric binary edges, as in the Cora version used here. If repeated or weighted edges exist, specify their semantics and sum weights when calculating degrees. For directed graphs, symmetric normalization no longer has the same spectral interpretation.

[ ]Ten seeds with validation selectionLocal GPU
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.c1 = Conv(data.num_node_features, 16)
        self.c2 = Conv(16, int(data.y.max()) + 1)
    def forward(self):
        x = F.dropout(data.x, p=.5, training=self.training)
        x = F.relu(self.c1(x))
        x = F.dropout(x, p=.5, training=self.training)
        return self.c2(x)

acc = []
for seed in range(10):
    torch.manual_seed(seed); torch.cuda.manual_seed_all(seed)
    model = Net().to(device)
    opt = torch.optim.Adam([
        {'params': model.c1.lin.parameters(), 'weight_decay': 5e-4},
        {'params': [model.c1.bias, *model.c2.parameters()], 'weight_decay': 0}], lr=.01)
    best = float('inf'); state = None; stale = 0
    for epoch in range(1, 201):
        model.train(); opt.zero_grad(); out = model()
        loss = F.cross_entropy(out[data.train_mask], data.y[data.train_mask])
        loss.backward(); opt.step()
        model.eval()
        with torch.no_grad():
            out = model()
            val = F.cross_entropy(out[data.val_mask], data.y[data.val_mask]).item()
        if val < best - 1e-5:
            best = val; state = copy.deepcopy(model.state_dict()); best_epoch = epoch; stale = 0
        else:
            stale += 1
        if stale >= 10: break
    model.load_state_dict(state); model.eval()
    with torch.no_grad():
        pred = model().argmax(1)
        score = (pred[data.test_mask] == data.y[data.test_mask]).float().mean().item()
    acc.append(score)
    print('semilla', seed, 'época', best_epoch, 'test', round(score, 4))
print('media', round(float(np.mean(acc)), 4), 'desviación muestral', round(float(np.std(acc, ddof=1)), 4))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The original paper reports 81.5% on Cora as the mean of 100 initializations on the public split. In one run of this cell, the ten accuracies were 0.815, 0.820, 0.822, 0.818, 0.827, 0.825, 0.815, 0.832, 0.826, and 0.813: mean 0.8213 and sample standard deviation approximately 0.00618. The difference from 0.815 is 0.0063, slightly greater than one sample deviation: this run does not strictly satisfy the criterion of being within one deviation. Variation across initializations on one split does not estimate variation across splits; Shchur and colleagues show why that distinction affects model comparisons. These numbers are our run, not the paper’s.

Reconstructing the figure

This cell calculates the operator with SciPy, fits PCA once, and propagates all of Cora. Visible classes are a deterministic index selection, not a subset used to calculate energy. PyG normalizations must not be confused with adjacency normalization. The step-zero value and energy list help detect preparation changes.

[ ]Cora energy and projectionLocal GPU
from scipy import sparse
from sklearn.decomposition import PCA
cpu = Planetoid(str(root), 'Cora', split='public', transform=NormalizeFeatures())[0]
edge = cpu.edge_index.numpy(); n = cpu.num_nodes
A = sparse.coo_matrix((np.ones(edge.shape[1]), (edge[1], edge[0])), shape=(n,n)).tocsr()
A.setdiag(0); A.eliminate_zeros(); A.data[:] = 1
A = A + sparse.eye(n, format='csr')
d = np.asarray(A.sum(axis=1)).ravel(); D = sparse.diags(d ** -.5); S = D @ A @ D
X = cpu.x.numpy().astype(np.float64); initial_norm = float(np.sum(X * X))
pca = PCA(n_components=2, svd_solver='randomized', random_state=14).fit(X)
labels = cpu.y.numpy(); selected = np.r_[np.flatnonzero(labels == 0)[:50], np.flatnonzero(labels == 1)[:50]]
projection = []; energy = []
for k in range(21):
    projection.append(pca.transform(X)[selected])
    energy.append(float(np.sum(X * (X - S @ X)) / initial_norm))
    X = S @ X
assert np.all(np.diff(energy) < 1e-10)
print('energía pasos 0, 1, 10, 20:', [round(energy[k], 7) for k in (0,1,10,20)])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

As a control, fit a linear classifier for each prespecified depth. Standardization is fitted only on training nodes and the regularization parameter fixed before looking at test. This is not equivalent to training a GCN with nonlinear layers.

[ ]Linear control of the propagated signalLocal GPU
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X = cpu.x.numpy().astype(np.float64); y = cpu.y.numpy()
train = cpu.train_mask.numpy(); test = cpu.test_mask.numpy()
for k in range(33):
    if k in (4,8,16,32):
        scaler = StandardScaler().fit(X[train]); z = scaler.transform(X)
        clf = LogisticRegression(C=1, max_iter=500, random_state=0).fit(z[train], y[train])
        print('pasos', k, 'exactitud test', round(clf.score(z[test], y[test]), 4))
    X = S @ X
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Residuals, PairNorm, and depth

An equal-dimension residual connection adds a layer’s input to its output, providing a path to preserve information. PairNorm centers representations across nodes and fixes the root mean square of their norms. Maintaining separations does not guarantee preserving label information or establish causality. Normalization is calculated over nodes present in the forward pass and, in this experiment, is transductive.

The next comparison controls hidden width, split, and seed; it compares networks of 2, 8, and 16 layers, with or without residuals and with PairNorm. It uses one seed to study the mechanism, not establish a winner. The best state by validation loss is retained, with patience 10 and a maximum of 200 epochs. Test results are printed for every prespecified configuration; do not use that table to choose hyperparameters and then present the same table as independent evaluation.

[ ]Depth and mitigationsLocal GPU
src, dst = edges
def propagate(x):
    result = x.new_zeros(x.shape)
    result.index_add_(0, dst, x[src] * norm[:,None])
    return result
def pairnorm(x):
    x = x - x.mean(0, keepdim=True)
    return x / x.square().sum(1).mean().sqrt().clamp_min(1e-12)
class DeepNet(nn.Module):
    def __init__(self, depth, mode):
        super().__init__(); self.mode = mode
        dims = [data.num_node_features] + [16]*(depth-1) + [int(data.y.max())+1]
        self.layers = nn.ModuleList(nn.Linear(a,b) for a,b in zip(dims[:-1],dims[1:]))
        for layer in self.layers:
            nn.init.xavier_uniform_(layer.weight); nn.init.zeros_(layer.bias)
    def forward(self):
        h = F.dropout(data.x, p=.5, training=self.training)
        for i, layer in enumerate(self.layers):
            z = propagate(layer(h))
            if i < len(self.layers)-1:
                z = F.relu(z)
                if self.mode == 'residual' and i > 0: z = z + h
                if self.mode == 'pairnorm': z = pairnorm(z)
                h = F.dropout(z, p=.5, training=self.training)
            else: h = z
        return h

for depth in (2, 8, 16):
    for mode in ('plain', 'residual', 'pairnorm'):
        torch.manual_seed(0); model = DeepNet(depth, mode).to(device)
        opt = torch.optim.Adam([
            {'params': [model.layers[0].weight], 'weight_decay': 5e-4},
            {'params': [p for name,p in model.named_parameters() if name != 'layers.0.weight'], 'weight_decay': 0}], lr=.01)
        best = float('inf'); stale = 0; state = None
        for epoch in range(1,201):
            model.train(); opt.zero_grad(); out = model()
            loss = F.cross_entropy(out[data.train_mask], data.y[data.train_mask]); loss.backward(); opt.step()
            model.eval()
            with torch.no_grad():
                out = model(); val = F.cross_entropy(out[data.val_mask], data.y[data.val_mask]).item()
            if val < best - 1e-5:
                best = val; state = copy.deepcopy(model.state_dict()); best_epoch = epoch; stale = 0
            else: stale += 1
            if stale >= 10: break
        model.load_state_dict(state); model.eval()
        with torch.no_grad():
            score = (model()[data.test_mask].argmax(1) == data.y[data.test_mask]).float().mean().item()
        print(depth, mode, 'época', best_epoch, 'test', round(score,4))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

This variant places bias before propagation, unlike the earlier Conv and GCNConv; keep that choice the same across its three modes. Greater depth also changes optimization and parameter count. A drop alone does not prove energy caused it. Another alternative is to decouple multi-hop propagation from a simple classifier, as in SGC; removing nonlinearities changes the model family.

In one cell run with seed 0, test accuracies were as follows. The two-layer residual network matches the ordinary one in this implementation because there is no pair of hidden layers between which to insert the sum. The cell also shows the selected epoch.

LayersOrdinaryResidualPairNorm
20.8160.8160.720
80.1300.1710.663
160.0640.1300.359

The deep ordinary network performed worse in this run and PairNorm improved it at 8 and 16 layers, though it remained below the ordinary two-layer network. This is a diagnostic with one seed and fixed split, not a definitive comparison. In a different experiment, a linear classifier on SkX\mat{S}^k\mat{X} signals standardized using training nodes reached 0.709, 0.715, 0.724, and 0.731 on test for 4, 8, 16, and 32 steps respectively. That result shows why an accuracy drop should not automatically be inferred from decreasing energy: classifier, scale, and training method matter.

Fixing the seed controls initialization and dropout, but not necessarily the order of atomic sums in CUDA. Deep networks with sensitive optimization can yield a different selected epoch and accuracy on repetition. To study robustness, repeat with several seeds, record device and PyTorch version, and try the deterministic-algorithm mode supported by your environment. A paired comparison should retain the same split and seeds for each alternative and reserve independent evaluation for the final decision.

Exercises

Proof
Prove: Justify the limit of powers of S for an undirected graph with nonnegative weights and a positive loop at each node.
0
S is symmetric and every degree with loops is positive.

Step 1 of 2. Why is no eigenvalue less than −1?

Numeric
In an undirected three-node chain, add a loop to each node. With x=(1,2,3), calculate the central component of Sx.
Quiz
Two means differ by 0.5 percentage points and each model has seed-to-seed deviation of 0.7 points. What conclusion is defensible?
Code
Implement dirichlet_energy(x, edge_index), with x of shape (N,F) and undirected edges represented in both directions. Return symmetric edge energy divided by the squared norm of x. Isolated nodes contribute zero; return zero for zero x.
import numpy as np
def dirichlet_energy(x, edge_index):
  ...
Shift+Enter to run
Key idea
GCN applies degree-weighted messages with loops. Spectral convergence explains a tendency of linear propagation, while classification and mitigations require experiments with explicit splits and budgets.