Skip to main content

Introduction

mlfeatures separates feature engineering into three phases:

  1. Specify: declare the Recipe, a sequence of pre-processing steps.
  2. Fit: estimate any required statistics from a training dataset.
  3. Transform: apply the fitted recipe identically to new data.

It’s designed to support common Python modeling workflows:

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` accessor
from 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 components
result = (
    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 beans

beans.head()
shape: (5, 17)
areaperimetermajor_axis_lengthminor_axis_lengthaspect_ratioeccentricityconvex_areaequiv_diameterextentsolidityroundnesscompactnessshape_factor_1shape_factor_2shape_factor_3shape_factor_4class
i64f64f64f64f64f64i64f64f64f64f64f64f64f64f64f64str
28395610.291208.178117173.8887471.1971910.54981228715190.1410970.7639230.9888560.9580270.9133580.0073320.0031470.8342220.998724"seker"
28734638.018200.524796182.7344191.0973560.41178529172191.272750.7839680.9849860.8870340.9538610.0069790.0035640.9098510.99843"seker"
29380624.11212.82613175.9311431.2097130.56272729690193.4109040.7781130.9895590.9478490.9087740.0072440.0030480.8258710.999066"seker"
30008645.884210.557999182.5165161.1536380.49861630724195.4670620.7826810.9766960.9039360.9283290.0070170.0032150.8617940.994199"seker"
30140620.134201.847882190.2792791.0607980.3336830417195.8965030.7730980.9908930.9848770.9705160.0066970.0036650.94190.999166"seker"

We’ll also use a small helper to draw a scatterplot matrix:

import seaborn as sns

sns.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` accessor
from mlfeatures import Selectors as s

bean_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)
classPC1PC2PC3PC4
strf64f64f64f64
"seker"-6.133307-0.6948490.8769060.075372
"seker"-6.788823-2.0753192.889575-0.737496
"seker"-5.813864-0.8668280.3668740.007208
"seker"-5.113239-1.0126773.447783-1.434654
"seker"-8.399019-3.9463180.984310.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_split
from 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))
)
fitted = recipe.fit(bean_train)
scores = fitted.transform(bean_validation)
scores.head()
shape: (5, 5)
classPC1PC2PC3PC4
strf64f64f64f64
"dermason"2.0239141.285164-0.103483-0.641545
"sira"0.279919-0.549593-0.829391-1.548377
"sira"-0.2165781.1813720.598133-0.172482
"horoz"-2.6581121.694809-0.077129-0.7787
"dermason"1.5015911.937009-0.7195751.138855

Pass to a scikit-learn pipeline

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.

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(bean_train.drop("class"), bean_train["class"])
pipe.score(bean_validation.drop("class"), bean_validation["class"])
0.8939171319424037

Note two key pieces:

  • 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:

Stage Step What it does
Handle missing values StepImputeMedian fill missing numeric values with the training median
StepUnknown recode missing categorical values to an explicit "unknown" level
Wrangle StepDummy expand a categorical column into k-1 indicator columns
StepOneHot expand into all k indicator columns
Model prep StepNormalize center and scale each column to mean 0, sd 1
StepOrderNorm rank-normalize each column onto a standard normal
StepPolynomial polynomial basis expansion of a numeric column
Multivariate transforms StepPca project numeric columns onto principal components

In addition, you’ll likely drop columns throughout using StepDropZeroVariance and StepDropCorr. More general transforming and dropping can be done with StepMutate and StepFilter, respectively.

Use with polars (.mlf)

Import mlfeatures.polars to use the polars.DataFrame.mlf accessor. Each method of the accessor returns a new DataFrame.

beans.mlf.step_pca(s.numeric_features(), num_comp=2).head()
shape: (5, 3)
classPC1PC2
strf64f64
"seker"-35149.92373822.086841
"seker"-34586.32189-58.586565
"seker"-33764.02629138.995373
"seker"-32586.564121-239.179424
"seker"-32712.80608271.43979

For more details, see With polars extension (.mlf).

Use in a scikit-learn pipeline

The RecipeTransformer class wraps a Recipe for use in a scikit-learn Pipeline:

from mlfeatures import Recipe, RecipeTransformer

recipe = (
    Recipe(data=bean_train, target="class")
    .add(StepDropZeroVariance(s.numeric_features()))
)

Pipeline(
    [
        ("recipe", RecipeTransformer(recipe)),
        ("model", LogisticRegression(max_iter=1000)),
    ]
)
Pipeline(steps=[('recipe',
                 RecipeTransformer(recipe=Recipe (untrained)
  Inputs: 17 columns (1 target)
  Steps:
    step_drop_zero_variance(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.

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.

For more details on using with cross-validation, tuning, and more, see With scikit-learn pipelines.

Next steps