Building Custom Estimators & Transformers

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Sooner or later a project needs a step that scikit-learn does not ship: a domain-specific feature, a model with an unusual rule, a wrapper that adds behaviour to another estimator. Written as a plain function it works until someone puts it in a Pipeline, clones it in a grid search, or saves it; written as an estimator that follows the conventions, it plugs into all of them. This page explains the conventions, shows three complete estimators (a transformer, a classifier, a meta-estimator), the tests that check them, and the mistakes that the tests catch.

Examples were run on Python 3.13 with scikit-learn 1.9.1, NumPy 2.5.4, pandas 3.1.0 and pytest 9.2.0 on 2026-10-31. Every API used (validate_data, __sklearn_tags__, check_estimator) exists since scikit-learn 1.6.

The short version of the rules is in the estimator-API page, section "Writing your own estimator": The scikit-learn Estimator API. This page assumes it and goes further: sample weights, meta-estimators, tags, the checks and what breaks them. Related pages: get_params, set_params and clone, Pipelines, set_output, Metadata Routing and Glossary.

The contract

Three boxes: the constructor stores hyperparameters, fit validates and learns attributes ending in an underscore and returns self, predict or transform checks fitted state; get_params, set_params and clone see only constructor arguments
Figure 1. The constructor stores parameters, fit learns state ending in an underscore, and predict or transform only reads it.

Everything scikit-learn does with an estimator depends on three facts:

  1. get_params reflects the constructor. BaseEstimator.get_params reads the signature of __init__ and returns the attribute of the same name for each argument. So every argument must be stored, unchanged, under its own name, and __init__ takes no *args or **kwargs. set_params writes the same attributes, which is why a grid search can change a parameter without calling __init__ again.

  2. clone builds a new object from get_params. It constructs an unfitted copy with the same parameters. State learned by fit is not copied, and a constructor that converts, validates or computes would give a clone different from its source. For that reason validation (period must be positive) belongs in fit.

  3. Fitted state ends in an underscore. check_is_fitted tests whether any attribute ending in _ exists. Public learned attributes (coef_, classes_) are documented; private ones start with an underscore.

The method contract:

  • fit(X, y=None, **fit_params) validates the input, learns, and returns self. Calling fit twice must be the same as calling it once on the second data (no leftover state), unless the estimator has a documented warm_start. Unsupervised estimators and transformers still accept y=None so that pipelines can pass it.

  • predict, transform, predict_proba and decision_function start with check_is_fitted(self), validate with reset=False, and never change the fitted state.

  • A transformer does not change the number of rows. A step that removes rows (for instance outlier removal) is not a transformer; imbalanced-learn calls such objects samplers and gives them their own pipeline (see Imbalanced Data).

  • Classifiers set classes_ (sorted unique labels, any hashable type) in fit, and the columns of predict_proba and decision_function follow its order. A binary decision_function returns a one-dimensional array: the score of the positive class (classes_[1]).

  • Random behaviour takes a random_state constructor argument, stored unchanged; fit calls sklearn.utils.check_random_state(self.random_state) and does not touch the global NumPy generator. See Common Pitfalls for what an integer versus an instance means.

validate_data(self, X, y, ...) (module sklearn.utils.validation) does the repetitive part: it converts the input to a NumPy array, rejects NaN and infinity unless the tags allow them, checks that X is two-dimensional, sets n_features_in_ and, for a DataFrame, feature_names_in_; with reset=False it instead checks that the new data have the same number of features and the same column names. The parameter reset=True (the default) belongs in fit, reset=False everywhere else.

Mixins add behaviour and go on the left of BaseEstimator: TransformerMixin (fit_transform, plus set_output when get_feature_names_out exists), ClassifierMixin (score = accuracy), RegressorMixin (score = R²), ClusterMixin, OutlierMixin, MetaEstimatorMixin. The order matters because the mixins override BaseEstimator’s defaults (for instance the tags).

A transformer: cyclical encoding

