You have probably written this code before: a pile of preprocessing that imputes here, scales there, one-hot encodes a hand-typed list of columns, and quietly breaks the day someone adds a column to the source table.

We present mlfeatures, a Python library for data preprocessing and feature engineering. You specify what you want to happen as a recipe, which is a declared sequence of steps that you fit once and apply anywhere. There is a lot to cover, so this is the first of three blog posts. The second and third will cover how mlfeatures works with scikit-learn and with polars. This one covers the recipe itself and the two ideas that make it different from a scikit-learn pipeline: selectors and roles.

Join us live

We will talk about mlfeatures next Tuesday 12pm ET / 9am PT (December 8) at the Data Science Lab. Register here.

You can install it with:

pip install mlfeatures

The problem mlfeatures solves#

Feature engineering is often the most impactful part of a machine learning pipeline, and it can often get quite complicated as we add more and more operations. Additionally we have to be careful that we do everything correctly to avoid things like data leakage.

Traditionally in scikit-learn, you would use a ColumnTransformer(), combined with a series of transformers or pipelines to specify which features should be handled by which transformations.

In scikit-learn that tends to look like this:

numeric_plain = ["sqft", "lot_size", "year_built"]
numeric_geo = ["geo_lat", "geo_lon", "geo_elevation"]
categorical = ["neighborhood", "style", "roof"]

pre = ColumnTransformer([
    ("plain", plain_pipe, numeric_plain),
    ("pca", pca_branch, numeric_geo + categorical),
])

Spelling out all the columns isn’t that bad when we don’t have many of them, but it is a chore to keep up to date, especially if our data set has a lot of columns.

Three literal lists, each a copy of the schema that nothing checks. If someone adds garage_sqft to the table, it is silently not imputed and not scaled. And because ColumnTransformer branches run in parallel, you cannot scale the PCA output together with the plain numerics without nesting yet another pipeline.

In mlfeatures we take a different approach. You declare a recipe as a sequence of steps, and each step says what kind of columns it applies to rather than which columns it applies to today.

Specify, fit, transform#

A recipe has three phases:

  1. Specify: declare the steps. No data is touched.
  2. Fit: estimate what each step needs (medians, levels, means, PCA loadings) from the training data.
  3. Transform: apply those stored estimates to any data frame, training or new.

We’ll use the credit data that ships with mlfeatures. It has a categorical target, Status, and a mix of numeric and string features with some missing values.

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)
Status Seniority Home Time Age Marital Records Job Expenses Income Assets Debt Amount Price
str i64 str i64 i64 str str str i64 i64 i64 i64 i64 i64
"good" 1 "owner" 36 21 "single" "no" "fixed" 35 127 10000 0 850 1014
"good" 28 "owner" 30 54 "married" "no" "fixed" 45 234 15000 0 1250 2166
"bad" 2 "rent" 60 36 "separated" "yes" "freelance" 35 null 0 0 2000 2676
"good" 12 "owner" 60 38 "married" "no" "fixed" 75 120 5000 0 1100 1172
"bad" 0 "parents" 24 21 "single" "yes" "partime" 35 126 0 0 1150 1586

Specifying a recipe means starting with Recipe() and chaining steps on with .add():

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]

Nothing has been computed. The recipe is just a description, and it prints each step’s selector exactly as written, tagged [untrained]. The data= argument is optional and only used to check column names and show you what’s there; nothing is estimated from it.

We can read what this recipe does in almost plain English. We specify a recipe on the credit_train with the target being "Status", everything else being features. Then we impute missing values of the numeric features with medians, impute missing values of the nominal features by their modes, create dummy variables from the nominal features, and finally normalize all the numeric features.

There are a couple of things to take note of here. The only time we specified something as a string was when we specified the target, everything else uses selectors, which we will get back to later in the post. One of the reasons why we do this is as an act of protection from previous steps that might remove a feature. Using selectors makes it so we don’t have to manually track each feature. Also, a recipe is a linear sequence of steps, not a graph of interconnected processes. This is not because we couldn’t support a graph. We just believe it isn’t needed, and it would complicate the design of mlfeatures.

Calling .fit() on the training data does the estimating. It hands back a new object, a FittedRecipe, and leaves the recipe itself alone, so one specification can be fitted to many data sets (every fold of a cross-validation, for example).

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]

