Sub topic 3
Using Custom Estimators in scikit-learn Workflows
Assume you know Python classes, NumPy indexing, and the fit, transform, and predict methods. A custom estimator should follow scikit-learn’s API so that larger tools can use it without special cases.
Pipeline and ColumnTransformer
Pipeline applies steps in sequence. ColumnTransformer applies different steps to different columns. A custom transformer can be used in either:
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
# QuantileClipper is the custom transformer defined earlier.
data = pd.DataFrame({
"age": [20, 35, 50, 42],
"city": ["A", "B", "A", "C"],
})
y = [0, 1, 1, 0]
preprocess = ColumnTransformer([
("numeric", QuantileClipper(), ["age"]),
("city", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])
model = Pipeline([
("preprocess", preprocess),
("classifier", LogisticRegression(max_iter=1000)),
])
model.fit(data, y)
print(model.predict(data))The pipeline fits each step only on training data. This prevents preprocessing from seeing validation or test values.
Cloning and tuning
GridSearchCV clones estimators before trying parameter combinations. Constructor arguments must therefore be stored unchanged. Nested parameters use step__parameter names:
param_grid = {
"preprocess__numeric__lower": [0.0, 0.05],
"classifier__C": [0.1, 1.0],
}Feature names and output
For pandas output, call set_output(transform="pandas"). A custom transformer should implement get_feature_names_out when it preserves or creates meaningful names. For a one-to-one transformer, return the input names unchanged.
Conformance checks
Run check_estimator(QuantileClipper()) to find violations such as missing fitted attributes, incorrect error handling, or mutation of inputs. Fix the first reported failure, then run the checks again.
Tags and compatibility
Estimator tags tell scikit-learn which inputs and behaviors an estimator supports. Use the tag mechanism documented for your installed version. Tag APIs can change between releases, so test against the versions you support.
> callout note > Never validate or learn data in __init__. Validate in fit or transform, keep learned values in attributes ending with _, and never fit preprocessing on test data.
Exercise
Why does GridSearchCV require constructor parameters to be stored unchanged?
Show answer
It clones the estimator and changes those parameters through get_params and set_params.