Put customized functions in Sklearn pipeline
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Scikit-learn pipelines chain preprocessing steps and models into a single object. When you need custom data transformations that are not available in sklearn (like domain-specific feature engineering, text cleaning, or custom scaling), you can integrate your own functions using FunctionTransformer, custom transformer classes, or TransformerMixin. This keeps your entire workflow in one pipeline, ensuring consistent training and inference.
Method 1: FunctionTransformer (Simple Functions)
For stateless transformations that do not need to learn from the training data:
With Parameters
Pass additional arguments via kw_args:
With Inverse Transform
If your function is invertible:
Method 2: Custom Transformer Class (Stateful)
When your transformation needs to learn parameters from the training data (like computing means, thresholds, or vocabularies), create a class that inherits from BaseEstimator and TransformerMixin:
Key rules:
fit()learns parameters from training data and returnsselftransform()applies the transformation using learned parameters__init__()stores hyperparameters only — never modify them infit()TransformerMixinprovidesfit_transform()automatically
Method 3: Column-Specific Transformations with ColumnTransformer
Apply different custom functions to different columns:
Method 4: Custom Feature Selector
A transformer that selects features based on criteria:
Complete Example: Feature Engineering Pipeline
Using with GridSearchCV
Custom transformer parameters are accessible for hyperparameter tuning:
Common Pitfalls
- Data Integrity: Always validate input to custom functions. A transformer that receives unexpected
NaNvalues or wrong dtypes can produce silent errors. - Feature Alignment: Ensure custom transformations output consistent shapes between
fitandtransform. Iffitsees 10 features,transformmust also process 10 features. - Modifying
__init__params infit: Sklearn'sget_params()/set_params()(used by GridSearchCV) relies on__init__parameters being stored unmodified. Use trailing underscores (likeself.mean_) for learned attributes. - Pandas vs NumPy: Some sklearn steps return NumPy arrays, losing column names. If your custom transformer expects a DataFrame, use
set_output(transform="pandas")(sklearn 1.2+) or convert explicitly. - Pickle serialization: Custom transformers must be picklable for
joblib.dump(). Avoid lambda functions or closures inFunctionTransformerif you need to save the pipeline.
Summary
| Approach | When to Use |
FunctionTransformer | Stateless transforms (log, clip, encode) |
Custom class with TransformerMixin | Stateful transforms (learn from training data) |
ColumnTransformer | Different transforms per column |
make_pipeline | Quick pipeline without naming steps |
- Use
FunctionTransformerfor simple, stateless functions - Create a class inheriting
BaseEstimator+TransformerMixinfor stateful transformations - Custom transformers work with
GridSearchCV,cross_val_score, andPipelineseamlessly - Always implement
fit()returningselfandtransform()returning the transformed data
Related reading
- Pybrain neural network _convertToOneOfMany error
- pybrain neural network not learning
- python3 recognizes tensorflow, but doesn''t recognize any of its attributes
- Python - A way to learn and detect text patterns?
- pyplot scatter plot marker size
- Python - Calculate Hierarchical clustering of word2vec vectors and plot the results as a dendrogram
- Putting an if-elif-else statement on one line?
- PyCharm error 'No Module' when trying to import own module python script
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.