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.
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 without initial loops, and positive degrees for the spectral derivation. With , a first-order polynomial spectral filter is , where . Approximating by 2, . Tying coefficients as gives
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
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 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 , quadratic forms are sums of terms proportional to over directed edges. The first is nonnegative; the second is positive for every because each node has a positive loop. By symmetry, eigenvalues of lie in . The vector has eigenvalue 1 in each connected component. The spectral theorem thus gives convergence of 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:
For a mode of with eigenvalue , its contribution to is multiplied by . Since , energy does not increase with . 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 . In this run and . 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 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.
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-5npm 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.
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))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.
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)])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.
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 @ Xnpm 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.
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))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.
| Layers | Ordinary | Residual | PairNorm |
|---|---|---|---|
| 2 | 0.816 | 0.816 | 0.720 |
| 8 | 0.130 | 0.171 | 0.663 |
| 16 | 0.064 | 0.130 | 0.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 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
Step 1 of 2. Why is no eigenvalue less than −1?
import numpy as np
def dirichlet_energy(x, edge_index):
...