SDK v1에서 SDK v2로 로깅 마이그레이션

Azure Machine Learning은 Azure Machine Learning Python SDK, Azure Machine Learning CLI 또는 Azure Machine Learning 스튜디오를 통해 실험을 만들었는지 여부에 관계없이 실험에 대한 메트릭 로깅 및 아티팩트 스토리지에 MLflow 추적을 사용합니다. 실험 추적에 MLflow를 사용하는 것이 좋습니다.

SDK v1에서 SDK v2로 마이그레이션하는 경우 이 섹션의 정보를 사용하여 SDK v1 로깅 API에 해당하는 MLflow를 이해합니다.

MLflow를 왜 사용합니까?

매월 1,300만 개 이상의 다운로드가 있는 MLflow는 모든 크기의 팀이 일괄 처리 또는 실시간 유추를 위해 모든 모델을 추적, 공유, 패키지 및 배포할 수 있도록 하는 엔드투엔드 MLOps의 표준 플랫폼이 되었습니다. Azure Machine Learning은 MLflow와 통합되어 학습 코드에 Azure Machine Learning 관련 지침이 포함되어 있지 않으므로 진정한 이식성과 다른 플랫폼과의 원활한 통합을 달성할 수 있습니다.

MLflow로 마이그레이션 준비

MLflow 추적을 사용하려면 Mlflow SDK 패키지 mlflow 및 MLflow azureml-mlflow용 Azure Machine Learning 플러그 인을 설치해야 합니다. 모든 Azure Machine Learning 환경에서는 이러한 패키지를 이미 사용할 수 있지만 사용자 고유의 환경을 만드는 경우 이러한 패키지를 포함해야 합니다.

pip install mlflow azureml-mlflow

작업 영역에 연결

Azure Machine Learning을 사용하면 사용자가 작업 영역에서 실행되거나 원격으로 실행되는 학습 작업(Azure Machine Learning 외부에서 실행되는 실험 추적)에서 추적을 수행할 수 있습니다. 원격 추적을 수행하는 경우 MLflow를 연결하려는 작업 영역을 나타내야 합니다.

Azure Machine Learning 컴퓨팅에서 실행할 때 작업 영역에 이미 연결되어 있습니다.

실험 및 실행

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()

MLflow가 포함된 SDK v2

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

로깅 API 비교

정수 또는 부동 소수점 메트릭 기록

SDK v1

azureml_run.log("sample_int_metric", 1)

MLflow가 포함된 SDK v2

mlflow.log_metric("sample_int_metric", 1)

부울 메트릭 기록

SDK v1

azureml_run.log("sample_boolean_metric", True)

MLflow가 포함된 SDK v2

mlflow.log_metric("sample_boolean_metric", 1)

문자열 메트릭 기록

SDK v1

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

MLflow가 포함된 SDK v2

mlflow.log_text("sample_string_text", "string.txt")
  • 문자열은 메트릭이 아닌 아티팩트로 기록됩니다. Azure Machine Learning 스튜디오에서는 값이 출력 + 로그 탭에 표시됩니다.

PNG 또는 JPEG 파일에 이미지 기록

SDK v1

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

MLflow가 포함된 SDK v2

mlflow.log_artifact("Azure.png")

이미지는 아티팩트로 기록되며 Azure Machine Learning 스튜디오의 이미지 탭에 표시됩니다.

matplotlib.pyplot 기록

SDK v1

import matplotlib.pyplot as plt

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

MLflow가 포함된 SDK v2

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")
  • 이미지는 아티팩트로 기록되며 Azure Machine Learning 스튜디오의 이미지 탭에 표시됩니다.

메트릭 목록 기록

SDK v1

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

MLflow가 포함된 SDK v2

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)
  • 메트릭은 Azure Machine Learning 스튜디오의 메트릭 탭에 표시됩니다.
  • 텍스트 값은 지원되지 않습니다.

메트릭 행 기록

