본문 바로가기

AWS

[SageMaker] 모델 훈련

728x90

모델 학습 작업을 실행하기 위해

Amazon SageMaker Python SDK 가져오기로 현재 sagemaker 세션에서 기본 정보를 검색하여 시작한다

import sagemaker

region = sagemaker.Session().boto_region_name
print("AWS Region: {}".format(region))

role = sagemaker.get_execution_role()
print("RoleArn: {}".format(role))

 

sagemaker.estimator.Estimator 클래스를 사용하여 XGBoost 추정기를 만든다

from sagemaker.debugger import Rule, rule_configs
from sagemaker.session import TrainingInput

s3_output_location='s3://{}/{}/{}'.format(bucket, prefix, 'xgboost_model')

container=sagemaker.image_uris.retrieve("xgboost", region, "1.2-1")
print(container)

xgb_model=sagemaker.estimator.Estimator(
    image_uri=container,
    role=role,
    instance_count=1,
    instance_type='ml.m4.xlarge',
    volume_size=5,
    output_path=s3_output_location,
    sagemaker_session=sagemaker.Session(),
    rules=[Rule.sagemaker(rule_configs.create_xgboost_report())]
)

 

set_hyperparameters 추정기의 메소드를 호출해 XGBoost 알고리즘에 대한 하이퍼파라미터를 설정한다

xgb_model.set_hyperparameters(
    max_depth = 5,
    eta = 0.2,
    gamma = 4,
    min_child_weight = 6,
    subsample = 0.7,
    objective = "binary:logistic",
    num_round = 1000
)

 

클래스를 사용하여 TrainingInput 교육을 위한 데이터 입력 흐름을 구성한다. S3에 업로드한 훈련 및 검증 데이터 세트를 사용하도록 객체를 구성하는 방법이다

from sagemaker.session import TrainingInput

train_input = TrainingInput(
    "s3://{}/{}/{}".format(bucket, prefix, "data/train.csv"), content_type="csv"
)
validation_input = TrainingInput(
    "s3://{}/{}/{}".format(bucket, prefix, "data/validation.csv"), content_type="csv"
)

 

fit으로 모델 훈련을 시작하기 위해 훈련 및 검증 세트로 호출

xgb_model.fit({"train": train_input, "validation": validation_input}, wait=True)

wait=True라고 하면 fit메서드가 진행 로그를 표시하고 훈련이 완료될 때까지 기다린다

 

디버거 교육 보고서가 생성되는 s3 버킷 URI를 지정하고 보고서가 있는지 확인

rule_output_path = xgb_model.output_path + "/" + xgb_model.latest_training_job.job_name + "/rule-output"
! aws s3 ls {rule_output_path} --recursive

 

Debugger XGBoost 교육 및 프로파일링 보고서를 현재 작업 공간에 다운로드한다

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

 

IPython 스크립트를 실행하여 XGBoost 교육 보고서의 파일 링크를 가져온다

from IPython.display import FileLink, FileLinks
display("Click link below to view the XGBoost Training report", FileLink("CreateXgboostReport/xgboost_report.html"))

 

EC2 인스턴스 리소스 사용률, 시스템 병목 현상 감지 결과, 파이썬 작업 프로파일링 결과에 대한 요약 및 세부 정보를 보여주는 디버거 프로파일링 보고서의 파일링크가 반환된다

profiler_report_name = [rule["RuleConfigurationName"] 
                        for rule in xgb_model.latest_training_job.rule_job_summary() 
                        if "Profiler" in rule["RuleConfigurationName"]][0]
profiler_report_name
display("Click link below to view the profiler report", FileLink(profiler_report_name+"/profiler-output/profiler-report.html"))

 

링크를 클릭하면 이런 표를 볼 수 있다

 

훈련된 XGBoost 모델이 생성되었고 세이지메이커는 s3 버킷에 모델 아티팩트를 저장한다

xgb_model.model_data

 

 

728x90

'AWS' 카테고리의 다른 글

[SageMaker] 모델 평가  (0) 2022.06.28
[SageMaker] 모델 배포  (1) 2022.06.28
[SageMaker] 데이터 세트 다운로드하기  (0) 2022.06.28
[SageMaker] 세이지메이커 시작하기  (0) 2022.06.28
[중간점검..seminarrr...,,] AWS Greengrass  (0) 2022.05.04