<jupyter_start><jupyter_text>Amazon SageMaker XGBoost Bring Your Own Model_**Hosting a Pre-Trained scikit-learn Model in Amazon SageMaker XGBoost Algorithm Container**_------ Contents1. [Background](Background)1. [Setup](Setup)1. [Optionally, train a scikit learn XGBoost model](Optionally,-train-a-scikit-learn-XGBoost-model)1. [Upload the pre-trained model to S3](Upload-the-pre-trained-model-to-S3)1. [Set up hosting for the model](Set-up-hosting-for-the-model)1. [Validate the model for use](Validate-the-model-for-use)--- BackgroundAmazon SageMaker includes functionality to support a hosted notebook environment, distributed, serverless training, and real-time hosting. We think it works best when all three of these services are used together, but they can also be used independently.  Some use cases may only require hosting.  Maybe the model was trained prior to Amazon SageMaker existing, in a different service.This notebook shows how to use a pre-existing scikit-learn trained XGBoost model with the Amazon SageMaker XGBoost Algorithm container to quickly create a hosted endpoint for that model. Please note that scikit-learn XGBoost model is compatible with SageMaker XGBoost container, whereas other gradient boosted tree models (such as one trained in SparkML) are not.--- SetupLet's start by specifying:* AWS region.* The IAM role arn used to give learning and hosting access to your data. See the documentation for how to specify these.* The S3 bucket that you want to use for training and model data.<jupyter_code>%%time

import os
import boto3
import re
import json
from sagemaker import get_execution_role

region = boto3.Session().region_name

role = get_execution_role()

bucket='<s3 bucket>' # put your s3 bucket name here, and create s3 bucket
prefix = 'sagemaker/DEMO-xgboost-byo'
bucket_path = 'https://s3-{}.amazonaws.com/{}'.format(region,bucket)
# customize to your bucket where you have stored the data<jupyter_output><empty_output><jupyter_text>Optionally, train a scikit learn XGBoost modelThese steps are optional and are needed to generate the scikit-learn model that will eventually be hosted using the SageMaker Algorithm contained.  Install XGboostNote that for conda based installation, you'll need to change the Notebook kernel to the environment with conda and Python3.<jupyter_code>!conda install -y -c conda-forge xgboost<jupyter_output><empty_output><jupyter_text>Fetch the dataset<jupyter_code>%%time
import pickle, gzip, numpy, urllib.request, json

# Load the dataset
urllib.request.urlretrieve("http://deeplearning.net/data/mnist/mnist.pkl.gz", "mnist.pkl.gz")
f = gzip.open('mnist.pkl.gz', 'rb')
train_set, valid_set, test_set = pickle.load(f, encoding='latin1')
f.close()<jupyter_output><empty_output><jupyter_text>Prepare the dataset for training<jupyter_code>%%time

import struct
import io
import boto3

def get_dataset():
  import pickle
  import gzip
  with gzip.open('mnist.pkl.gz', 'rb') as f:
      u = pickle._Unpickler(f)
      u.encoding = 'latin1'
      return u.load()
train_set, valid_set, test_set = get_dataset()

train_X = train_set[0]
train_y = train_set[1]

valid_X = valid_set[0]
valid_y = valid_set[1]

test_X = test_set[0]
test_y = test_set[1]<jupyter_output><empty_output><jupyter_text>Train the XGBClassifier<jupyter_code>import xgboost as xgb
import sklearn as sk 

bt = xgb.XGBClassifier(max_depth=5,
                       learning_rate=0.2,
                       n_estimators=10,
                       objective='multi:softmax')   # Setup xgboost model
bt.fit(train_X, train_y, # Train it to our data
       eval_set=[(valid_X, valid_y)], 
       verbose=False)<jupyter_output><empty_output><jupyter_text>Save the trained model fileNote that the model file name must satisfy the regular expression pattern: `^[a-zA-Z0-9](-*[a-zA-Z0-9])*;`. The model file also need to tar-zipped.<jupyter_code>model_file_name = "DEMO-local-xgboost-model"
bt._Booster.save_model(model_file_name)
!tar czvf model.tar.gz $model_file_name<jupyter_output><empty_output><jupyter_text>Upload the pre-trained model to S3<jupyter_code>fObj = open("model.tar.gz", 'rb')
key= os.path.join(prefix, model_file_name, 'model.tar.gz')
boto3.Session().resource('s3').Bucket(bucket).Object(key).upload_fileobj(fObj)<jupyter_output><empty_output><jupyter_text>Set up hosting for the model Import model into hostingThis involves creating a SageMaker model from the model file previously uploaded to S3.<jupyter_code>containers = {'us-west-2': '433757028032.dkr.ecr.us-west-2.amazonaws.com/xgboost:latest',
              'us-east-1': '811284229777.dkr.ecr.us-east-1.amazonaws.com/xgboost:latest',
              'us-east-2': '825641698319.dkr.ecr.us-east-2.amazonaws.com/xgboost:latest',
              'eu-west-1': '685385470294.dkr.ecr.eu-west-1.amazonaws.com/xgboost:latest',
              'ap-northeast-1': '501404015308.dkr.ecr.ap-northeast-1.amazonaws.com/xgboost:latest',
              'ap-northeast-2': '306986355934.dkr.ecr.ap-northeast-2.amazonaws.com/xgboost:latest'}
