

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

# 在訓練期間記錄指標、參數和 MLflow 模型
<a name="mlflow-track-experiments-log-metrics"></a>

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

## 記錄訓練指標
<a name="mlflow-track-experiments-log-metrics-example"></a>

在 MLflow 訓練執行中使用 `mlflow.log_metric` 來追蹤指標。如需使用 MLflow 記錄指標的詳細資訊，請參閱`[mlflow.log\_metric](https://mlflow.org/docs/2.13.2/python_api/mlflow.html#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 實驗選單中顯示的實驗。](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/mlflow/mlflow-ui-experiments.png)


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

![MLflow UI 中實驗執行頁面上顯示的實驗參數。](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/mlflow/mlflow-ui-foo.png)


## 日誌參數和模型
<a name="mlflow-track-experiments-log-params-models"></a>

**注意**  
下列範例需要您的環境具有 `s3:PutObject` 許可。此許可應與 MLflow SDK 使用者登入或聯合到其 AWS 帳戶時所擔任的 IAM 角色相關聯。如需詳細資訊，請參閱[使用者和角色政策範例](https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-policies-s3.html)。

下列範例使用 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}},
        name={{"iris_model"}}, # Changed from artifact_path to name for MLflow 3.0
        signature={{signature}},
        input_example={{X_train}},
        registered_model_name={{"tracking-quickstart"}},
    )
```

在 MLflow UI 中，選擇左側導覽窗格中的實驗名稱，以探索所有相關聯的執行。選擇**執行名稱**以查看每個執行的詳細資訊。在此範例中，此執行的實驗執行頁面應如下所示。

![在 MLflow UI 中執行之實驗的追蹤參數。](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/mlflow/mlflow-ui-parameters.png)


此範例會記錄邏輯迴歸模型。在 MLflow UI 中，您也應該會看到記錄的模型成品。

![MLflow UI 中實驗執行的已追蹤模型成品。](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/mlflow/mlflow-ui-model-artifacts.png)
