Chapitre 1 : Introduction à MLflow
Qu'est-ce que MLflow ?
MLflow est une plateforme open-source pour gérer le cycle de vie complet de l'apprentissage automatique. Elle fournit quatre composants principaux :
Configuration de MLflow
Installation
# Installation de base
pip install mlflow
# Avec extras
pip install mlflow[extras]
# Démarrer le serveur de suivi local
mlflow server --host 0.0.0.0 --port 5000
Configuration de production
# docker-compose.yml
version: '3.8'
services:
mlflow:
image: ghcr.io/mlflow/mlflow:v2.10.0
ports:
- "5000:5000"
environment:
- MLFLOW_BACKEND_STORE_URI=postgresql://user:pass@postgres:5432/mlflow
- MLFLOW_DEFAULT_ARTIFACT_ROOT=s3://mlflow-artifacts/
- AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID}
- AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY}
command: >
mlflow server
--backend-store-uri postgresql://user:pass@postgres:5432/mlflow
--default-artifact-root s3://mlflow-artifacts/
--host 0.0.0.0
--port 5000
depends_on:
- postgres
postgres:
image: postgres:15
environment:
- POSTGRES_USER=user
- POSTGRES_PASSWORD=pass
- POSTGRES_DB=mlflow
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
Suivi MLflow
Suivi d'expérience de base
import mlflow
import mlflow.sklearn
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, f1_score, roc_auc_score
# Définir l'URI de suivi
mlflow.set_tracking_uri("http://localhost:5000")
# Définir l'expérience
mlflow.set_experiment("customer-churn-prediction")
# Démarrer une exécution
with mlflow.start_run(run_name="random-forest-baseline"):
# Journaliser les paramètres
n_estimators = 100
max_depth = 10
mlflow.log_param("n_estimators", n_estimators)
mlflow.log_param("max_depth", max_depth)
mlflow.log_param("model_type", "RandomForest")
# Entraîner le modèle
model = RandomForestClassifier(
n_estimators=n_estimators,
max_depth=max_depth,
random_state=42
)
model.fit(X_train, y_train)
# Faire des prédictions
predictions = model.predict(X_test)
probabilities = model.predict_proba(X_test)[:, 1]
# Journaliser les métriques
mlflow.log_metric("accuracy", accuracy_score(y_test, predictions))
mlflow.log_metric("f1_score", f1_score(y_test, predictions))
mlflow.log_metric("auc_roc", roc_auc_score(y_test, probabilities))
# Journaliser le modèle
mlflow.sklearn.log_model(model, "model")
# Journaliser les artefacts (fichiers)
mlflow.log_artifact("feature_importance.csv")
Journalisation automatique
# Activer la journalisation automatique pour sklearn
mlflow.sklearn.autolog()
# Maintenant, l'entraînement journalise automatiquement tout
model = RandomForestClassifier(n_estimators=100)
model.fit(X_train, y_train)
# Les paramètres, métriques et modèles sont journalisés automatiquement !
# Journalisation automatique pour d'autres frameworks
mlflow.pytorch.autolog()
mlflow.tensorflow.autolog()
mlflow.xgboost.autolog()
mlflow.lightgbm.autolog()
Exécutions imbriquées pour l'optimisation des hyperparamètres
from sklearn.model_selection import ParameterGrid
param_grid = {
'n_estimators': [100, 200, 300],
'max_depth': [5, 10, 15, None],
'min_samples_split': [2, 5, 10]
}
with mlflow.start_run(run_name="hyperparameter-search"):
best_auc = 0
best_params = None
for params in ParameterGrid(param_grid):
with mlflow.start_run(nested=True):
# Journaliser les paramètres
mlflow.log_params(params)
# Entraîner le modèle
model = RandomForestClassifier(**params, random_state=42)
model.fit(X_train, y_train)
# Évaluer
auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])
mlflow.log_metric("auc_roc", auc)
# Suivre le meilleur
if auc > best_auc:
best_auc = auc
best_params = params
# Journaliser les meilleurs résultats dans l'exécution parente
mlflow.log_params({f"best_{k}": v for k, v in best_params.items()})
mlflow.log_metric("best_auc_roc", best_auc)
Projets MLflow
Structure du projet
ml-project/
├── MLproject # Définition du projet
├── conda.yaml # Spécification de l'environnement
├── train.py # Script d'entraînement
└── requirements.txt # Alternative à conda
Fichier MLproject
# MLproject
name: customer-churn-model
conda_env: conda.yaml
entry_points:
main:
parameters:
n_estimators: {type: int, default: 100}
max_depth: {type: int, default: 10}
data_path: {type: string, default: "data/processed/"}
command: "python train.py --n-estimators {n_estimators} --max-depth {max_depth} --data-path {data_path}"
evaluate:
parameters:
model_path: string
test_data: string
command: "python evaluate.py --model-path {model_path} --test-data {test_data}"
Exécution des projets
# Exécuter localement
mlflow run . -P n_estimators=200 -P max_depth=15
# Exécuter depuis Git
mlflow run https://github.com/company/ml-project -P n_estimators=200
# Exécuter avec un environnement spécifique
mlflow run . --env-manager conda
Modèles MLflow
Signature du modèle et exemple d'entrée
from mlflow.models.signature import infer_signature
import pandas as pd
# Inférer la signature à partir des données
signature = infer_signature(X_train, model.predict(X_train))
# Créer un exemple d'entrée
input_example = X_train.head(5)
# Journaliser le modèle avec signature
mlflow.sklearn.log_model(
model,
"model",
signature=signature,
input_example=input_example,
registered_model_name="customer-churn-model"
)
Saveurs de modèle
# Différentes manières de journaliser les modèles
# Sklearn
mlflow.sklearn.log_model(sklearn_model, "model")
# PyTorch
mlflow.pytorch.log_model(pytorch_model, "model")
# TensorFlow/Keras
mlflow.tensorflow.log_model(tf_model, "model")
# Modèles personnalisés avec pyfunc
class CustomModel(mlflow.pyfunc.PythonModel):
def load_context(self, context):
# Charger les artefacts
self.model = load_model(context.artifacts["model_path"])
def predict(self, context, model_input):
return self.model.predict(model_input)
mlflow.pyfunc.log_model(
"model",
python_model=CustomModel(),
artifacts={"model_path": "path/to/model"}
)
Points clés à retenir
Résumé
- Suivi MLflow journalise les paramètres, métriques et artefacts
- Journalisation automatique simplifie le suivi pour les frameworks pris en charge
- Projets MLflow assurent un code ML reproductible
- Modèles MLflow fournissent un emballage standard pour le déploiement
- Signatures de modèle définissent les entrées et sorties attendues
Suivant : Chapitre 2 : Weights and Biases