View a markdown version of this page

Amazon EC2에 모델 배포 - Amazon SageMaker AI

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

Amazon EC2에 모델 배포

예측을 위해서는 Amazon SageMaker AI를 사용하여 모델을 Amazon EC2에 배포하세요.

SageMaker AI 호스팅 서비스에 모델 배포

Amazon SageMaker AI를 사용하여 Amazon EC2를 통해 모델을 호스팅하려면에서 훈련한 모델을 배포합니다훈련 작업 생성 및 실행. Amazon SageMaker

ModelBuilder 클래스를 사용하여 모델을 빌드하고 배포합니다. ModelBuilder는 리소스 체인화를 지원하므로 훈련된를 ModelTrainer 직접 전달하여 모델을 빌드하고 배포할 수 있습니다.

from sagemaker.serve import ModelBuilder # Build and deploy using resource chaining from the trained model model_builder = ModelBuilder( model=xgb_model_trainer, role_arn=role, instance_type='ml.t2.medium' ) # Build creates a SageMaker Model resource model = model_builder.build() # Deploy creates a SageMaker Endpoint resource endpoint = model_builder.deploy(endpoint_name="xgboost-endpoint")
  • model - 훈련된 ModelTrainer 객체입니다.는 훈련 출력을 배포에 ModelBuilder 자동으로 연결합니다.

  • instance_type (str) – 배포된 모델을 작동할 인스턴스 유형입니다.

build() 메서드는 SageMaker AI 모델 리소스를 생성하고 SageMaker AI 엔드포인트 리소스를 deploy() 생성합니다. 자세한 내용은 Amazon SageMaker Python SDK의 SageMaker AI ModelBuilder를 참조하세요. Amazon SageMaker 엔드포인트의 이름을 검색하려면 다음 코드를 실행합니다.

endpoint.endpoint_name

이 엔드포인트는 ML 인스턴스에서 활성 상태로 유지되며 나중에 종료하지 않는 한 언제든지 즉시 예측을 수행할 수 있습니다. 이 엔드포인트 이름을 복사하고 저장하여 SageMaker Studio 또는 SageMaker AI 노트북 인스턴스의 다른 곳에서 재사용 및 실시간 예측을 수행할 수 있습니다.

작은 정보

Amazon EC2 인스턴스 또는 엣지 디바이스에 배포하기 위해 모델을 컴파일하고 최적화하는 방법에 대해 자세히 알아보려면 Neo로 모델 컴파일 및 배포를 참조하세요.

(선택 사항) 기존 엔드포인트 재사용 또는 호출

모델을 엔드포인트에 배포한 후 sagemaker-core의 Endpoint 클래스를 사용하여 다른 노트북 또는 애플리케이션에서 모델을 호출할 수 있습니다. 다음 예제 코드는 기존 엔드포인트를 가져오고 예측하는 방법을 보여줍니다. 위의 배포 단계에서 엔드포인트 이름을 재사용합니다.

from sagemaker.core.resources import Endpoint endpoint = Endpoint.get(endpoint_name="xgboost-endpoint") # Make a prediction response = endpoint.invoke( body=test_data, content_type="text/csv" ) result = response.body.read().decode('utf-8')

(선택 사항) 배치 변환으로 예측하기

프로덕션 환경에서 엔드포인트를 호스팅하는 대신 SageMaker AI 배치 변환을 사용하여 테스트 데이터세트를 예측하는 일회성 배치 추론 작업을 실행할 수 있습니다. 모델 훈련이 완료되면 배치 변환기를 사용하여 지정된 S3 버킷에서 입력 데이터를 읽고 예측할 수 있습니다.

배치 변환 작업을 생성하려면
  1. 다음 코드를 실행하여 테스트 데이터세트의 특성 열을 CSV 파일로 변환하고 S3 버킷에 업로드합니다.

    X_test.to_csv('test.csv', index=False, header=False) boto3.Session().resource('s3').Bucket(bucket).Object( os.path.join(prefix, 'test/test.csv')).upload_file('test.csv')
  2. 배치 변환 작업에 대한 입력 및 출력의 S3 버킷 URI를 다음과 같이 지정합니다.

    # The location of the test dataset batch_input = 's3://{}/{}/test'.format(bucket, prefix) # The location to store the results of the batch transform job batch_output = 's3://{}/{}/batch-prediction'.format(bucket, prefix)
  3. 배치 변환 작업을 생성하고 실행합니다.

    # Build a model from the trained ModelTrainer model_builder = ModelBuilder(model=xgb_model_trainer, role_arn=role) model = model_builder.build(model_name="xgboost-batch-model") # Create and run the batch transform job from sagemaker.core.resources import TransformJob transform_job = TransformJob.create( model_name=model.model_name, transform_input={ "data_source": { "s3_data_source": { "s3_data_type": "S3Prefix", "s3_uri": batch_input } }, "content_type": "text/csv", "split_type": "Line" }, transform_output={ "s3_output_path": batch_output }, transform_resources={ "instance_type": "ml.m4.xlarge", "instance_count": 1 } ) transform_job.wait()
  4. 배치 변환 작업이 완료되면 SageMaker AI는 batch_output 경로에 저장된 test.csv.out 예측 데이터를 생성하며, 이 데이터는 s3://sagemaker-<region>-111122223333/demo-sagemaker-xgboost-adult-income-prediction/batch-prediction 형식이어야 합니다. 다음을 실행 AWS CLI 하여 배치 변환 작업의 출력 데이터를 다운로드합니다.

    ! aws s3 cp {batch_output} ./ --recursive

    이렇게 하면 현재 작업 디렉터리 아래에 test.csv.out 파일이 생성됩니다. XGBoost 훈련 작업의 로지스틱 회귀 분석을 기반으로 예측된 부동 값을 확인할 수 있습니다.