← retour aux snippets

mlflow: log model et artefacts

Sauvegarder modèles, figures et fichiers dans un run.

python tracking #mlflow#artifacts#log-model

objectif

Sauvegarder modèles, figures et fichiers dans un run.

code minimal

import mlflow, mlflow.sklearn, matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestRegressor
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split

X, y = load_diabetes(return_X_y=True)
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, random_state=0)

mlflow.set_tracking_uri("file:./mlruns")
mlflow.set_experiment("artifacts-demo")
with mlflow.start_run():
    model = RandomForestRegressor(n_estimators=100, random_state=0).fit(Xtr, ytr)
    mlflow.sklearn.log_model(model, "model")
    plt.figure(); plt.plot([0,1],[0,1])
    plt.savefig("fig.png"); plt.close()
    mlflow.log_artifact("fig.png", artifact_path="plots")
print(True)

utilisation

# Télécharger un artifact (via client API)
client = mlflow.tracking.MlflowClient()
# client.download_artifacts(run_id, "plots/fig.png", dst_path=".")
print(True)

variante(s) utile(s)

# Log du conda.yaml/requirements.txt auto via autolog
print(True)

notes

  • Gardez une structure d’artefacts claire (plots/, data/, models/); versionnez indépendamment via DVC/Git LFS si volumineux.