---------------------------------------------------------------------- This is the API documentation for the mlfeatures library. ---------------------------------------------------------------------- ## Recipes Build a recipe, then fit and apply it. The Recipe class and its methods are flattened into this section so each method appears on the reference index. Recipe(steps: 'list[Step] | None' = None, *, data: 'DataFrame | None' = None, target: 'str | list[str] | None' = None, features: 'str | list[str] | None' = None, case_weights: 'str | list[str] | None' = None) A declarative, untrained pipeline of feature-engineering steps. A recipe is specified in two parts: the columns' roles are declared first (the ``target``, ``features`` and ``case_weights`` arguments, plus `set_roles()`), then steps are added with `add()`. Specifying a recipe never touches data; nothing is estimated until `fit()`, which returns a `FittedRecipe`, and `FittedRecipe.transform()` applies it to new data. ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepDropCorr, StepNormalize from mlfeatures import Selectors as s from mlfeatures.data import credit ``` Each `add()` returns a new recipe, so steps chain into a pipeline: ```{python} recipe = ( Recipe(data=credit, target="Status") .add(StepDropCorr(s.numeric_features(), threshold=0.9)) .add(StepNormalize(s.numeric_features())) ) ``` The untrained recipe shows the roles it carries and its steps with their selectors unresolved: ```{python} recipe ``` `set_roles()` declares roles on the input columns, so it can be applied anywhere among the steps, including after them, with the same result (once a role operation is written before the first step, `set_roles()` keeps the order it was written in with it, see `set_roles()`): ```{python} late = ( Recipe(data=credit) .add(StepDropCorr(s.numeric_features(), threshold=0.9)) .add(StepNormalize(s.numeric_features())) .set_roles(target="Status") ) late ``` To change a role part way through the pipeline instead, use `add_role()`, `update_role()` or `remove_role()`, which take effect from where they are written. Parameters ---------- steps Steps to start from, equivalent to chaining `add()` once per step. Default ``None`` (no steps). data A data frame whose column names are used to check role assignments as soon as they are made, and which backs `summary()` before fitting. Nothing is estimated from it and it is never modified, so a small sample with the right columns is enough. Default ``None``. target Column name or list of names to give the ``"target"`` role. Default ``None``. features Column name or list of names to give the ``"feature"`` role. With the default, ``None``, every column that is not a target or a case weight becomes a feature when the recipe is fitted, including columns given a custom role with `set_roles()`. Pass names to choose the features yourself and keep such columns out. case_weights Column name or list of names to give the ``"case_weights"`` role. Default ``None``. add(self, *steps: 'Step') -> "'Recipe'" Return a new recipe with ``steps`` added after the existing ones. The recipe itself is never changed, so a recipe can be extended in several directions from a common starting point. Steps run in the order they were added. Step ids are kept unique within the recipe. A step that did not get an explicit ``id`` and whose default collides with an earlier step's is added under a suffixed id instead (``"dummy"``, then ``"dummy_2"``), so the two are addressable separately. Passing an ``id`` that a step already in the recipe uses raises ``ValueError``. Parameters ---------- *steps The steps to add, in order. Examples -------- Each ``add()`` returns a new recipe, so steps chain into a pipeline without mutating the original: ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize, StepDummy from mlfeatures import Selectors as s ``` ```{python} recipe = ( Recipe() .add(StepNormalize(s.numeric_features())) .add(StepDummy(s.nominal_features())) ) recipe ``` Adding the same kind of step twice keeps the ids distinct: ```{python} twice = recipe.add(StepNormalize(s.integer_features())) [step.id for step in twice.steps] ``` fit(self, data: 'DataFrame') -> "'FittedRecipe'" Fit each step in order on the training data. Each step is fitted on the output of the step before it, so a later step sees the columns as the earlier ones left them, and its selector is resolved against those columns. Steps that only act on training samples, such as row filters, are applied here, so later steps are fitted on the filtered rows, but they are skipped by `FittedRecipe.transform()`. Every call estimates everything from scratch: the recipe is not changed, it can be fitted again on other data, and each `FittedRecipe` is independent of the recipe and of every other fit. Returning a separate trained object keeps the untrained specification reusable (for example inside cross-validation, where it is fitted once per fold) and makes the object that holds the statistics the one you save and apply to new data. Missing values are handled by the individual steps, not by the recipe. The training data is not kept, so to get the transformed training data call `FittedRecipe.transform()` on it; there is no ``fit_transform()``. Note that ``transform()`` skips row filters, so it can return more rows than the steps were fitted on. To see which columns each step added or removed, use `FittedRecipe.summary()`. When no ``features`` were declared, every column that is not a target or a case weight is given the ``"feature"`` role (see `Recipe`). Parameters ---------- data The training data frame. Raises ------ StepError If a step fails while fitting or while transforming the training data during the fit; the error names the step and the columns it was working on. ValueError If a step would produce a column name that already exists, or a role operation (`add_role()`, `update_role()`, `remove_role()`, or `set_roles()` written after one) fails: its columns cannot be selected, a column lacks the role it is asked to give up, the result would hold incompatible roles, or it is positioned after a step the recipe does not have. ImportError If a step needs an optional dependency that is not installed. Examples -------- ``fit()`` estimates each step's statistics on the training data and returns a `FittedRecipe` with the selectors resolved to concrete columns: ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize, StepDummy from mlfeatures import Selectors as s from mlfeatures.data import credit credit = credit.drop_nulls() ``` ```{python} recipe = ( Recipe(data=credit, target="Status") .add(StepNormalize(s.numeric_features())) .add(StepDummy(s.nominal_features())) ) fitted = recipe.fit(credit) fitted ``` set_roles(self, *, target: 'str | list[str] | None' = None, feature: 'str | list[str] | None' = None, case_weights: 'str | list[str] | None' = None, **custom: 'str | list[str]') -> "'Recipe'" Return a new recipe with the given role assignments added. Standard roles have dedicated keyword arguments; arbitrary custom roles may be passed as additional keywords. Each value is a column name or a list of names. Assignments are *added* to any roles the recipe already carries, so a column may end up with several roles at once; incompatible combinations (e.g. target + feature on one column) are rejected. When the recipe was built with a prototype ``data`` frame, every name is checked against it; without a prototype there is nothing to check against, so any name is accepted and typos surface later, when the recipe is fitted. Roles are what let a step say "all numeric features" without also picking up the target or case weights: selectors such as ``Selectors.numeric_features()`` only match columns carrying the ``feature`` role. Declare ``feature`` explicitly to keep other columns, such as an ID, out of those selections. A custom role marks columns for your own selectors, or for `update_role_requirements`. Roles apply to the columns of the input data, whatever the call's position among the steps. Columns that steps create get their roles from the step that creates them. ``set_roles()`` only adds roles; to add, change, or remove one part way through the pipeline, use `add_role`, `update_role` or `remove_role`. Next to those written before the first step, which also act on the input columns, it keeps the order it was written in, so ``update_role("x", new_role="id").set_roles(group="x")`` leaves ``x`` with both roles, while the same two calls the other way round leave it with ``"id"`` only. A custom role can be selected in a step with ``Selectors.has_role()``. The ``roles`` property returns a copy of the roles the recipe starts from: what the constructor and ``set_roles()`` declared, with any role operation written before the first step applied (default features are not shown). Changing the copy does not change the recipe; `summary()` shows the same roles per column. Parameters ---------- target Column(s) to assign the ``"target"`` role. Default ``None``. feature Column(s) to assign the ``"feature"`` role. Default ``None``. case_weights Column(s) to assign the ``"case_weights"`` role. Default ``None``. **custom Any further keywords assign arbitrary custom roles, the keyword being the role name (e.g. ``group="city"``). The constructor's plural ``features=`` is rejected here rather than silently becoming a custom role. Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import Recipe from mlfeatures.data import credit ``` Assigning roles returns a new recipe, leaving the original untouched: ```{python} recipe = Recipe(data=credit).set_roles( target="Status", feature=["Age", "Income", "Home"] ) recipe ``` Custom roles are just extra keywords, and stack with the roles a column already has: ```{python} recipe.set_roles(group="Home").roles.of("Home") ``` add_role(self, columns: 'Selector', *, role: 'str') -> "'Recipe'" Return a new recipe with a role added at this point in the chain. Unlike `set_roles()`, which declares roles on the input columns whatever its position, a role operation takes effect where it is written: steps added after it see the new role, steps added before it do not. It can also reach columns that earlier steps created. The columns are resolved when the recipe is fitted, against the columns as the steps before it left them. A selection matching nothing changes nothing. Adding a role a column already has is harmless; an incompatible one (``"target"`` on a feature) raises when the recipe is fitted. Wherever the call is written, a column that is only a feature by default (see `Recipe`) and is made the ``"target"`` or ``"case_weights"`` is taken out of the features instead of raising or keeping both roles, like `set_roles()`. A feature role you declared yourself is never taken away, so it still conflicts with ``"target"``. Adding the ``"feature"`` role never changes which other columns are features. Parameters ---------- columns Columns to give the role to. 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 as the steps before this one left it, when the recipe is fitted. role The role to add. Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize from mlfeatures import Selectors as s from mlfeatures.data import credit credit = credit.drop_nulls() ``` Give ``Seniority`` a ``"group"`` role after the normalization, so the step before it is unaffected: ```{python} recipe = ( Recipe(data=credit, target="Status") .add(StepNormalize(s.numeric_features())) .add_role(s.starts_with("Senior"), role="group") ) recipe ``` Fitting applies the role, which the summary then shows: ```{python} fitted = recipe.fit(credit) ``` ```{python} fitted.summary() ``` update_role(self, columns: 'Selector', *, new_role: 'str', old_role: 'str | None' = None) -> "'Recipe'" Return a new recipe with a role changed at this point in the chain. Takes effect where it is written (see `add_role()`). With ``old_role`` only that role is swapped for ``new_role`` and the column's other roles stay; without it, all of a column's roles are replaced by ``new_role``. Parameters ---------- columns Columns to change the role of. 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 as the steps before this one left it, when the recipe is fitted. new_role The role the columns end up with. old_role The role to replace. Every selected column must carry it, or fitting raises ``ValueError``. Default ``None`` (replace all roles). Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize from mlfeatures import Selectors as s from mlfeatures.data import credit credit = credit.drop_nulls() ``` Normalize every numeric feature, then swap the ``"feature"`` role of ``Seniority`` for ``"id"``, so steps added after this call no longer select it: ```{python} recipe = ( Recipe(data=credit, target="Status") .add(StepNormalize(s.numeric_features())) .update_role(s.starts_with("Senior"), new_role="id", old_role="feature") ) recipe ``` Fitting applies the change, which the summary then shows: ```{python} fitted = recipe.fit(credit) ``` ```{python} fitted.summary() ``` remove_role(self, columns: 'Selector', *, role: 'str') -> "'Recipe'" Return a new recipe with a role removed at this point in the chain. Takes effect where it is written (see `add_role()`). Every selected column must carry the role, or fitting raises ``ValueError``. A column left with no role is kept, but role selectors no longer match it. Parameters ---------- columns Columns to remove the role from. 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 as the steps before this one left it, when the recipe is fitted. role The role to remove. Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize from mlfeatures import Selectors as s from mlfeatures.data import credit credit = credit.drop_nulls() ``` ```{python} recipe = ( Recipe(data=credit, target="Status") .add(StepNormalize(s.numeric_features())) .remove_role(s.starts_with("Senior"), role="feature") ) recipe ``` Fitting applies the change, which the summary then shows: ```{python} fitted = recipe.fit(credit) ``` ```{python} fitted.summary() ``` update_role_requirements(self, role: 'str | FeaturesSelector', *, transform_required: 'bool') -> "'Recipe'" Return a new recipe overriding whether columns are required at transform. By default every column the recipe was fitted on must be present in the data given to `FittedRecipe.transform()`, except the target and case weights. That includes columns that no step uses, such as an ID column with a custom role, which is rarely what you want: transforming without it raises. Mark it as not required, or drop it from the data before fitting. The requirement of every column is recorded in the ``transform_required`` mapping of `FittedRecipe.schema`. The ``feature`` and ``target`` roles are fixed: features are always required at transform and targets never are. A column that holds a custom role *and* the ``feature`` role stays required, so declare ``features`` explicitly when a column carries a custom role (see `Recipe`). Parameters ---------- role A role name (e.g. ``"id"``), or a selector such as ``Selectors.starts_with("id_")`` resolved against the training data frame when the recipe is fitted. Passing ``"feature"`` or ``"target"`` raises ``ValueError``. A selector that happens to match a feature or target column leaves that column unchanged. transform_required ``True`` to require the columns at transform, ``False`` to allow them to be absent. When several overrides match a column, the last one wins. Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize from mlfeatures import Selectors as s from mlfeatures.data import credit credit = credit.drop_nulls() ``` Give ``Seniority`` an ``"id"`` role, relax its requirement, and fit: ```{python} recipe = ( Recipe( data=credit, target="Status", features=["Age", "Income", "Home"], ) .set_roles(id="Seniority") .update_role_requirements("id", transform_required=False) .add(StepNormalize(s.numeric_features())) ) fitted = recipe.fit(credit) ``` New data without the ID column now transforms: ```{python} fitted.transform(credit.drop("Seniority").head(5)) ``` summary(self) -> 'DataFrame' The input columns, before any step runs, as a tidy data frame. One row per column, with its ``name``, ``dtype``, ``roles`` (a column with several roles lists them all in one cell), ``source`` (always ``"original"`` before fitting) and whether it is ``sparse``. Requires data: construct the recipe with ``Recipe(data=...)``, or fit it and use `FittedRecipe.summary()` for the columns the recipe produces. Use it to check that the roles you assigned landed on the columns you meant before fitting; it cannot show what the steps will add or remove. Role operations written before the first step are reflected; later ones take effect at fit time and appear in `FittedRecipe.summary()`. Raises ------ ValueError If the recipe was constructed without ``data``. Examples -------- The pre-fit summary describes the input columns and their roles before any step has run, so ``Home`` is still a single ``str`` column with source ``"original"``: ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize, StepDummy from mlfeatures import Selectors as s from mlfeatures.data import credit ``` ```{python} recipe = ( Recipe(data=credit, target="Status") .add(StepNormalize(s.numeric_features())) .add(StepDummy(s.nominal_features())) ) ``` ```{python} recipe.summary() ``` ## Steps: numeric features Rescale, expand, or derive new numeric columns. StepNormalize(columns: 'Selector', *, id: 'str | None' = None) Center and scale numeric columns to zero mean and unit variance. Each selected numeric column ``x`` is replaced in place by ``(x - mean) / std``, using the column's mean and standard deviation. To scale onto a fixed interval instead, see `StepRange`; to reshape a skewed distribution, see `StepOrderNorm`. Constant (zero-variance) columns among the selection cannot be scaled to unit variance; they are dropped from the normalization (with a warning) and pass through ``transform`` untouched. You can get rid of these warnings by adding a `StepDropZeroVariance` before this step. See [Normalization](https://feaz-book.com/numeric-normalization) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to normalize. 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 ``"normalize"``; a second step of this type in the same recipe becomes ``"normalize_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- Each selected column is replaced in place by its centered, unit-variance values: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepNormalize from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame({"x": [1.0, 2.0, 3.0, 4.0]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepNormalize(s.numeric_features())) recipe ``` `fit()` learns each column's mean and standard deviation: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` applies them in place: ```{python} fitted.transform(df) ``` StepOrderNorm(columns: 'Selector', *, id: 'str | None' = None) Normalize numeric columns onto a standard normal distribution by rank. Each selected numeric column's training values are ranked (ties averaged) and mapped to normal quantiles, producing a lookup table between the original values and their normal-quantile scores. Every selected column is replaced in place by its score using that table. New values falling outside the training range are extrapolated using the slope of the nearest boundary segment rather than clamped. Unlike `StepNormalize`, which only recenters and rescales, this reshapes the column's whole distribution. A column with fewer than 2 distinct training values cannot be mapped onto a spread of normal quantiles; it is dropped from the normalization (with a warning) and passes through ``transform`` untouched. Missing values pass through as missing. See [Percentile Scaling](https://feaz-book.com/numeric-percentile) in *Feature Engineering A to Z* for the closely related rank-based scaling; it is not a perfect match, since it maps ranks onto [0, 1] rather than onto normal quantiles. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to normalize. 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 ``"order_norm"``; a second step of this type in the same recipe becomes ``"order_norm_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- Each selected column is replaced in place by its normal-quantile score: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepOrderNorm from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame({"x": [1.0, 2.0, 4.0, 8.0, 16.0]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepOrderNorm(s.numeric_features())) recipe ``` `fit()` learns each column's rank-to-normal-quantile lookup table: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` applies it in place, turning the right-skewed input into a symmetric, standard-normal-shaped output: ```{python} fitted.transform(df) ``` StepRange(columns: 'Selector', *, min: 'float' = 0.0, max: 'float' = 1.0, clipping: 'bool' = True, id: 'str | None' = None) Scale numeric columns to a fixed range. Each selected numeric column ``x`` is replaced in place by ``(x - low) / (high - low) * (max - min) + min``, where ``low`` and ``high`` are the column's smallest and largest values in the training data. On the training data itself the result therefore spans exactly ``min`` to ``max``. To center and scale to zero mean and unit variance instead, see `StepNormalize`. New values falling outside the training bounds would land outside the target range; by default (``clipping=True``) they are clamped back into the range. Constant columns (zero variance) among the selection have a zero range. They are dropped from the rescaling (with a warning) and pass through ``transform`` untouched. You can get rid of these warnings by adding a `StepDropZeroVariance` before this step. A column containing an infinite value yields ``NaN`` with a warning. See [Range Scaling](https://feaz-book.com/numeric-range) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to rescale. 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. min Lower end of the target range. Defaults to ``0.0``. max Upper end of the target range. Defaults to ``1.0``, and must be greater than ``min``. clipping Whether values outside the training bounds are clamped into ``[min, max]`` at transform time. Defaults to ``True``. id Stable step identifier. Defaults to ``"range"``; a second step of this type in the same recipe becomes ``"range_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- Each selected column is replaced in place by its rescaled values: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepRange from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame({"x": [1.0, 2.0, 3.0, 5.0]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepRange(s.numeric_features())) recipe ``` `fit()` learns each column's smallest and largest value: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` applies them in place: ```{python} fitted.transform(df) ``` ``min`` and ``max`` set the target range: ```{python} Recipe().add(StepRange(s.numeric_features(), min=-1.0, max=1.0)).fit( df ).transform(df) ``` New data can fall outside the training bounds: ```{python} new_df = pd.DataFrame({"x": [0.0, 9.0]}) new_df ``` With the default ``clipping=True`` those values are clamped into ``[min, max]``: ```{python} Recipe().add(StepRange(s.numeric_features(), clipping=True)).fit( df ).transform(new_df) ``` With ``clipping=False`` they extrapolate past the target range instead: ```{python} Recipe().add(StepRange(s.numeric_features(), clipping=False)).fit( df ).transform(new_df) ``` StepLog(columns: 'Selector', *, base: 'float' = 2.718281828459045, offset: 'float' = 0.0, signed: 'bool' = False, id: 'str | None' = None) Take the logarithm of numeric columns. Each selected column ``x`` is replaced by ``log(x + offset) / log(base)``. For a transform that handles skew without any domain restriction, see `StepOrderNorm`. A value equal to ``-offset`` becomes ``-inf`` and anything smaller becomes ``NaN``. These pass through with a warning naming the columns, at both fit and transform time. A positive ``offset`` brings zeros into the domain. ``signed=True`` suits columns that span zero. It computes ``sign(x) * log(|x|)`` with ``|x| < 1`` flattened to ``0``, so every real value is valid and the result is continuous through the origin, but flat between ``-1`` and ``1``. It does not use ``offset``, so passing both is an error. See [Logarithms](https://feaz-book.com/numeric-logarithms) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to log-transform. 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. base Base of the logarithm; must be positive and not ``1``. Defaults to ``math.e`` (the natural logarithm). offset Added to every value before the logarithm. Defaults to ``0.0``. Cannot be combined with ``signed``. signed Whether to use the signed formula described above instead of the plain logarithm. Defaults to ``False``. id Stable step identifier. Defaults to ``"log"``; a second step of this type in the same recipe becomes ``"log_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- Each selected column is replaced by its logarithm: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepLog from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame({"x": [1.0, 10.0, 100.0, 1000.0]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepLog(s.numeric_features())) recipe ``` There is nothing to estimate, so `fit()` only resolves the selection: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` takes the natural logarithm: ```{python} fitted.transform(df) ``` ``base`` changes the logarithm's base, here to the base-10 logarithm: ```{python} Recipe().add(StepLog(s.numeric_features(), base=10)).fit(df).transform(df) ``` Zeros are outside the logarithm's domain: ```{python} counts = pd.DataFrame({"x": [0.0, 1.0, 3.0, 7.0]}) counts ``` ``offset`` shifts every value up first, which brings them back in: ```{python} Recipe().add(StepLog(s.numeric_features(), offset=1.0)).fit( counts ).transform(counts) ``` A column spanning zero has negatives too: ```{python} spread = pd.DataFrame({"x": [-100.0, -1.0, 0.0, 1.0, 100.0]}) spread ``` ``signed`` logs each side separately and flattens the middle: ```{python} Recipe().add(StepLog(s.numeric_features(), base=10, signed=True)).fit( spread ).transform(spread) ``` StepPolynomial(columns: 'Selector', *, degree: 'int' = 2, keep_original_cols: 'bool' = False, role: 'str | None' = 'feature', id: 'str | None' = None) -> 'None' Replace numeric columns with their orthogonal polynomial expansion. Each selected numeric column ``x`` is replaced by up to ``degree`` orthogonal polynomial columns ``{x}_1``, ``{x}_2``, ..., ``{x}_degree``. The orthogonal basis is a centering mean plus a QR transform matrix. For a more local, flexible fit, see `StepSplineNatural`. The effective degree per column is capped at ``n_unique_non_null - 1``: a column with ``k`` unique values can support at most ``k - 1`` orthogonal polynomial terms. Constant (or all-null) columns get an effective degree of ``0``; `transform()` leaves those columns untouched and emits a warning. You can get rid of these warnings by adding a `StepDropZeroVariance` before this step. See [Polynomial Expansion](https://feaz-book.com/numeric-polynomial) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to expand. 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. degree Maximum polynomial degree. Must be a positive integer. Default ``2``. Each column's effective degree is the smaller of ``degree`` and ``n_unique_non_null - 1``. keep_original_cols If ``True``, the source columns are kept alongside their polynomial terms instead of being dropped. Default ``False``. role Role assigned to the new polynomial columns (see `Roles`). Default ``"feature"``. id Stable step identifier. Defaults to ``"polynomial"``; a second step of this type in the same recipe becomes ``"polynomial_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- Each selected column is replaced in place by its orthogonal polynomial terms ``{x}_1 ... {x}_degree``: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepPolynomial from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame({"x": [1.0, 2.0, 3.0, 4.0]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepPolynomial(s.numeric_features(), degree=2)) recipe ``` `fit()` learns the orthogonal basis for each column: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` replaces the column with its polynomial terms: ```{python} fitted.transform(df) ``` A higher ``degree`` produces more terms: ```{python} recipe = Recipe().add(StepPolynomial(s.numeric_features(), degree=3)) fitted = recipe.fit(df) fitted.transform(df) ``` ``keep_original_cols`` keeps the source column alongside its terms: ```{python} recipe = Recipe().add( StepPolynomial(s.numeric_features(), degree=2, keep_original_cols=True) ) fitted = recipe.fit(df) fitted.transform(df) ``` StepSplineNatural(columns: 'Selector', *, deg_free: 'int' = 10, complete_set: 'bool' = False, knots: 'Sequence[float] | None' = None, keep_original_cols: 'bool' = False, role: 'str | None' = 'feature', id: 'str | None' = None) -> 'None' Replace numeric columns with a natural cubic spline basis expansion. Each selected numeric column ``x`` is replaced by ``deg_free`` natural cubic spline basis columns ``{x}_1``, ``{x}_2``, ..., ``{x}_{deg_free}``. A natural spline is a piecewise cubic polynomial constrained to be linear beyond its boundary knots, which avoids the wild swings an ordinary polynomial or unconstrained cubic spline can show near the edges of the data. For a basis that keeps a model monotonic in ``x``, see `StepSplineMonotone`; for a lower-degree global fit, see `StepPolynomial`. Interior knots are placed at quantiles of each column's own training values (or at the caller-supplied `knots`, shared across every selected column). A column with fewer than 2 distinct training values cannot support a boundary at all; `transform()` leaves such a column untouched and emits a `UserWarning`. New data outside the fit-time boundary is extrapolated linearly, not as a wild polynomial continuation: this is what "natural" means for this basis. See [Splines](https://feaz-book.com/numeric-splines) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to expand. 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. deg_free Number of output basis columns per (non-degenerate) selected column. Must be an integer >= 2. The columns include the constant basis column when `complete_set` is ``True``, which leaves one fewer interior knot. Default ``10``. Ignored when `knots` is given. complete_set Whether to keep the constant column of the complete natural spline basis; when ``False`` it is dropped. Default ``False``. knots Explicit interior knot locations, shared across every selected column, instead of the default quantile placement. Each column's knots must lie strictly inside that column's own training boundary. Default ``None`` (quantile placement). keep_original_cols If ``True``, the source columns are kept alongside their basis columns instead of being dropped. Default ``False``. role Role assigned to the new basis columns (see `Roles`). Default ``"feature"``. id Stable step identifier. Defaults to ``"spline_natural"``; a second step of this type in the same recipe becomes ``"spline_natural_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- Each selected column is replaced in place by its natural-spline basis columns ``{x}_1 ... {x}_deg_free``: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepSplineNatural from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame({"x": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepSplineNatural(s.numeric_features(), deg_free=3)) recipe ``` `fit()` places the interior knots at quantiles of the training data: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` replaces the column with its basis columns: ```{python} fitted.transform(df) ``` A higher ``deg_free`` produces more, more flexible basis columns: ```{python} recipe = Recipe().add(StepSplineNatural(s.numeric_features(), deg_free=4)) fitted = recipe.fit(df) fitted.transform(df) ``` ``keep_original_cols`` keeps the source column alongside its basis columns: ```{python} recipe = Recipe().add( StepSplineNatural(s.numeric_features(), deg_free=3, keep_original_cols=True) ) fitted = recipe.fit(df) fitted.transform(df) ``` StepSplineMonotone(columns: 'Selector', *, deg_free: 'int' = 10, degree: 'int' = 3, complete_set: 'bool' = True, knots: 'Sequence[float] | None' = None, keep_original_cols: 'bool' = False, role: 'str | None' = 'feature', id: 'str | None' = None) -> 'None' Replace numeric columns with a monotone (I-spline) basis expansion. Each selected numeric column ``x`` is replaced by ``deg_free`` I-spline basis columns ``{x}_1``, ``{x}_2``, ..., ``{x}_{deg_free}``. Every basis column is non-negative and non-decreasing in ``x``; fit with a procedure that keeps its coefficients non-negative (e.g. non-negative least squares), the resulting model is monotonic in ``x``. For an unconstrained flexible fit, see `StepSplineNatural`. Interior knots are placed at quantiles of each column's own training values (or at the caller-supplied `knots`, shared across every selected column). A column with fewer than 2 distinct training values cannot support a boundary at all; `transform()` leaves such a column untouched and emits a `UserWarning`. New data outside the fit-time boundary continues the local polynomial piece and can leave ``[0, 1]`` or lose monotonicity: the shape guarantee only holds within the training range. See [Splines](https://feaz-book.com/numeric-splines) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to expand. 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. deg_free Number of output basis columns per (non-degenerate) selected column. Must be an integer at least ``degree`` (plus 1 if `complete_set`). Default ``10``. Ignored when `knots` is given. degree Degree of the underlying M-spline; the I-spline's pieces have degree ``degree + 1``. Must be a non-negative integer. Default ``3``. complete_set Whether to keep the first column of the complete I-spline basis; when ``False`` it is dropped. Keeping it adds one to the minimum ``deg_free``. Default ``True``. knots Explicit interior knot locations, shared across every selected column, instead of the default quantile placement. Each column's knots must lie strictly inside that column's own training boundary. Default ``None`` (quantile placement). keep_original_cols If ``True``, the source columns are kept alongside their basis columns instead of being dropped. Default ``False``. role Role assigned to the new basis columns (see `Roles`). Default ``"feature"``. id Stable step identifier. Defaults to ``"spline_monotone"``; a second step of this type in the same recipe becomes ``"spline_monotone_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- Each selected column is replaced in place by its monotone-spline basis columns ``{x}_1 ... {x}_deg_free``, each rising from 0 to 1: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepSplineMonotone from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame({"x": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepSplineMonotone(s.numeric_features(), deg_free=4)) recipe ``` `fit()` places the interior knots at quantiles of the training data: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` replaces the column with its basis columns: ```{python} fitted.transform(df) ``` A higher ``deg_free`` produces more, more flexible basis columns: ```{python} recipe = Recipe().add(StepSplineMonotone(s.numeric_features(), deg_free=6)) fitted = recipe.fit(df) fitted.transform(df) ``` ``keep_original_cols`` keeps the source column alongside its basis columns: ```{python} recipe = Recipe().add( StepSplineMonotone(s.numeric_features(), deg_free=4, keep_original_cols=True) ) fitted = recipe.fit(df) fitted.transform(df) ``` StepClassDistance(columns: 'Selector', target: 'str', *, metric: 'Metric' = 'euclidean', log_distance: 'bool' = True, eps: 'float' = 0.001, prefix: 'str' = 'distance', keep_original_cols: 'bool' = False, role: 'str | None' = 'feature', id: 'str | None' = None) Replace numeric columns with per-row distances to each class centroid. The selected columns are read to learn one centroid per target class, then replaced by one ``distance_`` column per class holding each row's distance to that class's centroid. Each distance is computed from all the selected columns at once, so no distance column belongs to any one of them. For the distance to a single fixed point, see `StepGeoDistance`. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to measure distances over. 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. target Name of the column in the training data frame that holds the target classes. Read at fit time only; the column is *not* declared as an input feature in `schema_in()`. metric Distance function: ``"euclidean"`` (default) or ``"manhattan"``. log_distance Whether to return ``log(distance + eps)`` instead of raw distances. Default ``True``. eps Offset inside the log (only used when ``log_distance`` is ``True``). Default ``0.001``. prefix Prefix for the new column names. Default ``"distance"`` gives ``distance_``. keep_original_cols If ``True``, the source columns are kept alongside the distance columns instead of being dropped. Default ``False``. role Role assigned to the new distance columns (see `Roles`). Default ``"feature"``. id Stable step identifier. Defaults to ``"class_distance"``; a second step of this type in the same recipe becomes ``"class_distance_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- The two numeric columns are replaced by one ``distance_`` column per class label found in ``target``: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepClassDistance from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame( { "x": [0.0, 1.0, 10.0, 11.0], "y": [0.0, 1.0, 10.0, 11.0], "label": ["a", "a", "b", "b"], } ) df ``` Specifying the step touches no data, so the recipe reports itself as untrained: ```{python} recipe = Recipe().add( StepClassDistance( s.numeric_features(), target="label", log_distance=False ) ) recipe ``` `fit()` learns one centroid per class label and returns a trained recipe: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` then replaces the numeric columns with one ``distance_`` column per label: ```{python} fitted.transform(df) ``` ``log_distance`` (the default) compresses the raw distances: ```{python} recipe = Recipe().add( StepClassDistance(s.numeric_features(), target="label") ) fitted = recipe.fit(df) fitted.transform(df) ``` ``keep_original_cols`` keeps the source columns alongside the distances: ```{python} recipe = Recipe().add( StepClassDistance( s.numeric_features(), target="label", keep_original_cols=True ) ) fitted = recipe.fit(df) fitted.transform(df) ``` StepGeoDistance(lat: 'str', lon: 'str', *, ref_lat: 'float', ref_lon: 'float', metric: 'GeoMetric' = 'haversine', log_distance: 'bool' = False, name: 'str' = 'geo_dist', keep_original_cols: 'bool' = False, role: 'str | None' = 'feature', id: 'str | None' = None) -> 'None' Add the distance from each row to a fixed reference point. Replaces the ``lat``/``lon`` columns with a single ``name`` column holding each row's distance to ``(ref_lat, ref_lon)``. With the default ``"haversine"`` metric the result is the great-circle distance in meters; with ``"euclidean"`` it is the flat-plane distance between the raw ``lat``/``lon`` values. See [Spatial Distance](https://feaz-book.com/spatial-distance) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- lat Name of the latitude column. lon Name of the longitude column. ref_lat Latitude of the reference point. Must be between -90 and 90 when ``metric`` is ``"haversine"``. ref_lon Longitude of the reference point. Must be between -180 and 180 when ``metric`` is ``"haversine"``. metric Distance function: ``"haversine"`` (default) for great-circle distance in meters, or ``"euclidean"`` for the flat-plane distance between the raw ``lat``/``lon`` values. log_distance Whether to return ``log(distance)`` instead of the raw distance. A row exactly at the reference point has distance 0, which gives ``-inf``; there is no ``eps`` offset as in ``StepClassDistance``. Default ``False``. name Name of the output distance column. Default ``"geo_dist"``. A `Recipe` rejects the step if the data frame already has a column of this name. keep_original_cols If ``True``, the ``lat``/``lon`` columns are kept alongside the distance column instead of being dropped. Default ``False``. role Role assigned to the new distance column (see `Roles`). Default ``"feature"``. id Stable step identifier. Defaults to ``"geo_distance"``; a second step of this type in the same recipe becomes ``"geo_distance_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- Each row's distance to Union Station in Washington, D.C.: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepGeoDistance ``` ```{python} df = pd.DataFrame( { "name": ["Union Station", "Smithsonian Castle"], "lat": [38.897303, 38.888504], "lon": [-77.006430, -77.026352], } ) df ``` Specifying the step touches no data, so the recipe reports itself as untrained: ```{python} recipe = Recipe().add( StepGeoDistance("lat", "lon", ref_lat=38.8986312, ref_lon=-77.0062457) ) recipe ``` `fit()` records the reference point and returns a trained recipe: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` replaces ``lat``/``lon`` with the ``geo_dist`` column, in meters: ```{python} fitted.transform(df) ``` ``metric="euclidean"`` computes the flat-plane distance between the raw coordinate values instead: ```{python} recipe = Recipe().add( StepGeoDistance( "lat", "lon", ref_lat=38.8986312, ref_lon=-77.0062457, metric="euclidean" ) ) fitted = recipe.fit(df) fitted.transform(df) ``` ``keep_original_cols`` keeps ``lat``/``lon`` alongside the distance: ```{python} recipe = Recipe().add( StepGeoDistance( "lat", "lon", ref_lat=38.8986312, ref_lon=-77.0062457, keep_original_cols=True, ) ) fitted = recipe.fit(df) fitted.transform(df) ``` StepIntercept(*, value: 'float' = 1.0, name: 'str' = 'intercept', role: 'str | None' = 'feature', id: 'str | None' = None) Add a constant column with a fixed value. A single constant column is added, by default a column of ones named ``"intercept"``. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- value The constant to fill the new column with. Default ``1.0``. The column's dtype follows the literal, so an ``int`` gives an integer column. name Name of the new column. Default ``"intercept"``. A `Recipe` rejects the step if the data frame already has a column of this name. role Role assigned to the new column (see `Roles`). Default ``"feature"``. id Stable step identifier. Defaults to ``"intercept"``; a second step of this type in the same recipe becomes ``"intercept_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- A constant ``intercept`` column of ones is added; the input columns pass through untouched: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepIntercept ``` ```{python} df = pd.DataFrame({"x": [1.0, 2.0, 3.0]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepIntercept()) recipe ``` `fit()` has nothing to estimate; the step is constant: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` adds the column: ```{python} fitted.transform(df) ``` ``value`` and ``name`` control what is added: ```{python} recipe = Recipe().add(StepIntercept(value=0.0, name="bias")) fitted = recipe.fit(df) fitted.transform(df) ``` StepInteract(columns: 'Selector', *, sep: 'str' = '_x_', keep_original_cols: 'bool' = False, role: 'str | None' = 'feature', id: 'str | None' = None) -> 'None' Add the pairwise product of every pair of selected columns. For every unordered pair among the selected columns, adds one column holding their elementwise product, named by joining the two source names with ``sep``. ``n`` selected columns produce ``n * (n - 1) / 2`` interaction columns. This step is **pairwise only**: it does not build 3-way-or-higher interaction terms. A user who needs one can write it explicitly with `StepMutate`. See [Arithmetic](https://feaz-book.com/numeric-arithmetic) in *Feature Engineering A to Z* for background on products of columns (feature crosses). See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to interact. 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. sep Separator joining each pair's two column names into the output column name. Default ``"_x_"``. keep_original_cols If ``True``, the source columns are kept alongside the interaction columns instead of being dropped. Default ``False``. role Role assigned to the new interaction columns (see `Roles`). Default ``"feature"``. id Stable step identifier. Defaults to ``"interact"``; a second step of this type in the same recipe becomes ``"interact_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- Every pair of the three numeric columns gets its own product column: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepInteract from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame({"a": [1.0, 2.0, 3.0], "b": [4.0, 5.0, 6.0], "c": [7.0, 8.0, 9.0]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepInteract(s.numeric_features())) recipe ``` `fit()` records the pairs to interact: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` adds one product column per pair and drops the sources: ```{python} fitted.transform(df) ``` A custom ``sep`` changes the generated names: ```{python} recipe = Recipe().add(StepInteract(s.numeric_features(), sep="_times_")) fitted = recipe.fit(df) fitted.transform(df) ``` ``keep_original_cols`` keeps the source columns alongside the products: ```{python} recipe = Recipe().add( StepInteract(s.numeric_features(), keep_original_cols=True) ) fitted = recipe.fit(df) fitted.transform(df) ``` ## Steps: categorical features Encode nominal columns as numeric ones. StepDummy(columns: 'Selector', *, name_fn: 'Callable[[str, str], str] | None' = None, keep_original_cols: 'bool' = False, role: 'str | None' = 'feature', id: 'str | None' = None) -> 'None' Expand categorical columns into *k-1* binary indicator columns. Each selected column is replaced by *k-1* indicator columns where *k* is the number of unique non-null levels seen during ``fit()``. Indicators are ``nw.Int8`` (0/1); a column that contains null-source or unseen-level rows is ``nw.Float64`` instead (0.0/1.0/NaN), since pandas' ``Int8`` cannot hold the missing values. The first level in ascending sort order is the reference level and is dropped. To keep an indicator for every level, use `StepOneHot` instead. See [Dummy Encoding](https://feaz-book.com/categorical-dummy) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to expand. Accepts a single column name, a list of names, a mlfeatures selector such as ``Selectors.nominal_features()`` (see `Selectors` for the full set), or a narwhals or polars selector (``narwhals.selectors.string()``, ``polars.selectors.string()``). Selectors are resolved against the data frame's schema when the recipe is fitted, so the same selector works on any backend. Only discrete columns (string, categorical, enum, boolean, and integer) are meaningful here. name_fn Callable mapping ``(source_column, level_as_str)`` to the indicator column's name. Default ``None``, which names them ``"{column}_{level}"``. keep_original_cols If ``True``, the source columns are kept alongside the indicators instead of being dropped. Default ``False``. role Role assigned to the indicator columns (see `Roles`). Default ``"feature"``. id Stable step identifier. Defaults to ``"dummy"``; a second step of this type in the same recipe becomes ``"dummy_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- Each categorical column is replaced by *k-1* indicators; the first level in sort order (``blue``) is the dropped reference: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepDummy from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame({"color": ["red", "green", "blue", "red"]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepDummy(s.nominal_features())) recipe ``` `fit()` records the levels of each selected column: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` replaces the column with its indicators: ```{python} fitted.transform(df) ``` ``keep_original_cols`` keeps the source column alongside them: ```{python} recipe = Recipe().add(StepDummy(s.nominal_features(), keep_original_cols=True)) fitted = recipe.fit(df) fitted.transform(df) ``` StepOneHot(columns: 'Selector', *, name_fn: 'Callable[[str, str], str] | None' = None, keep_original_cols: 'bool' = False, role: 'str | None' = 'feature', id: 'str | None' = None) -> 'None' Expand discrete columns into *k* binary indicator columns. Each selected column is replaced by *k* indicator columns where *k* is the number of unique non-null levels seen during ``fit()``. Indicators are ``nw.Int8`` (0/1); a column that contains null-source or unseen-level rows is ``nw.Float64`` instead (0.0/1.0/NaN), since pandas' ``Int8`` cannot hold the missing values. Unlike `StepDummy`, no reference level is dropped. See [Dummy Encoding](https://feaz-book.com/categorical-dummy) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to expand. Accepts a single column name, a list of names, a mlfeatures selector such as ``Selectors.nominal_features()`` (see `Selectors` for the full set), or a narwhals or polars selector (``narwhals.selectors.string()``, ``polars.selectors.string()``). Selectors are resolved against the data frame's schema when the recipe is fitted, so the same selector works on any backend. Only discrete columns (string, categorical, enum, boolean, and integer) are meaningful here. name_fn Callable mapping ``(source_column, level_as_str)`` to the indicator column's name. Default ``None``, which names them ``"{column}_{level}"``. keep_original_cols If ``True``, the source columns are kept alongside the indicators instead of being dropped. Default ``False``. role Role assigned to the indicator columns (see `Roles`). Default ``"feature"``. id Stable step identifier. Defaults to ``"one_hot"``; a second step of this type in the same recipe becomes ``"one_hot_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- Each categorical column is replaced by one indicator per level, with no reference level dropped (contrast `StepDummy`): ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepOneHot from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame({"color": ["red", "green", "blue", "red"]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepOneHot(s.nominal_features())) recipe ``` `fit()` records the levels of each selected column: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` replaces the column with one indicator per level: ```{python} fitted.transform(df) ``` ``keep_original_cols`` keeps the source column alongside them: ```{python} recipe = Recipe().add(StepOneHot(s.nominal_features(), keep_original_cols=True)) fitted = recipe.fit(df) fitted.transform(df) ``` StepOther(columns: 'Selector', *, threshold: 'float | None' = None, min_count: 'int | None' = None, other_level: 'str' = 'other', id: 'str | None' = None) Collapse infrequent categorical levels into a single ``"other"`` level. Each selected categorical column keeps the levels that are frequent enough in the training data and has every other level replaced in place by ``other_level``. Levels that never appeared during fitting are pooled into ``other_level`` as well, so new data can never introduce a level the rest of the recipe has not seen. Nulls stay null; use `StepUnknown` first when missingness should become a level of its own. See [Collapsing Categories](https://feaz-book.com/categorical-collapse) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to collapse. Accepts a single column name, a list of names, a mlfeatures selector such as ``Selectors.nominal_features()`` (see `Selectors` for the full set), or a narwhals or polars selector (``narwhals.selectors.string()``, ``polars.selectors.string()``). Selectors are resolved against the data frame's schema when the recipe is fitted, so the same selector works on any backend. Only categorical columns (string, categorical, and enum) are meaningful here. threshold Smallest share of a column's non-null rows a level may hold and still be kept, as a proportion strictly between 0 and 1. Default ``None``; mutually exclusive with ``min_count``, and when neither is given a proportion of ``0.05`` is used. min_count Smallest number of rows a level may appear in and still be kept, as a whole number of 1 or more. Default ``None``; mutually exclusive with ``threshold``. other_level The level that pooled levels are replaced with. Default ``"other"``. A `UserWarning` is emitted if a selected column already contains this level, since the pooled rows then become indistinguishable from real ones. id Stable step identifier. Defaults to ``"other"``; a second step of this type in the same recipe becomes ``"other_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- The rare levels are pooled in place into a single ``"other"`` level: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepOther from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame( {"city": ["NYC"] * 5 + ["LA"] * 4 + ["Reno", "Provo"]} ) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepOther(s.nominal_features(), threshold=0.2)) recipe ``` `fit()` records which levels are frequent enough to keep: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` pools everything else: ```{python} fitted.transform(df) ``` ``min_count`` states the cutoff as a number of rows instead of a share: ```{python} recipe = Recipe().add(StepOther(s.nominal_features(), min_count=5)) fitted = recipe.fit(df) fitted.transform(df) ``` ``other_level`` names the pooled level: ```{python} recipe = Recipe().add( StepOther(s.nominal_features(), threshold=0.2, other_level="rare") ) fitted = recipe.fit(df) fitted.transform(df) ``` ## Steps: date and datetime features Expand Date and Datetime columns into calendar-part feature columns. StepDateFeatures(columns: 'Selector', *, features: 'list[str] | tuple[str, ...]' = ('year', 'month', 'day', 'dow', 'doy'), categorical: 'list[str] | tuple[str, ...]' = (), keep_original_cols: 'bool' = False, role: 'str | None' = 'feature', id: 'str | None' = None) -> 'None' Expand Date columns into calendar-part feature columns. Each selected Date column is replaced by one integer column per requested entry of ``features`` (``year``, ``month``, ``day``, ``dow``, ``doy``), named ``{column}_{feature}``. Nothing is estimated from the training data: every calendar part is an elementwise function of the column's value, so the transform is identical on training and new data. ``dow`` is the ISO day of week (``1`` = Monday, ``7`` = Sunday); ``doy`` is the ordinal day of year (``1``-``366``). Produced columns are ``Int32`` regardless of backend, unless named in ``categorical``. A Datetime column (carrying a time-of-day component) is not accepted here; use `StepDatetimeFeatures` for those. See [Value Extraction](https://feaz-book.com/datetime-extraction) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to expand. Accepts a single column name, a list of names, a mlfeatures selector such as ``Selectors.date_features()`` (see `Selectors` for the full set), or a narwhals or polars selector (``narwhals.selectors.by_dtype(narwhals.Date)``). Selectors are resolved against the data frame's schema when the recipe is fitted, so the same selector works on any backend. Only Date columns are meaningful here. features Calendar parts to compute, from ``"year"``, ``"month"``, ``"day"``, ``"dow"`` (day of week), and ``"doy"`` (day of year). Default ``("year", "month", "day", "dow", "doy")``. Deduplicated and reordered to that same canonical order regardless of the order passed in, so the output columns are always in a fixed order. categorical Subset of ``features``, restricted to ``"month"`` and ``"dow"`` (the two parts with a natural, fixed vocabulary of level names), to encode as an ordered categorical column of level names (``"January"``, ``"Monday"``, ...) instead of a plain integer. Default ``()``: no feature is categorical. Each entry must also be present in ``features``. keep_original_cols If ``True``, the source columns are kept alongside their calendar-part columns instead of being dropped. Default ``False``. role Role assigned to the new calendar-part columns (see `Roles`). Default ``"feature"``. id Stable step identifier. Defaults to ``"date_features"``; a second step of this type in the same recipe becomes ``"date_features_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- Each selected column is replaced by its calendar-part columns: ```{python} #| echo: false #| output: false import polars as pl from datetime import date from mlfeatures import Recipe, StepDateFeatures from mlfeatures import Selectors as s ``` ```{python} df = pl.DataFrame({"d": [date(2020, 1, 1), date(2020, 6, 15), date(2020, 12, 31)]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepDateFeatures(s.date_features())) recipe ``` There is nothing to estimate, so `fit()` only resolves the selection: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` adds one column per requested calendar part and drops the source: ```{python} fitted.transform(df) ``` A narrower ``features`` produces fewer columns: ```{python} recipe = Recipe().add(StepDateFeatures(s.date_features(), features=["year", "month"])) fitted = recipe.fit(df) fitted.transform(df) ``` ``keep_original_cols`` keeps the source column alongside the calendar parts: ```{python} recipe = Recipe().add( StepDateFeatures(s.date_features(), keep_original_cols=True) ) fitted = recipe.fit(df) fitted.transform(df) ``` ``categorical`` names level names instead of raw numbers for ``month`` and ``dow``: ```{python} recipe = Recipe().add( StepDateFeatures(s.date_features(), categorical=["month", "dow"]) ) fitted = recipe.fit(df) fitted.transform(df) ``` StepDatetimeFeatures(columns: 'Selector', *, features: 'list[str] | tuple[str, ...]' = ('year', 'month', 'day', 'hour', 'minute', 'second', 'dow', 'doy'), categorical: 'list[str] | tuple[str, ...]' = (), keep_original_cols: 'bool' = False, role: 'str | None' = 'feature', id: 'str | None' = None) -> 'None' Expand Datetime columns into calendar-part feature columns. Each selected Datetime column is replaced by one integer column per requested entry of ``features`` (``year``, ``month``, ``day``, ``hour``, ``minute``, ``second``, ``dow``, ``doy``), named ``{column}_{feature}``. Nothing is estimated from the training data: every calendar part is an elementwise function of the column's value, so the transform is identical on training and new data. ``dow`` is the ISO day of week (``1`` = Monday, ``7`` = Sunday); ``doy`` is the ordinal day of year (``1``-``366``). Produced columns are ``Int32`` regardless of backend, unless named in ``categorical``. Calendar parts are read against whatever time zone the column already carries (including none); this step does not convert to a different zone. A caller who needs a specific zone should convert it first, e.g. with ``narwhals.Expr.dt.convert_time_zone()`` inside a `StepMutate`. A Date column (with no time-of-day component) is not accepted here; use `StepDateFeatures` for those. See [Value Extraction](https://feaz-book.com/datetime-extraction) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to expand. Accepts a single column name, a list of names, a mlfeatures selector such as ``Selectors.datetime_features()`` (see `Selectors` for the full set), or a narwhals or polars selector (``narwhals.selectors.by_dtype(narwhals.Datetime)``). Selectors are resolved against the data frame's schema when the recipe is fitted, so the same selector works on any backend. Only Datetime columns are meaningful here. features Calendar parts to compute, from ``"year"``, ``"month"``, ``"day"``, ``"hour"``, ``"minute"``, ``"second"``, ``"dow"`` (day of week), and ``"doy"`` (day of year). Default ``("year", "month", "day", "hour", "minute", "second", "dow", "doy")``. Deduplicated and reordered to that same canonical order regardless of the order passed in, so the output columns are always in a fixed order. categorical Subset of ``features``, restricted to ``"month"`` and ``"dow"`` (the two parts with a natural, fixed vocabulary of level names), to encode as an ordered categorical column of level names (``"January"``, ``"Monday"``, ...) instead of a plain integer. Default ``()``: no feature is categorical. Each entry must also be present in ``features``. keep_original_cols If ``True``, the source columns are kept alongside their calendar-part columns instead of being dropped. Default ``False``. role Role assigned to the new calendar-part columns (see `Roles`). Default ``"feature"``. id Stable step identifier. Defaults to ``"datetime_features"``; a second step of this type in the same recipe becomes ``"datetime_features_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- Each selected column is replaced by its calendar-part columns: ```{python} #| echo: false #| output: false import pandas as pd from datetime import datetime from mlfeatures import Recipe, StepDatetimeFeatures from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame( { "dt": [ datetime(2020, 1, 1, 8, 30, 0), datetime(2020, 6, 15, 13, 45, 30), datetime(2020, 12, 31, 23, 59, 59), ] } ) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepDatetimeFeatures(s.datetime_features())) recipe ``` There is nothing to estimate, so `fit()` only resolves the selection: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` adds one column per requested calendar part and drops the source: ```{python} fitted.transform(df) ``` A narrower ``features`` produces fewer columns: ```{python} recipe = Recipe().add( StepDatetimeFeatures(s.datetime_features(), features=["year", "month", "hour"]) ) fitted = recipe.fit(df) fitted.transform(df) ``` ``keep_original_cols`` keeps the source column alongside the calendar parts: ```{python} recipe = Recipe().add( StepDatetimeFeatures(s.datetime_features(), keep_original_cols=True) ) fitted = recipe.fit(df) fitted.transform(df) ``` ``categorical`` names level names instead of raw numbers for ``month`` and ``dow``: ```{python} recipe = Recipe().add( StepDatetimeFeatures(s.datetime_features(), categorical=["month", "dow"]) ) fitted = recipe.fit(df) fitted.transform(df) ``` StepHoliday(columns: 'Selector', *, holidays: 'list[str] | tuple[str, ...]' = ("New Year's Day", 'Labor Day', 'Christmas Day'), rules: 'Mapping[str, rrule | rruleset] | None' = None, country: 'str' = 'US', subdiv: 'str | None' = None, keep_original_cols: 'bool' = False, role: 'str | None' = 'feature', id: 'str | None' = None) -> 'None' Add binary indicator columns flagging named holidays and custom recurrences. Each selected Date/Datetime column gets one companion ``Int32`` column per requested holiday name and per requested recurrence rule, named ``{column}_{name}`` (the holiday or rule name lowercased with non-alphanumeric characters collapsed to underscores), that is ``1`` where the value falls on that holiday or matches that rule and ``0`` otherwise. A Datetime value is compared by its date part; time of day never affects the result. For calendar parts such as month or day of week, see `StepDateFeatures` and `StepDatetimeFeatures`. Named holidays (``holidays``) are looked up in the `holidays` PyPI package's calendar for ``country`` (and, if given, ``subdiv``), rebuilt from the actual year span present in the data being transformed, so dates outside the training year range are still classified correctly. A holiday name is only meaningful relative to the ``country``/``subdiv`` it was requested with; some public holidays shift onto an adjacent weekday and are reported under a separate ``"... (observed)"`` name, which only matches if requested explicitly. Custom recurrences (``rules``) are ``dateutil.rrule.rrule`` or ``dateutil.rrule.rruleset`` objects the caller builds directly (weekends, "last Friday of the month", Easter, and so on), evaluated the same way, over the year span present in the data being transformed. A rule constructed without an explicit ``dtstart`` only starts recurring from the moment it was built, so it should be given one early enough to cover the data it is matched against. See [Advanced Features](https://feaz-book.com/datetime-advanced) in *Feature Engineering A to Z* for background on indicators for irregular events such as holidays. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to flag. Accepts a single column name, a list of names, a mlfeatures selector such as ``Selectors.date_features()`` (see `Selectors` for the full set), or a narwhals or polars selector (``narwhals.selectors.by_dtype(narwhals.Date)``). Selectors are resolved against the data frame's schema when the recipe is fitted, so the same selector works on any backend. Only Date and Datetime columns are meaningful here. holidays Holiday names to flag, matched against the `holidays` package's calendar for ``country``/``subdiv``. Default ``("New Year's Day", "Labor Day", "Christmas Day")``. rules Custom recurrences to flag, keyed by name, each a ``dateutil.rrule.rrule`` or ``dateutil.rrule.rruleset``. Default ``None`` (no custom recurrences). A name here must not collapse to the same column-safe slug as a ``holidays`` name or another ``rules`` name. country `holidays` package country code the holiday names are resolved against. Default ``"US"``. subdiv Subdivision code within ``country`` (e.g. a US state or Canadian province code), for holidays observed only in part of a country. Default ``None``. keep_original_cols If ``True``, the source columns are kept alongside their indicator columns instead of being dropped. Default ``False``. role Role assigned to the new indicator columns (see `Roles`). Default ``"feature"``. id Stable step identifier. Defaults to ``"holiday"``; a second step of this type in the same recipe becomes ``"holiday_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- Each selected column gets one indicator column per requested holiday: ```{python} #| echo: false #| output: false import polars as pl from datetime import date from mlfeatures import Recipe, StepHoliday from mlfeatures import Selectors as s ``` ```{python} df = pl.DataFrame( {"d": [date(2023, 12, 24), date(2023, 12, 25), date(2024, 1, 1)]} ) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepHoliday(s.date_features(), holidays=["Christmas Day"])) recipe ``` `fit()` validates the holiday names against a real calendar built from the training data's years: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` adds one indicator column per requested holiday and drops the source: ```{python} fitted.transform(df) ``` ``keep_original_cols`` keeps the source column alongside the indicators: ```{python} recipe = Recipe().add( StepHoliday( s.date_features(), holidays=["Christmas Day"], keep_original_cols=True ) ) fitted = recipe.fit(df) fitted.transform(df) ``` ``country`` resolves the same holiday names against a different calendar: ```{python} recipe = Recipe().add( StepHoliday(s.date_features(), holidays=["Christmas Day"], country="CA") ) fitted = recipe.fit(df) fitted.transform(df) ``` ``rules`` flags custom recurrences, defined with `dateutil.rrule`, alongside named holidays: ```{python} from dateutil.rrule import rrule, WEEKLY, SA, SU weekend = rrule(WEEKLY, byweekday=(SA, SU), dtstart=date(2023, 1, 1)) recipe = Recipe().add( StepHoliday( s.date_features(), holidays=["Christmas Day"], rules={"weekend": weekend} ) ) fitted = recipe.fit(df) fitted.transform(df) ``` ## Steps: missing data Impute missing values, or give them an explicit level. StepImputeMean(columns: 'Selector', *, id: 'str | None' = None) Impute missing numeric values with the column mean. Each selected numeric column has its nulls filled in place with that column's mean. The median is less sensitive to outliers (see `StepImputeMedian`), and categorical columns need `StepImputeMode`. To keep a record of which values were missing, see `StepIndicateNa`. A column that is entirely null at fit time has no mean to impute with; it is left unchanged (not dropped) with a warning, and passes through ``transform`` untouched. See [Simple Imputation](https://feaz-book.com/missing-simple) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to impute. 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 ``"impute_mean"``; a second step of this type in the same recipe becomes ``"impute_mean_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- The null is filled in place with the column mean of the observed values: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepImputeMean from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame({"x": [1.0, 2.0, None, 4.0]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepImputeMean(s.numeric_features())) recipe ``` `fit()` computes the mean of the observed values: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` fills the nulls in place: ```{python} fitted.transform(df) ``` StepImputeMedian(columns: 'Selector', *, id: 'str | None' = None) Impute missing numeric values with the column median. Each selected numeric column has its nulls filled in place with that column's median, which is less sensitive to outliers than the mean (see `StepImputeMean`). Categorical columns need `StepImputeMode`. To keep a record of which values were missing, see `StepIndicateNa`. A column that is entirely null at fit time has no median to impute with; it is left unchanged (not dropped) with a warning, and passes through ``transform`` untouched. See [Simple Imputation](https://feaz-book.com/missing-simple) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to impute. 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 ``"impute_median"``; a second step of this type in the same recipe becomes ``"impute_median_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- The null is filled in place with the column median of the observed values: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepImputeMedian from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame({"x": [1.0, 2.0, None, 4.0]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepImputeMedian(s.numeric_features())) recipe ``` `fit()` computes the median of the observed values: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` fills the nulls in place: ```{python} fitted.transform(df) ``` StepImputeMode(columns: 'Selector', *, id: 'str | None' = None) Impute missing values with the column mode (most frequent value). Each selected column has its nulls filled in place with that column's mode. Mode imputation is for categorical columns (it accepts ``Categorical``/``Enum``/``String``, not numeric dtypes) and is dtype-preserving: the fill value is an observed level of the column. For numeric columns, see `StepImputeMean` or `StepImputeMedian`; to make missingness a level of its own, see `StepUnknown`. A column that is entirely null at fit time has no mode; it is left unchanged (not dropped) with a warning, and passes through ``transform`` untouched. See [Simple Imputation](https://feaz-book.com/missing-simple) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to impute. Accepts a single column name, a list of names, a mlfeatures selector such as ``Selectors.nominal_features()`` (see `Selectors` for the full set), or a narwhals or polars selector (``narwhals.selectors.string()``, ``polars.selectors.string()``). Selectors are resolved against the data frame's schema when the recipe is fitted, so the same selector works on any backend. Only categorical columns (string, categorical, and enum) are meaningful here. id Stable step identifier. Defaults to ``"impute_mode"``; a second step of this type in the same recipe becomes ``"impute_mode_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- The null is filled in place with the column mode (the most frequent observed level): ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepImputeMode from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame( {"city": pd.Series(["NYC", "LA", "NYC", None], dtype="category")} ) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepImputeMode(s.nominal_features())) recipe ``` `fit()` finds the most frequent observed level: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` fills the nulls in place: ```{python} fitted.transform(df) ``` StepUnknown(columns: 'Selector', *, new_level: 'str' = 'unknown', id: 'str | None' = None) Recode missing categorical levels to an explicit ``"unknown"`` level. Each selected categorical column has its nulls replaced in place by ``new_level``. To also pool infrequent levels, see `StepOther`. See [Simple Imputation](https://feaz-book.com/missing-simple) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to recode. Accepts a single column name, a list of names, a mlfeatures selector such as ``Selectors.nominal_features()`` (see `Selectors` for the full set), or a narwhals or polars selector (``narwhals.selectors.string()``, ``polars.selectors.string()``). Selectors are resolved against the data frame's schema when the recipe is fitted, so the same selector works on any backend. Only categorical columns (string, categorical, and enum) are meaningful here. new_level The level that replaces nulls. Default ``"unknown"``. A `UserWarning` is emitted if a selected column already contains this level, since the recoded rows then become indistinguishable from real ones. id Stable step identifier. Defaults to ``"unknown"``; a second step of this type in the same recipe becomes ``"unknown_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- Nulls in the selected column are recoded in place to an explicit ``"unknown"`` level: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepUnknown from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame( {"city": pd.Series(["NYC", "LA", "NYC", None], dtype="category")} ) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepUnknown(s.nominal_features())) recipe ``` `fit()` records the level to add to each column: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` recodes the nulls in place: ```{python} fitted.transform(df) ``` ``new_level`` names the added level: ```{python} recipe = Recipe().add(StepUnknown(s.nominal_features(), new_level="missing")) fitted = recipe.fit(df) fitted.transform(df) ``` StepIndicateNa(columns: 'Selector', *, keep_original_cols: 'bool' = False, role: 'str | None' = 'feature', id: 'str | None' = None) -> 'None' Add a binary indicator column flagging missing values. Each selected column gets a companion ``{column}_na`` column that is ``1`` where the source value is missing and ``0`` otherwise. Nothing is estimated from the training data: missingness is an elementwise property of each row's value, so the transform is identical on training and new data, and a column with no missing values at fit time still gets an indicator (new data may have missing values training data did not). A float column is flagged missing on either a null or a NaN value; every other dtype has no NaN representation, so only null counts. Unlike most steps that replace a column with several, ``keep_original_cols`` is usually worth setting to ``True`` here: the indicator alone discards the source column's own value, and a downstream imputation step (`StepImputeMean`, `StepImputeMedian`, `StepImputeMode`, `StepUnknown`) still needs that column to fill in. See [Missing Values Indicators](https://feaz-book.com/missing-indicator) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to flag. Accepts a single column name, a list of names, a mlfeatures selector such as ``Selectors.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. Any dtype is accepted. keep_original_cols If ``True``, the source columns are kept alongside their indicator columns instead of being dropped. Default ``False``. role Role assigned to the new indicator columns (see `Roles`). Default ``"feature"``. id Stable step identifier. Defaults to ``"indicate_na"``; a second step of this type in the same recipe becomes ``"indicate_na_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- Each selected column gets a companion ``_na`` indicator: ```{python} #| echo: false #| output: false import polars as pl from mlfeatures import Recipe, StepIndicateNa from mlfeatures import Selectors as s ``` ```{python} df = pl.DataFrame({"x": [1.0, None, 3.0], "g": ["a", "b", None]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepIndicateNa(s.features(), keep_original_cols=True)) recipe ``` There is nothing to estimate, so `fit()` only resolves the selection: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` adds one indicator column per selected column, keeping the source alongside it so it is still available to a later imputation step: ```{python} fitted.transform(df) ``` Without ``keep_original_cols``, the source column is dropped instead: ```{python} recipe = Recipe().add(StepIndicateNa(s.features())) fitted = recipe.fit(df) fitted.transform(df) ``` ## Steps: dimensionality reduction Reduce dimensionality, or filter columns that carry no signal. StepDropZeroVariance(columns: 'Selector', *, id: 'str | None' = None) Remove columns that have a single unique value (zero variance). The selected columns whose observed values are all the same (or all missing) are dropped, and no new columns are produced. For a looser rule that also drops columns dominated by one value, see `StepDropNearZeroVariance`. See [Zero Variance Filter](https://feaz-book.com/too-many-zv) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to consider for removal. Accepts a single column name, a list of names, a mlfeatures selector such as ``Selectors.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. Any dtype is accepted. id Stable step identifier. Defaults to ``"zv"``; a second step of this type in the same recipe becomes ``"zv_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- ``const`` has a single unique value, so it is dropped; ``x`` is kept: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepDropZeroVariance from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame({"x": [1.0, 2.0, 3.0], "const": [5.0, 5.0, 5.0]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepDropZeroVariance(s.numeric_features())) recipe ``` `fit()` counts the unique values in each column: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` drops the constant one: ```{python} fitted.transform(df) ``` StepDropNearZeroVariance(columns: 'Selector', *, freq_cut: 'float' = 19.0, unique_cut: 'float' = 10, id: 'str | None' = None) Remove columns that are sparse and unbalanced (near-zero variance). A selected column is dropped if it has a single unique value (or is entirely missing), or if it is both highly concentrated on one value and has few unique values relative to the number of samples: the ratio of the most common value's count to the second most common value's count exceeds ``freq_cut``, and the percentage of unique values is at or below ``unique_cut``. No new columns are produced. To drop only columns with a single unique value, see `StepDropZeroVariance`. See [Zero Variance Filter](https://feaz-book.com/too-many-zv) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to consider for removal. Accepts a single column name, a list of names, a mlfeatures selector such as ``Selectors.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. Any dtype is accepted. freq_cut Threshold for the frequency ratio of the most common value to the second most common value. Defaults to ``95 / 5``. unique_cut Threshold, in percent, for the share of unique values. Defaults to ``10``, and must be between ``0`` and ``100``. id Stable step identifier. Defaults to ``"nzv"``; a second step of this type in the same recipe becomes ``"nzv_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- ``sparse`` is a single value repeated 999 times with one outlier, so it is dropped; ``x`` is kept: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepDropNearZeroVariance from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame( { "x": list(range(1000)), "sparse": [1.0] + [0.0] * 999, } ) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepDropNearZeroVariance(s.numeric_features())) recipe ``` `fit()` computes each column's frequency ratio and percent of unique values: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` drops the sparse, unbalanced one: ```{python} fitted.transform(df) ``` A tighter ``unique_cut`` can keep columns that would otherwise be dropped: ```{python} Recipe().add( StepDropNearZeroVariance(s.numeric_features(), unique_cut=0.05) ).fit(df).transform(df) ``` StepPca(columns: 'Selector', *, num_comp: 'int' = 5, prefix: 'str' = 'PC', keep_original_cols: 'bool' = False, role: 'str | None' = 'feature', id: 'str | None' = None) -> 'None' Project numeric columns onto their principal components. The selected numeric columns are replaced by ``num_comp`` principal-component columns ``{prefix}1 ... {prefix}{num_comp}``. Each component is a linear combination of all the input columns, so no single component belongs to any one of them. Asking for more components than there are input columns yields fewer. To choose components that covary with the target instead, see `StepPls`. The columns are centered but not scaled, so a column measured on a larger numeric range contributes more to the components; normalize first if that is not what you want. Rows with a missing value are excluded when the components are computed, and such a row gets ``NaN`` for every component. See [Principal Component Analysis](https://feaz-book.com/too-many-pca) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to project. 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. num_comp Number of principal components to keep. Must be a positive integer. Capped at the number of selected columns and at the number of complete (null-free) training samples, so fewer components are produced when either is smaller than ``num_comp``. Default ``5``. prefix Prefix for the produced component column names. Default ``"PC"``. keep_original_cols If ``True``, the source columns are kept alongside the components instead of being dropped. Default ``False``. role Role assigned to the new component columns (see `Roles`). Default ``"feature"``. id Stable step identifier. Defaults to ``"pca"``; a second step of this type in the same recipe becomes ``"pca_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- The two correlated columns are replaced by two principal components: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepPca from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame( {"x": [1.0, 2.0, 3.0, 4.0], "y": [2.1, 3.9, 6.1, 8.0]} ) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepPca(s.numeric_features(), num_comp=2)) recipe ``` `fit()` learns the component loadings: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` replaces the columns with their scores: ```{python} fitted.transform(df) ``` ``num_comp`` caps how many components are kept: ```{python} recipe = Recipe().add(StepPca(s.numeric_features(), num_comp=1)) fitted = recipe.fit(df) fitted.transform(df) ``` ``keep_original_cols`` keeps the source columns alongside the components: ```{python} recipe = Recipe().add( StepPca(s.numeric_features(), num_comp=2, keep_original_cols=True) ) fitted = recipe.fit(df) fitted.transform(df) ``` StepPls(columns: 'Selector', target: 'str', *, num_comp: 'int' = 5, prefix: 'str' = 'PLS', keep_original_cols: 'bool' = False, role: 'str | None' = 'feature', id: 'str | None' = None) -> 'None' Project numeric columns onto partial-least-squares components. The selected numeric columns are replaced by ``num_comp`` component columns ``{prefix}1 ... {prefix}{num_comp}``. Each component is a linear combination of all the input columns chosen to covary with ``target``, so no single component belongs to any one of the input columns. Unlike unsupervised extraction such as `StepPca`, the components depend on the target as well as the selected columns. Asking for more components than there are input columns yields fewer. ``target`` may be numeric (partial least squares regression) or categorical/string (partial least squares discriminant analysis, fit by dummy-coding the classes into one indicator column per class). The columns are centered but not scaled, so a column measured on a larger numeric range contributes more to the components; normalize first if that is not what you want. Rows with a missing value in a selected column or a missing target are excluded when the components are fitted, and a row with a missing selected-column value gets ``NaN`` for every component at transform time. See [Partial Least Squares](https://feaz-book.com/too-many-pls) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to project. 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. target Name of the column in the training data frame that holds the numeric or categorical target. Read at fit time only; the column is *not* declared as an input feature in `schema_in()`. num_comp Number of components to keep. Must be a positive integer. Capped at the number of selected columns and at the number of complete (null-free) training samples, so fewer components are produced when either is smaller than ``num_comp``. Default ``5``. prefix Prefix for the produced component column names. Default ``"PLS"``. keep_original_cols If ``True``, the source columns are kept alongside the components instead of being dropped. Default ``False``. role Role assigned to the new component columns (see `Roles`). Default ``"feature"``. id Stable step identifier. Defaults to ``"pls"``; a second step of this type in the same recipe becomes ``"pls_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- The two feature columns are replaced by one PLS component predictive of ``target``: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepPls from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame( { "x": [1.0, 2.0, 3.0, 4.0], "y": [2.1, 3.9, 6.1, 8.0], "target": [1.0, 2.0, 3.0, 4.0], } ) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add( StepPls(s.numeric_features() - "target", target="target", num_comp=1) ) recipe ``` `fit()` learns the component rotation: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` replaces the columns with their scores: ```{python} fitted.transform(df) ``` ``keep_original_cols`` keeps the source columns alongside the components: ```{python} recipe = Recipe().add( StepPls( s.numeric_features() - "target", target="target", num_comp=1, keep_original_cols=True, ) ) fitted = recipe.fit(df) fitted.transform(df) ``` A categorical ``target`` runs partial least squares discriminant analysis instead, by dummy-coding its classes: ```{python} df_class = pd.DataFrame( { "x": [1.0, 2.0, 3.0, 4.0], "y": [2.1, 3.9, 6.1, 8.0], "target": ["a", "a", "b", "b"], } ) recipe = Recipe().add( StepPls(s.numeric_features() - "target", target="target", num_comp=1) ) fitted = recipe.fit(df_class) fitted.transform(df_class) ``` StepDropCorr(columns: 'Selector', *, threshold: 'float' = 0.9, method: "Literal['pearson', 'spearman']" = 'pearson', id: 'str | None' = None) Remove numeric columns whose pairwise absolute correlation is too high. The selected columns that exceed ``threshold`` are dropped, as are columns with no usable correlation at all (constant or all-null), and no new columns are produced. To drop columns with no variation rather than correlated ones, see `StepDropZeroVariance` and `StepDropNearZeroVariance`. See [High Correlation Filter](https://feaz-book.com/correlated-filter) in *Feature Engineering A to Z* for background on this technique. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to consider for removal. 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. threshold Pairs whose absolute correlation is strictly above this value trigger a removal. Default ``0.9``. method Correlation method: ``"pearson"`` (default) or ``"spearman"``. id Stable step identifier. Defaults to ``"corr"``; a second step of this type in the same recipe becomes ``"corr_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- ``a`` and ``b`` are almost perfectly correlated, so one of them is dropped; the uncorrelated ``c`` is kept: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepDropCorr from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame( { "a": [1.0, 2.0, 3.0, 4.0], "b": [1.0, 2.0, 3.0, 4.1], "c": [4.0, 1.0, 3.0, 2.0], } ) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepDropCorr(s.numeric_features(), threshold=0.9)) recipe ``` `fit()` computes the correlation matrix and picks the columns to drop: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` drops them: ```{python} fitted.transform(df) ``` A ``threshold`` above their correlation keeps both: ```{python} recipe = Recipe().add(StepDropCorr(s.numeric_features(), threshold=0.9999)) fitted = recipe.fit(df) fitted.transform(df) ``` StepDrop(columns: 'Selector', *, id: 'str | None' = None) Remove the selected columns. Every column the selector matches is dropped, and no new columns are produced. Nothing is estimated: which columns to drop is decided by the selector alone, fixed against the training data frame's schema. To drop columns by a data-driven rule instead, see `StepDropCorr`, `StepDropZeroVariance` or `StepDropNearZeroVariance`. The selection is taken at face value, so a selector that reaches a column with a role other than ``"feature"`` drops that column too. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- columns Columns to remove. Accepts a single column name, a list of names, a mlfeatures selector such as ``Selectors.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. Any dtype is accepted. id Stable step identifier. Defaults to ``"drop"``; a second step of this type in the same recipe becomes ``"drop_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- It is often easier to say what to remove than to enumerate what to keep: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepDrop from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame({"x": [1.0, 2.0, 3.0], "note": ["a", "b", "c"]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepDrop(s.string_features())) recipe ``` `fit()` resolves the selector against the training schema: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` drops the columns it matched: ```{python} fitted.transform(df) ``` ## Steps: general expressions Arbitrary row filters and column computations; escape hatches rather than a named feature-engineering method. StepFilter(predicate: 'Predicate', *, id: 'str | None' = None) -> 'None' Remove rows that do not match a predicate. Rows for which ``predicate`` is not ``True`` are dropped. To add or change columns instead, see `StepMutate`. Filtering applies to the training data only. Fitting a recipe drops the non-matching training rows, but transforming new data returns every row given to it, because dropping rows from data being scored would silently lose predictions. So a recipe that filters is not a way to filter new data. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- predicate Callable taking the data frame and returning a boolean narwhals expression or series, ``True`` for the rows to keep. Must be callable. id Stable step identifier. Defaults to ``"filter"``; a second step of this type in the same recipe becomes ``"filter_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- Rows where ``age`` is 30 or below are dropped when the recipe is fitted, while ``transform()`` leaves every row in place: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepFilter ``` ```{python} df = pd.DataFrame({"age": [25, 41, 33, 52]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add(StepFilter(lambda df: df["age"] > 30)) recipe ``` `fit()` applies the predicate to the training data: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` leaves new data untouched, so all four rows come back: ```{python} fitted.transform(df) ``` StepMutate(mutations: 'Mapping[str, Mutation]', *, role: 'str | None' = 'feature', id: 'str | None' = None) -> 'None' Apply arbitrary column expressions: the escape hatch. Each supplied mutation either adds a new column or overwrites an existing one, so the exact column change is only known after the mutations run on the training data frame. `fit()` applies them once to read off which columns were *added* (and their dtypes) versus modified in place, then re-applies the same expressions at transform time. To remove rows instead, see `StepFilter`. New columns are attributed to no declared parents (``output_parents`` maps each to ``[]``): the expressions are opaque callables, so mlfeatures does not try to infer which inputs a mutation read. This is the deliberate trade-off of an escape hatch: full flexibility, coarse lineage. See [Arguments shared across steps](../user-guide/common-step-arguments.qmd) for the arguments this step shares with the others. Parameters ---------- mutations Mapping from output column name to a callable taking the data frame and returning that column's value (a narwhals expression or series). Must be a non-empty ``dict`` of ``str`` names to callables. role Role assigned to any *new* columns the mutations create (see `Roles`). Columns overwritten in place keep their existing role. Default ``"feature"``. id Stable step identifier. Defaults to ``"mutate"``; a second step of this type in the same recipe becomes ``"mutate_2"``, and passing an ``id`` already used in the recipe is an error. Examples -------- ``x_sq`` is added from an expression over ``x``; ``x`` itself is overwritten in place: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepMutate ``` ```{python} df = pd.DataFrame({"x": [1.0, 2.0, 3.0]}) df ``` Specifying the step touches no data: ```{python} recipe = Recipe().add( StepMutate({"x_sq": lambda df: df["x"] ** 2, "x": lambda df: df["x"] + 1}) ) recipe ``` `fit()` runs the mutations once on the training data frame to read off which columns they add and with what dtypes: ```{python} fitted = recipe.fit(df) fitted ``` `transform()` applies them together, so every mutation sees the original data frame; ``x_sq`` squares the incoming ``x``, not the overwritten one: ```{python} fitted.transform(df) ``` ## Fitted recipes What Recipe.fit() returns: an immutable, fitted pipeline you can apply to new data. Serialization methods are listed under Serialization below. FittedRecipe(steps: 'list[Step]', roles: 'Roles | None' = None, lineage: 'Lineage | None' = None, schema: 'Schema | None' = None) A trained pipeline: applies statistics learned at fit time to new data. A `FittedRecipe` is what `Recipe.fit()` returns. It contains all the information it needs to be able to apply the transformations to new data: ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize, StepDummy from mlfeatures import Selectors as s from mlfeatures.data import credit credit = credit.drop_nulls() ``` ```{python} recipe = ( Recipe(data=credit, target="Status") .add(StepNormalize(s.numeric_features())) .add(StepDummy(s.nominal_features())) ) fitted = recipe.fit(credit) ``` The `repr` shows the columns each step resolved to: ```{python} fitted ``` Use `transform()` to apply the recipe to new data and `summary()` to inspect the resulting columns. A trained recipe can be saved and restored with `to_json()` and `from_json()` (or the `dict` and YAML equivalents). Attributes ---------- steps The trained steps, in the order they run. roles The role assignments after fitting, including any columns the steps added. lineage How each output column was derived from the input columns, as a `Lineage`, or ``None`` if the recipe was built without one. schema The `Schema` of the training data, which `transform()` checks new data against, or ``None`` if the recipe was built without one. transform(self, data: 'DataFrame') -> 'DataFrame' Apply each trained step, in order, to new data. Every step applies the statistics stored at fit time. Steps that only act on training samples (such as row filters) are skipped, as are steps whose selection matched no columns. The result is a data frame of the same type as ``data``. Parameters ---------- data The data frame to transform. Its columns and dtypes must match the training data; a mismatch raises an error naming the difference. Raises ------ StepError If a step fails while transforming; the error names the step and the columns it was working on. Examples -------- ``transform()`` applies the trained recipe to new data, returning a data frame with the columns the recipe learned at fit time: ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize, StepDummy from mlfeatures import Selectors as s from mlfeatures.data import credit credit = credit.drop_nulls() ``` ```{python} recipe = ( Recipe(data=credit, target="Status") .add(StepNormalize(s.numeric_features())) .add(StepDummy(s.nominal_features())) ) fitted = recipe.fit(credit) ``` ```{python} result = fitted.transform(credit.head(5)) result ``` summary(self) -> 'DataFrame' The columns the recipe produces, as a tidy data frame. One row per output column, with its dtype, role, and the step that created it (``"original"`` for columns passed through from the input). Use it to see which columns the trained recipe will hand to a model and which step each came from. For where a single column came from, or what it descends from, use the `Lineage` in the ``lineage`` attribute. Raises ------ ValueError If the recipe was constructed without a lineage. Examples -------- After fitting, the summary reflects the transformed columns: the nominal columns have been expanded into dummy indicators (source ``"dummy"``) while the normalized numeric columns keep their feature role: ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize, StepDummy from mlfeatures import Selectors as s from mlfeatures.data import credit credit = credit.drop_nulls() ``` ```{python} recipe = ( Recipe(data=credit, target="Status") .add(StepNormalize(s.numeric_features())) .add(StepDummy(s.nominal_features())) ) fitted = recipe.fit(credit) ``` ```{python} fitted.summary() ``` ## Lineage The column-lineage DAG a fitted recipe maintains: per-column provenance and dtype history, plus the queries that back has_source. Lineage() -> 'None' The record of where every column came from, and what happened to it. A recipe can change a data frame a lot: it adds columns (dummy indicators, polynomial terms), removes others (the categorical a dummy step consumed), and changes dtypes in place (an integer column becomes float after normalizing). After a few steps the output no longer looks much like the input, and column names alone do not say why a column exists. A ``Lineage`` keeps that history so a fitted recipe can answer questions such as "which step produced ``Home_rent``?", "which original columns does it depend on?" and "what dtype did ``Age`` have before it was normalized?". The same record backs ``summary()`` on a fitted recipe and the ``has_source`` and ``has_ancestor`` selectors, which pick columns by where they came from rather than by name. It is stored as a graph with one node per column (a `ColumnNode`). Each produced column points at its **parents**, the columns it was built from, so following those links back through the steps gives its **ancestors**: every column it ultimately descends from. A column that was in the input data has no parents and a ``source`` of ``"original"``; a column added by a step has the step's ``id`` as its ``source``. Columns come in two kinds: - **Live** columns are the ones currently in the data frame, in column order. These are what ``lineage["name"]``, ``"name" in lineage``, ``len(lineage)``, ``columns`` and ``dtypes`` describe. - **Removed** columns were dropped by a step. They are kept (see ``removed``) instead of being forgotten, because a live column's history often runs *through* one. A dummy indicator's parent is the categorical it was encoded from; if that categorical were forgotten when the dummy step dropped it, the indicator could no longer be traced to the original data. ``parents`` and ``ancestors`` therefore resolve removed columns too, and asking about a column that never existed raises ``KeyError``. The recipe builds the lineage and updates it after each step, so it is read rather than constructed: get it from ``FittedRecipe.lineage``. Examples -------- Here a small pipeline imputes missing values, rescales the numerics, and dummy-encodes the categoricals, composed step by step with ``.add()``: ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepImputeMean, StepNormalize, StepDummy from mlfeatures import Selectors as s from mlfeatures.data import credit ``` ```{python} recipe = ( Recipe(target="Status") .add(StepImputeMean(s.numeric_features())) .add(StepNormalize(s.numeric_features())) .add(StepDummy(s.nominal_features())) ) fitted = recipe.fit(credit) lineage = fitted.lineage lineage.summary() ``` ``Age`` stayed in place through the numeric steps, so its ``source`` is still ``"original"``, but ``dtype_history`` records the integer to float cast that `StepNormalize` applied: ```{python} lineage["Age"].source, lineage["Age"].dtype_history ``` ``Home`` was expanded into indicators and dropped. ``columns_from_source`` grabs everything a step produced: ```{python} lineage.columns_from_source("dummy") ``` ``ancestors`` traces an indicator back through the now-removed ``Home`` column: ```{python} lineage.ancestors("Home_rent") ``` Lineage.removed Archived nodes of the columns that steps have removed. In removal order. Each node has ``removed_by`` set to the id of the step that dropped it. These are the intermediates that `parents` and `ancestors` trace through; a column dropped and later re-created under the same name appears here once per removal. Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepDummy from mlfeatures import Selectors as s from mlfeatures.data import credit ``` ```{python} recipe = Recipe(target="Status").add(StepDummy(s.nominal_features())) fitted = recipe.fit(credit) lineage = fitted.lineage ``` Each removed node records which step dropped it: ```{python} [(node.name, node.removed_by) for node in lineage.removed] ``` summary(self, include_removed: 'bool' = False) -> 'DataFrame' The lineage as a tidy data frame. Columns ``name``, ``dtype``, ``roles``, ``source``, ``sparse``: one row per live column, in data frame order. ``dtype`` is the dtype category (``"float"``, ``"int"``, ``"str"``, ``"categorical_unordered"``, ...) and ``roles`` is the sorted role set joined with ``", "``. The result is always a polars ``DataFrame``, whatever backend the recipe was fitted on. This is the same table `FittedRecipe.summary` returns for the live columns. Reach for it when you also want the removed columns (``include_removed=True``) and which step dropped each; use `parents` and `ancestors` to trace a single column. Parameters ---------- include_removed If ``True``, append a row for each removed column (in removal order) and add two columns: ``parents``, the immediate parent columns joined with ``", "``, and ``removed_by``, the id of the step that dropped the column (null for live columns). Default ``False``. Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize, StepDummy from mlfeatures import Selectors as s from mlfeatures.data import credit recipe = ( Recipe(target="Status") .add(StepNormalize(s.numeric_features())) .add(StepDummy(s.nominal_features())) ) fitted = recipe.fit(credit) lineage = fitted.lineage ``` One row per live column, mixing the normalized numerics (source ``"original"``, now ``float``) with the dummy indicators (source ``"dummy"``): ```{python} lineage.summary() ``` With ``include_removed=True`` the dropped categoricals appear too, along with each column's parents: ```{python} lineage.summary(include_removed=True) ``` columns_from_source(self, step_id: 'str') -> 'list[str]' Live columns produced by the step with ``id == step_id``. This is what the ``has_source`` selector resolves to. A step's ``id`` is the one passed to it, or by default the step type's short name (``"dummy"`` for `StepDummy`); a second step of the same type in one recipe becomes ``"dummy_2"``. Parameters ---------- step_id The producing step's ``id``, or ``"original"`` for the input columns that survive to the live lineage. Returns ------- list of str Matching column names in data frame order; empty if the step produced no live column or no step has that id. Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize, StepDummy from mlfeatures import Selectors as s from mlfeatures.data import credit recipe = ( Recipe(target="Status") .add(StepNormalize(s.numeric_features())) .add(StepDummy(s.nominal_features())) ) fitted = recipe.fit(credit) lineage = fitted.lineage ``` Select every column a step produced (the dummy indicators): ```{python} lineage.columns_from_source("dummy") ``` ``"original"`` picks the inputs that survive to the output (the numerics and the target are still here; the categoricals were consumed by the dummy step): ```{python} lineage.columns_from_source("original") ``` parents(self, name: 'str') -> 'list[str]' Immediate parent columns of ``name`` (live or archived). Parameters ---------- name A column that is live or has been removed. Returns ------- list of str The columns ``name`` was built from; empty for an original column. Raises ------ KeyError If no column called ``name`` ever existed. Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepDummy from mlfeatures import Selectors as s from mlfeatures.data import credit recipe = Recipe(target="Status").add(StepDummy(s.nominal_features())) fitted = recipe.fit(credit) lineage = fitted.lineage ``` Each indicator's immediate parent is the column it was encoded from: ```{python} lineage.parents("Home_rent") ``` ancestors(self, name: 'str') -> 'set[str]' All columns ``name`` descends from, transitively. Walks ``parent_cols`` through archived nodes too, so a column traces back through removed intermediates (e.g. a polynomial term back to a distance column back to the numeric features it was computed from). The result is an unordered set; wrap it in ``sorted()`` for stable display. Parameters ---------- name A column that is live or has been removed. Returns ------- set of str Every column ``name`` descends from; empty for an original column. Raises ------ KeyError If no column called ``name`` ever existed. Examples -------- ``ancestors`` walks the whole chain, even through columns that later steps removed. Here `StepClassDistance` builds ``distance_good`` from the numeric features, then `StepPolynomial` consumes ``distance_good`` and expands it into polynomial terms: ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepImputeMean, StepClassDistance from mlfeatures import StepPolynomial from mlfeatures import Selectors as s from mlfeatures.data import credit ``` ```{python} recipe = ( Recipe(target="Status") .add(StepImputeMean(s.numeric_features())) .add(StepClassDistance(s.numeric_features(), target="Status")) .add(StepPolynomial(s.col("distance_good"), degree=2)) ) fitted = recipe.fit(credit) lineage = fitted.lineage lineage.columns ``` A polynomial term traces back through the now-removed ``distance_good`` to the original features it was built from: ```{python} sorted(lineage.ancestors("distance_good_1")) ``` ColumnNode(name: 'str', dtype: 'nw.dtypes.DType', roles: 'set[str]', source: 'str', parent_cols: 'list[str]', dtype_history: 'list[nw.dtypes.DType]', sparse: 'bool' = False, removed_by: 'str | None' = None) -> None One column's lineage record. A node is mutable: an in-place step (e.g. `StepNormalize`) updates ``dtype`` and appends to ``dtype_history`` without creating a new node, and a step that drops a column sets ``removed_by`` and the node is archived rather than discarded, so ancestry still resolves through it. Live nodes are read with ``lineage["name"]``; archived ones through `Lineage.removed`. Attributes ---------- name Current column name. dtype Current narwhals dtype (may change across steps). roles Current role names, as a set (unordered). source Which step *produced* this column: ``"original"`` for an input column, otherwise the producing step's ``id``. An in-place transform does not change ``source``: it does not *produce* a column. parent_cols The input column name(s) this column descends from. Empty for original columns and for parent-less produced columns (e.g. those added by `StepIntercept`). dtype_history The dtype trajectory: the creation dtype followed by an entry for each step that *changed* the dtype (not one per step boundary). sparse Whether this column is currently sparse. removed_by ``None`` while the column is live; set to the dropping step's ``id`` once it has been removed from the data frame and archived. Examples -------- Nodes are read off a fitted recipe's `Lineage` by column name. Here a numeric column is normalized in place, and `StepDummy` then expands a categorical column: ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize, StepDummy from mlfeatures import Selectors as s from mlfeatures.data import credit ``` ```{python} recipe = ( Recipe(target="Status") .add(StepNormalize(s.numeric_features())) .add(StepDummy(s.nominal_features())) ) fitted = recipe.fit(credit) lineage = fitted.lineage node = lineage["Home_rent"] node.name, node.source, node.parent_cols ``` ``Age`` was normalized in place, so it is still an ``"original"`` column but its dtype history records the integer to float cast: ```{python} lineage["Age"].source, lineage["Age"].dtype_history ``` ``Home`` was consumed by the dummy step, so it is archived with ``removed_by`` set: ```{python} [(n.name, n.removed_by) for n in lineage.removed if n.name == "Home"] ``` ## Serialization Save a fitted recipe to a diffable JSON or YAML format and reload it, or strip fit-only artifacts with minimize(). to_dict(recipe: 'FittedRecipe') -> 'dict[str, Any]' Serialize a `FittedRecipe` to a diffable, JSON-safe ``dict``. A fitted recipe has to outlive the process that fit it: it is saved next to a model, loaded elsewhere to transform new data, and reviewed in a pull request when it changes. So the ``dict`` captures what `transform()` needs (every step's hyperparameters and learned statistics, plus the roles, training schema, and lineage) and nothing that ties it to the training process: no training data, closures, or environments. The ``dict`` holds plain data only (strings, numbers, booleans, lists, and mappings), so it round-trips through `from_dict` and is stable enough to diff in code review. Unlike a pickle, it can be read and checked without running anything, and loading it only builds classes from trusted packages (see `from_dict`). Use `to_json` or `to_yaml` to write it to a file, and the ``dict`` itself when embedding the recipe in a larger payload. It has these keys, in this order: - ``mlfeatures_version``: the version of mlfeatures that wrote it. - ``format_version``: the layout version, which `from_dict` checks. - ``roles``: the role of each column. - ``schema``: the training data's column names and dtypes, or ``None``. - ``lineage``: the column lineage, or ``None``. - ``steps``: for each step, its class name and its state (the hyperparameters and the statistics learned at fit time). Parameters ---------- recipe The fitted recipe to serialize. Returns ------- dict The payload described above. Raises ------ TypeError If a step holds something that cannot be serialized: a raw polars or narwhals selector, a ``dateutil`` rule, or a function (``StepMutate``). Warns ----- UserWarning If a step, or a dataclass in its fit state, comes from a package that `from_dict` refuses by default (see `from_dict`). The payload is still produced, but loading it needs the step registered or passed as ``trusted``. Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize, to_dict from mlfeatures import Selectors as s from mlfeatures.data import credit credit = credit.drop_nulls() ``` ```{python} recipe = Recipe().add(StepNormalize(s.numeric_features())) fitted = recipe.fit(credit) payload = to_dict(fitted) payload["steps"][0]["type"] ``` from_dict(data: 'dict[str, Any]', *, trusted: 'Iterable[type]' = ()) -> 'FittedRecipe' Reconstruct a `FittedRecipe` from the ``dict`` produced by `to_dict`. The payload is treated as untrusted data: it can name only classes from ``mlfeatures``, from packages that register a step under the ``mlfeatures.steps`` entry-point group, and from the packages of the classes passed as ``trusted``. Each class must also be of the right kind (a `Step` subclass for a step, a dataclass for fit state). Loading never calls anything else the payload names, and a name is checked before its module is imported. The values inside the payload are not validated. A payload without a ``format_version`` is read as the current version. One with a different version is refused, because the layout changed incompatibly; fit the recipe again and save it again. Parameters ---------- data The ``dict`` produced by `to_dict`. trusted Classes whose top-level packages the payload may also name classes from, for a custom step that is not registered (one defined in a script or notebook, or still under development). Pass only classes you wrote or trust: a package listed here is imported as the payload asks. Defaults to none. Returns ------- FittedRecipe The recipe, ready to `FittedRecipe.transform` new data. Raises ------ ValueError If the payload is not a mapping with ``roles`` and ``steps``, has a ``format_version`` this mlfeatures does not read, names a class outside the trusted packages, or names something that is not a step or dataclass. Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize, from_dict, to_dict from mlfeatures import Selectors as s from mlfeatures.data import credit credit = credit.drop_nulls() ``` ```{python} recipe = Recipe().add(StepNormalize(s.numeric_features())) fitted = recipe.fit(credit) restored = from_dict(to_dict(fitted)) restored ``` to_json(recipe: 'FittedRecipe', *, indent: 'int' = 2) -> 'str' Serialize a `FittedRecipe` to a diffable JSON string. The string is the `to_dict` payload as strictly valid JSON (non-finite floats are encoded explicitly, never as a bare ``NaN``). It needs no optional dependency, so it is the default choice for storing a recipe next to a model. Warns like `to_dict` when the recipe names a class that `from_json` refuses by default. Parameters ---------- recipe The fitted recipe to serialize. indent Spaces of indentation per level. Defaults to 2. Returns ------- str The JSON text. Raises ------ TypeError As for `to_dict`. Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize, to_json from mlfeatures import Selectors as s from mlfeatures.data import credit credit = credit.drop_nulls() ``` ```{python} recipe = Recipe().add(StepNormalize(s.numeric_features())) fitted = recipe.fit(credit) text = to_json(fitted) text[:200] ``` A smaller `indent` gives a more compact file. ```{python} compact = to_json(fitted, indent=0) compact[:200] ``` from_json(text: 'str', *, trusted: 'Iterable[type]' = ()) -> 'FittedRecipe' Reconstruct a `FittedRecipe` from the JSON produced by `to_json`. Takes the same ``trusted`` argument as `from_dict` and raises the same ``ValueError`` for a class outside the trusted packages. Text that is not valid JSON raises ``json.JSONDecodeError`` (a ``ValueError`` subclass). Parameters ---------- text The JSON text produced by `to_json`. trusted Classes whose top-level packages the payload may also name classes from; see `from_dict`. Defaults to none. Returns ------- FittedRecipe The recipe, ready to `FittedRecipe.transform` new data. Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize, from_json, to_json from mlfeatures import Selectors as s from mlfeatures.data import credit credit = credit.drop_nulls() ``` ```{python} recipe = Recipe().add(StepNormalize(s.numeric_features())) fitted = recipe.fit(credit) restored = from_json(to_json(fitted)) restored.transform(credit).head() ``` to_yaml(recipe: 'FittedRecipe') -> 'str' Serialize a `FittedRecipe` to a diffable YAML string. The same `to_dict` payload as `to_json`, written as YAML with the keys in their stable order and a block layout that diffs cleanly in review, so the two formats round-trip identically. Choose it over `to_json` when people will read or review the file; it needs the optional ``pyyaml`` package. Warns like `to_dict` when the recipe names a class that `from_yaml` refuses by default. Parameters ---------- recipe The fitted recipe to serialize. Returns ------- str The YAML text. Raises ------ ImportError If the optional ``pyyaml`` package is not installed (``pip install mlfeatures[yaml]``). TypeError As for `to_dict`. Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize, to_yaml from mlfeatures import Selectors as s from mlfeatures.data import credit credit = credit.drop_nulls() ``` ```{python} recipe = Recipe().add(StepNormalize(s.numeric_features())) fitted = recipe.fit(credit) text = to_yaml(fitted) text[:200] ``` from_yaml(text: 'str', *, trusted: 'Iterable[type]' = ()) -> 'FittedRecipe' Reconstruct a `FittedRecipe` from the YAML produced by `to_yaml`. Takes the same ``trusted`` argument as `from_dict` and raises the same ``ValueError`` for a class outside the trusted packages. The YAML is parsed without building arbitrary objects, and the class names inside it are restricted by `from_dict`, as they are for JSON. Parameters ---------- text The YAML text produced by `to_yaml`. trusted Classes whose top-level packages the payload may also name classes from; see `from_dict`. Defaults to none. Returns ------- FittedRecipe The recipe, ready to `FittedRecipe.transform` new data. Raises ------ ImportError If the optional ``pyyaml`` package is not installed (``pip install mlfeatures[yaml]``). Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize, from_yaml, to_yaml from mlfeatures import Selectors as s from mlfeatures.data import credit credit = credit.drop_nulls() ``` ```{python} recipe = Recipe().add(StepNormalize(s.numeric_features())) fitted = recipe.fit(credit) restored = from_yaml(to_yaml(fitted)) restored.transform(credit).head() ``` minimize(recipe: 'FittedRecipe') -> 'FittedRecipe' Return a `FittedRecipe` that keeps only what ``transform()`` needs. Each step decides what it can drop: a step that keeps something only for inspection after fitting, or only because fitting needed it, returns a lighter version of itself that transforms identically. A step that has nothing to drop is kept as is, shared with ``recipe`` rather than copied, and ``recipe`` itself is never modified. The roles, schema, and lineage are kept, so the minimized recipe still validates new data at the boundary and reports its lineage. Call it before `to_dict`, `to_json`, or `to_yaml` when the recipe is going to be shipped with a model, so the saved file carries only what scoring needs; the writers save the recipe as it is and do not minimize it. No shipped step currently holds anything to drop, so today the result is an equivalent recipe. Parameters ---------- recipe The fitted recipe to minimize. Returns ------- FittedRecipe A new recipe with each step minimized. Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import Recipe, StepNormalize, minimize from mlfeatures import Selectors as s from mlfeatures.data import credit credit = credit.drop_nulls() ``` ```{python} recipe = Recipe().add(StepNormalize(s.numeric_features())) fitted = recipe.fit(credit) small = minimize(fitted) small.transform(credit).head() ``` to_dict(self) -> 'dict[str, object]' Serialize to a diffable, JSON-safe ``dict``. See `mlfeatures.to_dict` for the layout. Use the ``dict`` when you are embedding the recipe in a larger payload or handing it to your own writer; for a file, prefer `to_json` or `to_yaml`. Returns ------- dict Plain data holding the roles, schema, lineage, and every step's hyperparameters and learned statistics. Raises ------ TypeError If a step holds something that cannot be serialized, such as a raw polars or narwhals selector, a ``dateutil`` rule, or a function. Warns ----- UserWarning If a step comes from a package that `mlfeatures.from_dict` refuses by default. from_dict(data: 'dict[str, object]', *, trusted: 'Iterable[type]' = ()) -> "'FittedRecipe'" Reconstruct a fitted recipe from `FittedRecipe.to_dict` output. See `mlfeatures.from_dict`. Parameters ---------- data The ``dict`` produced by `FittedRecipe.to_dict`. trusted Classes whose top-level packages the payload may also name classes from, for a step that is not registered. Defaults to none. Raises ------ ValueError If the payload is malformed, has a ``format_version`` this mlfeatures does not read, or names a class outside ``mlfeatures``, the registered step plugins, and the packages of the ``trusted`` classes. to_json(self, *, indent: 'int' = 2) -> 'str' Serialize to a diffable JSON string. See `mlfeatures.to_json`. JSON needs no optional dependency and is readable by any tool, so it is the default choice for storing a recipe next to a model. Parameters ---------- indent Spaces of indentation per level. Defaults to 2. Returns ------- str The JSON text. Load it again with `FittedRecipe.from_json`. Raises ------ TypeError As for `FittedRecipe.to_dict`. Warns ----- UserWarning As for `FittedRecipe.to_dict`. from_json(text: 'str', *, trusted: 'Iterable[type]' = ()) -> "'FittedRecipe'" Reconstruct a fitted recipe from `FittedRecipe.to_json` output. See `mlfeatures.from_json`. Parameters ---------- text The JSON text produced by `FittedRecipe.to_json`. trusted Classes whose top-level packages the payload may also name classes from, for a step that is not registered. Defaults to none. Raises ------ ValueError As for `FittedRecipe.from_dict`; text that is not valid JSON raises ``json.JSONDecodeError``, a ``ValueError`` subclass. to_yaml(self) -> 'str' Serialize to a diffable YAML string. See `mlfeatures.to_yaml`. Choose YAML over JSON when people will read or review the file, since the block layout diffs more cleanly. It needs the optional ``pyyaml`` package. Returns ------- str The YAML text. Load it again with `FittedRecipe.from_yaml`. Raises ------ ImportError If the optional ``pyyaml`` package is not installed. TypeError As for `FittedRecipe.to_dict`. Warns ----- UserWarning As for `FittedRecipe.to_dict`. from_yaml(text: 'str', *, trusted: 'Iterable[type]' = ()) -> "'FittedRecipe'" Reconstruct a fitted recipe from `FittedRecipe.to_yaml` output. See `mlfeatures.from_yaml`. Parameters ---------- text The YAML text produced by `FittedRecipe.to_yaml`. trusted Classes whose top-level packages the payload may also name classes from, for a step that is not registered. Defaults to none. Raises ------ ValueError As for `FittedRecipe.from_dict`. ImportError If the optional ``pyyaml`` package is not installed. minimize(self) -> "'FittedRecipe'" Return a recipe that keeps only what `transform()` needs. See `mlfeatures.minimize`. Each step drops what it can: anything kept only for inspection after fitting, or only because fitting needed it. The result transforms new data identically and ``self`` is left unchanged. A step with nothing to drop is shared with ``self`` rather than copied. Call it before saving or shipping a recipe, so the artifact carries only what scoring needs. `FittedRecipe.to_dict` and the JSON and YAML writers save the recipe as it is and do not minimize it. No shipped step currently holds anything to drop, so today this returns an equivalent recipe. ## Interop Adapters for using recipes inside other ecosystems. RecipeTransformer(recipe: 'Recipe') Wrap a `Recipe` as a scikit-learn transformer. Use it to put a recipe in front of any scikit-learn model, so the feature engineering is trained, cross-validated, and tuned together with the model instead of being applied by hand beforehand. Usable as a single step in a `sklearn.pipeline.Pipeline`: ```python from mlfeatures import RecipeTransformer pipe = Pipeline([ ("recipe", RecipeTransformer(recipe)), ("model", LogisticRegression()), ]) pipe.fit(X_train, y_train) ``` The wrapped recipe is untrained: ``fit()`` trains it, and ``transform()`` applies the trained result. The recipe is stored verbatim so that `sklearn.base.clone()` (and therefore cross-validation / grid search) round-trips correctly; `Recipe` is immutable, so this is safe. Step hyperparameters are tunable through sklearn's nested parameter names, keyed on step ``id``: ``recipe____``, for example ``GridSearchCV(pipe, {"recipe__recipe__corr__threshold": [0.8, 0.9]})`` when the transformer is named ``"recipe"`` in the pipeline. A step's ``id`` and ``columns`` are not tunable. It implements `get_feature_names_out()` and therefore composes inside a `sklearn.compose.ColumnTransformer` and supports ``set_output(transform="pandas" | "polars")``. **Target handling.** sklearn keeps ``X`` and ``y`` apart, while a recipe identifies the target by its ``"target"`` role. At fit time ``y`` is joined onto ``X`` under the recipe's target column name, and ``transform()`` returns the feature columns only, with the target column removed. Passing ``y`` to a recipe with no ``"target"`` role raises a ``ValueError``, as does a recipe with more than 1 target column. A step that applies to the target column as one of its input columns (for example ``StepNormalize(["target"])``) also raises a ``ValueError`` at fit time, because sklearn's ``transform()`` never receives ``y``; transform the target outside the pipeline instead (for example with ``sklearn.compose.TransformedTargetRegressor``). A step that uses the target only at fit time, such as ``StepPls`` or ``StepClassDistance``, is fine. With no ``y`` (an unsupervised recipe), ``X`` is used as given. Parameters ---------- recipe The untrained recipe to wrap. Required. Attributes ---------- recipe The untrained recipe passed to the constructor. fitted_ The trained recipe; set by ``fit()``. feature_names_in_ Column names of the ``X`` seen by ``fit()``. n_features_in_ Number of columns of the ``X`` seen by ``fit()``. feature_names_out_ Column names of the output of ``transform()``. Raises ------ NotFittedError If ``transform()`` or ``get_feature_names_out()`` is called before ``fit()``. Examples -------- Wrap a recipe and drive it with sklearn's ``fit`` / ``transform`` API: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepNormalize, StepDummy from mlfeatures import Selectors as s from mlfeatures import RecipeTransformer ``` ```{python} X =pd.DataFrame( {"age": [25, 41, 33, 52], "city": ["NYC", "LA", "NYC", "SF"]} ) rec = ( Recipe() .add(StepNormalize(s.numeric_features())) .add(StepDummy(s.nominal_features())) ) fitted = RecipeTransformer(rec).fit(X) fitted.transform(X) ``` `get_feature_names_out()` reports the produced feature names, so the transformer composes inside a `sklearn.compose.ColumnTransformer`: ```{python} fitted.get_feature_names_out() ``` ## Types & selectors Selector DSL and the schema/type vocabulary that steps are written against. Selectors() Namespace of factory methods for built-in mlfeatures column selectors. All factories return a `FeaturesSelector` that composes with ``&`` / ``|`` / ``~`` / ``-``. Prefer a selector to a hard-coded list of column names. A list goes stale as soon as an earlier step adds or removes columns (a dummy step replaces ``city`` with ``city_LA`` and ``city_NYC``), while a selector is resolved against the columns each step actually sees, so it keeps working when the data frame changes. Examples -------- A selector stands in for an explicit column list and is resolved against the data frame at fit time. Here ``starts_with("x")`` picks up ``x1`` and ``x2`` but leaves ``y`` untouched: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepNormalize from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame( {"x1": [1.0, 2.0, 3.0], "x2": [4.0, 5.0, 6.0], "y": [7.0, 8.0, 9.0]} ) recipe = Recipe().add(StepNormalize(s.starts_with("x"))) fitted = recipe.fit(df) fitted.transform(df) ``` FeaturesSelector() Base class for all mlfeatures-native column selectors. Subclasses implement `resolve`. Instances compose with ``&`` (intersection), ``|`` (union), ``~`` (complement), and ``-`` (difference). A mlfeatures-native selector must **lead** any cross-family expression: ``mlfeatures_sel & cs.numeric()`` works (the right operand is coerced via `wrap`), but ``cs.numeric() & mlfeatures_sel`` does not: polars raises ``TypeError`` and narwhals silently produces a broken ``Expr``, neither of which mlfeatures can intercept. Use `Selectors.wrap` to put a polars / narwhals selector first. Prefer these over ``polars.selectors`` when a step should respect roles or column provenance. A polars selector knows only names and dtypes, so ``cs.numeric()`` also matches the target; mlfeatures selectors can restrict to the ``feature`` role or to columns derived from a given source. A polars selector is still accepted anywhere a selector is. Union(*args, **kwargs) ColSchema(columns: 'list[str] | None' = None, dtypes: 'dict[str, str] | None' = None) Column schema: the names and dtypes a step reports for a column set. Carries the column names and their dtype names: enough for a step to describe what it consumed (``schema_in``) and produced (``schema_out``). This is the lightweight step-facing report; the recipe-side column-lineage DAG that tracks roles, source, sparsity, and provenance is `Lineage`. Not to be confused with `SchemaInfo` (what a step is handed at fit time) or `Schema` (the snapshot of the training data that ``transform()`` validates new data against). Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import ColSchema ``` ```{python} schema = ColSchema(columns=["age", "city"], dtypes={"age": "Int64", "city": "String"}) schema.columns, schema.dtypes ``` SchemaInfo(columns: 'list[str] | None' = None, dtypes: 'dict[str, str] | None' = None, roles: 'Roles | None' = None, lineage: "'Lineage | None'" = None, producing_steps: "'dict[str, Step] | None'" = None) Schema-derived context handed to `Step.fit()`. Carries the current column names, their dtype names, and the live `Roles`. In practice a step reads only ``roles`` (for selector resolution). The recipe-side column-lineage DAG (`mlfeatures.lineage.Lineage`) is maintained separately by the recipe and is not handed to steps for their own logic; ``lineage`` and ``producing_steps`` are populated by the recipe purely so provenance selectors (``has_source`` / ``has_ancestor``) can resolve against the DAG at fit time. Both are ``None`` outside a recipe fit. Not to be confused with `ColSchema` (what a step reports back) or `Schema` (the snapshot of the training data used for boundary checks). Examples -------- Build a snapshot from a data frame with `from_frame`; steps read ``columns``, ``dtypes``, and ``roles`` off it during ``fit()``: ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import SchemaInfo, _frame ``` ```{python} frame = _frame.from_native(pd.DataFrame({"x": [1, 2], "y": ["a", "b"]})) info = SchemaInfo.from_frame(frame) info.columns, info.dtypes ``` Roles(mapping: 'dict[str, set[str]] | None' = None) Column → set of role names. Every column carries **zero or more** roles stored as a ``set[str]``. The standard roles are ``"target"``, ``"feature"``, and ``"case_weights"``; users may register arbitrary custom roles. A column may hold several roles at once, but nonsensical combinations are rejected at assignment time: ``"target"`` and ``"feature"`` cannot share a column. A column that carries no role is not selected by role selectors. Note that when a recipe declares no ``"feature"`` columns at all, fitting assigns the role to every column that is not a target or a case-weights column, custom roles included; declare features explicitly to keep, say, an ID column out of them. Examples -------- Construct from a column → roles mapping, then query it: ```{python} #| echo: false #| output: false from mlfeatures import Roles ``` ```{python} roles = Roles( {"price": {"target"}, "age": {"feature"}, "city": {"feature"}} ) roles.columns_with_role("feature"), roles.of("price") ``` Mode(*values) Shape of a step's input/output relationship. Every concrete step class declares one ``mode``. The framework reads it for two things: how the step's columns are recorded in the column lineage, and whether ``keep_original_cols`` is fixed or configurable (see `KeepOriginals`). The members, with the value ``keep_original_cols`` takes for each: - ``ONE_TO_ONE``: each input column produces exactly one output column, e.g. `StepNormalize`. Fixed at ``False``. - ``ONE_TO_MANY``: each input column produces one or more output columns, e.g. `StepDummy`. Configurable, default ``False``. - ``MANY_TO_MANY``: a set of input columns produces a new set of output columns, e.g. `StepPca`. Configurable, default ``False``. - ``REMOVING``: input columns are dropped and none are created, e.g. `StepDropZeroVariance`. Fixed at ``False``. - ``ADDING``: new columns appear with no corresponding input, e.g. `StepIntercept`. Fixed at ``True``. - ``ROW_OP``: no change to the columns, e.g. `StepFilter`. Fixed at ``True``. Row steps only act while the recipe is fitted and are skipped by ``transform()`` on new data. - ``UNCONSTRAINED``: the relationship cannot be declared in advance, e.g. `StepMutate`. Fixed at ``True``. Examples -------- Each step class declares its mode; for example `StepDummy` expands one column into many: ```{python} #| echo: false #| output: false from mlfeatures import Mode, StepDummy ``` ```{python} StepDummy.mode, [m.value for m in Mode] ``` KeepOriginals(*values) Whether a step's ``keep_original_cols`` is fixed or up to the caller. A step does not declare this: it follows from `Mode`, via `KeepOriginals.for_mode`. A step that turns its input columns into derived ones (``ONE_TO_MANY``, ``MANY_TO_MANY``) is ``CONFIGURABLE``, because keeping the sources beside the derived columns is a legitimate thing to want; every other mode has only one sensible answer, so ``Step.__init__`` fixes the value and ``keep_original_cols`` cannot be set to anything else. The attribute is a read-only property on every step, configurable or not: its value is settled when the step is constructed. Examples -------- ```{python} #| echo: false #| output: false from mlfeatures import KeepOriginals, Mode, StepDummy ``` ```{python} KeepOriginals.for_mode(StepDummy.mode), KeepOriginals.for_mode(Mode.ROW_OP) ``` for_mode(mode: 'Mode') -> "'KeepOriginals'" The policy that a step of ``mode`` must follow. fixed_value(self) -> 'bool | None' The mandated ``keep_original_cols``, or ``None`` if configurable. Schema(dtypes: 'nw.Schema', roles: 'Roles', transform_required: 'dict[str, bool]') -> None A structural snapshot of the training data used for boundary checks. Captured at ``Recipe.fit()`` and exposed as ``FittedRecipe.schema``. Holds the training :class:`narwhals.Schema` (column names and dtypes), the role assignments, and a precomputed per-column flag for whether each column is required at ``transform()`` time. Not to be confused with `ColSchema` (what a step reports about the columns it consumed and produced) or `SchemaInfo` (what a step is handed at fit time). Dtypes are compared exactly: a column that was ``Float64`` at fit must be ``Float64`` in new data, and parametrized dtypes must agree on their parameters (a ``Datetime`` in microseconds does not match one in nanoseconds, nor does an ``Enum`` with different categories). Cast new data to the training dtypes before transforming. Attributes ---------- dtypes The training data frame's column dtypes, as a narwhals schema: an ordered name→dtype mapping. roles Role assignments of the input columns, as the data entered the recipe (after any role operation written before the first step). Role operations written after a step are not reflected here. transform_required Per-column flag: ``True`` if the column must be present in new data at ``transform()`` time. Computed at fit from role requirements and any ``update_role_requirements`` overrides. Read this rather than deriving the requirement from ``roles``: a role operation written after a step can change a column's requirement without changing the roles recorded here. Examples -------- The schema is built by the recipe; read it back from a fitted recipe: ```{python} import pandas as pd from mlfeatures import Recipe, StepNormalize from mlfeatures import Selectors as s df = pd.DataFrame({"x": [1.0, 2.0, 3.0], "y": [0, 1, 0]}) rec = Recipe(target="y", features="x").add( StepNormalize(s.numeric_features()) ) rec = rec.fit(df) rec.schema.dtypes.names() ``` check(self, frame: 'Frame', *, context: 'str') -> 'None' Validate ``frame`` against this snapshot. ``context`` is ``"fit"`` or ``"transform"``. At ``"fit"`` every schema column is required; at ``"transform"`` only columns flagged in ``transform_required`` are. In both contexts, columns that *are* present must match the snapshot dtype. Extra columns beyond the snapshot are ignored. Dtypes are compared exactly (see the class docstring). Parameters ---------- frame The data frame to validate. context ``"fit"`` or ``"transform"``. Any value other than ``"fit"`` is treated as ``"transform"``. ``Recipe.fit()`` checks the frame it just took the snapshot from, so at ``"fit"`` the check cannot fail in practice; it exists so both phases go through one code path. Raises ------ ValueError If a required column is missing, or a present column's dtype differs from the snapshot. Any(*args, **kwargs) Special type indicating an unconstrained type. - Any is compatible with every type. - Any assumed to have all methods. - All values assumed to be instances of Any. Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks. DataFrame(*args, **kwargs) ANY_DTYPE Sentinel type for `ANY_DTYPE` (a singleton). NUMERIC_DTYPES set() -> new empty set object set(iterable) -> new set object Build an unordered collection of unique elements. Union(*args, **kwargs) ## Datasets Example datasets bundled with the package, loaded on access as polars frames (`from mlfeatures.data import credit`). Used throughout the user guide and the examples. ## Developing The abstract Step base class and its lifecycle methods, for authoring new steps. Flattened so each method appears on the reference index. Step(id: 'str | None', default_id: 'str', *, keep_original_cols: 'bool | None' = None, output_role: 'str | None' = None) -> 'None' Abstract base class for a feature-engineering step. A step is constructed declaratively, fitted against training data to estimate and store statistics, and then applied to new data. **Everything a step needs is computed at fit time.** Whatever a step has to learn from data (statistics, level sets, a basis, the list of columns to drop) is estimated once from the training data frame and stored on the step. ``transform()`` only applies that stored state; it never re-estimates anything, however different the new data looks. This is what makes a fitted recipe reproducible and free of train-to-serve skew, and it holds for every step, so individual steps do not restate it. A step's ``columns`` selector is resolved once, against the training data frame's schema, when the recipe is fitted. A selector that matches nothing is not an error: the step is kept in the fitted recipe for inspection but never fitted and never run, making it the identity transform. What a step promises about the data frame it returns is *which* columns are present and what they are named, not where they sit. Column position is an implementation detail that may differ between steps and backends, so downstream code should select columns by name rather than by position. ``Step`` subclasses always run at transform time; `RowOp` subclasses never run on new data. There is intentionally no ``skip`` flag: whether a step runs at transform time is determined structurally by its type. A subclass' ``__init__`` stores its own arguments and then calls ``super().__init__()`` to hand the framework-owned ones to the base class: ```python class StepMaxAbs(Step): mode = Mode.ONE_TO_ONE def __init__(self, columns: Selector, *, id: str | None = None): self.columns = columns super().__init__(id, "max_abs") ``` See ``__init__`` for the arguments it takes. fit(self, training_data: 'Frame', info: 'SchemaInfo') -> "'Self'" Resolve selectors, estimate and store statistics, return the fitted step. Must be idempotent given the same training data. transform(self, new_data: 'Frame') -> 'Frame' Apply stored statistics to ``new_data``. Never re-estimates. resolve_selection(self, data: 'Frame', info: 'SchemaInfo') -> 'list[str]' Resolve this step's ``columns`` selector to concrete column names. This is the supported way for a step to find out which columns it was pointed at. Call it at the top of ``fit()`` and select from the data frame with the names it returns; narwhals' own ``frame.schema`` then gives the dtypes: ```python def fit(self, training_data, info): names = self.resolve_selection(training_data, info) selected = training_data.select(names) dtypes = {name: str(dt) for name, dt in selected.schema.items()} ... ``` The default resolves ``self.columns``, which is right for every selector-taking step, including ones that take a second selector for a different purpose: the primary input selector is always ``columns``. Override only if a step's primary input is named something else. Takes ``data`` as well as ``info`` because narwhals and polars selectors resolve against the data frame's schema rather than against the schema snapshot alone. The recipe also calls this before ``fit()`` so that a selection matching no columns makes the step the identity transform; a step that resolves its own selection therefore never has to handle the empty case itself. update_roles(self, roles: 'Roles') -> 'None' Update ``roles`` to reflect the column changes made by this step. Called by the recipe after each step is fitted and transformed. The default is a no-op; steps that add, remove, or rename columns override this to keep roles in sync with the live schema. schema_in(self) -> 'ColSchema' Schema of the columns this step consumed. Known after ``fit()``. schema_out(self) -> 'ColSchema' Schema of the columns this step produced. Known after ``fit()``. output_parents(self) -> 'dict[str, list[str]]' Map each column this step *produces* to its parent input column(s). Known after ``fit()``. The keys are exactly the columns this step adds to the data frame; each value lists the input columns that column descends from. The recipe consults this to populate the column-lineage DAG and validates the keys against the post-step data frame. The default returns ``{}``: correct for steps that create no new columns (in-place ``ONE_TO_ONE`` such as ``step_normalize``; ``REMOVING``; ``ROW_OP``). Steps that add columns override this to declare per-output provenance: ``ONE_TO_MANY`` (each ``a1, a2 ← a``), ``MANY_TO_MANY`` (every output ← the whole input set, as in ``step_pca`` and ``step_class_distance``), and ``ADDING`` (``step_intercept``, whose column has no parents and so maps to ``[]``). accepts_dtypes(self) -> 'AcceptedDtypes' Dtypes this step is valid to apply to. Return a set of narwhals dtype classes (`NUMERIC_DTYPES` is ready-made for numeric-only steps), or `ANY_DTYPE` to skip dtype validation entirely. The recipe checks the resolved selection's dtypes against this set before ``fit()`` runs and raises a ``TypeError`` naming the step, the offending column(s), and their dtypes, so a step never sees a column it declared itself invalid for. The check does not run again at ``transform()`` time: the schema snapshot already pins new data's dtypes to what was seen at fit. Step.produces_sparse Whether this step produces sparse output. produced_columns(self) -> 'list[str]' Ordered names of the columns this step *adds* to the data frame. Known after ``fit()``. Unlike ``output_parents()`` (a name→parents map, so its keys are necessarily unique), this is an ordered list that *preserves duplicates*: a step that would emit two columns with the same name reports that name twice. The recipe validates this list for uniqueness (both against the existing schema and within the step itself) *before* the step runs, which is the single centralized name-collision check every column-adding step relies on. Validating up front means the error is clean on every backend (polars raises a backend-specific error when two columns share a name; pandas silently keeps only one), rather than a confusing failure or a silently dropped column mid-transform. The default derives the list from ``output_parents()`` keys, correct for every step whose outputs cannot collide by construction. Steps with a free-form naming scheme that *could* collide (``step_dummy`` / ``step_one_hot``, whose ``{col}_{level}`` names can clash across source columns or under a custom ``name_fn``) override this to preserve any duplicate names so the recipe can reject them. Step.keep_original_cols Whether to retain the source columns alongside any produced columns. Read-only: the value is settled when the step is constructed, and for every mode but ``ONE_TO_MANY`` and ``MANY_TO_MANY`` it is fixed by the mode rather than chosen. Reassigning it would silently break the step, so rebuild the step instead of mutating it. required_pkgs(self) -> 'list[str]' Third-party packages required to run this step. Defaults to none. Each entry is a requirement string, either a bare name (``"numpy"``) or one carrying a version constraint (``"scikit-learn>=1.3"``). The recipe checks the declared packages with `check_required_pkgs` when it is fitted and when a fitted recipe transforms data, so a missing optional dependency is reported as an actionable install hint instead of an ``ImportError`` from somewhere inside the step. Only running a step needs the package; building, inspecting, and serializing a recipe do not. check_required_pkgs(self) -> 'None' Raise if any package this step declares in `required_pkgs` is missing. The error names the step and the missing package(s) and suggests the ``pip install`` that fixes it. Version constraints in a requirement are reported but not enforced. get_params(self) -> 'dict[str, object]' The step's tunable hyperparameters, keyed by constructor argument name. Read from the instance attribute of the same name as each ``__init__`` parameter (``role`` is stored as ``output_role``). ``id`` and ``columns`` are not tunable and are left out. set_params(self, **params: 'object') -> "'Self'" Return a new untrained step with ``params`` replaced. The step is rebuilt through ``__init__``, so the usual argument validation runs again; ``self`` is left untouched. The new step keeps this step's ``id`` and ``columns``. to_state(self) -> 'dict[str, object]' Serialize this step's fields to a diffable, JSON-safe ``dict``. Every hyperparameter and learned statistic already lives as a plain instance attribute, so the default encodes ``self.__dict__`` through the shared value codec -- no per-step boilerplate. The step class itself is recorded separately (by qualified name) by `to_dict`. from_state(state: 'dict[str, object]') -> "'Self'" Reconstruct a step from the ``dict`` produced by `to_state`. Bypasses ``__init__`` and restores the decoded fields directly. Any attribute missing from ``state`` (e.g. a field added in a newer version) keeps whatever a bare instance would carry, so within a major version an older payload loads cleanly without per-field shims. ``state`` is meant to be one this process produced. A payload from outside goes through `FittedRecipe.from_dict`, which also restricts the classes the state may name; called directly, this accepts any importable class name in ``state``. Either way a key that would replace a method or property raises ``ValueError``, but the values are not validated. minimize(self) -> "'Self'" Return a copy of this step with fit-only artifacts stripped. The default is a no-op: it returns ``self`` unchanged. Steps that retain training artifacts only needed at fit time (e.g. a future KNN imputer's neighbor matrix) override this to return a lighter copy that still transforms identically. See `minimize`. RowOp(id: 'str | None', default_id: 'str', *, keep_original_cols: 'bool | None' = None, output_role: 'str | None' = None) -> 'None' Row-altering steps. ``transform()`` is a no-op on new data: these steps only take effect during ``fit()`` (e.g. filtering or shuffling training rows). The behaviour is structural: because the framework dispatches on type, a ``RowOp`` can never accidentally run at transform time. The mode follows from the base class, so a ``RowOp`` subclass does not declare one. StepError(step_id: 'str', step_type: 'str', columns: 'list[str]', phase: 'str') A failure raised while fitting or transforming a step. The recipe wraps any exception raised from a step's ``fit()`` or ``transform()`` in a ``StepError`` and chains the original with ``raise ... from``, so the underlying traceback is preserved. The wrapper attaches the offending step's ``id``, its type, and the column(s) it was operating on, so a failure deep inside a pipeline says *which* step broke without the user having to read the whole stack. Attributes ---------- step_id: The ``id`` of the step that failed. step_type: The step's snake-case type name (e.g. ``'step_normalize'``). columns: The column(s) the step was operating on, or ``[]`` if unknown. phase: ``'fit'`` or ``'transform'``: the lifecycle stage the failure occurred in. ---------------------------------------------------------------------- This is the User Guide documentation for the package. ---------------------------------------------------------------------- ## Getting started ### 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: - **DataFrame-agnostic.** Works with pandas or polars (thanks to [narwhals](https://narwhals-dev.github.io/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](basics/four-stages-eight-steps.qmd). - **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: ```bash 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](https://github.com/tidymodels/mlfeatures#installation) 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). ```python 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. ```python 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. ```{python} from mlfeatures.data import beans beans.head() ``` We'll also use a small helper to draw a scatterplot matrix: ```{python} 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. ```{python} 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() ``` 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. ```{python} 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 ```{python} 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)) ) ``` ```{python} fitted = recipe.fit(bean_train) scores = fitted.transform(bean_validation) scores.head() ``` ### 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. ```{python} 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"]) ``` 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](basics/four-stages-eight-steps.qmd). 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. ```{python} beans.mlf.step_pca(s.numeric_features(), num_comp=2).head() ``` For more details, see [With polars extension (.mlf)](polars-extension.qmd). ## Use in a scikit-learn pipeline The `RecipeTransformer` class wraps a `Recipe` for use in a scikit-learn `Pipeline`: ```{python} 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)), ] ) ``` 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](sklearn-pipelines.qmd). ## Next steps * Jump to the basics: [Fit, specify, transform](basics/recipe-specify-fit-transform.qmd) * Learn more about [the Polars accessor](polars-extension.qmd) or using [in scikit-learn pipelines](sklearn-pipelines.qmd) * [Browse the API reference](/reference) ### Arguments shared across steps Most steps take the same handful of arguments: `columns`, `keep_original_cols`, `role`, and `id`. Each step's reference page lists them briefly. This page goes into more detail on the ideas behind them: what a selector resolves to and when, what dropping a source column does to a recipe's column lineage, what a role is for, and why a step has an identifier at all. Every example below uses this data frame. ```{python} import pandas as pd from mlfeatures import Recipe, StepDropCorr, StepDummy, StepNormalize, StepPca from mlfeatures import Selectors as s df = pd.DataFrame( { "price": [200.0, 250.0, 310.0, 275.0], "sqft": [1.0, 2.0, 3.0, 2.5], "beds": [2.0, 3.0, 4.0, 3.0], "city": ["LA", "SF", "LA", "SD"], } ) df ``` ## Positional and keyword-only arguments Every step follows the same calling convention. Required arguments are positional; everything optional is keyword-only. So a threshold or a degree is always named at the call site: ```{python} StepDropCorr(s.numeric_features(), threshold=0.95) ``` Passing an option positionally is a `TypeError` rather than a silent mis-assignment. Reading a step is never a matter of counting commas, and options can be reordered or added without changing what existing calls mean. A few required arguments are keyword-only too, such as the reference point of `StepGeoDistance` (`ref_lat`, `ref_lon`), where two coordinates in a row would be easy to swap. ## `columns` `columns` says which columns a step applies to. It accepts any of: - a single column name: `"sqft"` - a list of names: `["sqft", "beds"]` - a mlfeatures selector: `s.numeric_features()` - a narwhals or polars selector: `narwhals.selectors.numeric()`, `polars.selectors.numeric()` A selector is what you will end up using the most. Selectors say what the step is *for* rather than naming today's columns, so they keep working when the data frame changes and when an earlier step in the recipe has already added or removed columns. Prefer the mlfeatures selectors over narwhals or polars ones: they know about roles and column lineage (`s.numeric_features()` leaves out the target, `s.has_source("dummy")` picks out one step's output), while narwhals and polars selectors only see names and dtypes. See `Selectors` for the full set. ```{python} recipe = ( Recipe(data=df, target="price") .add(StepNormalize(s.numeric_features())) ) fitted = recipe.fit(df) fitted.transform(df) ``` Selectors are resolved during `fit()`, one step at a time. As the recipe is fitted, each step's selector is resolved against the data frame as the steps before it have left it, so a step sees the columns earlier steps added and does not see the ones they removed. A fitted step holds the concrete column names it resolved to, and `transform()` applies itself to exactly those columns; it never re-resolves the selector against new data. This is what a fitted recipe's `repr` shows in place of the selector: ```{python} fitted ``` Because resolution follows the recipe step by step, the same selector can mean different columns at different points. Here `s.numeric_features()` appears twice. The first resolves to the original numeric columns; the second also picks up the indicator columns that the dummy step created in between: ```{python} recipe = ( Recipe(data=df, target="price") .add(StepNormalize(s.numeric_features())) .add(StepDummy(s.nominal_features())) .add(StepNormalize(s.numeric_features())) ) fitted = recipe.fit(df) fitted ``` A selection that matches nothing is not an error. The step is fitted on zero columns: it stays in the fitted recipe, shown with no columns, and changes nothing, which makes it the identity transform. This is deliberate. Whether a selector matches depends on the data, and a recipe is written before it sees any, so a step like `StepNormalize(s.numeric_features())` should be valid for every data frame, including one with no numeric features: ```{python} recipe = ( Recipe(data=df, target="price") .add(StepNormalize(s.numeric_features())) ) nominal_only = df[["price", "city"]] fitted = recipe.fit(nominal_only) fitted ``` ```{python} fitted.transform(nominal_only) ``` The same holds inside a recipe, because selectors resolve step by step: an earlier step can remove every column a later selector would have matched, and the recipe should not become invalid because of what the steps before it did. The recipe handles the empty case once, for every step, so no step has to guard against it. The cost is that a typo in a name-based selector, such as `s.starts_with("prce")`, silently does nothing. When a step seems to have had no effect, check the fitted recipe's `repr` for an empty selection. Selectors that depend only on the recipe, `Selectors.has_source` and `Selectors.has_ancestor`, raise instead when given a step id that names no earlier step, since that is a typo whatever the data. ## `keep_original_cols` Steps that *derive* new columns take `keep_original_cols`. It controls whether the columns the step consumed stay in the data frame alongside the columns it produced. The default is `False`: the source columns are dropped. Dropping is the default because the derived columns usually stand in for the sources: `StepPca` replaces its inputs with components that are linear combinations of all of them, and `StepDummy` replaces a nominal column with the indicator columns encoding it. Most of the time a model needs only one of the two forms, but not always, which is why the choice is yours. ```{python} recipe = ( Recipe(data=df, target="price") .add(StepPca(s.numeric_features(), num_comp=2)) ) fitted = recipe.fit(df) fitted.transform(df) ``` Set it to `True` when you want the sources too, for instance to compare a derived column against what it came from, or because a later step still needs the original scale: ```{python} recipe = ( Recipe(data=df, target="price") .add(StepPca(s.numeric_features(), num_comp=2, keep_original_cols=True)) ) fitted = recipe.fit(df) fitted.transform(df) ``` ### What dropping does to the lineage A fitted recipe maintains a column-lineage DAG (see `Lineage`), and dropping a source column does not erase it from that DAG. The node is *archived* rather than deleted, with a record of which step removed it, so a derived column's provenance still resolves through columns that no longer exist: ```{python} recipe = ( Recipe(data=df, target="price") .add(StepPca(s.numeric_features(), num_comp=2)) ) fitted = recipe.fit(df) fitted.lineage.summary() ``` `summary()` lists only the live columns, and `sqft` and `beds` are gone from it. Ancestry still finds them: ```{python} fitted.lineage.ancestors("PC1") ``` Pass `include_removed=True` to list the archived columns too, along with which step dropped each: ```{python} fitted.lineage.summary(include_removed=True) ``` Selectors, though, no longer see the dropped columns. A dropped source column is not a feature any more, because it is no longer a column, so a later `s.numeric_features()` in the same recipe will not pick it up (the archived record keeps the roles the column had, for provenance only). When `keep_original_cols=True`, the sources survive with their roles intact and later selectors do see them. ## `role` A role is what a column *is for*. The roles mlfeatures understands natively are `"target"` for the column being predicted, `"feature"` for a column used as model input, and `"case_weights"` for per-sample weights. Any other string you choose is a custom role. Roles are how selectors like `s.numeric_features()` know what to select, and how a fitted recipe knows which columns to require at transform time. See `Roles`. Steps that produce new columns take `role`, which assigns a role to those columns. The default is `"feature"`, because a step's whole purpose is normally to produce model input, and a newly created column with no role would be invisible to every role-based selector downstream: ```{python} recipe = ( Recipe(data=df, target="price") .add(StepPca(s.numeric_features(), num_comp=2)) ) fitted = recipe.fit(df) fitted.lineage.summary() ``` Pass something else when the new columns are not model input. This replaces the default rather than adding to it, so the components below are *not* features and a later `s.numeric_features()` will skip them: ```{python} recipe = ( Recipe(data=df, target="price") .add(StepPca(s.numeric_features(), num_comp=2, role="group")) ) fitted = recipe.fit(df) fitted.lineage.summary() ``` Two related recipe-level APIs are worth knowing about. `Recipe.set_roles` assigns roles to columns that already exist in the input data, which is the other half of the same picture: `role` is for columns a step creates, `set_roles` for columns that arrived with the data. To change a role part way through the pipeline, `Recipe.add_role`, `Recipe.update_role` and `Recipe.remove_role` take effect from where they are written. `Recipe.update_role_requirements` controls whether a role's columns must be present when `FittedRecipe.transform` is called on new data, which is where a custom role usually needs a decision: an identifier column you carry through the pipeline is required at transform time, an auxiliary column used only during fitting is not. ## `id` Every step takes `id`, a short string naming that step within the recipe. It defaults to the step type's short name: `"normalize"` for `StepNormalize`, `"pca"` for `StepPca`, `"dummy"` for `StepDummy`. The id exists because a step needs a name that does not change when you edit the recipe around it. Positions shift the moment you insert a step; the id does not, so everything that refers to a step refers to it by id: - **Column provenance.** Each column the DAG knows about records the id of the step that produced it, which is the `source` column in `Lineage.summary()` above (`pca`, not "step 1"). `Lineage.columns_from_source` looks columns up by that id. - **Selectors.** `Selectors.has_source` and `Selectors.has_ancestor` select columns by which step produced them, letting a later step operate on exactly one earlier step's output. - **Errors.** When a step fails, the raised error names the id (a `StepError` for a failure inside the step, a `TypeError` naming the step for a column of an unsupported dtype), so a failure deep in a long pipeline says which step broke. Here a normalize step is pointed at the dummy step's output, by id, without naming any of the columns that step will generate: ```{python} recipe = ( Recipe(data=df, target="price") .add(StepDummy(s.nominal_features())) .add(StepNormalize(s.has_source("dummy"))) ) fitted = recipe.fit(df) fitted.transform(df) ``` That works because an id names exactly one step. The default is per *type*, not per step, so two steps of the same type would collide; the recipe resolves that as you add them, by suffixing the second one: ```{python} recipe = ( Recipe(data=df, target="price") .add(StepNormalize(s.numeric_features())) .add(StepNormalize(s.numeric_features())) ) fitted = recipe.fit(df) [step.id for step in fitted.steps] ``` The suffix keeps the two addressable, but it does not make them readable: which one is `normalize_2` depends on the order you added them, and it shifts if you insert another normalize step earlier. So give steps explicit ids as soon as a recipe has two of a type you want to refer to individually. An id you pass yourself is never renamed, and passing one that a step already in the recipe uses raises instead. ```{python} recipe = ( Recipe(data=df, target="price") .add(StepDummy(s.nominal_features(), id="dummy_city")) .add(StepNormalize(s.has_source("dummy_city"), id="scale_city")) ) fitted = recipe.fit(df) [step.id for step in fitted.steps] ``` ### With polars extension (.mlf) `mlfeatures` ships an opt-in [polars](https://docs.pola.rs/) accessor for fitting and applying steps in one expression, without writing out a `Recipe`. Importing `mlfeatures.polars` registers the `mlf` accessor on polars DataFrames. The accessor is polars-only: for pandas data frames, use a `Recipe`. ```{python} import polars as pl import polars.selectors as cs import mlfeatures.polars # registers the `df.mlf` accessor orders = pl.DataFrame( { "city": ["NYC", "LA", "NYC", "SF", "LA", "SF"], "price": [10.0, 20.0, None, 30.0, 25.0, 12.0], "qty": [2, 1, 5, 1, 3, 4], } ) orders.mlf.step_dummy(cs.string()) ``` Notice that `.step_dummy()` returned a new DataFrame with a column for each level of `city` except one, which is the reference level that all-zero indicators stand for. Use `step_one_hot` to get a column for every level. In the following sections we'll show some of the more useful steps to use directly on a polars DataFrame. ## Fit and apply happen together Every `df.mlf.step_*()` call builds the step, fits it on the data frame, transforms that same data frame, and returns the result. This makes the accessor a quick way to do a transformation once, whether you are trying a step out or cleaning up a data frame you will not transform again. The fitted step is discarded, so nothing it estimated (a median, the levels of a column, PCA loadings) can be reused on other data. Calling the accessor again on a test set re-estimates everything from the test set, which leaks information and gives you different values than the training data got. When the same transform has to be applied to new data, build a `Recipe` and fit it once. ## Handle missing values: `step_impute_median` `step_impute_median` fills nulls with the column's median (`step_impute_mean` and `step_impute_mode` are the other flavors): ```{python} filled = orders.mlf.step_impute_median(cs.by_name("price")) filled ``` ## Multivariate feature engineering: `step_pca` `step_pca` replaces numeric columns with their projection onto principal components (here on the imputed data frame, since PCA needs complete data): ```{python} ( orders .mlf.step_impute_median(cs.by_name("price")) .mlf.step_pca(cs.numeric(), num_comp=2) ) ``` ## Chaining and other steps The accessor is available on every result, so calls chain, as above. `df.mlf.apply()` takes any step objects, which reaches steps that have no `step_*` wrapper and custom steps. Each step is fitted in order on the data frame the previous one produced: ```{python} from mlfeatures import Selectors as s from mlfeatures import StepImputeMedian, StepNormalize orders.mlf.apply( StepImputeMedian(s.numeric_features()), StepNormalize(s.numeric_features()), ) ``` ### With scikit-learn pipelines A `mlfeatures` recipe handles data preprocessing and feature engineering; the model that consumes those features often lives downstream in [scikit-learn](https://scikit-learn.org/). The `RecipeTransformer` adapter bridges the two: it wraps a recipe so it behaves like any other scikit-learn transformer and drops straight into a `sklearn.pipeline.Pipeline`. ## The adapter `RecipeTransformer` wraps an *unfitted* recipe. It exposes the familiar scikit-learn `fit` / `transform` / `fit_transform` methods, so the recipe's `specify → fit → transform` lifecycle is driven by the pipeline rather than by hand. ```{python} from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split X, y = load_breast_cancer(return_X_y=True, as_frame=True) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) X_train.iloc[:5, :3] ``` scikit-learn keeps the features `X` and the target `y` apart, while `mlfeatures` identifies the target by its **role**. Build the recipe with the target role assigned; the adapter re-joins `y` onto `X` under that name at fit time and strips it back out of the transformed output, so `transform` returns the feature matrix only. ```{python} from mlfeatures import Recipe, StepNormalize from mlfeatures import Selectors as s recipe = ( Recipe(data=X_train.assign(target=y_train), target="target") .add(StepNormalize(s.numeric_features())) ) ``` ## Inside a `Pipeline` Wrap the recipe in `RecipeTransformer` and place it ahead of an estimator. The pipeline's `fit` flows `X`/`y` through the recipe, then fits the model on the engineered features: ```{python} 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(X_train, y_train) pipe.score(X_test, y_test) ``` The statistics the recipe estimated (here the means and standard deviations) come from the training data only, and the test data is transformed with them. Displaying the fitted pipeline renders scikit-learn's diagram. The recipe shows up as a labelled `RecipeTransformer (trained)` block that expands to the recipe and its steps: ```{python} pipe ``` ## The target The target needs a little care, because scikit-learn's `transform(X)` never receives `y`. The adapter handles the common cases for you and raises a `ValueError` for the ones it cannot support: - Passing `y` to a recipe with no `"target"` role raises, since there is no column to join it onto. Name the column with `Recipe(target=...)`, or assign the role with `set_roles(target=...)` before the first step (a role assignment written after a step cannot define the target). If the recipe needs no target, call `fit(X)` without `y` instead. - A recipe with more than one target column raises, since scikit-learn passes a single `y`. - A step that applies to the target column as one of its input columns raises at fit time, because that step could not run when `transform(X)` is called without the target. Transform the target outside the pipeline instead, for example with `sklearn.compose.TransformedTargetRegressor`. Steps that use the target only while fitting are fine, because they need `y` at fit time and nothing at transform time. `StepPls` and `StepClassDistance` are the two examples: they learn from the target, and the columns they produce are computed from the features alone. ```{python} from mlfeatures import StepPls pls_recipe = ( Recipe(data=X_train.assign(target=y_train), target="target") .add(StepPls(s.numeric_features(), target="target", num_comp=2)) ) pls_pipe = Pipeline( [ ("recipe", RecipeTransformer(pls_recipe)), ("model", LogisticRegression(max_iter=1000)), ] ) pls_pipe.fit(X_train, y_train) pls_pipe.score(X_test, y_test) ``` A recipe that needs no target works without `y`: call `fit(X)` and `X` is used as given. ```{python} unsupervised_recipe = ( Recipe(data=X_train) .add(StepNormalize(s.numeric_features())) ) transformer = RecipeTransformer(unsupervised_recipe) ``` Fit on the training data, then apply the stored statistics to the held-out data: ```{python} transformer.fit(X_train) ``` ```{python} result = transformer.transform(X_test) result ``` ## Cross-validation and tuning Because the adapter stores the recipe verbatim, it clones cleanly, so it works inside `GridSearchCV` and any other tool that re-fits across folds: ```{python} from sklearn.model_selection import GridSearchCV search = GridSearchCV(pipe, {"model__C": [0.1, 1.0]}, cv=3) search.fit(X_train, y_train) search.best_params_ ``` ### Tuning step hyperparameters Step hyperparameters are reachable through scikit-learn's nested parameter names, so a grid can vary a step's argument directly. Steps are addressed by their `id`, never by position, giving keys of the form `__recipe____`: the name you gave the `RecipeTransformer` in the pipeline, the `recipe` it wraps, the step, and the step's parameter. Each step has a default `id` (`StepDropCorr` uses `"corr"`) that you can replace with the step's `id=` argument. A step's `id` and `columns` are not tunable. ```{python} from mlfeatures import StepDropCorr tuned_recipe = ( Recipe(data=X_train.assign(target=y_train), target="target") .add(StepDropCorr(s.numeric_features(), threshold=0.9)) .add(StepNormalize(s.numeric_features())) ) tuned_pipe = Pipeline( [ ("prep", RecipeTransformer(tuned_recipe)), ("model", LogisticRegression(max_iter=1000)), ] ) ``` The tunable keys are listed by `get_params`. Here `prep` is the pipeline step, `corr` is the `StepDropCorr` step's `id`, and `threshold` and `method` are its parameters: ```{python} [k for k in tuned_pipe.get_params() if k.startswith("prep__recipe__")] ``` ```{python} grid = {"prep__recipe__corr__threshold": [0.8, 0.95]} search = GridSearchCV(tuned_pipe, grid, cv=3) search.fit(X_train, y_train) search.best_params_ ``` ## Feature names and `set_output` `RecipeTransformer` implements `get_feature_names_out`, so it composes inside a `ColumnTransformer` and supports the `set_output` API for choosing the container type returned by `transform` (`"pandas"` or `"polars"`): ```{python} rt = RecipeTransformer(tuned_recipe).set_output(transform="pandas") rt.fit(X_train, y_train).transform(X_test).iloc[:5, :3] ``` ## Basics ### Recipe: specify, fit, transform A `Recipe` is a pre-processing pipeline with three phases. You **specify** it as a sequence of steps, **fit** it to training data, and **transform** any data frame with what it learned. ::: {.callout-note collapse="true" title="Key points"} * Steps operate on data frames, using mlfeatures selectors (or polars selectors) to choose the columns to operate on. * mlfeatures extends the selection process with roles. * Each step applies to the "output" data of the previous step. * mlfeatures fits and transforms the training data, but only transforms test data. * mlfeatures handles pre-processing, and plugs in to scikit pipelines for final model fitting. ::: {{< include ../_includes/workflow-diagram.qmd >}} ## Setup The credit data has a categorical target, `Status`, and a mix of numeric and string features with a few missing values in each. Hold out a test set before anything is estimated. ```{python} from sklearn.model_selection import train_test_split from mlfeatures import Recipe, StepDummy, StepImputeMedian, StepImputeMode, StepNormalize from mlfeatures import Selectors as s from mlfeatures.data import credit credit_train, credit_test = train_test_split( credit, train_size=0.75, stratify=credit["Status"], random_state=1 ) credit_train.head() ``` ## Specifying recipe roles and steps Start a recipe with `Recipe(data=training_data, target="SomeColumn")` and chain steps on with `.add()`, each choosing its columns with a selector. Nothing is computed yet: the recipe is a specification, and every step shows its selector as written. ```{python} recipe = ( Recipe(data=credit_train, target="Status") .add(StepImputeMedian(s.numeric_features())) .add(StepImputeMode(s.nominal_features())) .add(StepDummy(s.nominal_features())) .add(StepNormalize(s.numeric_features())) ) recipe ``` `target=` gives `Status` the `target` role, and every other column is a feature. That is what keeps `Status` out of `s.nominal_features()`, so it is not imputed or turned into indicator columns with the real string features, and it is what lets a scikit-learn pipeline hand the recipe its `y` later. `data=` is optional: the recipe only reads its column names, to check role assignments such as `target=` straight away and to show the columns before fitting. Nothing is estimated from it, and a step's columns are not checked until the recipe is fitted. ## Fitting training data `recipe.fit(training_data)` runs the steps in order, and each step estimates what it needs from the data as it goes: the medians, the modes, the levels of each string column, the means and standard deviations. Fitting also transforms the training data frame step by step, so each selector is resolved against the output of the step before it. ```{python} fitted = recipe.fit(credit_train) fitted ``` Every step is now `[trained]` and lists the concrete columns it resolved to. The dummy step produced indicator columns from `Home`, `Marital`, `Records`, and `Job`, and the normalize step's `numeric_features()` selector, resolved after it, picked those up along with the original numerics. ## Transforming test data `fitted.transform(data)` applies the stored estimates to any data frame that has the training features, with the training dtypes, and re-estimates nothing: the test set is filled with the training medians and modes and scaled by the training means. ```{python} result = fitted.transform(credit_test) result.head() ``` Wrap the recipe in `RecipeTransformer` to make it the first step of a scikit-learn `Pipeline`, so the model gets the same guarantee. scikit-learn keeps `X` and `y` apart while mlfeatures finds the target by role, so the adapter re-joins `y` under the target's name at fit time and hands the model only the features. ```{python} 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(credit_train.drop("Status"), credit_train["Status"]) pipe.score(credit_test.drop("Status"), credit_test["Status"]) ``` `pipe.fit` fits the recipe and then the model on the training split; `pipe.score` only transforms the test split with the stored estimates before scoring it. Cross-validation, tuning, and feature names are covered in [With scikit-learn pipelines](../sklearn-pipelines.qmd). ### Selectors and roles Recipe steps operate on columns of data, which are chosen with selectors. mlfeatures selectors cover the same ground as Polars selectors, such as all numeric columns (`s.numeric()`), and a step also accepts a Polars selector (`cs.numeric()`) as is. Polars selectors can't target modelling pieces like all "feature" columns, though. mlfeatures enables this by adding roles, modelling-specific tags for columns, and selectors to target them. ::: {.callout-note collapse="true" title="Key points"} - A step accepts a column name, a list of names, a polars or narwhals selector, or a mlfeatures selector from `Selectors`, imported as `s`. - mlfeatures selectors choose by name, type, role, or the step that produced a column, and compose with `&`, `|`, `~`, and `-`. - `Recipe(..., target="col")` gives a column the `target` role, which keeps it out of feature selectors like `s.numeric_features()`. - `Recipe.summary()` lists every column with its dtype, roles, and the step that produced it. - Every non-target column is a feature by default; `features=` names them explicitly, and `case_weights` columns are never features. - `set_roles()` attaches custom roles, and `s.has_role()` selects by them. ::: ## Setup The examples use two datasets from `mlfeatures.data`: the credit data, whose target is a string, and a small Ames housing subset, whose target is numeric. ```{python} import polars as pl import polars.selectors as cs from mlfeatures import Recipe, StepDummy, StepImputeMedian, StepNormalize from mlfeatures import Selectors as s from mlfeatures.data import ames_mini, credit ``` ## Selector basics Pass a polars selector, or a mlfeatures selector from `s`. mlfeatures selectors cover the same name and type checks (`s.numeric()`, `s.starts_with()`, `s.col()`) and compose with set operators, so "every numeric column except `Price`" is one expression. ```{python} recipe = ( Recipe(data=credit, target="Status") .add(StepImputeMedian(cs.numeric())) # polars selector .add(StepNormalize(s.numeric() - s.col("Price"))) # mlfeatures selector ) fitted = recipe.fit(credit) fitted ``` A selector is resolved when the recipe is fitted, against the columns that exist at that point in the pipeline. That is why the fitted recipe lists concrete names, why the same selector works on any backend, and why a later step can pick up columns an earlier step created. The full set is on the `Selectors` reference page. ## Roles: features and targets Use `Recipe(..., target="col")` to give a column the `target` role, which excludes it from the mlfeatures feature selectors such as `s.numeric_features()`. A polars selector like `cs.numeric()` knows nothing about roles, so it includes the target. That is rarely what you want: a step that works on the target makes it required when the fitted recipe transforms new data, and a column with no target (as at prediction time) then fails the transform. ```{python} recipe = ( Recipe(data=ames_mini, target="Sale_Price") .add(StepNormalize(s.numeric_features())) # excludes target .add(StepNormalize(cs.numeric())) # includes target ) fitted = recipe.fit(ames_mini) fitted ``` `s.numeric_features()` is simply `s.numeric()` restricted to the `feature` role. The `_features` variants exist for each type (`s.nominal_features()`, `s.date_features()`, and so on), and `s.features()` and `s.targets()` select by role alone. ## Roles: specifying features Every column that is not the target is a feature by default, so a feature selector sees all of them. Pass `features=` to name the features yourself: the other columns then carry no role, so selectors ignore them, and `transform()` passes them through unchanged. ```{python} recipe = Recipe( data=ames_mini, target="Sale_Price", features=["Gr_Liv_Area", "Year_Built", "Neighborhood"], ).add(StepNormalize(s.numeric_features())) fitted = recipe.fit(ames_mini) fitted ``` The default is applied when the recipe is fitted, which is why an untrained recipe with only a target reports just that target. One standard role is never a feature: a column declared `case_weights=` holds per-sample weights and is left out of every feature selector. ## Displaying role information `Recipe.summary()` lists one row per column with its dtype, its roles, and the step that produced it, so after a dummy step the indicator columns show up as features whose source is `dummy`: ```{python} recipe = ( Recipe(data=ames_mini, target="Sale_Price") .add(StepDummy(s.nominal_features())) .add(StepNormalize(s.numeric_features())) ) fitted = recipe.fit(ames_mini) fitted.summary() ``` ## Custom roles `set_roles(name=[...])` attaches any custom role, a column can carry several roles at once, and `s.has_role()` selects by one. Tagging `Latitude` and `Longitude` as `geo` keeps them out of normalization while they stay features: ```{python} recipe = ( Recipe(data=ames_mini, target="Sale_Price") .set_roles(geo=["Latitude", "Longitude"]) .add(StepNormalize(s.numeric_features() - s.has_role("geo"))) ) fitted = recipe.fit(ames_mini) fitted.summary().filter(pl.col("roles").str.contains("geo")) ``` ## Changing roles part way through `set_roles()` labels the columns that arrive with the data, and it does so whatever its position in the recipe. To change a role at a point in the pipeline, use `add_role()`, `update_role()` or `remove_role()`. Each takes effect where it is written: the steps after it see the new role, the steps before it do not, and it can reach columns that earlier steps created. Here the dummy indicators get an `indicator` role, which the normalization that follows leaves out by selecting features without it: ```{python} recipe = ( Recipe(data=ames_mini, target="Sale_Price") .add(StepDummy(s.nominal_features())) .add_role(s.has_source("dummy"), role="indicator") .add(StepNormalize(s.numeric_features() - s.has_role("indicator"))) ) fitted = recipe.fit(ames_mini) fitted.summary().filter(pl.col("roles").str.contains("indicator")) ``` `update_role(columns, new_role=..., old_role=...)` swaps one role for another, or replaces all of a column's roles when `old_role` is left out, and `remove_role(columns, role=...)` takes a role away. Like a step's `columns`, the first argument can be a name, a list of names, or a selector. ### Four stages, eight steps This page discusses the "Order the steps" box in the pre-processing workflow diagram below. Essentially, there are 8 positioning steps you can take to order your sequence of Step calls. Each position has its own page (e.g. "Missing: impute"). {{< include ../_includes/workflow-diagram.qmd >}} ## Overview of eight steps | Stage | Position | mlfeatures steps | |---|---|---| | 1. Handle missing values | 1. Missing: impute | `StepImputeMean`, `StepImputeMedian`, `StepImputeMode`, `StepIndicateNa` | | | 2. Missing: category levels | `StepUnknown`, `StepOther` | | 2. Wrangle | 3. Wrangle: transforms | `StepLog`, `StepOrderNorm`, `StepDateFeatures`, `StepDatetimeFeatures` | | | 4. Wrangle: discretize | *none; rarely advisable* | | | 5. Wrangle: dummy variables | `StepDummy`, `StepOneHot`, `StepHoliday` | | 3. Model prep | 6. Model prep: interactions | `StepInteract`, `StepPolynomial`, `StepSplineNatural`, `StepSplineMonotone` | | | 7. Model prep: normalize | `StepNormalize`, `StepRange` | | 4. Multivariate transforms | 8. Multivariate transforms | `StepPca`, `StepPls`, `StepClassDistance` | Each stage exists so the next one works: handle missing first (impute the numeric gaps and give missing categorical levels an explicit value), because every later step wants complete columns, and the guard levels must exist before the dummy step freezes its vocabulary; wrangle everything into numbers next; model prep after, so interactions can cross indicator columns with numerics and normalize catches the freshly created columns; multivariate transforms last, because they want the finished, scaled matrix. ## Example: eight steps in action One recipe on the credit data can fill most of the positions. The first stages handle missing values and turn everything into numbers, and their order matters because each step decides what the next one sees: impute first so nothing downstream meets a null, then give missing and rare levels a name *before* the dummy step, so its vocabulary already contains the pooled level and new data cannot introduce a level it has no column for. `StepUnknown` names the missing values `"unknown"`; here they are rare enough that `StepOther` then pools them into `"infrequent"` with the other small levels. ```{python} from sklearn.model_selection import train_test_split from mlfeatures import ( Recipe, StepDropZeroVariance, StepDummy, StepImputeMedian, StepInteract, StepNormalize, StepOther, StepPca, StepUnknown, ) from mlfeatures import Selectors as s from mlfeatures.data import credit credit_train, credit_validation = train_test_split( credit, train_size=0.75, stratify=credit["Status"], random_state=1 ) wrangled = ( Recipe(data=credit_train, target="Status") .add(StepImputeMedian(s.numeric_features())) # 1. impute .add(StepUnknown(s.nominal_features())) # 2. category levels .add(StepOther(s.nominal_features(), threshold=0.05, other_level="infrequent")) .add(StepDummy(s.nominal_features())) # 5. dummy variables ) wrangled.fit(credit_train) ``` The dummy step's resolved columns include `Job_infrequent`, the pooled level; `Home`'s few missing and rare values were pooled the same way, into the level its indicators are measured against. Model prep and the multivariate transform continue from there. Normalize sits after the interaction step so the new product column is scaled with the rest, and before PCA, which weights columns by their variance and would otherwise be dominated by the largest-valued ones. ```{python} recipe = ( wrangled.add(StepDropZeroVariance(s.features())) # filter .add(StepInteract(s.col("Income", "Amount"), keep_original_cols=True)) # 6. interactions .add(StepNormalize(s.numeric_features())) # 7. normalize .add(StepPca(s.numeric_features(), num_comp=3)) # 8. multivariate ) fitted = recipe.fit(credit_train) fitted ``` ```{python} fitted.transform(credit_validation).head() ``` ## Filtering-related steps The ordering is deliberately silent on the filter steps (`StepDropZeroVariance`, `StepDropNearZeroVariance`, `StepDropCorr`): [dropping columns](dropping-columns.qmd) is not a stage. In practice filters run as two passes: after stage 1, to drop dead or redundant raw columns before effort is spent encoding and scaling them, and again after the dummy step, where a rare level can produce an all-zero indicator column. ## Alternative perspective: feature type While the eight steps focus on the order that steps tend to be put in, the [crosswalk](../extra/crosswalk.qmd) cross-references them with the kind of column each step works on (e.g. datetime features). This is often useful when you already know what step you want, or want to browse steps that return similar types of results. ### Ensure robust to new data A fitted recipe is a model of the training data, applied to data it has never seen. Some of the failure modes that come with that are handled for you, and two are yours to prevent: missing values and category levels the training data lacked. ::: {.callout-note collapse="true" title="Key points"} * Everything a recipe estimates comes from the data passed to `fit()`; `transform()` only applies those estimates, so new data never leaks into them. * `transform()` checks new data against the training schema: a missing feature column or a changed dtype raises before any step runs. * Steps do not fill missing values; impute numeric gaps and give missing categorical values a level (`StepUnknown`) before anything else. * A level the dummy step never saw gives null indicators and a warning; `StepOther` pools rare and unseen levels into one level instead. ::: ## Setup ```{python} import polars as pl from sklearn.model_selection import train_test_split from mlfeatures import Recipe, StepDummy, StepImputeMedian, StepNormalize, StepOther, StepUnknown from mlfeatures import Selectors as s from mlfeatures.data import ames_mini, credit credit_train, credit_validation = train_test_split( credit, train_size=0.75, stratify=credit["Status"], random_state=1 ) ames_train, ames_validation = train_test_split(ames_mini, train_size=0.8, random_state=502) ``` ## Training data fits, new data is transformed Everything a recipe estimates comes from the data frame passed to `fit()`, and `transform()` reuses those estimates on every other data frame. That is the guard against data leakage: the validation set never influences the statistics that transform it. After normalizing with the training means, the validation mean is close to zero but not exactly zero. ```{python} recipe = ( Recipe(data=credit_train, target="Status") .add(StepImputeMedian(s.numeric_features())) .add(StepNormalize(s.numeric_features())) ) fitted = recipe.fit(credit_train) fitted.transform(credit_validation).select(pl.col("Income").mean()) ``` The same holds for every step: the medians used to fill gaps, the levels a dummy step expands, and the axes a PCA step projects onto are all fixed at fit time. ## New data is checked against the training schema Before any step runs, `transform()` compares the new data frame with the schema captured at fit time. A feature column that is missing raises a `ValueError` naming it, and so does a column whose dtype differs from the training dtype (`Int64` does not match `Float64`), so cast new data to the training dtypes first. The target is not needed to transform, and extra columns are ignored, which is why a model can score data that has no target column. The one exception is a target that a step operates on: normalizing it makes it required at transform time too. ## Missing values: impute first Steps do not fill missing values for you. A normalize step passes nulls through, a dummy step turns a null level into a row of null indicators, and most models refuse either. Put `StepImputeMedian` (or `StepImputeMean`) and `StepUnknown` before anything else so the later steps see complete columns. Without them, the transformed validation set still carries the gaps: ```{python} recipe = ( Recipe(data=credit_train, target="Status") .add(StepNormalize(s.numeric_features())) .add(StepDummy(s.nominal_features())) ) fitted = recipe.fit(credit_train) fitted.transform(credit_validation).null_count() ``` With imputation first, and `StepUnknown` giving missing categoricals their own `"unknown"` level, nothing is left for a model to trip on: ```{python} recipe = ( Recipe(data=credit_train, target="Status") .add(StepImputeMedian(s.numeric_features())) .add(StepUnknown(s.nominal_features())) .add(StepNormalize(s.numeric_features())) .add(StepDummy(s.nominal_features())) ) fitted = recipe.fit(credit_train) fitted.transform(credit_validation).null_count() ``` ## Rare and unseen category levels A dummy step learns its levels at fit time, so a level that first appears in new data gets null in every indicator column, with a warning. `StepOther(columns, threshold=...)` prevents that: it pools levels rarer than the threshold into one `"other"` level when fitted, and sends any level it has never seen to the same place when transforming. In this split, `"Stone"` exterior appears only in the validation rows: ```{python} recipe = ( Recipe(data=ames_train, target="Sale_Price") .add(StepOther(s.col("Exterior_1st"), threshold=0.01)) .add(StepDummy(s.col("Exterior_1st"))) ) fitted = recipe.fit(ames_train) stone = ames_validation.filter(pl.col("Exterior_1st") == "Stone") fitted.transform(stone).select(pl.col("^Exterior_1st_.*$")) ``` Both rows land in `Exterior_1st_other`, a column the model has seen, rather than getting nulls in every indicator. Rare levels pooled at fit time also stop a dummy step from producing near-empty indicator columns for them. ### Dropping columns Dropping columns removes model variables that might lead to underidentified models, or models that take a long time to fit. mlfeatures has three filter steps for it: one for correlated columns and two for columns with little or no variance. ::: {.callout-note collapse="true" title="Key points"} * `StepDropCorr` drops one column from each highly correlated pair (default threshold 0.9), which keeps a linear model from fitting redundant columns. * `StepDropNearZeroVariance` drops columns that are almost constant, and `StepDropZeroVariance` only those that are fully constant or all missing. * Filters are not a stage of the [eight-step order](four-stages-eight-steps.qmd); they run after stage 1 and again after the dummy step. ::: ## Setup ```{python} from mlfeatures import Recipe, StepDropCorr, StepDropNearZeroVariance, StepDropZeroVariance from mlfeatures import Selectors as s from mlfeatures.data import ames_mini, beans ``` ## Drop one of each highly correlated pair `StepDropCorr(columns, threshold=...)` drops one column from each pair whose correlation exceeds the threshold, keeping the other. In the Ames subset, `Garage_Cars` and `Garage_Area` say nearly the same thing (correlation 0.89), so one of them goes: ```{python} recipe = Recipe(data=ames_mini, target="Sale_Price").add( StepDropCorr(s.numeric_features(), threshold=0.8) ) fitted = recipe.fit(ames_mini) fitted.transform(ames_mini).columns ``` The default threshold is 0.9. The dry beans data shows how much a correlated set can collapse: its 16 shape measurements lose 9 of their number. ```{python} recipe = Recipe(data=beans, target="class").add(StepDropCorr(s.numeric_features())) fitted = recipe.fit(beans) fitted.transform(beans).columns ``` ## Drop columns with little or no variance `StepDropNearZeroVariance(columns)` drops columns that are nearly constant, which a model can only overfit to. `Street` is the case here: 12 of 2,930 houses are on a gravel road. ```{python} recipe = Recipe(data=ames_mini, target="Sale_Price").add( StepDropNearZeroVariance(s.features()) ) fitted = recipe.fit(ames_mini) fitted.transform(ames_mini).columns ``` `StepDropZeroVariance` is the strict version: it drops only columns that are completely constant or all missing. Its usual place is right after a dummy step, where a level that is present in the schema but absent from the training rows becomes an all-zero indicator column. ## Missing values are a row problem Filters remove columns. Rows with missing values are a different problem, handled by imputation rather than removal, and they are covered on [Ensure robust to new data](ensure-robust-to-new-data.qmd). ### Composing steps Steps run in order, and each one selects from the data frame as the previous step left it. That is what lets a later step pick up columns an earlier step created, and mlfeatures tracks which step produced each column so a selector can ask for exactly those. ::: {.callout-note collapse="true" title="Key points"} * Steps operate on the output of the previous step. * `s.has_source(step_type=StepDummy)` selects the columns a step produced; `s.has_ancestor()` follows that lineage through later steps. * `s.has_source("some_id")` selects by step id; a second step of the same type is numbered automatically (`dummy_2`), or name it with `id=`. ::: ## Setup ```{python} from mlfeatures import Recipe, StepDummy, StepImputeMode, StepNormalize from mlfeatures import Selectors as s from mlfeatures.data import credit ``` ## Each step sees the previous step's output A selector is resolved against the data frame as it exists when its step runs, so a step placed after `StepDummy` can select the indicator columns it created. Here the normalize step's `s.numeric_features()` matches the original numerics and every new indicator column: ```{python} recipe = ( Recipe(data=credit, target="Status") .add(StepImputeMode(s.nominal_features())) .add(StepDummy(s.nominal_features())) .add(StepNormalize(s.numeric_features())) ) fitted = recipe.fit(credit) fitted ``` ## Selecting by source step Use `s.has_source(step_type=SomeStep)` to select only the columns a step produced. This normalizes the indicator columns and leaves the original numerics as they were: ```{python} recipe = ( Recipe(data=credit, target="Status") .add(StepImputeMode(s.nominal_features())) .add(StepDummy(s.nominal_features())) .add(StepNormalize(s.has_source(step_type=StepDummy))) ) fitted = recipe.fit(credit) fitted ``` `s.has_source()` matches the step that produced a column. A step that rewrites its columns in place, such as `StepNormalize`, does not take over as their producer, so the indicators above still count as `StepDummy`'s output after they are normalized. `s.has_ancestor()` goes further: it also matches new columns that a later step derived from the step's output, such as the product column `StepInteract` builds from two indicators. ## Selecting by step id `s.has_source("some_id")` selects the output of one step by its id. Every step has one: it defaults to the step's short name (`"dummy"`), a second step of the same type is numbered (`"dummy_2"`), and `id=` lets you name a step yourself. ```{python} recipe = ( Recipe(data=credit, target="Status") .add(StepImputeMode(s.nominal_features())) .add(StepDummy(s.col("Home"))) # id "dummy" .add(StepDummy(s.col("Marital"))) # id "dummy_2" .add(StepNormalize(s.has_source("dummy_2"))) ) fitted = recipe.fit(credit) fitted ``` ### Fit and transform Fitting a recipe estimates everything its steps need from the training data and hands back a separate `FittedRecipe`. That object is what you keep: it transforms training, validation, and production data the same way, and it can be serialized to do so anywhere. ::: {.callout-note collapse="true" title="Key points"} * `fit()` estimates what each step needs and stores it on the fitted steps * selectors are resolved once, at fit time * `fit()` returns a new `FittedRecipe` and leaves the recipe untouched * row filters such as `StepFilter` run at fit time only, never in `transform()` * `transform()` applies the same estimates to training, validation, and production data * a `FittedRecipe` can be serialized and applied anywhere ::: ## Setup ```{python} import polars as pl from sklearn.model_selection import train_test_split from mlfeatures import Recipe, StepFilter, StepImputeMedian, StepNormalize, from_json, to_json from mlfeatures import Selectors as s from mlfeatures.data import credit credit_train, credit_validation = train_test_split( credit, train_size=0.75, stratify=credit["Status"], random_state=1 ) ``` ## Fitting returns a new FittedRecipe `recipe.fit(training_data)` returns a `FittedRecipe` and leaves the recipe itself untouched, so one specification can be fitted to different data frames. Fitting is also when selectors are resolved: each step lists the concrete columns it matched, and it holds the estimates it made (here the medians, then the means and standard deviations). ```{python} recipe = ( Recipe(data=credit_train, target="Status") .add(StepImputeMedian(s.numeric_features())) .add(StepNormalize(s.numeric_features())) ) fitted = recipe.fit(credit_train) fitted ``` The recipe is still the untrained specification: ```{python} recipe ``` ## Row filters run only at fit A row filter such as `StepFilter` drops rows when the recipe is fitted and none when it transforms, because dropping rows from data being scored would silently lose predictions. Use it to choose which training rows the other steps learn from, not to filter new data. ```{python} recipe = ( Recipe(data=credit_train, target="Status") .add(StepFilter(lambda df: ~df["Income"].is_null())) # fit only .add(StepNormalize(s.numeric_features())) ) fitted = recipe.fit(credit_train) fitted.transform(credit_validation).filter(pl.col("Income").is_null()).head() ``` The means were estimated without the null-income rows, but the validation rows with a null income all come back. ## Transform training, validation, and production data `fitted.transform(data)` applies the stored estimates to any data frame that has the training features, with the training dtypes (the target is not needed). Training data, a validation split, and rows arriving in production all get the training medians and means, which is what makes their transformed values comparable. ```{python} fitted.transform(credit_validation).head() ``` ## Serialize to transform anywhere `to_json(fitted)` writes the fitted recipe, estimates included, and `from_json()` restores it, so the transform can run in another process or on another machine without the training data. `to_yaml()` and `from_yaml()` do the same in YAML. ```{python} restored = from_json(to_json(fitted)) restored.transform(credit_validation).head() ``` A saved recipe is data, and loading it never runs code the file picks: the loaders accept only classes from mlfeatures and from packages that register steps under the `mlfeatures.steps` entry-point group, and raise `ValueError` for any other name. A step of your own that is not registered, such as one defined in a notebook, loads when you name it with `from_json(text, trusted=[MyStep])`. Saving warns when a recipe contains a class the loaders would refuse by default. See [Serializing recipes](../extra/serializing-recipes.qmd) for the file format and for `minimize()`, which strips fit-only artifacts before saving. ## Extra ### Feature types and the eight steps Feature type and the [eight positions](../basics/four-stages-eight-steps.qmd) are two groupings of the same steps: a feature type says what kind of column a step works on, a position says when it runs. Crossing them shows where each step lives, and that the two cut across each other rather than nesting. *Italicized* steps are planned or not yet in this build. | Position | Numeric | Categorical | Datetime | Missing data | Text | Dim. reduction | |---|---|---|---|---|---|---| | 1. Missing: impute | | | | `step_impute_mean` `step_impute_median` `step_impute_mode` `step_indicate_na` | | | | 2. Missing: category levels | | `step_unknown` `step_other` *`step_novel`* | | `step_unknown` | | | | 3. Wrangle: transforms | `step_log` `step_order_norm` | | `step_date_features` `step_datetime_features` | | | | | 4. Wrangle: discretize | none | | | | | | | 5. Wrangle: dummy variables | | `step_dummy` `step_one_hot` | `step_holiday` | | | | | 6. Model prep: interactions | `step_polynomial` `step_interact` `step_spline_natural` `step_spline_monotone` | | | | | | | 7. Model prep: normalize | `step_normalize` `step_range` | | | | | | | 8. Multivariate transforms | | | | | | `step_pca` `step_class_distance` `step_pls` | Reading the empty space is as useful as reading the cells: - **Text features has no entries at all**: that feature type is handled at the recipe's boundary today, not by steps. - **Position 4 (discretize) is empty by design**: no step fills it, and R recipes itself discourages it. - **The filter steps don't appear**: `step_drop_zero_variance` and `step_drop_corr` hold no position; see [dropping columns](../basics/dropping-columns.qmd). ### Vocabulary The R and Python modeling communities use different words for the same things, and mlfeatures has R `recipes` in its lineage while living in the Python ecosystem. This page is the translation table. mlfeatures follows scikit-learn's vocabulary wherever the two communities disagree, because that is the ecosystem a mlfeatures recipe actually plugs into. ## The three quantities | Quantity | mlfeatures | scikit-learn | R `recipes` / tidymodels | | --- | --- | --- | --- | | A column used as model input | `feature` | feature | predictor | | The column being predicted | `target` | target, label | outcome | | One row of the data | sample | sample | observation, case | These are not just prose conventions: `"feature"` and `"target"` are the literal role names mlfeatures assigns to columns, so they show up in `Recipe()` kwargs, in `Selectors` methods, and in a recipe's printed output. ```{python} #| echo: false #| output: false import pandas as pd from mlfeatures import Recipe, StepNormalize from mlfeatures import Selectors as s ``` ```{python} df = pd.DataFrame({"price": [200.0, 250.0, 310.0], "sqft": [1.0, 2.0, 3.0]}) recipe = Recipe(data=df, target="price", features="sqft").add( StepNormalize(s.numeric_features()) ) recipe ``` ## False friends A few words mean something different here than you might expect, so they are worth calling out. **`predictor` is not a column.** In scikit-learn, "predictor" means an *estimator* that implements `predict()`: `TreePredictor`, `make_predictor()`, `_linear_predictor`. It is never a name for an input column, which is exactly the opposite of R `recipes`, where `all_predictors()` selects input columns. mlfeatures does not use the word at all. **`label` is not the target.** scikit-learn uses "label" as a synonym for the target, roughly as often as it uses "target" itself. mlfeatures does not, because "label" would then collide with the class values of a categorical target and with the distinct concept below. Where a single class value of a categorical target is meant, mlfeatures says **class**, or **class label** where the fuller phrase reads better. What it never does is use a bare "label" to mean the target column. **`level`, not `label`, for a category's values.** The distinct values of a categorical column are its **levels**, following R's factor terminology. `StepDummy` and `StepOneHot` learn a column's levels at fit time, and `StepUnknown` deals with missing ones. A level is a value *within* a column, which is a different thing from a role, which is a property *of* a column. **A table of rows and columns is a data frame.** Prose says "data frame", not a bare "frame". The bare word survives only in code, as the internal `Frame` type alias and the `_frame` module. **`sample` also has its statistical sense.** mlfeatures says "sample" for one row of data, but "sample standard deviation" in `StepNormalize` means the `ddof=1` estimator, not anything about rows. ## mlfeatures-specific terms | Term | Meaning | R `recipes` equivalent | | --- | --- | --- | | `Recipe` | The declared, not-yet-estimated pipeline | `recipe` | | step | One feature-engineering operation | `step_*()` | | role | A user-assigned name on a column, such as `"feature"` or `"target"` | role | | selector | A description of *which* columns a step applies to, resolved at fit time | `all_predictors()` and friends | | untrained | A recipe whose steps have not estimated anything yet | unprepped | | trained | A recipe whose steps hold fitted state, ready to apply | prepped | | `fit()` | Estimate every step's state from training data | `prep()` | | `transform()` | Apply the fitted steps to data | `bake()` | | `Schema` | A zero-row snapshot of the training data's columns, dtypes, and roles, used to validate data at `fit()` and `transform()` | (no equivalent) | | `Lineage` | The record of where each column came from and how its dtype and roles changed across steps | `var_info` / `term_info` | Note the two lifecycle names in particular. mlfeatures deliberately does not use R `recipes`' cooking analogy, so a recipe is never "prepped" or "baked": it is untrained or trained, and you `fit()` then `transform()` it. ## Roles beyond feature and target `"feature"` and `"target"` are the two roles mlfeatures treats specially, but a role is just a string, and a column can carry more than one. `"case_weights"` is the third standard role, and you can register any custom role you like. See `Roles` for the details. A column with the `"feature"` role is always required when you `transform()` new data; a `"target"` column never is, since it is unknown at serving time. That asymmetry is the main reason the two roles are mutually exclusive. ### Serializing recipes A `FittedRecipe` can be saved as JSON or YAML and loaded again, in another process or on another machine, without the training data. The file holds every step's hyperparameters and learned statistics plus the recipe's roles, training schema, and lineage. It is plain text, so it can be reviewed in a pull request and kept next to a model. ::: {.callout-note collapse="true" title="Key points"} * `to_json()` and `to_yaml()` write a fitted recipe; `from_json()` and `from_yaml()` read it back * YAML needs the optional `pyyaml` package (`pip install mlfeatures[yaml]`) * loading only accepts classes from mlfeatures, registered step packages, and classes you pass as `trusted` * a file written by a different `format_version` is refused; fit the recipe again * `minimize()` drops what `transform()` does not need, for steps that have something to drop ::: ## Setup ```{python} from mlfeatures import ( Recipe, StepNormalize, from_json, from_yaml, minimize, to_dict, to_json, to_yaml, ) from mlfeatures import Selectors as s from mlfeatures.data import credit credit = credit.drop_nulls() recipe = Recipe().add(StepNormalize(s.numeric_features())) fitted = recipe.fit(credit) ``` ## Save and load `to_json()` returns the text and leaves writing it to a file to you. The same functions are available as methods, such as `fitted.to_json()` and `FittedRecipe.from_json(text)`. ```{python} text = to_json(fitted) text[:300] ``` The loaded recipe transforms new data the same way as the original. ```{python} restored = from_json(text) restored.transform(credit).head() ``` `to_yaml()` and `from_yaml()` write and read the same content as YAML. ```{python} from_yaml(to_yaml(fitted)).transform(credit).head() ``` ## What is in the file `to_dict()` returns the payload that both formats encode. It has six keys, in this order: `mlfeatures_version` (what wrote it), `format_version` (the layout), `roles`, `schema`, `lineage`, and `steps`. Each entry in `steps` has the step's class name as `type` and its hyperparameters and learned statistics as `state`. ```{python} payload = to_dict(fitted) list(payload) ``` The payload holds statistics and schemas, never the training data, and nothing in it is a closure or an environment. ## What cannot be saved Saving raises a `TypeError` rather than silently dropping something: * a raw polars or narwhals selector (a `Selectors` selector or a list of names is saved) * a `dateutil` rule, as held by `StepHoliday` * a function, as held by `StepMutate`; pickle recipes that contain it One more limitation does not raise: the categories of an `Enum` column are not kept, so after loading, the column's dtype in the schema and lineage is an `Enum` with no categories. Checks that compare dtypes by type are unaffected. ## Format versions `format_version` changes only when the layout changes incompatibly. A file with another version raises a `ValueError` that asks you to fit the recipe again and save it again. A file with no `format_version` is read as the current one. ## Loading files you did not write A saved recipe is data, and loading it never runs code the file picks. The loaders accept class names from mlfeatures, from packages that register a step under the `mlfeatures.steps` entry-point group, and from the packages of the classes you pass as `trusted`. Any other name raises a `ValueError`, as does a payload that is not shaped like a recipe. The values inside a payload are not validated, so only load files from sources you trust to give you sensible numbers. A step of your own that is not registered, such as one defined in a notebook, loads when you name it: ```python fitted = from_json(text, trusted=[MyStep]) ``` Saving warns when the recipe contains a class the loaders would refuse by default, so the problem shows up when the file is written rather than when it is first loaded. Pickle is not covered by these checks: unpickling runs arbitrary code, so only unpickle recipes you trust. ## Minimizing `minimize()` returns a recipe that keeps only what `transform()` needs. Each step decides what it can drop, such as something kept only for inspection after fitting. None of the steps shipped with mlfeatures has anything to drop yet, so for them the result is the same recipe and the same file. It is safe to call before saving, and it will shrink files once a step that keeps fit-only artifacts exists. ```{python} small = minimize(fitted) small.transform(credit).head() ``` ### 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. ::: {.callout-note collapse="true" title="Key points"} * 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. ```{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 ``` ```{python} #| echo: false #| output: false credit = credit.drop_nulls() ``` ## 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 at `False`. * `Mode.ONE_TO_MANY`: each input column produces one or more output columns, like `StepDummy`. `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`. `keep_original_cols` is configurable, default `False`. * `Mode.REMOVING`: input columns are dropped and none are created, like `StepDropZeroVariance`. `keep_original_cols` is fixed at `False`. * `Mode.ADDING`: new columns appear with no corresponding input, like `StepIntercept`. `keep_original_cols` is fixed at `True`. * `Mode.ROW_OP`: the columns are unchanged, like `StepFilter`. `keep_original_cols` is fixed at `True`. 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 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`). 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 ```python 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. ```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()` 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()` 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. ```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 ``` ```{python} fitted = recipe.fit(credit) fitted ``` ```{python} result = fitted.transform(credit) result ``` 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()`, 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: ```{python} text = fitted.to_json() loaded = from_json(text, trusted=[StepMaxAbs]) loaded ``` 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()` 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.