Skip to main content

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.

  • 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

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.

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() 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:

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)
StatusSeniorityTimeAgeExpensesIncomeAssetsDebtAmountPriceHome_otherHome_ownerHome_parentsHome_privHome_rentMarital_marriedMarital_separatedMarital_singleMarital_widowRecords_yesJob_freelanceJob_othersJob_partime
u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32
0000099155001111100000000

With imputation first, and StepUnknown giving missing categoricals their own "unknown" level, nothing is left for a model to trip on:

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)
StatusSeniorityTimeAgeExpensesIncomeAssetsDebtAmountPriceHome_otherHome_ownerHome_parentsHome_privHome_rentHome_unknownMarital_marriedMarital_separatedMarital_singleMarital_unknownMarital_widowRecords_yesJob_freelanceJob_othersJob_partimeJob_unknown
u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32u32
00000000000000000000000000

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:

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_BrkFaceExterior_1st_CemntBdExterior_1st_HdBoardExterior_1st_MetalSdExterior_1st_PlywoodExterior_1st_StuccoExterior_1st_VinylSdExterior_1st_Wd SdngExterior_1st_WdShingExterior_1st_other
i8i8i8i8i8i8i8i8i8i8
0000000001
0000000001

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.