Aller au contenu

Leçon 11 · Models and Signatures

Signatures and Input Examples

Define what a model accepts and returns with MLflow signatures, add input examples and parameters, and learn the main schema enforcement rules.

A model expects input in a particular shape. If someone sends a column with the wrong type, you want a clear error, not a strange prediction. A model signature is the contract of a model, and an input example is a sample that makes the contract concrete.

The three parts of a signature

  1. Inputs: column names and types (for tables), or tensor shapes and types (for arrays). Fields can be marked optional.
  2. Outputs: the shape and types of what comes back.
  3. Params (optional): settings that callers may change at prediction time, with defaults.

The easy way: provide an input example

Python
import mlflow

with mlflow.start_run():
    info = mlflow.sklearn.log_model(
        model, name="churn", input_example=X_train.head(3)
    )

When you pass an input example, MLflow can infer the signature from it, check that the model runs on it, and store both with the model.

Infer or set a signature yourself

For more control, use infer_signature:

Python
from mlflow.models import infer_signature

signature = infer_signature(X_train, model.predict(X_train))
mlflow.sklearn.log_model(model, name="churn", signature=signature)

You can also attach a signature to an already saved or logged model with mlflow.models.set_signature. Some registries, such as Databricks Unity Catalog, require a signature.

Inference parameters

Params are useful for things like a decision threshold or generation settings:

Python
signature = infer_signature(
    X_train, model.predict(X_train), params={"threshold": 0.5}
)

The caller then passes params={"threshold": 0.7} to predict. A custom model must actually read the parameter, because adding it to the signature does not change the logic of the model. Parameter values must be scalars or one-dimensional lists.

Enforcement rules

MLflow checks input against the signature when a model is loaded as pyfunc, served over REST, or used by deployment tools. The documented rules include:

  • Required columns must be present, while optional ones may be missing.
  • Extra columns are ignored and not passed to the model.
  • Safe type conversions are allowed, such as int to double. Unsafe ones, such as string to int, are rejected.
  • Unknown params produce a warning, and omitted params use their defaults.

Loading the native flavor, for example with mlflow.sklearn.load_model, gives you the plain library object, without these pyfunc checks.

A stand-in validator

The block below imitates a few of these rules. It is much simpler than the real schema system.

Python Stand-in: check input against a schema

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The missing-values trap

If a whole-number column contains missing values, pandas often stores it as decimals. A signature inferred from clean training data says "integer", and then real requests with a blank value can fail. If a column can be missing in real life, define it as double from the start.

Signatures check shape and type, not meaning. An age of -5 or an amount in the wrong currency passes the type check. Add your own range checks in preprocessing or in a custom model.

Design the contract on purpose

A signature that is inferred from a sample describes that sample, not necessarily your real intent. Before you accept it, review these points:

Check Question to ask
Column names Are they clear and stable?
Types Could real data have a wider type, such as decimals?
Optional fields Which columns can be missing in real requests?
Output Does the output shape match what callers expect?
Params Are the defaults safe?

Changing a signature later can break callers. If a new model needs another column, treat it as an interface change: tell the users of the model, version it, and plan the switch.

Where errors appear

Schema errors are most useful early. Test the model with a wrong request before it is deployed:

Python
loaded = mlflow.pyfunc.load_model(info.model_uri)

bad = X_test.head(3).drop(columns=[X_test.columns[0]])
try:
    loaded.predict(bad)
except Exception as error:
    print("Rejected as expected:", type(error).__name__)

If this request succeeds, your signature is weaker than you think, or the column was marked optional. Add a few such tests to your pipeline.

Tensor models

For models that work on arrays, such as images, the signature describes the data type and shape of tensors, and the first dimension is usually flexible, so you can send any number of items. Check that the shape matches what your preprocessing produces. A common bug is channel order, which a type check cannot detect, because both orders have the same type and size.

Documentation for humans

A signature tells software what to send. People also need meaning: what each column stands for, its unit and its allowed range. Put that in the model description or a short document attached as an artifact. Good documentation prevents a caller from sending monthly income where you expect yearly income, which would pass every type check.

Input examples and privacy

The input example is saved with the model, so anyone who can read the model can read it. Do not take the first rows of a customer table without thinking. Build a small synthetic example with the same column names and types, using made-up values that are clearly fake. Make sure that it still covers the types you expect, such as a decimal column that should accept missing values. This gives you the benefit of an example without exposing a real person.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. Which part of a signature lets callers change a setting at prediction time?

    The params schema lists settings with defaults that can be overridden at inference.
  2. 2. What happens to extra input columns under signature enforcement?

    Columns not in the schema are not passed to the model.
  3. 3. A whole-number column sometimes has missing values. What is a safer type?

    Missing values usually force a decimal type, so declaring double avoids surprise rejections.

Summary

  • A signature defines inputs, outputs and optional params.
  • An input example helps MLflow infer the signature and test the model.
  • Pyfunc loading and serving enforce the schema.
  • Type checks do not replace checks on values.

Next: Custom PyFunc Models

Votre progression est enregistrée dans ce navigateur. Aucun compte nécessaire.