Skip to main content
LearnMLAcademy
Advanced10 min read

Graph Neural Networks

Process relational graph structures with message passing and node embeddings, with sequence diagrams, attention calculations, and model-code exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Deep Learning · Connected Data

Graph Neural Networks: Learning From Entities and Relationships

A graph represents entities as nodes and their relationships as edges. A Graph Neural Network (GNN) learns by letting connected nodes exchange information. We will build a transaction graph, calculate one complete message-passing update, connect layers to multi-hop context, distinguish node/link/graph tasks, compare GCN, GraphSAGE and GAT, implement node classification, and diagnose leakage, over-smoothing and scale problems.

When Relationships Are Part of the Data

Suppose two bank accounts have identical balances and ages. One receives transfers from long-established payroll accounts; the other receives a burst from newly created accounts that also connect to known fraud. A row-by-row model sees the account features but loses this relational evidence.

A graph G=(V,E) contains a set of nodes V and edges E. Nodes may have feature vectors such as account age and transaction count. Edges may be directed, carry an amount or timestamp, and have different types. Graph construction is a modelling decision: an edge must represent a defensible relationship, not merely convenience.

A graph stores entities and the relationships between them

Example: accounts are nodes; money transfers are directed edges.

Transaction graph with five account nodes and directed edgesAccount nodes A through E have node features such as account age. Arrows between them represent transfers with amounts as edge features.₹2k₹18k₹4k₹11k₹500Aage 18dBage 2yCage 8mDage 4yEage 5dGraph datanodes + featuresedges + featuresoptional graph label
The arrow A→B can differ from B→A, so direction matters. Node features describe an entity; edge features describe a relationship. The graph structure itself is also information.

Message Passing: Gather, Combine, Update

A message-passing layer updates each node in three conceptual operations. First, create a message from each relevant neighbor (and optionally the edge). Second, aggregate incoming messages with an order-independent operation because a graph has no natural first or last neighbor. Third, combine the result with the node's current representation so its own evidence is not automatically erased.

General message-passing layer

mj→i(k) = φ(k)(hi(k−1), hj(k−1), ej,i)

mi(k) = AGGj∈N(i) mj→i(k)

hi(k) = γ(k)(hi(k−1), mi(k))

h(0) comes from the node-feature data; later h values are model-produced. Edge feature e comes from data when available. Neighborhood N(i) comes from the graph's edge list. The functions φ and γ contain shared learned weights; AGG is a developer-selected sum, mean or max rule applied identically at every node.

One message-passing layer updates B from its local neighborhood

Neighbors send features to target node BNodes A and C have incoming edges to B and send values two and eight. Node D is not an incoming neighbor and sends no message. B combines its own value four with incoming messages.Afeature=2message from ACfeature=8message from CDfeature=5not B's incoming neighborBown feature=4AGGREGATE + UPDATEmean(2,4,8)=4.67ReLU(0.5×4.67+0.1)new h′B = 2.43
Aggregation must not depend on arbitrary neighbor ordering. Sum, mean, max and attention-weighted sums are common permutation-invariant choices.

One Mean-Aggregation Update With Numbers

For a complete scalar teaching example, use B's feature 4 and neighbor features A=2 and C=8. These stand in for feature values from graph data. Include B itself, take a chosen mean aggregation, then use illustrative trained parameters W=0.5 and b=0.1 before ReLU. A real model learns W and b across all training nodes; it does not choose them separately for B.

1. Include self
values = [2,4,8]
keeps B's own evidence

2. Aggregate
mean=(2+4+8)/3
=4.667
division controls degree scale

3. Update
ReLU(0.5×4.667+0.1)
=ReLU(2.433)=2.433
learned transform, then nonlinearity

Interpretation: B's new representation contains its own feature and local-neighbor context. Reordering A and C would not change the mean, which is essential because graph neighbors have no meaningful list order.

A GCN Normalizes Neighbor Contributions

A Graph Convolutional Network (GCN) adds self-loops, transforms node features and sums neighbors with degree normalization. The normalization keeps high-degree nodes from simply accumulating much larger values because they have more edges.

One GCN layer in matrix form

H(k+1) = σ(D̃−1/2ÃD̃−1/2H(k)W(k))

