Implementing GCN in PyTorch Geometric
You'll learn: How to build and train a graph convolutional network using PyTorch Geometric for a node classification task.
The Core Idea
Now that you understand GCN theory—normalized message passing with neighborhood aggregation—it's time to implement it. PyTorch Geometric (PyG) provides ready-to-use GCN layers that handle all the mathematical details we've covered. You'll define a multi-layer GCN model, load graph data, and train it to classify nodes based on their features and neighborhood structure.
Building a GCN Model
In PyG, GCNConv implements a single graph convolutional layer. You stack multiple layers and add activation functions between them:
import torch
import torch.nn.functional as F
from torch_geometric.nn import GCNConv
class GCN(torch.nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels):
super().__init__()
self.conv1 = GCNConv(in_channels, hidden_channels)
self.conv2 = GCNConv(hidden_channels, out_channels)
def forward(self, x, edge_index):
# First GCN layer + activation
x = self.conv1(x, edge_index)
x = F.relu(x)
# Second GCN layer (no activation for output)
x = self.conv2(x, edge_index)
return x
Training on Node Classification
# Assume 'data' contains graph with node features and labels
model = GCN(in_channels=data.num_features, hidden_channels=16, out_channels=dataset.num_classes)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
model.train()
for epoch in range(200):
optimizer.zero_grad()
out = model(data.x, data.edge_index)
loss = F.cross_entropy(out[data.train_mask], data.y[data.train_mask])
loss.backward()
optimizer.step()
The model learns to predict node labels by aggregating information from neighbors through message passing layers.
Key Takeaway: PyTorch Geometric's GCNConv simplifies GCN implementation—you stack layers, pass node features and edge indices, and train like any PyTorch model using masked node subsets for classification.