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 creditCreating 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 callsuper().__init__()from your constructor - fit() estimates and stores state; transform() only applies it
- use resolve_selection() to turn the
columnsselector into column names, and the data frame’s ownschemafor dtypes - describe what the step consumed and produced with schema_in() and schema_out()
StepConformanceTestchecks the whole contract; you supply a step and some data- register the step under the
mlfeatures.stepsentry-point group so saved recipes can load it
Setup
The imports are shown because they are the public names a step author needs.
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:
Mode.ONE_TO_ONE: each input column produces exactly one output column, like StepNormalize. keep_original_cols is fixed atFalse.Mode.ONE_TO_MANY: each input column produces one or more output columns, like StepDummy. keep_original_cols is configurable, defaultFalse.Mode.MANY_TO_MANY: a set of input columns produces a new set of output columns, like StepPca. keep_original_cols is configurable, defaultFalse.Mode.REMOVING: input columns are dropped and none are created, like StepDropZeroVariance. keep_original_cols is fixed atFalse.Mode.ADDING: new columns appear with no corresponding input, like StepIntercept. keep_original_cols is fixed atTrue.Mode.ROW_OP: the columns are unchanged, like StepFilter. keep_original_cols is fixed atTrue. Row steps only act while the recipe is fitted and are skipped by transform() on new data.Mode.UNCONSTRAINED: the relationship cannot be declared in advance, like StepMutate. keep_original_cols is fixed atTrue.
For our step, it is one line on the class:
class StepMaxAbs(Step):
mode = Mode.ONE_TO_ONEThe 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 selftransform
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 FalsePutting 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 FalseError 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()))
recipeRecipe (untrained)
Inputs: no roles assigned
Steps:
step_max_abs(select(role='feature', type=NumericType)) [untrained]
fitted = recipe.fit(credit)
fittedRecipe (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| Status | Seniority | Home | Time | Age | Marital | Records | Job | Expenses | Income | Assets | Debt | Amount | Price |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| str | f64 | str | f64 | f64 | str | str | str | f64 | f64 | f64 | f64 | f64 | f64 |
| "good" | 0.191489 | "rent" | 0.833333 | 0.441176 | "married" | "no" | "freelance" | 0.421965 | 0.134515 | 0.0 | 0.0 | 0.177778 | 0.075943 |
| "good" | 0.361702 | "rent" | 0.833333 | 0.852941 | "widow" | "no" | "fixed" | 0.277457 | 0.136601 | 0.0 | 0.0 | 0.222222 | 0.148833 |
| "bad" | 0.212766 | "owner" | 0.5 | 0.676471 | "married" | "yes" | "freelance" | 0.520231 | 0.208551 | 0.015 | 0.0 | 0.444444 | 0.267953 |
| "good" | 0.0 | "rent" | 0.833333 | 0.352941 | "single" | "no" | "fixed" | 0.364162 | 0.189781 | 0.0125 | 0.0 | 0.2 | 0.118941 |
| "good" | 0.0 | "rent" | 0.5 | 0.382353 | "single" | "no" | "fixed" | 0.265896 | 0.111575 | 0.0 | 0.0 | 0.068889 | 0.081688 |
| … | … | … | … | … | … | … | … | … | … | … | … | … | … |
| "bad" | 0.021277 | "rent" | 0.833333 | 0.573529 | "married" | "no" | "fixed" | 0.398844 | 0.095933 | 0.0 | 0.0 | 0.2 | 0.091562 |
| "good" | 0.468085 | "owner" | 0.833333 | 0.676471 | "married" | "no" | "fixed" | 0.346821 | 0.078206 | 0.015 | 0.028037 | 0.211111 | 0.113375 |
| "bad" | 0.0 | "owner" | 0.333333 | 0.544118 | "married" | "no" | "partime" | 0.346821 | 0.093848 | 0.0175 | 0.0 | 0.111111 | 0.086445 |
| "good" | 0.0 | "rent" | 0.666667 | 0.338235 | "single" | "no" | "freelance" | 0.283237 | 0.145985 | 0.0 | 0.0 | 0.122222 | 0.049372 |
| "good" | 0.106383 | "owner" | 0.833333 | 0.470588 | "married" | "no" | "freelance" | 0.346821 | 0.145985 | 0.02 | 0.046729 | 0.3 | 0.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_MANYstep, 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 thepip installthat 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.