# Creating a new Step

A step is a class with two jobs: learn something from the training data in [fit()](../../reference/Step.fit.md#mlfeatures.Step.fit), and apply what it learned in [transform()](../../reference/Step.transform.md#mlfeatures.Step.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.

> **Note: Key points**
>
> - subclass [Step](../../reference/Step.md#mlfeatures.Step), declare a `mode`, and call `super().__init__()` from your constructor
> - [fit()](../../reference/Step.fit.md#mlfeatures.Step.fit) estimates and stores state; [transform()](../../reference/Step.transform.md#mlfeatures.Step.transform) only applies it
> - use [resolve_selection()](../../reference/Step.resolve_selection.md#mlfeatures.Step.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()](../../reference/Step.schema_in.md#mlfeatures.Step.schema_in) and [schema_out()](../../reference/Step.schema_out.md#mlfeatures.Step.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.


``` python
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](../../reference/Step.keep_original_cols.md#mlfeatures.Step.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](../../reference/RowOp.md#mlfeatures.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](../../reference/StepNormalize.md#mlfeatures.StepNormalize). [keep_original_cols](../../reference/Step.keep_original_cols.md#mlfeatures.Step.keep_original_cols) is fixed at `False`.
- `Mode.ONE_TO_MANY`: each input column produces one or more output columns, like [StepDummy](../../reference/StepDummy.md#mlfeatures.StepDummy). [keep_original_cols](../../reference/Step.keep_original_cols.md#mlfeatures.Step.keep_original_cols) is configurable, default `False`.
- `Mode.MANY_TO_MANY`: a set of input columns produces a new set of output columns, like [StepPca](../../reference/StepPca.md#mlfeatures.StepPca). [keep_original_cols](../../reference/Step.keep_original_cols.md#mlfeatures.Step.keep_original_cols) is configurable, default `False`.
- `Mode.REMOVING`: input columns are dropped and none are created, like [StepDropZeroVariance](../../reference/StepDropZeroVariance.md#mlfeatures.StepDropZeroVariance). [keep_original_cols](../../reference/Step.keep_original_cols.md#mlfeatures.Step.keep_original_cols) is fixed at `False`.
- `Mode.ADDING`: new columns appear with no corresponding input, like [StepIntercept](../../reference/StepIntercept.md#mlfeatures.StepIntercept). [keep_original_cols](../../reference/Step.keep_original_cols.md#mlfeatures.Step.keep_original_cols) is fixed at `True`.
- `Mode.ROW_OP`: the columns are unchanged, like [StepFilter](../../reference/StepFilter.md#mlfeatures.StepFilter). [keep_original_cols](../../reference/Step.keep_original_cols.md#mlfeatures.Step.keep_original_cols) is fixed at `True`. Row steps only act while the recipe is fitted and are skipped by [transform()](../../reference/Step.transform.md#mlfeatures.Step.transform) on new data.
- `Mode.UNCONSTRAINED`: the relationship cannot be declared in advance, like [StepMutate](../../reference/StepMutate.md#mlfeatures.StepMutate). [keep_original_cols](../../reference/Step.keep_original_cols.md#mlfeatures.Step.keep_original_cols) is fixed at `True`.

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

``` python
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](../../reference/Step.keep_original_cols.md#mlfeatures.Step.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()](../../reference/Step.get_params.md#mlfeatures.Step.get_params) and [set_params()](../../reference/Step.set_params.md#mlfeatures.Step.set_params) find it for tuning

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


# fit

[fit()](../../reference/Step.fit.md#mlfeatures.Step.fit) receives the training data frame and a [SchemaInfo](../../reference/SchemaInfo.md#mlfeatures.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()](../../reference/Step.resolve_selection.md#mlfeatures.Step.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()](../../reference/Step.fit.md#mlfeatures.Step.fit) runs, so [fit()](../../reference/Step.fit.md#mlfeatures.Step.fit) never checks for one.

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

``` python
    #: 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()](../../reference/Step.transform.md#mlfeatures.Step.transform) applies the stored state to new data and never re-estimates. Write it with narwhals expressions so it works on every backend.

``` python
    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()](../../reference/Step.schema_in.md#mlfeatures.Step.schema_in) and [schema_out()](../../reference/Step.schema_out.md#mlfeatures.Step.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()](../../reference/Step.fit.md#mlfeatures.Step.fit).

[accepts_dtypes()](../../reference/Step.accepts_dtypes.md#mlfeatures.Step.accepts_dtypes) lists the dtypes the step can work on. The recipe checks the selection against it before [fit()](../../reference/Step.fit.md#mlfeatures.Step.fit) and raises a `TypeError` naming the step and column, so [fit()](../../reference/Step.fit.md#mlfeatures.Step.fit) never has to defend itself. [NUMERIC_DTYPES](../../reference/NUMERIC_DTYPES.md#mlfeatures.NUMERIC_DTYPES) is the ready-made set for numeric steps, and [ANY_DTYPE](../../reference/ANY_DTYPE.md#mlfeatures.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](../../reference/Step.produces_sparse.md#mlfeatures.Step.produces_sparse) says whether the output is sparse. Ours is not.

``` python
    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:


``` python
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.


``` python
recipe = Recipe().add(StepMaxAbs(s.numeric_features()))
recipe
```


    Recipe (untrained)
      Inputs: no roles assigned
      Steps:
        step_max_abs(select(role='feature', type=NumericType))  [untrained]


``` python
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]


``` python
result = fitted.transform(credit)
result
```


shape: (4_039, 14)

| 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.

``` python
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()](../../reference/Step.fit.md#mlfeatures.Step.fit), a [transform()](../../reference/Step.transform.md#mlfeatures.Step.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:


``` python
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:

``` toml
[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()](../../reference/Step.output_parents.md#mlfeatures.Step.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()](../../reference/Step.required_pkgs.md#mlfeatures.Step.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()](../../reference/minimize.md#mlfeatures.minimize) to drop anything [transform()](../../reference/Step.transform.md#mlfeatures.Step.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.
