Overfitting in small chemical datasets, and how to catch it
With a few dozen compounds and thousands of fingerprint bits, models memorise noise. Learn to spot overfitting with CV gaps and y-scrambling.
Overfitting in a small chemical dataset happens when the model has more freedom than the data can constrain, so it learns noise and scores well only on the compounds it has seen. You catch it by comparing training and cross-validated scores, by testing against shuffled labels, and by keeping the model small. A model with 2048 fingerprint bits and 60 compounds will fit nearly anything.
Why small chemical sets are risky
Three features of chemical data make overfitting easy.
- The number of inputs often exceeds the number of compounds. A 2048-bit fingerprint on 60 molecules has far more columns than rows, so many different models fit the training data perfectly.
- Compounds are correlated. A series of analogues carries less independent information than its count suggests, so the effective sample size is smaller than the row count.
- Labels are noisy. Experimental error, mixed assay conditions and thresholds all add variance that a flexible model will happily memorise. The guide on IC50, Ki, EC50 and Kd explains why values from different sources should not be mixed casually.
The result is a model with a training R² near 1 and a cross-validated R² near 0, or even negative.
Reading the gap
The simplest diagnostic is the gap between fit and validation. A scikit-learn pipeline makes it easy to compute honestly.
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import RidgeCV
from sklearn.model_selection import RepeatedKFold, cross_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
cv = RepeatedKFold(n_splits=5, n_repeats=5, random_state=0)
models = {
"ridge": make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-2, 3, 20))),
"forest": RandomForestRegressor(n_estimators=300, min_samples_leaf=3, random_state=0),
}
for name, model in models.items():
res = cross_validate(model, X, y, cv=cv, scoring="r2", return_train_score=True)
print(name, res["train_score"].mean(), res["test_score"].mean(), res["test_score"].std())
Look at three things: the train score, the test score and the spread of the test score across folds. A random forest will often show a high train score even on noise, so the test score is what counts. The spread tells you how much one lucky split could mislead you. With small data the spread is large, and reporting it is part of an honest result.
The y-scrambling test
To check that a model has learned something real, shuffle the target values and refit.
from sklearn.model_selection import cross_val_score
rng = np.random.default_rng(0)
real = cross_val_score(models["ridge"], X, y, cv=cv, scoring="r2").mean()
shuffled = [
cross_val_score(models["ridge"], X, rng.permutation(y), cv=cv, scoring="r2").mean()
for _ in range(30)
]
print(real, max(shuffled))
If the real score sits clearly above the best scrambled one, the signal is not chance. If scrambled models come close, the apparent fit is an artefact. Tropsha's best-practice paper recommends this kind of randomisation test as a standard part of QSAR validation.
Tactics that reduce overfitting
- Fewer, better inputs. A handful of physically meaningful descriptors, such as those in the ESOL example, beats a thousand bits on 80 compounds.
- Regularisation. Ridge, lasso and elastic net shrink coefficients. For trees, raise the minimum leaf size and limit depth.
- Nested selection. If you choose features or tune hyperparameters, do it inside each training fold. Selecting the ten best descriptors on all data and then cross-validating is a classic leak that produces impressive and false scores.
- Grouped validation. Use a cluster or scaffold split so that analogues do not sit on both sides, as in train and test splits in chemistry.
- Simple baselines. Compare against predicting the training mean and against a nearest-neighbour model. If your elaborate model barely beats the mean, say so.
- More data of the same kind. Plot a learning curve, the validation score against training set size. If it is still rising at your full size, more data will help more than a better algorithm.
Large pretrained models do not remove the problem
Fine-tuning a transformer with tens of millions of parameters on a 100-compound table is an extreme case of too much capacity. Pretraining helps because the model starts with useful representations, but the fine-tuned head and any unfrozen layers can still memorise the training set. Use early stopping on a validation split, a small learning rate, and compare with a ridge regression on frozen embeddings or on fingerprints. The guide on fine-tuning a chemistry model on your own CSV describes this in more detail.
A short example of the trap
Suppose you have 60 compounds and compute 200 RDKit descriptors. You keep the 10 that correlate best with the target across all 60, then run cross-validation on those 10. The score looks good, and it is wrong, because the selection already saw every label, including the ones in each held-out fold. Even with random numbers as the target, the best ten of 200 columns will correlate with it by chance. Place the selection step inside a pipeline so that it is refitted on each training fold, and the optimistic score collapses to what the data really support.
Key points
- Overfitting is likely when inputs outnumber compounds, analogues are correlated and labels are noisy.
- Always compare training and cross-validated scores and report the spread over repeats.
- Y-scrambling shows whether the real score beats chance.
- Prefer few meaningful descriptors, regularisation and nested feature selection.
- A learning curve tells you whether more data or a better model is the next step.
Questions people ask
- What is overfitting in QSAR?
- Overfitting means the model has fitted noise and quirks of the training compounds, so it scores well on them and poorly on new molecules. It is most likely when there are many inputs and few compounds.
- How can I tell if my model is overfitted?
- Compare the training score with a cross-validated or held-out score. A large gap is the classic sign. A y-scrambling test, where the labels are shuffled and the model is refitted, checks whether the real score is better than chance.
- What is y-scrambling?
- Y-scrambling, or y-randomisation, refits the model on the same inputs with randomly permuted target values. If those models score nearly as well as the real one, the real model has found no genuine structure-activity relationship.
- How do I avoid overfitting with only 50 compounds?
- Use a few readable descriptors, a regularised or low-capacity model, a grouped cross-validation, and keep all feature selection inside the validation loop. Accept that the uncertainty will be wide and report it.
Further reading
- Tropsha, Best practices for QSAR model development, validation and exploitation (2010)
- scikit-learn documentation, common pitfalls and recommended practices
- scikit-learn documentation, cross-validation
In practice: Advanced Modeling trains and applies QSAR models; the AI Foundry runs or fine-tunes ChemBERTa, MoLFormer-XL and Chemprop on a CSV, as a preview. Validation is the user's responsibility, and these guides show how.