A stateless-looking transformer that still follows every rule: it maps a periodic feature (hour of day, day of year) to a sine and a cosine, so that the end of the cycle is next to its start. The period is a hyperparameter. It validates it in fit, reports feature names, and supports pandas output through set_output.

import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.estimator_checks import check_estimator
from sklearn.utils.validation import check_is_fitted, validate_data


class CyclicalEncoder(TransformerMixin, BaseEstimator):
    """Encode each column of a periodic feature as a sine and cosine pair."""

    def __init__(self, period=24):
        self.period = period

    def fit(self, X, y=None):
        validate_data(self, X)                       # sets n_features_in_ and feature_names_in_
        if self.period <= 0:
            raise ValueError(f"period must be positive, got {self.period!r}")
        return self

    def transform(self, X):
        check_is_fitted(self)
        X = validate_data(self, X, reset=False)
        angle = 2 * np.pi * X / self.period
        return np.hstack([np.sin(angle), np.cos(angle)])

    def get_feature_names_out(self, input_features=None):
        if input_features is None:
            input_features = getattr(self, "feature_names_in_",
                                     [f"x{i}" for i in range(self.n_features_in_)])
        names = np.asarray(input_features, dtype=object)
        return np.concatenate([[f"{n}_sin" for n in names], [f"{n}_cos" for n in names]]).astype(object)


df = pd.DataFrame({"hour": [0, 6, 12, 18], "load": [1.0, 2.0, 3.0, 4.0]})
enc = CyclicalEncoder(period=24).set_output(transform="pandas")
print(enc.fit_transform(df[["hour"]]).round(2))
check_estimator(CyclicalEncoder())
print("CyclicalEncoder checks passed")
   hour_sin  hour_cos
0       0.0       1.0
1       1.0       0.0
2       0.0      -1.0
3      -1.0      -0.0
CyclicalEncoder checks passed

Notes on this listing:

  • fit_transform and set_output come from TransformerMixin; the second exists because the class defines get_feature_names_out. Without it, set_output(transform="pandas") would not be available.

  • -0.0 in the last row is the IEEE negative zero from \(\cos(3\pi/2)\) rounding; it is harmless.

  • check_estimator returns without error when all checks pass.

  • The same class works inside a ColumnTransformer (("cyc", CyclicalEncoder(24), ["hour"])) and its names flow into the output of get_feature_names_out of the whole pipeline. Compare it with the periodic SplineTransformer used in End-to-End ML Project: the spline is the more flexible choice for linear models, the sine-cosine pair is the minimal one.

A classifier with sample weights

A nearest-centroid classifier that supports sample_weight and predict_proba. The weights make each centroid a weighted mean, which is how many scikit-learn estimators interpret them (duplicating a sample is equivalent to doubling its weight).

import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.utils.estimator_checks import check_estimator
from sklearn.utils.multiclass import check_classification_targets
from sklearn.utils.validation import _check_sample_weight, check_is_fitted, validate_data


class WeightedCentroidClassifier(ClassifierMixin, BaseEstimator):
    """Assigns the class with the nearest weighted centroid."""

    def __init__(self, temperature=1.0):
        self.temperature = temperature

    def fit(self, X, y, sample_weight=None):
        X, y = validate_data(self, X, y)
        check_classification_targets(y)
        sample_weight = _check_sample_weight(sample_weight, X)
        self.classes_, y_idx = np.unique(y, return_inverse=True)
        totals = np.bincount(y_idx, weights=sample_weight)
        if np.any(totals <= 0):
            raise ValueError("Every class needs a positive total sample weight; "
                             "a class has none after weighting.")
        self.centroids_ = np.vstack([
            np.average(X[y_idx == k], axis=0, weights=sample_weight[y_idx == k])
            for k in range(len(self.classes_))
        ])
        return self

    def _scores(self, X):
        check_is_fitted(self)
        X = validate_data(self, X, reset=False)
        return -np.linalg.norm(X[:, None, :] - self.centroids_[None], axis=2)

    def predict_proba(self, X):
        z = self._scores(X) / self.temperature
        z -= z.max(axis=1, keepdims=True)           # numerical stability
        p = np.exp(z)
        return p / p.sum(axis=1, keepdims=True)

    def predict(self, X):
        scores = self._scores(X)                     # checks that the model is fitted
        return self.classes_[np.argmax(scores, axis=1)]


