Sub topic 8
Hyperparameters versus attributes learned in fit
This chapter assumes you can write basic Python classes, know what fit and predict do on a scikit-learn estimator, and have split data with train_test_split. It separates two kinds of values on an estimator: settings you choose and values the estimator learns.
Two kinds of values
Every scikit-learn estimator holds two kinds of state.
- Hyperparameters are settings you pass to the constructor, such as
Cormax_iter. They control how the estimator learns. You choose them before training. - Fitted attributes are values the estimator computes from the training data inside
fit. Their names end with an underscore, such ascoef_ormean_.
The trailing underscore is a convention you can rely on. If an attribute ends in _, fit created it. If it has no underscore, you set it.
Seeing the difference in code
This example fits a model on the iris data and prints one value of each kind.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
model = LogisticRegression(max_iter=200)
print(model.max_iter) # 200, set by you
model.fit(X_train, y_train)
print(model.coef_.shape) # (3, 4), learned during fit
print(model.classes_) # [0 1 2]
print(model.predict(X_test[:5]))The shape (3, 4) comes from the data: three classes and four features. Changing the training data changes coef_. Changing max_iter changes how long the solver may run, but it is never overwritten by fit.
What happens before fit
Fitted attributes do not exist until fit runs. Reading one early raises an error.
from sklearn.linear_model import LogisticRegression
from sklearn.exceptions import NotFittedError
from sklearn.utils.validation import check_is_fitted
model = LogisticRegression()
try:
check_is_fitted(model)
except NotFittedError:
print("not fitted yet")
print(hasattr(model, "coef_")) # Falsecheck_is_fitted is the standard way to test this. Scikit-learn calls it inside predict and transform, so calling them on an unfitted estimator raises NotFittedError instead of returning nonsense.
Where the line falls
| Property | Hyperparameter | Fitted attribute |
|---|---|---|
| Set by | You, in the constructor | `fit` |
| Name | No trailing underscore | Trailing underscore |
| Depends on training data | No | Yes |
| Exists before `fit` | Yes | No |
| Example | `C`, `max_iter` | `coef_`, `classes_` |
A transformer follows the same rule. StandardScaler(with_mean=True) holds a hyperparameter. After fit, scaler.mean_ and scaler.scale_ hold the learned values.
Common errors
- Reading a fitted attribute too early.
model.coef_beforefitraisesAttributeError. Callfitfirst. - Assuming fit changes hyperparameters. It does not. If a model needs more iterations, you must raise
max_iteryourself and refit. - Overwriting a fitted attribute by hand. Assigning to
coef_bypasses learning and makes results hard to trace. Refit instead. - Reusing a fitted estimator across datasets. Calling
fitagain discards the earlier learned values and replaces them, so the old fit is lost. Use a fresh copy when you need both.
Exercise
You create m = Ridge(alpha=1.0) and call m.fit(X_train, y_train). Which of alpha, coef_, and intercept_ exist before the call to fit, and which one is a hyperparameter?
Show answer
Only alpha exists before fit, and it is the hyperparameter. coef_ and intercept_ end in an underscore, so they are fitted attributes created by fit.
Exercise
A colleague reads scaler.mean_ and gets an AttributeError. What is the most likely cause, and what is the fix?
Show answer
The scaler has not been fitted. Call scaler.fit(X_train) (or fit_transform) first, and mean_ will then exist.