Sub topic 14
Common Mistakes and How to Avoid Them
This chapter assumes you have written a custom transformer with BaseEstimator and TransformerMixin. It also assumes you know how Pipeline and GridSearchCV clone and fit estimators. Most bugs in custom estimators come from breaking a convention that those tools rely on. The errors often appear far from the cause.
Doing work in `__init__`
clone, get_params and GridSearchCV all assume the constructor only stores its arguments, under the same names. Validating, converting, or renaming a value breaks that assumption.
from sklearn.base import BaseEstimator, TransformerMixin, clone
class BadScaler(TransformerMixin, BaseEstimator):
def __init__(self, factor=1.0):
if factor <= 0:
raise ValueError("factor must be positive")
self.scale = float(factor) # renamed and converted
def fit(self, X, y=None):
return self
def transform(self, X):
return X * self.scale
class GoodScaler(TransformerMixin, BaseEstimator):
def __init__(self, factor=1.0):
self.factor = factor
def fit(self, X, y=None):
if self.factor <= 0:
raise ValueError("factor must be positive")
return self
def transform(self, X):
return X * self.factor
print(clone(GoodScaler(2.0)).factor) # 2.0
# clone(BadScaler(2.0)) fails: get_params looks for an attribute named "factor"Move validation into fit. Search sets parameters after construction with set_params, so a check in __init__ would never see the new values.
Also avoid mutable defaults such as columns=[]. Use None or a tuple, and leave the value untouched.
Mutating the input
check_array often returns the caller's own array without copying it. An in-place operation then changes the user's data.
import numpy as np
X = np.array([[1.0, 2.0], [3.0, 4.0]])
def bad_transform(X):
X -= X.mean(axis=0) # modifies the caller's array
return X
def good_transform(X):
return X - X.mean(axis=0) # creates a new array
good_transform(X)
print(X) # unchangedFitting on the wrong data
Calling fit or fit_transform on the full dataset before splitting leaks test information into training. Learned values such as the clipping bounds in QuantileClipper then come partly from the validation rows.
flowchart TD
A[Full dataset] --> B[Fit transformer on all rows]
B --> C[Split into folds]
C --> D[Scores look better than reality]Put the transformer inside a Pipeline instead. Cross-validation then refits it on each training fold only.
Inside your own transform, never call fit and never recompute statistics from the incoming X. Use only the attributes learned in fit.
Other frequent errors
| Mistake | Symptom | Fix |
|---|---|---|
| Learned attribute lacks a trailing underscore | `check_is_fitted` passes before `fit`, or never passes | Name it `lower_`, not `lower` |
| `fit` does not return `self` | `AttributeError: 'NoneType'` when chaining | End `fit` with `return self` |
| Skipping `check_array` | Lists or DataFrames fail in odd places | Validate in `fit` and `transform` |
| No feature count check in `transform` | Silent wrong output on mismatched columns | Compare with `n_features_in_` |
| Overwriting a constructor parameter in `fit` | Second `fit` call behaves differently | Write results to new `name_` attributes |
| Random behavior without `random_state` | Results differ between runs | Accept `random_state` and store it |
A checklist before you ship
__init__only doesself.param = param, one line per parameter.fitvalidates, learnsname_attributes, setsn_features_in_, and returnsself.transformandpredictcallcheck_is_fitted, thencheck_array, and never modifyX.- The estimator sits inside a
Pipelinefor any cross-validation. check_estimator(MyEstimator())passes.
Run check_estimator early. Its error messages name the convention you broke, which is usually faster than debugging a failed grid search.
Exercise
A colleague's transformer stores self.cols = list(columns) in __init__. Grid search over columns raises an error after set_params. What two problems does this have, and how do you fix them?
Show answer
The attribute name cols differs from the parameter name columns, so get_params cannot find it. The list(...) conversion also changes the stored value during construction. Store self.columns = columns unchanged, and convert to a list inside fit into a new attribute such as columns_.