Skip to main content

With scikit-learn pipelines

A mlfeatures recipe handles data preprocessing and feature engineering; the model that consumes those features often lives downstream in scikit-learn. The RecipeTransformer adapter bridges the two: it wraps a recipe so it behaves like any other scikit-learn transformer and drops straight into a sklearn.pipeline.Pipeline.

The adapter

RecipeTransformer wraps an unfitted recipe. It exposes the familiar scikit-learn fit / transform / fit_transform methods, so the recipe’s specify → fit → transform lifecycle is driven by the pipeline rather than by hand.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split

X, y = load_breast_cancer(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
X_train.iloc[:5, :3]
mean radius mean texture mean perimeter
293 11.85 17.46 75.54
332 11.22 19.86 71.94
565 20.13 28.25 131.20
278 13.59 17.84 86.24
489 16.69 20.20 107.10

scikit-learn keeps the features X and the target y apart, while mlfeatures identifies the target by its role. Build the recipe with the target role assigned; the adapter re-joins y onto X under that name at fit time and strips it back out of the transformed output, so transform returns the feature matrix only.

from mlfeatures import Recipe, StepNormalize
from mlfeatures import Selectors as s

recipe = (
    Recipe(data=X_train.assign(target=y_train), target="target")
    .add(StepNormalize(s.numeric_features()))
)

Inside a Pipeline

Wrap the recipe in RecipeTransformer and place it ahead of an estimator. The pipeline’s fit flows X/y through the recipe, then fits the model on the engineered features:

from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline

from mlfeatures import RecipeTransformer

pipe = Pipeline(
    [
        ("recipe", RecipeTransformer(recipe)),
        ("model", LogisticRegression(max_iter=1000)),
    ]
)
pipe.fit(X_train, y_train)
pipe.score(X_test, y_test)
0.958041958041958

The statistics the recipe estimated (here the means and standard deviations) come from the training data only, and the test data is transformed with them.

Displaying the fitted pipeline renders scikit-learn’s diagram. The recipe shows up as a labelled RecipeTransformer (trained) block that expands to the recipe and its steps:

pipe
Pipeline(steps=[('recipe',
                 RecipeTransformer(recipe=Recipe (untrained)
  Inputs: 31 columns (1 target)
  Steps:
    step_normalize(select(role='feature', type=NumericType))  [untrained])),
                ('model', LogisticRegression(max_iter=1000))])
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

The target

The target needs a little care, because scikit-learn’s transform(X) never receives y. The adapter handles the common cases for you and raises a ValueError for the ones it cannot support:

  • Passing y to a recipe with no "target" role raises, since there is no column to join it onto. Name the column with Recipe(target=...), or assign the role with set_roles(target=...) before the first step (a role assignment written after a step cannot define the target). If the recipe needs no target, call fit(X) without y instead.
  • A recipe with more than one target column raises, since scikit-learn passes a single y.
  • A step that applies to the target column as one of its input columns raises at fit time, because that step could not run when transform(X) is called without the target. Transform the target outside the pipeline instead, for example with sklearn.compose.TransformedTargetRegressor.

Steps that use the target only while fitting are fine, because they need y at fit time and nothing at transform time. StepPls and StepClassDistance are the two examples: they learn from the target, and the columns they produce are computed from the features alone.

from mlfeatures import StepPls

pls_recipe = (
    Recipe(data=X_train.assign(target=y_train), target="target")
    .add(StepPls(s.numeric_features(), target="target", num_comp=2))
)
pls_pipe = Pipeline(
    [
        ("recipe", RecipeTransformer(pls_recipe)),
        ("model", LogisticRegression(max_iter=1000)),
    ]
)
pls_pipe.fit(X_train, y_train)
pls_pipe.score(X_test, y_test)
0.9230769230769231

A recipe that needs no target works without y: call fit(X) and X is used as given.

unsupervised_recipe = (
    Recipe(data=X_train)
    .add(StepNormalize(s.numeric_features()))
)
transformer = RecipeTransformer(unsupervised_recipe)

Fit on the training data, then apply the stored statistics to the held-out data:

transformer.fit(X_train)
RecipeTransformer
  Recipe (trained)
    Inputs: 30 columns (30 features)
    Steps:
      step_normalize(mean radius, mean texture, mean perimeter, mean area, mean smoothness, mean compactness, mean concavity, mean concave points, mean symmetry, mean fractal dimension, radius error, texture error, perimeter error, area error, smoothness error, compactness error, concavity error, concave points error, symmetry error, fractal dimension error, worst radius, worst texture, worst perimeter, worst area, worst smoothness, worst compactness, worst concavity, worst concave points, worst symmetry, worst fractal dimension)  [trained]
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
result = transformer.transform(X_test)
result
mean radius mean texture mean perimeter mean area mean smoothness mean compactness mean concavity mean concave points mean symmetry mean fractal dimension ... worst radius worst texture worst perimeter worst area worst smoothness worst compactness worst concavity worst concave points worst symmetry worst fractal dimension
512 -0.213708 0.312179 -0.143383 -0.282209 1.027364 0.852955 0.711305 0.839185 1.124014 1.551743 ... 0.019037 0.663188 0.171967 -0.073757 1.085748 0.874025 1.215573 1.368828 1.087833 1.537475
457 -0.267193 1.459508 -0.329165 -0.334369 -0.610325 -1.018477 -0.776008 -0.733260 -0.670696 -0.989010 ... -0.401817 1.416733 -0.476052 -0.434462 -0.157145 -0.964695 -0.657806 -0.841671 -0.714933 -0.880025
439 -0.039177 -0.866683 -0.104508 -0.144038 -1.205783 -0.944291 -0.863249 -0.582816 -0.779028 -0.986092 ... -0.287410 -1.043417 -0.321776 -0.338956 -1.269208 -0.994978 -1.042968 -0.504725 -1.201569 -0.923857
298 0.028383 -0.257847 -0.037807 -0.070237 -2.209040 -1.015518 -0.813834 -0.912040 -0.612918 -0.986092 ... -0.019780 -0.062325 -0.048848 -0.115882 -1.659520 -0.237897 -0.569582 -0.609268 -0.411576 -0.381015
37 -0.317863 -0.197206 -0.390137 -0.373490 -0.471746 -1.302398 -0.802753 -0.513004 -1.219581 -0.581848 ... -0.616330 -0.466304 -0.677141 -0.582836 -1.547878 -1.360418 -1.114908 -0.992848 -1.436988 -1.227871
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
236 2.547820 1.876718 2.510759 2.806644 -0.092096 1.273213 1.354474 1.920627 0.376519 0.069029 ... 3.001789 1.462902 2.901242 3.507021 0.680172 1.051774 1.575528 2.194813 0.326279 0.181495
113 -1.027247 0.232133 -0.961805 -0.899535 1.142847 0.525429 -0.304265 -0.475651 0.423464 2.218672 ... -1.053528 -0.476197 -1.025734 -0.875322 -0.109174 -0.315580 -0.705699 -0.821708 -0.811313 0.377615
527 -0.512099 -1.688976 -0.540318 -0.526920 -0.457311 -0.801048 -0.752319 -0.584104 -0.417920 -0.662113 ... -0.552998 -1.050013 -0.595881 -0.550433 -0.144062 -0.299122 -0.455646 -0.126174 0.337338 -0.428219
76 -0.177113 -2.011586 -0.173256 -0.275272 2.362634 0.020330 -0.253194 0.422889 2.160396 0.553538 ... -0.456977 -2.167963 -0.473991 -0.481191 0.549341 -0.756662 -0.928075 -0.628013 -0.294657 -0.653560
162 1.528785 -0.262698 1.577758 1.541472 1.128412 1.241644 2.065144 2.046856 0.802628 -0.262247 ... 2.127393 0.124000 1.985595 2.292735 0.492648 0.867441 2.074626 1.667524 1.179472 0.488318

143 rows × 30 columns

Cross-validation and tuning

Because the adapter stores the recipe verbatim, it clones cleanly, so it works inside GridSearchCV and any other tool that re-fits across folds:

from sklearn.model_selection import GridSearchCV

search = GridSearchCV(pipe, {"model__C": [0.1, 1.0]}, cv=3)
search.fit(X_train, y_train)
search.best_params_
{'model__C': 1.0}

Tuning step hyperparameters

Step hyperparameters are reachable through scikit-learn’s nested parameter names, so a grid can vary a step’s argument directly. Steps are addressed by their id, never by position, giving keys of the form <pipeline step>__recipe__<step id>__<parameter>: the name you gave the RecipeTransformer in the pipeline, the recipe it wraps, the step, and the step’s parameter. Each step has a default id (StepDropCorr uses "corr") that you can replace with the step’s id= argument. A step’s id and columns are not tunable.

from mlfeatures import StepDropCorr

tuned_recipe = (
    Recipe(data=X_train.assign(target=y_train), target="target")
    .add(StepDropCorr(s.numeric_features(), threshold=0.9))
    .add(StepNormalize(s.numeric_features()))
)
tuned_pipe = Pipeline(
    [
        ("prep", RecipeTransformer(tuned_recipe)),
        ("model", LogisticRegression(max_iter=1000)),
    ]
)

The tunable keys are listed by get_params. Here prep is the pipeline step, corr is the StepDropCorr step’s id, and threshold and method are its parameters:

[k for k in tuned_pipe.get_params() if k.startswith("prep__recipe__")]
['prep__recipe__corr__threshold', 'prep__recipe__corr__method']
grid = {"prep__recipe__corr__threshold": [0.8, 0.95]}
search = GridSearchCV(tuned_pipe, grid, cv=3)
search.fit(X_train, y_train)
search.best_params_
{'prep__recipe__corr__threshold': 0.95}

Feature names and set_output

RecipeTransformer implements get_feature_names_out, so it composes inside a ColumnTransformer and supports the set_output API for choosing the container type returned by transform ("pandas" or "polars"):

rt = RecipeTransformer(tuned_recipe).set_output(transform="pandas")
rt.fit(X_train, y_train).transform(X_test).iloc[:5, :3]
mean texture mean area mean smoothness
512 0.312179 -0.282209 1.027364
457 1.459508 -0.334369 -0.610325
439 -0.866683 -0.144038 -1.205783
298 -0.257847 -0.070237 -2.209040
37 -0.197206 -0.373490 -0.471746