Sam Austinon November 17, 202615 min read

Graph Machine Learning for Beginners: A Complete Guide to Learning from Networks

Graph Machine Learning for Beginners: A Complete Guide to Learning from Networks
Contents

Figure 1: Graph Machine Learning for Beginners: A Complete Guide to Learning from Networks — the edges are data, and a model that ignores them is throwing away half the signal

Some data refuses to fit in a table. Friends follow each other, molecules link atoms through bonds, papers cite papers, and accounts send money to accounts. The connections carry as much information as the rows.

Graph machine learning lets models use those connections directly. This post explains graphs, message passing, and the main architectures from scratch, and shows a tiny experiment you can run to see exactly why structure matters.

What Is a Graph?

A graph has nodes (the things) and edges (the relationships between them). Nodes and edges can carry features: a user's age, a transaction's amount, an atom's type.

Everyday examples:

  • Social networks: people are nodes, friendships are edges.
  • Molecules: atoms are nodes, bonds are edges.
  • Citation networks: papers are nodes, citations are edges.
  • Financial systems: accounts are nodes, transfers are edges.
  • Road maps: intersections are nodes, roads are edges.

A sharp way to see it: every relational database is a graph hiding in plain sight, since foreign keys are edges. That is why graph ML shows up in fraud detection, recommendations, and knowledge graphs.

Why Not Just Flatten It?

You could convert each node into a row of features and use a standard model. That throws away who connects to whom.

A fraudulent account may look ordinary by itself but sit next to ten known fraud accounts. A paper's topic often matches the topic of the papers it cites. Graph models let each node borrow information from its neighbours, and flat-table machine learning cannot do that.

What Can You Predict?

Graph tasks fall into three levels:

  • Node-level: a label per node — a paper's topic, or whether an account is fraudulent.
  • Edge-level: whether an edge exists or what type it is — link prediction for recommendations.
  • Graph-level: a property of the whole graph — a molecule's toxicity.

Choose the prediction target before the architecture. The same message-passing backbone serves all three, and only the output head and the loss function change.

The Core Idea: Message Passing

Almost every modern graph neural network (GNN) uses message passing. One layer performs three steps for every node:

  1. Message — neighbours send information.
  2. Aggregate — the node combines incoming messages, usually by summing or averaging.
  3. Update — the node merges the aggregate with its own features, usually through a small neural network.

Repeat this for several layers. The number of layers sets each node's receptive field: two layers expose a node to its two-hop neighbourhood. After the final layer, each node has an embedding that reflects its local neighbourhood, and a node head, edge decoder, or graph readout turns those embeddings into predictions.

The Message Passing Neural Network (MPNN) framework describes GCN, GraphSAGE, and GAT as different choices of message and aggregation functions [4]. Once you understand the loop, the architecture zoo stops looking mysterious.

The Simplest GNN: GCN

The Graph Convolutional Network (Kipf and Welling, 2016) is the standard starting point [1]. Its layer fits in one line:

H' = ReLU( Â H W )     where  Â = D^(-1/2) (A + I) D^(-1/2)

In words: add self-loops (A + I) so each node keeps its own features, normalise by degree so high-degree nodes do not dominate, multiply by the node features H, then apply a learned weight matrix W and a nonlinearity.

Here it is in NumPy, which I ran:

import numpy as np

def norm_adj(A):
    A_hat = A + np.eye(len(A))                # add self-loops
    d = A_hat.sum(1)
    Dm = np.diag(d ** -0.5)
    return Dm @ A_hat @ Dm                    # symmetric normalization

# one forward pass of a 2-layer GCN
S = norm_adj(A)
H1 = np.maximum(S @ X @ W1, 0)
logits = S @ H1 @ W2

That is the whole model. The matrix S mixes each node's features with its neighbours', and W1 and W2 learn what to do with the mixture.

Does Structure Actually Help? A Small Experiment

I built a toy test. Each graph has 90 nodes in three communities, with dense connections inside communities and sparse connections between them. Node features are deliberately weak: a faint class signal buried in noise. Only three labelled nodes per class are available for training.

I trained a two-layer GCN and, as a control, the same network with the graph removed — a plain MLP that sees only each node's own features — then repeated the test on 20 random graphs:

                    mean test accuracy
MLP (ignores graph)        0.349
GCN (uses graph)           0.854
GCN better on 20 of 20 graphs

Random guessing gives 0.333, so the MLP barely beats chance while the GCN nearly solves the task. Both models fit their nine training nodes perfectly, which is the point: the MLP memorised, the GCN generalised.

Remember the caveat: I designed this toy so that structure matters a lot. Real graphs vary, and sometimes node features alone do fine. Still, the experiment shows the core benefit: neighbours reveal what noisy features cannot.

