Sub topic 6
Storing files as artifacts
This chapter assumes you can create MLflow runs and log parameters and metrics, as covered in the previous chapters. You should also know basic pandas and matplotlib.
What an artifact is
An artifact is a file or directory stored with a run. Parameters, metrics and tags are small key-value records. Artifacts hold everything else: plots, confusion matrices, data samples, configuration files, serialized models and text reports.
Each run has its own artifact location. On Databricks, MLflow writes to that location for you, and the files appear in the Artifacts section of the run page.
| Record | Holds | Typical size |
|---|---|---|
| Parameter | One input value, such as `C` | Bytes |
| Metric | A number, optionally per step | Bytes |
| Tag | A label string | Bytes |
| Artifact | Any file or directory | Kilobytes to gigabytes |
Logging a single file
Use mlflow.log_artifact to copy one local file into the active run. The optional artifact_path argument places it in a subfolder.
import mlflow
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import ConfusionMatrixDisplay
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
model = LogisticRegression(max_iter=200).fit(X_train, y_train)
with mlflow.start_run(run_name="artifact-demo") as run:
ConfusionMatrixDisplay.from_estimator(model, X_test, y_test)
plt.savefig("confusion_matrix.png")
plt.close()
mlflow.log_artifact("confusion_matrix.png", artifact_path="plots")
print(run.info.run_id)The file is copied when you call log_artifact. Changing the local file afterwards does not change the stored copy.
Logging a directory
mlflow.log_artifacts (plural) uploads every file in a local directory.
import os
import mlflow
os.makedirs("reports", exist_ok=True)
with open("reports/summary.txt", "w") as f:
f.write("Baseline logistic regression on iris\n")
with mlflow.start_run(run_name="artifact-dir"):
mlflow.log_artifacts("reports", artifact_path="reports")Logging without a local file
For small objects you often don't need to write a file yourself. These helpers create the file for you:
mlflow.log_text(text, "notes/summary.txt")stores a string.mlflow.log_dict(obj, "config/params.json")stores a dictionary as JSON or YAML, chosen by the file extension.mlflow.log_figure(fig, "plots/roc.png")stores a matplotlib figure.mlflow.log_table(df, "predictions.json")stores a pandas DataFrame that the UI can display as a table.
import mlflow
with mlflow.start_run(run_name="inline-artifacts"):
mlflow.log_dict({"features": ["sepal_length", "sepal_width"]}, "config/features.json")
mlflow.log_text("Trained on the 2026-12 snapshot.", "notes/data_version.txt")Reading artifacts back
Use mlflow.artifacts.download_artifacts to copy a run's artifacts to local disk.
import mlflow
local_path = mlflow.artifacts.download_artifacts(
run_id="<run-id>",
artifact_path="plots/confusion_matrix.png",
)
print(local_path)Replace <run-id> with an ID printed by an earlier run.
Common errors
- File not found.
log_artifactreads the path at call time. Save the file first, and check that the notebook's working directory is what you expect. - Artifacts land in the wrong run. Calls made outside a
with mlflow.start_run()block start or reuse an active run. Keep logging inside the block. - Overwritten files. Logging the same
artifact_pathand file name twice in one run replaces or conflicts with the earlier file. Give files distinct names or folders. - Large files slow the run. Artifacts upload to storage. Log summaries or samples rather than full datasets.
Exercise
You want to store a dictionary of feature names in a run as config/features.json without creating a local file first. Which function do you call, and why use it instead of log_artifact?
Show answer
Call mlflow.log_dict(features_dict, "config/features.json"). It serializes the dictionary and stores it directly, so you don't have to write a temporary file and then pass its path to mlflow.log_artifact.
Exercise
A teammate logs plots/roc.png twice in one run, with different figures. What should they change?
Show answer
Use a different file name or artifact_path for each figure, such as plots/roc_train.png and plots/roc_test.png, so the second upload does not replace or conflict with the first.