Sub topic 13
Counting the fits and keeping cost under control
Nested cross-validation gives an honest estimate, but it multiplies the training work. This chapter shows how to count the model fits before you launch a run, and which changes reduce cost without breaking the estimate.
You should already know how GridSearchCV and cross_val_score work, and how nested cross-validation is built from them. This chapter assumes that earlier material and does not repeat it.
The fit-count formula
Every fit of an estimator is one unit of cost. Take these quantities:
K_o: the number of outer folds.K_i: the number of inner folds.C: the number of candidate hyperparameter settings.
For each outer fold, GridSearchCV fits K_i × C models during the search. With the default refit=True, it then fits one more model on the whole outer training set using the best setting. The total is:
total fits = K_o × (K_i × C + 1)Scoring is not counted here. Scoring is usually much cheaper than fitting, but it can matter for slow predict methods such as k-nearest neighbors on large data.
The table uses the 3 × 3 grid from earlier chapters, so C = 9.
| Procedure | Formula | Fits |
|---|---|---|
| Plain grid search, 5 folds | 5 × 9 + 1 | 46 |
| Nested CV, 5 outer, 5 inner | 5 × (5 × 9 + 1) | 230 |
| Nested CV, 10 outer, 5 inner | 10 × (5 × 9 + 1) | 460 |
| Nested CV, 5 outer, 3 inner | 5 × (3 × 9 + 1) | 140 |
| Final model on all data | 5 × 9 + 1 | 46 |
Nested cross-validation costs roughly K_o times a plain grid search. If you also fit the final model, add one more plain search to the total. The nested run and the final run are separate jobs, so the final search does not reuse the nested fits.
Verifying the count
You can check the formula by counting calls to fit. The estimator below is a thin subclass of SVC that increments a class-level counter. The counter works because n_jobs is left at 1, so every fit happens in the same process.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
class CountingSVC(SVC):
n_fits = 0
def fit(self, X, y, sample_weight=None):
CountingSVC.n_fits += 1
return super().fit(X, y, sample_weight=sample_weight)
X, y = load_breast_cancer(return_X_y=True)
inner_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
outer_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=2)
pipe = Pipeline([("scale", StandardScaler()), ("clf", CountingSVC())])
param_grid = {"clf__C": [0.1, 1, 10], "clf__gamma": ["scale", 0.01, 0.001]}
search = GridSearchCV(pipe, param_grid, cv=inner_cv)
cross_val_score(search, X, y, cv=outer_cv)
k_outer, k_inner, n_candidates = 5, 5, 9
expected = k_outer * (k_inner * n_candidates + 1)
print("counted fits:", CountingSVC.n_fits)
print("formula: ", expected)Both lines print 230. Run this kind of check before a long job. If the counted number differs from your expectation, the grid or the cross-validation setup is not what you thought.
Where the cost grows
The formula shows that each factor multiplies the others.
- Adding one hyperparameter with 4 values multiplies
Cby 4. A grid of 3 × 3 × 4 has 36 candidates, so the nested run above grows to 5 × (5 × 36 + 1) = 905 fits. - Going from 5 to 10 outer folds doubles the cost. Each fit is also on more data, so it is slightly slower.
- The cost of a single fit often grows faster than linearly with the number of rows. For an SVM it is between quadratic and cubic in the number of samples, so doubling the data can multiply the run time by four or more.
Estimate the time of one fit first, then multiply. A quick way is to time a single fit on one outer training set, using the settings you expect to be slowest. Large C values in an SVM and deep trees in a boosting model are often the slowest candidates.
Ways to reduce the cost
Each option below trades something. The last column says what.
| Change | Effect on fits | What you give up |
|---|---|---|
| Fewer inner folds (for example 3) | Reduces `K_i` | Noisier choice of hyperparameters in each outer fold |
| Fewer outer folds (for example 5 instead of 10) | Reduces `K_o` | A noisier performance estimate, and a more pessimistic one because models train on less data |
| Smaller or coarser grid | Reduces `C` | May miss a better region |
| Random search | Fixes the number of candidates at `n_iter` | Not guaranteed to hit the best grid point |
| Successive halving | Drops weak candidates early | Early rounds use little data, so a slow starter can be dropped |
| Parallel execution | Same fits, less wall-clock time | More memory and CPU needed |
| Cached preprocessing | Same fits, cheaper ones | Disk space |
Reducing the inner loop and reducing the outer loop affect different things. The outer loop produces the performance estimate, so shrinking it makes the estimate noisier. The inner loop only chooses hyperparameters, so shrinking it makes the choice less reliable. Either way, the estimate stays honest, because the outer test folds are still never used for selection. Keep K_o at 5 or more unless you have a strong reason.
Random search instead of a full grid
A grid spends its budget on a fixed lattice. Random search draws n_iter settings from distributions, so the cost is K_o × (K_i × n_iter + 1) regardless of how many hyperparameters you add. It also covers continuous ranges that a grid would have to discretize.
from scipy.stats import loguniform
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
inner_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
outer_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=2)
pipe = make_pipeline(StandardScaler(), SVC())
param_dist = {
"svc__C": loguniform(1e-2, 1e2),
"svc__gamma": loguniform(1e-4, 1e-1),
}
search = RandomizedSearchCV(
pipe, param_dist, n_iter=10, cv=inner_cv, random_state=0
)
scores = cross_val_score(search, X, y, cv=outer_cv)
print(f"nested CV accuracy: {scores.mean():.3f} +/- {scores.std():.3f}")This run costs 5 × (5 × 10 + 1) = 255 fits. Because random_state=0 is an integer, every outer fold draws the same 10 candidates. That keeps runs reproducible and makes outer folds comparable.
Successive halving
HalvingGridSearchCV and HalvingRandomSearchCV start all candidates on a small amount of data, keep the best fraction, and give the survivors more data in each round. They can cut the search cost by a large factor when fits are expensive. They are still marked experimental, so you need an explicit import:
from sklearn.experimental import enable_halving_search_cv # noqa: F401
from sklearn.model_selection import HalvingGridSearchCVYou then use HalvingGridSearchCV in place of GridSearchCV inside cross_val_score. Because it ranks candidates on small subsets first, check that your model's ranking on small data resembles its ranking on full data. This often holds for regularization strength and often fails for hyperparameters whose effect depends on sample size, such as tree depth.
Parallelism and caching
Use n_jobs=-1 on the inner search. It produces K_i × C independent tasks per outer fold, which is enough to keep many cores busy. Putting n_jobs on cross_val_score as well gives only K_o outer tasks and risks running more processes than you have cores.
If the pipeline has an expensive preprocessing step, pass memory to make_pipeline (a directory path or a joblib.Memory object). Fitted transformers are then cached by their input data and parameters. A step that does not depend on the hyperparameters being searched is fitted once per inner training set instead of once per candidate. This helps when you tune only the final model and the transformer is slow, such as a large PCA. It helps little with a cheap StandardScaler.
Choosing what to cut
A practical order of decisions:
- Count the fits with the formula and time one slow fit. Multiply to get a run-time estimate.
- If it is too long, shrink the search first: a random search with a modest
n_iter, or a coarser grid. - Then reduce
K_ito 3. - Parallelize at one level.
- Reduce
K_olast, and not below 5 for a final report.
Develop on a subsample of the rows. Once the code runs and the grid looks sensible, run the full nested procedure once for the number you report.
Exercise
You plan a nested run with 10 outer folds, 3 inner folds, and a grid of 4 values of one hyperparameter times 5 values of another, with refit=True. How many fits does it perform? You then replace the grid with RandomizedSearchCV using n_iter=15. How many fits now?
Show answer
The grid has C = 4 × 5 = 20 candidates, so the total is 10 × (3 × 20 + 1) = 610 fits. With random search and n_iter = 15 the total is 10 × (3 × 15 + 1) = 460 fits.
Exercise
A colleague halves the cost of a nested run by cutting the outer loop from 10 folds to 5. Does the nested score stay unbiased? What changes?
Show answer
The outer test folds are still never used for selection, so the estimate stays free of selection bias. What changes is that each model trains on 80% of the data instead of 90%, which tends to make the score slightly pessimistic, and fewer outer scores are averaged, so the estimate is noisier.