Blur the Communities and the Advantage Disappears

The draft of this post suggested raising the inter-community edge probability and watching the GCN's advantage shrink. I ran that too, with the between-community probability raised from 0.01 to 0.12:

p_out = 0.01:  MLP 0.349   GCN 0.854
p_out = 0.12:  MLP 0.349   GCN 0.359   (GCN better on 9 of 20)

With the communities blurred, the graph stops carrying class information and the GCN collapses back to chance. That is the single most useful lesson in this post: a GNN is only as good as the homophily in your edges.

GCN, GraphSAGE, and GAT

Three architectures cover most beginner needs:

  • GCN — fast and effective on graphs with relatively uniform structure, and a useful baseline [1]. It does not learn which neighbours matter most.
  • GraphSAGE — samples a fixed number of neighbours and learns to embed unseen nodes, which makes it practical for very large graphs and inductive learning, at the cost of sampling variance [2].
  • GAT — learns attention scores between connected nodes, so it helps when neighbour relevance varies [3].

Others worth knowing: GIN, designed for maximum expressive power among message-passing GNNs, and R-GCN, built for heterogeneous graphs with several edge types.

On Cora, the original GCN paper reports about 81.5% test accuracy [1], and GAT reports a modest improvement on the same split [3]. Start with GCN, then swap in the others on the same dataset and compare — that comparison teaches more than any benchmark table.

Node Embeddings Without Neural Networks

Before GNNs became popular, researchers learned node embeddings from random walks. DeepWalk and Node2Vec generate walks across the graph and treat them like sentences, so nodes that appear near each other get similar vectors.

The key distinction is transductive versus inductive. These methods only embed nodes seen during training, while GNNs such as GraphSAGE can embed new nodes at inference time [2]. Node2Vec still makes a good baseline and a gentle first step.

Two Failure Modes to Know

Over-Smoothing

Stack many message-passing layers, and node representations become too similar. I measured it by repeatedly propagating the same features across a graph and tracking the mean pairwise distance between node vectors:

propagation steps -> spread across nodes
  k= 0: 3.964
  k= 2: 1.009
  k= 8: 0.332
  k=32: 0.096

The spread collapses by a factor of four within two steps and by forty over the full run, so nodes blur together. Repeated propagation pushes representations toward a common pattern on a connected graph [5]. That is why many GNNs use just two or three layers. Residual connections and jumping-knowledge networks help when you need more depth.

Over-Squashing

A related problem: information from distant nodes gets compressed through bottlenecks, so a node's receptive field grows without its capacity to carry information growing with it. Graph transformers, which combine local message passing with global attention, partly address it.

Tools and Datasets

You do not need to code the maths yourself.

  • PyTorch Geometric (PyG): the most common library, with dozens of built-in GNN layers and 100+ datasets. Install with pip install torch-geometric on top of PyTorch.
  • DGL (Deep Graph Library): another popular framework.
  • NetworkX: pure Python graph operations, good for learning but not for huge graphs.
  • GraphFrames: large-scale graph analytics on Spark.

For practice, start with Cora: 2,708 papers, 10,556 citation edges, and seven topic classes [1]. Citeseer and PubMed are similar, and the Open Graph Benchmark (OGB) leaderboard tracks state-of-the-art results across harder tasks.

Here is the minimal PyG version of the GCN:

import torch
import torch.nn.functional as F
from torch_geometric.datasets import Planetoid
from torch_geometric.nn import GCNConv

dataset = Planetoid(root="/tmp/Cora", name="Cora")
data = dataset[0]

class GCN(torch.nn.Module):
    def __init__(self, hidden=16):
        super().__init__()
        self.conv1 = GCNConv(dataset.num_features, hidden)
        self.conv2 = GCNConv(hidden, dataset.num_classes)

    def forward(self, x, edge_index):
        x = F.relu(self.conv1(x, edge_index))
        x = F.dropout(x, p=0.5, training=self.training)
        return self.conv2(x, edge_index)

PyTorch Geometric is not installed in my environment, so I could not run this snippet here — treat it as a starting point and check it against the current documentation. Train with cross-entropy on the training mask and evaluate on the test mask, and expect roughly the paper's 81% on Cora with a standard split [1].

When Not to Use a GNN

GNNs are not always the answer. Try something simpler first when:

  • Node features alone already predict the target well.
  • Your edges are noisy or arbitrary, so neighbours carry little signal.
  • You have a small dataset and can hand-craft graph features — degree, neighbour counts, clustering coefficient — then feed them to gradient-boosted trees.
  • You need very fast inference on a huge, constantly changing graph.

