Introduction

Welcome to our end-to-end example of distributed image classification algorithm in transfer learning mode. In this demo, we will use the Amazon sagemaker image classification algorithm in transfer learning mode to fine-tune a pre-trained model (trained on imagenet data) to learn to classify a new dataset. In particular, the pre-trained model will be fine-tuned using caltech-256 dataset.

To get started, we need to set up the environment with a few prerequisite steps, for permissions, configurations, and so on.

Prequisites and Preprocessing

Permissions and environment variables

Here we set up the linkage and authentication to AWS services. There are three parts to this:

  • The roles used to give learning and hosting access to your data. This will automatically be obtained from the role used to start the notebook
  • The S3 bucket that you want to use for training and model data
  • The Amazon sagemaker image classification docker image which need not be changed
In [1]:
%%time
import boto3
import re
from sagemaker import get_execution_role

role = get_execution_role()

bucket='sagemaker-galaxy' # customize to your bucket

containers = {'us-west-2': '433757028032.dkr.ecr.us-west-2.amazonaws.com/image-classification:latest',
              'us-east-1': '811284229777.dkr.ecr.us-east-1.amazonaws.com/image-classification:latest',
              'us-east-2': '825641698319.dkr.ecr.us-east-2.amazonaws.com/image-classification:latest',
              'eu-west-1': '685385470294.dkr.ecr.eu-west-1.amazonaws.com/image-classification:latest'}
training_image = containers[boto3.Session().region_name]
print(training_image)
433757028032.dkr.ecr.us-west-2.amazonaws.com/image-classification:latest
CPU times: user 272 ms, sys: 96 ms, total: 368 ms
Wall time: 582 ms

Fine-tuning the Image classification model

The caltech 256 dataset consist of images from 257 categories (the last one being a clutter category) and has 30k images with a minimum of 80 images and a maximum of about 800 images per category.

The image classification algorithm can take two types of input formats. The first is a recordio format and the other is a lst format. Files for both these formats are available at http://data.dmlc.ml/mxnet/data/caltech-256/. In this example, we will use the recordio format for training and use the training/validation split specified here.

In [2]:
import os
import urllib.request
import boto3

def download(url):
    filename = url.split("/")[-1]
    if not os.path.exists(filename):
        urllib.request.urlretrieve(url, filename)

        
def upload_to_s3(channel, file):
    s3 = boto3.resource('s3')
    data = open(file, "rb")
    key = channel + '/' + file
    s3.Bucket(bucket).put_object(Key=key, Body=data)


# # caltech-256
download('https://s3-us-west-2.amazonaws.com/learn-galaxies/galaxies-train2.rec')
download('https://s3-us-west-2.amazonaws.com/learn-galaxies/galaxies-test2.rec')
upload_to_s3('validation', 'galaxies-test2.rec')
upload_to_s3('train', 'galaxies-train2.rec')

Once we have the data available in the correct format for training, the next step is to actually train the model using the data. Before training the model, we need to setup the training parameters. The next section will explain the parameters in detail.

Training parameters

There are two kinds of parameters that need to be set for training. The first one are the parameters for the training job. These include:

  • Input specification: These are the training and validation channels that specify the path where training data is present. These are specified in the "InputDataConfig" section. The main parameters that need to be set is the "ContentType" which can be set to "application/x-recordio" or "application/x-image" based on the input data format and the S3Uri which specifies the bucket and the folder where the data is present.
  • Output specification: This is specified in the "OutputDataConfig" section. We just need to specify the path where the output can be stored after training
  • Resource config: This section specifies the type of instance on which to run the training and the number of hosts used for training. If "InstanceCount" is more than 1, then training can be run in a distributed manner.

Apart from the above set of parameters, there are hyperparameters that are specific to the algorithm. These are:

  • num_layers: The number of layers (depth) for the network. We use 18 in this samples but other values such as 50, 152 can be used.
  • num_training_samples: This is the total number of training samples. It is set to 15420 for caltech dataset with the current split
  • num_classes: This is the number of output classes for the new dataset. Imagenet was trained with 1000 output classes but the number of output classes can be changed for fine-tuning. For caltech, we use 257 because it has 256 object categories + 1 clutter class
  • epochs: Number of training epochs
  • learning_rate: Learning rate for training
  • mini_batch_size: The number of training samples used for each mini batch. In distributed training, the number of training samples used per batch will be N * mini_batch_size where N is the number of hosts on which training is run

After setting training parameters, we kick off training, and poll for status until training is completed, which in this example, takes between 10 to 12 minutes per epoch on a p2.xlarge machine. The network typically converges after 10 epochs.

In [120]:
# The algorithm supports multiple network depth (number of layers). They are 18, 34, 50, 101, 152 and 200
# For this training, we will use 18 layers
num_layers = 101
# we need to specify the input image shape for the training data
image_shape = "3,224,224"
# we also need to specify the number of training samples in the training set
# for caltech it is 15420
num_training_samples = 19*4
# specify the number of output classes
num_classes = 5
# batch size for training
mini_batch_size =  21
# number of epochs
epochs = 5
# learning rate
learning_rate = 0.0018
top_k=2
# Since we are using transfer learning, we set use_pretrained_model to 1 so that weights can be 
# initialized with pre-trained weights
use_pretrained_model = 1

Training

Run the training using Amazon sagemaker CreateTrainingJob API

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