Now every step is [trained] and lists the concrete columns it resolved to. Notice the last step. We wrote s.numeric_features() twice, but the normalize step operates on more columns than the imputation step did, because the dummy step in between created a bunch of new indicator columns and the selector picked them up. Selectors are evaluated on the data the step sees in the sequence, not the data the recipe sees at the beginning.

Finally, .transform() applies the stored estimates to any data frame. It never re-estimates anything, so the test set is filled with the training medians and scaled by the training means:

fitted.transform(credit_test).head()
shape: (5, 23)
Status 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
str f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64
"good" 0.256525 0.932128 -0.814945 1.162917 2.353534 -0.481696 2.10856 2.560203 1.250825 -0.278202 -0.946206 -0.467881 -0.23793 1.893895 0.623887 -0.172001 -0.542203 -0.122003 -0.462644 -0.553287 -0.193851 -0.346977
"bad" -0.355733 -0.302985 -0.449476 0.237705 -0.574492 0.050584 0.362355 1.396303 1.408383 -0.278202 1.056536 -0.467881 -0.23793 -0.527854 0.623887 -0.172001 -0.542203 -0.122003 -0.462644 -0.553287 -0.193851 -0.346977
"good" -0.355733 0.932128 -1.180413 -1.047312 -0.625637 -0.483297 -0.272628 -0.021538 -0.630322 -0.278202 -0.946206 2.136656 -0.23793 -0.527854 -1.602375 -0.172001 1.843776 -0.122003 -0.462644 -0.553287 -0.193851 -0.346977
"good" 2.705559 0.520424 1.560598 -1.047312 1.062134 1.296306 -0.272628 0.126595 0.221128 -0.278202 1.056536 -0.467881 -0.23793 -0.527854 -1.602375 -0.172001 -0.542203 8.194093 -0.462644 1.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.946206 2.136656 -0.23793 -0.527854 -1.602375 -0.172001 1.843776 -0.122003 -0.462644 -0.553287 -0.193851 2.881169

A quick note on data frames: the examples in this series use polars because that is how the bundled datasets are stored, but mlfeatures works with pandas too. Under the hood every step is written once against narwhals, a compatibility layer for data frame libraries, so a recipe returns the same kind of data frame you gave it: polars in, polars out; pandas in, pandas out. The third post in this series looks at this in more detail.

That is the whole lifecycle, and it is the part that keeps test data from leaking into your preprocessing.

A chain of transformers that keep their names#

If you have used a scikit-learn Pipeline, a recipe will look familiar. It is a chain, and each step is applied to the output of the one before it. The step that fits the median imputation produces a data frame, the mode imputation is fitted on that, the dummy step on the result of that, and so on. .transform() replays the same chain in the same order.

The difference is what travels along the chain. By default a scikit-learn transformer hands the next one a NumPy array (you can ask for data frames with set_output), so by the second step the column names and dtypes are at best a convention. And you have to keep features of different types separate, since a NumPy array can’t mix numeric and non-numeric data. In a recipe, what passes from step to step is always a named, typed data frame, along with the roles and the record of which step produced each column. That is what lets a step’s columns be a description resolved against the previous step’s output.

We can watch it happen on the Ames housing data by fitting the chain one step at a time. After the dummy step, the string columns have been replaced by indicator columns.

from mlfeatures import StepDummy, StepNormalize
from mlfeatures.data import ames_mini

base = Recipe(data=ames_mini, target="Sale_Price")

dummied = base.add(StepDummy(s.col("Bldg_Type", "Street")))
dummied.fit(ames_mini).transform(ames_mini)
shape: (2_930, 14)
Neighborhood Exterior_1st Gr_Liv_Area Year_Built Garage_Cars Garage_Area Latitude Longitude Sale_Price Bldg_Type_OneFam Bldg_Type_Twnhs Bldg_Type_TwnhsE Bldg_Type_TwoFmCon Street_Pave
str str i64 i64 i64 i64 f64 f64 i64 i8 i8 i8 i8 i8
"North_Ames" "BrkFace" 1656 1960 2 528 42.054035 -93.619754 215000 1 0 0 0 1
"North_Ames" "VinylSd" 896 1961 1 730 42.053014 -93.619756 105000 1 0 0 0 1
"North_Ames" "Wd Sdng" 1329 1958 1 312 42.052659 -93.619387 172000 1 0 0 0 1
"North_Ames" "BrkFace" 2110 1968 2 522 42.051245 -93.61732 244000 1 0 0 0 1
"Gilbert" "VinylSd" 1629 1997 2 482 42.060899 -93.638933 189900 1 0 0 0 1
… … … … … … … … … … … … … …
"Mitchell" "HdBoard" 1003 1984 2 588 41.988964 -93.604776 142500 1 0 0 0 1
"Mitchell" "HdBoard" 902 1983 2 484 41.988314 -93.60268 131000 1 0 0 0 1
"Mitchell" "HdBoard" 970 1992 0 0 41.98651 -93.606847 132000 1 0 0 0 1
"Mitchell" "HdBoard" 1389 1974 2 418 41.990921 -93.60019 170000 1 0 0 0 1
"Mitchell" "HdBoard" 2000 1993 3 650 41.989265 -93.599996 188000 1 0 0 0 1

