Module contents
Lesson 10 of 30Core 115 min

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

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 UU and applies Ugθ(Λ)U⊤xUg_\theta(\Lambda)U\T x. 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 Ug(Λ)U⊤Ug(\Lambda)U\T. 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-KK polynomial uses information only at graph distance at most KK and is evaluated recursively without diagonalization. Some libraries call KK the number of terms, so maximum degree is K−1K-1: check the convention before comparing configurations.

For normalized Laplacian L=I−D−1/2AD−1/2L=I-D^{-1/2}AD^{-1/2} and approximation λmax⁡≈2\lambda_{\max}\approx2, rescaling gives L~≈L−I=−D−1/2AD−1/2\tilde L\approx L-I=-D^{-1/2}AD^{-1/2}. Keeping degree-zero and degree-one terms and tying their coefficients as θ0=−θ1=θ\theta_0=-\theta_1=\theta gives

gθ∗x≈θ(I+D−1/2AD−1/2)x.g_\theta*x\approx \theta(I+D^{-1/2}AD^{-1/2})x.

Kipf and Welling replace that operator with the renormalized matrix A^=D~−1/2(A+I)D~−1/2\hat A=\tilde D^{-1/2}(A+I)\tilde D^{-1/2}, where D~\tilde D 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

H(ℓ+1)=σ(A^H(ℓ)W(ℓ)),hi′=σ(∑j∈N(i)∪{i}A~ijhjWd~id~j).H^{(\ell+1)}=\sigma(\hat A H^{(\ell)}W^{(\ell)}),\qquad h_i'=\sigma\left(\sum_{j\in N(i)\cup\{i\}}\frac{\tilde A_{ij}h_jW}{\sqrt{\tilde d_i\tilde d_j}}\right).

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, A~ij/d~id~j\tilde A_{ij}/\sqrt{\tilde d_i\tilde d_j} 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 A^(HW)\hat A(HW) or (A^H)W(\hat AH)W; 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 I+D−1/2AD−1/2I+D^{-1/2}AD^{-1/2} from multiplying a component by 2K2^K when stacking KK linear steps. On an undirected graph with positive self-loops, I−A^I-\hat A and I+A^I+\hat A are positive semidefinite. For the latter, the quadratic form is a sum of squares of xi/d~i+xj/d~jx_i/\sqrt{\tilde d_i}+x_j/\sqrt{\tilde d_j} weighted by edges; positive self-loops prevent it being zero for a nonzero vector. Thus eigenvalues of A^\hat A lie in (−1,1](-1,1]. Moreover A^D~1/21=D~1/21\hat A\tilde D^{1/2}\mathbf1=\tilde D^{1/2}\mathbf1; each connected component contributes one eigenvalue-1 mode.

InteractiveWhy renormalize
Operator eigenvalues-1012Signal norm (log₁₀ scale)5.8−0.4020 layersBlue: renormalizedOrange: unnormalized

Without loops: operator I + A/2. With loops: (I + A)/3. The plot represents the regular cycle, not every possible graph.

Operator
5
Spectral radius1.000
Norm after K layers0.534
Undirected six-node cycle. Both operators and actual propagation of a fixed signal are computed for up to 20 layers. Norm uses a logarithmic scale; the point corresponds to the selected operator and number of layers.

The bound controls isolated linear propagation in Euclidean norm. A trainable network includes matrices WW, activations and possible biases: normalizing A^\hat A 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 I+A/2I+A/2 and (I+A)/3(I+A)/3: the constant mode changes from multiplication by 2 to multiplication by 1. Simply replacing AA by A+IA+I 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 L~=I−A^\tilde L=I-\hat A, an eigenvector of L~\tilde L with eigenvalue λ\lambda is multiplied by 1−λ1-\lambda in one linear step and by (1−λ)K(1-\lambda)^K in KK steps. The signed response decreases in λ\lambda for one step, but its magnitude ∣1−λ∣|1-\lambda| does not decrease monotonically throughout [0,2][0,2]: for λ>1\lambda>1 a negative response reappears and can have considerable magnitude. When KK 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.

InteractiveGCN as a frequency filter
0λ = 21−1

Blue and orange indicate sign; intensity shows relative magnitude within each K. The curve shows signed response and points show actual subgraph frequencies. For even K, some high frequencies regain positive response.