container = containers[boto3.Session().region_name]
%%time
from time import gmtime, strftime

model_name = model_file_name + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
model_url = 'https://s3-{}.amazonaws.com/{}/{}'.format(region,bucket,key)
sm_client = boto3.client('sagemaker')

print (model_url)

primary_container = {
    'Image': container,
    'ModelDataUrl': model_url,
}

create_model_response2 = sm_client.create_model(
    ModelName = model_name,
    ExecutionRoleArn = role,
    PrimaryContainer = primary_container)

print(create_model_response2['ModelArn'])<jupyter_output><empty_output><jupyter_text>Create endpoint configurationSageMaker supports configuring REST endpoints in hosting with multiple models, e.g. for A/B testing purposes. In order to support this, you can 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.<jupyter_code>from time import gmtime, strftime

endpoint_config_name = 'DEMO-XGBoostEndpointConfig-' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
print(endpoint_config_name)
create_endpoint_config_response = sm_client.create_endpoint_config(
    EndpointConfigName = endpoint_config_name,
    ProductionVariants=[{
        'InstanceType':'ml.m4.xlarge',
        'InitialInstanceCount':1,
        'InitialVariantWeight':1,
        'ModelName':model_name,
        'VariantName':'AllTraffic'}])

print("Endpoint Config Arn: " + create_endpoint_config_response['EndpointConfigArn'])<jupyter_output><empty_output><jupyter_text>Create endpointLastly, you create 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.<jupyter_code>%%time
import time

endpoint_name = 'DEMO-XGBoostEndpoint-' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
print(endpoint_name)
create_endpoint_response = sm_client.create_endpoint(
    EndpointName=endpoint_name,
    EndpointConfigName=endpoint_config_name)
print(create_endpoint_response['EndpointArn'])

resp = sm_client.describe_endpoint(EndpointName=endpoint_name)
status = resp['EndpointStatus']
print("Status: " + status)

while status=='Creating':
    time.sleep(60)
    resp = sm_client.describe_endpoint(EndpointName=endpoint_name)
    status = resp['EndpointStatus']
    print("Status: " + status)

print("Arn: " + resp['EndpointArn'])
print("Status: " + status)<jupyter_output><empty_output><jupyter_text>Validate the model for useNow you can obtain the endpoint from the client library using the result from previous operations and generate classifications from the model using that endpoint.<jupyter_code>runtime_client = boto3.client('runtime.sagemaker')<jupyter_output><empty_output><jupyter_text>Lets generate the prediction for a single datapoint. We'll pick one from the test data generated earlier.<jupyter_code>import numpy as np
point_X = test_X[0]
point_X = np.expand_dims(point_X, axis=0)
point_y = test_y[0]
np.savetxt("test_point.csv", point_X, delimiter=",")
%%time
import json


file_name = 'test_point.csv' #customize to your test file, will be 'mnist.single.test' if use data above

with open(file_name, 'r') as f:
    payload = f.read().strip()

response = runtime_client.invoke_endpoint(EndpointName=endpoint_name, 
                                   ContentType='text/csv', 
                                   Body=payload)
result = response['Body'].read().decode('ascii')
print('Predicted Class Probabilities: {}.'.format(result))<jupyter_output><empty_output><jupyter_text>Post process the outputSince the result is a string, let's process it to determine the the output class label.<jupyter_code>floatArr = np.array(json.loads(result))
predictedLabel = np.argmax(floatArr)
print('Predicted Class Label: {}.'.format(predictedLabel))
print('Actual Class Label: {}.'.format(point_y))<jupyter_output><empty_output><jupyter_text>(Optional) Delete the EndpointIf you're ready to be done with this notebook, please run the delete_endpoint line in the cell below.  This will remove the hosted endpoint you created and avoid any charges from a stray instance being left on.<jupyter_code>sm_client.delete_endpoint(EndpointName=endpoint_name)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10539137803198814, 'fraction_numerical': 0.014723016629594323, 'mean_word_length': 5.232343234323432, 'pattern_counts': {'":': 0, '<': 58, '<?xml version=': 0, '>': 58, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '146417', 'license': 'Apache-2.0', 'n_tokens_mistral': 3062, 'n_tokens_neox': 2952, 'n_words': 800, 'path': 'advanced_functionality/xgboost_bring_your_own_model/xgboost_bring_your_own_model.ipynb', 'repo_name': 'csanchiz/amazon-sagemaker-examples', 'size': '9441'}