Sub topic 5
Validating input and checking that the estimator is fitted
This chapter assumes you can write a Python class, index NumPy arrays, and use fit, transform and predict on built-in scikit-learn estimators. It also assumes you have seen the earlier chapters' rules: constructors only store parameters, and learned attributes end with an underscore. Here you add the two guards every custom estimator needs. One guard checks the data going in. The other checks that fit has run before transform or predict is used.
Why validation belongs in your estimator
Your estimator will receive whatever the caller passes. That can be a list of lists, a pandas DataFrame, a 1-D array, an array with NaN, a sparse matrix, or an array with the wrong number of columns. If you do nothing, NumPy may fail deep inside your code with an unrelated message, or it may silently return a wrong answer. Both are worse than a clear error at the entry point.
Built-in estimators follow a pattern that you should copy:
fitconverts and checksX(andy), then records what it saw, such as the number of features.transformandpredictfirst confirm thatfitran, then convert and checkX, then compare it with whatfitsaw.
check_array: converting and checking X
check_array lives in sklearn.utils.validation. It takes anything array-like and returns a NumPy array that meets a set of requirements, or raises an error that says which requirement failed.
With default arguments it does the following:
- Converts lists, tuples and DataFrames to a NumPy array.
- Requires 2-D input and raises
ValueErrorfor a 1-D array. - Requires numeric data and raises
ValueErrorif it cannot convert (for example, strings that are not numbers). - Rejects
NaNand infinity withValueError. - Rejects sparse matrices with
TypeError. - Requires at least one sample and one feature.
The arguments you will change most often are in this table.
| Argument | Default | Use it to |
|---|---|---|
| `accept_sparse` | `False` | Allow sparse input, for example `"csr"` or `["csr", "csc"]`. Only do this if your code handles sparse arrays. |
| `dtype` | `"numeric"` | Force a type, for example `np.float64`, or give a list such as `[np.float64, np.float32]` to keep floats as they are. |
| `ensure_all_finite` | `True` | Allow `NaN` with `"allow-nan"`. In versions before 1.6 this argument is named `force_all_finite`. |
| `ensure_2d` | `True` | Accept 1-D input (rarely wanted). |
| `ensure_min_samples` | `1` | Demand more rows, for example `2` for a standard deviation. |
| `copy` | `False` | Guarantee that the returned array is not the caller's array. |
Run this to see the common failures:
import numpy as np
from sklearn.utils.validation import check_array
print(check_array([[1, 2], [3, 4]])) # list of lists becomes an ndarray
bad_inputs = {
"1-D": [1, 2, 3],
"NaN": [[1.0, np.nan], [3.0, 4.0]],
"empty": np.empty((0, 2)),
"text": [["a", "b"], ["c", "d"]],
}
for name, data in bad_inputs.items():
try:
check_array(data)
except ValueError as exc:
print(f"{name}: {str(exc).splitlines()[0]}")Each bad input raises ValueError with a message that names the problem.
check_X_y: validating features and target together
During fit for a supervised estimator, validate X and y in one call:
import numpy as np
from sklearn.utils.validation import check_X_y
X, y = check_X_y([[1.0, 2.0], [3.0, 4.0]], [0, 1])
print(X.shape, y.shape)
try:
check_X_y([[1.0, 2.0], [3.0, 4.0]], [0, 1, 1])
except ValueError as exc:
print(exc)check_X_y runs check_array on X, makes sure y is a 1-D array, and raises ValueError if the two have different numbers of rows. For a classifier, also call check_classification_targets(y) from sklearn.utils.multiclass. It rejects targets that are continuous floats, which usually means the user passed a regression target to a classifier by mistake.
A transformer's fit takes y=None by convention, so use plain check_array(X) there.
check_is_fitted: refusing to run before fit
check_is_fitted(estimator) looks for attributes that end with an underscore (and do not start with two underscores). If none exist, it raises NotFittedError from sklearn.exceptions. NotFittedError inherits from both ValueError and AttributeError, so code that catches either still works.
This is why the underscore convention from the previous chapter matters. The check uses it to tell the constructor parameters (lower) from the learned state (lower_). If you stored a learned value under a name without a trailing underscore, check_is_fitted could not see it, and cloning or get_params could pick it up by mistake.
You can name the attributes explicitly when you want a stricter test:
check_is_fitted(self, ["lower_", "upper_"])With a list, the check passes only if all of those attributes exist.
Putting it together in a transformer
This is the QuantileClipper from the plan. It validates in fit, checks fitted state in transform, validates again, and compares the column count. The demo below it exercises each guard.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.exceptions import NotFittedError
from sklearn.utils.validation import check_array, check_is_fitted
class QuantileClipper(TransformerMixin, BaseEstimator):
def __init__(self, lower=0.01, upper=0.99):
self.lower = lower
self.upper = upper
def fit(self, X, y=None):
X = check_array(X)
self.lower_ = np.quantile(X, self.lower, axis=0)
self.upper_ = np.quantile(X, self.upper, axis=0)
self.n_features_in_ = X.shape[1]
return self
def transform(self, X):
check_is_fitted(self)
X = check_array(X)
if X.shape[1] != self.n_features_in_:
raise ValueError(
f"X has {X.shape[1]} features, but {self.__class__.__name__} "
f"is expecting {self.n_features_in_} features as input"
)
return np.clip(X, self.lower_, self.upper_)
rng = np.random.default_rng(0)
X_train = rng.normal(size=(100, 3))
clipper = QuantileClipper()
try:
clipper.transform(X_train)
except NotFittedError as exc:
print("not fitted:", exc)
clipper.fit(X_train)
print(clipper.transform(X_train).shape)
try:
clipper.transform(X_train[:, :2])
except ValueError as exc:
print("wrong width:", exc)
print(clipper.transform(X_train.tolist()).shape) # lists work tooThe first call fails with NotFittedError, the second succeeds, the third fails with the feature-count message, and the last shows that check_array accepted a plain list.
Notice where the guards sit. check_is_fitted comes first in transform, so an unfitted estimator fails with the clear "not fitted" message and not with an AttributeError about lower_. The feature-count comparison uses the n_features_in_ that fit recorded, which is why fit must set it.
Letting scikit-learn do the bookkeeping
Writing the column-count check by hand is correct but repetitive. Since version 1.6, scikit-learn provides validate_data in sklearn.utils.validation:
from sklearn.utils.validation import validate_data
# in fit
X = validate_data(self, X, reset=True)
# in transform or predict
X = validate_data(self, X, reset=False)With reset=True it validates X, sets n_features_in_, and, for DataFrame input, sets feature_names_in_. With reset=False it validates X and raises if the column count or the column names differ from what fit saw. Older versions did the same through a private method, self._validate_data, which later versions removed. If your code must run on both old and new versions, the manual pattern above works everywhere. The chapter on version compatibility returns to this.
Edge cases to decide on deliberately
- Missing values. The default rejects
NaN. If your estimator can handle them (an imputer would), passensure_all_finite="allow-nan"and make sure your arithmetic usesnp.nanquantileor similar. Passing the flag without changing the math just moves the failure. - Sparse input. If you leave
accept_sparse=False, a sparse matrix raisesTypeError, which is the right outcome for code that callsnp.quantile. Accept sparse input only when you have tested the sparse code path. - Dtype.
dtype="numeric"keeps integers as integers. If your math produces fractions, ask fordtype=[np.float64, np.float32]so integer data becomes float64 and float32 data stays float32. - Minimum samples. A quantile of one row is meaningless. Use
ensure_min_sampleswhen your statistic needs more rows. - Stateless transformers. An estimator that learns nothing has no trailing-underscore attributes, so
check_is_fittedwould always fail. Skip the call intransform, or define a method__sklearn_is_fitted__(self)that returnsTrueoncefithas run (scikit-learn calls it when it exists). - Validate in
fitand intransform, never in__init__. Checking0 <= lower < upper <= 1in the constructor breaksset_paramsandGridSearchCV, which assign parameters after construction. Put parameter checks at the start offit.
Summary of the rules
- Call
check_array(orcheck_X_ywhenyexists) at the start offit. - Record
n_features_in_infit. - In
transformandpredict, callcheck_is_fittedfirst, thencheck_array, then compare the column count. - Choose
check_arrayoptions on purpose: sparse,NaN, dtype, minimum samples. - Do not mutate the validated array unless you passed
copy=True. - Check parameter values in
fit, not in__init__.
Exercise
A colleague writes a transformer whose transform begins with X = check_array(X) and then uses self.mean_. Calling transform before fit raises AttributeError: 'Scaler' object has no attribute 'mean_'. Which line should they add, where, and what changes in the error? Also, their transform ends with X -= self.mean_; return X. Why is this a bug even after the fix, and how do they correct it?
Show answer
Add check_is_fitted(self) as the first line of transform, before check_array. The error then becomes NotFittedError with the message that the estimator is not fitted yet and fit must be called first. The in-place subtraction is a bug because check_array does not copy by default. When the caller passes a float NumPy array, X -= self.mean_ changes the caller's array. They should write return X - self.mean_, which builds a new array, or call check_array(X, copy=True).
Exercise
Write the guard you would add to the end of the QuantileClipper.fit method so that lower and upper are checked, and explain why the check cannot go in __init__.
Show answer
At the start of fit, add: if not 0 <= self.lower < self.upper <= 1: raise ValueError("Need 0 <= lower < upper <= 1"). It cannot go in __init__ because scikit-learn clones estimators with the stored parameters and GridSearchCV changes them with set_params after construction. Constructor checks would not run on those new values, and a constructor that does anything besides storing arguments breaks the cloning convention.
Exercise
Why does check_is_fitted(self) depend on the trailing-underscore naming convention, and what should a stateless transformer do instead?
Show answer
By default check_is_fitted looks for instance attributes that end with an underscore, such as lower_, and treats their presence as proof that fit ran. Learned values stored under other names would be invisible to it. A stateless transformer learns nothing, so it can skip the check in transform, or define __sklearn_is_fitted__ returning True once fit has run.