Skip to main content

Creating a new Step

A step is a class with two jobs: learn something from the training data in fit(), and apply what it learned in transform(). This page builds one from scratch, importing everything from mlfeatures itself (no internal modules), then checks it against the same contract mlfeatures’s own steps pass. A step written this way can live in your own project or in a plugin package.

  • subclass Step, declare a mode, and call super().__init__() from your constructor
  • fit() estimates and stores state; transform() only applies it
  • use resolve_selection() to turn the columns selector into column names, and the data frame’s own schema for dtypes
  • describe what the step consumed and produced with schema_in() and schema_out()
  • StepConformanceTest checks the whole contract; you supply a step and some data
  • register the step under the mlfeatures.steps entry-point group so saved recipes can load it

Setup

The imports are shown because they are the public names a step author needs.

import math

import narwhals.stable.v2 as nw

from mlfeatures import (
    NUMERIC_DTYPES,
    AcceptedDtypes,
    ColSchema,
    Frame,
    Mode,
    Recipe,
    SchemaInfo,
    Selector,
    Step,
    from_json,
)
from mlfeatures import Selectors as s
from mlfeatures.data import credit

The step we will write

StepMaxAbs divides each selected numeric column by its largest absolute value, which puts the column in [-1, 1] and keeps zeros as zeros. The statistic is a single number per column, so there is little to distract from the structure.

Decide the mode

Every step declares a mode, which says how its input columns relate to its output columns. Here each input column becomes exactly one output column, so the mode is Mode.ONE_TO_ONE. The mode also decides which columns the recipe tracks as new and whether keep_original_cols is an argument (it is only for steps that add columns beside their inputs, Mode.ONE_TO_MANY and Mode.MANY_TO_MANY). A step that changes rows rather than columns subclasses RowOp instead, which sets its mode for it.

The available modes are:

For our step, it is one line on the class:

class StepMaxAbs(Step):
    mode = Mode.ONE_TO_ONE

The constructor

The constructor stores its own arguments and then calls super().__init__(), which sets the attributes the framework owns (id, trained, output_role, keep_original_cols). It takes the caller’s id and the name to default to when there is none.

Two rules keep the step usable everywhere:

  • only required arguments are positional; every optional argument is keyword-only
  • each argument is stored unchanged under an attribute of the same name, which is how get_params() and set_params() find it for tuning
    def __init__(self, columns: Selector, *, id: str | None = None) -> None:
        self.columns = columns
        super().__init__(id, "max_abs")

fit

fit() receives the training data frame and a SchemaInfo. It resolves the selector, computes what it needs, stores it, and returns self. The recipe sets trained afterwards, so the step does not need to do it.

resolve_selection() turns the columns selector into column names. The dtypes come from the data frame’s own schema, so nothing private is needed. The recipe has already handled an empty selection by the time fit() runs, so fit() never checks for one.

By convention the learned state lives on _estimates. Narrow its type with a class-level annotation.

    #: Populated by ``fit()``: {column: largest absolute value}.
    _estimates: dict[str, float] | None

    def fit(self, training_data: Frame, info: SchemaInfo) -> "StepMaxAbs":
        names = self.resolve_selection(training_data, info)
        selected = training_data.select(names)
        dtypes = {name: str(dt) for name, dt in selected.schema.items()}

        estimates: dict[str, float] = {}
        for col in selected.columns:
            largest = selected[col].abs().max()
            # An empty or all-null column has no maximum, a column of zeros
            # has nothing to scale by, and a NaN or infinite maximum would
            # turn the column into NaN or zeros
            if largest is None:
                continue
            scale = float(largest)
            if math.isfinite(scale) and scale != 0.0:
                estimates[col] = scale

        self._estimates = estimates
        self._schema_in = ColSchema(columns=selected.columns, dtypes=dtypes)
        return self

transform

transform() applies the stored state to new data and never re-estimates. Write it with narwhals expressions so it works on every backend.

    def transform(self, new_data: Frame) -> Frame:
        if self._estimates is None:
            raise RuntimeError("StepMaxAbs.transform() called before fit()")
        exprs = [
            (nw.col(col) / scale).cast(nw.Float64).alias(col)
            for col, scale in self._estimates.items()
        ]
        return new_data.with_columns(*exprs)

Describing the columns

schema_in() and schema_out() tell the recipe what the step consumed and what it left behind. The recipe uses them to keep its lineage up to date, so later selectors see accurate dtypes. Both are known only after fit().

accepts_dtypes() lists the dtypes the step can work on. The recipe checks the selection against it before fit() and raises a TypeError naming the step and column, so fit() never has to defend itself. NUMERIC_DTYPES is the ready-made set for numeric steps, and ANY_DTYPE is the choice for a step that works on anything. A column is accepted when the exact class of its dtype is in the set, so list concrete classes such as nw.Int64.