s3 = boto3.client('s3')
# create unique job name 
job_name_prefix = 'sagemaker-imageclassification-notebook'
timestamp = time.strftime('-%Y-%m-%d-%H-%M-%S', time.gmtime())
job_name = job_name_prefix + timestamp
training_params = \
{
    # specify the training docker image
    "AlgorithmSpecification": {
        "TrainingImage": training_image,
        "TrainingInputMode": "File"
    },
    "RoleArn": role,
    "OutputDataConfig": {
        "S3OutputPath": 's3://{}/{}/output'.format(bucket, job_name_prefix)
    },
    "ResourceConfig": {
        "InstanceCount": 1,
        "InstanceType": "ml.p2.xlarge",
        "VolumeSizeInGB": 50
    },
    "TrainingJobName": job_name,
    "HyperParameters": {
        "image_shape": image_shape,
        "num_layers": str(num_layers),
        "num_training_samples": str(num_training_samples),
        "num_classes": str(num_classes),
        "mini_batch_size": str(mini_batch_size),
        "epochs": str(epochs),
        "learning_rate": str(learning_rate),
        "use_pretrained_model": str(use_pretrained_model)
    },
    "StoppingCondition": {
        "MaxRuntimeInSeconds": 360000
    },
#Training data should be inside a subdirectory called "train"
#Validation data should be inside a subdirectory called "validation"
#The algorithm currently only supports fullyreplicated model (where data is copied onto each machine)
    "InputDataConfig": [
        {
            "ChannelName": "train",
            "DataSource": {
                "S3DataSource": {
                    "S3DataType": "S3Prefix",
                    "S3Uri": 's3://{}/train/'.format(bucket),
                    "S3DataDistributionType": "FullyReplicated"
                }
            },
            "ContentType": "application/x-recordio",
            "CompressionType": "None"
        },
        {
            "ChannelName": "validation",
            "DataSource": {
                "S3DataSource": {
                    "S3DataType": "S3Prefix",
                    "S3Uri": 's3://{}/validation/'.format(bucket),
                    "S3DataDistributionType": "FullyReplicated"
                }
            },
            "ContentType": "application/x-recordio",
            "CompressionType": "None"
        }
    ]
}
print('Training job name: {}'.format(job_name))
print('\nInput Data Location: {}'.format(training_params['InputDataConfig'][0]['DataSource']['S3DataSource']))
Training job name: sagemaker-imageclassification-notebook-2018-02-15-18-37-41

Input Data Location: {'S3DataType': 'S3Prefix', 'S3Uri': 's3://sagemaker-galaxy/train/', 'S3DataDistributionType': 'FullyReplicated'}
CPU times: user 4 ms, sys: 0 ns, total: 4 ms
Wall time: 4.17 ms
In [122]:
# create the Amazon SageMaker training job
sagemaker = boto3.client(service_name='sagemaker')
sagemaker.create_training_job(**training_params)

# confirm that the training job has started
status = sagemaker.describe_training_job(TrainingJobName=job_name)['TrainingJobStatus']
print('Training job current status: {}'.format(status))

try:
    # wait for the job to finish and report the ending status
    sagemaker.get_waiter('training_job_completed_or_stopped').wait(TrainingJobName=job_name)
    training_info = sagemaker.describe_training_job(TrainingJobName=job_name)
    status = training_info['TrainingJobStatus']
    print("Training job ended with status: " + status)
except:
    print('Training failed to start')
     # if exception is raised, that means it has failed
    message = sagemaker.describe_training_job(TrainingJobName=job_name)['FailureReason']
    print('Training failed with the following error: {}'.format(message))
Training job current status: InProgress
Training job ended with status: Completed
In [123]:
training_info = sagemaker.describe_training_job(TrainingJobName=job_name)
status = training_info['TrainingJobStatus']
print("Training job ended with status: " + status)
Training job ended with status: Completed

If you see the message,

Training job ended with status: Completed

then that means training sucessfully completed and the output model was stored in the output path specified by training_params['OutputDataConfig'].

You can also view information about and the status of a training job using the AWS SageMaker console. Just click on the "Jobs" tab.

Inference


A trained model does nothing on its own. We now want to use the model to perform inference. For this example, that means predicting the topic mixture representing a given document.

This section involves several steps,

  1. Create Model - Create model for the training output
  2. Create Endpoint Configuration - Create a configuration defining an endpoint.
  3. Create Endpoint - Use the configuration to create an inference endpoint.
  4. Perform Inference - Perform inference on some input data using the endpoint.

Create Model

We now create a SageMaker Model from the training output. Using the model we can create an Endpoint Configuration.

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

sage = boto3.Session().client(service_name='sagemaker') 

model_name="galaxy-clasifier4"
print(model_name)
info = sage.describe_training_job(TrainingJobName=job_name)
model_data = info['ModelArtifacts']['S3ModelArtifacts']
print(model_data)
containers = {'us-west-2': '433757028032.dkr.ecr.us-west-2.amazonaws.com/image-classification:latest',
              'us-east-1': '811284229777.dkr.ecr.us-east-1.amazonaws.com/image-classification:latest',
              'us-east-2': '825641698319.dkr.ecr.us-east-2.amazonaws.com/image-classification:latest',
              'eu-west-1': '685385470294.dkr.ecr.eu-west-1.amazonaws.com/image-classification:latest'}
hosting_image = containers[boto3.Session().region_name]
primary_container = {
    'Image': hosting_image,
    'ModelDataUrl': model_data,
}

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

print(create_model_response['ModelArn'])
galaxy-clasifier4
s3://sagemaker-galaxy/sagemaker-imageclassification-notebook/output/sagemaker-imageclassification-notebook-2018-02-15-18-37-41/output/model.tar.gz
arn:aws:sagemaker:us-west-2:066301190734:model/galaxy-clasifier4
CPU times: user 44 ms, sys: 0 ns, total: 44 ms
Wall time: 858 ms

Create Endpoint Configuration

At launch, we will support 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, and at launch will describe the autoscaling configuration.

In [125]:
from time import gmtime, strftime

