Sub topic 13
Counting the fits and keeping cost under control
This chapter assumes you can run GridSearchCV and cross_val_score, and that you know how nested cross-validation separates an inner selection loop from an outer evaluation loop. Here we count how many models a nested run trains and look at ways to cut that number.
Counting the fits
Nested cross-validation multiplies the cost of a grid search by the number of outer folds. Take these values:
Couter foldsKinner foldsGcandidate settings in the grid
Each outer fold runs a full grid search on its training part. That search fits G × K models. After the search, refit=True (the default) fits one more model on the whole outer training part. The total is:
C × (G × K + 1)
For the grid used in this tutorial, G = 3 × 3 = 9, with K = 5 and C = 5. That gives 5 × (9 × 5 + 1) = 230 fits. A plain grid search with the same grid needs 9 × 5 + 1 = 46. Nested cross-validation costs five times as much here, which matches C = 5.
You can check the count without running any search:
def nested_fit_count(outer_folds, inner_folds, grid_size, refit=True):
per_search = grid_size * inner_folds + (1 if refit else 0)
return outer_folds * per_search
grid_size = 3 * 3
print("plain grid search:", nested_fit_count(1, 5, grid_size))
print("nested 5x5:", nested_fit_count(5, 5, grid_size))
print("nested 10x5:", nested_fit_count(10, 5, grid_size))The last line prints 460. Going from 5 to 10 outer folds doubles the cost.
Ways to reduce the cost
The options below trade accuracy or coverage for speed. Choose them knowing what you give up.
| Option | What it does | What you give up |
|---|---|---|
| Fewer outer folds | Cuts cost linearly | The estimate rests on fewer test folds and is noisier |
| Fewer inner folds | Cuts cost linearly | Selection is less stable |
| Smaller grid | Cuts `G` | You may miss a better setting |
| `RandomizedSearchCV` | Samples `n_iter` settings instead of a full grid | Results are random unless you set `random_state` |
| `HalvingGridSearchCV` | Drops weak candidates early | Needs an experimental import; early scores can mislead |
| `n_jobs` | Runs fits in parallel | Uses more memory and CPU |
RandomizedSearchCV helps most when the grid grows with several hyperparameters, because the cost depends on n_iter and not on the grid size.
Parallelism: pick one level
You can set n_jobs on the inner search, on cross_val_score, or on both. Setting it on both can create more workers than your machine has cores. A common choice is to parallelize the outer loop only. Each worker then runs one whole inner search, and the tasks are large and few.
import time
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, 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_grid = {"svc__C": [0.1, 1, 10], "svc__gamma": ["scale", 0.01, 0.001]}
search = GridSearchCV(pipe, param_grid, cv=inner_cv) # inner stays serial
start = time.perf_counter()
scores = cross_val_score(search, X, y, cv=outer_cv, n_jobs=-1) # outer runs in parallel
elapsed = time.perf_counter() - start
print(f"accuracy: {scores.mean():.3f}")
print(f"elapsed: {elapsed:.1f} s")With five outer folds, at most five workers do useful work. On a machine with more cores, you could also parallelize the inner search, but check that the total worker count stays reasonable.
Exercise
You use 10 outer folds, 5 inner folds, and a RandomizedSearchCV with n_iter=20 and refit=True. How many fits does one nested run perform?
Show answer
Each inner search fits 20 × 5 + 1 = 101 models. With 10 outer folds the total is 10 × 101 = 1010 fits.
Exercise
You set n_jobs=-1 on both the inner GridSearchCV and on cross_val_score. Why can this be a problem, and what is a simple fix?
Show answer
Each outer worker starts its own set of inner workers, so the number of processes can far exceed the number of cores. This causes memory pressure and slowdowns. A simple fix is to set n_jobs only on cross_val_score and leave the inner search serial.