🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Graph Neural Networks — Learning on Graph Structures

Expert TopicsGraph ML🟢 Free Lesson

Advanced Topics

Graph Neural Networks — Learning from Connections and Relationships

Explore graph neural networks (GNNs) for learning on structured data with complex relationships. Perfect for social networks, molecular analysis, and recommendation systems.

  • Message Passing — How nodes aggregate information from neighbors

  • Graph Convolutional Networks — The foundational GNN architecture

  • Graph Attention Networks — Learning which connections matter most

"Everything is connected, and those connections are where the real learning happens."

Graph Neural Networks — Complete Guide

GNNs learn from graph-structured data — social networks, molecules, knowledge graphs.


Why GNNs?

Graph Data Structure

Graph-Structured Data ExamplesSocial NetworkABCDMoleculeOHHH₂O: Atoms=nodes, Bonds=edgesCitation NetworkP1P2P3P4Papers=nodes, Citations=edgesGraph Definition: G = (V, E)V = {v₁, v₂, ..., v₅} : Set of nodes (vertices)E = {(vᵢ, v⊥) : vᵢ, v⊥ ∈ V} : Set of edges (connections)Node features: X ∈ ℝ^{N×d}, Adjacency: A ∈ {0,1}^{N×N}

Message Passing

Where:

  • = node v's representation

  • = neighbors of v

Message Passing Visualization

Message Passing in GNNsStep 1: Send Messagesvu₁u₂u₃u₄m_u = MSG(h_u)Step 2: Aggregate Messagesva_v = AGGREGATE({m_u})e.g., sum, mean, maxΣ m_u / |N(v)|Step 3: Update Nodevh_v' = UPDATE(h_v, a_v)e.g., MLP + ReLUσ(W · [h_v || a_v])Process repeats for K layers: each node aggregates from K-hop neighborsMore layers = larger receptive field (but risk of over-smoothing)

GCN (Graph Convolutional Network)

GCN Architecture

Graph Convolutional Network (GCN) ArchitectureInput Graph1234X ∈ ℝ^{4×3}A ∈ {0,1}^{4×4}GCN Layer 1H' = σ(D̂^{-½}AD̂^{-½}HW)Aggregate neighborsTransform featuresApply activationGCN Layer 2H'' = σ(D̂^{-½}AD̂^{-½}H'W')2-hop aggregationRicher representationsWider receptive fieldOutputNode embeddingsH^{(K)} ∈ ℝ^{N×d}For node classificationor graph-level tasksEach layer: aggregate from 1-hop neighbors. K layers = K-hop neighborhood.

GNN Variants

GCN (Graph Convolutional Network):

  • Spectral-based

  • Averaging neighbor features

  • Simple and effective

GraphSAGE:

  • Sample neighbors (scalable)

  • Multiple aggregation functions

  • Inductive (works on new nodes)

GAT (Graph Attention Network):

  • Attention over neighbors

  • Learn which neighbors matter

  • More expressive than GCN

GNN Variants Comparison

GNN Variants: GCN vs GraphSAGE vs GATGCNGraph Convolutional Network• Fixed neighborhood• Mean aggregation• Transductive (needs full graph)• Spectral theory foundationBest for: Small-medium graphsComplexity: O(|E|·d²)GraphSAGESample and AggreGatE• Neighbor sampling• Mean/Max/LSTM aggregation• Inductive (new nodes ok)• Scalable to large graphsBest for: Large graphs, graphsComplexity: O(K·|S|·d²)GATGraph Attention Network• Attention over neighbors• Weighted aggregation• Multi-head attention• More expressive than GCNBest for: Heterogeneous graphsComplexity: O(|E|·d²)All share the message-passing paradigm but differ in aggregation strategy

Message Passing on a Four-Node Ring

Take the smallest graph worth computing by hand: a ring of four nodes A, B, C, D with edges A–B, B–C, C–D, D–A and a single scalar feature per node — A is 1, B is 2, C is 4, D is 8. With self-loops and mean aggregation, each layer replaces a node's value with the average of itself and its two neighbors.

NodeInputAfter layer 1After layer 2
A1.0003.6673.444
B2.0002.3333.556
C4.0004.6673.778
D8.0004.3334.222
Spread (max minus min)7.0002.3330.778

Two properties fall straight out of the table. The mean never moves: the average of all four nodes is 3.75 before the first layer and 3.75 after it, which is exactly what a normalized mean aggregator preserves. The spread, meanwhile, shrinks by roughly a factor of three every layer, so by layer eight all four nodes sit within rounding distance of 3.75 and a node classifier has nothing left to separate. That is over-smoothing with a number attached: the same aggregation that shares useful information also erases the differences that make nodes classifiable.

python
import numpy as np

# four-node ring A-B-C-D-A, scalar feature per node
edges = np.array([[0, 1, 1, 2, 2, 3, 3, 0],
                  [1, 0, 2, 1, 3, 2, 0, 3]])
x = np.array([1.0, 2.0, 4.0, 8.0])

adj = np.eye(x.shape[0])                      # self-loops keep a node's own feature
for src, dst in edges.T:
    adj[src, dst] = 1.0
