Skip to main content

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.

  • 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

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

recipe = (
    Recipe(data=credit_train, target="Status")
    .add(StepImputeMedian(s.numeric_features()))
    .add(StepNormalize(s.numeric_features()))
)
fitted = recipe.fit(credit_train)
fitted
Recipe (trained)
  Inputs: 14 columns (13 features, 1 target)
  Steps:
    step_impute_median(Seniority, Time, Age, Expenses, Income, Assets, Debt, Amount, Price)  [trained]
    step_normalize(Seniority, Time, Age, Expenses, Income, Assets, Debt, Amount, Price)      [trained]

The recipe is still the untrained specification:

recipe
Recipe (untrained)
  Inputs: 14 columns (1 target)
  Steps:
    step_impute_median(select(role='feature', type=NumericType))  [untrained]
    step_normalize(select(role='feature', type=NumericType))      [untrained]

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.

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()
shape: (5, 14)
StatusSeniorityHomeTimeAgeMaritalRecordsJobExpensesIncomeAssetsDebtAmountPrice
strf64strf64f64strstrstrf64f64f64f64f64f64
"bad"-0.86776"owner"0.915250.286994"married""no""fixed"-0.548023null-0.220421-0.1479321.4624620.535977
"bad"-0.499015null0.0897570.923549"married""yes""freelance"-0.548023nullnullnull0.696931.184969
"good"0.238474"owner"0.91525-0.804243"married""no""freelance"-0.548023null-0.118696-0.3197580.368844-0.389041
"bad"-0.990675"owner"-0.7357360.468867"married""no""freelance"0.229539null-0.016971-0.3197580.696930.655918
"bad"-0.990675"other"0.089757-0.986116"married""no""others"-0.548023null-0.169558-0.3197580.8062910.02007

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.

fitted.transform(credit_validation).head()
shape: (5, 14)
StatusSeniorityHomeTimeAgeMaritalRecordsJobExpensesIncomeAssetsDebtAmountPrice
strf64strf64f64strstrstrf64f64f64f64f64f64
"good"0.238474"rent"0.91525-0.804243"married""no""fixed"1.1626142.238271-0.5237632.544012.6654411.313124
"bad"-0.3761"owner"-0.32299-0.440498"married""no""fixed"0.229539-0.568760.0847530.4439141.4624621.475783
"good"-0.3761"parents"0.91525-1.167989"single""no""fixed"-1.066398-0.617791-0.525594-0.319758-0.002985-0.628921
"good"2.696773"owner"0.5025031.560104"widow""no""freelance"-1.0663981.0002351.508897-0.3197580.1501210.250093
"good"-0.86776"parents"-1.561229-1.440798"single""no""partime"-1.066398-0.642307-0.525594-0.319758-0.287326-0.23624

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.

restored = from_json(to_json(fitted))
restored.transform(credit_validation).head()
shape: (5, 14)
StatusSeniorityHomeTimeAgeMaritalRecordsJobExpensesIncomeAssetsDebtAmountPrice
strf64strf64f64strstrstrf64f64f64f64f64f64
"good"0.238474"rent"0.91525-0.804243"married""no""fixed"1.1626142.238271-0.5237632.544012.6654411.313124
"bad"-0.3761"owner"-0.32299-0.440498"married""no""fixed"0.229539-0.568760.0847530.4439141.4624621.475783
"good"-0.3761"parents"0.91525-1.167989"single""no""fixed"-1.066398-0.617791-0.525594-0.319758-0.002985-0.628921
"good"2.696773"owner"0.5025031.560104"widow""no""freelance"-1.0663981.0002351.508897-0.3197580.1501210.250093
"good"-0.86776"parents"-1.561229-1.440798"single""no""partime"-1.066398-0.642307-0.525594-0.319758-0.287326-0.23624

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 for the file format and for minimize(), which strips fit-only artifacts before saving.