FrozenEstimator
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
This page was checked in October 2026 against scikit-learn 1.9 (1.9.1, released September 2026) on Python 3.13 with NumPy 2.5, and every example was run on those versions. FrozenEstimator was introduced in scikit-learn 1.6 (December 2024), and the 1.6 to 1.9 release notes list no behaviour changes to it afterwards.
Almost everything in scikit-learn assumes that fit learns something. A meta-estimator such as GridSearchCV, CalibratedClassifierCV or Pipeline clones the estimators it receives and fits the clones, so a model you trained yesterday, or one that someone else trained, cannot be passed in directly. sklearn.frozen.FrozenEstimator is the official answer: it wraps a fitted estimator so that calling fit has no effect, and clone returns the very same object instead of an unfitted copy.
What a frozen estimator does
FrozenEstimator(estimator) takes one argument, the already fitted estimator, and behaves as follows.
| Operation | Behaviour |
|---|---|
|
Does nothing and returns the frozen object. Extra positional and keyword arguments are accepted and ignored. It still checks that the inner estimator is fitted, so wrapping an unfitted model raises |
|
Delegated to the inner estimator. Fitted attributes such as |
|
Not available: accessing them raises |
|
Returns the same frozen object, with its fitted state. A normal clone would return an unfitted copy. This works through the |
|
Returns only |
|
Only the key |
|
True when the inner estimator is fitted, so |
Estimator tags |
Copied from the inner estimator, so the wrapper reports the same task type and capabilities. |
|
Available when the inner estimator is a |
The example below shows each of these in a few lines.
import numpy as np
from sklearn import clone
from sklearn.datasets import make_classification
from sklearn.frozen import FrozenEstimator
from sklearn.linear_model import LogisticRegression
X, y = make_classification(n_samples=400, random_state=0)
X_train, y_train = X[:300], y[:300]
X_new, y_new = X[300:], y[300:]
clf = LogisticRegression(random_state=0).fit(X_train, y_train)
frozen = FrozenEstimator(clf)
print(frozen)
print("fit returns self:", frozen.fit(X_new, y_new) is frozen)
print("same predictions:", np.array_equal(frozen.predict(X_new), clf.predict(X_new)))
print("delegated attribute:", frozen.coef_ is clf.coef_)
print("clone returns the same object:", clone(frozen) is frozen)
print("get_params:", frozen.get_params())
print("is fitted:", frozen.__sklearn_is_fitted__())
Output:
FrozenEstimator(estimator=LogisticRegression(random_state=0))
fit returns self: True
same predictions: True
delegated attribute: True
clone returns the same object: True
get_params: {'estimator': LogisticRegression(random_state=0)}
is fitted: True
What it refuses to do
from sklearn.datasets import make_classification
from sklearn.exceptions import NotFittedError
from sklearn.frozen import FrozenEstimator
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
X, y = make_classification(random_state=0)
fitted = FrozenEstimator(StandardScaler().fit(X))
for name in ("fit_predict", "fit_transform"):
try:
getattr(fitted, name)
except AttributeError as exc:
print("AttributeError:", exc)
try:
fitted.set_params(with_mean=False)
except ValueError as exc:
print("ValueError:", str(exc).split(" You can use")[0])
fitted.estimator.set_params(with_mean=False) # the supported route
print(fitted.estimator)
try:
FrozenEstimator(LogisticRegression()).fit(X, y)
except NotFittedError as exc:
print("NotFittedError:", str(exc).split(" Call")[0])
Output:
AttributeError: fit_predict is not available for frozen estimators. AttributeError: fit_transform is not available for frozen estimators. ValueError: You cannot set parameters of the inner estimator in a frozen estimator since calling `fit` has no effect. StandardScaler(with_mean=False) NotFittedError: This LogisticRegression instance is not fitted yet.
Notice the last-but-one lines: editing the inner estimator is possible, and it changes the object everybody shares, but it does not refit it. Treat the wrapped model as read-only.
Source: sklearn.frozen.FrozenEstimator.
How a pipeline treats a frozen step
A pipeline or a search clones every step before fitting, and a cloned frozen step is the original object. That is what lets pipeline.fit(X, y) train the last step while the frozen first step keeps the statistics it learned elsewhere. Because the object is shared, any copy of the pipeline (including those created by GridSearchCV and cross_val_score) uses the same fitted state.
Calibrating a model that is already trained
This is the use case that motivated the class. Before 1.6, CalibratedClassifierCV(clf, cv="prefit") calibrated a fitted classifier. That option was deprecated in 1.6, raised a FutureWarning in 1.7, and is rejected in 1.9.1: cv must be an integer, a splitter or an iterable. The replacement is to freeze the model.
| Older code | Current code |
|---|---|
|
|
All the data given to fit is used to learn the calibrator, because there is no cross-validation to split. It is up to you to keep that data disjoint from the data the classifier was trained on. The example uses three disjoint sets: one to train the classifier, one to calibrate and one to measure.
import numpy as np
from sklearn.calibration import CalibratedClassifierCV
from sklearn.datasets import make_classification
from sklearn.frozen import FrozenEstimator
from sklearn.metrics import brier_score_loss
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC
X, y = make_classification(n_samples=3000, n_informative=5, flip_y=0.1, random_state=0)
X_train, X_rest, y_train, y_rest = train_test_split(X, y, test_size=0.6, random_state=0)
X_cal, X_test, y_cal, y_test = train_test_split(X_rest, y_rest, test_size=0.5, random_state=0)
svc = LinearSVC(random_state=0).fit(X_train, y_train) # trained once, elsewhere
calibrated = CalibratedClassifierCV(FrozenEstimator(svc), method="sigmoid")
calibrated.fit(X_cal, y_cal) # only the calibrator is learned
proba = calibrated.predict_proba(X_test)[:, 1]
raw = 1 / (1 + np.exp(-svc.decision_function(X_test))) # naive squashing of raw margins
print("Brier, raw margins squashed:", round(brier_score_loss(y_test, raw), 4))
print("Brier, calibrated: ", round(brier_score_loss(y_test, proba), 4))
print("calibrated_classifiers_:", len(calibrated.calibrated_classifiers_))
print("base model untouched:", calibrated.calibrated_classifiers_[0].estimator.estimator is svc)
Output:
Brier, raw margins squashed: 0.1533 Brier, calibrated: 0.1147 calibrated_classifiers_: 1 base model untouched: True
A lower Brier score means better probabilities. The calibrated model holds a single (classifier, calibrator) pair, and the classifier inside it is your original svc. The full treatment of the sigmoid, isotonic and temperature methods and of calibration curves is in Probability Calibration.
Post-hoc decision thresholds without refitting
The same wrapper stops the threshold meta-estimators from refitting the model. The user guide recommends FixedThresholdClassifier(FrozenEstimator(estimator), ...) when you want to set a cut-off manually without retraining, and the pattern works for TunedThresholdClassifierCV too.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.frozen import FrozenEstimator
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
from sklearn.model_selection import FixedThresholdClassifier, TunedThresholdClassifierCV, train_test_split
X, y = make_classification(n_samples=2000, weights=[0.9], flip_y=0.05, random_state=0)
X_train, X_rest, y_train, y_rest = train_test_split(X, y, test_size=0.5, stratify=y, random_state=0)
X_val, X_test, y_val, y_test = train_test_split(X_rest, y_rest, test_size=0.5, stratify=y_rest, random_state=0)
base = LogisticRegression(random_state=0).fit(X_train, y_train)
frozen = FrozenEstimator(base)
fixed = FixedThresholdClassifier(frozen, threshold=0.25, response_method="predict_proba").fit(X_val, y_val)
tuned = TunedThresholdClassifierCV(frozen, scoring="f1", response_method="predict_proba", cv=5).fit(X_val, y_val)
print("default 0.5 :", round(f1_score(y_test, base.predict(X_test)), 3))
print("fixed 0.25 :", round(f1_score(y_test, fixed.predict(X_test)), 3))
print("tuned :", round(f1_score(y_test, tuned.predict(X_test)), 3), "threshold", round(float(tuned.best_threshold_), 3))
print("coefficients unchanged:", np.array_equal(base.coef_, frozen.estimator.coef_))
Output:
default 0.5 : 0.881 fixed 0.25 : 0.842 tuned : 0.873 threshold 0.323 coefficients unchanged: True
The scores are not the point: on this dataset the default cut-off is already good, and a threshold picked on a small validation set can even lose a little on the test set. What the example shows is the mechanism: the threshold is learned or applied on X_val while the classifier stays exactly as trained on X_train. See Tuning the Decision Threshold.
A pre-trained transformer inside a pipeline
Use a frozen step when part of the pipeline comes from elsewhere: a scaler fitted on a large reference dataset, a vectoriser trained once on a corpus, a feature extractor shipped with a model. The step is applied in transform and ignored in fit.
import numpy as np
from sklearn import clone
from sklearn.datasets import make_classification
from sklearn.frozen import FrozenEstimator
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X_pre, _ = make_classification(n_samples=2000, random_state=1) # data the scaler was fitted on
X, y = make_classification(n_samples=300, random_state=0)
scaler = StandardScaler().fit(X_pre)
mean_before = scaler.mean_.copy()
pipe = Pipeline([("scale", FrozenEstimator(scaler)), ("clf", LogisticRegression())])
search = GridSearchCV(pipe, {"clf__C": [0.1, 1.0, 10.0]}, cv=3).fit(X, y)
print("best C:", search.best_params_)
print("scaler statistics unchanged:", np.array_equal(scaler.mean_, mean_before))
print("step shared with the clone:", clone(pipe).named_steps["scale"] is pipe.named_steps["scale"])
print("refit pipeline step is the same object:", search.best_estimator_.named_steps["scale"] is pipe.named_steps["scale"])
# Careful: cross-validating a frozen model does not retrain it
clf = LogisticRegression().fit(X[:200], y[:200])
print(cross_val_score(FrozenEstimator(clf), X[200:], y[200:], cv=3).round(2))
# Its parameters are unreachable from the pipeline
try:
pipe.set_params(scale__with_mean=False)
except ValueError as exc:
print("ValueError:", str(exc).split(" You can use")[0])
Output:
best C: {'clf__C': 1.0}
scaler statistics unchanged: True
step shared with the clone: True
refit pipeline step is the same object: True
[0.91 0.91 0.88]
ValueError: You cannot set parameters of the inner estimator in a frozen estimator since calling `fit` has no effect.
The grid search tunes C of the last step. The frozen scaler is never refitted, even inside the search’s cross-validation, so its statistics come only from the reference data and the validation folds do not influence it. The search cannot tune the scaler’s own parameters, by design.
Pitfalls
-
Frozen means not retrained, not validated.
cross_val_score(FrozenEstimator(clf), X, y)scores the model you already have on each fold. Ifclfsaw those rows during its training, the numbers are optimistic. Evaluate a frozen model on data it never saw. -
Disjoint data for the meta-estimator. With
CalibratedClassifierCV(FrozenEstimator(...)), all rows given tofittrain the calibrator. Reusing the classifier’s training rows calibrates on the data it memorised and produces overconfident probabilities. The same holds for the threshold classifiers. -
Shared mutable state.
clonereturns the same object, so every clone, parallel worker thread and search candidate shares one fitted model. Editing the inner estimator (frozen.estimator.set_params(...)or assigning attributes) changes it everywhere. Do not mutate it after wrapping. -
Ignored arguments.
fitaccepts and ignoresX,yand any extra arguments, includingsample_weight. A call that looks like training has no effect, and nothing warns you about weights passed to it. -
Unreachable parameters. Grid and random searches cannot tune the inner estimator, and
set_paramswith an inner key raises. If the step must be tuned, do not freeze it. -
Fit must have happened first. The wrapper checks
check_is_fittedinsidefit. A model that fails to load, or that was never trained, surfaces asNotFittedErroronly when the enclosing pipeline is fitted. -
No
fit_transform. Code that callsfit_transformon the frozen object (a hand-written loop over pipeline steps, for example) fails withAttributeError. Usefit(X).transform(X)or calltransformon its own. -
Version coupling. A frozen model is still a pickled scikit-learn object. Loading it with another scikit-learn version is unsupported and can break or silently change results; see Model Persistence and Security and never unpickle a file you do not trust.
-
Old code with
cv="prefit". Replace it as in the table above.StackingClassifierandStackingRegressorare different: they keep their owncv="prefit"option (added in 1.1), which trains the final estimator on in-sample predictions of the fitted base models. The official documentation warns of a very high risk of overfitting if those models were trained on the same data.