

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

# 训练模型
<a name="ex1-train-model"></a>

在此步骤中，您需要选择一种训练算法，并为模型运行训练作业。[Amaz SageMaker on Python SDK](https://sagemaker.readthedocs.io/en/stable) 提供框架估算器和通用估算器来训练您的模型，同时协调机器学习 (ML) 生命周期，访问用于训练 SageMaker 的人工智能功能和基础设施，例如亚马逊弹性容器注册表 (Amazon ECR) AWS 、亚马逊弹性计算云 (Amazon EC2)、亚马逊简单存储服务 (Amazon S3)、亚马逊简单存储服务 (Amazon S3) 3A。有关 SageMaker AI 内置框架估算器的更多信息，请参阅 Amaz [on Pyth SageMaker on SDK](https://sagemaker.readthedocs.io/en/stable) 文档中的[框架](https://sagemaker.readthedocs.io/en/stable/frameworks/index.html)。有关内置算法的更多信息，请参阅 [Amazon 中的内置算法和预训练模型 SageMaker](algos.md)。

**Topics**
+ [选择训练算法](#ex1-train-model-select-algorithm)
+ [创建并运行训练作业](#ex1-train-model-sdk)

## 选择训练算法
<a name="ex1-train-model-select-algorithm"></a>

要为数据集选择正确的算法，通常需要评估不同的模型，以找到最适合数据的模型。为简单起见，本教程中使用了 SageMaker AI [XGBoost 使用 Amazon A SageMaker I 的算法](xgboost.md) 内置算法，无需对模型进行预评估。

**提示**  
如果您想让 SageMaker AI 为您的表格数据集找到合适的模型，请使用自动执行机器学习解决方案的 Amazon A SageMaker utopilot。有关更多信息，请参阅 [SageMaker 自动驾驶](autopilot-automate-model-development.md)。

## 创建并运行训练作业
<a name="ex1-train-model-sdk"></a>

弄清楚要使用哪个模型后，开始构造用于训练的 A SageMaker I 估计器。本教程使用了 SageMaker AI 通用估计器的 XGBoost 内置算法。

**运行模型训练作业**

1. 导入 [Amaz SageMaker on Python 软件开发工具包](https://sagemaker.readthedocs.io/en/stable)，然后从当前 SageMaker 的人工智能会话中检索基本信息。

   ```
   import sagemaker
   
   region = sagemaker.Session().boto_region_name
   print("AWS Region: {}".format(region))
   
   role = sagemaker.get_execution_role()
   print("RoleArn: {}".format(role))
   ```

   此过程返回以下信息：
   + `region`— 运行 SageMaker AI 笔记本实例的当前 AWS 区域。
   + `role` – 笔记本实例使用的 IAM 角色。
**注意**  
通过运行来检查 SageMaker Python 开发工具包的版本`sagemaker.__version__`。本教程基于 `sagemaker>=2.20`。如果 SDK 已过时，请运行以下命令安装最新版本：  

   ```
   ! pip install -qU sagemaker
   ```
如果您在现有的 SageMaker Studio 或笔记本实例中运行此安装，则需要手动刷新内核才能完成版本更新的应用。

1. 使用类创建 XGBoost 估算器。`sagemaker.estimator.Estimator`在下面的示例代码中， XGBoost 估计器被命名为。`xgb_model`

   ```
   from sagemaker.debugger import Rule, ProfilerRule, rule_configs
   from sagemaker.session import TrainingInput
   
   s3_output_location='s3://{}/{}/{}'.format(bucket, prefix, 'xgboost_model')
   
   container=sagemaker.image_uris.retrieve("xgboost", region, "1.2-1")
   print(container)
   
   xgb_model=sagemaker.estimator.Estimator(
       image_uri=container,
       role=role,
       instance_count=1,
       instance_type='ml.m4.xlarge',
       volume_size=5,
       output_path=s3_output_location,
       sagemaker_session=sagemaker.Session(),
       rules=[
           Rule.sagemaker(rule_configs.create_xgboost_report()),
           ProfilerRule.sagemaker(rule_configs.ProfilerReport())
       ]
   )
   ```

   要构造 A SageMaker I 估计器，请指定以下参数：
   + `image_uri` – 指定训练容器映像 URI。在此示例中，使用指定 SageMaker AI XGBoost 训练容器 URI `sagemaker.image_uris.retrieve`。
   + `role`— A SageMaker I 用来代表您执行任务的 AWS Identity and Access Management (IAM) 角色（例如，读取训练结果、从 Amazon S3 调用模型工件以及将训练结果写入 Amazon S3）。
   + `instance_count` 和 `instance_type` – 用于模型训练的 Amazon EC2 ML 计算实例的类型和数量。在此训练练习中，您使用的是单个 `ml.m4.xlarge` 实例，该实例有 4 个 CPU、16 GB 内存、Amazon Elastic Block Store (Amazon EBS) 存储和高网络性能。有关 EC2 计算实例类型的更多信息，请参阅 [Amazon EC2 实例类型](https://aws.amazon.com/ec2/instance-types/)。有关账单的更多信息，请参阅 [Amazon SageMaker 定价](https://aws.amazon.com/sagemaker/pricing/)。
   + `volume_size` – 要附加到训练实例的 EBS 存储卷的大小 (GB)。如果使用 `File` 模式（默认情况下 `File` 模式处于打开状态），该值必须足够大，以存储训练数据。如果不指定该参数，默认值为 30。
   + `output_path`— 指向 SageMaker AI 存储模型工件和训练结果的 S3 存储桶的路径。
   + `sagemaker_session`— 管理与训练作业使用 SageMaker 的 API 操作和其他 AWS 服务的交互的会话对象。
   + `rules`— 指定 SageMaker 调试器内置规则列表。在此示例中，`create_xgboost_report()`规则创建了一 XGBoost 份报告，该报告提供了对训练进度和结果的见解，该`ProfilerReport()`规则创建了有关 EC2 计算资源利用率的报告。有关更多信息，请参阅 [SageMaker 的调试器交互式报告 XGBoost](debugger-report-xgboost.md)。
**提示**  
如果要对大型深度学习模型（例如卷积神经网络 (CNN) 和自然语言处理 (NLP) 模型）进行分布式训练，请使用 SageMaker AI Distributed 进行数据并行性或模型并行性。有关更多信息，请参阅 [在 Amazon A SageMaker I 中进行分布式训练](distributed-training.md)。

1. 通过调用估计器的`set_hyperparameters`方法来设置 XGBoost 算法的超参数。有关 XGBoost 超参数的完整列表，请参见[XGBoost 超参数](xgboost_hyperparameters.md)。

   ```
   xgb_model.set_hyperparameters(
       max_depth = 5,
       eta = 0.2,
       gamma = 4,
       min_child_weight = 6,
       subsample = 0.7,
       objective = "binary:logistic",
       num_round = 1000
   )
   ```
**提示**  
您也可以使用 SageMaker AI 超参数优化功能调整超参数。有关更多信息，请参阅 [使用 SageMaker AI 自动调整模型](automatic-model-tuning.md)。

1. 使用 `TrainingInput` 类来配置用于训练的数据输入流。以下示例代码演示如何配置 `TrainingInput` 对象以使用您在[将数据集拆分为训练、验证和测试数据集](ex1-preprocess-data.md#ex1-preprocess-data-transform)部分上传到 Amazon S3 的训练数据集和验证数据集。

   ```
   from sagemaker.session import TrainingInput
   
   train_input = TrainingInput(
       "s3://{}/{}/{}".format(bucket, prefix, "data/train.csv"), content_type="csv"
   )
   validation_input = TrainingInput(
       "s3://{}/{}/{}".format(bucket, prefix, "data/validation.csv"), content_type="csv"
   )
   ```

1. 要开始模型训练，请使用训练数据集和验证数据集调用估算器的 `fit` 方法。通过设置 `wait=True`，`fit` 方法会显示进度日志，并等待训练完成。

   ```
   xgb_model.fit({"train": train_input, "validation": validation_input}, wait=True)
   ```

   有关模型训练的更多信息，请参阅 [使用 Amazon 训练模型 SageMaker](how-it-works-training.md)。本教程的训练作业最多可能需要 10 分钟时间。

   训练作业完成后，您可以下载由 D SageMaker ebugger 生成的 XGBoost 训练报告和分析报告。 XGBoost 训练报告为您提供训练进度和结果的见解，例如与迭代相关的损失函数、特征重要性、混淆矩阵、精度曲线和其他训练统计结果。例如，您可以从 XGBoost 训练报告中找到以下损失曲线，该曲线清楚地表明存在过度拟合问题。  
![\[XGBoost 训练报告中的图表。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/get-started-ni/gs-ni-train-loss-curve-validation-overfitting.png)

   运行以下代码以指定生成 Debugger 训练报告的 S3 存储桶 URI，并检查这些报告是否存在。

   ```
   rule_output_path = xgb_model.output_path + "/" + xgb_model.latest_training_job.job_name + "/rule-output"
   ! aws s3 ls {rule_output_path} --recursive
   ```

   将 Debugger XGBoost 训练和分析报告下载到当前工作区：

   ```
   ! aws s3 cp {rule_output_path} ./ --recursive
   ```

   运行以下 IPython 脚本以获取 XGBoost 训练报告的文件链接：

   ```
   from IPython.display import FileLink, FileLinks
   display("Click link below to view the XGBoost Training report", FileLink("CreateXgboostReport/xgboost_report.html"))
   ```

   以下 IPython 脚本返回 Debugger 分析报告的文件链接，该报告显示 EC2 实例资源利用率、系统瓶颈检测结果和 python 操作分析结果的摘要和详细信息：

   ```
   profiler_report_name = [rule["RuleConfigurationName"] 
                           for rule in xgb_model.latest_training_job.rule_job_summary() 
                           if "Profiler" in rule["RuleConfigurationName"]][0]
   profiler_report_name
   display("Click link below to view the profiler report", FileLink(profiler_report_name+"/profiler-output/profiler-report.html"))
   ```
**提示**  
如果 HTML 报告未在 JupyterLab 视图中呈现绘图，则必须在报告顶部选择 T **rust HTML**。  
要识别训练问题，例如过度拟合、渐变消失以及其他阻碍模型收敛的问题，请使用 D SageMaker ebugger，在对机器学习模型进行原型设计和训练时自动执行操作。有关更多信息，请参阅 [Amazon SageMaker 调试器](train-debugger.md)。要查找模型参数的完整分析，请参阅 [Amazon D SageMaker ebugger 的可解释性](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/xgboost_census_explanations/xgboost-census-debugger-rules.html#Explainability-with-Amazon-SageMaker-Debugger)示例笔记本。

你现在有一个经过训练的 XGBoost 模型了。 SageMaker AI 将模型工件存储在您的 S3 存储桶中。要查找模型构件的位置，请运行以下代码以打印 `xgb_model` 估算器的 model\$1data 属性：

```
xgb_model.model_data
```

**提示**  
要测量机器学习生命周期的每个阶段（数据收集、模型训练和调整以及监控为预测而部署的机器学习模型）中可能出现的偏差，请使用 Clarify SageMaker 。有关更多信息，请参阅 [模型可解释性](clarify-model-explainability.md)。有关 end-to-end示例，请参阅 Clarify 的[公平性和可解释性示例 SageMaker 笔记本](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-clarify/fairness_and_explainability/fairness_and_explainability.html)。