check_estimator(WeightedCentroidClassifier())
print("WeightedCentroidClassifier checks passed")
WeightedCentroidClassifier checks passed

The listing is the third version of the class; the first two failed check_estimator, and the failures show what the checks look for:

  • The first version did not call check_is_fitted in predict and failed with "Estimator should raise a NotFittedError when calling predict before fit". Computing the scores first (self._scores(X) checks) and only then reading self.classes_ fixed it, because Python evaluates the index expression of self.classes_[...] before the call inside it; the check message says to either call check_is_fitted(self) at the beginning of predict or to set tags.requires_fit=False.

  • The second used np.average with weights and failed in check_classifiers_one_label_sample_weights: giving zero weight to every sample of a class made np.average raise ZeroDivisionError, and the check requires an explicit error message that mentions the word "class". The validation of the totals produces it. The convention is that a zero weight removes a sample, so a class with zero total weight is as if it were absent.

  • An earlier variant exposed a method called decision_function that returned one score per class, also for two classes. The check check_classifiers_predictions failed: a binary decision_function must be one-dimensional. The listing avoids the problem by keeping the scores private and offering predict_proba.

_check_sample_weight is a private helper of scikit-learn (it has an underscore); it is used by many estimators and is convenient, but it may change without notice. Replace it with your own conversion (np.asarray(sample_weight, dtype=float), a shape check, and a non-negativity check) in a library you maintain.

A meta-estimator

A meta-estimator wraps another estimator that arrives as a constructor argument. The rules are the same plus three more: clone the sub-estimator in fit and keep the fitted copy under a name with an underscore, expose its parameters through get_params(deep=True) (inherited, nothing to write), and forward fit parameters. This one trains a regressor on a target clipped to its quantiles, which limits the influence of extreme values.

import numpy as np
from sklearn.base import BaseEstimator, MetaEstimatorMixin, RegressorMixin, clone
from sklearn.linear_model import Ridge
from sklearn.model_selection import GridSearchCV
from sklearn.utils.estimator_checks import check_estimator
from sklearn.utils.validation import check_is_fitted, validate_data


class ClippedTargetRegressor(MetaEstimatorMixin, RegressorMixin, BaseEstimator):
    def __init__(self, regressor=None, q=0.01):
        self.regressor = regressor
        self.q = q

    def fit(self, X, y, **fit_params):
        X, y = validate_data(self, X, y, y_numeric=True)
        regressor = Ridge() if self.regressor is None else self.regressor
        self.regressor_ = clone(regressor)          # never fit the object the user passed
        lo, hi = np.quantile(y, [self.q, 1 - self.q])
        self.regressor_.fit(X, np.clip(y, lo, hi), **fit_params)
        return self

    def predict(self, X):
        check_is_fitted(self)
        X = validate_data(self, X, reset=False)
        return self.regressor_.predict(X)


check_estimator(ClippedTargetRegressor())
print("ClippedTargetRegressor checks passed")

model = ClippedTargetRegressor(Ridge(), q=0.05)
print(sorted(model.get_params())[:6])

rng = np.random.RandomState(0)
X = rng.normal(size=(200, 3))
y = X @ [1, 2, 3] + rng.standard_cauchy(200)         # heavy-tailed noise
grid = GridSearchCV(ClippedTargetRegressor(Ridge()),
                    {"q": [0.001, 0.05, 0.2], "regressor__alpha": [0.1, 10]}, cv=3).fit(X, y)
print(grid.best_params_)
ClippedTargetRegressor checks passed
['q', 'regressor', 'regressor__alpha', 'regressor__copy_X', 'regressor__fit_intercept', 'regressor__max_iter']
{'q': 0.05, 'regressor__alpha': 0.1}

