Lesson 2 of 9
Developing Custom Scikit-Learn Transformers with BaseEstimator & TransformerMixin
While Scikit-Learn provides extensive built-in transformers, production ML systems frequently require custom business logic: domain clipping, outlier winsorization, logit transformations, or database lookups. Implementing custom classes inheriting from `BaseEstimator` and `TransformerMixin` guarantees compatibility with `Pipeline`, `clone()`, and `GridSearchCV`.
Custom Outlier Winsorizer Transformer Implementation
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
# CUSTOM TRANSFORMER INHERITING FROM SCIKIT-LEARN BASE CLASSES
class EmpiricalWinsorizer(BaseEstimator, TransformerMixin):
"""
Clips extreme feature outliers to empirical lower and upper percentiles.
Learns quantile bounds strictly during .fit(), applies them during .transform().
"""
def __init__(self, lower_percentile=1.0, upper_percentile=99.0):
# Cardinal Rule: NEVER modify arguments in __init__; assign directly to self
self.lower_percentile = lower_percentile
self.upper_percentile = upper_percentile
self.lower_bounds_ = None
self.upper_bounds_ = None
def fit(self, X, y=None):
# Learn state ONLY during fit
X_arr = np.asarray(X)
self.lower_bounds_ = np.percentile(X_arr, self.lower_percentile, axis=0)
self.upper_bounds_ = np.percentile(X_arr, self.upper_percentile, axis=0)
# Cardinal Rule: fit() must always return self
return self
def transform(self, X):
# Apply learned state without modifying bounds
X_arr = np.asarray(X)
return np.clip(X_arr, self.lower_bounds_, self.upper_bounds_)
# Test in an end-to-end Pipeline
np.random.seed(42)
X_dirty = np.array([
[10.0, 50.0],
[12.0, 52.0],
[11.0, 51.0],
[999.0, -999.0] # Severe contamination outliers
])
y_dummy = np.array([100.0, 110.0, 105.0, 108.0])
custom_pipe = Pipeline([
('winsorizer', EmpiricalWinsorizer(lower_percentile=5.0, upper_percentile=95.0)),
('scaler', StandardScaler()),
('regressor', Ridge(alpha=1.0))
])
custom_pipe.fit(X_dirty, y_dummy)
print("=== CUSTOM TRANSFORMER VERIFICATION ===")
print("Learned Lower Bounds:", custom_pipe.named_steps['winsorizer'].lower_bounds_)
print("Learned Upper Bounds:", custom_pipe.named_steps['winsorizer'].upper_bounds_)
print("Prediction on Clean Sample:", custom_pipe.predict([[11.5, 51.5]]))Pro Tip: The `get_params()` and `set_params()` Free Bonus
By inheriting from `BaseEstimator`, your custom transformer automatically gets `get_params()` and `set_params()` methods without writing a single line of code! This allows hyperparameter search tools like `GridSearchCV` and `Optuna` to tune your custom parameters automatically (e.g. `param_grid = {'winsorizer__lower_percentile': [0.5, 1.0, 2.0]}`).
MlCustomTransformers Visual Representation
Hands-On Challenge: Build a DataFrame Feature Drop Transformer
Create a custom Scikit-Learn transformer `CorrelationPruner(threshold=0.85)` that computes the correlation matrix during `.fit()`, stores feature names exceeding the threshold, and drops them during `.transform()`.
Quick Quiz & Key Concept Checks
Common Pitfall: Storing Transformed Data as Class State
Never store the transformed data matrix as an attribute (e.g. `self.X_transformed = X`) inside `fit()` or `transform()`. Storing data matrices inside estimators wastes gigabytes of memory when models are serialized or pickled.