{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# [모듈 3.3] 모델 훈련 스텝 개발 (SageMaker Model Building Pipeline 훈련 스텝)\n", "\n", "이 노트북은 아래와 같은 목차로 진행 됩니다. 전체를 모두 실행시에 완료 시간은 약 5분-10분 소요 됩니다.\n", "\n", "- 1. 모델 훈련 스텝 개요\n", "- 2. 기본 라이브러리 로딩\n", "- 3. 훈련에 사용할 전처리된 파일을 확인\n", "- 4. 모델 빌딩 파이프라인 의 스텝(Step) 생성\n", "- 5. 파리마터, 단계, 조건을 조합하여 최종 파이프라인 정의 및 실행\n", "- 6. 세이지 메이커 스튜디오에서 확인하기\n", "- 7. 모델 아티펙트 경로 추출\n", " \n", "---\n", "### 노트북 커널\n", "- 이 워크샵은 노트북 커널이 `conda_python3` 를 사용합니다. 다른 커널일 경우 변경 해주세요.\n", "---\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 1. 모델 훈련 스텝 개요\n", "- 모델 훈련 및 등록 단계의 개발자 가이드 \n", " - [모델 훈련 스텝](https://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/build-and-manage-steps.html#step-type-training)\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 2. 기본 라이브러리 로딩\n", "\n", "세이지 메이커 관련 라이브러리를 로딩 합니다." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Stored variables and their in-db values:\n", "bucket -> 'sagemaker-us-east-1-051065130547'\n", "claims_data_uri -> 's3://sagemaker-us-east-1-051065130547/sagemaker-w\n", "customers_data_uri -> 's3://sagemaker-us-east-1-051065130547/sagemaker-w\n", "input_data_uri -> 's3://sagemaker-us-east-1-051065130547/sagemaker-w\n", "preprocessing_code -> 'src/preprocessing.py'\n", "project_prefix -> 'sagemaker-webinar-pipeline-base'\n", "test_preproc_dir_artifact -> 's3://sagemaker-us-east-1-051065130547/Fraud-Basic\n", "train_preproc_dir_artifact -> 's3://sagemaker-us-east-1-051065130547/Fraud-Basic\n" ] } ], "source": [ "import boto3\n", "import sagemaker\n", "import pandas as pd\n", "import os\n", "\n", "sagemaker_session = sagemaker.session.Session()\n", "role = sagemaker.get_execution_role()\n", "\n", "\n", "%store -r \n", "# 노트북에 저장되어 있는 변수를 보기 위해서는 주석을 제거하고 실행하시면 됩니다.\n", "%store " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 3. 훈련에 사용할 전처리된 파일을 확인\n", "이후에 훈련에서 사용할 S3의 저장된 전처리 데이터를 확인 합니다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3.1. 데이터 세트 로딩\n", "- 이전 단계(전처리)에서 결과 파일을 로딩 합니다. 실제 훈련에 제공되는 데이터를 확인하기 위함 입니다.\n", "- 로딩힐 데이터 파일이 S3에 있는지 변수의 경로를 확인 합니다. (train_preproc_dir_artifact)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "train_preproc_dir_artifact_file: \n", " s3://sagemaker-us-east-1-051065130547/Fraud-Basic-Process-476f3bbbf986da0944ce9ca52d7c54b6/output/train/train.csv\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
fraudvehicle_claimtotal_claim_amountcustomer_agemonths_as_customernum_claims_past_yearnum_insurers_past_5_yearspolicy_deductablepolicy_annual_premiumcustomer_zip...collision_type_missingincident_severity_Majorincident_severity_Minorincident_severity_Totaledauthorities_contacted_Ambulanceauthorities_contacted_Fireauthorities_contacted_Noneauthorities_contacted_Policepolice_report_available_Nopolice_report_available_Yes
008913.66876380513.668763549401750300099207...0010001010
1019746.72439526146.7243954116501750295095632...0001000101
2011652.96991822052.9699185715501750300093203...0010000101
3011260.930936115960.930936398001750300085208...0010001010
4027987.70465231387.704652396001750300091792...0100000110
..................................................................
3995018052.61162667152.6116264210311750300093654...0010001010
3996034949.20246851749.20246823603750300094305...0001100010
399704063.7014109963.701410443502750255095476...0010000101
3998017390.52045120490.520451223801750300090680...0100000101
399902501.8115938401.811593577401900265098029...0100000101
\n", "

4000 rows × 59 columns

\n", "
" ], "text/plain": [ " fraud vehicle_claim total_claim_amount customer_age \\\n", "0 0 8913.668763 80513.668763 54 \n", "1 0 19746.724395 26146.724395 41 \n", "2 0 11652.969918 22052.969918 57 \n", "3 0 11260.930936 115960.930936 39 \n", "4 0 27987.704652 31387.704652 39 \n", "... ... ... ... ... \n", "3995 0 18052.611626 67152.611626 42 \n", "3996 0 34949.202468 51749.202468 23 \n", "3997 0 4063.701410 9963.701410 44 \n", "3998 0 17390.520451 20490.520451 22 \n", "3999 0 2501.811593 8401.811593 57 \n", "\n", " months_as_customer num_claims_past_year num_insurers_past_5_years \\\n", "0 94 0 1 \n", "1 165 0 1 \n", "2 155 0 1 \n", "3 80 0 1 \n", "4 60 0 1 \n", "... ... ... ... \n", "3995 103 1 1 \n", "3996 6 0 3 \n", "3997 35 0 2 \n", "3998 38 0 1 \n", "3999 74 0 1 \n", "\n", " policy_deductable policy_annual_premium customer_zip ... \\\n", "0 750 3000 99207 ... \n", "1 750 2950 95632 ... \n", "2 750 3000 93203 ... \n", "3 750 3000 85208 ... \n", "4 750 3000 91792 ... \n", "... ... ... ... ... \n", "3995 750 3000 93654 ... \n", "3996 750 3000 94305 ... \n", "3997 750 2550 95476 ... \n", "3998 750 3000 90680 ... \n", "3999 900 2650 98029 ... \n", "\n", " collision_type_missing incident_severity_Major \\\n", "0 0 0 \n", "1 0 0 \n", "2 0 0 \n", "3 0 0 \n", "4 0 1 \n", "... ... ... \n", "3995 0 0 \n", "3996 0 0 \n", "3997 0 0 \n", "3998 0 1 \n", "3999 0 1 \n", "\n", " incident_severity_Minor incident_severity_Totaled \\\n", "0 1 0 \n", "1 0 1 \n", "2 1 0 \n", "3 1 0 \n", "4 0 0 \n", "... ... ... \n", "3995 1 0 \n", "3996 0 1 \n", "3997 1 0 \n", "3998 0 0 \n", "3999 0 0 \n", "\n", " authorities_contacted_Ambulance authorities_contacted_Fire \\\n", "0 0 0 \n", "1 0 0 \n", "2 0 0 \n", "3 0 0 \n", "4 0 0 \n", "... ... ... \n", "3995 0 0 \n", "3996 1 0 \n", "3997 0 0 \n", "3998 0 0 \n", "3999 0 0 \n", "\n", " authorities_contacted_None authorities_contacted_Police \\\n", "0 1 0 \n", "1 0 1 \n", "2 0 1 \n", "3 1 0 \n", "4 0 1 \n", "... ... ... \n", "3995 1 0 \n", "3996 0 0 \n", "3997 0 1 \n", "3998 0 1 \n", "3999 0 1 \n", "\n", " police_report_available_No police_report_available_Yes \n", "0 1 0 \n", "1 0 1 \n", "2 0 1 \n", "3 1 0 \n", "4 1 0 \n", "... ... ... \n", "3995 1 0 \n", "3996 1 0 \n", "3997 0 1 \n", "3998 0 1 \n", "3999 0 1 \n", "\n", "[4000 rows x 59 columns]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "train_preproc_dir_artifact_file = os.path.join(train_preproc_dir_artifact,'train.csv')\n", "print(\"train_preproc_dir_artifact_file: \\n\", train_preproc_dir_artifact_file)\n", "train_prep_df = pd.read_csv(train_preproc_dir_artifact_file)\n", "train_prep_df" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### [참고] AioClientError 발생시\n", "\n", "* pip uninstall boto3\n", "* pip uninstall botocore\n", "* pip uninstall aiobotocore\n", "\n", "실행후\n", "\n", "* pip install boto3==1.17.106\n", "* pip install s3fs==2021.11.1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 4. 모델 빌딩 파이프라인 의 스텝(Step) 생성\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.1 모델 빌딩 파이프라인 변수 생성\n", "\n", "파이프라인에서 사용할 파이프라인 파라미터를 정의합니다. 파이프라인을 스케줄하고 실행할 때 파라미터를 이용하여 실행조건을 커스마이징할 수 있습니다. 파라미터를 이용하면 파이프라인 실행시마다 매번 파이프라인 정의를 수정하지 않아도 됩니다.\n", "\n" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "from sagemaker.workflow.parameters import (\n", " ParameterInteger,\n", " ParameterString,\n", ")\n", "\n", "training_instance_type = ParameterString(\n", " name=\"TrainingInstanceType\",\n", " default_value=\"ml.m5.xlarge\"\n", ")\n", "\n", "training_instance_count = ParameterInteger(\n", " name=\"TrainingInstanceCount\",\n", " default_value= 1\n", ")\n", "\n", "input_data = ParameterString(\n", " name=\"InputData\",\n", " default_value=input_data_uri,\n", ")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.2 하이퍼파라미터 세팅" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 기본 훈련 변수 및 하이퍼파라미터 설정\n", "- XGBoost에 알고리즘에 입력될 하이퍼 파리미터의 값을 설정 합니다.\n", "- scale_pos_weight 의 경우는 현재의 데이터가 레이블(fraud)간 불균형이 있기에, fraud: 1, non-fraud: 0 의 비율을 계산하여 제공합니다.\n", " - 하이퍼 파라미터 상세 사항은 여기를 보세요. --> [XGBoost Parameters](https://xgboost.readthedocs.io/en/latest/parameter.html)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Stored 'hyperparameters' (dict)\n" ] } ], "source": [ "from sagemaker.xgboost.estimator import XGBoost\n", "\n", "\n", "estimator_output_path = f's3://{bucket}/{project_prefix}/training_jobs'\n", "train_instance_count = 1\n", "\n", "hyperparameters = {\n", " \"scale_pos_weight\" : \"29\", \n", " \"max_depth\": \"3\",\n", " \"eta\": \"0.2\",\n", " \"objective\": \"binary:logistic\",\n", " \"num_round\": \"100\",\n", "}\n", "%store hyperparameters" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.3 Estimator 생성\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 모델 학습을 위한 학습단계 정의 \n", "\n", " XGBoost 사용자 알고리즘을 이용하도록 Estimator를 구성합니다. \n", " - 보편적인 학습스크립트를 이용하여 입력 채널에서 정의한 학습데이터를 로드하고, 하이퍼파라미터 설정을 통해 학습을 설정하고, 모델을 학습한 후 `model_dir`경로에 학습된 모델을 저장합니다. 저장된 모델은 이후 호스팅을 위해 사용됩니다. \n", "- 사용자 훈련 코드 \"src/xgboost_starter_script.py\"\n", "- 훈련이 끝난 후에 결과인 모델 아티펙트를 경로 \"estimator_output_path\" 에 지정 합니다. 지정 안할 시에는 디폴트 경로로 저장 됩니다.\n", "\n", "\n", "- 파이프라인 파라미터인 `training_instance_type`, `training_instance_count` 파라미터가 사용된 것을 확인합니다. " ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "xgb_train = XGBoost(\n", " entry_point = \"xgboost_starter_script.py\",\n", " source_dir = \"src\",\n", " output_path = estimator_output_path,\n", " code_location = estimator_output_path,\n", " hyperparameters = hyperparameters,\n", " role = role,\n", " instance_count = training_instance_count,\n", " instance_type = training_instance_type,\n", " framework_version=\"1.3-1\" \n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.4 모델 훈련 스탭 생성\n", "- 스텝 생성시에 위에서 생성한 Estimator 입력 및 입력 데이타로서 전처리 데이터가 존재하는 S3 경로를 제공합니다." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "from sagemaker.inputs import TrainingInput\n", "from sagemaker.workflow.steps import TrainingStep\n", "\n", "\n", "step_train = TrainingStep(\n", " name=\"Fraud-Basic-Train\",\n", " estimator=xgb_train,\n", " inputs={\n", " \"train\": TrainingInput(\n", " s3_data= train_preproc_dir_artifact,\n", " content_type=\"text/csv\"\n", " ),\n", " },\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "이전 단계에서 (프로세싱) 전처리 훈련, 검증 데이터 세트를 입력으로 제공 합니다.\n", "- [알림] `6.1.All-Pipeline.ipynb` 노트북에서는 입력을 전처리 스텝의 결과를 지정합니다. 여기서는 전처리 스텝과 독립적으로 실행하기 위해서 S3의 입력 파일 경로를 직접 기술 하였습니다.\n", "- `6.1.All-Pipeline.ipynb` 에서의 step_train 코드\n", "\n", "```python\n", "step_train = TrainingStep(\n", " name=\"FraudScratchTrain\",\n", " estimator=xgb_train,\n", " inputs={\n", " \"train\": TrainingInput(\n", " s3_data=step_process.properties.ProcessingOutputConfig.Outputs[\n", " \"train\"\n", " ].S3Output.S3Uri,\n", " content_type=\"text/csv\"\n", " ),\n", " },\n", ") \n", " ```\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 5. 파리마터, 단계, 조건을 조합하여 최종 파이프라인 정의 및 실행\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.1 파이프라인 정의\n", "파이프라인 정의시에 아래 3개의 인자를 제공합니다.\n", "- 파이프라인 이름\n", "- 파이프라인 파라미터\n", "- 파이프라인 실험 설정\n", "- 스텝 정의 (여기서는 훈련, 모델 등록 두가지 스텝 임)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "from sagemaker.workflow.pipeline import Pipeline\n", "\n", "pipeline_name = project_prefix\n", "pipeline = Pipeline(\n", " name=pipeline_name,\n", " parameters=[\n", " training_instance_type, \n", " training_instance_count, \n", " input_data,\n", " ],\n", " steps=[step_train],\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.2 파이프라인 정의 확인\n", "위에서 정의한 파이프라인 정의는 Json 형식으로 정의 되어 있습니다." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'Version': '2020-12-01',\n", " 'Metadata': {},\n", " 'Parameters': [{'Name': 'TrainingInstanceType',\n", " 'Type': 'String',\n", " 'DefaultValue': 'ml.m5.xlarge'},\n", " {'Name': 'TrainingInstanceCount', 'Type': 'Integer', 'DefaultValue': 1},\n", " {'Name': 'InputData',\n", " 'Type': 'String',\n", " 'DefaultValue': 's3://sagemaker-us-east-1-051065130547/sagemaker-webinar-pipeline-base/input'}],\n", " 'PipelineExperimentConfig': {'ExperimentName': {'Get': 'Execution.PipelineName'},\n", " 'TrialName': {'Get': 'Execution.PipelineExecutionId'}},\n", " 'Steps': [{'Name': 'Fraud-Basic-Train',\n", " 'Type': 'Training',\n", " 'Arguments': {'AlgorithmSpecification': {'TrainingInputMode': 'File',\n", " 'TrainingImage': '683313688378.dkr.ecr.us-east-1.amazonaws.com/sagemaker-xgboost:1.3-1'},\n", " 'OutputDataConfig': {'S3OutputPath': 's3://sagemaker-us-east-1-051065130547/sagemaker-webinar-pipeline-base/training_jobs'},\n", " 'StoppingCondition': {'MaxRuntimeInSeconds': 86400},\n", " 'ResourceConfig': {'InstanceCount': {'Get': 'Parameters.TrainingInstanceCount'},\n", " 'InstanceType': {'Get': 'Parameters.TrainingInstanceType'},\n", " 'VolumeSizeInGB': 30},\n", " 'RoleArn': 'arn:aws:iam::051065130547:role/sagemaker-notebook-SageMakerIamRole-13SLYUPDCYIY9',\n", " 'InputDataConfig': [{'DataSource': {'S3DataSource': {'S3DataType': 'S3Prefix',\n", " 'S3Uri': 's3://sagemaker-us-east-1-051065130547/Fraud-Basic-Process-476f3bbbf986da0944ce9ca52d7c54b6/output/train',\n", " 'S3DataDistributionType': 'FullyReplicated'}},\n", " 'ContentType': 'text/csv',\n", " 'ChannelName': 'train'}],\n", " 'HyperParameters': {'scale_pos_weight': '\"29\"',\n", " 'max_depth': '\"3\"',\n", " 'eta': '\"0.2\"',\n", " 'objective': '\"binary:logistic\"',\n", " 'num_round': '\"100\"',\n", " 'sagemaker_submit_directory': '\"s3://sagemaker-us-east-1-051065130547/sagemaker-webinar-pipeline-base/training_jobs/sagemaker-xgboost-2022-03-21-09-07-49-103/source/sourcedir.tar.gz\"',\n", " 'sagemaker_program': '\"xgboost_starter_script.py\"',\n", " 'sagemaker_container_log_level': '20',\n", " 'sagemaker_job_name': '\"sagemaker-xgboost-2022-03-21-09-07-49-103\"',\n", " 'sagemaker_region': '\"us-east-1\"'},\n", " 'DebugHookConfig': {'S3OutputPath': 's3://sagemaker-us-east-1-051065130547/sagemaker-webinar-pipeline-base/training_jobs',\n", " 'CollectionConfigurations': []},\n", " 'ProfilerRuleConfigurations': [{'RuleConfigurationName': 'ProfilerReport-1647853669',\n", " 'RuleEvaluatorImage': '503895931360.dkr.ecr.us-east-1.amazonaws.com/sagemaker-debugger-rules:latest',\n", " 'RuleParameters': {'rule_to_invoke': 'ProfilerReport'}}],\n", " 'ProfilerConfig': {'S3OutputPath': 's3://sagemaker-us-east-1-051065130547/sagemaker-webinar-pipeline-base/training_jobs'}}}]}" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import json\n", "\n", "definition = json.loads(pipeline.definition())\n", "definition" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.3 파이프라인 정의를 제출하고 실행하기 \n", "\n", "파이프라인 정의를 파이프라인 서비스에 제출합니다. 함께 전달되는 역할(role)을 이용하여 AWS에서 파이프라인을 생성하고 작업의 각 단계를 실행할 것입니다. " ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "pipeline.upsert(role_arn=role)\n", "execution = pipeline.start()" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'PipelineArn': 'arn:aws:sagemaker:us-east-1:051065130547:pipeline/sagemaker-webinar-pipeline-base',\n", " 'PipelineExecutionArn': 'arn:aws:sagemaker:us-east-1:051065130547:pipeline/sagemaker-webinar-pipeline-base/execution/4o0prgdpt7zv',\n", " 'PipelineExecutionDisplayName': 'execution-1647853670418',\n", " 'PipelineExecutionStatus': 'Executing',\n", " 'CreationTime': datetime.datetime(2022, 3, 21, 9, 7, 50, 350000, tzinfo=tzlocal()),\n", " 'LastModifiedTime': datetime.datetime(2022, 3, 21, 9, 7, 50, 350000, tzinfo=tzlocal()),\n", " 'CreatedBy': {},\n", " 'LastModifiedBy': {},\n", " 'ResponseMetadata': {'RequestId': '683cea38-b27f-4b85-9840-96a97f000cdd',\n", " 'HTTPStatusCode': 200,\n", " 'HTTPHeaders': {'x-amzn-requestid': '683cea38-b27f-4b85-9840-96a97f000cdd',\n", " 'content-type': 'application/x-amz-json-1.1',\n", " 'content-length': '425',\n", " 'date': 'Mon, 21 Mar 2022 09:07:49 GMT'},\n", " 'RetryAttempts': 0}}" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "execution.describe()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.4 파이프라인 실행 기다리기" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "execution.wait()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "실행이 완료될 때까지 기다립니다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "실행된 단계들을 리스트업합니다. 파이프라인의 단계실행 서비스에 의해 시작되거나 완료된 단계를 보여줍니다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.5 파이프라인 실행 단계 기록 보기" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[{'StepName': 'Fraud-Basic-Train',\n", " 'StartTime': datetime.datetime(2022, 3, 21, 9, 7, 51, 799000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2022, 3, 21, 9, 11, 7, 277000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'AttemptCount': 0,\n", " 'Metadata': {'TrainingJob': {'Arn': 'arn:aws:sagemaker:us-east-1:051065130547:training-job/pipelines-4o0prgdpt7zv-fraud-basic-train-8qhpipk1of'}}}]" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "execution.list_steps()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 6. 세이지 메이커 스튜디오에서 확인하기\n", "- 아래의 그림 처럼 SageMaker Studio에 로긴후에 따라하시면, SageMaker Studio 에서도 실행 내역을 확인할 수 있습니다.\n", " - SageMaker Studio 개발자 가이드 --> [SageMaker Studio](https://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/studio.html)\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![train_step_sm.studio.png](img/train_step_sm.studio.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 7. 모델 아티펙트 경로 추출\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7.1. 훈련 모델 결과의 경로 지정\n", "- 다음 노트북에서 사용할 훈련 모델 아티펙트의 S3 경로를 저장 합니다." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " train_model_artifact: \n", " s3://sagemaker-us-east-1-051065130547/sagemaker-webinar-pipeline-base/training_jobs/pipelines-4o0prgdpt7zv-Fraud-Basic-Train-8qHPipk1OF/output/model.tar.gz\n" ] } ], "source": [ "from src.p_utils import get_train_artifact\n", "\n", "import boto3\n", "client = boto3.client(\"sagemaker\")\n", " \n", "train_model_artifact = get_train_artifact(execution, client,job_type='TrainingJob', kind=0)\n", "print(\" train_model_artifact: \\n\", train_model_artifact)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7.2 훈련시 사용한 도커 이미지를 저장\n", "- 추론시에 사용할 도커 이미지를 추론시에도 동일하게 사용하기 위해서 저장 합니다.\n", " - 일반적으로 훈련, 추론의 도커 이미지를 분리해서 사용합니다. 하지만 간단한 알고리즘의 경우는 훈련, 추론의 도커 이미지를 같이 사용하기도 합니다." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "image_uri: \n", " 683313688378.dkr.ecr.us-east-1.amazonaws.com/sagemaker-xgboost:1.3-1\n" ] } ], "source": [ "image_uri = xgb_train.image_uri\n", "print(\"image_uri: \\n\", image_uri)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "훈련 모델 아티펙트와, 훈련시 사용한 다커 이미지의 경로를 저장 합니다." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Stored 'train_model_artifact' (str)\n", "Stored 'image_uri' (str)\n" ] } ], "source": [ "%store train_model_artifact\n", "%store image_uri" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "instance_type": "ml.t3.medium", "kernelspec": { "display_name": "conda_python3", "language": "python", "name": "conda_python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 4 }