regressor__alpha is a valid grid key without any code in the class: get_params(deep=True) found the nested parameters. Two cautions:

  • Do not fit self.regressor itself. The grid search clones the meta-estimator, and a clone shares the same sub-estimator object unless fit clones it; fitting the shared object would make the folds overwrite each other.

  • For a regressor that transforms the target and must also inverse-transform the prediction, scikit-learn already offers TransformedTargetRegressor (see the Pipelines page); a threshold wrapper has TunedThresholdClassifierCV. Check whether a meta-estimator exists before writing one.

If the wrapped estimator must receive routed metadata (groups, sample_weight) from a pipeline, the meta-estimator has to implement get_metadata_routing; that is a larger topic covered on the metadata routing page.

Estimator tags

Tags tell tools what an estimator can do: whether it accepts NaN, sparse input or one feature, whether it needs to be fitted, which kind of estimator it is. The tests of check_estimator consult them to decide which checks to run. In scikit-learn 1.6 the tags became a public dataclass-based API: you override __sklearn_tags__, call the parent first, and change fields.

import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils import get_tags
from sklearn.utils.estimator_checks import check_estimator
from sklearn.utils.validation import validate_data


class NanAwareClipper(TransformerMixin, BaseEstimator):
    """Clip values to [-limit, limit] and let NaN through."""

    def __init__(self, limit=3.0):
        self.limit = limit

    def __sklearn_tags__(self):
        tags = super().__sklearn_tags__()
        tags.input_tags.allow_nan = True             # and tell validate_data to accept it, below
        tags.requires_fit = False                     # stateless: nothing to learn
        return tags

    def fit(self, X, y=None):
        validate_data(self, X, ensure_all_finite="allow-nan")
        return self

    def transform(self, X):
        X = validate_data(self, X, reset=False, ensure_all_finite="allow-nan")
        return np.clip(X, -self.limit, self.limit)

    def get_feature_names_out(self, input_features=None):
        if input_features is None:
            input_features = [f"x{i}" for i in range(self.n_features_in_)]
        return np.asarray(input_features, dtype=object)


t = NanAwareClipper()
print(get_tags(t).input_tags.allow_nan, get_tags(t).requires_fit)
print(t.fit_transform(np.array([[1.0, np.nan], [10.0, -9.0]])))
check_estimator(NanAwareClipper())
print("checks passed")
True False
[[ 1. nan]
 [ 3. -3.]]
checks passed

Tags are declarations; they do not change behaviour by themselves. Declaring allow_nan = True while validate_data still rejects NaN fails the checks, which is why both lines appear in the listing. The argument that controls it in validate_data and check_array is ensure_all_finite (force_all_finite before scikit-learn 1.6; the old name has since been removed, and passing it in 1.9.1 raises a TypeError). The class returned by __sklearn_tags__ is a Tags dataclass with estimator_type, target_tags, transformer_tags, classifier_tags, regressor_tags, input_tags (sparse, allow_nan, one_d_array, pairwise, …​) and boolean flags such as non_deterministic and requires_fit. The mixins fill in the right defaults, which is the second reason they go to the left of BaseEstimator. To add a custom tag, subclass Tags as a dataclass with defaults for every new field.

Stateless steps: FunctionTransformer

If the step is a function of the data with no state and no hyperparameters worth tuning, a class is overkill: FunctionTransformer(func, inverse_func=None, feature_names_out=None, ...) wraps a function.

import numpy as np
from sklearn.preprocessing import FunctionTransformer

log = FunctionTransformer(np.log1p, inverse_func=np.expm1, feature_names_out="one-to-one")
print(log.fit_transform(np.array([[0.0, 1.0]])), log.get_feature_names_out(["a", "b"]))
[[0.         0.69314718]] ['a' 'b']

