Regression with Amazon SageMaker XGBoost algorithm¶

Single machine training for regression with Amazon SageMaker XGBoost algorithm



Contents¶

  1. Introduction
  2. Setup
  3. Fetching the dataset
  4. Data Ingestion
  5. Training the XGBoost model
  6. Plotting evaluation metrics
  7. Set up hosting for the model
  8. Import model into hosting
  9. Create endpoint configuration
  10. Create endpoint
  11. Validate the model for use

Introduction¶

This notebook demonstrates the use of Amazon SageMaker’s implementation of the XGBoost algorithm to train and host a regression model. We use the Abalone data originally from the UCI data repository [1]. More details about the original dataset can be found here. In the libsvm converted version, the nominal feature (Male/Female/Infant) has been converted into a real valued feature. Age of abalone is to be predicted from eight physical measurements. Dataset is already processed and stored on S3. Scripts used for processing the data can be found in the Appendix. These include downloading the data, splitting into train, validation and test, and uploading to S3 bucket.

[1] Dua, D. and Graff, C. (2019). UCI Machine Learning Repository [http://archive.ics.uci.edu/ml]. Irvine, CA: University of California, School of Information and Computer Science.

Setup¶

This notebook was tested in Amazon SageMaker Studio on a ml.t3.medium instance with Python 3 (Data Science) kernel.

Let's start by specifying:

  1. The S3 buckets and prefixes that you want to use for saving the model and where training data is located. This should be within the same region as the Notebook Instance, training, and hosting.
  2. The IAM role arn used to give training and hosting access to your data. See the documentation for how to create these. Note, if more than one role is required for notebook instances, training, and/or hosting, please replace the boto regexp with a the appropriate full IAM role arn string(s).
In [ ]:
%%time

import os
import boto3
import re
import sagemaker

role = sagemaker.get_execution_role()
region = boto3.Session().region_name

# S3 bucket where the training data is located.
# Feel free to specify a different bucket and prefix
#data_bucket = f"jumpstart-cache-prod-{region}"
data_bucket = "dsoaws"
#data_prefix = "1p-notebooks-datasets/abalone/libsvm"

# 7.8 hours for all years with ml.m5.24xlarge
# TODO:  Use csv or parquet?
#data_prefix = "nyc-taxi-orig-cleaned-csv-without-header-all-years/all-years.csv" # SUCCESS
#data_prefix = "nyc-taxi-orig-cleaned-parquet-all-years-multiple-files/"          # FAILURE
data_prefix = "nyc-taxi-orig-cleaned-parquet-all-years/"                          # FAILURE?
data_bucket_path = f"s3://{data_bucket}"

##########################################################
# TODO:  Create /train (80%) and /validation (20%) splits
##########################################################

##########################################################
# TODO:  Add experiment_config to script mode
##########################################################

# S3 bucket for saving code and model artifacts.
# Feel free to specify a different bucket and prefix
output_bucket = sagemaker.Session().default_bucket()
output_prefix = "sagemaker/DEMO-xgboost-nyc-taxi"
output_bucket_path = f"s3://{output_bucket}"
In [ ]:
!aws s3 ls $data_bucket_path/$data_prefix

Training the XGBoost model¶

After setting training parameters, we kick off training, and poll for status until training is completed, which in this example, takes between 5 and 6 minutes.

In [ ]:
from sagemaker.amazon.amazon_estimator import get_image_uri
container = get_image_uri(region, "xgboost", "1.5-1")
In [ ]:
import boto3
from time import gmtime, strftime

job_name = f"jumpstart-example-xgboost-nyc-taxi-{strftime('%Y-%m-%d-%H-%M-%S', gmtime())}"

print("Training job", job_name)
In [ ]:
from IPython.core.display import display, HTML

display(
    HTML(
        '<b>Review <a target="blank" href="https://console.aws.amazon.com/sagemaker/home?region={}#/jobs/{}">Training Job</a> After About 5 Minutes</b>'.format(
            region, job_name
        )
    )
)
In [ ]:
%%time

# Ensure that the training and validation data folders generated above are reflected in the "InputDataConfig" parameter below.

# sagemaker training time for all data:  7.78 hours * 6 ml.m5.24xlarge instances * $5.53 = $258.14 (ec2 + sagemaker surcharge)
# other training time for all data:  5.50 hours * 6 ml.i3.8xlarge instances * $7.20 = $237.60 (ec2 + other surcharge)

create_training_params = {
    "AlgorithmSpecification": {"TrainingImage": container, "TrainingInputMode": "File"},
    "RoleArn": role,
    "OutputDataConfig": {"S3OutputPath": f"{output_bucket_path}/{output_prefix}/jumpstart-example-xgboost-nyc-taxi"},
    "ResourceConfig": {"InstanceCount": 20, "InstanceType": "ml.m5.24xlarge", "VolumeSizeInGB": 500},
    "TrainingJobName": job_name,
    "HyperParameters": {
        "max_depth": "5",
        "eta": "0.2",
        "gamma": "4",
        "min_child_weight": "6",
        "subsample": "0.7",
#        "silent": "0",
#        "objective": "reg:linear",
        "objective": "reg:squarederror",
        "num_round": "50",
    },
#    "StoppingCondition": {"MaxRuntimeInSeconds": 3600},
    "StoppingCondition": {"MaxRuntimeInSeconds": 54000},
    "InputDataConfig": [
        {
            "ChannelName": "train",
            "DataSource": {
                "S3DataSource": {
                    "S3DataType": "S3Prefix",
# TODO:  Using the /train split
#                    "S3Uri": f"{data_bucket_path}/{data_prefix}/train",
                    "S3Uri": f"{data_bucket_path}/{data_prefix}",
                    "S3DataDistributionType": "FullyReplicated",
                }
            },
# TODO:  Use csv or parquet?
#            "ContentType": "csv",
            "ContentType": "application/x-parquet",
            "CompressionType": "None",
        },
# TODO:  Using the /validation split
        # {
        #     "ChannelName": "validation",
        #     "DataSource": {
        #         "S3DataSource": {
        #             "S3DataType": "S3Prefix",
        #             "S3Uri": f"{data_bucket_path}/{data_prefix}/validation",
        #             "S3DataDistributionType": "FullyReplicated",
        #         }
        #     },
        #     "ContentType": "csv",
        #     "CompressionType": "None",
        # },
    ],
}

client = boto3.client("sagemaker", region_name=region)
client.create_training_job(**create_training_params)

import time

status = client.describe_training_job(TrainingJobName=job_name)["TrainingJobStatus"]
print(status)
while status != "Completed" and status != "Failed":
    time.sleep(60)
    status = client.describe_training_job(TrainingJobName=job_name)["TrainingJobStatus"]
    print(status)
In [ ]:
from IPython.core.display import display, HTML

display(
    HTML(
        '<b>Review <a target="blank" href="https://console.aws.amazon.com/sagemaker/home?region={}#/jobs/{}">Training Job</a> After About 5 Minutes</b>'.format(
            region, job_name
        )
    )
)

Note that the "validation" channel has been initialized too. The SageMaker XGBoost algorithm actually calculates RMSE and writes it to the CloudWatch logs on the data passed to the "validation" channel.

Set up hosting for the model¶

In order to set up hosting, we have to import the model from training to hosting.

Import model into hosting¶

Register the model with hosting. This allows the flexibility of importing models trained elsewhere.

In [ ]:
import boto3
from time import gmtime, strftime

model_name = f"{job_name}-model"
print(model_name)

info = client.describe_training_job(TrainingJobName=job_name)
model_data = info["ModelArtifacts"]["S3ModelArtifacts"]
print(model_data)
In [ ]:
# %%time
# primary_container = {"Image": container, "ModelDataUrl": model_data}

# create_model_response = client.create_model(
#     ModelName=model_name, ExecutionRoleArn=role, PrimaryContainer=primary_container
# )

# print(create_model_response["ModelArn"])

Create endpoint configuration¶

SageMaker supports configuring REST endpoints in hosting with multiple models, e.g. for A/B testing purposes. In order to support this, customers create an endpoint configuration, that describes the distribution of traffic across the models, whether split, shadowed, or sampled in some way. In addition, the endpoint configuration describes the instance type required for model deployment.

In [ ]:
# from time import gmtime, strftime

# endpoint_config_name = f"jumpstart-example-xgboostconfig-{strftime('%Y-%m-%d-%H-%M-%S', gmtime())}"

# print(endpoint_config_name)
# create_endpoint_config_response = client.create_endpoint_config(
#     EndpointConfigName=endpoint_config_name,
#     ProductionVariants=[
#         {
#             "InstanceType": "ml.m5.xlarge",
#             "InitialVariantWeight": 1,
#             "InitialInstanceCount": 1,
#             "ModelName": model_name,
#             "VariantName": "AllTraffic",
#         }
#     ],
# )

# print(f"Endpoint Config Arn: {create_endpoint_config_response['EndpointConfigArn']}")

Create endpoint¶

Lastly, the customer creates the endpoint that serves up the model, through specifying the name and configuration defined above. The end result is an endpoint that can be validated and incorporated into production applications. This takes 9-11 minutes to complete.

In [ ]:
# %%time
# import time

# endpoint_name = f"jumpstart-example-xgboost-regression-{strftime('%Y-%m-%d-%H-%M-%S', gmtime())}"
# print(endpoint_name)
# create_endpoint_response = client.create_endpoint(
#     EndpointName=endpoint_name, EndpointConfigName=endpoint_config_name
# )
# print(create_endpoint_response["EndpointArn"])

# resp = client.describe_endpoint(EndpointName=endpoint_name)
# status = resp["EndpointStatus"]
# while status == "Creating":
#     print(f"Status: {status}")
#     time.sleep(60)
#     resp = client.describe_endpoint(EndpointName=endpoint_name)
#     status = resp["EndpointStatus"]

# print(f"Arn: {resp['EndpointArn']}")
# print(f"Status: {status}")

Validate the model for use¶

Finally, the customer can now validate the model for use. They can obtain the endpoint from the client library using the result from previous operations, and generate classifications from the trained model using that endpoint.

In [ ]:
# runtime_client = boto3.client("runtime.sagemaker", region_name=region)

Download test data

In [ ]:
# FILE_TEST = "abalone.test"
# s3 = boto3.client("s3")
# s3.download_file(data_bucket, f"{data_prefix}/test/{FILE_TEST}", FILE_TEST)

Start with a single prediction.

In [ ]:
# !head -1 abalone.test > abalone.single.test
In [ ]:
# %%time
# import json
# from itertools import islice
# import math
# import struct

# file_name = "abalone.single.test"  # customize to your test file
# with open(file_name, "r") as f:
#     payload = f.read().strip()
# response = runtime_client.invoke_endpoint(
#     EndpointName=endpoint_name, ContentType="text/x-libsvm", Body=payload
# )
# result = response["Body"].read()
# result = result.decode("utf-8")
# result = result.split(",")
# result = [math.ceil(float(i)) for i in result]
# label = payload.strip(" ").split()[0]
# print(f"Label: {label}\nPrediction: {result[0]}")

OK, a single prediction works. Let's do a whole batch to see how good is the predictions accuracy.

In [ ]:
# import sys
# import math


# def do_predict(data, endpoint_name, content_type):
#     payload = "\n".join(data)
#     response = runtime_client.invoke_endpoint(
#         EndpointName=endpoint_name, ContentType=content_type, Body=payload
#     )
#     result = response["Body"].read()
#     result = result.decode("utf-8")
#     result = result.split(",")
#     preds = [float((num)) for num in result]
#     preds = [math.ceil(num) for num in preds]
#     return preds


# def batch_predict(data, batch_size, endpoint_name, content_type):
#     items = len(data)
#     arrs = []

#     for offset in range(0, items, batch_size):
#         if offset + batch_size < items:
#             results = do_predict(data[offset : (offset + batch_size)], endpoint_name, content_type)
#             arrs.extend(results)
#         else:
#             arrs.extend(do_predict(data[offset:items], endpoint_name, content_type))
#         sys.stdout.write(".")
#     return arrs

The following helps us calculate the Median Absolute Percent Error (MdAPE) on the batch dataset.

In [ ]:
# %%time
# import json
# import numpy as np

# with open(FILE_TEST, "r") as f:
#     payload = f.read().strip()

# labels = [int(line.split(" ")[0]) for line in payload.split("\n")]
# test_data = [line for line in payload.split("\n")]
# preds = batch_predict(test_data, 100, endpoint_name, "text/x-libsvm")

# print(
#     "\n Median Absolute Percent Error (MdAPE) = ",
#     np.median(np.abs(np.array(labels) - np.array(preds)) / np.array(labels)),
# )
In [ ]:
 

Delete Endpoint¶

Once you are done using the endpoint, you can use the following to delete it.

In [ ]:
# client.delete_endpoint(EndpointName=endpoint_name)

Appendix¶

Data split and upload¶

Following methods split the data into train/test/validation datasets and upload files to S3.

In [ ]:
# import io
# import boto3
# import random


# def data_split(
#     FILE_DATA, FILE_TRAIN, FILE_VALIDATION, FILE_TEST, PERCENT_TRAIN, PERCENT_VALIDATION, PERCENT_TEST
# ):
#     data = [l for l in open(FILE_DATA, "r")]
#     train_file = open(FILE_TRAIN, "w")
#     valid_file = open(FILE_VALIDATION, "w")
#     tests_file = open(FILE_TEST, "w")

#     num_of_data = len(data)
#     num_train = int((PERCENT_TRAIN / 100.0) * num_of_data)
#     num_valid = int((PERCENT_VALIDATION / 100.0) * num_of_data)
#     num_tests = int((PERCENT_TEST / 100.0) * num_of_data)

#     data_fractions = [num_train, num_valid, num_tests]
#     split_data = [[], [], []]

#     rand_data_ind = 0

#     for split_ind, fraction in enumerate(data_fractions):
#         for i in range(fraction):
#             rand_data_ind = random.randint(0, len(data) - 1)
#             split_data[split_ind].append(data[rand_data_ind])
#             data.pop(rand_data_ind)

#     for l in split_data[0]:
#         train_file.write(l)

#     for l in split_data[1]:
#         valid_file.write(l)

#     for l in split_data[2]:
#         tests_file.write(l)

#     train_file.close()
#     valid_file.close()
#     tests_file.close()


# def write_to_s3(fobj, bucket, key):
#     return (
#         boto3.Session(region_name=region).resource("s3").Bucket(bucket).Object(key).upload_fileobj(fobj)
#     )


# def upload_to_s3(bucket, channel, filename):
#     fobj = open(filename, "rb")
#     key = f"{prefix}/{channel}"
#     url = f"s3://{bucket}/{key}/{filename}"
#     print(f"Writing to {url}")
#     write_to_s3(fobj, bucket, key)

Data ingestion¶

Next, we read the dataset from the existing repository into memory, for preprocessing prior to training. This processing could be done in situ by Amazon Athena, Apache Spark in Amazon EMR, Amazon Redshift, etc., assuming the dataset is present in the appropriate location. Then, the next step would be to transfer the data to S3 for use in training. For small datasets, such as this one, reading into memory isn't onerous, though it would be for larger datasets.

In [ ]:
# %%time
# import urllib.request

# bucket = sagemaker.Session().default_bucket()
# prefix = "sagemaker/DEMO-xgboost-abalone-default"
# # Load the dataset
# FILE_DATA = "abalone"
# urllib.request.urlretrieve(
#     "https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/regression/abalone", FILE_DATA
# )

# # split the downloaded data into train/test/validation files
# FILE_TRAIN = "abalone.train"
# FILE_VALIDATION = "abalone.validation"
# FILE_TEST = "abalone.test"
# PERCENT_TRAIN = 70
# PERCENT_VALIDATION = 15
# PERCENT_TEST = 15
# data_split(
#     FILE_DATA, FILE_TRAIN, FILE_VALIDATION, FILE_TEST, PERCENT_TRAIN, PERCENT_VALIDATION, PERCENT_TEST
# )

# # upload the files to the S3 bucket
# upload_to_s3(bucket, "train", FILE_TRAIN)
# upload_to_s3(bucket, "validation", FILE_VALIDATION)
# upload_to_s3(bucket, "test", FILE_TEST)