produces_sparse says whether the output is sparse. Ours is not.

    def schema_in(self) -> ColSchema:
        if self._schema_in is None:
            raise RuntimeError("StepMaxAbs.schema_in() called before fit()")
        return self._schema_in

    def schema_out(self) -> ColSchema:
        if self._schema_in is None or self._estimates is None:
            raise RuntimeError("StepMaxAbs.schema_out() called before fit()")
        scaled = set(self._estimates)
        dtypes = {
            col: "Float64" if col in scaled else self._schema_in.dtypes[col]
            for col in self._schema_in.columns
        }
        return ColSchema(columns=self._schema_in.columns, dtypes=dtypes)

    def accepts_dtypes(self) -> AcceptedDtypes:
        return set(NUMERIC_DTYPES)

    @property
    def produces_sparse(self) -> bool:
        return False

Putting it together

The pieces above, assembled into one class:

class StepMaxAbs(Step):
    """Scale numeric columns to ``[-1, 1]`` by their largest absolute value.

    Parameters
    ----------
    columns
        Columns to scale. Accepts a single column name, a list of names, a
        mlfeatures selector such as ``Selectors.numeric_features()`` (see
        `Selectors` for the full set), or a narwhals or polars selector
        (``narwhals.selectors.numeric()``, ``polars.selectors.numeric()``).
        Selectors are resolved against the data frame's schema when the recipe is
        fitted, so the same selector works on any backend. Only numeric columns
        are meaningful here.
    id
        Stable step identifier. Defaults to ``"max_abs"``.
    """

    mode = Mode.ONE_TO_ONE

    #: Populated by ``fit()``: {column: largest absolute value}.
    _estimates: dict[str, float] | None

    def __init__(self, columns: Selector, *, id: str | None = None) -> None:
        self.columns = columns
        super().__init__(id, "max_abs")

    def fit(self, training_data: Frame, info: SchemaInfo) -> "StepMaxAbs":
        names = self.resolve_selection(training_data, info)
        selected = training_data.select(names)
        dtypes = {name: str(dt) for name, dt in selected.schema.items()}

        estimates: dict[str, float] = {}
        for col in selected.columns:
            largest = selected[col].abs().max()
            # An empty or all-null column has no maximum, a column of zeros
            # has nothing to scale by, and a NaN or infinite maximum would
            # turn the column into NaN or zeros
            if largest is None:
                continue
            scale = float(largest)
            if math.isfinite(scale) and scale != 0.0:
                estimates[col] = scale

        self._estimates = estimates
        self._schema_in = ColSchema(columns=selected.columns, dtypes=dtypes)
        return self

    def transform(self, new_data: Frame) -> Frame:
        if self._estimates is None:
            raise RuntimeError("StepMaxAbs.transform() called before fit()")
        exprs = [
            (nw.col(col) / scale).cast(nw.Float64).alias(col)
            for col, scale in self._estimates.items()
        ]
        return new_data.with_columns(*exprs)

    def schema_in(self) -> ColSchema:
        if self._schema_in is None:
            raise RuntimeError("StepMaxAbs.schema_in() called before fit()")
        return self._schema_in

    def schema_out(self) -> ColSchema:
        if self._schema_in is None or self._estimates is None:
            raise RuntimeError("StepMaxAbs.schema_out() called before fit()")
        scaled = set(self._estimates)
        dtypes = {
            col: "Float64" if col in scaled else self._schema_in.dtypes[col]
            for col in self._schema_in.columns
        }
        return ColSchema(columns=self._schema_in.columns, dtypes=dtypes)

    def accepts_dtypes(self) -> AcceptedDtypes:
        return set(NUMERIC_DTYPES)

    @property
    def produces_sparse(self) -> bool:
        return False

Error messages follow the house style: lowercase first word, no trailing period, and single quotes around values.

Using it

The step is used like any other. Add it to a recipe, fit, and transform.

recipe = Recipe().add(StepMaxAbs(s.numeric_features()))
recipe
Recipe (untrained)
  Inputs: no roles assigned
  Steps:
    step_max_abs(select(role='feature', type=NumericType))  [untrained]
fitted = recipe.fit(credit)
fitted
Recipe (trained)
  Inputs: 14 columns (14 features)
  Steps:
    step_max_abs(Seniority, Time, Age, Expenses, Income, Assets, Debt, Amount, Price)  [trained]