Use feature_names_out="one-to-one" or a callable, otherwise the transformer cannot report names inside a pipeline. The weakness of a function wrapped like this is serialisation: a lambda or a function defined in a notebook cannot be pickled by reference, so joblib or pickle fails, or loads only where the function exists. Use a named, importable function, a class like the ones above (a module that is installed in both training and serving environments), or cloudpickle as a last resort; the model persistence page lists the formats. When the function has parameters that you want to tune, use kw_args and set_params(kw_args=...), or write the class.

Testing the estimator

check_estimator(estimator) runs the library’s own checks on an instance and raises AssertionError with an explicit message on the first failure; on_fail=None collects the results instead. parametrize_with_checks([instances]) turns the same checks into individual pytest cases, so a failure names the check. Both live in sklearn.utils.estimator_checks. In 1.9.1 the signature of the first is check_estimator(estimator=None, *, legacy=True, expected_failed_checks=None, on_skip="warn", on_fail="raise", callback=None) (the older generate_only argument is gone); this function evolves, so check the API reference of your version.

A deliberately broken transformer shows what the checks catch:

import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.estimator_checks import check_estimator
from sklearn.utils.validation import check_is_fitted, validate_data


class Broken(TransformerMixin, BaseEstimator):
    def __init__(self, scale=1.0):
        self.scale = float(scale)           # converts in the constructor
        self.mean_ = None                    # learned state in the constructor

    def fit(self, X, y=None):
        X = validate_data(self, X)
        self.mean_ = X.mean(axis=0)
        return self

    def transform(self, X):
        check_is_fitted(self)
        X = validate_data(self, X, reset=False)
        return (X - self.mean_) * self.scale


results = check_estimator(Broken(), on_fail=None)
failed = [r for r in results if r["status"] == "failed"]
print(len(results), "checks,", len(failed), "failed")
for r in failed[:3]:
    print(r["check_name"], "->", str(r["exception"])[:110])
47 checks, 4 failed
check_no_attributes_set_in_init -> Estimator Broken should not set any attribute apart from parameters during init. Found attributes ['mean_'].
check_do_not_raise_errors_in_init_or_set_params -> could not convert string to float: 'helloworld'
check_transformers_unfitted -> The unfitted transformer Broken does not raise an error when transform is called. Perhaps use check_is_fitted

(The count of 47 checks is from 1.9.1 with the default legacy=True; it varies by version and by the tags of the estimator. The fourth failure, not shown, is check_fit_check_is_fitted.) The three messages point at the three mistakes: an attribute set in __init__ besides the parameters, a conversion in __init__ that breaks set_params, and a missing check_is_fitted (here the check fires because mean_ = None exists, so check_is_fitted finds a fitted-looking attribute; the real fix is to remove the attribute from the constructor).

In a project, put the check in the test suite:

# test_estimators.py -- run with pytest
from sklearn.utils.estimator_checks import parametrize_with_checks

from myproject.estimators import ClippedTargetRegressor, CyclicalEncoder, WeightedCentroidClassifier


@parametrize_with_checks([CyclicalEncoder(), WeightedCentroidClassifier(), ClippedTargetRegressor()])
def test_sklearn_compatible_estimator(estimator, check):
    check(estimator)

With the three classes of this page in an importable module, pytest collected 161 cases: 158 passed and 3 were skipped (the array API checks, which need SCIPY_ARRAY_API set).

When a check does not apply to an estimator for a good reason, both entry points accept expected_failed_checks, a mapping from the check name to the reason it is expected to fail, so that the suite documents the exception instead of hiding it. Some checks only warn or skip (for example array API support) via SkipTestWarning.

The checks are necessary, not sufficient: they verify the conventions, not that the model is correct. Add tests for the behaviour: the output on a known example, the effect of sample_weight (a weight of 2 equals a duplicated row), the error messages of invalid parameters, and a pickle round trip.

