Sub topic 5
Logging artifacts: files, plots and data
Assume you know basic Python, can train a scikit-learn model, and have a local MLflow tracking server running. This chapter focuses on artifacts: files produced during a run that help you inspect, validate, or reproduce the result.
What artifacts are
An artifact is a file associated with an MLflow run. Examples include:
- A plot showing a confusion matrix.
- A CSV file containing predictions.
- A JSON file containing an evaluation report.
- A text file containing notes.
- A serialized model.
Parameters, metrics, and tags are run metadata. They are useful for filtering and comparison. Artifacts contain larger or richer evidence from the run.
For example, a metric can tell you that accuracy was 0.93. A confusion-matrix image can show which classes caused the errors.
Where artifacts go
MLflow separates run metadata from artifact files. The tracking client sends both through the tracking server, but they may use different storage systems.
For local development, the artifact store might be a directory such as ./mlartifacts. In a team deployment, it might be object storage such as Amazon S3 or Azure Blob Storage. Your code should use MLflow logging functions rather than writing directly into the artifact store.
Every artifact has a path relative to the run's artifact root. You can group files with an artifact_path, such as plots or evaluation.
Logging files and generated content
Use mlflow.log_artifact() for one existing file and mlflow.log_artifacts() for all files in a directory. Use mlflow.log_text() and mlflow.log_dict() when the content starts as a Python string or dictionary.
The following example logs a plot, a prediction table, an evaluation report, and notes in one run. It assumes the server is available at http://127.0.0.1:5000.
import json
import matplotlib.pyplot as plt
import mlflow
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import ConfusionMatrixDisplay, classification_report
from sklearn.model_selection import train_test_split
mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment("iris-artifacts")
data = load_iris(as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
data.data,
data.target,
test_size=0.2,
random_state=42,
stratify=data.target,
)
with mlflow.start_run(run_name="artifact-example"):
model = LogisticRegression(max_iter=200).fit(X_train, y_train)
predictions = model.predict(X_test)
report = classification_report(
y_test,
predictions,
output_dict=True,
target_names=data.target_names,
)
mlflow.log_dict(report, "evaluation/classification_report.json")
prediction_table = X_test.copy()
prediction_table["actual"] = y_test.to_numpy()
prediction_table["predicted"] = predictions
prediction_table.to_csv("predictions.csv", index=False)
mlflow.log_artifact("predictions.csv", artifact_path="data")
fig, ax = plt.subplots()
ConfusionMatrixDisplay.from_predictions(y_test, predictions, ax=ax)
ax.set_title("Iris test confusion matrix")
mlflow.log_figure(fig, "plots/confusion_matrix.png")
plt.close(fig)
mlflow.log_text(
"This run uses a stratified 80/20 split and no feature scaling.",
"notes/run_notes.txt",
)
print(json.dumps(report, indent=2))log_figure() saves a Matplotlib or Plotly figure directly. It avoids requiring you to manage a plot file yourself. For a file created by another library, create the file first and pass its path to log_artifact().
MLflow records the artifact path, but it does not automatically make every artifact meaningful. Include useful filenames, stable folder names, and enough context in the file itself. A file named output.csv is less informative than data/test_predictions.csv.
Common errors
An artifact path is not the same as a local filesystem path. In log_artifact("predictions.csv", artifact_path="data"), the first argument points to a local file. The second argument names the folder inside MLflow.
Large artifacts can slow runs and increase storage costs. Log representative samples when a complete dataset is unnecessary. For sensitive data, check access controls and retention rules before logging it.
Artifacts also do not replace dataset versioning. A prediction file may show what a run produced, but it does not prove which external dataset version was used unless you record that version in a parameter, tag, or metadata file.
Exercise
You have a local file named metrics.json and a Matplotlib figure named fig. How would you store the file under evaluation and the figure under plots in the active MLflow run?
Show answer
Use mlflow.logartifact("metrics.json", artifactpath="evaluation") and mlflow.log_figure(fig, "plots/metrics.png").