

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

# 如何使用 SageMaker AI xgBoost
<a name="xgboost-how-to-use"></a>

借助 SageMaker AI，您可以将 XGBoost 用作内置算法或框架。当将 XGBoost 用作框架，您可以自定义自己的训练脚本，从而具有更大的灵活性并可以访问更高级的方案。以下各节介绍如何将 XGBoost 与 Pyth SageMaker on SDK 配合使用，以及 XGBoost 算法的 input/output 接口。有关如何通过 Amazon SageMaker Studio Classic 用户界面使用 XGBoost 的信息，请参阅。[SageMaker JumpStart 预训练模型](studio-jumpstart.md)

**Topics**
+ [使用 XGBoost 作为框架](#xgboost-how-to-framework)
+ [使用 XGBoost 作为内置算法](#xgboost-how-to-built-in)
+ [Input/Output XGBoost 算法的接口](#InputOutput-XGBoost)

## 使用 XGBoost 作为框架
<a name="xgboost-how-to-framework"></a>

使用 XGBoost 作为框架来运行可以将附加数据处理合并到训练作业中的自定义训练脚本。在以下代码示例中， SageMaker Python SDK 将 XGBoost API 作为框架提供。其功能与 SageMaker AI 提供其他框架 API 的方式类似 TensorFlow，例如 MxNet 和。 PyTorch

```
import boto3
import sagemaker
from sagemaker.xgboost.estimator import XGBoost
from sagemaker.session import Session
from sagemaker.inputs import TrainingInput

# initialize hyperparameters
hyperparameters = {
        "max_depth":"5",
        "eta":"0.2",
        "gamma":"4",
        "min_child_weight":"6",
        "subsample":"0.7",
        "verbosity":"1",
        "objective":"reg:squarederror",
        "num_round":"50"}

# set an output path where the trained model will be saved
bucket = sagemaker.Session().default_bucket()
prefix = 'DEMO-xgboost-as-a-framework'
output_path = 's3://{}/{}/{}/output'.format(bucket, prefix, 'abalone-xgb-framework')

# construct a SageMaker AI XGBoost estimator
# specify the entry_point to your xgboost training script
estimator = XGBoost(entry_point = "{{your_xgboost_abalone_script.py}}", 
                    framework_version='{{1.7-1}}',
                    hyperparameters=hyperparameters,
                    role=sagemaker.get_execution_role(),
                    instance_count=1,
                    instance_type='ml.m5.2xlarge',
                    output_path=output_path)

# define the data type and paths to the training and validation datasets
content_type = "libsvm"
train_input = TrainingInput("s3://{}/{}/{}/".format(bucket, prefix, 'train'), content_type=content_type)
validation_input = TrainingInput("s3://{}/{}/{}/".format(bucket, prefix, 'validation'), content_type=content_type)

# execute the XGBoost training job
estimator.fit({'train': train_input, 'validation': validation_input})
```

有关使用 SageMaker AI xgBoost 作为框架的端到端示例，请参阅使用[亚马逊 A SageMaker I xgBoost 进行回归](https://sagemaker-examples.readthedocs.io/en/latest/introduction_to_amazon_algorithms/xgboost_abalone/xgboost_abalone_dist_script_mode.html)。

## 使用 XGBoost 作为内置算法
<a name="xgboost-how-to-built-in"></a>

使用 XGBoost 内置算法构建 XGBoost 训练容器，如以下代码示例所示。你可以使用 AI API 自动发现 XGBoost 内置算法图像 UR SageMaker I `image_uris.retrieve`。如果使用[亚马逊 SageMaker Python 软件开发工具包](https://sagemaker.readthedocs.io/en/stable)版本 1，请使用 `get_image_uri` API。要确保 `image_uris.retrieve` API 找到正确的 URI，请参阅[内置算法的常用参数](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-algo-docker-registry-paths.html)。然后从内置算法映像 URI 和可用区域的完整列表中查找 `xgboost`。

指定 XGBoost 图像 URI 后，使用 XGBoost 容器使用 AI 估算器 AP SageMaker I 构造估算器并启动训练作业。此 XGBoost 内置算法模式不包含您自己的 XGBoost 训练脚本，而是直接在输入数据集上运行。

**重要**  
检索 SageMaker AI xgBoost 图像 URI 时，请勿使用`:latest`或`:1`作为图像 URI 标签。必须指定其中一个才能选择包含[支持的版本](xgboost.md#xgboost-supported-versions)要使用的本机 SageMaker AI-managed XGBoost 包版本的 XGBoost 容器。要查找迁移到 SageMaker AI xgBoost 容器中的软件包版本，请参阅 [Docker 注册表路径和示例](https://docs.aws.amazon.com/sagemaker/latest/dg-ecr-paths/sagemaker-algo-docker-registry-paths.html)代码。然后选择 AWS 区域，并导航至 **XGBoost（算法）**部分。

```
import sagemaker
import boto3
from sagemaker import image_uris
from sagemaker.session import Session
from sagemaker.inputs import TrainingInput

# initialize hyperparameters
hyperparameters = {
        "max_depth":"5",
        "eta":"0.2",
        "gamma":"4",
        "min_child_weight":"6",
        "subsample":"0.7",
        "objective":"reg:squarederror",
        "num_round":"50"}

# set an output path where the trained model will be saved
bucket = sagemaker.Session().default_bucket()
prefix = 'DEMO-xgboost-as-a-built-in-algo'
output_path = 's3://{}/{}/{}/output'.format(bucket, prefix, 'abalone-xgb-built-in-algo')

# this line automatically looks for the XGBoost image URI and builds an XGBoost container.
# specify the repo_version depending on your preference.
xgboost_container = sagemaker.image_uris.retrieve("xgboost", region, "{{1.7-1}}")

# construct a SageMaker AI estimator that calls the xgboost-container
estimator = sagemaker.estimator.Estimator(image_uri=xgboost_container, 
                                          hyperparameters=hyperparameters,
                                          role=sagemaker.get_execution_role(),
                                          instance_count=1, 
                                          instance_type='ml.m5.2xlarge', 
                                          volume_size=5, # 5 GB 
                                          output_path=output_path)

# define the data type and paths to the training and validation datasets
content_type = "libsvm"
train_input = TrainingInput("s3://{}/{}/{}/".format(bucket, prefix, 'train'), content_type=content_type)
validation_input = TrainingInput("s3://{}/{}/{}/".format(bucket, prefix, 'validation'), content_type=content_type)

# execute the XGBoost training job
estimator.fit({'train': train_input, 'validation': validation_input})
```

有关如何将 XGBoost 设置为内置算法的更多信息，请参阅以下笔记本示例。
+ [适用于 XGBoost 的托管 Spot 训练](https://sagemaker-examples.readthedocs.io/en/latest/introduction_to_amazon_algorithms/xgboost_abalone/xgboost_managed_spot_training.html)
+ [使用亚马逊 A SageMaker I xgBoost 进行回归（Parquet 输入）](https://sagemaker-examples.readthedocs.io/en/latest/introduction_to_amazon_algorithms/xgboost_abalone/xgboost_parquet_input_training.html)

## Input/Output XGBoost 算法的接口
<a name="InputOutput-XGBoost"></a>

梯度提升对表格数据进行操作，其中行表示观察、一个列表示目标变量或标签，其余列表示特征。

XGBoost 的 SageMaker AI 实现支持以下用于训练和推理的数据格式：
+  *text/libsvm*（默认值） 
+  *text/csv*
+  *application/x-实木复合地板*
+  *application/x-recordio-protobuf*

**注意**  
关于训练和推理输入，有几个事项需要注意：  
为提高性能，我们建议将 XGBoost 与*文件模式*结合使用，在这种模式下，Amazon S3 中的数据将存储在训练实例卷上。
对于使用列式输入的训练，算法会假定目标变量（标签）是第一列。对于推理，算法会假定输入没有标签列。
对于 CSV 数据，输入不应有标题记录。
对于 LIBSVM 训练，算法假定标签列后面的列包含特征的索引值对，索引从零开始。因此，每一行的格式为：<label> <index0>:<value0> <index1>:<value1>。
有关实例类型和分布式训练的信息，请参阅 [XGBoost 算法的 EC2 实例推荐](xgboost.md#Instance-XGBoost)。

对于 CSV 训练输入模式，可用于算法的总内存必须能够容纳训练数据集。可用内存总量的计算公式为 `Instance Count * the memory available in the InstanceType`。对于 libsvm 训练输入模式，它不是必需的，但我们建议使用它。

对于 v1.3-1 及更高版本， SageMaker AI xgBoost 使用 xgBoost 内部二进制格式将模型保存为 xgBoost 内部二进制格式。`Booster.save_model`之前的版本在模型中使用 Python pickle 模块 serialize/deserialize 。

**注意**  
在开源 XGBoost 中使用 A SageMaker I xgBoost 模型时，请注意版本。版本 1.3-1 及更高版本使用 XGBoost 内部二进制格式，而之前的版本使用 Python pickle 模块。

**要在开源 xgBoost 中使用使用 SageMaker AI xgBoost v1.3-1 或更高版本训练的模型 xgBoost**
+ 使用以下 Python 代码：

  ```
  import xgboost as xgb
  
  xgb_model = xgb.Booster()
  xgb_model.load_model({{model_file_path}})
  xgb_model.predict({{dtest}})
  ```

**在开源 xgBoost 中使用使用以前版本的 SageMaker AI xgBoost 训练过的模型**
+ 使用以下 Python 代码：

  ```
  import pickle as pkl 
  import tarfile
  
  t = tarfile.open('model.tar.gz', 'r:gz')
  t.extractall()
  
  model = pkl.load(open({{model_file_path}}, 'rb'))
  
  # prediction with test data
  pred = model.predict({{dtest}})
  ```

**使用实例权重支持区分标记数据点的重要性**
+ SageMaker AI xgBoost 允许客户通过为每个实例分配权重值来区分已标记数据点的重要性。对于*text/libsvm*输入，客户可以通过在标签后面附加权重值来为数据实例分配权重值。例如 `label:weight idx_0:val_0 idx_1:val_1...`。要进行*text/csv*输入，客户需要在参数中打开`csv_weights`标记，并在标签后面的列中附加重量值。例如：`label,weight,val_0,val_1,...`。