timestamp = time.strftime('-%Y-%m-%d-%H-%M-%S', time.gmtime())
endpoint_config_name = job_name_prefix + '-epc-' + timestamp
endpoint_config_response = sage.create_endpoint_config(
    EndpointConfigName = endpoint_config_name,
    ProductionVariants=[{
        'InstanceType':'ml.m4.xlarge',
        'InitialInstanceCount':1,
        'ModelName':model_name,
        'VariantName':'AllTraffic'}])

print('Endpoint configuration name: {}'.format(endpoint_config_name))
print('Endpoint configuration arn:  {}'.format(endpoint_config_response['EndpointConfigArn']))
Endpoint configuration name: sagemaker-imageclassification-notebook-epc--2018-02-15-18-50-06
Endpoint configuration arn:  arn:aws:sagemaker:us-west-2:066301190734:endpoint-config/sagemaker-imageclassification-notebook-epc--2018-02-15-18-50-06

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 [126]:
%%time
import time

timestamp = time.strftime('-%Y-%m-%d-%H-%M-%S', time.gmtime())
endpoint_name = job_name_prefix + '-ep-' + timestamp
print('Endpoint name: {}'.format(endpoint_name))

endpoint_params = {
    'EndpointName': endpoint_name,
    'EndpointConfigName': endpoint_config_name,
}
endpoint_response = sagemaker.create_endpoint(**endpoint_params)
print('EndpointArn = {}'.format(endpoint_response['EndpointArn']))
Endpoint name: sagemaker-imageclassification-notebook-ep--2018-02-15-18-50-13
EndpointArn = arn:aws:sagemaker:us-west-2:066301190734:endpoint/sagemaker-imageclassification-notebook-ep--2018-02-15-18-50-13
CPU times: user 4 ms, sys: 0 ns, total: 4 ms
Wall time: 247 ms

Finally, now the endpoint can be created. It may take sometime to create the endpoint...

In [127]:
# get the status of the endpoint
response = sagemaker.describe_endpoint(EndpointName=endpoint_name)
status = response['EndpointStatus']
print('EndpointStatus = {}'.format(status))


# wait until the status has changed
sagemaker.get_waiter('endpoint_in_service').wait(EndpointName=endpoint_name)


# print the status of the endpoint
endpoint_response = sagemaker.describe_endpoint(EndpointName=endpoint_name)
status = endpoint_response['EndpointStatus']
print('Endpoint creation ended with EndpointStatus = {}'.format(status))

if status != 'InService':
    raise Exception('Endpoint creation failed.')
EndpointStatus = Creating
Endpoint creation ended with EndpointStatus = InService

If you see the message,

Endpoint creation ended with EndpointStatus = InService

then congratulations! You now have a functioning inference endpoint. You can confirm the endpoint configuration and status by navigating to the "Endpoints" tab in the AWS SageMaker console.

We will finally create a runtime object from which we can invoke the endpoint.

Perform Inference

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 [128]:
import boto3
runtime = boto3.Session().client(service_name='runtime.sagemaker') 

Download test image

In [129]:
import cv2
In [130]:
#!wget https://s3-us-west-2.amazonaws.com/learn-galaxies/bigspiral.zip
In [131]:
#!unzip bigspiral.zip
In [132]:
#!wget https://s3-us-west-2.amazonaws.com/learn-galaxies/bigtest.zip
#!unzip bigtest.zip
#!wget https://s3-us-west-2.amazonaws.com/learn-galaxies/bigelliptical.zip
#!unzip bigelliptical.zip
#!wget https://s3-us-west-2.amazonaws.com/learn-galaxies/bigbarred.zip
#!unzip bigbarred.zip
#!wget https://s3-us-west-2.amazonaws.com/learn-galaxies/bigirregular.zip
#!unzip bigirregular.zip
In [133]:
file_name = 'bigspiral/s1.jpg'
# test image
from IPython.display import Image
Image(file_name)  
Out[133]:
In [134]:
import json
import numpy as np
with open(file_name, 'rb') as f:
    payload = f.read()
    payload = bytearray(payload)
response = runtime.invoke_endpoint(EndpointName=endpoint_name, 
                                   ContentType='application/x-image', 
                                   Body=payload)
result = response['Body'].read()
# result will be in json format and convert it to ndarray
result = json.loads(result)
# the result will output the probabilities for all classes
# find the class with maximum probability and print the class index
print(result)
index = np.argmax(result)
print(index)
object_categories = ['unk', 'barred spiral', 'elliptical', 'irregular', 'spiral'] 
print("Result: label - " + object_categories[index] + ", probability - " + str(result[index]))
[0.0026439609937369823, 0.07960028946399689, 0.024301812052726746, 0.3611459732055664, 0.5323079824447632]
4
Result: label - spiral, probability - 0.5323079824447632
In [135]:
predictions = []
for i in range(0,40):
    file_name = 'bigtest/t'+str(i)+'.jpg'
    with open(file_name, 'rb') as f:
        payload = f.read()
        payload = bytearray(payload)
    response = runtime.invoke_endpoint(EndpointName=endpoint_name, 
                                       ContentType='application/x-image', 
                                       Body=payload)
    result = response['Body'].read()
    # result will be in json format and convert it to ndarray
    result = json.loads(result)
    # the result will output the probabilities for all classes
    # find the class with maximum probability and print the class index
    print(result)
    index = np.argmax(result)
    print(index)
    object_categories = ['unk', 'barred spiral', 'elliptical', 'irregular', 'spiral'] 
    print("Result: label - " + object_categories[index] + ", probability - " + str(result[index]))
    predictions.append(index)
