Contents
Figure 1: Graph Classification for Molecules: Predict Chemical Properties with GNNs — a molecule is already a graph, which is why the architecture is the easy part and the evaluation is where the work lives
A medicinal chemist hands you a molecule drawn as a diagram: atoms joined by bonds. She wants to know whether it dissolves in water, crosses the blood-brain barrier, or shows toxicity. A lab test takes days and costs money. A model can guess in milliseconds.
Molecules are graphs already, so graph neural networks fit this problem naturally, and "predict one property per molecule" is exactly graph classification or regression.
The lesson that matters most here is not the architecture but the split. I ran the full pipeline on ESOL: the same model scored 0.678 RMSE on a random split and 1.061 on a scaffold split. That gap is 13 times the spread between seeds, which is larger than most method-to-method differences in published tables.
Molecules as Graphs
A molecule becomes a graph like this:
- Nodes — atoms.
- Edges — bonds, stored in both directions.
- Node features — atom type, charge, number of connections, aromaticity, hybridisation.
- Edge features — bond type (single, double, triple, aromatic), conjugation, ring membership.
- Label — one number or class for the whole molecule.
You usually start from SMILES, a text notation for molecules, and convert it with RDKit, a cheminformatics toolkit. The feature set below follows the specification in the pre-training paper by Hu et al. [2], which is the one most molecular GNN papers inherit.
The Standard Benchmarks
Most molecular GNN papers use MoleculeNet datasets [1]. A sample:
| Dataset | Molecules | Task | Metric |
|---|---|---|---|
| ESOL | 1,128 | regression, aqueous solubility | RMSE |
| FreeSolv | 642 | regression, hydration free energy | RMSE |
| Lipophilicity | 4,200 | regression | RMSE |
| BBBP | 2,039 | classification, blood-brain barrier | ROC-AUC |
| BACE | 1,513 | classification | ROC-AUC |
| Tox21 | 7,831 | classification, 12 tasks | ROC-AUC |
| HIV | 41,127 | classification | ROC-AUC |
| QM9 | 130,829 | regression, 8 quantum properties | MAE |
Every benchmark except QM9 uses a scaffold split with 8/1/1 fractions, which the pre-training paper describes as a harder and more realistic setting; QM9 uses a random split [2]. I verified the ESOL row myself: the CSV has exactly 1,128 rows.
Start with ESOL — small, fast, and the target is a number you can reason about.
From Atoms to One Prediction: The Architecture
A graph classifier has three parts:
- Message-passing layers update each atom's vector using its bonded neighbours.
- Pooling collapses all atom vectors into one molecule vector.
- A prediction head turns that vector into the answer.
I used GINE, the GIN variant that also reads edge features, because bond type matters in chemistry [2]. GIN's selling point is theoretical: it is designed to be as powerful as the 1-WL graph isomorphism test, which is the ceiling for message-passing GNNs [3].
Step 1: Install and Load Data
pip install rdkit torch_geometric scikit-learn pandas
RDKit installs from pip as rdkit — I ran this article with RDKit 2026.09.2 on Python 3.12. For data, read the ESOL CSV from MoleculeNet, which stores SMILES and measured log solubility. Print df.columns and adjust, because column names vary by source:
Compound ID, ESOL predicted log solubility in mols per litre, Minimum Degree,
Molecular Weight, Number of H-Bond Donors, Number of Rings,
Number of Rotatable Bonds, Polar Surface Area,
measured log solubility in mols per litre, smiles
PyTorch Geometric also ships MoleculeNet dataset classes, but their default featurisation differs from the one below, so the explicit route is worth writing once.
Step 2: Featurize Molecules
This is the code I ran, with one fix to the original version:
import numpy as np
import pandas as pd
import torch
from rdkit import Chem
from torch_geometric.data import Data
ATOMS = [6, 7, 8, 9, 15, 16, 17, 35, 53] # C N O F P S Cl Br I
HYB = [Chem.HybridizationType.SP, Chem.HybridizationType.SP2,
Chem.HybridizationType.SP3, Chem.HybridizationType.SP3D,
Chem.HybridizationType.SP3D2]
BONDS = [Chem.BondType.SINGLE, Chem.BondType.DOUBLE,
Chem.BondType.TRIPLE, Chem.BondType.AROMATIC]
def one_hot(v, choices): # last slot = "other"
return [int(v == c) for c in choices] + [int(v not in choices)]
def atom_features(a):
return (one_hot(a.GetAtomicNum(), ATOMS)
+ one_hot(a.GetTotalDegree(), [1, 2, 3, 4])
+ one_hot(a.GetFormalCharge(), [-1, 0, 1])
+ one_hot(a.GetHybridization(), HYB)
+ [int(a.GetIsAromatic()), a.GetTotalNumHs() / 4.0])
def bond_features(b):
return (one_hot(b.GetBondType(), BONDS)
+ [int(b.GetIsConjugated()), int(b.IsInRing())]) # GetIsConjugated, not IsConjugated
ATOM_DIM = len(atom_features(Chem.MolFromSmiles("C").GetAtomWithIdx(0)))
BOND_DIM = len(BONDS) + 1 + 2
def smiles_to_data(smiles, y):
mol = Chem.MolFromSmiles(smiles)
if mol is None: # invalid SMILES: skip and count them
return None
x = torch.tensor([atom_features(a) for a in mol.GetAtoms()], dtype=torch.float)
src, dst, ea = [], [], []
for b in mol.GetBonds():
i, j, f = b.GetBeginAtomIdx(), b.GetEndAtomIdx(), bond_features(b)
src += [i, j]; dst += [j, i]; ea += [f, f] # both directions
edge_index = (torch.tensor([src, dst], dtype=torch.long) if src
else torch.empty((2, 0), dtype=torch.long))
edge_attr = (torch.tensor(ea, dtype=torch.float) if ea
else torch.empty((0, BOND_DIM)))
return Data(x=x, edge_index=edge_index, edge_attr=edge_attr,
y=torch.tensor([y], dtype=torch.float))
The fix: RDKit's Bond object has no IsConjugated() method. It has GetIsConjugated(). The first version of this code crashed on molecule one with AttributeError: 'Bond' object has no attribute 'IsConjugated'. Atom aromaticity is GetIsAromatic(), bond ring membership is IsInRing() — the naming is inconsistent, so read the error rather than the pattern.
On the full dataset:
parsed 1128 molecules, 0 invalid SMILES
total atoms 14991, total bonds 15428, mean atoms/molecule 13.3
ATOM_DIM=27 BOND_DIM=7
target: mean -3.050 std 2.096 min -11.60 max 1.58
Every SMILES in ESOL parsed, but do not assume that of your own data. Count the None returns and report how many you lost, because silently dropping 5% of your molecules changes the label distribution.
Clean SMILES before featurising: strip salts and counterions, standardise tautomers, neutralise charged species, and drop duplicates. Dirty structures teach the model noise, and duplicates that straddle a split leak labels.
Step 3: Split by Scaffold, Not at Random
A scaffold is a molecule's core ring-and-linker framework. A scaffold split groups molecules by that core, so the test set contains cores the model never saw in training [2]. That matches how chemists use models: you want predictions on new chemistry, not near-copies of training molecules.
from collections import defaultdict
from rdkit.Chem.Scaffolds import MurckoScaffold
def scaffold_split(smiles_list, frac=(0.8, 0.1, 0.1)):
groups = defaultdict(list)
for i, smi in enumerate(smiles_list):
scaf = MurckoScaffold.MurckoScaffoldSmiles(smiles=smi, includeChirality=False)
groups[scaf].append(i)
ordered = sorted(groups.values(), key=lambda g: (len(g), g[0]), reverse=True)
n = len(smiles_list)
train, valid, test = [], [], []
for g in ordered: # biggest scaffold groups go to train first
if len(train) + len(g) <= frac[0] * n:
train += g
elif len(valid) + len(g) <= frac[1] * n:
valid += g
else:
test += g
return train, valid, test
It runs cleanly and produces a genuine holdout:
scaffold split: train 902 val 112 test 114
unique scaffolds: 269
test scaffolds seen in train: 0/114 = 0.0%
Now compare that with a random 80/10/10 split of the same 1,128 molecules:
random split: train 902 val 113 test 113
test scaffolds seen in train: 29/50 = 58.0%
Fifty-eight percent of the test scaffolds also appear in training. The model is not being asked to generalise to new chemistry; it is being asked to recognise chemistry it has already seen. That single number explains the rest of this article.
Different papers use slightly different scaffold recipes — this one is deterministic and sorts groups by size, others randomise group order — so state yours when you report results.
Step 4: Build the Model
The PyG version, which I could not run here because PyTorch Geometric is not installed:
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GINEConv, global_mean_pool
class MolGNN(nn.Module):
def __init__(self, in_dim, edge_dim, hidden=128, layers=4, out_dim=1, dropout=0.1):
super().__init__()
self.embed = nn.Linear(in_dim, hidden)
self.convs, self.norms = nn.ModuleList(), nn.ModuleList()
for _ in range(layers):
mlp = nn.Sequential(nn.Linear(hidden, hidden), nn.ReLU(), nn.Linear(hidden, hidden))
self.convs.append(GINEConv(mlp, edge_dim=edge_dim))
self.norms.append(nn.BatchNorm1d(hidden))
self.head = nn.Sequential(nn.Linear(hidden, hidden), nn.ReLU(),
nn.Dropout(dropout), nn.Linear(hidden, out_dim))
self.dropout = dropout
def forward(self, x, edge_index, edge_attr, batch):
h = self.embed(x)
for conv, norm in zip(self.convs, self.norms):
h = h + F.relu(norm(conv(h, edge_index, edge_attr))) # residual connection
h = F.dropout(h, self.dropout, self.training)
return self.head(global_mean_pool(h, batch)).squeeze(-1) # one value per molecule
The residual connection keeps deeper stacks from blurring atom identities, which is the over-smoothing problem that limits depth in every GNN. Try sum pooling too: for properties that grow with molecule size, summing atom contributions can beat averaging them.
Step 5: Train and Evaluate
Standardise the target using training statistics, train with MSE, and pick the epoch by validation RMSE:
from torch_geometric.loader import DataLoader
y_tr = torch.cat([d.y for d in train_ds])
mu, sd = y_tr.mean().item(), y_tr.std().item()
train_loader = DataLoader(train_ds, batch_size=32, shuffle=True)
val_loader, test_loader = DataLoader(val_ds, batch_size=128), DataLoader(test_ds, batch_size=128)
@torch.no_grad()
def rmse(model, loader):
model.eval(); se, n = 0.0, 0
for b in loader:
b = b.to(device)
pred = model(b.x, b.edge_index, b.edge_attr, b.batch) * sd + mu # back to original units
se += ((pred - b.y.view(-1)) ** 2).sum().item(); n += b.y.numel()
return (se / n) ** 0.5
def train_one(seed, epochs=100):
torch.manual_seed(seed)
model = MolGNN(ATOM_DIM, BOND_DIM).to(device)
opt = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-5)
best_val, best_test = 1e9, None
for epoch in range(epochs):
model.train()
for b in train_loader:
b = b.to(device); opt.zero_grad()
out = model(b.x, b.edge_index, b.edge_attr, b.batch)
F.mse_loss(out, (b.y.view(-1) - mu) / sd).backward(); opt.step()
v = rmse(model, val_loader)
if v < best_val: # select by validation, report test once
best_val, best_test = v, rmse(model, test_loader)
return best_val, best_test
n in that RMSE is a count of molecules, not batches — n += b.y.numel() — so the final value is comparable across batch sizes. Averaging per-batch RMSE instead silently weights small molecules and large molecules equally per batch rather than per molecule.
Step 6: Beat a Fingerprint Baseline First
Before you celebrate, build the classic baseline: an ECFP4 (Morgan) fingerprint fed to a random forest. The comparison is not a formality — a widely cited study found the literature had not settled whether fingerprints or graph convolutions generalise better to new chemical space [4].
from rdkit.Chem import rdFingerprintGenerator
from sklearn.ensemble import RandomForestRegressor
gen = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=2048) # ECFP4-style
X = np.array([gen.GetFingerprintAsNumPy(Chem.MolFromSmiles(s)) for s in smiles_all])
y = np.array([d.y.item() for d in data_all])
rf = RandomForestRegressor(n_estimators=500, n_jobs=-1, random_state=0)
rf.fit(X[train_idx], y[train_idx])
pred = rf.predict(X[test_idx])
print("RF + ECFP4 test RMSE:", float(np.sqrt(np.mean((pred - y[test_idx]) ** 2))))
This API works in RDKit 2026.09.2 — rdFingerprintGenerator.GetMorganGenerator with GetFingerprintAsNumPy returns a 2048-bit array per molecule.
What the Split Actually Cost Me
PyG is not installed here, so I ran an equivalent from-scratch implementation: the same GINE update rule (h_i ← MLP((1+ε)h_i + Σ ReLU(h_j + e_ji))), the same mean pooling, the same residual-plus-BatchNorm stack and MLP head, with hidden size 64, three layers, 80 epochs, and three seeds.
class GINEConv(nn.Module):
def __init__(self, mlp, hidden, edge_dim):
super().__init__()
self.mlp, self.edge_proj = mlp, nn.Linear(edge_dim, hidden)
def forward(self, h, edge_index, edge_attr):
src, dst = edge_index
msg = F.relu(h[src] + self.edge_proj(edge_attr))
agg = torch.zeros_like(h).index_add_(0, dst, msg)
return self.mlp(h + agg)
Note the edge projection. h has width 64 and edge_attr has width 7, so they cannot be added directly — PyG's GINEConv does this projection internally, which is why the version above never hits it. Writing it by hand, it is the first error you meet.
Results, same data, same model, only the split changed:
| Split | Train / Val / Test | Test scaffolds seen in train | GINE test RMSE | RF + ECFP4 |
|---|---|---|---|---|
| Scaffold | 902 / 112 / 114 | 0 / 114 (0.0%) | 1.061 ± 0.029 | 1.643 |
| Random | 902 / 113 / 113 | 29 / 50 (58.0%) | 0.678 ± 0.019 | 1.251 |
Three things to read from that table.
First, the split is worth 0.383 RMSE — from 0.678 to 1.061. The seed spread is ±0.029, so the split effect is thirteen times the noise. Any comparison of two architectures on ESOL that does not fix the split is measuring noise.
Second, the GNN beat the fingerprint baseline on both splits — 1.061 against 1.643 on the scaffold split, a 35% improvement. That is not guaranteed in the literature [4], but on this dataset and this split it is not close.
Third, the random forest degrades more gracefully — 1.251 to 1.643, a 31% increase, against the GNN's 56%. The GNN was leaning harder on scaffold overlap. That is exactly what you want a baseline to reveal.
Classification and Multi-Task Variants
For BBBP, BACE, or HIV, change three things:
- Output — one logit per task.
- Loss —
BCEWithLogitsLoss. - Metric — ROC-AUC, as the benchmark tables use.
Tox21 has 12 tasks, and many molecules have missing labels for some of them. Mask the loss so missing entries do not count:
def masked_bce(logits, targets): # targets use NaN for "unknown"
mask = ~torch.isnan(targets)
return F.binary_cross_entropy_with_logits(logits[mask], targets[mask])
Compute ROC-AUC per task over the molecules that have that label, then average. For heavily imbalanced data like HIV, ROC-AUC can look comfortable while the minority class suffers, so check precision-recall metrics beside it.
Why Numbers Vary So Much Between Papers
Do not compare your RMSE to a paper's without checking these five things:
- The split — random or scaffold, and which scaffold recipe.
- The preprocessing — salt stripping, tautomer standardisation, duplicate handling.
- The seeds — mean and spread across how many runs.
- The model selection — validation-based, or quietly peeking at test.
- The features — which atom and bond descriptors.
My own numbers illustrate the size of the problem: 0.678 and 1.061 from the same model on the same molecules. If I had reported only the random-split figure, it would look competitive with the best published ESOL results, and it would mean nothing.
Improving the Model
Try these one at a time:
- Edge features — compare GINE against plain GCN or GIN without bond types.
- Pooling — mean, sum, max, or attention-based readout.
- Depth and width — 3 to 5 layers, 64 to 256 hidden units.
- Regularisation — dropout and weight decay matter on tiny datasets.
- Fingerprint fusion — concatenate the graph embedding with an ECFP vector before the head [4].
- Pretraining — self-supervised methods such as MolCLR learn from unlabelled molecules [5]; GROVER, GEM, and masked-autoencoder approaches follow the same idea. They help most when labelled data is scarce, so check each paper's protocol before trusting its gains.
- Ensembling — average several seeds, which often beats any single architecture tweak.
- 3D information — quantum-chemistry tasks like QM9 benefit from geometry, which this 2D pipeline ignores.
Limits and Responsibilities
- Small data. A few hundred to a few thousand molecules overfit easily.
- Out-of-distribution failure. Scaffold splits exist precisely because models are fragile on new chemistry.
- Label noise. Experimental measurements carry error, so a perfect fit is not the goal.
- No guarantees. A prediction is not a measurement. Do not use model output for safety or toxicity decisions without experimental confirmation.
- Applicability domain. Flag molecules unlike anything in training.
- Interpretability. Atom-level attributions help chemists, but they do not prove causation.
Common Pitfalls
- Random splits for headline results. Mine showed 58% scaffold overlap and a 0.383 RMSE flattery.
- Skipping SMILES cleanup. Salts, tautomers, and duplicates distort training and leak labels.
- Reporting one seed. My scaffold-split seeds spanned 1.020 to 1.085.
- No fingerprint baseline. It is twenty lines and it tells you whether the GNN earns its complexity.
- Tuning on the test set. Select by validation; report test once.
- Forgetting to standardise regression targets. Training gets harder and the learning rate stops transferring.
- Treating missing labels as zeros. Mask them, as in
masked_bce. - Comparing numbers across papers blindly. Splits and preprocessing differ more than architectures.
- Dropping invalid SMILES silently. Count them and report how many you lost.
- Averaging per-batch RMSE. Count molecules, not batches.
Best Book to Read
| Cover | Book | Description | Get it |
|---|---|---|---|
![]() |
Deep Learning for the Life Sciences | the practical companion to MoleculeNet, covering featurisation, model selection, and the evaluation traps that make molecular benchmarks so hard to compare. | 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 run ESOL once. The book explains the chemistry conventions; the experiment shows you why the split decides the answer.
Wrapping Up
Molecular property prediction with GNNs follows a clear recipe: convert SMILES to atom-and-bond graphs, run message passing with bond-aware layers, pool atoms into one molecule vector, and evaluate with a scaffold split against a fingerprint baseline.
The numbers from my run: the same GINE model scored 0.678 RMSE on a random split and 1.061 on a scaffold split, where 58% of test scaffolds appeared in training under the random split and 0% under the scaffold split. ECFP4 with a random forest scored 1.251 and 1.643 on the same splits.
So run the ESOL example this week, then compare a random split against the scaffold split on the same model. If the random-split RMSE looks noticeably better, you just measured how much near-duplicate molecules were flattering you.
Frequently Asked Questions
What is graph classification for molecules?
It is predicting one property per molecule from its structure. Atoms become nodes, bonds become edges, and a GNN pools all atom vectors into a single molecule vector that a small head turns into a number or a class. Solubility, toxicity, and blood-brain barrier penetration are all this task.
Why use a scaffold split instead of a random split?
Because a random split puts near-duplicates on both sides. In my ESOL run, 58% of the test scaffolds also appeared in training under a random split, against 0% under a scaffold split. The same model scored 0.678 RMSE on the random split and 1.061 on the scaffold split.
Does a GNN beat a fingerprint plus random forest baseline?
In my run, yes, clearly. The GINE model reached 1.061 RMSE on the scaffold split against 1.643 for ECFP4 with a random forest, and 0.678 against 1.251 on the random split. That is not universal, which is why the baseline is worth building every time.
How do I convert SMILES to a graph in Python?
Parse with RDKit's Chem.MolFromSmiles, then read GetAtoms for node features and GetBonds for edges. Store each bond in both directions, and build atom features from element, degree, charge, hybridisation, aromaticity, and hydrogen count. Invalid SMILES return None, so count them.
How many molecules do I need to train a molecular GNN?
ESOL has 1,128 molecules and that is enough for a small model to beat a fingerprint baseline, but not enough for stable results from a single seed. My three seeds spanned 1.020 to 1.085 RMSE on the scaffold split, so always report a spread and prefer a small model with strong regularisation.
Sources
[1]Wu et al., MoleculeNet: A Benchmark for Molecular Machine Learning — the datasets and metrics used across molecular GNN papers: arxiv.org[2]Hu et al., Strategies for Pre-training Graph Neural Networks — the GINE layer, the atom/bond feature specification, and the 8/1/1 scaffold split protocol: arxiv.org[3]Xu et al., How Powerful are Graph Neural Networks? — the 1-WL ceiling and the sum-aggregation design behind GIN: arxiv.org[4]Yang et al., Analyzing Learned Molecular Representations for Property Prediction — the head-to-head between fingerprint models and graph convolutions, and the case for fusing them: arxiv.org[5]Wang et al., Molecular Contrastive Learning of Representations via Graph Neural Networks — MolCLR, self-supervised pretraining for molecular graphs: arxiv.org
