Sub topic 7
Logging a Model with a Signature and Input Example
This chapter assumes you can train a scikit-learn model, use mlflow.start_run, and log parameters and metrics. It also assumes you know that a run can store artifacts, which are files attached to the run. Here you will log a trained model to a run, attach a signature and an input example, and learn the errors that follow when either is missing or wrong.
Why log the model itself
Parameters and metrics describe a run. They do not let anyone reuse it. If the best run in an experiment has an accuracy of 0.93, you still need the fitted model to serve predictions, evaluate it again, or register it.
Logging a model stores it as an artifact in a standard layout called the MLflow Model format. The folder holds three kinds of information:
- The serialized model, for example a pickled scikit-learn estimator.
- An
MLmodelfile that lists the model's flavors, its signature, and the time and run that produced it. - Environment files, such as
requirements.txtandconda.yaml, that record the library versions used.
A flavor is a way of loading the same model. A scikit-learn model has a sklearn flavor, which returns the original estimator, and a python_function flavor, which wraps it behind a common predict method. The python_function flavor, also called pyfunc, is what lets tools load models without knowing which library produced them.
Logging a model with `log_model`
Autologging can log a model for you, but the explicit call gives you control over the signature and the input example. The code below continues from the earlier chapters. It assumes model, X_test, and mlflow already exist in your notebook.
from mlflow.models import infer_signature
preds = model.predict(X_test)
signature = infer_signature(X_test, preds)
with mlflow.start_run(run_name="explicit-model-log") as run:
mlflow.sklearn.log_model(
model,
artifact_path="model",
signature=signature,
input_example=X_test[:5],
)
print(run.info.run_id)The arguments do the following:
modelis the fitted estimator.artifact_pathis the folder name inside the run's artifacts. You use it later in URIs such asruns:/<run_id>/model.signaturedescribes the model's inputs and outputs.input_exampleis a few real input rows saved next to the model.
Newer MLflow releases may show name in place of artifact_path in their documentation. Check the version on your cluster before you copy an example, since older runtimes accept only artifact_path.
What a signature is
A signature is a schema for the model. It lists the name and data type of each input column and each output. MLflow stores it in the MLmodel file.
Signatures matter for three reasons:
- They document the model. Anyone who opens the run can see what the model expects.
- They are enforced when you load the model as pyfunc. If you pass the wrong columns or types, MLflow raises an error before the model runs.
- Unity Catalog requires one. You cannot register a model in Unity Catalog without a signature, which is covered later in this tutorial.
Inferring a signature
infer_signature(model_input, model_output) looks at sample data and builds the schema from it. The input can be a pandas DataFrame, a NumPy array, or a dictionary. The result depends on the type you pass.
| Input type | Signature produced |
|---|---|
| pandas DataFrame | Column-based schema with names and types |
| NumPy array | Tensor-based schema with a dtype and shape |
| Dictionary of arrays | Named tensor schema |
In the example above, X_test is a NumPy array, so the signature is tensor-based. It records a float64 input with shape (-1, 4) and an int64 output with shape (-1,). The -1 means any batch size.
If you want named columns, train and score with a DataFrame. Named columns are easier to read in the UI and safer for callers, because column order mistakes become errors rather than silent mistakes.
import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris(as_frame=True)
X_df = iris.data
print(X_df.columns.tolist())If you train on X_df instead of a bare array, infer_signature records the four column names such as sepal length (cm). Those names include spaces and parentheses, which is legal but awkward. Many teams rename columns before training.
Gotchas with inferred signatures
Inference reads whatever you give it, so it can capture the wrong thing.
- Integer columns with missing values. A column that is
int64in your sample may contain nulls in production. Pandas turns such columns into floats, and the enforced schema then rejects them or converts them. Declare the column as a float, or as an optional type, in the signature if nulls can occur. - Output type mismatch. Passing probabilities as the output when the deployed model returns class labels creates a signature that does not match behavior. Use the same method for the output that callers will use.
- Tiny samples. Inference from a sample that lacks a category or has only one type of value can narrow the schema.
For full control, build the schema by hand.
from mlflow.models.signature import ModelSignature
from mlflow.types.schema import Schema, ColSpec
input_schema = Schema([
ColSpec("double", "sepal_length"),
ColSpec("double", "sepal_width"),
ColSpec("double", "petal_length"),
ColSpec("double", "petal_width"),
])
output_schema = Schema([ColSpec("long")])
manual_signature = ModelSignature(inputs=input_schema, outputs=output_schema)
print(manual_signature)A hand-built signature only works if the model's real inputs match it. If you name columns that the model never saw, scoring fails at load time or gives wrong results.
What an input example is
An input example is a small set of real input rows, saved as JSON next to the model. It does two jobs.
- It shows a reader a concrete example of valid input.
- When you pass an
input_examplewithout a signature, MLflow can infer the signature from it. When you pass both, MLflow also uses the example to check that the model loads and scores.
In the Databricks UI, the run's model page shows the example, and it appears in generated code snippets for loading the model.
Keep examples small. Five rows is usually enough. Do not include sensitive data such as personal information, because the example is stored in plain text with the run and anyone with read access to the experiment can see it.
Autologging versus explicit logging
mlflow.sklearn.autolog() logs a model by default, and it infers a signature and an input example when it can. That covers many cases. Use log_model yourself when:
- you want the model logged from a pipeline you built yourself, not from the last
fitcall; - you need a hand-built signature;
- you want to log a model only for runs that pass a quality check;
- you train with several estimators in one run and need to say which one counts.
If you leave autologging on and also call log_model, the run holds two logged models. Pick one approach per run, or pass log_models=False to autolog() when you log models yourself.
Where the model lives and how to inspect it
After the run finishes, open it in the experiment UI and look at the Artifacts section. You will see the model folder with MLmodel, model.pkl, requirements.txt, and the input example file. Selecting MLmodel shows the signature as YAML.
You can read the same information in code:
import mlflow
from mlflow.models import get_model_info
info = get_model_info(f"runs:/{run.info.run_id}/model")
print(info.signature)
print(info.flavors.keys())To confirm that the model loads and that the signature is enforced, load it as pyfunc and score the example.
loaded = mlflow.pyfunc.load_model(f"runs:/{run.info.run_id}/model")
print(loaded.predict(X_test[:3]))Passing an array with the wrong number of columns, such as X_test[:3, :2], raises an MlflowException that names the expected shape. This is the signature working as intended.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Registration fails because the model has no signature | The model was logged without one | Log again with `signature=` or an `input_example` |
| `MlflowException` about missing columns at predict time | Input columns differ from the signature | Pass the columns and types the signature lists |
| Schema enforcement rejects an integer column | Training sample was integer, production data has nulls | Declare the column as `double` |
| Two models appear in one run | Autolog and `log_model` both ran | Set `log_models=False` in `autolog()` |
| Warning that the model has no input example | `input_example` was omitted | Pass a few rows of real input |
Reproducibility notes
The model folder records the Python and library versions in requirements.txt and conda.yaml. These files are inferred from the packages imported when the model was logged, so they are usually accurate but can miss libraries that you load dynamically. Check them before you deploy.
Exercises
Exercise
You log a model trained on a NumPy array and then call loaded.predict with a DataFrame that has four named columns. Why might this still work, and what does the signature type tell you about it?
Show answer
A tensor-based signature, which NumPy input produces, records only a dtype and shape, not column names. A DataFrame with four numeric columns of the right dtype therefore passes the shape check. Only a column-based signature, produced from a DataFrame, enforces names, so name mistakes would be caught only if you had trained with a DataFrame.
Exercise
Your team wants to register a model in Unity Catalog, but registration fails. The log_model call had no signature and no input_example. Give two ways to fix the logged model.
Show answer
Log the model again with signature=infer_signature(X_test, preds). Alternatively, pass input_example=X_test[:5] so MLflow can infer the signature from it. You can also build a ModelSignature by hand and pass it as signature.