Sub topic 12
Checking conformance with check_estimator
This chapter assumes you can write a class with BaseEstimator and a mixin, and that you know the constructor rule (store arguments unchanged) and the trailing-underscore rule (learned attributes end in _). It also assumes you have run Pipeline and GridSearchCV before. Here you will learn to run scikit-learn's own conformance checks against your estimator, read their failures, and put them in a test suite.
Why a conformance checker exists
Cloning, grid search, pipelines and pickling all rely on conventions that Python does not enforce. If you set an extra attribute in __init__, the estimator still runs on its own. It then fails later inside clone, GridSearchCV or cross_val_score, often with an error that points somewhere else.
check_estimator runs a large collection of small tests, called checks, against an instance of your estimator. Each check is a function that exercises one convention. The first violation raises an error whose message names the check and the problem. This moves a vague late failure to a precise early one.
Running check_estimator
Pass an instance, not a class. The function lives in sklearn.utils.estimator_checks.
from sklearn.utils.estimator_checks import check_estimator
check_estimator(QuantileClipper())If every check passes, the call returns without output. If one fails, it raises an exception, usually AssertionError or ValueError. The exact set of checks depends on your scikit-learn version and on what kind of estimator you pass.
The checks are chosen from the base classes you inherited and from the estimator's tags. A transformer gets transformer checks. A classifier gets checks on classes_, label handling and predict. This is why inheriting from the correct mixin matters: it decides which tests run.
Reading a failure
The example below defines an estimator that breaks the constructor rule on purpose. It catches the exception and prints it, so you can see what a failure looks like.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.estimator_checks import check_estimator
from sklearn.utils.validation import check_array, check_is_fitted
class BadClipper(TransformerMixin, BaseEstimator):
def __init__(self, lower=0.01):
self.lower = lower
self.lower_ = None # learned attribute created in __init__: not allowed
def fit(self, X, y=None):
X = check_array(X)
self.lower_ = np.quantile(X, self.lower, axis=0)
self.n_features_in_ = X.shape[1]
return self
def transform(self, X):
check_is_fitted(self)
X = check_array(X)
return np.maximum(X, self.lower_)
try:
check_estimator(BadClipper())
except Exception as exc:
print(type(exc).__name__)
print(exc)The printed message names the offending attribute. A failure message usually contains three useful pieces:
- The name of the check, such as
check_no_attributes_set_in_init. Search for this name in the scikit-learn source to see exactly what it does. - The estimator class name.
- A short description of what was found, for example the list of unexpected attributes.
When a message is unclear, open the check function itself. Checks are short, readable Python, and they show the input data they use.
What the checks cover
You do not need to memorize the list. The table groups the main areas and ties each one to a convention you have already learned.
| Area | What a check verifies | Typical cause of failure |
|---|---|---|
| Constructor | Parameters are stored unchanged, defaults are simple, no other attributes are set | Validation or computation in `__init__` |
| Cloning | `clone` produces an equal, unfitted copy; `get_params` and `set_params` round-trip | A parameter not stored under its own name |
| Input validation | NaN, infinity, empty data, 1D input and wrong dtypes give clear errors | Missing `check_array` or `check_X_y` |
| Fitted state | `predict` or `transform` before `fit` raises `NotFittedError` | Missing `check_is_fitted` |
| Feature count | A different number of columns at predict time raises `ValueError` | `n_features_in_` not set or not compared |
| Immutability | `fit`, `transform` and `predict` do not modify their inputs | In-place operations on `X` or `y` |
| Determinism | The same `random_state` gives the same result | Using global random state instead of the parameter |
| Pickling | A fitted estimator survives `pickle` and gives the same output | Lambdas or open handles stored as attributes |
| Subset invariance | Predicting on one row gives the same answer as on the full batch | Batch-dependent statistics in `predict` |
Some checks are skipped for estimators that cannot satisfy them. Tags tell scikit-learn which ones to skip. The final section of this tutorial covers tags.
Using the checks in a test suite
Running check_estimator once in a notebook is useful. Running it in continuous integration is better, because it catches regressions when you edit the class. The pytest helper parametrize_with_checks turns each check into its own test case. A failure then shows exactly which check broke, and the other checks still run.
from sklearn.utils.estimator_checks import parametrize_with_checks
from myproject.estimators import MeanCentroidClassifier, QuantileClipper
@parametrize_with_checks([QuantileClipper(), MeanCentroidClassifier()])
def test_sklearn_compatible_estimator(estimator, check):
check(estimator)Replace myproject.estimators with the module that holds your classes. Run it with pytest. Compared with a bare check_estimator call, this form has two advantages:
- Each check appears as a separate test ID, so the report lists every failure instead of stopping at the first.
- You can pass several estimators, including the same class with different parameters, to test non-default settings.
Known failures
Sometimes a check does not apply to your design. For example, your estimator may legitimately accept NaN values. Recent scikit-learn releases (1.6 and later) let you list such checks in an expected_failed_checks argument, which is a dictionary mapping check names to a reason string. Both check_estimator and parametrize_with_checks accept it. The reason string documents the decision for the next reader. In older versions the usual route is to set the matching tag instead.
Fixing the usual failures
Most failures come from a small set of causes. This list pairs common messages with their fixes.
- Attributes set in
__init__. Move everything except plainself.param = paramassignments intofit. Names ending in_belong infitonly. - Parameters changed in
__init__. Writingself.lower = float(lower)orself.items = list(items)breaks the clone check, because the stored value no longer equals the value passed in. Convert insidefitand keep the original unchanged. - Unclear or wrong error on bad input. Call
check_array(X)infitandtransform, orcheck_X_y(X, y)in a supervisedfit. These functions produce the messages the checks expect. - No
NotFittedError. Callcheck_is_fitted(self)first intransformandpredict. It looks for attributes that end in an underscore. - Wrong feature count not detected. Set
self.n_features_in_ = X.shape[1]infitand compare it intransform, as theQuantileClipperfrom earlier chapters does. The error message must read like the built-in one:X has 2 features, but QuantileClipper is expecting 3 features as input. - Input modified in place. Operations such as
X -= meanchange the caller's array. Make a copy or use an expression that returns a new array.np.clip(X, lo, hi)returns a new array, so it is safe. - Random behavior not repeatable. Accept
random_stateas a parameter and build a generator withsklearn.utils.check_random_state(self.random_state)insidefit.
What a passing result does not prove
check_estimator tests the interface, not the quality of your model or the correctness of your math. A transformer that clips every value to zero can pass every check. You still need ordinary unit tests for the behavior you care about, such as these:
- Fit on a small array and compare the learned
lower_andupper_to values you computed by hand. - Confirm that
transformleaves values inside the bounds unchanged. - Check that the training statistics, not the test statistics, are used when you transform new data. This protects against data leakage, which a later chapter covers.
Treat the two kinds of tests as complementary. The conformance checks protect the contract with scikit-learn. Your own tests protect the meaning of the estimator.
Exercise
Your custom transformer stores self.columns = list(columns) in __init__ and check_estimator fails. Why does it fail, and how do you fix it?
Show answer
The constructor must store each argument exactly as it was passed. list(columns) creates a new object, so get_params() no longer returns the value given to __init__, and clone and the parameter round-trip checks fail. Store self.columns = columns in __init__ and do the list(...) conversion inside fit, keeping the result in a trailing-underscore attribute such as self.columns_.
Exercise
Why is parametrize_with_checks usually preferred over a single check_estimator call in a project's test suite?
Show answer
It makes each check a separate pytest test. A report then lists every failing check at once instead of stopping at the first failure, and each failure has its own test ID. It also lets you pass several estimator instances, for example the same class with different parameters, and run all checks on each.
Exercise
Your estimator passes every check from check_estimator. Does that mean it computes the right result? Give one test you would still write.
Show answer
No. The checks verify the interface conventions only, such as cloning, input validation and fitted-state errors. They say nothing about whether the learned values are correct. For QuantileClipper, fit on a small array with known quantiles and assert that lower_ and upper_ equal the hand-computed values, then assert that transform clips values outside those bounds.