[0.007212264463305473, 0.09899540990591049, 0.09319622069597244, 0.06372448056936264, 0.7368716597557068]
4
Result: label - spiral, probability - 0.7368716597557068
[0.011643357574939728, 0.48240914940834045, 0.04089115560054779, 0.14230449497699738, 0.32275184988975525]
1
Result: label - barred spiral, probability - 0.48240914940834045
[0.0028429406229406595, 0.07304813712835312, 0.031106136739253998, 0.8543398380279541, 0.03866296634078026]
3
Result: label - irregular, probability - 0.8543398380279541
[0.005356378387659788, 0.8740479350090027, 0.03972466662526131, 0.054362840950489044, 0.026508264243602753]
1
Result: label - barred spiral, probability - 0.8740479350090027
[0.0020518051460385323, 0.7649766802787781, 0.024181833490729332, 0.15407368540763855, 0.05471593886613846]
1
Result: label - barred spiral, probability - 0.7649766802787781
[0.004674331285059452, 0.8232294321060181, 0.01596684567630291, 0.075883649289608, 0.08024577796459198]
1
Result: label - barred spiral, probability - 0.8232294321060181
[0.0037751367781311274, 0.5421715974807739, 0.14185813069343567, 0.2945815324783325, 0.01761358045041561]
1
Result: label - barred spiral, probability - 0.5421715974807739
[0.0058089131489396095, 0.21095505356788635, 0.07274720072746277, 0.1469571739435196, 0.5635316967964172]
4
Result: label - spiral, probability - 0.5635316967964172
[0.006837133783847094, 0.18553432822227478, 0.06403797119855881, 0.6986154913902283, 0.04497509449720383]
3
Result: label - irregular, probability - 0.6986154913902283
[0.006837133783847094, 0.18553432822227478, 0.06403797119855881, 0.6986154913902283, 0.04497509449720383]
3
Result: label - irregular, probability - 0.6986154913902283
[0.0027223348151892424, 0.07078635692596436, 0.808366596698761, 0.08682229369878769, 0.03130235895514488]
2
Result: label - elliptical, probability - 0.808366596698761
[0.008049281314015388, 0.08110368251800537, 0.7798495888710022, 0.0809701606631279, 0.05002725124359131]
2
Result: label - elliptical, probability - 0.7798495888710022
[0.009990334510803223, 0.3668842911720276, 0.21414877474308014, 0.2574363350868225, 0.15154026448726654]
1
Result: label - barred spiral, probability - 0.3668842911720276
[0.0031963607762008905, 0.07294361293315887, 0.8325294256210327, 0.058363646268844604, 0.03296700119972229]
2
Result: label - elliptical, probability - 0.8325294256210327
[0.0019124733516946435, 0.04521629214286804, 0.8085571527481079, 0.12309369444847107, 0.021220380440354347]
2
Result: label - elliptical, probability - 0.8085571527481079
[0.0003501351166050881, 0.005072535015642643, 0.60300213098526, 0.38325098156929016, 0.008324159309267998]
2
Result: label - elliptical, probability - 0.60300213098526
[0.0034880908206105232, 0.012057457119226456, 0.5715329051017761, 0.4023367166519165, 0.010584880597889423]
2
Result: label - elliptical, probability - 0.5715329051017761
[0.000641469145193696, 0.003258073003962636, 0.963557779788971, 0.02991555631160736, 0.002627131761983037]
2
Result: label - elliptical, probability - 0.963557779788971
[0.0012019227724522352, 0.020221032202243805, 0.8451790809631348, 0.12852123379707336, 0.004876760300248861]
2
Result: label - elliptical, probability - 0.8451790809631348
[0.0009690159349702299, 0.030032474547624588, 0.927095353603363, 0.0332544669508934, 0.008648672141134739]
2
Result: label - elliptical, probability - 0.927095353603363
[0.00889911875128746, 0.04977919161319733, 0.1184503361582756, 0.7547831535339355, 0.06808815896511078]
3
Result: label - irregular, probability - 0.7547831535339355
[0.0036571237724274397, 0.06591496616601944, 0.15253335237503052, 0.748692512512207, 0.029201997444033623]
3
Result: label - irregular, probability - 0.748692512512207
[0.00914640910923481, 0.2784613072872162, 0.3231434226036072, 0.20109771192073822, 0.18815119564533234]
2
Result: label - elliptical, probability - 0.3231434226036072
[0.0008389810682274401, 0.021454215049743652, 0.011052793823182583, 0.9607841372489929, 0.0058698710054159164]
3
Result: label - irregular, probability - 0.9607841372489929
[0.003128883894532919, 0.10907914489507675, 0.6533143520355225, 0.2022760957479477, 0.03220150247216225]
2
Result: label - elliptical, probability - 0.6533143520355225
[0.004484685603529215, 0.10348328202962875, 0.09064402431249619, 0.7361637949943542, 0.06522416323423386]
3
Result: label - irregular, probability - 0.7361637949943542
[0.015860000625252724, 0.048588886857032776, 0.6179089546203613, 0.24361735582351685, 0.07402484863996506]
2
Result: label - elliptical, probability - 0.6179089546203613
[0.00913572870194912, 0.0995045080780983, 0.05071638524532318, 0.7858873009681702, 0.05475613474845886]
3
Result: label - irregular, probability - 0.7858873009681702
[0.013766653835773468, 0.10922116041183472, 0.5176740288734436, 0.2441270351409912, 0.11521114408969879]
2
Result: label - elliptical, probability - 0.5176740288734436
[0.003460512263700366, 0.06594543904066086, 0.013662571087479591, 0.8999217748641968, 0.01700969785451889]
3
Result: label - irregular, probability - 0.8999217748641968
[0.008748449385166168, 0.1987289935350418, 0.3603745996952057, 0.36109066009521484, 0.0710572823882103]
3
Result: label - irregular, probability - 0.36109066009521484
[0.022650975733995438, 0.23546674847602844, 0.10082581639289856, 0.4158460199832916, 0.22521047294139862]
3
Result: label - irregular, probability - 0.4158460199832916
[0.01481001079082489, 0.27682414650917053, 0.21901315450668335, 0.2294188141822815, 0.25993379950523376]
1
Result: label - barred spiral, probability - 0.27682414650917053
[0.006942750886082649, 0.2938857078552246, 0.3168080151081085, 0.2918265461921692, 0.0905369371175766]
2
Result: label - elliptical, probability - 0.3168080151081085
[0.003632553853094578, 0.29809820652008057, 0.032937292009592056, 0.17404556274414062, 0.49128633737564087]
4
Result: label - spiral, probability - 0.49128633737564087
[0.001643260009586811, 0.09164001047611237, 0.258711040019989, 0.052482958883047104, 0.5955227017402649]
4
Result: label - spiral, probability - 0.5955227017402649
[0.012405657209455967, 0.3870147466659546, 0.08078796416521072, 0.30885452032089233, 0.21093714237213135]
1
Result: label - barred spiral, probability - 0.3870147466659546
[0.008523747324943542, 0.3140750527381897, 0.07344751060009003, 0.09664908051490784, 0.5073046684265137]
4
Result: label - spiral, probability - 0.5073046684265137
[0.0116305872797966, 0.5000225901603699, 0.12801910936832428, 0.14380693435668945, 0.21652084589004517]
1
Result: label - barred spiral, probability - 0.5000225901603699
[0.0021640220656991005, 0.01579316146671772, 0.01601489447057247, 0.07445301115512848, 0.8915749192237854]
4
Result: label - spiral, probability - 0.8915749192237854
In [136]:
mydict = {'spiral': {'spiral':0.0, 'barred spiral':0.0, 'elliptical':0.0, 'irregular':0.0},
          'barred spiral': {'spiral':0.0, 'barred spiral':0.0, 'elliptical':0.0, 'irregular':0.0},
          'elliptical': {'spiral':0.0, 'barred spiral':0.0, 'elliptical':0.0, 'irregular':0.0},
          'irregular': {'spiral':0.0, 'barred spiral':0.0, 'elliptical':0.0, 'irregular':0.0}}
