Skip to main content

to_dict()

Serialize a FittedRecipe to a diffable, JSON-safe dict.

Usage

Source

to_dict(recipe)

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: FittedRecipe
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

recipe = Recipe().add(StepNormalize(s.numeric_features()))
fitted = recipe.fit(credit)
payload = to_dict(fitted)
payload["steps"][0]["type"]
'mlfeatures.step_normalize.StepNormalize'