mlfeatures separates feature engineering into three phases:
Specify: declare the Recipe, a sequence of pre-processing steps.
Fit: estimate any required statistics from a training dataset.
Transform: apply the fitted recipe identically to new data.
It’s designed to support common Python modeling workflows:
DataFrame-agnostic. Works with pandas or polars (thanks to narwhals).
Column selectors. Use mlfeatures selectors (or polars and narwhals selectors) to target columns for pre-processing.
Steps for all kinds of workflows. Many built-in steps to support pre-processing data for a wide range of models. Organized into a four stages, eight steps workflow.
Polars .mlf accessor: Run steps directly on a polars DataFrame.
scikit-learn support: Recipes plug into scikit-learn pipelines.
Installing
Install mlfeatures using your package manager of choice:
pip install mlfeatures
A few steps need an optional package, such as scipy for StepOrderNorm (used below). Install the matching extra, for example pip install "mlfeatures[scipy]". The README lists them all.
Quickstart
Here is a quick snippet that normalizes numeric columns and then runs PCA on a Polars DataFrame (using the .mlf accessor).
import mlfeatures.polars # registers the `df.mlf` accessorfrom mlfeatures import Selectors as s# fit each step on `df` and apply it right there: center and scale the# numeric features, then project them onto 4 principal componentsresult = ( df.mlf.step_normalize(s.numeric_features()) .mlf.step_pca(s.numeric_features(), num_comp=4))
While the code above runs on a single DataFrame, modelling workflows often split data into test and training sets. Use a Recipe to fit on training data, and transform test data. This is shown below.
from mlfeatures import Recipe, StepNormalize, StepPca# a recipe fits the same steps on training data and applies them unchanged# to any other data frame; `RecipeTransformer` drops one into a scikit-learn# `Pipeline`recipe = ( Recipe() .add(StepNormalize(s.numeric_features())) .add(StepPca(s.numeric_features(), num_comp=4)))fitted = recipe.fit(df_train)result = fitted.transform(df_test)
Setting up examples
We’ll use two examples to illustrate using mlfeatures with polars and scikit-learn. Both examples use the dry beans data packaged with mlfeatures.
from mlfeatures.data import beansbeans.head()
shape: (5, 17)
area
perimeter
major_axis_length
minor_axis_length
aspect_ratio
eccentricity
convex_area
equiv_diameter
extent
solidity
roundness
compactness
shape_factor_1
shape_factor_2
shape_factor_3
shape_factor_4
class
i64
f64
f64
f64
f64
f64
i64
f64
f64
f64
f64
f64
f64
f64
f64
f64
str
28395
610.291
208.178117
173.888747
1.197191
0.549812
28715
190.141097
0.763923
0.988856
0.958027
0.913358
0.007332
0.003147
0.834222
0.998724
"seker"
28734
638.018
200.524796
182.734419
1.097356
0.411785
29172
191.27275
0.783968
0.984986
0.887034
0.953861
0.006979
0.003564
0.909851
0.99843
"seker"
29380
624.11
212.82613
175.931143
1.209713
0.562727
29690
193.410904
0.778113
0.989559
0.947849
0.908774
0.007244
0.003048
0.825871
0.999066
"seker"
30008
645.884
210.557999
182.516516
1.153638
0.498616
30724
195.467062
0.782681
0.976696
0.903936
0.928329
0.007017
0.003215
0.861794
0.994199
"seker"
30140
620.134
201.847882
190.279279
1.060798
0.33368
30417
195.896503
0.773098
0.990893
0.984877
0.970516
0.006697
0.003665
0.9419
0.999166
"seker"
We’ll also use a small helper to draw a scatterplot matrix:
import seaborn as snssns.set_theme(palette="colorblind")def plot_pairs(frame):"""Scatterplot matrix, one color per level of class column.""" sns.pairplot( frame.to_pandas(), hue="class", hue_order=sorted(frame["class"].unique()), plot_kws={"s": 8, "alpha": 0.5, "linewidth": 0}, diag_kws={"alpha": 0.3}, height=1.8, )
Example: polars beans PCA
Importing mlfeatures.polars registers a mlf namespace on polars DataFrames. Each df.mlf.step_*() call fits that step on the data frame, applies it, and returns a new data frame.
For example, the code below drops constant columns, rank-normalizes and then normalizes each measurement, then projects onto 4 principal components.
import mlfeatures.polars # registers the `df.mlf` accessorfrom mlfeatures import Selectors as sbean_pcs = ( beans.mlf.step_drop_zero_variance(s.numeric_features()) .mlf.step_order_norm(s.numeric_features()) .mlf.step_normalize(s.numeric_features()) .mlf.step_pca(s.numeric_features(), num_comp=4))bean_pcs.head()
shape: (5, 5)
class
PC1
PC2
PC3
PC4
str
f64
f64
f64
f64
"seker"
-6.133307
-0.694849
0.876906
0.075372
"seker"
-6.788823
-2.075319
2.889575
-0.737496
"seker"
-5.813864
-0.866828
0.366874
0.007208
"seker"
-5.113239
-1.012677
3.447783
-1.434654
"seker"
-8.399019
-3.946318
0.98431
0.470248
Notice that the output has reduced the data to 4 components. class is not numeric, so the s.numeric_features() selector didn’t try to normalize it.
plot_pairs(bean_pcs)
Each mlf call estimated its step on beans and applied it right there, which is useful for exploring data. However, modelling usually involves fitting pre-processing on a training set, and then using that to transform a test set. To handle this workflow, mlfeatures provides a Recipe class for specifying steps, fitting, and transforming.
Example: sklearn Recipe PCA
While the previous example used a single DataFrame, this example splits it into training and test frames. It uses the Recipe class to specify the pre-processing, fit to the training data frame, and then transform the test frame. Then, it shows how the Recipe can be used in a scikit-learn pipeline.
Split data and specify Recipe
from sklearn.model_selection import train_test_splitfrom mlfeatures import Recipe, StepDropZeroVariance, StepNormalize, StepOrderNorm, StepPca# split training and test ---------------------bean_train, bean_validation = train_test_split( beans, train_size=0.75, stratify=beans["class"], random_state=1601)# specify recipe -----------------------------recipe = ( Recipe(data=bean_train, target="class") .add(StepDropZeroVariance(s.numeric_features())) .add(StepOrderNorm(s.numeric_features())) .add(StepNormalize(s.numeric_features())) .add(StepPca(s.numeric_features(), num_comp=4)))
In order to use the Recipe object in a scikit-learn pipeline, wrap it in RecipeTransformer. For example, the code below uses our pre-processing steps as part of fitting a logistic regression.
pipe.fit() fits the recipe and the model on the training split
pipe.score() only pre-processes the test split using the stored estimates before scoring.
Available steps
The steps above are a few of the built-in ones. Each does one job, and they fall into the four stages, eight steps workflow. Here is a representative subset of each kind of step:
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.
Note that the output above is how scikit-learn represents a Pipeline, with the top box being the Recipe pre-processing, and the bottom box (LogisticRegression) being the scikit model fitting piece.