Skip to main content

Recipe: specify, fit, transform

A Recipe is a pre-processing pipeline with three phases. You specify it as a sequence of steps, fit it to training data, and transform any data frame with what it learned.

  • Steps operate on data frames, using mlfeatures selectors (or polars selectors) to choose the columns to operate on.
  • mlfeatures extends the selection process with roles.
  • Each step applies to the “output” data of the previous step.
  • mlfeatures fits and transforms the training data, but only transforms test data.
  • mlfeatures handles pre-processing, and plugs in to scikit pipelines for final model fitting.

fit(train)

surprise?
add a guard

2 · Order the steps

handle missing 
values (1–2)

wrangle
(3–5)

model prep
(6–7)

multivariate 
transforms (8) 

1 · Assign
roles

3 · Ensure robust
to new data
new data arrives

4 · Pass to the
scikit-learn pipeline

Setup

The credit data has a categorical target, Status, and a mix of numeric and string features with a few missing values in each. Hold out a test set before anything is estimated.

from sklearn.model_selection import train_test_split

from mlfeatures import Recipe, StepDummy, StepImputeMedian, StepImputeMode, StepNormalize
from mlfeatures import Selectors as s
from mlfeatures.data import credit

credit_train, credit_test = train_test_split(
    credit, train_size=0.75, stratify=credit["Status"], random_state=1
)
credit_train.head()
shape: (5, 14)
StatusSeniorityHomeTimeAgeMaritalRecordsJobExpensesIncomeAssetsDebtAmountPrice
stri64stri64i64strstrstri64i64i64i64i64i64
"good"1"owner"3621"single""no""fixed"351271000008501014
"good"28"owner"3054"married""no""fixed"4523415000012502166
"bad"2"rent"6036"separated""yes""freelance"35null0020002676
"good"12"owner"6038"married""no""fixed"751205000011001172
"bad"0"parents"2421"single""yes""partime"351260011501586

Specifying recipe roles and steps

Start a recipe with Recipe(data=training_data, target="SomeColumn") and chain steps on with .add(), each choosing its columns with a selector. Nothing is computed yet: the recipe is a specification, and every step shows its selector as written.

recipe = (
    Recipe(data=credit_train, target="Status")
    .add(StepImputeMedian(s.numeric_features()))
    .add(StepImputeMode(s.nominal_features()))
    .add(StepDummy(s.nominal_features()))
    .add(StepNormalize(s.numeric_features()))
)
recipe
Recipe (untrained)
  Inputs: 14 columns (1 target)
  Steps:
    step_impute_median(select(role='feature', type=NumericType))                [untrained]
    step_impute_mode(select(role='feature', type=(String, Categorical, Enum)))  [untrained]
    step_dummy(select(role='feature', type=(String, Categorical, Enum)))        [untrained]
    step_normalize(select(role='feature', type=NumericType))                    [untrained]

target= gives Status the target role, and every other column is a feature. That is what keeps Status out of s.nominal_features(), so it is not imputed or turned into indicator columns with the real string features, and it is what lets a scikit-learn pipeline hand the recipe its y later. data= is optional: the recipe only reads its column names, to check role assignments such as target= straight away and to show the columns before fitting. Nothing is estimated from it, and a step’s columns are not checked until the recipe is fitted.

Fitting training data

recipe.fit(training_data) runs the steps in order, and each step estimates what it needs from the data as it goes: the medians, the modes, the levels of each string column, the means and standard deviations. Fitting also transforms the training data frame step by step, so each selector is resolved against the output of the step before it.

fitted = recipe.fit(credit_train)
fitted
Recipe (trained)
  Inputs: 23 columns (22 features, 1 target)
  Steps:
    step_impute_median(Seniority, Time, Age, Expenses, Income, Assets, Debt, Amount, Price)                                                                                                                                                                                  [trained]
    step_impute_mode(Home, Marital, Records, Job)                                                                                                                                                                                                                            [trained]
    step_dummy(Home, Marital, Records, Job → Home_other, Home_owner, Home_parents, Home_priv, Home_rent, Marital_married, Marital_separated, Marital_single, Marital_widow, Records_yes, Job_freelance, Job_others, Job_partime)                                             [trained]
    step_normalize(Seniority, Time, Age, Expenses, Income, Assets, Debt, Amount, Price, Home_other, Home_owner, Home_parents, Home_priv, Home_rent, Marital_married, Marital_separated, Marital_single, Marital_widow, Records_yes, Job_freelance, Job_others, Job_partime)  [trained]

Every step is now [trained] and lists the concrete columns it resolved to. The dummy step produced indicator columns from Home, Marital, Records, and Job, and the normalize step’s numeric_features() selector, resolved after it, picked those up along with the original numerics.

Transforming test data

fitted.transform(data) applies the stored estimates to any data frame that has the training features, with the training dtypes, and re-estimates nothing: the test set is filled with the training medians and modes and scaled by the training means.

result = fitted.transform(credit_test)
result.head()
shape: (5, 23)
StatusSeniorityTimeAgeExpensesIncomeAssetsDebtAmountPriceHome_otherHome_ownerHome_parentsHome_privHome_rentMarital_marriedMarital_separatedMarital_singleMarital_widowRecords_yesJob_freelanceJob_othersJob_partime
strf64f64f64f64f64f64f64f64f64f64f64f64f64f64f64f64f64f64f64f64f64f64
"good"0.2565250.932128-0.8149451.1629172.353534-0.4816962.108562.5602031.250825-0.278202-0.946206-0.467881-0.237931.8938950.623887-0.172001-0.542203-0.122003-0.462644-0.553287-0.193851-0.346977
"bad"-0.355733-0.302985-0.4494760.237705-0.5744920.0505840.3623551.3963031.408383-0.2782021.056536-0.467881-0.23793-0.5278540.623887-0.172001-0.542203-0.122003-0.462644-0.553287-0.193851-0.346977
"good"-0.3557330.932128-1.180413-1.047312-0.625637-0.483297-0.272628-0.021538-0.630322-0.278202-0.9462062.136656-0.23793-0.527854-1.602375-0.1720011.843776-0.122003-0.462644-0.553287-0.193851-0.346977
"good"2.7055590.5204241.560598-1.0473121.0621341.296306-0.2726280.1265950.221128-0.2782021.056536-0.467881-0.23793-0.527854-1.602375-0.172001-0.5422038.194093-0.4626441.806839-0.193851-0.346977
"good"-0.84554-1.538097-1.454514-1.047312-0.651209-0.483297-0.272628-0.296642-0.249954-0.278202-0.9462062.136656-0.23793-0.527854-1.602375-0.1720011.843776-0.122003-0.462644-0.553287-0.1938512.881169

Wrap the recipe in RecipeTransformer to make it the first step of a scikit-learn Pipeline, so the model gets the same guarantee. scikit-learn keeps X and y apart while mlfeatures finds the target by role, so the adapter re-joins y under the target’s name at fit time and hands the model only the 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(credit_train.drop("Status"), credit_train["Status"])
pipe.score(credit_test.drop("Status"), credit_test["Status"])
0.7935368043087971

pipe.fit fits the recipe and then the model on the training split; pipe.score only transforms the test split with the stored estimates before scoring it. Cross-validation, tuning, and feature names are covered in With scikit-learn pipelines.