Ã=A+I
Graph edges plus one self-edge per node.

D̃−1/2 on both sides
Balances source and destination degree.

H(k)W(k)
Learned matrix W mixes input features.

σ
Activation adds nonlinearity after aggregation.

A and D are calculated from the provided graph, H(0) comes from node features, W is initialized then learned, and σ is chosen with the architecture. This is a common undirected GCN formulation; directed or typed graphs often need different operators.

Stacking layers expands the receptive field by graph hops

B

target

↓

A, C

1-hop neighbors

↓

E, F, G

2-hop neighbors

After one layer, B can use immediate neighbors. After two, information can arrive from neighbors-of-neighbors. More layers do not automatically help: states may become too similar and distant information can be compressed.

The Output Can Belong to a Node, Edge or Whole Graph

The readout changes with the prediction target

Node prediction

one output per node

fraud risk for account B

Edge/link prediction

one output per node pair/edge

will A connect to D?

Graph prediction

one output for whole graph

is this molecule toxic?

Graph prediction needs a permutation-invariant pooling/readout such as sum, mean or learned attention over node embeddings. Link prediction needs careful negative-edge sampling and time-aware evaluation.

In semi-supervised node classification, message passing can use the graph and features for all nodes while the loss is calculated only on labelled training nodes. Validation and test labels must remain outside the training loss, and the evaluation protocol must state whether their features/edges were visible.

GCN, GraphSAGE and GAT Change the Neighborhood Rule

Model familyHow neighbors contributeReasonable starting situationImportant limitation
GCNDegree-normalized sum of transformed neighborsSmall/medium homophilous graphs and a clear baselineFull-neighborhood computation; smoothing assumptions
GraphSAGESamples neighbors and aggregates themInductive use and larger graphsSampling adds variance and can miss neighbors
GATLearns attention weights over neighborsNeighbor importance may varyMore compute; weights are not guaranteed explanations
Relational GNNSeparate relation-aware transformationsKnowledge graphs and typed edgesParameters/cost grow with relation design
Graph TransformerAttention with graph/position structureRich long-range interactionsPotential quadratic cost and structural encoding choices

Choose from graph properties and deployment. GCN-style smoothing often fits homophily, where connected nodes tend to share labels/features. Fraud or biological graphs can be heterophilous, where unlike nodes connect; blindly averaging neighbors may erase the distinction you need.

A Two-Layer Node Classifier With PyTorch Geometric

x stores one feature vector per node as [num_nodes, num_features]. edge_index stores source and destination node IDs as [2, num_edges]. The model produces one logit vector per node, but cross-entropy is calculated only on the training mask.

gcn_node_classifier.py
import torch
from torch import nn
from torch_geometric.nn import GCNConv

class NodeClassifier(nn.Module):
    def __init__(self, input_features, hidden, classes):
        super().__init__()
        self.conv1 = GCNConv(input_features, hidden)
        self.conv2 = GCNConv(hidden, classes)

    def forward(self, x, edge_index):
        x = self.conv1(x, edge_index).relu()
        x = nn.functional.dropout(x, p=0.4, training=self.training)
        return self.conv2(x, edge_index)  # [nodes, classes]

model = NodeClassifier(data.num_features, hidden=32, classes=3)
optimizer = torch.optim.AdamW(model.parameters(), lr=0.01, weight_decay=5e-4)

model.train()
optimizer.zero_grad()
logits = model(data.x, data.edge_index)
loss = nn.CrossEntropyLoss()(
    logits[data.train_mask],
    data.y[data.train_mask],
)
loss.backward()
optimizer.step()

Where the dimensions come from

data.num_features is read from the dataset. Hidden width 32, dropout probability 0.4, learning rate 0.01 and weight decay 0.0005 are chosen hyperparameters. Output size 3 comes from the three node labels. If the graph has 1,000 nodes, logits have shape [1000,3].

What the framework does

GCNConv adds normalized neighbor aggregation and a learned feature transform. During model.train(), dropout independently zeros each hidden value with probability 0.4; the actual fraction in one finite batch can be higher or lower than exactly 40%. The boolean training mask selects labelled training nodes before cross-entropy; gradients still flow through graph computations that produced those nodes' logits.

