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

> **Note: Key points**
>
> - Everything a recipe estimates comes from the data passed to [fit()](../../reference/Step.fit.md#mlfeatures.Step.fit); [transform()](../../reference/Step.transform.md#mlfeatures.Step.transform) only applies those estimates, so new data never leaks into them.
> - [transform()](../../reference/Step.transform.md#mlfeatures.Step.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](../../reference/StepUnknown.md#mlfeatures.StepUnknown)) before anything else.
> - A level the dummy step never saw gives null indicators and a warning; [StepOther](../../reference/StepOther.md#mlfeatures.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()](../../reference/Step.fit.md#mlfeatures.Step.fit), and [transform()](../../reference/Step.transform.md#mlfeatures.Step.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())
```


shape: (1, 1)

| Income    |
|-----------|
| f64       |
| -0.034283 |


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()](../../reference/Step.transform.md#mlfeatures.Step.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](../../reference/StepImputeMedian.md#mlfeatures.StepImputeMedian) (or [StepImputeMean](../../reference/StepImputeMean.md#mlfeatures.StepImputeMean)) and [StepUnknown](../../reference/StepUnknown.md#mlfeatures.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()
```


shape: (1, 23)

| Status | Seniority | Time | Age | Expenses | Income | Assets | Debt | Amount | Price | Home_other | Home_owner | Home_parents | Home_priv | Home_rent | Marital_married | Marital_separated | Marital_single | Marital_widow | Records_yes | Job_freelance | Job_others | Job_partime |
|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|
| u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 |
| 0 | 0 | 0 | 0 | 0 | 99 | 15 | 5 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |


With imputation first, and [StepUnknown](../../reference/StepUnknown.md#mlfeatures.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()
```


shape: (1, 26)

| Status | Seniority | Time | Age | Expenses | Income | Assets | Debt | Amount | Price | Home_other | Home_owner | Home_parents | Home_priv | Home_rent | Home_unknown | Marital_married | Marital_separated | Marital_single | Marital_unknown | Marital_widow | Records_yes | Job_freelance | Job_others | Job_partime | Job_unknown |
|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|
| u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 | u32 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |


# 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_.*$"))
```


shape: (2, 10)

| Exterior_1st_BrkFace | Exterior_1st_CemntBd | Exterior_1st_HdBoard | Exterior_1st_MetalSd | Exterior_1st_Plywood | Exterior_1st_Stucco | Exterior_1st_VinylSd | Exterior_1st_Wd Sdng | Exterior_1st_WdShing | Exterior_1st_other |
|----|----|----|----|----|----|----|----|----|----|
| i8 | i8 | i8 | i8 | i8 | i8 | i8 | i8 | i8 | i8 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |


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.
