Sub topic 12
Caching fitted steps during tuning
This chapter assumes you can build a Pipeline, you know GridSearchCV and the step__parameter naming convention, and you understand cross-validation folds. It covers the memory parameter of Pipeline. The parameter stores the output of fitted transformers on disk, so a search does not repeat the same expensive work.
Why tuning repeats work
GridSearchCV evaluates every combination of parameters on every fold. With 4 values of clf__C and cv=5, it runs 20 fits. Each fit refits the whole pipeline from the first step.
Suppose the first step is a slow transformer, such as PCA, a TF-IDF vectorizer, or a KNNImputer. Its parameters do not change between the four C values, and neither does its training data within a fold. So the search fits the same transformer on the same data 4 times per fold, and the result is identical each time.
Caching removes this waste. The pipeline remembers the result of fitting a step with a given set of parameters on a given input. When the same combination comes up again, it loads the stored result instead of fitting again.
The memory parameter
Pipeline accepts a memory argument. It can be:
None(the default), which means no caching.- A string, which is a directory path where results are stored.
- A
joblib.Memoryobject, which gives you control over verbosity and cleanup.
Joblib is the library scikit-learn uses for parallelism and for saving objects to disk. It does the hashing and storage here.
Caching applies to every step except the last one. The final estimator is never cached, so changing clf__C always triggers a real fit of the classifier. That is the behavior you want.
How the cache key works
For each transformer, joblib builds a key from:
- the transformer's parameters (the cloned, unfitted object), and
- a hash of the input data
Xandythat the step receives.
If the key matches a stored entry, the pipeline loads the saved fitted transformer and the transformed output. Otherwise it fits the step, stores both, and continues.
The input to each step includes the output of earlier steps. If an early step changes, every later step sees different data, so those later steps miss the cache too.
Measuring the effect
The example below tunes only the classifier after a PCA step. It runs the same search with and without caching. Absolute times depend on your machine, but the cached run should be clearly faster.
import time
from tempfile import TemporaryDirectory
from sklearn.datasets import make_classification
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
X, y = make_classification(
n_samples=3000, n_features=400, n_informative=30, random_state=0
)
param_grid = {"clf__C": [0.01, 0.1, 1, 10, 100]}
def run(memory):
pipe = Pipeline(
[
("pca", PCA(n_components=50, svd_solver="full", random_state=0)),
("clf", LogisticRegression(max_iter=1000)),
],
memory=memory,
)
search = GridSearchCV(pipe, param_grid, cv=5)
start = time.perf_counter()
search.fit(X, y)
return time.perf_counter() - start, search.best_params_
t_plain, best_plain = run(None)
with TemporaryDirectory() as cache_dir:
t_cached, best_cached = run(cache_dir)
print(f"no cache: {t_plain:.1f} s, best {best_plain}")
print(f"with cache: {t_cached:.1f} s, best {best_cached}")Both runs choose the same best parameters, because caching changes only the speed. PCA is fitted 25 times without the cache (5 values times 5 folds) and 5 times with it (once per fold), plus one extra fit during the final refit on all the data.
Counting fits to confirm hits
Timing is noisy. A more reliable check is to count how many times a transformer's fit runs. The subclass below increments a class-level counter. A class attribute works because clone copies parameters, not class attributes, so every cloned instance shares the same counter.
from tempfile import TemporaryDirectory
from sklearn.datasets import load_breast_cancer
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
class CountingScaler(StandardScaler):
fit_calls = 0
def fit(self, X, y=None, sample_weight=None):
type(self).fit_calls += 1
return super().fit(X, y, sample_weight)
X, y = load_breast_cancer(return_X_y=True)
X_train, _, y_train, _ = train_test_split(X, y, random_state=0)
param_grid = {"clf__C": [0.01, 0.1, 1, 10]}
def count_fits(memory):
CountingScaler.fit_calls = 0
pipe = Pipeline(
[("scale", CountingScaler()), ("clf", LogisticRegression(max_iter=1000))],
memory=memory,
)
GridSearchCV(pipe, param_grid, cv=5).fit(X_train, y_train)
return CountingScaler.fit_calls
print("without cache:", count_fits(None))
with TemporaryDirectory() as cache_dir:
print("with cache: ", count_fits(cache_dir))Expected output:
without cache: 21
with cache: 6The counts follow from the search structure. Without caching, there are 4 candidates times 5 folds = 20 fits, plus 1 refit of the best candidate on all training data. With caching, the scaler is fitted once per fold (5), because the 4 candidates in a fold share a key. The refit sees the full training set, which is different data, so it is a new key and one more fit.
Where caching helps and where it does not
The benefit depends on which step your grid varies.
| Grid varies | Effect of caching |
|---|---|
| Only the final estimator (`clf__C`) | Every earlier step hits the cache after its first fit per fold. Largest savings. |
| A middle step (`pca__n_components`) | Steps before it hit. The varied step and everything after it are refit for each new value. |
| The first step | Almost no hits within one search, because every later input differs. |
Take a grid with 3 values of pca__n_components and 4 values of clf__C, with cv=5. Without caching, PCA is fitted 3 × 4 × 5 = 60 times. With caching, it is fitted 3 × 5 = 15 times, because each (n_components, fold) pair is computed once and reused across the 4 values of C.
Caching also pays off across separate runs. If you give a persistent directory (not a temporary one), a rerun of the same search in a notebook or script finds the entries from the previous run.
Gotchas
The step you passed in is not the fitted step
When memory is set, the pipeline clones each transformer before fitting it. The object you passed in stays unfitted. The fitted copy replaces it inside the pipeline. Always read fitted state through the pipeline.
from tempfile import TemporaryDirectory
from sklearn.datasets import make_classification
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
X, y = make_classification(n_samples=300, n_features=40, random_state=0)
with TemporaryDirectory() as cache_dir:
pca = PCA(n_components=5)
pipe = Pipeline(
[("pca", pca), ("clf", LogisticRegression(max_iter=1000))],
memory=cache_dir,
)
pipe.fit(X, y)
print(hasattr(pca, "components_")) # False
print(pipe.named_steps["pca"].components_.shape) # (5, 40)The first line prints False because the original pca object was never fitted. The second reads the fitted copy through named_steps and prints (5, 40). This is the same access you used in the inspection chapter, and it is the only reliable way when caching is on.
Cheap steps can get slower
Before reading a stored result, joblib hashes the input arrays. For a large X, hashing takes time. A StandardScaler fits in milliseconds, so the hashing and disk reads can cost more than refitting. In the breast-cancer example above, the count drops from 21 to 6, but the wall-clock time is not guaranteed to improve. Cache steps that are slow to fit, such as decompositions, text vectorizers, kernel approximations, and neighbor-based imputers.
Disk use grows
Each stored entry holds a fitted transformer and its transformed output. A grid that varies a middle step across many folds can write many large arrays. Check the directory size, and clean up when you finish:
from joblib import Memory
memory = Memory(location="./pipeline_cache", verbose=0)
# ... build Pipeline(..., memory=memory) and run the search ...
memory.clear(warn=False) # deletes every cached entryWith a TemporaryDirectory, as in the examples above, cleanup happens when the with block exits.
Edited custom transformers can return stale results
Joblib invalidates an entry when the code of the cached function changes. The cached function is scikit-learn's internal fit helper, not your class. If you edit the fit method of your own transformer and reuse the same cache directory with the same parameters and data, the key does not change. You can get results from the old code. Clear the cache whenever you change a custom transformer.
The key is built from the transformer's parameters, so a custom transformer must follow the usual rules: every constructor argument is stored unchanged as an attribute with the same name. Otherwise clone and the hash can disagree with the real configuration.
Parallel workers and shared directories
With n_jobs greater than 1, worker processes share the same directory on disk. This works, but two workers can compute the same missing key at the same time before either writes it, so the savings can be smaller than the serial case. Do not share one cache directory between machines unless the filesystem handles concurrent writes safely.
Trust the cache directory
Stored entries are pickled Python objects, like files saved with joblib.dump. Loading them can run arbitrary code, so use directories that only you control.
Deciding whether to cache
- Identify the slowest step before the final estimator. If every earlier step fits in well under a second, skip caching.
- Check which parameters your grid varies. Caching helps most when the expensive step is early and stays fixed while later steps vary.
- Estimate the disk cost: transformed array size times the number of distinct (parameters, fold) combinations that reach each cached step.
- Use a
joblib.Memoryobject when you want a persistent location or explicit cleanup. Use a temporary directory for a one-off search.
Exercise
A pipeline is Pipeline([("tfidf", TfidfVectorizer()), ("svd", TruncatedSVD()), ("clf", LogisticRegression())], memory=cachedir). You run GridSearchCV with cv=5 and the grid {"svdncomponents": [50, 100], "clf__C": [0.1, 1, 10]}. How many times is TfidfVectorizer fitted during the search (ignore the final refit), and how many times is TruncatedSVD fitted? Explain why.
Show answer
TfidfVectorizer is fitted 5 times, once per fold. Its parameters never change and it sees the same fold data for every candidate, so every candidate after the first in a fold hits the cache. TruncatedSVD is fitted 2 × 5 = 10 times, once per (n_components, fold) pair. The 3 values of C share each pair's cached result. Without caching, both would be fitted 6 × 5 = 30 times.
Exercise
You enable memory on a pipeline, fit it, and then call scaler.mean_ on the StandardScaler object you passed to the pipeline. You get an AttributeError. Why does this happen, and what is the correct way to read the fitted mean?
Show answer
With memory set, the pipeline clones each transformer before fitting, so the object you passed in is never fitted. The fitted copy replaces it inside the pipeline. Read it with pipe.namedsteps["scale"].mean (or pipe["scale"].mean_).
Exercise
Name two situations where setting memory on a pipeline is unlikely to speed up a grid search.
Show answer
(1) The steps before the final estimator are cheap, such as StandardScaler on a small dataset, so hashing the data and reading from disk costs as much as refitting. (2) The grid varies the first step, so every candidate gives different inputs to later steps and almost nothing is reused within the search.