training/built-in-algorithms/Image-classification-multilabel-lst.ipynb (673 lines of code) (raw):
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Image classification multi-label classification\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"\n",
"This notebook's CI test result for us-west-2 is as follows. CI test results in other regions can be found at the end of the notebook. \n",
"\n",
"\n",
"\n",
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"1. [Introduction](#Introduction)\n",
"2. [Prerequisites](#Prequisites)\n",
"3. [Data Preparation](#Data-Preparation)\n",
"3. [Multi-label Training](#Multi-label-Training)\n",
"4. [Inference](#Inference)\n",
"5. [Clean-up](#Clean-up)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Introduction\n",
"\n",
"Welcome to our end-to-end example of multi-label classification using the Sagemaker 1P image classification algorithm. 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 multi-label dataset. In particular, the pre-trained model will be fine-tuned using [MS-COCO](http://cocodataset.org/#overview) dataset. \n",
"\n",
"To get started, we need to set up the environment with a few prerequisite steps, for permissions, configurations, and so on."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prequisites\n",
"\n",
"### Permissions and environment variables\n",
"\n",
"Here we set up the linkage and authentication to AWS services. There are three parts to this:\n",
"\n",
"* 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\n",
"* The S3 bucket that you want to use for training and model data\n",
"* The Amazon sagemaker image classification docker image which need not be changed"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Install tools\n",
"\n",
"We need pycocotools to parse the annotations for the MSCOCO dataset"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"! pip install --upgrade sagemaker"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"conda install -c esri pycocotools"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import sagemaker\n",
"from sagemaker import get_execution_role\n",
"\n",
"role = get_execution_role()\n",
"print(role)\n",
"\n",
"sess = sagemaker.Session()\n",
"bucket = sess.default_bucket()\n",
"prefix = \"ic-multilabel\"\n",
"\n",
"print(\"using bucket %s\" % bucket)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"training_image = sagemaker.image_uris.retrieve(\n",
" region=sess.boto_region_name, framework=\"image-classification\", version=\"latest\"\n",
")\n",
"print(training_image)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Data Preparation\n",
"MS COCO is a large-scale dataset for multiple computer vision tasks, including object detection, segmentation, and captioning. In this notebook, we will use the object detection dataset to construct the multi-label dataset for classification. We will use the 2017 validation set from MS-COCO dataset to train multi-label classifier. MS-COCO dataset consist of images from 80 categories. We will choose 5 categories out of 80 and train the model to learn to classify these 5 categories. These are: \n",
"\n",
"1. Person\n",
"2. Bicycle\n",
"3. Car\n",
"4. Motorcycle\n",
"5. Airplane\n",
"\n",
"An image can contain objects of multiple categories. We first create a dataset with these 5 categories. COCO is a very large dataset, and the purpose of this notebook is to show how multi-label classification works. So, instead we\u2019ll take what COCO calls their validation dataset from 2017, and use this as our only data. We then split this dataset into a train and holdout dataset for fine tuning the model and testing our final accuracy\n",
"\n",
"The image classification algorithm can take two types of input formats. The first is a [recordio format](https://mxnet.apache.org/versions/1.7.0/api/faq/recordio) and the other is a lst format. We will use the lst file format for training. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Dataset License\n",
"\n",
"The annotations in this dataset belong to the COCO Consortium and are licensed under a Creative Commons Attribution 4.0 License. The COCO Consortium does not own the copyright of the images. Use of the images must abide by the Flickr Terms of Use. The users of the images accept full responsibility for the use of the dataset, including but not limited to the use of any copies of copyrighted images that they may create from the dataset. Before you use this data for any other purpose than this example, you should understand the data license, described at http://cocodataset.org/#termsofuse\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import urllib.request\n",
"\n",
"\n",
"def download(url):\n",
" filename = url.split(\"/\")[-1]\n",
" if not os.path.exists(filename):\n",
" urllib.request.urlretrieve(url, filename)\n",
"\n",
"\n",
"# MSCOCO validation image files\n",
"download(\"http://images.cocodataset.org/zips/val2017.zip\")\n",
"download(\"http://images.cocodataset.org/annotations/annotations_trainval2017.zip\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!unzip -qo val2017.zip\n",
"!unzip -qo annotations_trainval2017.zip"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Parse the annotation to create lst file\n",
"Use pycocotools to parse the annotation and create the lst file"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from pycocotools.coco import COCO\n",
"import numpy as np\n",
"import os\n",
"\n",
"annFile = \"./annotations/instances_val2017.json\"\n",
"coco = COCO(annFile)\n",
"\n",
"catIds = coco.getCatIds()\n",
"image_ids_of_cats = []\n",
"for cat in catIds:\n",
" image_ids_of_cats.append(coco.getImgIds(catIds=cat))\n",
"\n",
"image_ids = []\n",
"labels = []\n",
"# use only the first 5 classes\n",
"# obtain image ids and labels for images with these 5 classes\n",
"cats = [1, 2, 3, 4, 5]\n",
"for ind_cat in cats:\n",
" for image_id in image_ids_of_cats[ind_cat - 1]:\n",
" if image_id in image_ids:\n",
" labels[image_ids.index(image_id)][ind_cat - 1] = 1\n",
" else:\n",
" image_ids.append(image_id)\n",
" labels.append(np.zeros(len(cats), dtype=np.int))\n",
" labels[-1][ind_cat - 1] = 1\n",
"# Construct the lst file from the image ids and labels\n",
"# The first column is the image index, the last is the image filename\n",
"# and the second to last but one are the labels\n",
"with open(\"image.lst\", \"w\") as fp:\n",
" sum_labels = labels[0]\n",
" for ind, image_id in enumerate(image_ids):\n",
" coco_img = coco.loadImgs(image_id)\n",
" image_path = os.path.join(coco_img[0][\"file_name\"])\n",
" label_h = labels[ind]\n",
" sum_labels += label_h\n",
" fp.write(str(ind) + \"\\t\")\n",
" for j in label_h:\n",
" fp.write(str(j) + \"\\t\")\n",
" fp.write(image_path)\n",
" fp.write(\"\\n\")\n",
" fp.close()\n",
"print(sum_labels)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create training and validation set\n",
"Create training and validation set by splitting the lst file. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!shuf image.lst > im.lst\n",
"!head -n 2500 im.lst > mscocoval2017train.lst\n",
"!tail -n +2501 im.lst > mscocoval2017val.lst\n",
"!head mscocoval2017train.lst\n",
"!wc -l mscocoval2017train.lst\n",
"!wc -l mscocoval2017val.lst"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Upload the data\n",
"Upload the data onto the s3 bucket. The images are uploaded onto train and validation bucket. The lst files are uploaded to train_lst and validation_lst folders. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Four channels: train, validation, train_lst, and validation_lst\n",
"s3train = \"s3://{}/{}/train/\".format(bucket, prefix)\n",
"s3validation = \"s3://{}/{}/validation/\".format(bucket, prefix)\n",
"s3train_lst = \"s3://{}/{}/train_lst/\".format(bucket, prefix)\n",
"s3validation_lst = \"s3://{}/{}/validation_lst/\".format(bucket, prefix)\n",
"\n",
"# upload the image files to train and validation channels\n",
"!aws s3 cp val2017 $s3train --recursive --quiet\n",
"!aws s3 cp val2017 $s3validation --recursive --quiet\n",
"\n",
"# upload the lst files to train_lst and validation_lst channels\n",
"!aws s3 cp mscocoval2017train.lst $s3train_lst --quiet\n",
"!aws s3 cp mscocoval2017val.lst $s3validation_lst --quiet"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Multi-label Training\n",
"\n",
"Now that we are done with all the setup that is needed, we are ready to train our object detector.\n",
"\n",
"Training can be done by either calling SageMaker Training with a set of hyperparameters values to train with, or by leveraging SageMaker Automatic Model Tuning ([AMT](https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning.html)). AMT, also known as hyperparameter tuning (HPO), finds the best version of a model by running many training jobs on your dataset using the algorithm and ranges of hyperparameters that you specify. It then chooses the hyperparameter values that result in a model that performs the best, as measured by a metric that you choose.\n",
"\n",
"In this notebook, both methods are used for demonstration purposes, but the model that the HPO job creates is the one that is eventually hosted. You can instead choose to deploy the model created by the standalone training job by changing the below variable `deploy_amt_model` to False."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"deploy_amt_model = True"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Training with SageMaker Training\n",
"\n",
"To begin, let us create a ``sageMaker.estimator.Estimator`` object. This estimator will launch the training job.\n",
"\n",
"#### Training parameters\n",
"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:\n",
"\n",
"* **Training instance count**: This is the number of instances on which to run the training. When the number of instances is greater than one, then the image classification algorithm will run in distributed settings. \n",
"* **Training instance type**: This indicates the type of machine on which to run the training. Typically, we use GPU instances for these training \n",
"* **Output path**: This the s3 folder in which the training output is stored"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"s3_output_location = \"s3://{}/{}/output\".format(bucket, prefix)\n",
"\n",
"multilabel_ic = sagemaker.estimator.Estimator(\n",
" training_image,\n",
" role,\n",
" instance_count=1,\n",
" instance_type=\"ml.p2.xlarge\",\n",
" volume_size=50,\n",
" max_run=360000,\n",
" input_mode=\"File\",\n",
" output_path=s3_output_location,\n",
" sagemaker_session=sess,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Algorithm parameters\n",
"\n",
"Apart from the above set of parameters, there are hyperparameters that are specific to the algorithm. These are:\n",
"\n",
"* **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.\n",
"* **use_pretrained_model**: Set to 1 to use pretrained model for transfer learning.\n",
"* **image_shape**: The input image dimensions,'num_channels, height, width', for the network. It should be no larger than the actual image size. The number of channels should be same as the actual image.\n",
"* **num_classes**: This is the number of output classes for the dataset. We use 5 classes from MSCOCO and hence it is set to 5\n",
"* **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\n",
"* **resize**: Resize the image before using it for training. The images are resized so that the shortest side is of this parameter. If the parameter is not set, then the training data is used as such without resizing.\n",
"* **epochs**: Number of training epochs\n",
"* **learning_rate**: Learning rate for training\n",
"* **num_training_samples**: This is the total number of training samples. It is set to 2500 for COCO dataset with the current split\n",
"* **use_weighted_loss**: This parameter is used to balance the influence of the positive and negative samples within the dataset.\n",
"* **augmentation_type**: This parameter determines the type of augmentation used for training. It can take on three values, 'crop', 'crop_color' and 'crop_color_transform'\n",
"* **precision_dtype**: The data type precision used during training. Using ``float16`` can lead to faster training with minimal drop in accuracy, paritcularly on P3 machines. By default, the parameter is set to ``float32``\n",
"* **multi_label**: Set multi_label to 1 for multi-label processing\n",
"\n",
"You can find a detailed description of all the algorithm parameters at https://docs.aws.amazon.com/sagemaker/latest/dg/IC-Hyperparameter.html"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"multilabel_ic.set_hyperparameters(\n",
" num_layers=18,\n",
" use_pretrained_model=1,\n",
" image_shape=\"3,224,224\",\n",
" num_classes=5,\n",
" mini_batch_size=128,\n",
" resize=256,\n",
" epochs=5,\n",
" learning_rate=0.001,\n",
" num_training_samples=2500,\n",
" use_weighted_loss=1,\n",
" augmentation_type=\"crop_color_transform\",\n",
" precision_dtype=\"float32\",\n",
" multi_label=1,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Input data specification\n",
"Set the data type and channels used for training. In this training, we use application/x-image content type that require individual images and lst file for data input. In addition, Sagemaker image classification algorithm supports application/x-recordio format which can be used for larger datasets. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"train_data = sagemaker.inputs.TrainingInput(\n",
" s3train,\n",
" distribution=\"FullyReplicated\",\n",
" content_type=\"application/x-image\",\n",
" s3_data_type=\"S3Prefix\",\n",
")\n",
"validation_data = sagemaker.inputs.TrainingInput(\n",
" s3validation,\n",
" distribution=\"FullyReplicated\",\n",
" content_type=\"application/x-image\",\n",
" s3_data_type=\"S3Prefix\",\n",
")\n",
"train_data_lst = sagemaker.inputs.TrainingInput(\n",
" s3train_lst,\n",
" distribution=\"FullyReplicated\",\n",
" content_type=\"application/x-image\",\n",
" s3_data_type=\"S3Prefix\",\n",
")\n",
"validation_data_lst = sagemaker.inputs.TrainingInput(\n",
" s3validation_lst,\n",
" distribution=\"FullyReplicated\",\n",
" content_type=\"application/x-image\",\n",
" s3_data_type=\"S3Prefix\",\n",
")\n",
"data_channels = {\n",
" \"train\": train_data,\n",
" \"validation\": validation_data,\n",
" \"train_lst\": train_data_lst,\n",
" \"validation_lst\": validation_data_lst,\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Start the training\n",
"\n",
"Start training by calling the fit method in the estimator"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"multilabel_ic.fit(inputs=data_channels, logs=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Training with Automatic Model Tuning ([HPO](https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning.html)) <a id='AMT'></a>\n",
"***\n",
"As mentioned above, instead of manually configuring our hyper parameter values and training with SageMaker Training, we'll use Amazon SageMaker Automatic Model Tuning. \n",
" \n",
"The code sample below shows you how to use the HyperParameterTuner. For recommended default hyparameter ranges, check the [Amazon SageMaker Image Classification HPs documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/IC-Hyperparameter.html). \n",
"\n",
"The tuning job will take 15 to 20 minutes to complete.\n",
"***"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import time\n",
"from sagemaker.tuner import IntegerParameter, ContinuousParameter\n",
"from sagemaker.tuner import HyperparameterTuner\n",
"\n",
"job_name = \"DEMO-ic-mul-\" + time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.gmtime())\n",
"print(\"Tuning job name: \", job_name)\n",
"\n",
"# Linear Learner tunable hyper parameters can be found here https://docs.aws.amazon.com/sagemaker/latest/dg/IC-tuning.html\n",
"hyperparameter_ranges = {\n",
" \"beta_1\": ContinuousParameter(1e-6, 0.999, scaling_type=\"Auto\"),\n",
" \"beta_2\": ContinuousParameter(1e-6, 0.999, scaling_type=\"Auto\"),\n",
" \"eps\": ContinuousParameter(1e-8, 1.0, scaling_type=\"Auto\"),\n",
" \"gamma\": ContinuousParameter(1e-8, 0.999, scaling_type=\"Auto\"),\n",
" \"learning_rate\": ContinuousParameter(1e-6, 0.5, scaling_type=\"Auto\"),\n",
" \"mini_batch_size\": IntegerParameter(8, 512, scaling_type=\"Auto\"),\n",
" \"momentum\": ContinuousParameter(0.0, 0.999, scaling_type=\"Auto\"),\n",
" \"weight_decay\": ContinuousParameter(0.0, 0.999, scaling_type=\"Auto\"),\n",
"}\n",
"\n",
"# Increase the total number of training jobs run by AMT, for increased accuracy (and training time).\n",
"max_jobs = 6\n",
"# Change parallel training jobs run by AMT to reduce total training time, constrained by your account limits.\n",
"# if max_jobs=max_parallel_jobs then Bayesian search turns to Random.\n",
"max_parallel_jobs = 2\n",
"\n",
"\n",
"hp_tuner = HyperparameterTuner(\n",
" multilabel_ic,\n",
" \"validation:accuracy\",\n",
" hyperparameter_ranges,\n",
" max_jobs=max_jobs,\n",
" max_parallel_jobs=max_parallel_jobs,\n",
" objective_type=\"Maximize\",\n",
")\n",
"\n",
"\n",
"# Launch a SageMaker Tuning job to search for the best hyperparameters\n",
"hp_tuner.fit(inputs=data_channels, job_name=job_name)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Inference\n",
"\n",
"***\n",
"\n",
"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 class of the image. You can deploy the created model by using the deploy method in the estimator or the tuner. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sagemaker.serializers import IdentitySerializer\n",
"\n",
"ic_classifier = (hp_tuner if deploy_amt_model else multilabel_ic).deploy(\n",
" initial_instance_count=1,\n",
" instance_type=\"ml.m4.xlarge\",\n",
" serializer=IdentitySerializer(content_type=\"application/x-image\"),\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Evaluation\n",
"\n",
"Evaluate an image through the network for inference. The network outputs class probabilities for all the classes. As can be seen from this example, the network output is pretty good even with training for only 5 epochs."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"\n",
"# This image was used in training. In practice, test another image that is 600x400\n",
"file_name = \"val2017/000000000139.jpg\"\n",
"with open(file_name, \"rb\") as image:\n",
" f = image.read()\n",
" b = bytearray(f)\n",
"\n",
"results = ic_classifier.predict(b)\n",
"prob = json.loads(results)\n",
"classes = [\"Person\", \"Bicycle\", \"Car\", \"Motorcycle\", \"Airplane\"]\n",
"for idx, val in enumerate(classes):\n",
" print(\"%s:%f \" % (classes[idx], prob[idx]), end=\"\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Clean up\n",
"You can use the following command to delete the endpoint. The endpoint that is created above is persistent and would consume resources till it is deleted. It is good to delete the endpoint when it is not used"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ic_classifier.delete_endpoint()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Notebook CI Test Results\n",
"\n",
"This notebook was tested in multiple regions. The test results are as follows, except for us-west-2 which is shown at the top of the notebook.\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n"
]
}
],
"metadata": {
"instance_type": "ml.t3.medium",
"kernelspec": {
"display_name": "Python 3 (Data Science)",
"language": "python",
"name": "python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-east-1:081325390199:image/datascience-1.0"
},
"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.7.10"
},
"notice": "Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.",
"pycharm": {
"stem_cell": {
"cell_type": "raw",
"metadata": {
"collapsed": false
},
"source": []
}
}
},
"nbformat": 4,
"nbformat_minor": 4
}