norm = adj / adj.sum(axis=1)[:, None]         # mean over self plus neighbors

h = x.copy()
for layer in range(1, 9):
    h = norm @ h
    print(f"layer {layer:2d}  mean={h.mean():.3f}  spread={h.max() - h.min():.3f}")

Running that script shows the mean pinned at 3.75 while the spread falls from 7.000 to 2.333, 0.778, 0.259, and keeps dividing by three. Use it as a sanity check for any GNN implementation you write: if the mean drifts under mean aggregation, the normalization is wrong.

Aggregation Functions and How Deep to Go

The three aggregation operators answer different questions, and the choice is rarely revisited after the first baseline.

AggregationWhat it preservesUse it whenWatch out for
MeanScale and degree invarianceNeighbor features are comparable per hop, the usual defaultHub and leaf nodes become hard to tell apart after several layers
SumCardinality and subgraph sizeThe task depends on counting motifs or graph sizeValues explode on high-degree nodes without normalization
MaxPresence of a salient neighborOne strong neighbor carries the signalDiscards everything else and is unstable on sparse graphs
Attention (GAT)Learned per-edge weightsNeighbor reliability varies inside the same graphExtra parameters and memory, still only one hop per layer

Depth follows the same caution. Each layer widens the receptive field by one hop, so three layers let a node see three hops away — enough for a molecule where an atom's chemical role depends on neighbors three bonds distant. Most public node-classification benchmarks stop improving at two or three layers, and stacking further brings over-smoothing on one side and over-squashing on the other: information from a neighborhood that grows exponentially has to squeeze through a fixed-width vector, so distant evidence arrives as noise. Start with two layers and 64 hidden units, add a third only when the label demonstrably depends on three-hop structure, and when you need longer range reach for jump connections, residual links, or separate heads per hop instead of deeper stacks.

python
import torch
from torch_geometric.nn import GCNConv

class GCN(torch.nn.Module):
    def __init__(self, in_channels, hidden, num_classes):
        super().__init__()
        self.conv1 = GCNConv(in_channels, hidden)
        self.conv2 = GCNConv(hidden, hidden)
        self.head = torch.nn.Linear(hidden, num_classes)

    def forward(self, x, edge_index):
        x = torch.relu(self.conv1(x, edge_index))
        x = torch.nn.functional.dropout(x, p=0.5, training=self.training)
        x = self.conv2(x, edge_index)
        return self.head(x)

model = GCN(data.num_node_features, 64, data.num_classes)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)

for epoch in range(200):
    model.train()
    optimizer.zero_grad()
    logits = model(data.x, data.edge_index)
    loss = torch.nn.functional.cross_entropy(
        logits[data.train_mask], data.y[data.train_mask]
    )
    loss.backward()
    optimizer.step()

model.eval()
with torch.no_grad():
    pred = model(data.x, data.edge_index).argmax(dim=1)
    hit = (pred[data.test_mask] == data.y[data.test_mask]).sum()
print(f"test accuracy {int(hit) / int(data.test_mask.sum()):.3f}")

Scaling Training to Graphs That Do Not Fit in Memory

Full-batch training keeps the whole feature matrix and the normalized adjacency on the device. Four million edges at 256 dimensions is already about one billion multiply-adds for the aggregation term in a single forward pass, before the dense layers and before backpropagation, so transductive node classification at that size consumes a high-memory card on its own.

Neighbor sampling replaces the full neighborhood with a fixed fan-out. A two-layer model with fan-out list 10, 10 visits at most 100 sampled neighbors per node instead of every neighbor it has, which turns an unpredictable hub into a bounded mini-batch. Cluster-GCN partitions the graph and trains on one partition at a time; GraphSAINT samples a subgraph per step and rescales the loss to stay unbiased. The practical split: use full-batch below roughly a million edges, switch to sampling above it, and expect a low single-digit accuracy cost for the memory you get back.

The same choice decides whether a model is transductive or inductive. A GCN trained with every node of a fixed graph present at training time is transductive — it has no mechanism for a node that arrives tomorrow, because its embedding was never part of any message-passing step during training. GraphSAGE-style sampling aggregates features rather than stored embeddings, so unseen nodes get scored as soon as their features exist. That distinction decides the architecture for any live graph: fraud rings, new accounts, and freshly published papers all appear after training ends.


Key Takeaways


What to Learn Next

-> Neural Networks Fundamentals — Perceptrons to Deep Learning

Learn about neural networks fundamentals — perceptrons to deep learning.

-> Convolutional Neural Networks — Complete Guide for Vision

Learn about convolutional neural networks — complete guide for vision.

-> Transformers — Attention Is All You Need Complete Guide

Learn about transformers — attention is all you need complete guide.

-> Clustering — K-Means, DBSCAN, Hierarchical Complete Guide

Learn about clustering — k-means, dbscan, hierarchical complete guide.

-> Recommendation Systems — Collaborative and Content-Based Filtering

Learn about recommendation systems — collaborative and content-based filtering.

-> ML System Design — Architecture and Production Patterns

Learn about ml system design — architecture and production patterns.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-17

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Machine Learning Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement