Graph Neural Networks: GCN, GAT, and GraphSAGE
Most machine learning assumes data lives in a grid or a table: images in pixel arrays, transactions in rows. Many of the most valuable datasets in industry โ social networks, molecular structures, citation graphs, fraud rings, supply chains โ are graphs: sets of nodes connected by edges, with no natural ordering. Graph Neural Networks (GNNs) extend deep learning to this structure through a single powerful idea: message passing, where each node repeatedly gathers information from its neighbors and updates its own representation.
By the end of this lesson you will understand why message passing works, how the three foundational architectures (GCN, GAT, GraphSAGE) differ in how they aggregate, how to build and train them in PyTorch Geometric, and how to apply them to the three canonical tasks โ node classification, link prediction, and graph classification. You will also learn the practical limits: oversmoothing, scalability, and the challenges of heterophilous graphs.
What You'll Learn
- 1Explain the message passing framework and derive GCN updates from first principles
- 2Implement GCN, GAT, and GraphSAGE for node classification in PyTorch Geometric
- 3Design a link predictor with an encoder-decoder architecture
- 4Diagnose oversmoothing and choose architectures for homophilous vs heterophilous graphs
Prerequisites
- !PyTorch fundamentals: tensors, autograd, optimizers
- !Basic understanding of convolutional networks
- !Comfort with NumPy
Why graphs need a different architecture
A standard neural network expects fixed-size inputs with a defined order. A graph violates both assumptions: it has a variable number of nodes, no canonical ordering, and connections that carry structural meaning. Flattening a graph into a feature matrix throws away the edges, which are often the most informative part โ knowing that two bank accounts share a device is more predictive than either account's individual features.
The GNN solution is permutation-equivariant processing: the network treats all nodes with the same shared function, aggregating over each node's neighborhood. Swapping the indices of two nodes swaps their outputs identically, so the model never depends on arbitrary labeling. This is the graph analogue of how a convolution kernel slides over every position in an image.
The message passing framework
Every GNN can be decomposed into three steps per layer. First, each node produces a message from its current hidden state. Second, messages from all neighbors are aggregated with a permutation-invariant operator (sum, mean, or max). Third, the aggregated message is combined with the node's own state through an update function, typically a neural network.
Formally, at layer l the hidden state of node v is updated as:
h_v^(l+1) = UPDATE( h_v^(l), AGG( { MESSAGE(h_u^(l)) : u in N(v) } ) )
where N(v) is the neighbor set of v. Different architectures are different choices of MESSAGE, AGGREGATE, and UPDATE. GCN uses a degree-normalized mean; GAT learns attention weights over neighbors; GraphSAGE samples neighbors and concatenates. Understanding this decomposition is the key to reading any new GNN paper quickly.
Building graph data in PyTorch Geometric
PyTorch Geometric (PyG) represents a graph as a Data object holding node features x, an edge list edge_index in COO format (2 ร E tensor of source and target indices), optional node labels y, and boolean masks for train/test splits.
import torch
import torch.nn.functional as F
from torch_geometric.data import Data
from torch_geometric.nn import GCNConv, GATConv, SAGEConv, global_mean_pool
# Karate-club-style synthetic graph with community structure
torch.manual_seed(42)
num_nodes, num_features, num_classes = 100, 16, 3
x = torch.randn(num_nodes, num_features)
# Within-community edges create the homophily GNNs exploit
community = torch.randint(0, 4, (num_nodes,))
src, dst = [], []
for c in range(4):
members = (community == c).nonzero(as_tuple=True)[0]
for _ in range(60):
u, v = members[torch.randint(0, len(members), (2,))]
src += [u.item(), v.item()]
dst += [v.item(), u.item()]
edge_index = torch.tensor([src, dst], dtype=torch.long)
y = community % num_classes
train_mask = torch.zeros(num_nodes, dtype=torch.bool)
test_mask = torch.zeros(num_nodes, dtype=torch.bool)
train_mask[:70] = True
test_mask[70:] = True
data = Data(x=x, edge_index=edge_index, y=y,
train_mask=train_mask, test_mask=test_mask)
print(data) # 100 nodes, ~480 directed edges, 16 features
Notice the edge index is directed: an undirected edge (u, v) must be stored as two directed edges (u โ v) and (v โ u). Forgetting the reverse edge is one of the most common bugs when building graphs from scratch.
Graph convolutional networks
GCN collapses the message passing equations into a single normalized adjacency multiplication. The layer computes H' = ฯ(Dฬโปยนแยฒ ร Dฬแตแยฒ H W) where ร = A + I adds self-loops and Dฬ is the diagonal degree matrix. Intuitively, each node takes a weighted average of its own and its neighbors' features, then applies a linear transform.
class GCN(torch.nn.Module):
def __init__(self, in_dim, hidden_dim, out_dim):
super().__init__()
self.conv1 = GCNConv(in_dim, hidden_dim)
self.conv2 = GCNConv(hidden_dim, hidden_dim)
self.conv3 = GCNConv(hidden_dim, out_dim)
def forward(self, x, edge_index):
x = F.relu(self.conv1(x, edge_index))
x = F.dropout(x, p=0.5, training=self.training)
x = F.relu(self.conv2(x, edge_index))
return self.conv3(x, edge_index)
model = GCN(num_features, 32, num_classes)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
def train(model, data):
model.train()
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()
return loss.item()
@torch.no_grad()
def evaluate(model, data):
model.eval()
pred = model(data.x, data.edge_index).argmax(dim=1)
accs = []
for mask in (data.train_mask, data.test_mask):
accs.append((pred[mask] == data.y[mask]).float().mean().item())
return accs
for epoch in range(1, 201):
loss = train(model, data)
if epoch % 50 == 0:
tr, te = evaluate(model, data)
print(f"Epoch {epoch:03d} loss={loss:.4f} train={tr:.3f} test={te:.3f}")
The weight decay term is not optional garnish โ it acts as a mild regularizer that slows the oversmoothing discussed below. Two or three layers is the practical sweet spot for most homophilous graphs.
Graph attention networks
GCN weights neighbors by degree, which is static and structure-blind. GAT learns the weights: for each edge it computes an attention coefficient from the pair of node embeddings, softmaxes over the neighborhood, and uses those coefficients as aggregation weights. Multi-head attention runs several independent attention functions in parallel and concatenates (or averages) their outputs.
class GAT(torch.nn.Module):
def __init__(self, in_dim, hidden_dim, out_dim, heads=4):
super().__init__()
self.conv1 = GATConv(in_dim, hidden_dim, heads=heads, concat=True)
self.conv2 = GATConv(hidden_dim * heads, hidden_dim, heads=heads, concat=True)
self.conv3 = GATConv(hidden_dim * heads, out_dim, heads=1, concat=False)
def forward(self, x, edge_index):
x = F.elu(self.conv1(x, edge_index))
x = F.dropout(x, p=0.5, training=self.training)
x = F.elu(self.conv2(x, edge_index))
return self.conv3(x, edge_index)
gat = GAT(num_features, 8, num_classes, heads=4)
n_params = sum(p.numel() for p in gat.parameters())
print(f"GAT parameter count: {n_params:,}")
Attention is genuinely useful when some neighbors are far more informative than others โ fraud detection, where most transactions are benign but a few are suspicious, is a canonical case. The cost is roughly heads ร the compute of a GCN layer, so start with GCN and graduate to GAT only when the validation gain justifies it.
GraphSAGE: sampling for scale
Full-batch training works on a citation graph with 30k nodes; it collapses on a social graph with 100 million. GraphSAGE addresses this by sampling: for each target node, draw a fixed number of neighbors per layer, aggregate over the sample, and train with stochastic mini-batches. Crucially, GraphSAGE learns aggregation functions (mean, LSTM, pooling) rather than fixed normalized weights, which lets it inductively produce embeddings for nodes never seen in training โ essential when new users and items arrive daily.
class GraphSAGE(torch.nn.Module):
def __init__(self, in_dim, hidden_dim, out_dim):
super().__init__()
self.conv1 = SAGEConv(in_dim, hidden_dim)
self.conv2 = SAGEConv(hidden_dim, hidden_dim)
self.conv3 = SAGEConv(hidden_dim, out_dim)
def forward(self, x, edge_index):
x = F.relu(self.conv1(x, edge_index))
x = F.relu(self.conv2(x, edge_index))
return self.conv3(x, edge_index)
sage = GraphSAGE(num_features, 32, num_classes)
# Mini-batch neighbor sampling for large graphs
from torch_geometric.loader import NeighborLoader
loader = NeighborLoader(data, num_neighbors=[15, 10], batch_size=64,
input_nodes=data.train_mask)
batch = next(iter(loader))
print(f"Sampled subgraph: {batch.num_nodes} nodes, {batch.num_edges} edges")
The num_neighbors argument controls the fan-out per layer. Two layers with [15, 10] means each node sees up to 15 first-hop and 10 second-hop neighbors โ a compute budget you can tune against accuracy.
Link prediction and graph classification
Node classification labels existing nodes; link prediction guesses missing or future edges. The standard recipe is an encoder-decoder: a GNN encodes all nodes into embeddings, and a decoder scores edge pairs, usually by dot product or an MLP on concatenated embeddings.
class LinkPredictor(torch.nn.Module):
def __init__(self, in_dim, hidden_dim):
super().__init__()
self.encoder = GCNConv(in_dim, hidden_dim)
self.decoder = torch.nn.Sequential(
torch.nn.Linear(hidden_dim * 2, hidden_dim),
torch.nn.ReLU(),
torch.nn.Linear(hidden_dim, 1),
)
def encode(self, x, edge_index):
return F.relu(self.encoder(x, edge_index))
def decode(self, z, edge_label_index):
src, dst = edge_label_index
return torch.sigmoid(self.decoder(torch.cat([z[src], z[dst]], dim=1)))
# Train/test split over edges, with negative samples as non-edges
pos_edge = edge_index
perm = torch.randperm(pos_edge.size(1))
train_pos = pos_edge[:, perm[:int(0.8 * perm.size(0))]]
test_pos = pos_edge[:, perm[int(0.8 * perm.size(0)):]]
link_model = LinkPredictor(num_features, 32)
z = link_model.encode(x, edge_index)
scores = link_model.decode(z, train_pos)
print(f"Predicted edge probabilities: shape {scores.shape}")
Graph-level classification pools node embeddings into a single vector per graph โ global_mean_pool, global_max_pool, or attention pooling โ before a final linear layer. This is how molecular property prediction works: atoms are nodes, bonds are edges, and the pooled embedding predicts solubility or toxicity.
Choosing an architecture
| Architecture | Aggregation | Inductive? | Best for | Main cost |
|---|---|---|---|---|
| GCN | Degree-normalized mean | No (transductive) | Homophilous citation/knowledge graphs | Oversmoothing in deep stacks |
| GAT | Learned attention | No | Graphs with informative vs noisy neighbors | Memory for attention coefficients |
| GraphSAGE | Sampled mean/LSTM/max | Yes | Huge, evolving graphs (social, e-commerce) | Sampling variance |
| GIN | Sum + MLP (theory-maximal) | Yes | Graph classification benchmarks | Sensitivity to degree scale |
For a first project on a static, reasonably homophilous graph, GCN is the right default. Reach for GraphSAGE the moment new nodes appear after training. Add GAT when you have reason to believe neighbor importance varies widely and you can afford the compute.
Production pitfalls and oversmoothing
After stacking many GCN layers, all node embeddings converge toward the same vector โ oversmoothing. The graph's distinct structure is literally averaged away. Symptoms include training accuracy plateauing near a naive baseline and embeddings from different classes becoming hard to separate. Remedies include skip connections (JK-Net style), initial residual connections, dropping edges during training (DropEdge), and simply keeping the stack shallow.
The second production trap is heterophily: graphs where connected nodes tend to have different labels (molecule atoms bonded to different elements, fraud rings deliberately mimicking normal behavior). Message passing assumes neighbors share information; with heterophily it actively injects noise. Diagnose it by measuring label agreement among edges versus random pairs; if agreement is near chance, vanilla GCN will underperform MLPs on node features alone.
Common Mistakes
Storing undirected edges as a single directed pair, then wondering why GCN performance is poor
Fix: Always add both (u, v) and (v, u) to edge_index for undirected graphs โ GCNConv aggregates over directed edges only.
Stacking 6+ GCN layers hoping for larger receptive fields
Fix: Three layers is usually the ceiling; use skip connections or GraphSAGE sampling if you need longer-range information.
Applying GNNs to heterophilous graphs without a baseline
Fix: Train a simple MLP on node features as a sanity check; if the MLP wins, consider heterophily-specific architectures or feature-only models.
Evaluating link prediction with random negative samples that include easy non-edges
Fix: Sample hard negatives (nodes that share neighbors but no edge) to measure realistic retrieval quality.
Best Practices
- Normalize adjacency (GCNConv does this for you) and add self-loops so isolated nodes keep their features
- Log the number of parameters and training time per epoch early โ GAT with many heads grows fast
- Use train/val/test masks on nodes; for links, split edges, not nodes, and exclude test edges from message passing
- Monitor embedding similarity across layers to catch oversmoothing before accuracy collapses
- For graphs larger than a million edges, move to NeighborLoader mini-batches from the first experiment
Interview Questions
Q1: Why is GraphSAGE inductive while vanilla GCN is transductive?
GCN learns a fixed weight per node through the full adjacency matrix, so unseen nodes have no learned state. GraphSAGE learns a shared aggregation function applied to sampled neighborhoods, which computes embeddings for any node given its features and edges.
Q2: What causes oversmoothing and how do you detect it?
Repeated neighbor averaging makes all embeddings converge to a common principal eigenvector. It appears as rising pairwise cosine similarity across layers and flat validation accuracy despite lower training loss.
Q3: How would you detect whether your graph is homophilous or heterophilous?
Compute the fraction of edges connecting nodes with the same label versus the base rate of that label. If edge label agreement is near the base rate or lower, the graph is heterophilous and vanilla message passing may hurt.
Key Takeaways
- GNNs learn through message passing: aggregate neighbor information, update the node state, repeat over layers
- GCN uses degree-normalized means, GAT learns attention weights, GraphSAGE samples neighbors for inductive, scalable training
- Three layers is the practical depth limit before oversmoothing degrades node embeddings
- Link prediction is encoder-decoder over node embeddings; graph classification pools node embeddings per graph
- Always benchmark against an MLP on node features โ if it wins, your graph structure is not helping