

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

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

您可以透過 SageMaker AI 使用 XGBoost 做為內建演算法或框架。將 XGBoost 作為框架時，您具備更多彈性並且可存取更進階的案例，因為您可以自訂自己的訓練指令碼。下列各節說明如何搭配 SageMaker Python SDK 使用 XGBoost，以及 XGBoost 演算法的輸入/輸出介面。如需如何從 Amazon SageMaker Studio Classic 使用者介面使用 XGBoost 的資訊，請參閱[SageMaker JumpStart 預先訓練模型](studio-jumpstart.md)。

**Topics**
+ [使用 XGBoost 做為框架](#xgboost-how-to-framework)
+ [使用 XGBoost 做為內建演算法](#xgboost-how-to-built-in)
+ [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 做為框架的完整範例，請參閱[使用 Amazon SageMaker AI 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 訓練容器，如下面的程式碼範例所示。您可以使用 SageMaker AI `image_uris.retrieve` API 自動找出 XGBoost 內建演算法映像 URI。如果使用 [Amazon SageMaker Python SDK](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 容器來建置使用 SageMaker AI 估算器 API 的估算器，並啟動訓練任務。這個 XGBoost 內建演算法模式不會納入您自己的 XGBoost 訓練指令碼中，並且會直接在輸入資料集上執行。

**重要**  
擷取 SageMaker AI XGBoost 映像 URI 時，請勿使用 `:latest` 或 `:1` 作為映像 URI 標記。您必須指定 [支援的版本](xgboost.md#xgboost-supported-versions) 其中之一，才能選擇由 SageMaker AI 管理的 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)
+ [使用 Amazon SageMaker AI XGBoost 進行迴歸 (Parquet 輸入)](https://sagemaker-examples.readthedocs.io/en/latest/introduction_to_amazon_algorithms/xgboost_abalone/xgboost_parquet_input_training.html)

## XGBoost 演算法的輸入/輸出介面
<a name="InputOutput-XGBoost"></a>

梯度提升在表格式資料中操作，含有代表觀察的行、還有一個代表目標變數或標籤的欄，而剩下的欄則代表功能。

XGBoost 的 SageMaker AI 實作支援以下資料格式用於訓練與推論：
+  *text/libsvm* (預設值) 
+  *text/csv*
+  *application/x-parquet*
+  *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 使用 `Booster.save_model` 以 XGBoost 內部二進位格式儲存模型。之前的版本使用 Python 保存模組將模型序列化/取消序列化。

**注意**  
在開放原始碼 XGBoost 中使用 SageMaker AI XGBoost 模型時，請留意其版本。1.3-1 版及更新的版本使用 XGBoost 內部二進位格式，而之前的版本使用 Python 保存模組。

**在開放原始碼 XGBoost 中使用以 SageMaker AI XGBoost v1.3-1 或更新的版本訓練的模型**
+ 使用以下 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,...`。