Sub topic 1
What scikit-learn expects from an estimator
Scikit-learn does not define its estimators through a base class with abstract methods. It defines them through conventions: which methods exist, what they return, how constructor arguments are stored, and where learned values live. Pipelines, GridSearchCV, cross_val_score and clone all depend on these conventions. If your own class follows them, it works with all of these tools. If it breaks one, you usually get a confusing error far from the cause.
This chapter sets out the contract. Later chapters build transformers and predictors on top of it.
Prerequisites
This chapter assumes you can:
- Write a Python class with
__init__, methods and inheritance. - Use NumPy arrays: shapes, slicing and
axisarguments. - Call
fit,predictandtransformon built-in scikit-learn objects. - Explain why you split data into train and test sets, and what cross-validation does.
What an estimator is
In scikit-learn, an estimator is any object that learns something from data through a fit method. Three kinds appear most often:
- A transformer learns from data and then changes data (
StandardScaler,PCA). - A predictor learns a mapping from features to targets (
LogisticRegression,RandomForestRegressor). Classifiers and regressors are both predictors. - A meta-estimator wraps other estimators (
Pipeline,GridSearchCV).
All three share one lifecycle: you construct the object with settings, you call fit on training data, and then you call transform or predict on any data.
The core methods
The table lists the methods scikit-learn relies on and what each must do.
| Method | Applies to | Signature | Returns |
|---|---|---|---|
| `fit` | All estimators | `fit(X, y=None)` | `self` |
| `transform` | Transformers | `transform(X)` | Array of transformed data |
| `fit_transform` | Transformers | `fit_transform(X, y=None)` | Array of transformed data |
| `predict` | Predictors | `predict(X)` | Array of labels or values, one per row |
| `score` | Predictors | `score(X, y)` | A float, where higher is better |
| `get_params` | All estimators | `get_params(deep=True)` | Dict of constructor parameters |
| `set_params` | All estimators | `set_params(**params)` | `self` |
Some details matter more than they look.
fitreturnsself. Pipelines and users chain calls such asest.fit(X).transform(X). ReturningNonebreaks this.yis accepted even when unused. Unsupervised transformers declarefit(self, X, y=None). APipelinepassesyto every step, so a step that omits the argument raises aTypeError.transformdoes not learn. It uses only whatfitstored. Iftransformrecomputes statistics from its input, test data would leak into the result and the output for a row would depend on the other rows in the batch.predictandtransformreturn one row per input row for the standard cases. Row order must match the input.- Calling
fitagain replaces the earlier result. Fitting twice on different data must give the same state as a fresh object fitted on the second data.
fit_transform has a default implementation in TransformerMixin that calls fit(X, y).transform(X). score comes from ClassifierMixin (accuracy) and RegressorMixin (R²). The next chapter covers these mixins.
Parameters and learned state are kept apart
The most important convention separates two kinds of attributes.
| Kind | Set in | Name | Example |
|---|---|---|---|
| Hyperparameter | `__init__` | Same as the argument | `self.with_mean` |
| Learned attribute | `fit` | Ends with `_` | `self.mean_` |
Scikit-learn uses this split for three jobs:
- Inspection.
get_paramsreads the hyperparameters. It finds them by inspecting the signature of__init__and callinggetattrfor each argument name. - Copying.
clone(est)builds a new, unfitted object fromest.get_params(). Learned attributes are not copied, because they are not constructor arguments. - Fitted checks.
check_is_fittedlooks for attributes that end with an underscore. If none exist, it raisesNotFittedError.
A short example shows all three.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin, clone
class MeanCenterer(TransformerMixin, BaseEstimator):
def __init__(self, with_mean=True):
self.with_mean = with_mean
def fit(self, X, y=None):
X = np.asarray(X, dtype=float)
if self.with_mean:
self.mean_ = X.mean(axis=0)
else:
self.mean_ = np.zeros(X.shape[1])
return self
def transform(self, X):
return np.asarray(X, dtype=float) - self.mean_
X = np.array([[1, 2], [3, 4], [5, 6]])
est = MeanCenterer()
print(est.get_params()) # {'with_mean': True}
print(hasattr(est, "mean_")) # False: not fitted yet
print(est.fit(X) is est) # True: fit returns self
print(est.mean_) # [3. 4.]
print(est.transform(X)) # [[-2. -2.] [ 0. 0.] [ 2. 2.]]
copy = clone(est)
print(copy.get_params()) # {'with_mean': True}
print(hasattr(copy, "mean_")) # False: the clone is unfitted
est.set_params(with_mean=False)
print(est.fit(X).mean_) # [0. 0.]This class skips input validation so the contract stays visible. A later chapter adds check_array and check_is_fitted. Because it does not validate, calling transform before fit raises a plain AttributeError here, not the NotFittedError that built-in estimators raise.
Why cloning drives the rules
Many scikit-learn tools never use the object you give them. They clone it first. cross_val_score clones the estimator once per fold, so each fold starts from an unfitted copy. GridSearchCV clones it for every parameter combination and fold. clone has a strict check: after building the new object, it confirms that each constructor argument was stored unchanged, using an identity test (is).
The following class looks harmless but fails that check.
from sklearn.base import BaseEstimator, clone
class Bad(BaseEstimator):
def __init__(self, n=None):
self.n = 5 if n is None else n # modifies the argument
try:
clone(Bad())
except RuntimeError as err:
print("clone failed:", type(err).__name__)Bad() stores 5 in self.n, so get_params() reports n=5. The clone is built with n=5. That works, but the check compares the value passed to the constructor (None is what the first object received, and the clone sees 5) with the value stored, and the two differ. The fix is to store self.n = n and resolve the default inside fit, saving the result as self.n_ if you need it later.
Fitted state and repeated calls
A learned attribute describes only the most recent call to fit. Two consequences follow.
- Reset, don't accumulate. If
fitappends to a list that__init__created, a secondfitmixes old and new data. Build learned attributes fresh insidefit. - Do not change hyperparameters in
fit. Writingself.lower = ...infitchanges whatget_paramsreports and whatclonecopies. Put computed values in attributes that end with_.
The convention also covers shapes of learned state. Scikit-learn records n_features_in_ after fitting so later calls can reject input with a different number of columns. Predictors that know their label set store classes_. Both follow the same trailing-underscore rule.
How meta-estimators use the contract
A Pipeline shows how the pieces fit together. When you call pipe.fit(X, y), it calls fit_transform(X, y) on each intermediate step and passes the output to the next step. It calls fit(X, y) on the final step. When you call pipe.predict(X), it calls only transform on the intermediate steps, then predict on the last.
This means an intermediate step must be a transformer: it needs fit and transform. The final step may be any estimator. If your class lacks transform, the pipeline rejects it at construction time with a TypeError.
Nested parameter names rely on get_params(deep=True). A pipeline step named clip with a parameter lower is addressed as clip__lower. This works for your class without extra code, as long as __init__ follows the parameter rule.
Common errors at this stage
| Symptom | Likely cause |
|---|---|
| `AttributeError: 'X' object has no attribute 'a'` from `get_params` or `repr` | `__init__` takes an argument `a` but never stores it as `self.a` |
| `RuntimeError` from `clone` | `__init__` modifies, validates or copies an argument before storing it |
| `NotFittedError` after calling `fit` | `fit` stores nothing ending in `_`, or `check_is_fitted` finds only private attributes |
| `AttributeError: 'NoneType' object has no attribute 'transform'` | `fit` returns `None` instead of `self` and the result is chained |
| `TypeError: fit() takes 2 positional arguments but 3 were given` | `fit(self, X)` has no `y=None` and sits inside a `Pipeline` |
| Scores differ between a fresh object and a refitted one | `fit` keeps state from an earlier call |
What comes next
The following chapters apply this contract. You will meet BaseEstimator and the mixins, the constructor rules in detail, input validation, and then a full transformer and classifier. The contract above is the checklist that check_estimator runs against your classes.
Exercise
A class Scaler has __init__(self, factor=1.0) that sets self.factor = float(factor), and fit(self, X, y=None) that computes self.scale = X.std(axis=0) and returns self. List every convention this class breaks or puts at risk, and give the fix for each.
Show answer
First, float(factor) modifies the argument. With factor=2 (an int), the stored value is a different object, so clone raises RuntimeError. Store self.factor = factor and convert in fit if needed. Second, the learned value self.scale has no trailing underscore. check_is_fitted can't detect it, and it looks like a hyperparameter. Rename it self.scale_. The fit signature and return self are correct.
Exercise
A pipeline Pipeline([("a", MyStep()), ("clf", LogisticRegression())]) fails at fit with TypeError: fit() takes 2 positional arguments but 3 were given. What is wrong with MyStep, and what is the minimal change?
Show answer
MyStep.fit is declared as fit(self, X). The pipeline calls fit(X, y) (through fit_transform) on every intermediate step. Change the signature to fit(self, X, y=None).
Exercise
You call est = MeanCenterer().fit(X_train) and then est.transform(X_test). Why is it important that transform uses mean_ and does not compute the mean of X_test?
Show answer
The learned mean_ comes from training data only. Computing the mean of X_test inside transform would use test information, which leaks it into the result, and the output for one row would depend on the other rows in the batch. Using the stored mean_ makes each row's output depend only on that row and the training data.