In [137]:
keys = []
for i in range(4):
    for j in range(10):
        keys.append(i+1)
In [138]:
keytab = {1: 'barred spiral', 2: 'elliptical', 3:'irregular', 4:'spiral'}
i = 0
for key in keys:
    mydict[keytab[key]][keytab[predictions[i]]]+= 1
    i = i+1
In [139]:
import pandas as pd
In [140]:
df = pd.DataFrame.from_dict(mydict)
In [141]:
df.transpose()
Out[141]:
barred spiral elliptical irregular spiral
barred spiral 5.0 0.0 3.0 2.0
elliptical 1.0 9.0 0.0 0.0
irregular 0.0 4.0 6.0 0.0
spiral 3.0 1.0 2.0 4.0
In [142]:
train_predictions = []
for i in range(1,20):
    file_name = 'bigbarred/bs'+str(i)+'.jpg'
    with open(file_name, 'rb') as f:
        payload = f.read()
        payload = bytearray(payload)
    response = runtime.invoke_endpoint(EndpointName=endpoint_name, 
                                       ContentType='application/x-image', 
                                       Body=payload)
    result = response['Body'].read()
    # result will be in json format and convert it to ndarray
    result = json.loads(result)
    # the result will output the probabilities for all classes
    # find the class with maximum probability and print the class index
    print(result)
    index = np.argmax(result)
    print(index)
    object_categories = ['unk', 'barred spiral', 'elliptical', 'irregular', 'spiral'] 
    print("Result: label - " + object_categories[index] + ", probability - " + str(result[index]))
    train_predictions.append(index)
print("now elliptical")
for i in range(1,20):
    file_name = 'bigelliptical/e'+str(i)+'.jpg'
    with open(file_name, 'rb') as f:
        payload = f.read()
        payload = bytearray(payload)
    response = runtime.invoke_endpoint(EndpointName=endpoint_name, 
                                       ContentType='application/x-image', 
                                       Body=payload)
    result = response['Body'].read()
    # result will be in json format and convert it to ndarray
    result = json.loads(result)
    # the result will output the probabilities for all classes
    # find the class with maximum probability and print the class index
    print(result)
    index = np.argmax(result)
    print(index)
    object_categories = ['unk', 'barred spiral', 'elliptical', 'irregular', 'spiral'] 
    print("Result: label - " + object_categories[index] + ", probability - " + str(result[index]))
    train_predictions.append(index)
    
print("now irregular")
for i in range(1,20):
    file_name = 'bigirregular/i'+str(i)+'.jpg'
    with open(file_name, 'rb') as f:
        payload = f.read()
        payload = bytearray(payload)
    response = runtime.invoke_endpoint(EndpointName=endpoint_name, 
                                       ContentType='application/x-image', 
                                       Body=payload)
    result = response['Body'].read()
    # result will be in json format and convert it to ndarray
    result = json.loads(result)
    # the result will output the probabilities for all classes
    # find the class with maximum probability and print the class index
    print(result)
    index = np.argmax(result)
    print(index)
    object_categories = ['unk', 'barred spiral', 'elliptical', 'irregular', 'spiral'] 
    print("Result: label - " + object_categories[index] + ", probability - " + str(result[index]))
    train_predictions.append(index)
