GCN: from spectral networks to graph convolution
Derive GCN propagation from spectral and Chebyshev filters, study renormalization and oversmoothing, and compare GCN with decoupled and learnable propagation.
After this lesson you can
- Derive the GCN propagation rule from first-order Chebyshev filters and renormalization.
- Analyze how renormalization changes the propagation spectrum.
- Implement a two-layer GCN with manual forward and backward passes and evaluate on Cora.
- Interpret the signed propagation response and its smoothing behavior.
- Explain SGC, APPNP and decoupled propagation.
- Compare learnable spectral filters in homophilous and heterophilous graphs.
Before you start
- 25Chebyshev filter approximationSpectral graph filterMessage passing neural network frameworkMessage passing as sparse matrix multiplicationPersonalized PageRank and the push algorithmLabel propagation
- 15Dropout
- 06Weight decay versus L2 regularization
- 13Early stopping as regularizationValidation-based model selection guarantee
- 11Softmax (multinomial logistic) regressionWhat cross-validation estimates and its variance
Learning with a few labels
In a paper network we want to classify documents from their words and citations. There may be thousands of nodes and only a few training labels. A GCN shares weights between nodes and combines features with those of neighbors. Validation and test node topology and features are used during propagation: this is a transductive protocol. Their labels remain outside training loss, and the test set must not select epochs or hyperparameters.
A spectral network represents a signal in the Laplacian eigenvector basis and applies . Learning one free parameter per eigenvalue can make evaluating or storing the basis expensive, leaves the filter unrestricted to nearby neighbors, and does not automatically transfer a table fitted to one graph’s spectrum to another. Eigenvectors are also ambiguous within repeated eigenspaces. Bruna and colleagues introduced spectral networks; subsequent constraints seek locality and scalability.
Convolution here has a spectral meaning: multiplying coefficients in a generalized Fourier basis. On a regular grid, translation structure recovers ordinary convolution. An irregular graph generally has no unique translation taking each node to another while preserving edges. The analogy helps construct filters but does not imply the same ordered spatial kernel exists around every node.
A filter defined by an arbitrary value at each frequency can produce a dense matrix . A perturbation at one node can affect distant nodes in one step. When two eigenvalues coincide, assigning different values to chosen vectors in that eigenspace makes the result basis-dependent. A scalar function of the Laplacian assigns the same value to every vector in the eigenspace and is independent of that rotation. Polynomials avoid storing the basis and give a direct notion of hop reach.
From Chebyshev to message passing
Defferrard and colleagues’ ChebNet parameterizes the filter using Chebyshev polynomials of the rescaled Laplacian. A degree- polynomial uses information only at graph distance at most and is evaluated recursively without diagonalization. Some libraries call the number of terms, so maximum degree is : check the convention before comparing configurations.
For normalized Laplacian and approximation , rescaling gives . Keeping degree-zero and degree-one terms and tying their coefficients as gives
Kipf and Welling replace that operator with the renormalized matrix , where is calculated after adding a unit-weight self-loop to each node. This substitution is not an algebraic equality: it changes degrees and generally eigenvectors too. A GCN layer takes the form
The second expression is the same rule viewed as message passing: each edge sends a transformed representation and the receiver sums using symmetric weights. Normalization here is defined for an undirected graph with nonnegative weights. For a directed graph, decide what source and destination represent and which normalization applies; symmetrizing is a modeling choice, not an identity.
For an isolated node, adding its self-loop gives degree one and preserves its own representation. For an edge between unequal-degree nodes, is not a uniform average over the receiver’s neighbors: its weight and both sender and receiver degrees matter. In a sparse implementation, the operation can be associated as or ; they are equal in exact arithmetic, but cost and memory depend on channel sizes and sparsity. Backward uses transposes in reverse order. Symmetry simplifies this expression, but retaining the explicit transpose helps catch errors when testing directed operators.
Why the scale changes
The renormalization trick prevents eigenvalue 2 of from multiplying a component by when stacking linear steps. On an undirected graph with positive self-loops, and are positive semidefinite. For the latter, the quadratic form is a sum of squares of weighted by edges; positive self-loops prevent it being zero for a nonzero vector. Thus eigenvalues of lie in . Moreover ; each connected component contributes one eigenvalue-1 mode.
The bound controls isolated linear propagation in Euclidean norm. A trainable network includes matrices , activations and possible biases: normalizing alone does not guarantee stability of the whole network. Recomputing degrees from the loop-free matrix or adding duplicate loops produces a different operation.
In the example cycle each node has degree 2 before and 3 after adding loops. Thus the operators are and : the constant mode changes from multiplication by 2 to multiplication by 1. Simply replacing by in the numerator while retaining old degrees is insufficient. On an irregular graph new degrees change differently at each endpoint, making the relationship less trivial. A zero-weight edge adds no connection; a positive-weight self-loop contributes to degree.
Which frequencies remain
If , an eigenvector of with eigenvalue is multiplied by in one linear step and by in steps. The signed response decreases in for one step, but its magnitude does not decrease monotonically throughout : for a negative response reappears and can have considerable magnitude. When is even, that response becomes positive. Low-pass language is a useful interpretation of smoothing bias, not a claim that every high frequency always has lower gain than every intermediate frequency.
The subgraph also includes 70 test nodes and 100 additional neighbors; validation and test selection is conditioned on being training neighbors and is not a uniform sample. It has 68 components, including isolates before adding loops. SVD is fitted on all Cora features without labels and the subgraph is standardized transductively; each classifier standardizes inputs using training nodes. Precomputed results use logistic regression, a fixed seed and the same graph, not a hand-drawn curve. Coordinates come from a force layout, not a trained embedding. The preparation script reads original Cora files downloaded by Planetoid into the lab’s temporary folder; it requires NumPy, SciPy, scikit-learn and NetworkX and writes reproducible JSON.
In a connected component with loops, powers of converge to the projector onto its eigenvalue-1 mode. Representations eventually become dominated by that mode, weighted by ; they do not necessarily become identical row by row. This explains one form of oversmoothing. Label propagation also uses structure, but propagating a label matrix and training a GCN with features are different procedures; equivalence requires additional assumptions.
The distinction between signed response and magnitude appears in two example frequencies: for the one-layer factor is , whereas for it is . The second signal changes sign but its magnitude decreases less in that step. After four steps the factors are and , both positive. Loops guarantee nonstationary modes have magnitude below one in a connected component, but rates can differ greatly. The graph’s actual spectrum, not only the theoretical interval, determines which modes are present.
With several components, each retains its own stationary mode. A graph with many isolates can preserve information per component even without exchange between them; interpret the reduced figure together with its 68 components. In a trained GCN, intermediate matrices and activations make this linear account a guide rather than a complete description of the network. An accuracy drop after more propagation steps can have several causes and requires evaluation on appropriate splits.
The button runs up to 60 epochs of full-batch gradient descent; pause or change model to restart. The 140 training labels belong to the public split, but induced subgraph and feature reduction change the problem: do not directly compare accuracy with published full-Cora results. The 2D projection rescales across epochs and can hide variation in other dimensions. Displayed loss is calculated before each epoch’s update.
Decoupling transformation and propagation
Decoupled propagation separates these steps. SGC removes intermediate nonlinearities and combines linear weights: for steps it calculates and fits a linear classifier. Reusing propagation is cheaper when graph and features do not change. It can work well when neighbor information and smoothing suit the task; in heterophilous graphs, where different labels tend to connect, repeated averaging can erase discriminative information.
APPNP first obtains predictions with a network, then iterates , . Restart always mixes in the initial prediction; and step count control the tradeoff between context and retention. This is a finite approximation to PageRank-like propagation, not equivalent to training a GCN with a nonlinearity at each hop.
If nonlinearities and biases between layers are removed, : propagation can be calculated once and weights combined. With ReLU between the layers, the equality generally fails because activation depends on each node and channel. SGC is a simplified architecture rather than an exact alternative implementation of every trained GCN. Similarly, increasing in SGC changes the fixed filter; it does not automatically add nonlinear parameters.
Learnable spectral filters extend the family: GPR-GNN learns coefficients of different propagation powers, and BernNet uses a Bernstein polynomial basis. They can represent responses a fixed power of cannot, including behavior useful for heterophily. More flexibility also requires validation and does not guarantee better results on every graph.
Lab: GCN and manual backward
We implement normalization, the layer and its adjoints; then a two-layer network with ReLU, hidden-layer dropout, masked cross-entropy and Adam. The normalization function treats binary unweighted edges: it removes the existing diagonal, turns nonzero edges into ones and adds exactly one loop per node. The Pyodide example uses a small synthetic graph to keep each cell under five seconds. Ten seeds on full Cora are run locally with the same algorithm and reported separately: the small example is not presented as benchmark reproduction.
For and output gradient , the chain rule gives and . In the full network, loss is calculated only on training indices, so logit gradients are zero in other rows. This does not make other nodes invisible: their features contribute to neighbor sums. Dropout uses a random training mask and usual inverse scaling; it is disabled for validation and test. Finite differences run without dropout to compare a deterministic function.
import numpy as np
from scipy import sparse
def normalized_adjacency(A):
A=sparse.csr_matrix(A,dtype=np.float64).copy(); A.setdiag(0); A.eliminate_zeros(); A.data[:]=1
A=A+sparse.eye(A.shape[0],format='csr'); d=np.asarray(A.sum(axis=1)).ravel(); D=sparse.diags(d**-.5)
return (D@A@D).tocsr()
def gcn_forward(S,X,W):
SX=S@X
return SX@W,(S,X,W,SX)
def gcn_backward(cache,grad):
S,X,W,SX=cache
return S.T@(grad@W.T), SX.T@grad
def init_params(in_dim,hidden,out_dim,seed):
rng=np.random.default_rng(seed)
return [rng.normal(0,np.sqrt(2/in_dim),(in_dim,hidden)),np.zeros(hidden),rng.normal(0,np.sqrt(2/hidden),(hidden,out_dim)),np.zeros(out_dim)]
def loss_grad(S,SX,y,indices,params,rng=None,dropout=0.,weight_decay=0.):
W1,b1,W2,b2=params; pre=SX@W1+b1; H=np.maximum(pre,0)
mask=np.ones_like(H) if dropout==0 else (rng.random(H.shape)>=dropout)/(1-dropout)
H*=mask; SH=S@H; Z=SH@W2+b2
logits=Z[indices]; shift=logits-logits.max(axis=1,keepdims=True); p=np.exp(shift); p/=p.sum(axis=1,keepdims=True)
loss=-np.log(np.maximum(p[np.arange(len(indices)),y[indices]],1e-15)).mean()+.5*weight_decay*np.sum(W1*W1)
p[np.arange(len(indices)),y[indices]]-=1; p/=len(indices); G=np.zeros_like(Z); G[indices]=p
gW2=SH.T@G; gb2=G.sum(axis=0); delta=(S.T@(G@W2.T))*mask*(pre>0)
gW1=SX.T@delta+weight_decay*W1; gb1=delta.sum(axis=0)
return float(loss),[gW1,gb1,gW2,gb2]
def scores(S,SX,params):
W1,b1,W2,b2=params; H=np.maximum(SX@W1+b1,0)
return (S@H)@W2+b2
def fit(S,X,y,train,val,seed,max_epochs=200,patience=30):
SX=S@X; params=init_params(X.shape[1],16,int(y[train].max())+1,seed); rng=np.random.default_rng(100+seed)
m=[np.zeros_like(p) for p in params]; v=[np.zeros_like(p) for p in params]; best=float('inf'); state=None; best_epoch=0; stale=0
for t in range(1,max_epochs+1):
_,g=loss_grad(S,SX,y,train,params,rng,.5,.0005)
for i,p in enumerate(params):
m[i]=.9*m[i]+.1*g[i]; v[i]=.999*v[i]+.001*g[i]**2
p-=.01*(m[i]/(1-.9**t))/(np.sqrt(v[i]/(1-.999**t))+1e-8)
val_loss,_=loss_grad(S,SX,y,val,params)
if val_loss<best-1e-5: best=val_loss; state=[p.copy() for p in params]; best_epoch=t; stale=0
else: stale+=1
if stale>=patience: break
return state,best_epoch,bestrng=np.random.default_rng(11); A=np.array([[0,1,1,0],[1,0,1,0],[1,1,0,1],[0,0,1,0]],float); S=normalized_adjacency(A); X=rng.normal(size=(4,3)); W=rng.normal(size=(3,2)); G=rng.normal(size=(4,2)); O,cache=gcn_forward(S,X,W); gx,gw=gcn_backward(cache,G)
def objective(): return float((gcn_forward(S,X,W)[0]*G).sum())
maxerr=0.
for V,grad in ((X,gx),(W,gw)):
for ix in np.ndindex(V.shape):
v=V[ix]; V[ix]=v+1e-6; plus=objective(); V[ix]=v-1e-6; minus=objective(); V[ix]=v; maxerr=max(maxerr,abs((plus-minus)/2e-6-grad[ix]))
print('capa error máximo',maxerr); assert maxerr<1e-7
params=init_params(3,4,2,9); y=np.array([0,1,0,1]); ids=np.array([0,1,2]); SX=S@X; loss,grads=loss_grad(S,SX,y,ids,params)
maxerr=0.
for p,grad in zip(params,grads):
for ix in np.ndindex(p.shape):
v=p[ix]; p[ix]=v+1e-6; plus=loss_grad(S,SX,y,ids,params)[0]; p[ix]=v-1e-6; minus=loss_grad(S,SX,y,ids,params)[0]; p[ix]=v; maxerr=max(maxerr,abs((plus-minus)/2e-6-grad[ix]))
print('red completa error máximo',maxerr); assert maxerr<1e-7rng=np.random.default_rng(7); n=30; labels=np.r_[np.zeros(15,dtype=int),np.ones(15,dtype=int)]; A=np.zeros((n,n))
for i in range(n):
for j in range(i+1,n):
if rng.random()<(.45 if labels[i]==labels[j] else .05): A[i,j]=A[j,i]=1
X=rng.normal(size=(n,4))*.3+np.column_stack([2*labels-1,np.zeros((n,3))]); S=normalized_adjacency(A); train=np.array([0,1,2,15,16,17]); val=np.array([3,4,18,19]); test=np.array([i for i in range(n) if i not in set(train)|set(val)])
for seed in (0,1):
p,epoch,best=fit(S,X,labels,train,val,seed,max_epochs=60,patience=12); pred=scores(S,S@X,p).argmax(1)
print(seed,epoch,round(best,4),round(float(np.mean(pred[test]==labels[test])),4))Full Cora: ten seeds
The semi-supervised node protocol uses Planetoid’s public split: 140 training, 500 validation and 1000 test nodes. Reconstructing data requires official Planetoid files, NumPy and SciPy; the local cell gets data through PyG then uses only the NumPy/SciPy computation above. Feature rows are normalized by their sum; loops are added once. Epoch selection minimizes validation loss; test is evaluated only with selected weights. The t interval describes variation across seeds on this same split, not uncertainty over other splits or graphs.
import tempfile
from pathlib import Path
from scipy import stats
from torch_geometric.datasets import Planetoid
root=Path(tempfile.gettempdir())/'oryon-graph-datasets'/'cora'
data=Planetoid(str(root),'Cora',split='public')[0]
X=sparse.csr_matrix(data.x.numpy(),dtype=float); totals=np.asarray(X.sum(axis=1)).ravel(); X=sparse.diags(1/np.maximum(totals,1))@X
y=data.y.numpy(); edge=data.edge_index.numpy(); A=sparse.coo_matrix((np.ones(edge.shape[1]),(edge[0],edge[1])),shape=(len(y),len(y))); S=normalized_adjacency(A)
train=np.flatnonzero(data.train_mask.numpy()); val=np.flatnonzero(data.val_mask.numpy()); test=np.flatnonzero(data.test_mask.numpy())
print('datos',len(y),X.shape,'aristas dirigidas',edge.shape[1],'train/val/test',len(train),len(val),len(test))
acc=[]; epochs=[]
for seed in range(10):
params,epoch,best=fit(S,X,y,train,val,seed,max_epochs=200,patience=30)
pred=scores(S,S@X,params).argmax(axis=1); accuracy=float(np.mean(pred[test]==y[test])); acc.append(accuracy); epochs.append(epoch)
print('semilla',seed,'época elegida',epoch,'exactitud test',round(accuracy,4))
mean=np.mean(acc); sd=np.std(acc,ddof=1); half=stats.t.ppf(.975,len(acc)-1)*sd/np.sqrt(len(acc))
print('media',round(mean,4),'desviación',round(sd,4),'IC t 95%',round(mean-half,4),round(mean+half,4))npm run lab and open the connection link.In one ten-seed execution, test accuracies were 0.806, 0.814, 0.808, 0.804, 0.815, 0.816, 0.810, 0.814, 0.814 and 0.809. Mean was 0.8110, sample standard deviation 0.0042, and the 95% t interval for that mean approximately [0.8080, 0.8140]. Two runs reached the maximum epoch of 200, so their optimal epoch may lie outside the budget. The GCN paper reports a mean of 81.5% on Cora across 100 initializations with its configuration; this execution is similar in scale but uses specific initialization, dropout and selection choices and does not prove identical reproduction.
Local lab: operators and splits
PyTorch Geometric layers implement variants with specific loop, normalization and bias conventions. The next experiment states data, splits, device, budget, time and memory; it does not use test to select epochs. By default it runs three epochs with two seeds and compares the official split with an unstratified random split of the same sizes. The latter changes with seed, so its deviation combines initialization and split variation. Validation is held out but not used to fit a model under that fixed budget. ORYON_GCN_DATASETS limits comma-separated names and ORYON_GCN_EPOCHS increases epochs. For ogbn-arxiv citations are explicitly symmetrized and the official temporal split retained when selected. Downloading the dataset can require considerable space and time. Interpret short results as an execution diagnostic rather than an exhaustive performance comparison.
In ogbn-arxiv, the official split separates papers by year; this experiment remains transductive because the full structure and later-paper features are visible during training, though their labels do not enter loss. It does not simulate strict historical availability. This environment’s OGB loader stores PyG objects in a processed file. For recent PyTorch, the specific required PyG classes are enabled only during loading; use data files obtained from a trusted source. The reported peak is memory allocated by the CUDA process, including data and model, and times depend on machine and shared load.
import os,time,tempfile
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.nn import GCNConv,ChebConv,SGConv,APPNP
from torch_geometric.utils import to_undirected
from torch_geometric.data import Data
from torch_geometric.data.data import DataEdgeAttr,DataTensorAttr
from torch_geometric.data.storage import GlobalStorage
from ogb.nodeproppred import PygNodePropPredDataset
root=Path(os.environ.get('ORYON_GRAPH_DATA',str(Path(tempfile.gettempdir())/'oryon-graph-datasets')))
names=os.environ.get('ORYON_GCN_DATASETS','Cora,CiteSeer,PubMed,ogbn-arxiv').split(',')
epochs=int(os.environ.get('ORYON_GCN_EPOCHS','3')); seeds=(0,1)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('dispositivo',device,'épocas',epochs,'semillas',seeds)
class Model(nn.Module):
def __init__(self,d,c,kind):
super().__init__(); self.kind=kind
if kind=='GCN': self.a=GCNConv(d,16); self.b=GCNConv(16,c)
elif kind.startswith('Cheb'):
k=int(kind[-1]); self.a=ChebConv(d,16,K=k); self.b=ChebConv(16,c,K=k)
elif kind=='SGC': self.a=SGConv(d,c,K=2,cached=True)
else: self.a=nn.Linear(d,16); self.b=nn.Linear(16,c); self.prop=APPNP(K=10,alpha=.1)
def forward(self,x,edge):
if self.kind=='SGC': return self.a(x,edge)
if self.kind=='APPNP':
z=F.dropout(F.relu(self.a(x)),p=.5,training=self.training); return self.prop(self.b(z),edge)
z=F.dropout(F.relu(self.a(x,edge)),p=.5,training=self.training); return self.b(z,edge)
def load(name):
if name=='ogbn-arxiv':
with torch.serialization.safe_globals([Data,DataEdgeAttr,DataTensorAttr,GlobalStorage]):
dataset=PygNodePropPredDataset(name=name,root=str(root)); data=dataset[0]; data.y=data.y.view(-1); split=dataset.get_idx_split()
masks={k:split[k] for k in ('train','valid','test')}; data.edge_index=to_undirected(data.edge_index,num_nodes=data.num_nodes)
else:
data=Planetoid(str(root/name),name,split='public')[0]; masks={'train':data.train_mask.nonzero().view(-1),'valid':data.val_mask.nonzero().view(-1),'test':data.test_mask.nonzero().view(-1)}
data.x=data.x/data.x.sum(1,keepdim=True).clamp_min(1)
return data,masks
def random_split(data,official,seed):
gen=torch.Generator().manual_seed(seed+123); order=torch.randperm(data.num_nodes,generator=gen)
a,b,c=len(official['train']),len(official['valid']),len(official['test']); return {'train':order[:a],'valid':order[a:a+b],'test':order[a+b:a+b+c]}
def run(data,masks,kind,seed):
torch.manual_seed(seed); torch.cuda.manual_seed_all(seed)
model=Model(data.num_features,int(data.y.max())+1,kind).to(device); opt=torch.optim.Adam(model.parameters(),lr=.01,weight_decay=.0005)
train=masks['train'].to(device); test=masks['test'].to(device)
if device.type=='cuda': torch.cuda.reset_peak_memory_stats(); torch.cuda.synchronize()
start=time.perf_counter()
for _ in range(epochs):
model.train(); opt.zero_grad(); logits=model(data.x,data.edge_index); loss=F.cross_entropy(logits[train],data.y[train]); loss.backward(); opt.step()
if device.type=='cuda': torch.cuda.synchronize()
duration=(time.perf_counter()-start)/epochs
model.eval()
with torch.no_grad(): pred=model(data.x,data.edge_index).argmax(1); accuracy=float((pred[test]==data.y[test]).float().mean())
memory=torch.cuda.max_memory_allocated()/1024**2 if device.type=='cuda' else 0.
return accuracy,duration,memory
for name in names:
data,official=load(name); print('datos',name,data.num_nodes,data.num_edges,'train/val/test',*(len(official[k]) for k in ('train','valid','test')),flush=True)
data=data.to(device)
for split in ('public','random'):
for kind in ('GCN','Cheb1','Cheb2','Cheb3','Cheb4','Cheb5','SGC','APPNP'):
results=[]
for seed in seeds:
masks=official if split=='public' else random_split(data,official,seed)
results.append(run(data,masks,kind,seed))
arr=np.array(results); print(name,split,kind,'test media/desv',round(arr[:,0].mean(),4),round(arr[:,0].std(ddof=1),4),'seg/época',round(arr[:,1].mean(),4),'pico MiB',round(arr[:,2].max(),1),flush=True)npm run lab and open the connection link.An RTX 3060 execution with three epochs and two seeds produced these test-accuracy means and sample standard deviations for the official split; the cell also prints Cheb1 through Cheb4, APPNP, the random split, times and memory.
| Dataset | GCN | Cheb5 | SGC |
|---|---|---|---|
| Cora | 0.3705 ± 0.0672 | 0.4575 ± 0.1407 | 0.5280 ± 0.1004 |
| CiteSeer | 0.3040 ± 0.1103 | 0.5125 ± 0.0219 | 0.4915 ± 0.0417 |
| PubMed | 0.5645 ± 0.0785 | 0.3730 ± 0.0113 | 0.6275 ± 0.0700 |
| ogbn-arxiv symmetrized | 0.1334 ± 0.1058 | 0.0862 ± 0.0374 | 0.1233 ± 0.0904 |
In that execution, ogbn-arxiv had 169 343 nodes and 2 315 598 directed edges after symmetrization; Cheb5 reached an allocated peak of 2982.3 MiB and mean 1.0427 s per epoch. Cora with GCN recorded 33.9 MiB and 0.265 s per epoch. These are timings from one shared-load execution; startup and contention especially affect such short measurements. Low accuracies reflect insufficient budget and do not justify choosing a method. Two seeds in particular do not characterize variability well, and a random split is not equivalent to a temporal split.
Exercises
Step 1 of 2. What is rescaled L, 2L/λmax−I, under the approximation?
Step 1 of 2. Which vector has eigenvalue 1?
def gcn_backward(cache, grad):
passKey ideas
SGC, APPNP and learnable filters separate or modify propagation and transformation. Choice depends on structure, features and a leakage-free evaluation protocol.