This is a transductive full-graph teaching example. Large or changing graphs often require neighbor sampling, subgraph batching and an inductive evaluation plan.

Graph Splits Can Leak Through Structure

Time leakage

A future transfer edge, citation or interaction appears while predicting an earlier event.

Check: Build time-respecting graph snapshots and timestamp every feature/edge.

Identity leakage

The same user, molecule scaffold or near-duplicate subgraph crosses splits.

Check: Group by deployment identity or scaffold, not random rows.

Label-derived features

A node feature or edge was constructed from labels that should be unknown.

Check: Audit feature provenance and rebuild using prediction-time information only.

Negative-edge leakage

Random non-edges include pairs that become positive later or are impossible candidates.

Check: Use time-aware, task-valid negative sampling.

Why Deeper Is Not Automatically Better

FailureWhat happensPossible response
Over-smoothingRepeated aggregation makes node representations too similarUse fewer layers, residual/initial connections, normalization or specialized operators
Over-squashingExponentially many distant signals are compressed through narrow representationsRewire/augment structure, use positional encodings or architectures for long range
Neighbor explosionSampling all multi-hop neighbors becomes too expensiveNeighbor/subgraph sampling, caching and distributed graph systems
Noisy/adversarial edgesBad relationships spread misleading informationEdge filtering/weighting, robust training and domain rules
Cold-start nodesNew node has few features or connectionsUse inductive feature encoders and explicit cold-start evaluation
HeterophilyConnected nodes may have different labelsUse operators designed/tested for heterophilous structure; keep feature-only baseline

Decide Whether You Need a GNN

A GNN is justified when relationships are available at prediction time and add stable signal beyond node features. Start with a feature-only model, then add simple graph statistics, then compare a GNN under the same split. This reveals whether the graph—not just model capacity—is contributing.

Graph structure can expose sensitive relationships and amplify network bias. Document how edges were created, who may be excluded, how often the graph changes, and whether a prediction can unfairly propagate one node's behavior to its neighbors.

The GNN in One Connected Explanation

  • A graph represents entities as nodes, relationships as edges, and attributes as features.
  • Message passing creates neighbor messages, aggregates them without depending on order, and updates each node.
  • One layer uses one-hop context; stacked layers reach farther but can over-smooth or over-squash information.
  • GCN normalizes neighbor sums, GraphSAGE samples/aggregates, and GAT learns neighbor weights.
  • Node, link and graph tasks require different outputs, losses and split strategies.
  • Graph construction, leakage and deployment-time edge availability are part of the model—not preprocessing details.

Continue Learning

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Graph Neural Networks"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • Graphs store entities as nodes and relationships as edges.
  • Message passing transforms, aggregates, and updates neighbour information.
  • More layers expand the multi-hop receptive field.
  • Permutation-invariant aggregation ignores arbitrary neighbour order.
  • Node, edge, and graph tasks need different readouts.
  • Oversmoothing, oversquashing, graph errors, leakage, and scale limit performance.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What happens in one message-passing layer?
Question 2 of 5interpretation
Why should neighbour aggregation be permutation invariant?
Question 3 of 5conceptual
After two basic message-passing layers, which nodes can usually influence a node?
Question 4 of 5debugging/diagnostic
What is oversmoothing?
Question 5 of 5practical selection
Why can a random node split leak information?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What happens in one message-passing layer?▼

Correct Answer: Neighbour messages are transformed, aggregated, and used to update nodes

The layer combines information allowed by the graph's edges.

2Why should neighbour aggregation be permutation invariant?▼

Correct Answer: Neighbour listing order is arbitrary

Reordering the same neighbours should not change the represented graph.

3After two basic message-passing layers, which nodes can usually influence a node?▼

Correct Answer: Nodes up to two hops away

Each layer expands the receptive field by roughly one graph hop.

4What is oversmoothing?▼

Correct Answer: Node representations become too similar after many layers

Repeated averaging can erase distinctions needed for prediction.

5Why can a random node split leak information?▼

Correct Answer: Connected train and test nodes may exchange target-related signals

Edges can carry information across partitions, so the split must match the deployment boundary.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next