Sub topic 12
Caching fitted steps during tuning
This chapter assumes you can build a Pipeline, run GridSearchCV with step__param names, and read cross-validation scores. It shows how to stop a search from refitting the same preprocessing step over and over.
The problem: repeated work in a search
GridSearchCV fits the whole pipeline once for every parameter combination in every fold. Suppose the pipeline is a scaler, a PCA step, and a classifier, and you tune only the classifier's C. With 4 values of C and 5 folds, that is 20 fits. The scaler and PCA see the same training data in every fit for a given fold, so they produce the same result 4 times over.
Only the fold changes the input to the early steps. Everything before the tuned step could be fitted once per fold and reused.
The memory parameter
Pipeline accepts a memory argument. It can be a directory path or a joblib.Memory object. When it is set, the pipeline stores each fitted transformer on disk. The cache key is made from the transformer's parameters and the input data. If the same transformer is asked to fit the same data again, the pipeline loads the stored result instead of fitting.
The final estimator is never cached. Only the steps before it are.
from shutil import rmtree
from tempfile import mkdtemp
from time import perf_counter
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
param_grid = {"clf__C": [0.01, 0.1, 1, 10]}
def run(memory):
pipe = Pipeline(
[
("scale", StandardScaler()),
("pca", PCA(n_components=40)),
("clf", LogisticRegression(max_iter=2000)),
],
memory=memory,
)
search = GridSearchCV(pipe, param_grid, cv=5)
start = perf_counter()
search.fit(X_train, y_train)
return search, perf_counter() - start
_, t_plain = run(memory=None)
cache_dir = mkdtemp()
try:
search, t_cached = run(memory=cache_dir)
print(f"no cache: {t_plain:.2f}s, cache: {t_cached:.2f}s")
print(search.best_params_, search.score(X_test, y_test))
finally:
rmtree(cache_dir)Your timings will differ. On a dataset this small the saving is tiny, and the first run with an empty cache pays the cost of writing files. The cache pays off when an early step is slow, such as a large PCA, a text vectorizer, or a feature extractor, and the grid is wide.
What triggers a cache hit
The pipeline refits a step whenever the step's parameters or its input data change. Two situations matter in practice:
- Tuning a later step. Varying
clf__Cleaves the scaler and PCA unchanged, so they are loaded from the cache. - Tuning an early step. Varying
pca__n_componentschanges the PCA parameters, so PCA is refitted. Steps after PCA see new input and are refitted too. Steps before PCA, such as the scaler, still hit the cache.
Put the parameters you tune most often toward the end of the pipeline, where possible. More of the earlier steps can then be reused.
Gotchas
The cache changes how fitted objects behave, so check these points.
- The original transformer is not fitted. With caching on, the pipeline clones each transformer before fitting it. The object you passed in stays unfitted. Read fitted steps from the pipeline instead, for example
search.best_estimator_.named_steps["pca"]. - Caches use disk space. Each distinct fit writes a file. A wide grid on large data can fill a disk. Use a temporary directory and delete it when you are done, as the example does.
- Hashing large inputs costs time. joblib hashes the input to build the key. For fast transformers such as
StandardScaler, hashing and loading can take longer than refitting. Cache only when the early steps are expensive. - Stale caches are a risk with custom code. If you edit a custom transformer's code but keep its parameters, an old cache directory may still hold results from the earlier version. Use a fresh directory after changing such code.
Exercise
You run GridSearchCV on a pipeline of StandardScaler, a slow text-based feature step, and a classifier, with memory set. You tune only clf__C over 6 values with cv=5. How many times is the slow feature step fitted during the search, not counting the final refit, and why?
Show answer
Five times, once per fold. The step's parameters do not change as C varies, and the input for a given fold is identical across the 6 C values, so after the first fit on each fold the result is loaded from the cache. Without memory it would be fitted 30 times (6 values times 5 folds).
Exercise
After a cached search, you call search.bestestimator and want to inspect the fitted PCA. Why does the PCA object you originally put in the Pipeline raise a NotFittedError, and how do you get the fitted one?
Show answer
With memory enabled, the pipeline clones each transformer before fitting, so the original object is never fitted. Get the fitted copy from the pipeline itself, for example search.bestestimator.named_steps["pca"].