# Fit and transform

Fitting a recipe estimates everything its steps need from the training data and hands back a separate [FittedRecipe](../../reference/FittedRecipe.md#mlfeatures.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.

> **Note: Key points**
>
> - [fit()](../../reference/Step.fit.md#mlfeatures.Step.fit) estimates what each step needs and stores it on the fitted steps
> - selectors are resolved once, at fit time
> - [fit()](../../reference/Step.fit.md#mlfeatures.Step.fit) returns a new [FittedRecipe](../../reference/FittedRecipe.md#mlfeatures.FittedRecipe) and leaves the recipe untouched
> - row filters such as [StepFilter](../../reference/StepFilter.md#mlfeatures.StepFilter) run at fit time only, never in [transform()](../../reference/Step.transform.md#mlfeatures.Step.transform)
> - [transform()](../../reference/Step.transform.md#mlfeatures.Step.transform) applies the same estimates to training, validation, and production data
> - a [FittedRecipe](../../reference/FittedRecipe.md#mlfeatures.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](../../reference/FittedRecipe.md#mlfeatures.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
```


    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:


``` python
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](../../reference/StepFilter.md#mlfeatures.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()
```


shape: (5, 14)

| Status | Seniority | Home | Time | Age | Marital | Records | Job | Expenses | Income | Assets | Debt | Amount | Price |
|----|----|----|----|----|----|----|----|----|----|----|----|----|----|
| str | f64 | str | f64 | f64 | str | str | str | f64 | f64 | f64 | f64 | f64 | f64 |
| "bad" | -0.86776 | "owner" | 0.91525 | 0.286994 | "married" | "no" | "fixed" | -0.548023 | null | -0.220421 | -0.147932 | 1.462462 | 0.535977 |
| "bad" | -0.499015 | null | 0.089757 | 0.923549 | "married" | "yes" | "freelance" | -0.548023 | null | null | null | 0.69693 | 1.184969 |
| "good" | 0.238474 | "owner" | 0.91525 | -0.804243 | "married" | "no" | "freelance" | -0.548023 | null | -0.118696 | -0.319758 | 0.368844 | -0.389041 |
| "bad" | -0.990675 | "owner" | -0.735736 | 0.468867 | "married" | "no" | "freelance" | 0.229539 | null | -0.016971 | -0.319758 | 0.69693 | 0.655918 |
| "bad" | -0.990675 | "other" | 0.089757 | -0.986116 | "married" | "no" | "others" | -0.548023 | null | -0.169558 | -0.319758 | 0.806291 | 0.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.


``` python
fitted.transform(credit_validation).head()
```


shape: (5, 14)

| Status | Seniority | Home | Time | Age | Marital | Records | Job | Expenses | Income | Assets | Debt | Amount | Price |
|----|----|----|----|----|----|----|----|----|----|----|----|----|----|
| str | f64 | str | f64 | f64 | str | str | str | f64 | f64 | f64 | f64 | f64 | f64 |
| "good" | 0.238474 | "rent" | 0.91525 | -0.804243 | "married" | "no" | "fixed" | 1.162614 | 2.238271 | -0.523763 | 2.54401 | 2.665441 | 1.313124 |
| "bad" | -0.3761 | "owner" | -0.32299 | -0.440498 | "married" | "no" | "fixed" | 0.229539 | -0.56876 | 0.084753 | 0.443914 | 1.462462 | 1.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.502503 | 1.560104 | "widow" | "no" | "freelance" | -1.066398 | 1.000235 | 1.508897 | -0.319758 | 0.150121 | 0.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()](../../reference/from_json.md#mlfeatures.from_json) restores it, so the transform can run in another process or on another machine without the training data. [to_yaml()](../../reference/to_yaml.md#mlfeatures.to_yaml) and [from_yaml()](../../reference/from_yaml.md#mlfeatures.from_yaml) do the same in YAML.


``` python
restored = from_json(to_json(fitted))
restored.transform(credit_validation).head()
```


shape: (5, 14)

| Status | Seniority | Home | Time | Age | Marital | Records | Job | Expenses | Income | Assets | Debt | Amount | Price |
|----|----|----|----|----|----|----|----|----|----|----|----|----|----|
| str | f64 | str | f64 | f64 | str | str | str | f64 | f64 | f64 | f64 | f64 | f64 |
| "good" | 0.238474 | "rent" | 0.91525 | -0.804243 | "married" | "no" | "fixed" | 1.162614 | 2.238271 | -0.523763 | 2.54401 | 2.665441 | 1.313124 |
| "bad" | -0.3761 | "owner" | -0.32299 | -0.440498 | "married" | "no" | "fixed" | 0.229539 | -0.56876 | 0.084753 | 0.443914 | 1.462462 | 1.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.502503 | 1.560104 | "widow" | "no" | "freelance" | -1.066398 | 1.000235 | 1.508897 | -0.319758 | 0.150121 | 0.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](../../user-guide/extra/serializing-recipes.md) for the file format and for [minimize()](../../reference/minimize.md#mlfeatures.minimize), which strips fit-only artifacts before saving.
