

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 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를 프레임워크로 사용하는 전체 예시는 [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(알고리즘)** 섹션으로 이동합니다.

```
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를 위한 관리형 스팟 훈련](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>

그라디언트 부스팅은 테이블형 데이터에서 작동합니다. 행은 관측치를 나타내고 1개 열은 대상 변수 또는 레이블을 나타내며, 나머지 열은 특징을 나타냅니다.

SageMaker AI의 XGBoost 구현은 훈련 및 추론을 위해 다음 데이터 형식을 지원합니다.
+  *text/libsvm*(기본값) 
+  *text/csv*
+  *application/x-parquet*
+  *application/x-recordio-protobuf*

**참고**  
훈련 및 추론 입력과 관련하여 알아두어야 할 몇 가지 고려 사항이 있습니다.  
성능을 높이려면 Amazon S3의 데이터가 훈련 인스턴스 볼륨에 저장되는 *파일 모드*와 함께 XGBoost를 사용하는 것이 좋습니다.
열 형식 입력값을 사용한 훈련의 경우, 알고리즘은 대상 변수(label) 가 첫 번째 열이라고 가정합니다. 추론의 경우 알고리즘은 입력에 레이블 열이 없다고 추정합니다.
CSV 데이터의 경우 입력값에 헤더 레코드가 없어야 합니다.
LIBSVM 훈련의 경우 알고리즘은 레이블 열 뒤의 후속 열에 기능에 대한 0부터 시작하는 인덱스 값 쌍이 포함되어 있다고 가정합니다. 그래서 각 행은 <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 피클 모듈을 사용합니다.

**오픈 소스 XGBoost에서 v1.3-1 이상의 SageMaker AI 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,...`.