Sub topic 4
Logging a model with a signature
This chapter assumes you can train a scikit-learn model and that you know MLflow Tracking basics: runs, artifacts, and mlflow.set_experiment. You also need the tracking server from the previous chapter, running at http://127.0.0.1:5000. By the end you will be able to log a model whose input and output schema is recorded with it. You will also know how that schema is enforced when the model is loaded, and which errors to expect.
Why the registry cares about signatures
The registry stores pointers to logged model artifacts. It does not check that a version can be called safely. The artifact itself carries the contract.
A model signature is the part of that contract that describes the data going in and out. It is stored in the MLmodel file next to the model. It lists the input columns (or tensors) with their types, and the output type.
A signature gives you three things:
- A readable contract for anyone who finds the model version later.
- Input checking in
mlflow.pyfuncmodels, so bad requests fail with a clear message instead of a confusing error from deep inside scikit-learn. - Compatibility with registries and serving tools that expect a signature. Databricks Unity Catalog, for example, requires one to register a model. The open-source registry does not, but you should treat it as required anyway.
Two kinds of signature
infer_signature(model_input, model_output) looks at the Python types you pass and builds one of two shapes.
| Input you pass | Signature type | Each field records |
|---|---|---|
| pandas DataFrame | Column-based | Column name, data type, required or optional |
| NumPy array | Tensor-based | Data type and shape, with `-1` for the batch dimension |
The two kinds are not interchangeable. A model logged with a tensor signature expects an array. A model logged with a column signature expects named columns, and it can validate that those names exist.
For tabular models, use a DataFrame. Column names make the contract much more useful. A four-column array with the wrong column order will still pass a tensor check, because only the dtype and shape are compared.
Logging the model
This script trains on the iris data, infers a signature from a DataFrame, and logs the model with an input example. Run it against the tracking server.
import mlflow
from mlflow.exceptions import MlflowException
from mlflow.models import infer_signature
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment("iris-classifier")
X, y = load_iris(return_X_y=True, as_frame=True)
model = LogisticRegression(max_iter=200).fit(X, y)
predictions = model.predict(X)
signature = infer_signature(X, predictions)
print(signature.inputs.input_names())
with mlflow.start_run() as run:
mlflow.sklearn.log_model(
model,
artifact_path="model",
signature=signature,
input_example=X.head(3),
)
run_id = run.info.run_id
print(run_id)
loaded = mlflow.pyfunc.load_model(f"runs:/{run_id}/model")
print(loaded.predict(X.head(2)))
try:
loaded.predict(X.drop(columns=[X.columns[0]]))
except MlflowException as exc:
print("rejected:", exc)The first print shows the four feature names, such as sepal length (cm). The predict call with all four columns returns class labels. The last call drops a column, so the loaded model raises an MlflowException that names the missing input.
If you use MLflow 3, artifact_path is deprecated in favor of a name argument, and the model is addressed through a logged-model URI. The runs:/<run_id>/model URI used here still works for models logged this way. The rest of this tutorial uses artifact_path, so check which style your installed version expects.
How inference works
infer_signature does not inspect the model. It only inspects the two objects you give it. That has two consequences.
First, the signature is only as good as the sample you pass. If you pass X and model.predict(X), the signature describes the training data's types, including whether a column is integer or floating point. Pass a sample that has the same types your serving code will send.
Second, the output side comes from whatever you pass as model_output. For a classifier, model.predict(X) gives an integer array and the output is a tensor of int64. If you want probabilities as the output, pass model.predict_proba(X) and make sure the model's predict behavior matches what you recorded. The signature does not change what the model returns. It only documents it, so a mismatch is a bug you introduced.
What enforcement does and does not do
When you load with mlflow.pyfunc.load_model, MLflow applies schema enforcement before calling the underlying model. For column-based signatures, the rules are:
- Every required column must be present. A missing column raises an
MlflowException. - Extra columns are ignored.
- Column order does not matter, because columns are matched by name.
- A value is converted only when no information is lost. An integer column sent to a
doublefield is converted. A float sent to anintfield is rejected.
Some details commonly trip people up:
- An integer column that contains missing values is read by pandas as floating point. If your training data had no missing values, the inferred type is
long, and serving requests with missing values will then fail the check. If a column can be missing in production, declare it asdouble, or mark it optional. - Enforcement happens only in the pyfunc flavor. If you load with
mlflow.sklearn.load_model, you get the raw scikit-learn object back, and no signature check runs. - Enforcement checks types and names. It does not check value ranges, so a negative petal length passes.
Setting a signature by hand
Sometimes inference gives the wrong answer. A column may be absent from your sample, or a column may be optional. You can build the signature directly from a Schema.
from mlflow.models import ModelSignature
from mlflow.types.schema import ColSpec, Schema
input_schema = Schema(
[
ColSpec("double", "sepal length (cm)"),
ColSpec("double", "sepal width (cm)"),
ColSpec("double", "petal length (cm)"),
ColSpec("double", "petal width (cm)"),
]
)
output_schema = Schema([ColSpec("long")])
signature = ModelSignature(inputs=input_schema, outputs=output_schema)
print(signature)This describes the same contract as the inferred one, but you control every type. Pass signature to log_model as before.
Input examples
input_example stores a few real rows next to the model, in input_example.json. It has three uses:
- People reading the artifact see a valid request.
- Serving tools can use it to build a test call.
- Recent MLflow versions can infer a signature from the example when you do not pass one. Do not rely on this for important models. Passing
signatureexplicitly makes the logged contract obvious in your code review.
Keep the example small. It is stored as a file, and a large frame is wasted space.
Where this fits before registration
A run holds the logged model. A registered model version points at that logged model through a URI such as runs:/<run_id>/model. The version does not copy a new contract. It inherits the signature of the artifact it points to.
That has a practical effect. If you register a model that has no signature, every later version created from that run has none either, and you cannot add one to the version afterwards. You would have to log the model again from a new run. Setting the signature at log time is the only cheap time to do it.
You can add registered_model_name="iris-classifier" to the log_model call to log and register in one step. The next chapter covers registration in full.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `MlflowException` about a missing column | Request lacks a column the signature requires | Send every required column, or mark it optional when you build the signature |
| Error about converting `float64` to `int64` | Request sends decimals to an integer field | Fix the data, or change the field to `double` |
| Warning that no signature was found | `log_model` called without `signature` or `input_example` | Log again from a new run with a signature |
| Tensor shape mismatch | Signature was inferred from an array of a different width | Infer from a DataFrame, or pass an array with the right shape |
| No error on bad input | Loaded through `mlflow.sklearn.load_model` | Load with `mlflow.pyfunc.load_model` |
Exercise
You log a model by calling infer_signature on a NumPy array of shape (150, 4) and then register it. A serving team reports that requests with the four features in a different order return wrong predictions and no error. Why did enforcement not catch it, and what would you change?
Show answer
A NumPy input produces a tensor-based signature, which records only the dtype and shape (-1, 4). A reordered request still has four float64 values, so it passes. Infer the signature from a pandas DataFrame instead, so the signature records column names and requests are matched by name. Because the signature is part of the logged artifact, you must log the model again from a new run and register the new version.
Exercise
A model was logged with an integer column "age" inferred as long. In production, some requests have a missing age, and pyfunc predict starts failing. What are two ways to fix this?
Show answer
Pandas turns an integer column with missing values into floating point, and a float is not safely convertible to long, so enforcement rejects it. Either declare "age" as double in the signature, or define the column as optional with an explicit Schema. Both require logging the model again with the corrected signature.