SDK v1

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

MLflow가 포함된 SDK v2

metrics = {"sample_table.col1": 5, "sample_table.col2": 10}
mlflow.log_metrics(metrics)
  • 메트릭은 Azure Machine Learning 스튜디오에서 테이블로 렌더링되지 않습니다.
  • 텍스트 값은 지원되지 않습니다.
  • 메트릭이 아닌 아티팩트로 기록됩니다.

테이블 기록

SDK v1

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

MLflow가 포함된 SDK v2

# 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")
  • 각 열에 대한 메트릭을 기록합니다.
  • 메트릭은 Azure Machine Learning 스튜디오에서 테이블로 렌더링되지 않습니다.
  • 텍스트 값은 지원되지 않습니다.
  • 메트릭이 아닌 아티팩트로 기록됩니다.

정확도 테이블 기록

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)

MLflow가 포함된 SDK v2

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')
  • 메트릭은 Azure Machine Learning 스튜디오에서 정확도 테이블로 렌더링되지 않습니다.
  • 메트릭이 아닌 아티팩트로 기록됩니다.
  • mlflow.log_dict 메서드는 실험적입니다.

혼동 행렬 기록

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))

MLflow가 포함된 SDK v2

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')
  • 메트릭은 Azure Machine Learning 스튜디오에서 혼동 행렬로 렌더링되지 않습니다.
  • 메트릭이 아닌 아티팩트로 기록됩니다.
  • mlflow.log_dict 메서드는 실험적입니다.

로그 예측

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))

MLflow가 포함된 SDK v2

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')
  • 메트릭은 Azure Machine Learning 스튜디오에서 혼동 행렬로 렌더링되지 않습니다.
  • 메트릭이 아닌 아티팩트로 기록됩니다.
  • mlflow.log_dict 메서드는 실험적입니다.

로그 잔류

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))

MLflow가 포함된 SDK v2

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')
  • 메트릭은 Azure Machine Learning 스튜디오에서 혼동 행렬로 렌더링되지 않습니다.
  • 메트릭이 아닌 아티팩트로 기록됩니다.
  • mlflow.log_dict 메서드는 실험적입니다.

실행 정보 및 데이터 보기

MLflow run(mlflow.entities.Run) 개체의 datainfo 속성을 사용하여 실행 정보에 액세스할 수 있습니다.

Azure Machine Learning의 실험 및 실행 추적 정보는 실험 및 실행을 쉽게 쿼리 및 검색하고 결과를 빠르게 비교할 수 있는 포괄적인 검색 API를 제공하는 MLflow를 사용하여 쿼리할 수 있습니다. 이 차원의 MLflow의 모든 기능에 대한 자세한 내용은 MLflow를 사용하여 실험 및 실행 비교 쿼리를 참조 하세요.

다음 예제에서는 완료된 실행을 검색하는 방법을 보여줍니다.

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>")

다음 예제에서는 metrics, tagsparams를 보는 방법을 보여 줍니다.

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

참고 항목

metrics에는 지정된 메트릭에 대해 가장 최근에 로그된 값만 있습니다. 예를 들어 1 값을 순서대로 로깅한 다음, 23, 마지막으로 4sample_metric이라는 메트릭에 로그인하는 경우 metrics 사전에는 4만 표시됩니다. 명명된 특정 메트릭에 대해 기록된 모든 메트릭을 가져오려면 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"))

자세한 내용은 MlFlowClient 참조를 참조하세요.

info 필드는 시작 시간, 실행 ID, 실험 ID 등과 같은 실행에 대한 일반 정보를 제공합니다.

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

실행 아티팩트 보기

실행의 아티팩트를 보려면 MlFlowClient.list_artifacts를 사용합니다.

client.list_artifacts(finished_mlflow_run.info.run_id)

아티팩트를 다운로드하려면 mlflow.artifacts.download_artifacts를 사용합니다.

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

다음 단계