Sub topic 5
Validating input and checking that the estimator is fitted
This chapter assumes you know how fit and transform work and why learned attributes end with an underscore. It covers the checks an estimator should run before it computes anything.
Why validate at all
Without checks, bad input fails late and with confusing messages. A NumPy broadcasting error deep inside transform says nothing about the real cause, which may be a missing column or a NaN. scikit-learn provides helpers in sklearn.utils.validation so that custom estimators fail early with clear messages, like the built-in ones.
check_array and check_X_y
check_array(X) converts the input to a 2D NumPy array and rejects data that most estimators cannot handle. By default it:
- converts lists and DataFrames to a NumPy array
- raises
ValueErrorfor 1D input, because scikit-learn expects shape(n_samples, n_features) - raises
ValueErrorforNaNand infinity - raises
ValueErrorfor empty input and non-numeric data
check_X_y(X, y) applies the same checks to X. It also validates y and confirms that both have the same number of samples. Use it in fit for supervised estimators. Use check_array in fit for transformers that ignore y, and in transform and predict.
You can relax the defaults through parameters. For example, check_array(X, dtype=None) keeps the original dtype, and accept_sparse=True allows sparse matrices. Only relax a check if your code handles the case.
check_is_fitted
Calling transform or predict before fit is a common mistake. check_is_fitted(self) raises NotFittedError unless the estimator has at least one attribute that ends with an underscore. This is why the trailing underscore convention matters.
You can name the attributes to require, such as check_is_fitted(self, "mean_"). This is stricter and clearer when your estimator learns several things.
Checking the feature count
A fitted estimator should refuse input with a different number of columns than it saw in fit. Store n_features_in_ in fit and compare it in transform.
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 MeanCenterer(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, "mean_")
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 X - self.mean_
centerer = MeanCenterer()
try:
centerer.transform([[1.0, 2.0]])
except NotFittedError as e:
print("Not fitted:", e)
centerer.fit([[1.0, 2.0], [3.0, 4.0]])
print(centerer.transform([[2.0, 3.0]]))
try:
centerer.transform([[1.0, 2.0, 3.0]])
except ValueError as e:
print("Wrong width:", e)
try:
centerer.transform([[1.0, np.nan]])
except ValueError as e:
print("Bad values:", e)The order inside transform matters. The diagram shows it.
Do not modify the input
check_array may return the same array you passed in, not a copy. Writing into it in place, as in X -= self.mean_, changes the caller's data. The example above uses X - self.mean_, which creates a new array. If you must work in place, call check_array(X, copy=True).
Newer helper
Recent scikit-learn versions (1.6 and later) provide validate_data(self, X, reset=True) in sklearn.utils.validation. It runs check_array and also sets n_features_in_ on fit and checks it on later calls. It can replace the manual feature count code. The manual version above works in every version, so use it if you must support older releases.
Exercise
A colleague's transformer sets self.scale_ = None inside __init__ and calls check_is_fitted(self) in transform. Why does the check never raise NotFittedError, and how do you fix it?
Show answer
check_is_fitted looks for any attribute ending with an underscore, and scale_ exists from construction, so the estimator always looks fitted. Remove the assignment from __init__ and create scale_ only in fit. Passing the attribute name, as in check_is_fitted(self, "scale_"), also makes the check stricter.