Sub topic 1
What scikit-learn expects from an estimator
Every scikit-learn component follows a small set of conventions. Pipelines, cross-validation and grid search rely on them. If your own class follows them, it works with all of these tools. If it breaks them, failures often appear only later, inside a search or a pipeline.
Prerequisites
This chapter assumes you know:
- Python classes and inheritance.
- NumPy arrays and basic indexing.
- How to use scikit-learn estimators with
fit,predictandtransform. - The idea of train/test splits and cross-validation.
The three roles
An estimator is any object that learns something from data through a fit method. Scikit-learn uses the word for all of these:
| Role | Required methods | Typical use |
|---|---|---|
| Transformer | `fit`, `transform` | Scaling, encoding, feature creation |
| Predictor | `fit`, `predict` | Classifiers and regressors |
| Both | `fit`, `transform`, `predict` | Rare. Most objects pick one role. |
Calling fit(X, y) learns from data and returns self. Returning self lets you chain calls, such as est.fit(X).transform(X). Calling transform(X) or predict(X) uses what was learned and does not change the estimator.
Two kinds of state
The contract separates an estimator's state into two groups.
- Parameters are the settings you pass to
__init__, such aswith_mean=True. They are available before fitting and are not changed byfit. - Learned attributes are results computed by
fit. Their names end with an underscore, such asmean_orclasses_. They do not exist untilfithas run.
The trailing underscore is how scikit-learn, and you, can tell the two groups apart. The check below shows both.
import numpy as np
from sklearn.preprocessing import StandardScaler
X = np.array([[1.0, 10.0], [2.0, 20.0], [3.0, 30.0]])
scaler = StandardScaler()
print(scaler.get_params()) # parameters exist before fitting
print(hasattr(scaler, "mean_")) # False: nothing learned yet
scaler.fit(X)
print(scaler.mean_) # [ 2. 20.]
print(scaler.transform(X))Running this prints the parameter dictionary, then False, then [ 2. 20.], then the scaled array.
What the tools rely on
Other scikit-learn tools depend on this split in specific ways.
- Cloning.
clone(est)builds a fresh, unfitted copy by reading the parameters withget_paramsand passing them to the constructor. Learned attributes are not copied. Cross-validation clones the estimator for every fold, so each fold starts clean. - Tuning.
GridSearchCVchanges parameters withset_params. This only works if the parameters are stored under the same names as the constructor arguments. - Pipelines. A
Pipelinecallsfitandtransformon each step in order. It expectsfitto returnselfandtransformto return an array with one row per input row. - Scoring. Predictors expose
score(X, y). Classifiers report accuracy and regressors report R².
You can see cloning drop learned state:
from sklearn.base import clone
fresh = clone(scaler)
print(hasattr(fresh, "mean_")) # False
print(fresh.get_params() == scaler.get_params()) # TrueRules in short
The later chapters cover each rule in detail. For now, keep these in mind:
__init__only stores its arguments, under the same names, without changing them.fitlearns attributes ending in_and returnsself.transformandpredictdo not modify the estimator or the input array.- Methods that need a fitted estimator should fail with a clear error if
fitwas never called.
Exercise
You call clone(est) on a fitted estimator with n_neighbors=3. What does the copy keep, and what does it lose?
Show answer
The copy keeps the constructor parameters, so n_neighbors is still 3. It loses all learned attributes, the ones ending in an underscore, so it must be fitted again before it can predict.