result = fitted.transform(credit)
result
shape: (4_039, 14)
StatusSeniorityHomeTimeAgeMaritalRecordsJobExpensesIncomeAssetsDebtAmountPrice
strf64strf64f64strstrstrf64f64f64f64f64f64
"good"0.191489"rent"0.8333330.441176"married""no""freelance"0.4219650.1345150.00.00.1777780.075943
"good"0.361702"rent"0.8333330.852941"widow""no""fixed"0.2774570.1366010.00.00.2222220.148833
"bad"0.212766"owner"0.50.676471"married""yes""freelance"0.5202310.2085510.0150.00.4444440.267953
"good"0.0"rent"0.8333330.352941"single""no""fixed"0.3641620.1897810.01250.00.20.118941
"good"0.0"rent"0.50.382353"single""no""fixed"0.2658960.1115750.00.00.0688890.081688
……………………………………
"bad"0.021277"rent"0.8333330.573529"married""no""fixed"0.3988440.0959330.00.00.20.091562
"good"0.468085"owner"0.8333330.676471"married""no""fixed"0.3468210.0782060.0150.0280370.2111110.113375
"bad"0.0"owner"0.3333330.544118"married""no""partime"0.3468210.0938480.01750.00.1111110.086445
"good"0.0"rent"0.6666670.338235"single""no""freelance"0.2832370.1459850.00.00.1222220.049372
"good"0.106383"owner"0.8333330.470588"married""no""freelance"0.3468210.1459850.020.0467290.30.148115

Because the step declared its schemas, the fitted recipe knows its output, and selectors that come later in a recipe resolve against the right dtypes.

Test it against the contract

mlfeatures.testing.StepConformanceTest ships inside the package, so your step is held to the same contract as the built-in ones. Subclass it and supply make_step() and training_data; pytest collects every check.

from mlfeatures.testing import StepConformanceTest


class TestStepMaxAbs(StepConformanceTest):
    training_data = {"a": [1.0, -4.0, 2.0], "b": [10, 20, 30]}

    def make_step(self) -> StepMaxAbs:
        return StepMaxAbs(["a", "b"])

The checks include keyword-only optional arguments, a constructor that delegates to Step.__init__(), 0-row and 1-row transforms, idempotent fit(), a transform() that never re-estimates, pickle and JSON round trips, and identical results on pandas and polars data frames. The suite needs pytest, which mlfeatures does not require at runtime: install the test extra with pip install mlfeatures[test].

A check that genuinely does not apply is opted out through a hook rather than by omission. Override make_empty_step() to return None for a step with no column selector, or set estimates_attr = None for a step that estimates nothing.

Make saved recipes loadable

Loading a saved recipe only accepts classes from mlfeatures, from registered packages, and from classes you pass as trusted. During development, name your step when you load:

text = fitted.to_json()
loaded = from_json(text, trusted=[StepMaxAbs])
loaded
/tmp/ipykernel_6454/1704624079.py:1: UserWarning: recipe names class(es) ['__main__.StepMaxAbs'] that 'from_dict' refuses by default; register a step from their package(s) under the 'mlfeatures.steps' entry-point group, or pass a class from them as 'trusted' when loading
  text = fitted.to_json()
Recipe (trained)
  Inputs: 14 columns (14 features)
  Steps:
    step_max_abs(Seniority, Time, Age, Expenses, Income, Assets, Debt, Amount, Price)  [trained]

The warning above is expected here: StepMaxAbs is defined in this notebook rather than in a registered package, so loading it needs trusted. Registering the step, as shown next, removes the need for both.

For a package, register the step under the mlfeatures.steps entry-point group in its pyproject.toml, so anyone who installs the package can load recipes that use it:

[project.entry-points."mlfeatures.steps"]
step_max_abs = "mypackage.steps:StepMaxAbs"

Optional pieces

  • New columns. A step that adds columns, such as a Mode.ONE_TO_MANY step, also implements output_parents() to say which input columns each new column descends from. The recipe uses it for lineage and to catch name collisions before the step runs.
  • Heavy dependencies. Return requirement strings from required_pkgs(), such as ["scikit-learn>=1.3"], and import the package inside the method that uses it. A missing package then raises an error that names the step and the pip install that fixes it.
  • Several statistics. When a step has more than one piece of learned state, bundle it into a single frozen dataclass stored on _estimates.
  • Fit-only artifacts. Override minimize() to drop anything transform() does not need.

Adding a step to mlfeatures itself

A step contributed to mlfeatures has two extra requirements. It needs a tests/test_step_x_infrastructure.py that subclasses StepConformanceTest, as above. It also needs a matching step_* method on MlfNamespace in mlfeatures/polars.py, so the step is reachable through the df.mlf accessor. A parity test fails if either is missing.