

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# SageMaker AI XGBoost の使用方法
<a name="xgboost-how-to-use"></a>

SageMaker AI では、組み込みのアルゴリズムまたはフレームワークとして XGBoost を使用できます。XGBoost をフレームワークとして使用すると、独自のトレーニングスクリプトをカスタマイズできるため、柔軟性が高まり、より高度なシナリオを利用できるようになります。以下のセクションでは、SageMaker Python SDK で XGBoost を使用する方法と、XGBoost アルゴリズムの入出力インターフェイスについて説明します。Amazon SageMaker Studio Classic UI から 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 が TensorFlow、MXNet、PyTorch などの他のフレームワーク API を提供する場合と同様に機能します。

```
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 を使用するエンドツーエンドの例については、「[Regression with 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 Estimator API を使って推定器を作成し、トレーニングジョブを開始します。この XGBoost 組み込みアルゴリズムモードでは、独自の XGBoost トレーニングスクリプトは組み込まれず、入力データセット上で直接実行されます。

**重要**  
SageMaker AI XGBoost イメージ URI を取得する場合は、イメージ URI タグに `:latest` または `:1` を使用しないでください。使用するネイティブ XGBoost パッケージバージョンの SageMaker AI が管理する XGBoost コンテナを選択するには、[サポートバージョン](xgboost.md#xgboost-supported-versions) のいずれかを指定する必要があります。SageMaker AI XGBoost コンテナに移行されたパッケージバージョンを確認するには、「[Docker Registry Paths and Example Code](https://docs.aws.amazon.com/sagemaker/latest/dg-ecr-paths/sagemaker-algo-docker-registry-paths.html)」を参照してください。次に、 AWS リージョンを選択し、「**XGBoost (algorithm)**」セクションに移動します。

```
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 を組み込みアルゴリズムとして設定する方法の詳細については、次のノートブックの例を参照してください。
+ [Managed Spot Training for XGBoost](https://sagemaker-examples.readthedocs.io/en/latest/introduction_to_amazon_algorithms/xgboost_abalone/xgboost_managed_spot_training.html)
+ [Regression with Amazon SageMaker AI XGBoost (Parquet input)](https://sagemaker-examples.readthedocs.io/en/latest/introduction_to_amazon_algorithms/xgboost_abalone/xgboost_parquet_input_training.html)

## XGBoost アルゴリズムの入出力インターフェイス
<a name="InputOutput-XGBoost"></a>

勾配ブースティングは表形式のデータで動作し、行が観測値、1 つの列がターゲット変数またはラベル、残りの列が特徴を表します。

SageMaker AI の XGBoost の実装では、トレーニングと推論に次のデータ形式が対応しています。
+  text/libsvm (default) 
+  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 の pickle モジュールを使用していました。

**注記**  
オープンソースの XGBoost で SageMaker AI XGBoost モデルを使用する場合は、バージョンに注意してください。バージョン 1.3-1 以降は XGBoost 内部バイナリ形式を使用していますが、以前のバージョンでは Python の pickle モジュールを使用しています。

**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}})
  ```

**以前のバージョンの SageMaker AI XGBoost でトレーニングされたモデルをオープンソースの 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,...`)。