Beyond the basics

  • Fitted-state detection. If the learned attribute names are not suffixed with an underscore, define __sklearn_is_fitted__(self) returning a boolean; check_is_fitted then uses it.

  • Feature names and n_features_in_. validate_data sets both; if you avoid it (a transformer for text or images), set them yourself and implement get_feature_names_out, or pipelines cannot report names.

  • Sparse input. validate_data(..., accept_sparse=["csr"]) allows sparse matrices; then the tags must allow them and the code must not call dense-only functions.

  • Estimator type. Mixins determine estimator_type in the tags, which scorers and cross-validation use to pick stratified splits for classifiers.

  • Custom cloning. __sklearn_clone__ overrides clone; FrozenEstimator uses it so that a fitted model survives cloning.

  • Documentation links and HTML representation. BaseEstimator objects render as a diagram in notebooks; this API is experimental.

  • Inheriting from an existing estimator. Subclassing LogisticRegression to change one method is tempting, but the subclass inherits its constructor and tags; overriding fit without respecting them breaks the checks. Prefer composition, as in the meta-estimator above.

Packaging

Third-party estimators that follow the conventions and pass check_estimator are called scikit-learn compatible. The scikit-learn-contrib project template (https://github.com/scikit-learn-contrib/project-template) is a starting point for such a package: a package folder with a placeholder estimator, documentation and example folders, GitHub workflows for tests and for publishing the documentation, a pyproject.toml, and a BSD-3-Clause license. Its README says it helps with testing, including some API compliance checks; look at the repository itself for what the current version contains.

For code inside one application there is no need for a package: put the classes in a module that both the training script and the serving code import, so that pickled pipelines can find them. A class defined in __main__ (a script or notebook) is saved as a reference to __main__.ClassName and cannot be loaded elsewhere. See the persistence page (Model Persistence and Security) and, for the complete life cycle, End-to-End ML Project.

Pitfalls

  • Work in __init__. Validation, conversion, default objects (self.regressor = Ridge() when None) and learned attributes break get_params, clone and set_params. Keep the constructor a list of assignments and resolve defaults in fit.

  • A mutable default argument. An empty list or dict as the default of a constructor argument is shared by all instances. Use None and create the value in fit.

  • Fitting the sub-estimator you were given. Clone it first.

  • Forgetting return self in fit; fit_transform and pipelines depend on it.

  • Not resetting state in fit. Appending to a list attribute across calls makes fit depend on its history.

  • reset=True in predict or transform. It silently re-learns the number of features instead of validating it.

  • Binary decision_function with two columns. It is one-dimensional for two classes.

  • Using the global random generator. Results then depend on whatever else ran.

  • Mixins to the right of BaseEstimator. BaseEstimator’s defaults then win over the mixin’s.

  • Relying on private helpers (_check_sample_weight, _validate_data) that change between versions.

  • Unpicklable members. Lambdas, open files and database connections stored in attributes stop the model from being saved.

What is outdated

Compared with older books and tutorials:

  • Older code calls self._validate_data(X, y), check_X_y and check_array in fit. The public validate_data function replaced the private method in scikit-learn 1.6, and the method no longer exists on BaseEstimator in 1.9.1; check_array and check_X_y remain available for code that does not need the bookkeeping of n_features_in_.

  • Estimator tags used to be a private dictionary returned by _get_tags, customised with a _more_tags method. The public __sklearn_tags__ API replaced it in 1.6. In 1.9.1 a _more_tags method is silently ignored (no warning; a tag it sets, such as allow_nan, keeps its default), so code that defines it needs porting; the 1.9 guide describes only the new form.

  • force_all_finite was renamed ensure_all_finite in 1.6 and is no longer accepted in 1.9.1.

  • Books that introduce custom transformers (Sebastian Raschka’s chapter on pipelines is the structural reference for this page) rely on the same pattern of inheriting from BaseEstimator and TransformerMixin; whatever the version, a class that sets learned attributes in __init__ or does not return self from fit fails check_estimator.

  • Third-party libraries such as SciKeras (archived) and older wrappers around other frameworks are outside the scope of this page; see Using scikit-learn with PyTorch & Keras.