Now add a normalize step that asks for s.numeric_features(). We wrote no column names, but the step is fitted on the dummy step’s output, so the selector can see the new indicator columns.

chained = dummied.add(StepNormalize(s.numeric_features()))
chained.fit(ames_mini).transform(ames_mini)
shape: (2_930, 14)
Neighborhood Exterior_1st Gr_Liv_Area Year_Built Garage_Cars Garage_Area Latitude Longitude Sale_Price Bldg_Type_OneFam Bldg_Type_Twnhs Bldg_Type_TwnhsE Bldg_Type_TwoFmCon Street_Pave
str str f64 f64 f64 f64 f64 f64 i64 f64 f64 f64 f64 f64
"North_Ames" "BrkFace" 0.309212 -0.375473 0.307157 0.257179 1.062069 0.900517 215000 0.456263 -0.188917 -0.293875 -0.147005 0.064117
"North_Ames" "VinylSd" -1.194223 -0.34241 -1.006668 1.195897 1.00661 0.900439 105000 0.456263 -0.188917 -0.293875 -0.147005 0.064117
"North_Ames" "Wd Sdng" -0.337661 -0.441599 -1.006668 -0.746598 0.987327 0.914786 172000 0.456263 -0.188917 -0.293875 -0.147005 0.064117
"North_Ames" "BrkFace" 1.207317 -0.11097 0.307157 0.229296 0.910521 0.995227 244000 0.456263 -0.188917 -0.293875 -0.147005 0.064117
"Gilbert" "VinylSd" 0.255801 0.847855 0.307157 0.043412 1.434908 0.15424 189900 0.456263 -0.188917 -0.293875 -0.147005 0.064117
… … … … … … … … … … … … … …
"Mitchell" "HdBoard" -0.982555 0.418037 0.307157 0.536006 -2.472464 1.483328 142500 0.456263 -0.188917 -0.293875 -0.147005 0.064117
"Mitchell" "HdBoard" -1.182354 0.384974 0.307157 0.052706 -2.50777 1.564886 131000 0.456263 -0.188917 -0.293875 -0.147005 0.064117
"Mitchell" "HdBoard" -1.047836 0.682541 -2.320492 -2.196499 -2.60576 1.402743 132000 0.456263 -0.188917 -0.293875 -0.147005 0.064117
"Mitchell" "HdBoard" -0.218968 0.087408 0.307157 -0.254004 -2.366163 1.661775 170000 0.456263 -0.188917 -0.293875 -0.147005 0.064117
"Mitchell" "HdBoard" 0.989715 0.715604 1.620981 0.824127 -2.456114 1.669324 188000 0.456263 -0.188917 -0.293875 -0.147005 0.064117

The normalize step lists the indicators (Bldg_Type_OneFam, Street_Pave, and so on) next to the original numeric columns, even though none of them existed when we wrote the recipe.

Selectors: say what, not which#

Selectors are descriptions of columns, and they live in the Selectors namespace, which the mlfeatures docs import as s. You can select by name, by type, by role (more on that next), or by which step created a column:

s.col("Income", "Assets")        # by name
s.starts_with("Garage")          # by name pattern
s.numeric()                      # by type
s.has_role("geo")                # by role
s.has_source(step_type=StepDummy)  # by the step that produced it

They compose with &, |, ~, and -, so “every numeric feature except the ones in the geo group” is one expression. We’ll use that shortly.

You may have noticed we have been using s.numeric_features() and not s.numeric(). That is deliberate and it brings us to roles.

