

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 训练期间的日志指标、参数和 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 用户界面中，该示例应类似于下面的内容：

![顶层 MLflow 实验菜单中显示的实验。](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/mlflow/mlflow-ui-experiments.png)


选择**运行名称**，查看更多运行详情。

![MLflow 用户界面中实验运行页面上显示的实验参数。](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/mlflow/mlflow-ui-foo.png)


## 对数参数和模型
<a name="mlflow-track-experiments-log-params-models"></a>

**注意**  
以下示例要求环境具有 `s3:PutObject` 权限。此权限应与 mlFlow SDK 用户登录账户或联合账户时所扮演的 IAM 角色相关联。 AWS 更多信息，请参阅[用户和角色策略示例](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 用户界面中，选择左侧导航窗格中的实验名称，即可查看所有相关运行。选择**运行名称**，查看每个运行的更多信息。在此示例中，该运行的实验运行页面应类似于以下内容。

![在 MLflow 用户界面中运行的实验的跟踪参数。](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/mlflow/mlflow-ui-parameters.png)


本例记录逻辑回归模型。在 MLflow 用户界面中，您还应该看到记录的模型构件。

![跟踪在 MLflow 用户界面中运行的实验的模型构件。](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/mlflow/mlflow-ui-model-artifacts.png)
