Share via


Migrer la journalisation du SDK v1 vers SDK v2

Azure Machine Learning utilise MLflow Tracking pour la journalisation des métriques et le stockage d’artefacts pour vos expériences, que vous ayez créé l’expérience via le SDK Python Azure Machine Learning, l’interface CLI Azure Machine Learning ou Azure Machine Learning studio. Nous vous recommandons d’utiliser MLflow pour les expériences de suivi.

Si vous migrez du SDK v1 vers le SDK v2, utilisez les informations de cette section pour comprendre les équivalents MLflow des API de journalisation du SDK v1.

Pourquoi MLflow ?

Avec plus de 13 millions de téléchargements mensuels, MLflow est devenu la plateforme standard pour les MLOps de bout en bout : il permet aux équipes de toute taille de suivre, partager, empaqueter et déployer n’importe quel modèle pour l’inférence par lots ou en temps réel. Azure Machine Learning s’intègre à MLflow. Cela vous permet d’obtenir un code d’entraînement disposant d’une véritable portabilité et s’intégrant de façon transparente à d’autres plateformes, car il ne contient pas d’instructions spécifiques à Azure Machine Learning.

Préparer la migration vers MLflow

Pour utiliser le suivi MLflow, vous devez installer le package SDK MLflowmlflow et le plug-in Azure Machine Learning pour MLflow azureml-mlflow. Tous les environnements Azure Machine Learning mettent déjà ces packages à votre disposition, mais vous devez les inclure si vous créez votre propre environnement.

pip install mlflow azureml-mlflow

Se connecter à un espace de travail

Azure Machine Learning permet aux utilisateurs de suivre les travaux d’entraînement exécutés sur votre espace de travail ou exécutés à distance (suivi d’expériences exécutées en dehors d’Azure Machine Learning). Si vous effectuez un suivi à distance, vous devez indiquer l’espace de travail auquel vous souhaitez connecter MLflow.

Vous êtes déjà connecté à votre espace de travail quand l’exécution s’effectue dans la capacité de calcul Azure Machine Learning.

Expériences et exécutions

SDK v1

from azureml.core import Experiment

# create an Azure Machine Learning experiment and start a run
experiment = Experiment(ws, "create-experiment-sdk-v1")
azureml_run = experiment.start_logging()

SDK v2 avec MLflow

# Set the MLflow experiment and start a run
mlflow.set_experiment("logging-with-mlflow")
mlflow_run = mlflow.start_run()

Comparaison des API de journalisation

Journaliser une métrique de type entier ou float

SDK v1

azureml_run.log("sample_int_metric", 1)

SDK v2 avec MLflow

mlflow.log_metric("sample_int_metric", 1)

Journaliser une métrique booléenne

SDK v1

azureml_run.log("sample_boolean_metric", True)

SDK v2 avec MLflow

mlflow.log_metric("sample_boolean_metric", 1)

Journaliser une métrique de chaîne

SDK v1

azureml_run.log("sample_string_metric", "a_metric")

SDK v2 avec MLflow

mlflow.log_text("sample_string_text", "string.txt")
  • La chaîne est journalisée en tant qu’artefact, et non en tant que métrique. Dans Azure Machine Learning Studio, la valeur s’affiche sous l’onglet Sorties + journaux.

Journaliser une image dans un fichier PNG ou JPEG

SDK v1

azureml_run.log_image("sample_image", path="Azure.png")

SDK v2 avec MLflow

mlflow.log_artifact("Azure.png")

L’image est journalisée en tant qu’artefact et s’affiche sous l’onglet Images dans Azure Machine Learning Studio.

Journaliser un matplotlib.pyplot

SDK v1

import matplotlib.pyplot as plt

plt.plot([1, 2, 3])
azureml_run.log_image("sample_pyplot", plot=plt)

SDK v2 avec MLflow

import matplotlib.pyplot as plt

plt.plot([1, 2, 3])
fig, ax = plt.subplots()
ax.plot([0, 1], [2, 3])
mlflow.log_figure(fig, "sample_pyplot.png")
  • L’image est journalisée en tant qu’artefact et s’affiche sous l’onglet Images dans Azure Machine Learning Studio.

Journaliser une liste des métriques

SDK v1

list_to_log = [1, 2, 3, 2, 1, 2, 3, 2, 1]
azureml_run.log_list('sample_list', list_to_log)

SDK v2 avec MLflow

list_to_log = [1, 2, 3, 2, 1, 2, 3, 2, 1]
from mlflow.entities import Metric
from mlflow.tracking import MlflowClient
import time