print("now spiral")
for i in range(1,20):
    file_name = 'bigspiral/s'+str(i)+'.jpg'
    with open(file_name, 'rb') as f:
        payload = f.read()
        payload = bytearray(payload)
    response = runtime.invoke_endpoint(EndpointName=endpoint_name, 
                                       ContentType='application/x-image', 
                                       Body=payload)
    result = response['Body'].read()
    # result will be in json format and convert it to ndarray
    result = json.loads(result)
    # the result will output the probabilities for all classes
    # find the class with maximum probability and print the class index
    print(result)
    index = np.argmax(result)
    print(index)
    object_categories = ['unk', 'barred spiral', 'elliptical', 'irregular', 'spiral'] 
    print("Result: label - " + object_categories[index] + ", probability - " + str(result[index]))
    train_predictions.append(index)
[0.0010279712732881308, 0.907320499420166, 0.022354718297719955, 0.04725029319524765, 0.022046582773327827]
1
Result: label - barred spiral, probability - 0.907320499420166
[0.002105571562424302, 0.8870357275009155, 0.04203949496150017, 0.046070970594882965, 0.02274825982749462]
1
Result: label - barred spiral, probability - 0.8870357275009155
[0.01685378886759281, 0.5487107634544373, 0.1553972214460373, 0.15754330158233643, 0.12149497121572495]
1
Result: label - barred spiral, probability - 0.5487107634544373
[0.002878892933949828, 0.8501783013343811, 0.057146839797496796, 0.03949885815382004, 0.05029706284403801]
1
Result: label - barred spiral, probability - 0.8501783013343811
[0.007667208556085825, 0.7676709890365601, 0.04553759843111038, 0.14555801451206207, 0.033566273748874664]
1
Result: label - barred spiral, probability - 0.7676709890365601
[0.0059331064112484455, 0.8556891083717346, 0.05648469552397728, 0.03999477997422218, 0.041898392140865326]
1
Result: label - barred spiral, probability - 0.8556891083717346
[0.006915590260177851, 0.5975708365440369, 0.2697668969631195, 0.08601514250040054, 0.03973156958818436]
1
Result: label - barred spiral, probability - 0.5975708365440369
[0.0030283681116998196, 0.26950350403785706, 0.04988877475261688, 0.6340970993041992, 0.0434822216629982]
3
Result: label - irregular, probability - 0.6340970993041992
[0.03330779820680618, 0.674288272857666, 0.06497019529342651, 0.1042514443397522, 0.1231822669506073]
1
Result: label - barred spiral, probability - 0.674288272857666
[0.002611217787489295, 0.8110836148262024, 0.09603285044431686, 0.04091974347829819, 0.04935260862112045]
1
Result: label - barred spiral, probability - 0.8110836148262024
[0.005403901915997267, 0.8394284248352051, 0.05693470686674118, 0.042268797755241394, 0.055964212864637375]
1
Result: label - barred spiral, probability - 0.8394284248352051
[0.008424561470746994, 0.7328515648841858, 0.1303010880947113, 0.08146897703409195, 0.04695378243923187]
1
Result: label - barred spiral, probability - 0.7328515648841858
[0.002050576265901327, 0.8798288106918335, 0.030415760353207588, 0.064012810587883, 0.023692060261964798]
1
Result: label - barred spiral, probability - 0.8798288106918335
[0.0043403678573668, 0.419436514377594, 0.026339814066886902, 0.5116335153579712, 0.03824984282255173]
3
Result: label - irregular, probability - 0.5116335153579712
[0.0057829306460917, 0.7617557048797607, 0.11046716570854187, 0.07572413980960846, 0.046269942075014114]
1
Result: label - barred spiral, probability - 0.7617557048797607
[0.006713164038956165, 0.7659129500389099, 0.06907536089420319, 0.10459558665752411, 0.05370292440056801]
1
Result: label - barred spiral, probability - 0.7659129500389099
[0.002455314854159951, 0.8560612201690674, 0.04400036484003067, 0.04012644290924072, 0.05735668167471886]
1
Result: label - barred spiral, probability - 0.8560612201690674
[0.002014275174587965, 0.8715226650238037, 0.02037484385073185, 0.05761754512786865, 0.04847059026360512]
1
Result: label - barred spiral, probability - 0.8715226650238037
[0.0019912198185920715, 0.8680242300033569, 0.03483432158827782, 0.05842462182044983, 0.03672562167048454]
1
Result: label - barred spiral, probability - 0.8680242300033569
now elliptical
[0.003287338651716709, 0.0334925577044487, 0.6104640960693359, 0.33476489782333374, 0.01799107901751995]
2
Result: label - elliptical, probability - 0.6104640960693359
[0.007567195687443018, 0.07700329273939133, 0.7326911687850952, 0.08414039760828018, 0.0985979214310646]
2
Result: label - elliptical, probability - 0.7326911687850952
[0.0018654868472367525, 0.09235350042581558, 0.3877021074295044, 0.4879956543445587, 0.03008323907852173]
3
Result: label - irregular, probability - 0.4879956543445587
[0.0030551692470908165, 0.04906388744711876, 0.85813307762146, 0.062192827463150024, 0.027555083855986595]
2
Result: label - elliptical, probability - 0.85813307762146
[0.0022870339453220367, 0.03530525788664818, 0.898676335811615, 0.03762800991535187, 0.02610333450138569]
2
Result: label - elliptical, probability - 0.898676335811615
[0.004280530381947756, 0.12699832022190094, 0.7742352485656738, 0.05651982128620148, 0.037966202944517136]
2
Result: label - elliptical, probability - 0.7742352485656738
[0.01816757768392563, 0.28856605291366577, 0.5723285675048828, 0.06645290553569794, 0.05448492243885994]
2
Result: label - elliptical, probability - 0.5723285675048828
[0.001773641793988645, 0.0478752925992012, 0.8853607177734375, 0.05610418692231178, 0.00888625904917717]
2
Result: label - elliptical, probability - 0.8853607177734375
[0.010634558275341988, 0.101668581366539, 0.7547025084495544, 0.08968473970890045, 0.043309539556503296]
2
Result: label - elliptical, probability - 0.7547025084495544
[0.0007148808217607439, 0.07415115088224411, 0.8406915664672852, 0.05873614549636841, 0.025706233456730843]
2
Result: label - elliptical, probability - 0.8406915664672852
[0.004228980280458927, 0.030605891719460487, 0.8850685358047485, 0.047970280051231384, 0.03212637081742287]
2
Result: label - elliptical, probability - 0.8850685358047485
[0.0005916637601330876, 0.0032985531724989414, 0.968010425567627, 0.02527557499706745, 0.0028237143997102976]
2
Result: label - elliptical, probability - 0.968010425567627
[0.0026924866251647472, 0.03402582183480263, 0.7553783655166626, 0.1897047460079193, 0.018198663368821144]
2
Result: label - elliptical, probability - 0.7553783655166626
[0.008747651241719723, 0.13614268600940704, 0.6871249079704285, 0.07398854941129684, 0.09399618208408356]
2
Result: label - elliptical, probability - 0.6871249079704285
[0.005349430721253157, 0.06309215724468231, 0.6996669769287109, 0.20650634169578552, 0.025385089218616486]
2
Result: label - elliptical, probability - 0.6996669769287109
[0.0018359011737629771, 0.027001800015568733, 0.9109044075012207, 0.04850131645798683, 0.011756643652915955]
2
Result: label - elliptical, probability - 0.9109044075012207
[0.0047980318777263165, 0.03252715244889259, 0.8921998739242554, 0.05913088843226433, 0.011344049125909805]
2
Result: label - elliptical, probability - 0.8921998739242554
[0.004975678399205208, 0.07538039237260818, 0.7449381947517395, 0.16077739000320435, 0.013928416185081005]
2
Result: label - elliptical, probability - 0.7449381947517395
[0.007034516427665949, 0.0895109623670578, 0.43819066882133484, 0.44851139187812805, 0.016752535477280617]
3
Result: label - irregular, probability - 0.44851139187812805
now irregular
[0.008654586039483547, 0.09021711349487305, 0.10089680552482605, 0.7347139716148376, 0.06551746279001236]
3
Result: label - irregular, probability - 0.7347139716148376
[0.003836500458419323, 0.015876425430178642, 0.028530647978186607, 0.926641583442688, 0.025114795193076134]
3
Result: label - irregular, probability - 0.926641583442688
[0.0008644727058708668, 0.014102738350629807, 0.007196993567049503, 0.9673057794570923, 0.010530062951147556]
3
Result: label - irregular, probability - 0.9673057794570923
[0.006367767695337534, 0.044562969356775284, 0.11740122735500336, 0.7762677073478699, 0.055400315672159195]
3
Result: label - irregular, probability - 0.7762677073478699
[0.0010990044102072716, 0.004091451410204172, 0.11547891795635223, 0.8691325187683105, 0.010198093019425869]
3
Result: label - irregular, probability - 0.8691325187683105
[0.003197451587766409, 0.025882884860038757, 0.1708792895078659, 0.7819303870201111, 0.018109943717718124]
3
Result: label - irregular, probability - 0.7819303870201111
[0.00013745491742156446, 0.0033155318815261126, 0.07621622830629349, 0.9172816872596741, 0.00304909679107368]
3
Result: label - irregular, probability - 0.9172816872596741
[0.006140223238617182, 0.17311476171016693, 0.23641854524612427, 0.5434606075286865, 0.040865831077098846]
3
Result: label - irregular, probability - 0.5434606075286865
[0.004886952228844166, 0.13948263227939606, 0.12337321043014526, 0.7045894265174866, 0.02766772173345089]
3
Result: label - irregular, probability - 0.7045894265174866
[0.004641332663595676, 0.01907491311430931, 0.11986702680587769, 0.8077115416526794, 0.04870523139834404]
3
Result: label - irregular, probability - 0.8077115416526794
[0.0016981608932837844, 0.15364156663417816, 0.03986287862062454, 0.6410871148109436, 0.1637103110551834]
3
Result: label - irregular, probability - 0.6410871148109436
[0.0015327318105846643, 0.02242753468453884, 0.009713005274534225, 0.955703616142273, 0.010623202659189701]
3
Result: label - irregular, probability - 0.955703616142273
[0.0012233315501362085, 0.00971941463649273, 0.011318624950945377, 0.9637594819068909, 0.013979102484881878]
3
Result: label - irregular, probability - 0.9637594819068909
[0.007168464828282595, 0.07302546501159668, 0.07332482933998108, 0.8032405376434326, 0.0432407446205616]
3
Result: label - irregular, probability - 0.8032405376434326
[0.0006713686743751168, 0.03321423381567001, 0.053633131086826324, 0.9092507362365723, 0.0032305887434631586]
3
Result: label - irregular, probability - 0.9092507362365723
[0.002615415956825018, 0.03452685847878456, 0.2715490758419037, 0.6742355823516846, 0.01707305945456028]
3
Result: label - irregular, probability - 0.6742355823516846
[0.022000616416335106, 0.1418653428554535, 0.299450546503067, 0.4755397140979767, 0.06114376336336136]
3
Result: label - irregular, probability - 0.4755397140979767
[0.00952627882361412, 0.04031480476260185, 0.11161965876817703, 0.774489164352417, 0.06405006349086761]
3
Result: label - irregular, probability - 0.774489164352417
[0.013387951999902725, 0.12006370723247528, 0.18541596829891205, 0.6415802836418152, 0.03955204784870148]
3
Result: label - irregular, probability - 0.6415802836418152
now spiral
[0.0026439609937369823, 0.07960028946399689, 0.024301812052726746, 0.3611459732055664, 0.5323079824447632]
4
Result: label - spiral, probability - 0.5323079824447632
[0.005364022683352232, 0.3816812336444855, 0.13571147620677948, 0.160086989402771, 0.31715628504753113]
1
Result: label - barred spiral, probability - 0.3816812336444855
[0.012528532184660435, 0.1501101851463318, 0.14032743871212006, 0.17045730352401733, 0.5265765190124512]
4
Result: label - spiral, probability - 0.5265765190124512
[0.012380652129650116, 0.12324447184801102, 0.09091399610042572, 0.07756565511226654, 0.695895254611969]
4
Result: label - spiral, probability - 0.695895254611969
[0.008190101943910122, 0.02981363609433174, 0.0593835711479187, 0.09963618218898773, 0.8029764890670776]
4
Result: label - spiral, probability - 0.8029764890670776
[0.008190101943910122, 0.02981363609433174, 0.0593835711479187, 0.09963618218898773, 0.8029764890670776]
4
Result: label - spiral, probability - 0.8029764890670776
[0.005148271564394236, 0.20115876197814941, 0.023478923365473747, 0.5789682865142822, 0.19124570488929749]
3
Result: label - irregular, probability - 0.5789682865142822
[0.013668617233633995, 0.13188982009887695, 0.14066433906555176, 0.23451052606105804, 0.4792667627334595]
4
Result: label - spiral, probability - 0.4792667627334595
[0.016199735924601555, 0.3533635139465332, 0.2187536060810089, 0.21921345591545105, 0.19246964156627655]
1
Result: label - barred spiral, probability - 0.3533635139465332
[0.0008888196316547692, 0.0231563039124012, 0.004346329253166914, 0.021200450137257576, 0.9504081010818481]
4
Result: label - spiral, probability - 0.9504081010818481
[0.006812945939600468, 0.09337477385997772, 0.24545349180698395, 0.3859702944755554, 0.2683885097503662]
3
Result: label - irregular, probability - 0.3859702944755554
[0.0069922651164233685, 0.18431955575942993, 0.28074556589126587, 0.19833852350711823, 0.3296040892601013]
4
Result: label - spiral, probability - 0.3296040892601013
[0.018744265660643578, 0.32230648398399353, 0.3197038769721985, 0.08574662357568741, 0.25349876284599304]
1
Result: label - barred spiral, probability - 0.32230648398399353
[0.0017773894360288978, 0.045077335089445114, 0.21341225504875183, 0.36855632066726685, 0.37117674946784973]
4
Result: label - spiral, probability - 0.37117674946784973
[0.005294592119753361, 0.07947451621294022, 0.06910264492034912, 0.09444800019264221, 0.7516802549362183]
4
Result: label - spiral, probability - 0.7516802549362183
[0.011262122541666031, 0.06800501048564911, 0.06291303783655167, 0.3420937955379486, 0.5157260298728943]
4
Result: label - spiral, probability - 0.5157260298728943
[0.025909466668963432, 0.29424765706062317, 0.11735246330499649, 0.2812035381793976, 0.28128689527511597]
1
Result: label - barred spiral, probability - 0.29424765706062317
[0.006901011802256107, 0.049757976084947586, 0.03985581547021866, 0.044366318732500076, 0.8591188192367554]
4
Result: label - spiral, probability - 0.8591188192367554
[0.010934649035334587, 0.06618252396583557, 0.24268610775470734, 0.28081241250038147, 0.39938434958457947]
4
Result: label - spiral, probability - 0.39938434958457947
In [143]:
len(train_predictions)
Out[143]:
76
In [144]:
train_keys = []
for i in range(4):
    for j in range(19):
        train_keys.append(i+1)