Always compare against a no-graph baseline, like the MLP in my experiment. If the GNN does not beat it, the graph is not adding value, and you have saved yourself a lot of engineering.

A Beginner's Learning Path

This is my own plan, so adjust it:

  1. Week 1: graph basics in NetworkX — build graphs, compute degrees, visualise.
  2. Week 2: implement the NumPy GCN above and reproduce the MLP comparison.
  3. Week 3: train a GCN on Cora with PyG, then try GAT and GraphSAGE.
  4. Week 4: try link prediction on the same dataset, taking care with train and test edges.
  5. Later: heterogeneous graphs, graph transformers, and graph classification on molecules.

For reading, Kipf and Welling's 2016 paper introduces the GCN [1], and the book Graph Neural Networks in Action covers Node2Vec, GCN, GraphSAGE, GAT, over-smoothing, and graph autoencoders for link prediction.

Common Pitfalls

  • Skipping the no-graph baseline. You will not know whether the graph helps.
  • Leaking test edges in link prediction. Remove test edges from the graph used for message passing.
  • Too many layers. Over-smoothing hurts accuracy; two or three is usually right.
  • Evaluating with random splits when time matters. Use time-based splits for temporal data.
  • Confusing transductive and inductive setups. New nodes at test time need an inductive method.
  • Ignoring class imbalance. Fraud and rare-event graphs are heavily skewed.
  • Forgetting degree normalisation. Unnormalised propagation lets hub nodes dominate.
  • Masking the loss incorrectly. Compute the gradient only over training nodes; a stray term over all nodes silently fights the learning signal.

Best Book to Read

CoverBookDescriptionGet it
Cover of “Graph Neural Networks in Action” Graph Neural Networks in Actionby Keita Broadwater and Namid Stillman walks through Node2Vec, GCN, GraphSAGE, GAT, over-smoothing, and link prediction with working code. View on Amazon

As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.

Read it after you have trained your first GCN on Cora. The book makes far more sense once you have watched a shallow model beat an MLP on a graph you built yourself.

Wrapping Up

Graph ML works by letting nodes pass messages to their neighbours, aggregating what they receive, and updating their representations. GCN gives you a simple baseline, GraphSAGE scales to huge graphs, and GAT learns which neighbours matter.

The experiment is the takeaway: with weak features and only nine labels, the MLP scored 0.349 and the GCN scored 0.854, winning 20 of 20 graphs — and when I blurred the communities, the advantage vanished.

Keep the network shallow, compare against a no-graph baseline, and start on Cora.

Frequently Asked Questions

What is message passing in a graph neural network?

Each layer has every node collect messages from its neighbours, combine them with an aggregation function such as sum or mean, and update its own representation with a small neural network. Stacking layers widens each node's receptive field, so two layers let a node see its two-hop neighbourhood.

Why do GNNs use only two or three layers?

Because stacking message-passing layers makes node representations converge toward each other. This is over-smoothing: after enough propagation every node looks similar, and accuracy falls. In my measurement the spread between node features dropped from 3.96 to 1.01 after two propagation steps and to 0.10 after thirty-two.

What is the difference between GCN, GraphSAGE, and GAT?

GCN averages neighbours with a fixed degree-normalised weight, which is fast but treats all neighbours alike. GraphSAGE samples a fixed number of neighbours and learns aggregation, which supports new nodes at test time. GAT learns attention weights between connected nodes, so it can emphasise the neighbours that matter.

When should I not use a graph neural network?

When node features alone predict the target, when edges are noisy or arbitrary, when the graph is small enough for hand-crafted features plus gradient-boosted trees, or when you need very fast inference on a constantly changing graph. Always compare against a no-graph baseline first.

What dataset should a beginner start with?

Cora: 2,708 papers, 10,556 citation edges, and seven topic classes, with a standard train/validation/test split. It is small enough to train in seconds and is the de facto benchmark for a first GCN, which is why it gets called the MNIST of graph machine learning.

Sources

  • [1] Kipf and Welling, Semi-Supervised Classification with Graph Convolutional Networks — the GCN layer, normalisation, and Cora results: arxiv.org
  • [2] Hamilton, Ying, and Leskovec, Inductive Representation Learning on Large Graphs — GraphSAGE and neighbour sampling: arxiv.org
  • [3] Veličković et al., Graph Attention Networks — learned attention over neighbours: arxiv.org
  • [4] Gilmer et al., Neural Message Passing for Quantum Chemistry — the MPNN framework that unifies the architectures: arxiv.org
  • [5] Li, Han, and Wu, Deeper Insights into Graph Convolutional Networks for Semi-Supervised Learning — why deep GCNs smooth representations together: arxiv.org

What are You Looking For?

esc