metrics = [Metric(key="sample_list", value=val, timestamp=int(time.time() * 1000), step=0) for val in list_to_log]
MlflowClient().log_batch(mlflow_run.info.run_id, metrics=metrics)
  • Les métriques apparaissent sous l’onglet Métriques dans Azure Machine Learning studio.
  • Les valeurs de texte ne sont pas prises en charge.

Journaliser une ligne de métriques

SDK v1

azureml_run.log_row("sample_table", col1=5, col2=10)

SDK v2 avec MLflow

metrics = {"sample_table.col1": 5, "sample_table.col2": 10}
mlflow.log_metrics(metrics)
  • Les métriques ne s’affichent pas en tant que table dans Azure Machine Learning studio.
  • Les valeurs de texte ne sont pas prises en charge.
  • Journalisé en tant qu’artefact, et non en tant que métrique.

Journaliser une table

SDK v1

table = {
"col1" : [1, 2, 3],
"col2" : [4, 5, 6]
}
azureml_run.log_table("table", table)

SDK v2 avec MLflow

# Add a metric for each column prefixed by metric name. Similar to log_row
row1 = {"table.col1": 5, "table.col2": 10}
# To be done for each row in the table
mlflow.log_metrics(row1)

# Using mlflow.log_artifact
import json

with open("table.json", 'w') as f:
json.dump(table, f)
mlflow.log_artifact("table.json")
  • Journalise des métriques pour chaque colonne.
  • Les métriques ne s’affichent pas en tant que table dans Azure Machine Learning studio.
  • Les valeurs de texte ne sont pas prises en charge.
  • Journalisé en tant qu’artefact, et non en tant que métrique.

Journaliser un table de précision

SDK v1

ACCURACY_TABLE = '{"schema_type": "accuracy_table", "schema_version": "v1", "data": {"probability_tables": ' +\
        '[[[114311, 385689, 0, 0], [0, 0, 385689, 114311]], [[67998, 432002, 0, 0], [0, 0, ' + \
        '432002, 67998]]], "percentile_tables": [[[114311, 385689, 0, 0], [1, 0, 385689, ' + \
        '114310]], [[67998, 432002, 0, 0], [1, 0, 432002, 67997]]], "class_labels": ["0", "1"], ' + \
        '"probability_thresholds": [0.52], "percentile_thresholds": [0.09]}}'

azureml_run.log_accuracy_table('v1_accuracy_table', ACCURACY_TABLE)

SDK v2 avec MLflow

ACCURACY_TABLE = '{"schema_type": "accuracy_table", "schema_version": "v1", "data": {"probability_tables": ' +\
        '[[[114311, 385689, 0, 0], [0, 0, 385689, 114311]], [[67998, 432002, 0, 0], [0, 0, ' + \
        '432002, 67998]]], "percentile_tables": [[[114311, 385689, 0, 0], [1, 0, 385689, ' + \
        '114310]], [[67998, 432002, 0, 0], [1, 0, 432002, 67997]]], "class_labels": ["0", "1"], ' + \
        '"probability_thresholds": [0.52], "percentile_thresholds": [0.09]}}'

mlflow.log_dict(ACCURACY_TABLE, 'mlflow_accuracy_table.json')
  • Les métriques ne s’affichent pas en tant que table de précision dans Azure Machine Learning studio.
  • Journalisé en tant qu’artefact, et non en tant que métrique.
  • La méthode mlflow.log_dict est expérimentale.

Journaliser une matrice de confusion

SDK v1

CONF_MATRIX = '{"schema_type": "confusion_matrix", "schema_version": "v1", "data": {"class_labels": ' + \
    '["0", "1", "2", "3"], "matrix": [[3, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]]}}'

azureml_run.log_confusion_matrix('v1_confusion_matrix', json.loads(CONF_MATRIX))

SDK v2 avec MLflow

CONF_MATRIX = '{"schema_type": "confusion_matrix", "schema_version": "v1", "data": {"class_labels": ' + \
    '["0", "1", "2", "3"], "matrix": [[3, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]]}}'

mlflow.log_dict(CONF_MATRIX, 'mlflow_confusion_matrix.json')
  • Les métriques ne s’affichent pas en tant que matrice de fusion dans Azure Machine Learning studio.
  • Journalisé en tant qu’artefact, et non en tant que métrique.
  • La méthode mlflow.log_dict est expérimentale.

Journaliser des prédictions

SDK v1

