Sub topic 14
Common mistakes and how to avoid them
This chapter assumes you have read the earlier chapters on BaseEstimator, the constructor rules, learned attributes with a trailing underscore, Pipeline, and GridSearchCV. It collects the errors that most often break a custom estimator, shows why each one fails inside scikit-learn's machinery, and gives the fix.
Where mistakes happen
Most errors come from putting the right code in the wrong method. Each method has one job, and the rest of scikit-learn relies on that.
Doing work in `__init__`
clone builds a new object from get_params() and then checks that each parameter on the new object is the same object it passed in. GridSearchCV uses set_params, which assigns attributes and never calls __init__ again. Both break if the constructor converts, validates, or derives anything.
The following transformer converts its parameter with list(...). clone fails because the constructor returns a different list than the one it received.
from sklearn.base import BaseEstimator, TransformerMixin, clone
class BadColumnPicker(TransformerMixin, BaseEstimator):
def __init__(self, columns=()):
self.columns = list(columns) # wrong: changes the parameter
def fit(self, X, y=None):
return self
def transform(self, X):
return X[:, self.columns]
try:
clone(BadColumnPicker(columns=[0, 2]))
except RuntimeError as exc:
print("clone failed:", type(exc).__name__)The fix is to store the argument as given and do the conversion and validation in fit. Put derived values in an attribute with a trailing underscore.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin, clone
from sklearn.utils.validation import check_array, check_is_fitted
class ColumnPicker(TransformerMixin, BaseEstimator):
def __init__(self, columns=None):
self.columns = columns
def fit(self, X, y=None):
X = check_array(X)
n = X.shape[1]
cols = list(range(n)) if self.columns is None else list(self.columns)
if any(c < 0 or c >= n for c in cols):
raise ValueError(f"columns must be between 0 and {n - 1}, got {cols}")
self.columns_ = cols
self.n_features_in_ = n
return self
def transform(self, X):
check_is_fitted(self)
X = check_array(X)
return X[:, self.columns_]
picker = clone(ColumnPicker(columns=[0, 2]))
print(picker.fit(np.arange(12.0).reshape(3, 4)).transform(np.ones((1, 4))))Other constructor mistakes follow the same logic:
- Mutable defaults.
columns=[]is shared by every instance. UseNoneor a tuple. *argsin the signature.get_paramsraises aRuntimeError. Every parameter must be a named keyword.- `kwargs
.**get_paramssilently ignores them, soclone` drops them. Name each parameter. - Underscore attributes in
__init__.check_is_fittedtreats any attribute ending in_as evidence of fitting. Settingself.cache_ = Nonein the constructor makes an unfitted estimator look fitted.
Changing the caller's data
check_array returns the same array when the dtype is already acceptable. It does not copy. Writing into that array changes the data the caller passed in, which is a hard bug to find when a later pipeline step or cross-validation fold sees altered values.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_array, check_is_fitted
class ZeroNegatives(TransformerMixin, BaseEstimator):
def fit(self, X, y=None):
X = check_array(X)
self.n_features_in_ = X.shape[1]
return self
def transform(self, X):
check_is_fitted(self)
X = check_array(X)
X[X < 0] = 0 # wrong: writes into the caller's array
return X
data = np.array([[1.0, -2.0], [-3.0, 4.0]])
ZeroNegatives().fit(data).transform(data)
print(data) # the original array has changedThere are two safe options. Use an operation that returns a new array, such as np.where(X < 0, 0, X) or np.clip. Or ask for a copy with check_array(X, copy=True) before you modify anything. The same rule applies to the parameters you stored in __init__. Never modify self.columns or any other constructor argument in place.
Learning in the wrong place
Anything that depends on the data belongs in fit, and transform should only read what fit stored. If transform recomputes a statistic from its own input, its output depends on whatever batch it receives. A single row at prediction time is centered to zero, and test rows influence their own transformation.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_array, check_is_fitted
class Center(TransformerMixin, BaseEstimator):
def fit(self, X, y=None):
X = check_array(X)
self.mean_ = X.mean(axis=0)
self.n_features_in_ = X.shape[1]
return self
def transform(self, X):
check_is_fitted(self)
X = check_array(X)
return X - self.mean_
X_train = np.array([[1.0], [3.0]])
X_new = np.array([[10.0]])
print(Center().fit(X_train).transform(X_new)) # [[8.]]A version that computed X.mean(axis=0) inside transform would return [[0.]] for the same input.
The second form of this mistake is calling fit or fit_transform on test data, or on the full dataset before splitting. Cross-validation then evaluates on rows whose statistics, or target values, helped build the transformer. The fix is to put the transformer in a Pipeline so each fold fits it on that fold's training rows only.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
X, y = load_iris(return_X_y=True)
# Leaks: Center sees every row, including each fold's validation rows.
leaky = cross_val_score(
LogisticRegression(max_iter=1000), Center().fit_transform(X), y, cv=5
)
# Safe: Center is refit on the training rows of every fold.
safe = cross_val_score(
make_pipeline(Center(), LogisticRegression(max_iter=1000)), X, y, cv=5
)
print(leaky.mean(), safe.mean())Centering leaks very little. A transformer that uses y, such as target encoding or supervised feature selection, can inflate scores badly when fitted outside the pipeline.
Method signature and return value mistakes
These errors usually show up only when the estimator is placed in a pipeline.
fitdoes not returnself.TransformerMixin.fit_transformrunsself.fit(X, y).transform(X). IffitreturnsNone, you get anAttributeErroraboutNoneType.fit(self, X)withouty.Pipelinealways passesy. Transformers must acceptfit(self, X, y=None).- Missing
n_features_in_or the width check. Without them, a wrong-width input fails deep inside NumPy with an unclear message instead of a clearValueError. - Unseeded randomness. If an estimator draws random numbers, accept a
random_stateparameter and convert it withcheck_random_stateinfit. Otherwise results change between runs and cross-validation is not reproducible.
Symptom guide
| Symptom | Likely cause | Fix |
|---|---|---|
| `RuntimeError` from `clone` | `__init__` modifies or does not store a parameter | Assign `self.param = param` and nothing else |
| `Invalid parameter` in `GridSearchCV` | Name is not in the `__init__` signature, or the step prefix is wrong | Use `stepname__param` and match the constructor |
| Grid search changes a parameter but results do not change | A value was derived from the parameter in `__init__` | Derive it in `fit` |
| `'NoneType' object has no attribute 'transform'` | `fit` returns `None` | End `fit` with `return self` |
| `TypeError` about `y` | `fit` has no `y=None` argument | Use `fit(self, X, y=None)` |
| Input array changed after a call | In-place write in `transform` | Return a new array or use `copy=True` |
| Unfitted object passes `check_is_fitted` | A trailing-underscore attribute set in `__init__` | Create learned attributes only in `fit` |
| Scores drop sharply on truly new data | Fitting happened outside the pipeline or on test rows | Fit inside `Pipeline` and cross-validation |
Catching mistakes automatically
Run check_estimator on every custom class. It detects most of the problems above, including parameter modification, missing return self, input mutation, and inconsistent results between calls. It raises on the first violation and names the convention.
from sklearn.utils.estimator_checks import check_estimator
check_estimator(ColumnPicker())Add this call to your test suite. A custom estimator that passes it will work in clone, Pipeline, ColumnTransformer, and GridSearchCV.
Exercise
A teammate's transformer has def __init__(self, scale=1.0): self.scale = scale; self.inv_scale_ = 1.0 / scale. GridSearchCV tries scale values of 1.0 and 2.0 through set_params, but the output is the same each time. Why, and how do you fix it?
Show answer
set_params only assigns the scale attribute and never calls __init__, so inv_scale_ keeps the value computed at construction. The attribute also ends in an underscore, so the object looks fitted before fit runs. Remove inv_scale_ from __init__, compute self.inv_scale_ = 1.0 / self.scale in fit (after checking that scale is not zero), and use it in transform.
Exercise
A transformer's transform does X = check_array(X); X -= X.mean(axis=0); return X. Name the two separate mistakes and the correct version.
Show answer
It changes the caller's array in place, because check_array does not copy and -= writes into it. It also recomputes the mean from the data passed to transform instead of using a value learned in fit. Learn self.mean_ in fit, then in transform return check_array(X) - self.mean_, which creates a new array.