Sub topic 2
Adding a Signature and Input Example
This chapter assumes you can train a scikit-learn model, have logged one with mlflow.sklearn.log_model, and know that a pandas DataFrame has typed columns. You do not need a Unity Catalog workspace to run the code here. It uses a local MLflow run.
Why a logged model needs a contract
A model file stores learned parameters. It does not say which columns it expects, what types they have, or what shape the output takes. Without that information, every caller has to guess. A client that sends "5.1" as a string instead of 5.1 as a number may get an obscure error deep in the model code, or a silently wrong answer.
MLflow solves this with two pieces of metadata stored next to the model:
- A signature is a schema for the model's inputs and outputs. It lists column names and data types.
- An input example is a small piece of real sample input saved with the model.
Both matter later in this tutorial. Unity Catalog refuses to register a model that has no signature. Model Serving also relies on the signature to validate the JSON your clients send.
Inferring a signature
The quickest way to get a signature is infer_signature. You give it sample inputs and the model's outputs on those inputs. It reads the column names and types from them.
import mlflow
from mlflow.models import infer_signature
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
X, y = load_iris(return_X_y=True, as_frame=True)
model = RandomForestClassifier(n_estimators=50, random_state=0).fit(X, y)
predictions = model.predict(X)
signature = infer_signature(X, predictions)
print(signature)The printed signature has an inputs part and an outputs part. The inputs are four named columns of type double. The Iris data has no missing values, so none are marked optional. The output is a NumPy array of integers. A bare array has no column names, so MLflow describes it as a tensor of type int64 with shape (-1,). The -1 means any number of rows.
Pass X and predictions exactly as the model sees them at prediction time. If you pass in a version of X that you scaled or reordered before training, the signature describes the wrong thing.
> A signature records what you showed it, not what the model can handle. infer_signature cannot detect that a column was meant to accept nulls if your sample had none.
Writing a signature by hand
Inference is convenient, but a hand-written signature lets you control types. This matters when your sample data is not representative. For example, an integer column that is sometimes empty in production arrives as floats with NaN values.
import numpy as np
from mlflow.models import ModelSignature
from mlflow.types.schema import ColSpec, Schema, TensorSpec
input_schema = Schema([ColSpec("double", name) for name in X.columns])
output_schema = Schema([TensorSpec(np.dtype("int64"), (-1,))])
explicit_signature = ModelSignature(inputs=input_schema, outputs=output_schema)
print(explicit_signature == signature)This prints True, because the hand-written schema describes the same thing the inference produced. Use ColSpec for column-based data such as a DataFrame. Use TensorSpec for array-based data such as images or a plain NumPy array. A single schema must use one kind or the other, not both. The input and output schemas may differ in kind, as they do here.
You can mark a column optional with ColSpec("double", "income", required=False). Callers may then leave that column out.
Logging with a signature and input example
Both pieces are arguments to log_model.
with mlflow.start_run() as run:
mlflow.sklearn.log_model(
model,
artifact_path="model",
signature=signature,
input_example=X.head(5),
)
model_uri = f"runs:/{run.info.run_id}/model"MLflow writes the signature into the MLmodel file in the model's artifact folder. It writes the input example as a JSON file in the same folder. If you pass input_example and omit signature, recent MLflow versions try to infer the signature by running the example through the model. Treat this as a fallback. Passing the signature yourself makes the result explicit and visible in your code review.
Keep the input example small and realistic. A handful of rows is enough. Do not put sensitive records in it, because it is stored in plain text alongside the model, and anyone who can read the model can read the example.
Schema enforcement at prediction time
When you load a model as a pyfunc model, MLflow checks incoming data against the signature before calling the model. This is called schema enforcement. You can see it locally.
import pandas as pd
from mlflow.exceptions import MlflowException
loaded = mlflow.pyfunc.load_model(model_uri)
# A valid request: same columns, same types
print(loaded.predict(X.head(2)))
# An invalid request: one column is missing
bad = X.head(2).drop(columns=["petal width (cm)"])
try:
loaded.predict(bad)
except MlflowException as err:
print("Rejected:", err)The first call returns two class labels. The second raises an MlflowException that names the missing input. The model code never runs for the bad request.
Enforcement covers three things:
- Names. Every required column in the signature must be present. Extra columns are ignored for column-based schemas.
- Types. Values must convert to the declared type without losing information. An integer can widen to a double. A double with a fractional part cannot become an integer.
- Shape. For tensor-based schemas, the array must match the declared shape and dtype.
What the input example is for
The signature is a type description. The input example is a concrete value. It serves three purposes:
- Documentation. Someone browsing the model can see what a real request looks like.
- Signature inference. As noted above, MLflow can derive a signature from it.
- Testing. You can replay it through a loaded model to confirm the model still works after you change library versions.
example_check = loaded.predict(X.head(5))
print(example_check)The input example does not enforce anything. Only the signature does.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Registration fails and mentions a missing signature or signature without outputs | `signature` was omitted, or it was built with inputs only | Use `infer_signature(X, model.predict(X))` so both inputs and outputs are present |
| `Model is missing inputs [...]` | A client sent JSON without a required column, or with misspelled column names | Check column names against the signature, including spaces and units such as `(cm)` |
| Error about converting `float64` to `int64` | The signature says integer but the data has fractions or nulls | Declare the column as `double`, or mark it `required=False` if it can be absent |
| Signature shows `long` for a column you meant as a float | The sample you inferred from held whole numbers only | Write the schema by hand with `ColSpec("double", ...)` |
| Signature describes columns that the model does not actually use | You inferred from a DataFrame that had extra columns | Infer from the exact frame passed to `model.predict` |
| Model works in the notebook but fails when served | The notebook accepted a looser input than the signature allows, for example calling the raw model, not the `pyfunc` wrapper | Test with `mlflow.pyfunc.load_model`, because that applies enforcement |
The last row deserves emphasis. Calling model.predict on the original scikit-learn object skips schema enforcement. Calling loaded.predict on the pyfunc model applies it. Always test the second form before you register.
Decision guide
Use infer_signature when your training frame is representative and all its columns have the types you want served. Write the signature by hand when:
- A column can contain nulls or may be omitted.
- A column is an integer in training but arrives as a decimal.
- You want the output schema to use named columns, for example
probability_setosa, instead of a bare array. - The model takes tensors with a fixed shape and you need to control it.
Whichever route you take, print the signature and read it before logging. It takes ten seconds and catches most of the errors in the table above.
Looking ahead
The next chapter turns to naming. The model you just logged has a run URI, such as runs:/<run_id>/model. Unity Catalog will give it a permanent three-level name, and the signature you added here is what makes that registration possible. When you reach the querying chapter, the column names in this signature will appear again as keys in your JSON payload.
Exercise
You log a model whose input signature was inferred from a DataFrame with an integer column age. In production, some requests send "age": 41.5. What happens when the model is called through pyfunc or a serving endpoint, and how would you change the logging step so those requests are accepted?
Show answer
Schema enforcement rejects the request, because a float with a fractional part cannot be converted to an integer without losing information. To fix it, declare the column as double by writing the signature by hand, for example ColSpec("double", "age"), then log a new model version with that signature. Changing the sample data alone is not enough unless it already contains fractional values. Existing versions keep their old signature, so the endpoint must be updated to the new version.
Exercise
Why does Unity Catalog registration need infer_signature(X, model.predict(X)) and not infer_signature(X), and why should you test with mlflow.pyfunc.load_model instead of calling the scikit-learn model directly?
Show answer
Unity Catalog requires a signature that describes both inputs and outputs, and infer_signature(X) produces inputs only. Testing through mlflow.pyfunc.load_model applies schema enforcement, which is what a serving endpoint will do. Calling the raw scikit-learn object skips enforcement, so type and column problems stay hidden until deployment.