PREDICTIONS = '{"schema_type": "predictions", "schema_version": "v1", "data": {"bin_averages": [0.25,' + \
    ' 0.75], "bin_errors": [0.013, 0.042], "bin_counts": [56, 34], "bin_edges": [0.0, 0.5, 1.0]}}'

azureml_run.log_predictions('test_predictions', json.loads(PREDICTIONS))

SDK v2 avec MLflow

PREDICTIONS = '{"schema_type": "predictions", "schema_version": "v1", "data": {"bin_averages": [0.25,' + \
    ' 0.75], "bin_errors": [0.013, 0.042], "bin_counts": [56, 34], "bin_edges": [0.0, 0.5, 1.0]}}'

mlflow.log_dict(PREDICTIONS, 'mlflow_predictions.json')
  • Les métriques ne s’affichent pas en tant que matrice de fusion dans Azure Machine Learning studio.
  • Journalisé en tant qu’artefact, et non en tant que métrique.
  • La méthode mlflow.log_dict est expérimentale.

Journaliser des résidus

SDK v1

RESIDUALS = '{"schema_type": "residuals", "schema_version": "v1", "data": {"bin_edges": [100, 200, 300], ' + \
'"bin_counts": [0.88, 20, 30, 50.99]}}'

azureml_run.log_residuals('test_residuals', json.loads(RESIDUALS))

SDK v2 avec MLflow

RESIDUALS = '{"schema_type": "residuals", "schema_version": "v1", "data": {"bin_edges": [100, 200, 300], ' + \
'"bin_counts": [0.88, 20, 30, 50.99]}}'

mlflow.log_dict(RESIDUALS, 'mlflow_residuals.json')
  • Les métriques ne s’affichent pas en tant que matrice de fusion dans Azure Machine Learning studio.
  • Journalisé en tant qu’artefact, et non en tant que métrique.
  • La méthode mlflow.log_dict est expérimentale.

Afficher les informations d’exécution et les données

Vous pouvez accéder aux informations d’exécution à l’aide des propriétés data et info de l’objet d’exécution MLflow (mlflow.entities.Run).

Conseil

Vous pouvez interroger les informations de suivi des expériences et des exécutions dans Azure Machine Learning à l’aide de MLflow, qui fournit une API de recherche complète pour interroger et rechercher facilement des expériences et des exécutions, et comparer rapidement les résultats. Pour plus d’informations sur toutes les fonctionnalités de MLflow dans cette dimension, consultez Requête & comparer les expériences et les exécutions avec MLflow

L’exemple suivant montre comment récupérer une exécution terminée :

from mlflow.tracking import MlflowClient

# Use MlFlow to retrieve the run that was just completed
client = MlflowClient()
finished_mlflow_run = MlflowClient().get_run("<RUN_ID>")

L’exemple suivant montre comment afficher metrics, tags et params :

metrics = finished_mlflow_run.data.metrics
tags = finished_mlflow_run.data.tags
params = finished_mlflow_run.data.params

Notes

metrics aura seulement la valeur journalisée la plus récente pour une métrique donnée. Par exemple, si vous journalisez dans l’ordre une valeur de 1, puis 2, 3 et enfin 4 en une métrique nommée sample_metric, seule 4 sera présente dans le dictionnaire metrics. Pour obtenir toutes les métriques enregistrées pour une métrique nommée spécifique, utilisez MlFlowClient.get_metric_history :

with mlflow.start_run() as multiple_metrics_run:
    mlflow.log_metric("sample_metric", 1)
    mlflow.log_metric("sample_metric", 2)
    mlflow.log_metric("sample_metric", 3)
    mlflow.log_metric("sample_metric", 4)

print(client.get_run(multiple_metrics_run.info.run_id).data.metrics)
print(client.get_metric_history(multiple_metrics_run.info.run_id, "sample_metric"))

Pour plus d’informations, consultez les informations de référence sur MlFlowClient.

Le champ info fournit des informations générales sur l’exécution, telles que l’heure de début, l’ID d’exécution, l’ID d’expérience, etc. :

run_start_time = finished_mlflow_run.info.start_time
run_experiment_id = finished_mlflow_run.info.experiment_id
run_id = finished_mlflow_run.info.run_id

Afficher les artefacts des exécutions

Pour afficher les artefacts d’une exécution, utilisez MlFlowClient.list_artifacts.

client.list_artifacts(finished_mlflow_run.info.run_id)

Pour télécharger un artefact, utilisez mlflow.artifacts.download_artifacts :

mlflow.artifacts.download_artifacts(run_id=finished_mlflow_run.info.run_id, artifact_path="Azure.png")

Étapes suivantes