Sub topic 2
Validating Input and Checking That the Estimator Is Fitted
Assume you know Python classes, NumPy arrays, and the basic fit, transform, and predict methods. A scikit-learn estimator should validate inputs at method boundaries and should reject use before fitting.
Validate Inputs and Fitted State
Use check_array for feature data and check_X_y when both features and targets are required. Learned attributes should end with _. check_is_fitted checks for these attributes before inference.
from sklearn.utils.validation import check_array, check_is_fitted, check_X_y
def transform(self, X):
check_is_fitted(self)
X = check_array(X)
return XValidation belongs in fit, transform, and predict, not in __init__. The constructor only stores configuration. This lets scikit-learn clone the estimator safely.
Build a Custom Transformer
A transformer implements fit and transform. TransformerMixin supplies fit_transform. This example learns a separate lower and upper quantile for each column, then clips later data to those bounds.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
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("The number of features changed")
return np.clip(X, self.lower_, self.upper_)Use `FunctionTransformer` for Stateless Functions
For a stateless operation, a class may be unnecessary. FunctionTransformer adapts a function to the transformer API.
import numpy as np
from sklearn.preprocessing import FunctionTransformer
log_step = FunctionTransformer(
np.log1p,
inverse_func=np.expm1,
feature_names_out="one-to-one",
)Build a Custom Classifier
A classifier implements fit and predict. ClassifierMixin provides a standard accuracy-based score method.
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.utils.validation import check_array, check_X_y, check_is_fitted
class MeanCentroidClassifier(ClassifierMixin, BaseEstimator):
def fit(self, X, y):
X, y = check_X_y(X, y)
self.classes_, indices = np.unique(y, return_inverse=True)
self.centroids_ = np.vstack([
X[indices == i].mean(axis=0)
for i in range(len(self.classes_))
])
self.n_features_in_ = X.shape[1]
return self
def predict(self, X):
check_is_fitted(self)
X = check_array(X)
distances = np.linalg.norm(
X[:, None, :] - self.centroids_[None, :, :], axis=2
)
return self.classes_[np.argmin(distances, axis=1)]Exercise
Why does fit return self?
Show answer
Scikit-learn expects this return value so calls can be chained and the estimator can be used in pipelines and cross-validation.