Sub topic 8
Hyperparameters versus attributes learned in fit
This chapter assumes you can fit an estimator and call predict and score on held-out data. It also assumes you know that X is a 2D feature matrix and y is a 1D label vector. Every scikit-learn estimator keeps two kinds of state, and they have different owners. You, the programmer, choose the first kind. The data produces the second kind.
Two kinds of state
A hyperparameter is a setting you choose before training. Examples are C and max_iter for LogisticRegression, or with_mean for StandardScaler. You pass hyperparameters to the constructor, and the estimator stores them unchanged under the same name.
A fitted attribute is a value the estimator computes from the training data inside fit. Examples are coef_, classes_, and mean_. By convention its name ends with an underscore.
| Row | Hyperparameters | Fitted attributes |
|---|---|---|
| Set by | You, in the constructor or `set_params` | The estimator, inside `fit` |
| Name | No trailing underscore (`C`) | Trailing underscore (`coef_`) |
| Exists before `fit` | Yes | No |
| Depends on the data | No | Yes |
| Read by | `get_params` | `check_is_fitted` and direct access |
Seeing the difference
This example builds a model and inspects it before and after fit.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
model = LogisticRegression(C=0.5, max_iter=200)
print(model.C, model.max_iter) # 0.5 200
print(hasattr(model, "coef_")) # False
model.fit(X, y)
print(hasattr(model, "coef_")) # True
print(model.coef_.shape) # (3, 4)
print(model.intercept_.shape) # (3,)
print(model.classes_) # [0 1 2]
print(model.n_features_in_) # 4Before fit, coef_ does not exist at all. It is not None and not an empty array. Accessing it raises AttributeError. The shape (3, 4) comes from the data: three classes in y and four columns in X. Nothing in the constructor mentions those numbers.
The trailing underscore convention
You can list the fitted attributes of an estimator by filtering for names that end with an underscore.
fitted = sorted(
name for name in vars(model)
if name.endswith("_") and not name.startswith("_")
)
print(fitted)
# includes: classes_, coef_, intercept_, n_features_in_, n_iter_These attributes appear on many estimators:
n_features_in_is the number of columns seen duringfit. Estimators use it to reject inputs with a different column count.feature_names_in_holds the column names. It is set only whenXis a DataFrame whose column names are all strings.classes_holds the sorted unique labels. Classifiers use it to map columns ofpredict_probaback to labels.coef_andintercept_hold the learned weights of linear models.mean_andscale_hold whatStandardScalerlearned.
The next example shows how a DataFrame sets feature_names_in_.
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
df = pd.DataFrame(X, columns=["sl", "sw", "pl", "pw"])
m = LogisticRegression(max_iter=200).fit(df, y)
print(m.feature_names_in_) # ['sl' 'sw' 'pl' 'pw']Calling fit with a DataFrame and later predict with a NumPy array triggers a warning that the model was fitted with feature names. Keep the input type consistent between the two calls.
Checking whether an estimator is fitted
Calling predict on an unfitted estimator raises NotFittedError. You can run the same check yourself with check_is_fitted. It looks for attributes that end with an underscore.
from sklearn.exceptions import NotFittedError
from sklearn.linear_model import LogisticRegression
from sklearn.utils.validation import check_is_fitted
fresh = LogisticRegression()
try:
check_is_fitted(fresh)
except NotFittedError:
print("not fitted yet")NotFittedError inherits from both ValueError and AttributeError. Existing handlers for either exception type will catch it.
Fitting again replaces learned state
Calling fit a second time does not accumulate knowledge. It discards the previous fitted attributes and computes new ones from the new data. This is true for almost every estimator. The exceptions are explicit options such as warm_start=True and methods named partial_fit.
import numpy as np
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(np.array([[1.0], [2.0], [3.0]]))
print(scaler.mean_) # [2.]
scaler.fit(np.array([[10.0], [20.0], [30.0]]))
print(scaler.mean_) # [20.]The second call forgets the first dataset entirely. If you want a model that learns from several batches, look for partial_fit on the estimator you use. Calling fit repeatedly on batches is a common mistake, and it leaves you with a model trained only on the last batch.
Changing a hyperparameter does not update the model
Hyperparameters are plain attributes, so you can change them at any time with set_params or by assignment. Changing one after fit has no effect on the fitted attributes. The fitted state stays as it was until you call fit again.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
model = LogisticRegression(C=0.5, max_iter=1000).fit(X, y)
before = model.coef_.copy()
model.set_params(C=100.0)
print(np.array_equal(before, model.coef_)) # True: nothing was relearned
model.fit(X, y)
print(np.array_equal(before, model.coef_)) # False: new C, new weightsAfter set_params(C=100.0), the object reports C=100.0 but its weights were learned under C=0.5. The object is now inconsistent: its settings describe one training run and its weights come from another. If you tune a hyperparameter, refit before you trust any prediction. Tools such as GridSearchCV avoid this problem by refitting a fresh copy for each candidate setting. The clone function that makes this possible is covered in a later chapter.
Hyperparameters describe the procedure, attributes describe the result
A useful test sorts any name into the right group. Ask whether the value would change if you swapped the training data for different data while keeping the code the same.
- If yes, it is learned.
mean_changes with the data, and so doesn_iter_, the number of iterations the solver actually ran. - If no, it is a hyperparameter.
max_iteris the iteration limit you chose.
max_iter and n_iter_ show the pattern well. You set the limit, and the solver reports how many iterations it used. If n_iter_ equals max_iter, the solver probably stopped at the limit without converging. That is the situation a ConvergenceWarning reports.
Random settings follow the same rule. random_state is a hyperparameter, because you choose it. The random numbers it produces are not stored as fitted attributes.
Rules for the constructor
scikit-learn estimators follow strict constructor rules. These rules make get_params, set_params, and clone work, and your own code will rely on them.
- Every argument has a default value, so
Estimator()works with no arguments. - Each argument is stored unchanged in an attribute with the same name.
self.C = C, notself.C = float(C). - The constructor does no computation and no validation. Validation happens in
fit. - The constructor creates no attributes ending in an underscore.
Rule 2 explains why you can read any setting as estimator.name. Rule 3 explains why a bad value, such as LogisticRegression(C=-1), often fails only when you call fit. The estimator checks C at that point and raises an error.
Common errors
- Reading an attribute too early.
AttributeError: 'LogisticRegression' object has no attribute 'coef_'meansfithas not run on this object. Check which object you calledfiton, sincefitreturnsselfand you may have discarded it. - Treating a tuned setting as learned. Printing
model.Cafter a search shows the value you set. It does not show anything the model derived from data. - Fitting on batches with
fit. Each call replaces the previous state. Usepartial_fitor train once on the combined data. - Mixing input types. A model fitted on a DataFrame warns when it later sees a bare array, because
feature_names_in_no longer matches.
Exercise
You run m = LogisticRegression(C=1.0).fit(X, y), then m.set_params(C=10.0), then m.predict(X_new). Which value of C do the predictions reflect, and what should you do to make them reflect the other one?
Show answer
The predictions reflect C=1.0. The weights in coef_ and intercept_ were learned during the original fit, and set_params only changes the stored hyperparameter. To get predictions that reflect C=10.0, call m.fit(X, y) again after set_params.
Exercise
A colleague writes a scaler whose __init__ sets self.mean_ = None. Why does this break scikit-learn's check for a fitted estimator, and where should mean_ be set instead?
Show answer
check_is_fitted treats any estimator with an attribute ending in an underscore as fitted, so the object would look fitted before fit runs, and predict or transform would fail later with a confusing error instead of NotFittedError. mean_ should be assigned inside fit, based on the training data.