Roles: what a column is for#

In scikit-learn, “which column is the target” is something you track yourself, by splitting X and y before anything else happens. In a recipe, it is a property of the column in the data frame, called a role.

The two roles you will use constantly are "feature" (a column used as model input) and "target" (the column being predicted). When we wrote Recipe(data=credit_train, target="Status"), Status got the target role and every other column became a feature by default.

This is why s.numeric_features() exists. It is s.numeric() restricted to the feature role, so it leaves out a numeric target. A plain type selector knows nothing about roles, so it would happily normalize the thing you’re trying to predict, which is almost never what you want.

recipe = (
    Recipe(data=ames_mini, target="Sale_Price")
    .add(StepNormalize(s.numeric_features()))  # leaves Sale_Price alone
    .add(StepNormalize(s.numeric()))  # includes Sale_Price
)
recipe.fit(ames_mini)
Recipe (trained)
  Inputs: 11 columns (10 features, 1 target)
  Steps:
    step_normalize(Gr_Liv_Area, Year_Built, Garage_Cars, Garage_Area, Latitude, Longitude)              [trained]
    step_normalize(Gr_Liv_Area, Year_Built, Garage_Cars, Garage_Area, Latitude, Longitude, Sale_Price)  [trained]

You can name the features yourself with features=. A role is just a string, though, so you can invent your own. Here we tag the coordinates geo, and then normalize every numeric feature except those.

import polars as pl

recipe = (
    Recipe(data=ames_mini, target="Sale_Price")
    .set_roles(geo=["Latitude", "Longitude"])
    .add(StepNormalize(s.numeric_features() - s.has_role("geo")))
)
fitted = recipe.fit(ames_mini)
fitted
Recipe (trained)
  Inputs: 11 columns (10 features, 2 geos, 1 target)
  Steps:
    step_normalize(Gr_Liv_Area, Year_Built, Garage_Cars, Garage_Area)  [trained]

Roles can also change part way through a recipe. add_role(), update_role(), and remove_role() take effect at the point they are written: steps after them see the new role, steps before them do not. Here the dummy columns get an indicator role so the normalization that follows can skip them:

from mlfeatures import StepDummy

recipe = (
    Recipe(data=ames_mini, target="Sale_Price")
    .add(StepDummy(s.nominal_features()))
    .add_role(s.has_source(step_type=StepDummy), role="indicator")
    .add(StepNormalize(s.numeric_features() - s.has_role("indicator")))
)
fitted = recipe.fit(ames_mini)
fitted.summary().filter(pl.col("roles").str.contains("indicator")).head()
shape: (5, 5)
name dtype roles source sparse
str str str str bool
"Neighborhood_Blueste" "int" "feature, indicator" "dummy" false
"Neighborhood_Briardale" "int" "feature, indicator" "dummy" false
"Neighborhood_Brookside" "int" "feature, indicator" "dummy" false
"Neighborhood_Clear_Creek" "int" "feature, indicator" "dummy" false
"Neighborhood_College_Creek" "int" "feature, indicator" "dummy" false

That has_source() selector is the last one worth a closer look.

Selecting by where a column came from#

A fitted recipe tracks the lineage of every column: which step produced it and which columns it was derived from. A selector can ask for it.

s.has_source(step_type=StepDummy) means “the columns that StepDummy produced”. Every step also has an id (it defaults to the step’s short name, like "dummy", and a second step of the same type becomes "dummy_2"), so you can be more specific with s.has_source("dummy_2"), or name steps yourself with id=.

The lineage is also queryable after the fact. If a model flags a PCA component as important, you can ask what it was built from:

from mlfeatures import StepPca

recipe = Recipe(data=ames_mini, target="Sale_Price").add(
    StepPca(s.col("Garage_Cars", "Garage_Area", "Gr_Liv_Area"), num_comp=2)
)
fitted = recipe.fit(ames_mini)
fitted.lineage.ancestors("PC1")
{'Garage_Area', 'Garage_Cars', 'Gr_Liv_Area'}

Putting it together#

Back to the scenario from the start: encode the categories, compress the encoded columns together with the geographic columns using PCA, then normalize everything numeric, including the new components. Here it is as a recipe on the Ames housing data (we only encode two of the categorical columns to keep the output readable). The first normalize standardizes the PCA inputs, which matters because latitude and longitude are on a very different scale from the 0/1 indicators:

