Sub topic 9
Logging Models with Signatures
Prerequisites
This chapter assumes that you know basic Python, can train a scikit-learn model, and understand a train/test split. You should also know how to create an MLflow run and log parameters or metrics.
A model signature describes the data a model expects as input and the data it produces as output. MLflow stores this signature with the logged model. The signature helps users detect incompatible inputs before sending data to a production model.
Why signatures matter
A model can be trained successfully and still fail later because serving code sends the wrong columns, data types, or shape. For example, a model trained with four named features may receive three unnamed values during inference.
A signature records details such as:
- Input column names.
- Input data types.
- Whether an input is required or optional.
- Output columns and output types.
- Tensor shapes for supported tensor inputs.
The signature documents the model interface. It does not prove that the features have the correct business meaning. A column called age can still contain invalid values even when its type is correct.
Inferring a signature
The usual workflow is to train the model, generate predictions on representative input data, and pass both the input and output to infer_signature.
import mlflow
from mlflow.models import infer_signature
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True, as_frame=True)
model = LogisticRegression(max_iter=200)
model.fit(X, y)
predictions = model.predict(X)
signature = infer_signature(X, predictions)
mlflow.set_experiment("iris-signatures")
with mlflow.start_run(run_name="logistic-regression-with-signature") as run:
mlflow.sklearn.log_model(
sk_model=model,
name="model",
signature=signature,
input_example=X.head(3),
)
print("run_id:", run.info.run_id)
print("signature:", signature)X is a pandas DataFrame, so MLflow can infer the feature names and their types. The prediction array lets MLflow infer the output type. The input_example stores a small example of valid input with the model. Tools such as the MLflow UI can display this example to help users understand how to call the model.
Use representative input for signature inference. If you infer a signature from an empty DataFrame or from data with incorrect types, the stored contract may not describe real requests.
What a signature does and does not validate
When a model is loaded through an MLflow flavor, MLflow can validate input against the signature. Validation may detect missing columns, unexpected columns, incompatible types, or an invalid tensor shape.
| Signature detail | Example problem it can reveal |
|---|---|
| Column name | `petal length` is missing |
| Data type | A string is supplied where a number is expected |
| Required field | A required feature is omitted |
| Shape | A tensor has the wrong number of dimensions |
Validation cannot detect every data-quality error. It usually cannot determine whether a value is realistic, whether units are correct, or whether a categorical value is allowed by your business rules. Add explicit validation for those requirements at the application boundary.
Inspecting and loading the logged model
The model artifact contains the serialized model and MLflow metadata, including the signature and input example. You can load it with the scikit-learn flavor or the general pyfunc interface.
import mlflow
import pandas as pd
model_uri = "runs:/REPLACE_WITH_RUN_ID/model"
loaded_model = mlflow.pyfunc.load_model(model_uri)
request = pd.DataFrame(
{
"sepal length (cm)": [5.1],
"sepal width (cm)": [3.5],
"petal length (cm)": [1.4],
"petal width (cm)": [0.2],
}
)
prediction = loaded_model.predict(request)
print(prediction)Replace REPLACE_WITH_RUN_ID with the run ID printed by the previous program. The request must contain the feature columns used during training. The pyfunc interface gives callers a consistent predict method, even when the underlying model uses a different framework.
Common errors
- Inferring from transformed data without documenting the transformation: The signature may describe scaled or encoded columns rather than the original request fields.
- Changing feature names between training and serving: Renaming a column breaks the model contract.
- Logging only the serialized model: A model without a signature leaves callers to guess the input format.
- Using a misleading input example: The example should use valid, representative values and the same column structure as real requests.
- Assuming signatures version preprocessing: If preprocessing happens outside the model, log its code, configuration, and version separately, or package preprocessing with the model.
Exercise
Why should infer_signature receive both the model input and a prediction output?
Show answer
MLflow needs the input to describe the accepted feature names, types, and shapes, and it needs the output to describe the prediction type, columns, or shape.