2
Nodes380
Validation accuracy0.8000
Minimum response0.000
Real Cora subgraph: 380 nodes, 808 directed edges, 140 training labels and 70 validation nodes selected among training neighbors. Features are reduced to 16 dimensions by unlabeled SVD. The linear classifier was fitted independently for each K; validation is shown, not test.

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 A^\hat A converge to the projector onto its eigenvalue-1 mode. Representations eventually become dominated by that mode, weighted by d~i\sqrt{\tilde d_i}; 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 λ=0.5\lambda=0.5 the one-layer factor is 0.50.5, whereas for λ=1.8\lambda=1.8 it is −0.8-0.8. The second signal changes sign but its magnitude decreases less in that step. After four steps the factors are 0.540.5^4 and (−0.8)4(-0.8)^4, 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.

InteractiveTrain a GCN in the browser

Color: predicted class, not ground-truth label. The run uses 140 training labels; the subgraph and 16 reduced features are not the full Cora protocol.

Class 0Class 1Class 2Class 3Class 4Class 5Class 6

PCA projection of hidden activations, calculated in the current run. Each model restarts with a fixed seed; scales adapt to the projection.

Model
Epoch0
Training lossnot trained
Validation accuracy0.1571
A two-layer GCN, MLP or SGC is actually trained on the same reduced subgraph. Predictions color nodes and a PCA projection shows hidden activations or logits. Validation is observed; training never uses validation or test labels.

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 KK steps it calculates A^KX\hat A^K X 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 ZZ with a network, then iterates H(0)=ZH^{(0)}=Z, H(k+1)=(1−α)A^H(k)+αZH^{(k+1)}=(1-\alpha)\hat A H^{(k)}+\alpha Z. Restart always mixes in the initial prediction; α\alpha 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, A^(A^XW1)W2=A^2X(W1W2)\hat A(\hat AXW_1)W_2=\hat A^2X(W_1W_2): 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 KK 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 A^\hat A 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 Y=(SX)WY=(SX)W and output gradient GG, the chain rule gives ∇W=(SX)⊤G\nabla_W=(SX)\T G and ∇X=S⊤GW⊤\nabla_X=S\T GW\T. 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.

[ ]Normalization, network and manual optimizerBrowser
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,best
[ ]Check all gradientsBrowser
rng=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-7
[ ]Train on a synthetic graphBrowser
rng=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.

[ ]Ten seeds on CoraLocal GPU
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))
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

[ ]GCN, ChebNet, SGC and APPNPLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

DatasetGCNCheb5SGC
Cora0.3705 ± 0.06720.4575 ± 0.14070.5280 ± 0.1004
CiteSeer0.3040 ± 0.11030.5125 ± 0.02190.4915 ± 0.0417
PubMed0.5645 ± 0.07850.3730 ± 0.01130.6275 ± 0.0700
ogbn-arxiv symmetrized0.1334 ± 0.10580.0862 ± 0.03740.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

Proof
Prove: Derive the first-order GCN operator before renormalization.
0
L=I−D⁻¹ᐟ²AD⁻¹ᐟ² and λmax≈2.

Step 1 of 2. What is rescaled L, 2L/λmax−I, under the approximation?

Proof
Prove: Justify that eigenvalues of  lie in (−1,1] when each node has a positive self-loop.
0
The graph is undirected and its weights are nonnegative.

Step 1 of 2. Which vector has eigenvalue 1?

Numeric
A bias-free GCN has 1433 input features, 16 hidden channels and 7 classes. How many parameters are in its two weight matrices?
Numeric
With 2708 nodes and 10 556 directed edges, add 2708 loops. Using dense matrices for XW, associating each layer as (HW) then Â(HW), and counting two FLOPs per multiply-accumulate, approximately how many FLOPs does the forward pass of the 1433→16→7 layers use? Ignore activations, biases and degrees.
Quiz
Which conclusion is appropriate when comparing SGC with a GCN?
Code
Implement gcn_backward(cache, grad), where cache=(S,X,W,SX) comes from Y=(S@X)@W and grad has the shape of Y. Return gradients with respect to X and W; S may be sparse.
def gcn_backward(cache, grad):
  pass
Shift+Enter to run

Key ideas

Key idea
GCN combines shared transformation and normalized aggregation; renormalization changes the operator and bounds its linear spectrum, but does not turn the whole network into a fixed filter or guarantee extra depth helps.

SGC, APPNP and learnable filters separate or modify propagation and transformation. Choice depends on structure, features and a leakage-free evaluation protocol.