Sub topic 14
Inspecting and copying estimators with get_params, set_params, and clone
This chapter assumes you can fit an estimator and know the difference between constructor arguments (hyperparameters) and attributes ending in an underscore (learned values). It also assumes you have used Pipeline at a basic level. Here you will learn how scikit-learn exposes an estimator's configuration, how to change it safely, and how to make a fresh unfitted copy.
Why configuration needs its own interface
Every scikit-learn estimator is built from two kinds of state:
- Configuration. The values you pass to the constructor, such as
C=0.5forLogisticRegression. - Learned state. The values computed by
fit, such ascoef_. These end in an underscore.
Tools like cross-validation and grid search need to create many copies of the same model. Each copy must have the same configuration but none of the learned state. If a copy kept the learned state from an earlier fit, results from one fold could leak into the next. The three methods in this chapter exist to make that copying reliable.
| Tool | What it does | Touches learned state? |
|---|---|---|
| `get_params()` | Returns the constructor settings as a dictionary | No |
| `set_params(**params)` | Changes constructor settings in place and returns the estimator | No, but old fitted attributes remain until you refit |
| `clone(estimator)` | Builds a new, unfitted estimator with the same settings | No, learned state is discarded |
Reading settings with get_params
get_params returns a dictionary that maps each constructor argument name to its current value.
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(C=0.5)
params = model.get_params()
print(params["C"]) # 0.5
print(params["max_iter"]) # 100, the default
print(sorted(params)[:4])The dictionary includes arguments you did not set, filled in with their defaults. This makes it a convenient way to see exactly what a model will do before you fit it.
get_params finds the argument names by reading the signature of __init__. For that reason, scikit-learn expects every constructor argument to be stored on the object under the same name. This rule matters again in the last section, where you write your own estimator.
Changing settings with set_params
set_params takes keyword arguments, updates the estimator, and returns the estimator itself. Returning self allows chaining.
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(C=0.5)
model.set_params(C=2.0, max_iter=500)
print(model.C, model.max_iter) # 2.0 500Assigning the attribute directly (model.C = 2.0) also works for simple estimators. set_params is preferred because it validates that the name is a real parameter. A typo raises an error instead of silently creating an unused attribute.
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
try:
model.set_params(Cc=1.0)
except ValueError as err:
print("Rejected:", type(err).__name__)Changing parameters does not undo fitting
set_params changes configuration only. If the model was already fitted, the learned attributes are still there and still reflect the old settings.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
model = LogisticRegression(C=0.01, max_iter=200).fit(X, y)
before = model.coef_.copy()
model.set_params(C=100.0)
print((model.coef_ == before).all()) # True: nothing relearned yet
model.fit(X, y)
print((model.coef_ == before).all()) # False: refit used the new CMaking a fresh copy with clone
clone creates a new estimator of the same class. It calls get_params(deep=False), builds a new object from those values, and does not copy anything learned during fit.
from sklearn.base import clone
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
original = LogisticRegression(C=0.5, max_iter=200).fit(X, y)
copy = clone(original)
print(hasattr(original, "coef_")) # True
print(hasattr(copy, "coef_")) # False
print(copy.get_params()["C"]) # 0.5Compare this with copy.deepcopy, which duplicates everything, including the fitted attributes. Use clone when you want a clean start with the same configuration. Use deepcopy only when you want to preserve a trained model, for example to snapshot it before experimenting.
You can change a setting in the same expression, because set_params returns the estimator:
from sklearn.base import clone
from sklearn.linear_model import LogisticRegression
a = LogisticRegression(C=0.5)
b = clone(a).set_params(C=2.0)
print(a.C, b.C) # 0.5 2.0The original a is unchanged. This is the standard pattern for trying several configurations from one template.
Where clone is used for you
You rarely call clone directly in everyday work, but scikit-learn calls it constantly:
cross_val_scoreclones the estimator for every fold, so each fold starts unfitted.GridSearchCVclones the estimator for every parameter combination.PipelineandColumnTransformerclone their steps in some workflows, such as when used inside cross-validation.
This is why passing the same estimator object to cross_val_score repeatedly is safe. The object you pass is not fitted by the call.
Nested parameters in pipelines
A Pipeline is itself an estimator, so it has get_params and set_params. Its parameters include those of its steps, addressed with a double underscore: stepname__parametername.
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
pipe = Pipeline([
("scale", StandardScaler()),
("model", LogisticRegression()),
])
print(pipe.get_params()["model__C"]) # 1.0
pipe.set_params(model__C=10.0, scale__with_mean=False)
print(pipe.named_steps["model"].C) # 10.0get_params(deep=True), the default, includes these nested names. get_params(deep=False) returns only the top-level arguments, which for a pipeline are steps, memory, verbose, and transform_input. The nested naming is what lets GridSearchCV tune a parameter inside a pipeline, for example model__C.
Rules that make this work
get_params, set_params, and clone all rely on the same conventions. Estimators that break them fail in confusing ways, usually inside clone or a grid search.
- Every
__init__argument has a default value.cloneand tools likeGridSearchCVmust be able to build an object from the parameters alone. - Store each argument under the same name, unchanged. Write
self.offset = offsetand nothing else. Do not convert, validate, or compute from it in__init__. - Do no work in
__init__. Validation and conversion belong infit, becauseset_paramscan change a value after construction and bypass the constructor. - Put learned values in attributes ending in an underscore. Anything without the trailing underscore is treated as configuration.
When clone builds the new object, it checks that each parameter on the copy is the same object that was passed in. If __init__ modified a value, for example by turning a list into a tuple, clone raises a RuntimeError saying the constructor did not set the parameter correctly.
from sklearn.base import BaseEstimator, clone
class BadEstimator(BaseEstimator):
def __init__(self, values=None):
# Breaks the rule: stores a modified copy, not the original.
self.values = list(values) if values is not None else []
try:
clone(BadEstimator(values=(1, 2)))
except RuntimeError as err:
print("clone failed:", type(err).__name__)The fix is to store values as given and convert it later, inside fit:
from sklearn.base import BaseEstimator, clone
class GoodEstimator(BaseEstimator):
def __init__(self, values=None):
self.values = values
def fit(self, X, y=None):
self.values_ = list(self.values) if self.values is not None else []
return self
print(clone(GoodEstimator(values=(1, 2))).values) # (1, 2)Note the learned values_ with a trailing underscore, set in fit, next to the untouched values.
Common errors
- Using a fitted model after
set_params. The learned attributes are stale. Refit before predicting. - Expecting
cloneto copy trained weights. It does not. Usecopy.deepcopyif you need the fitted state. - Misspelled nested names.
set_params(model_C=1)with a single underscore raisesValueError. Usemodel__C. You can list valid names withpipe.get_params().keys(). - Assigning to the same object and thinking you made a copy.
b = amakes both names point to one estimator. Changingbchangesa. Useclone(a)instead. - Doing work in
__init__of a custom estimator. This breakscloneand grid search, as shown above.
Exercise
You build base = LogisticRegression(C=1.0, max_iter=200) and fit it on training data. You then run variant = clone(base).set_params(C=10.0) and call variant.predict(X_test) without fitting. What happens, and what is the value of base.C afterwards?
Show answer
variant.predict(X_test) raises a NotFittedError, because clone discards learned attributes and variant has not been fitted. base.C is still 1.0, because clone made a separate object and set_params changed only that new object. The fitted base keeps its coefficients.
Exercise
A custom transformer has __init__(self, columns) and contains the line self.columns = list(columns). Calling clone on it with columns=("a", "b") fails. Why, and how do you fix it?
Show answer
clone compares the parameter on the new object with the value it passed in. Because __init__ converted the tuple into a list, the stored value is a different object and clone raises a RuntimeError. The fix is to write self.columns = columns in __init__ and convert the value inside fit, storing the result under a name with a trailing underscore such as self.columns_. Also give columns a default value such as None.