from mlfeatures import StepPca

ames_train, ames_test = train_test_split(ames_mini, train_size=0.8, random_state=502)

compress = s.has_source(step_type=StepDummy) | s.col("Latitude", "Longitude")

recipe = (
    Recipe(data=ames_train, target="Sale_Price")
    .add(StepDummy(s.col("Bldg_Type", "Street")))
    .add(StepNormalize(compress))
    .add(StepPca(compress, num_comp=3))
    .add(StepNormalize(s.numeric_features()))
)
fitted = recipe.fit(ames_train)
fitted
Recipe (trained)
  Inputs: 10 columns (9 features, 1 target)
  Steps:
    step_dummy(Bldg_Type, Street → Bldg_Type_OneFam, Bldg_Type_Twnhs, Bldg_Type_TwnhsE, Bldg_Type_TwoFmCon, Street_Pave)                 [trained]
    step_normalize(Latitude, Longitude, Bldg_Type_OneFam, Bldg_Type_Twnhs, Bldg_Type_TwnhsE, Bldg_Type_TwoFmCon, Street_Pave)            [trained]
    step_pca(Latitude, Longitude, Bldg_Type_OneFam, Bldg_Type_Twnhs, Bldg_Type_TwnhsE, Bldg_Type_TwoFmCon, Street_Pave → PC1, PC2, PC3)  [trained]
    step_normalize(Gr_Liv_Area, Year_Built, Garage_Cars, Garage_Area, PC1, PC2, PC3)                                                     [trained]
fitted.transform(ames_test).head()
shape: (5, 10)
Neighborhood Exterior_1st Gr_Liv_Area Year_Built Garage_Cars Garage_Area Sale_Price PC1 PC2 PC3
str str f64 f64 f64 f64 i64 f64 f64 f64
"Old_Town" "Wd Sdng" 0.076542 -2.522462 -2.340051 -2.217032 148000 0.346995 -0.348378 0.421788
"Bloomington_Heights" "VinylSd" 0.187633 1.047201 1.645233 0.739286 226500 -2.551539 2.128751 -0.750674
"Clear_Creek" "Wd Sdng" 1.74089 -2.092781 0.316805 -0.527708 240000 0.506054 0.170912 -0.309718
"Brookside" "Wd Sdng" -0.394081 -1.563942 0.316805 -0.152302 100000 0.387593 -0.297109 0.216065
"Timberland" "VinylSd" 0.268427 1.014149 1.645233 1.574563 270000 0.527388 -0.779915 -0.646561

A few things to notice. There is one selector, compress, that unions “whatever the dummy step made” with two named columns, and the living area, year built, and garage columns flow past the PCA untouched (they are only normalized, at the end). There are no nested branches to reconcile, just a list of steps in the order they run. And if a rare neighborhood goes missing from a particular training split, nothing in the recipe needs editing, because nothing in it names a dummy column.

If you want to know what each step did, fitted.summary() gives you the column-by-column accounting, and the recipe prints as a readable record of the whole pipeline.

What’s next#

A recipe is a specification you fit once and apply anywhere, which also means you can save a fitted recipe to JSON or YAML and load it back in production without the training data (see to_json() and from_json()).

In the next two posts, we’ll look at how recipes fit into the rest of your stack: In the meantime, the mlfeatures documentation has the full list of steps and six worked examples ported from Tidy Modeling with R. and tuning, then with polars and the df.mlf accessor. In the meantime, the mlfeatures documentation has the full list of steps and six worked examples ported from Tidy Modeling with R.

mlfeatures is new and there are plenty of great things to come. This is mainly focused on additional steps that will be useful to users. This initial release provides a solid foundation and a set of steps that should cover a lot of basic cases.

A note on where this comes from: mlfeatures is a Python port of the R package recipes, part of tidymodels. If you have used recipes, most of this will feel familiar. We have been working on the R package for quite a while and think that it is worth porting to our Python users as well. We know that 1:1 ports are usually not great, so we took the best of recipes, added some cool things, and made sure that it was as pythonic as possible.

Two differences are deliberate: mlfeatures follows scikit-learn’s vocabulary (“feature” and “target” rather than “predictor” and “outcome”), and role changes such as add_role() take effect at the point you write them, whereas in R they are applied up front no matter where they appear.