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.
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
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
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?
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 family | How neighbors contribute | Reasonable starting situation | Important limitation |
|---|---|---|---|
| GCN | Degree-normalized sum of transformed neighbors | Small/medium homophilous graphs and a clear baseline | Full-neighborhood computation; smoothing assumptions |
| GraphSAGE | Samples neighbors and aggregates them | Inductive use and larger graphs | Sampling adds variance and can miss neighbors |
| GAT | Learns attention weights over neighbors | Neighbor importance may vary | More compute; weights are not guaranteed explanations |
| Relational GNN | Separate relation-aware transformations | Knowledge graphs and typed edges | Parameters/cost grow with relation design |
| Graph Transformer | Attention with graph/position structure | Rich long-range interactions | Potential 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.
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
| Failure | What happens | Possible response |
|---|---|---|
| Over-smoothing | Repeated aggregation makes node representations too similar | Use fewer layers, residual/initial connections, normalization or specialized operators |
| Over-squashing | Exponentially many distant signals are compressed through narrow representations | Rewire/augment structure, use positional encodings or architectures for long range |
| Neighbor explosion | Sampling all multi-hop neighbors becomes too expensive | Neighbor/subgraph sampling, caching and distributed graph systems |
| Noisy/adversarial edges | Bad relationships spread misleading information | Edge filtering/weighting, robust training and domain rules |
| Cold-start nodes | New node has few features or connections | Use inductive feature encoders and explicit cold-start evaluation |
| Heterophily | Connected nodes may have different labels | Use 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.