Sub topic 12
Checking conformance with check_estimator
This chapter assumes you can write a custom transformer with BaseEstimator and TransformerMixin. It also assumes you know the constructor rule (store arguments unchanged) and the trailing-underscore rule for learned attributes. Here you will test those conventions automatically instead of by eye.
What check_estimator does
check_estimator is a function in sklearn.utils.estimator_checks. It takes an estimator instance and runs scikit-learn's own conformance checks against it. Examples include:
- calling
fittwice gives the same result fitdoes not change the constructor parameters- the estimator can be cloned
- bad input such as NaN or the wrong number of features raises a clear error
n_features_in_is set afterfit
If every check passes, the call returns quietly. If one fails, it raises an error whose message names the check that failed.
from sklearn.utils.estimator_checks import check_estimator
check_estimator(QuantileClipper())This runs against the QuantileClipper from the earlier chapter. Passing means the class follows the conventions that clone, GridSearchCV and Pipeline depend on.
Running it under pytest
For a project with a test suite, parametrize_with_checks turns each check into its own pytest case. A failure then shows exactly which check broke, and the other checks still run.
from sklearn.utils.estimator_checks import parametrize_with_checks
@parametrize_with_checks([QuantileClipper(), MeanCentroidClassifier()])
def test_sklearn_compatible(estimator, check):
check(estimator)Put this in a test file next to the class definitions. Both classes need to be importable there.
Reading a failure
Failures usually point back to a convention you already know. This table lists common causes and fixes.
| Symptom | Likely cause | Fix |
|---|---|---|
| Error about parameters changing after `fit` | `fit` assigns to a constructor argument | Write learned values to `name_` attributes only |
| Error about a constructor argument | `__init__` validates, copies or renames it | Store the argument unchanged under the same name |
| Estimator accepts bad input silently | No `check_array` or `check_X_y` call | Validate at the start of `fit` and `transform` |
| Error about an unfitted estimator | `transform` or `predict` skips `check_is_fitted` | Call `check_is_fitted(self)` first |
| Wrong feature count not rejected | `n_features_in_` is not set or compared | Set it in `fit` and compare it in `transform` |
Fix one failure, run again, and repeat. Checks run in sequence, so later problems stay hidden until earlier ones are resolved.
Expected failures
Sometimes a check does not apply to your estimator. For example, an estimator may deliberately accept NaN. In scikit-learn 1.6 and later, check_estimator accepts expected_failed_checks, a dictionary that maps a check name to a reason. Those checks are then skipped and the reason is recorded. Use it sparingly. Each entry should explain a deliberate design choice, not hide a bug.
The same release also added on_fail. If you pass on_fail=None, the function returns a list of results instead of raising on the first failure. This is useful for seeing every problem at once.
results = check_estimator(QuantileClipper(), on_fail=None)
failed = [r for r in results if r["status"] == "failed"]
print(len(failed), "checks failed")Older versions do not have this argument and raise on the first failure. Check your installed version if the call raises a TypeError.
Summary of the workflow
- Write the estimator following the constructor, validation and trailing-underscore rules.
- Run
check_estimatoron a default instance. - Fix the first named failure and rerun.
- Move the check into a pytest test with
parametrize_with_checks. - Add your own tests for the estimator's real behavior.
Exercise
You run check_estimator on your transformer and it fails with a message saying a constructor parameter was changed during fit. Where should you look in your code, and what is the usual fix?
Show answer
Look in fit for a line that assigns to a constructor argument, such as self.lower = ... . Fit should leave constructor arguments untouched. Store learned values in new attributes that end with an underscore, such as self.lower_.