MolBasis
nested-cross-validationmodel-selectionoptimismqspr-validation5 min read

Nested cross-validation, choosing a model without peeking

Nested cross-validation puts the whole model search inside each outer fold, so the score of the chosen equation is not the score that chose it. Why and how.

Updated November 28, 2026

Nested cross-validation places the entire model search inside each fold of an outer cross-validation, so the data that score the chosen equation are never the data that chose it. Without nesting, the best score found by a search is an optimistic estimate, because selecting the maximum of many noisy scores selects favourable noise along with signal. The effect is large for short equations chosen from thousands of candidates on small datasets, which is exactly the setting of a property kernel.

The search is part of the model

A one-term kernel looks like a model with two coefficients. The search that produced it is far larger. Suppose nine descriptors and an exponent grid of 13 values with a step of 0.25. That is 9 × 13 = 117 one-term candidates. For two-term equations there are 36 descriptor pairs and 13 × 13 exponent combinations per pair, 36 × 169 = 6084 candidates. The search tries about 6200 equations and keeps one.

The chosen equation is short, but the choice carries the degrees of freedom of the whole grid. The guide on overfitting with few parameters develops this point. Any score computed on the data that drove the choice inherits the optimism of the choice.

A numeric picture of selection optimism

Imagine 100 candidate equations that are in truth all equally good, with a true held-out r of 0.50 each. Cross-validation on a small dataset estimates each one's r with noise of standard deviation 0.05. The scores scatter around 0.50. The search reports the maximum.

The expected maximum of 100 independent standard normal draws is about 2.5 standard deviations above the mean. The reported best score is therefore about 0.50 + 2.5 × 0.05 = 0.625. Nothing about the winner is better than the others. The 0.125 is pure selection. With 6000 candidates the expected maximum sits above 3.5 standard deviations, though candidates in an exponent grid are correlated, so the effective number is smaller. The direction is the same. The more you search, the more the winning score lies.

Nested cross-validation measures the lie. In each outer fold, the inner search picks its winner on four fifths of the training data and the outer fold scores that winner on molecules it never used. Averaging the outer scores gives an estimate near 0.50, the truth, rather than 0.625.

The two loops in code

Both loops must respect groups, otherwise duplicates leak into the inner selection and the outer score as the guide on grouped cross-validation explains. The example searches a ridge penalty over a small grid. For a kernel the grid would enumerate descriptor and exponent choices instead, but the structure is identical.

import numpy as np
from sklearn.model_selection import GroupKFold, GridSearchCV
from sklearn.linear_model import Ridge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

inner = GroupKFold(n_splits=5)
outer = GroupKFold(n_splits=5)
grid = {"ridge__alpha": [1e-3, 1e-2, 1e-1, 1.0]}
search = GridSearchCV(make_pipeline(StandardScaler(), Ridge()), grid,
                      cv=inner, scoring="neg_mean_absolute_error")
outer_mae, winners = [], []
for tr, te in outer.split(X, y, groups):
    search.fit(X[tr], y[tr], groups=groups[tr])
    pred = search.predict(X[te])
    outer_mae.append(np.mean(np.abs(y[te] - pred)))
    winners.append(search.best_params_["ridge__alpha"])
print(np.mean(outer_mae), winners)

The inner best score, search.best_score_, is the optimistic number. The outer mean of outer_mae is the honest one. The list of winners is informative in its own right. If five outer folds pick five different alphas, or five different descriptor pairs, the search is sitting on a plateau rather than a peak.

What nested cross-validation estimates, and what it does not

The outer average estimates the performance of the procedure, meaning "run this search on data like these and use what it returns". It does not score one specific equation, because different outer folds may return different equations. That is a feature. If the winners disagree, the record should say so. The guide on the plateau of equivalent models explains why the MolBasis record counts equations within ±0.01 r of the best rather than declaring one winner.

The final equation is obtained by running the search once on all training data. Its honest score is the outer average from the nesting, not the inner score it was chosen with. And a final untouched held-out set, never used by either loop, remains the cleanest single number a report can give.

How this fits the MolBasis protocol

The MolBasis methodology lists nested cross-validation among the checks of its rigor gate, alongside a permutation floor, bootstrap intervals, a plateau count and a feature-addition test. The final figures on each kernel page come from a different step, a 25 percent scaffold-blind split drawn before fitting. The equation the gate selected on the 75 percent is refitted on that 75 percent and scored once on the held-out molecules. The page states its held-out r and the number of molecules it rests on. The figures are reported from the research record and not recomputed here, since the fitting scripts are not available for review.

The guide on permutation tests and y-scrambling covers the companion check, which asks how high the best score of the same search climbs when the target is pure noise.

Key points

  • A searched equation carries the degrees of freedom of the whole search, not just its two coefficients.
  • Picking the best of many noisy scores inflates the winner's score. With 100 equal candidates and noise of 0.05 the inflation is about 0.125 in r.
  • Nested cross-validation runs the full search inside each outer fold and scores the winner on untouched molecules.
  • The outer average scores the procedure. Disagreeing winners across folds signal a plateau, not a single best equation.
  • Pass groups to both loops. A final untouched held-out set remains the cleanest single figure.

Questions people ask

What is nested cross-validation?
It is two cross-validation loops, one inside the other. The inner loop runs on the training part of each outer fold and chooses the descriptors, exponents or hyperparameters. The outer loop scores that choice on molecules the inner loop never saw. The outer scores estimate how the whole search procedure performs.
Why is the best cross-validation score of a search optimistic?
Each candidate's score is a noisy estimate, and picking the maximum of many noisy estimates picks the one whose noise was most favourable. The chosen candidate's score is therefore biased upward by an amount that grows with the number of candidates and shrinks with the dataset size.
Does nested cross-validation give me a single final model?
Not by itself. It gives an honest score for the procedure, and the procedure may pick different equations in different outer folds. The final model is obtained by running the search once on all training data, and its honest score is the outer average, not its own inner score.

Further reading

In practice: The methodology page describes the checks applied to every kernel, scaffold-blind split included, and the limits of those checks. Every kernel page quotes the held-out figure first and the in-sample figure second.

See the kernels themselves

Every kernel is shown with its held-out result, the number of molecules it rests on and what it cannot be trusted for.