In [145]:
train_mydict = {'spiral': {'spiral':0.0, 'barred spiral':0.0, 'elliptical':0.0, 'irregular':0.0},
          'barred spiral': {'spiral':0.0, 'barred spiral':0.0, 'elliptical':0.0, 'irregular':0.0},
          'elliptical': {'spiral':0.0, 'barred spiral':0.0, 'elliptical':0.0, 'irregular':0.0},
          'irregular': {'spiral':0.0, 'barred spiral':0.0, 'elliptical':0.0, 'irregular':0.0}}
keytab = {1: 'barred spiral', 2: 'elliptical', 3:'irregular', 4:'spiral'}
i = 0
for key in train_keys:
    train_mydict[keytab[key]][keytab[train_predictions[i]]]+= 1
    i = i+1
In [146]:
train_df = pd.DataFrame.from_dict(train_mydict)
In [147]:
train_df.transpose()
Out[147]:
barred spiral elliptical irregular spiral
barred spiral 17.0 0.0 2.0 0.0
elliptical 0.0 17.0 2.0 0.0
irregular 0.0 0.0 19.0 0.0
spiral 4.0 0.0 2.0 13.0

Clean up

When we're done with the endpoint, we can just delete it and the backing instances will be released. Run the following cell to delete the endpoint.

In [119]:
sage.delete_endpoint(EndpointName=endpoint_name)
Out[119]:
{'ResponseMetadata': {'HTTPHeaders': {'connection': 'keep-alive',
   'content-length': '0',
   'content-type': 'application/x-amz-json-1.1',
   'date': 'Thu, 15 Feb 2018 18:35:38 GMT',
   'x-amzn-requestid': 'a69a2025-d4ef-4b54-9e62-16bd3764bb89'},
  'HTTPStatusCode': 200,
  'RequestId': 'a69a2025-d4ef-4b54-9e62-16bd3764bb89',
  'RetryAttempts': 0}}