訓練期間的日誌指標、參數和 MLflow 模型 - Amazon SageMaker AI

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

訓練期間的日誌指標、參數和 MLflow 模型

連線至 MLflow 追蹤伺服器後,您可以使用 MLflow SDK 記錄指標、參數和 MLflow 模型。

日誌訓練指標

在 MLflow 訓練執行mlflow.log_metric中使用 來追蹤指標。如需使用 MLflow 記錄指標的詳細資訊,請參閱 mlflow.log_metric

with mlflow.start_run(): mlflow.log_metric("foo", 1) print(mlflow.search_runs())

此指令碼應建立實驗執行,並列印出類似下列的輸出:

run_id experiment_id status artifact_uri ... tags.mlflow.source.name tags.mlflow.user tags.mlflow.source.type tags.mlflow.runName 0 607eb5c558c148dea176d8929bd44869 0 FINISHED s3://dddd/0/607eb5c558c148dea176d8929bd44869/a... ... file.py user-id LOCAL experiment-code-name

在 MLflow UI 中,此範例看起來應該類似以下內容:

最上層 MLflow 實驗選單中顯示的實驗。

選擇執行名稱以查看更多執行詳細資訊。

MLflow UI 中實驗執行頁面上顯示的實驗參數。

日誌參數和模型

注意

下列範例需要您的環境具有 s3:PutObject 許可。此許可應與 MLflow SDK 使用者登入或聯合到其 AWS 帳戶時所擔任的 IAM 角色相關聯。如需詳細資訊,請參閱使用者和角色政策範例

下列範例使用 SKLearn 引導您完成基本模型訓練工作流程,並示範如何在 MLflow 實驗執行中追蹤該模型。此範例會記錄參數、指標和模型成品。

import mlflow from mlflow.models import infer_signature import pandas as pd from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score # This is the ARN of the MLflow Tracking Server you created mlflow.set_tracking_uri(your-tracking-server-arn) mlflow.set_experiment("some-experiment") # Load the Iris dataset X, y = datasets.load_iris(return_X_y=True) # Split the data into training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Define the model hyperparameters params = {"solver": "lbfgs", "max_iter": 1000, "multi_class": "auto", "random_state": 8888} # Train the model lr = LogisticRegression(**params) lr.fit(X_train, y_train) # Predict on the test set y_pred = lr.predict(X_test) # Calculate accuracy as a target loss metric accuracy = accuracy_score(y_test, y_pred) # Start an MLflow run and log parameters, metrics, and model artifacts with mlflow.start_run(): # Log the hyperparameters mlflow.log_params(params) # Log the loss metric mlflow.log_metric("accuracy", accuracy) # Set a tag that we can use to remind ourselves what this run was for mlflow.set_tag("Training Info", "Basic LR model for iris data") # Infer the model signature signature = infer_signature(X_train, lr.predict(X_train)) # Log the model model_info = mlflow.sklearn.log_model( sk_model=lr, artifact_path="iris_model", signature=signature, input_example=X_train, registered_model_name="tracking-quickstart", )

在 MLflow UI 中,選擇左側導覽窗格中的實驗名稱,以探索所有相關執行。選擇執行名稱,以查看每個執行的詳細資訊。在此範例中,此執行的實驗執行頁面看起來應該類似以下內容。

在 MLflow UI 中執行之實驗的追蹤參數。

此範例會記錄羅吉斯迴歸模型。在 MLflow UI 中,您也應該會看到已記錄的模型成品。

在 MLflow UI 中執行實驗的追蹤模型成品。