Creating an Object Detection Server Easily with Amazon SageMaker

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/e7e7a42f-166b-6deb-e789-bfd3112e4886.png)

This article is the 5th entry for the [UMITRON Advent Calendar 2023](https://adventar.org/calendars/8726).

[Japanese page](https://qiita.com/hosonot/items/133fffd62bb60be6dd24)

## Table of Contents
[Introduction](#introduction)
[Overview](#overview)
[Creating Training Data with Amazon SageMaker Ground Truth](#creating-training-data-with-amazon-sagemaker-ground-truth)
[Training Object Detection Model with Amazon SageMaker Built-in Algorithm](#training-object-detection-model-with-amazon-sagemaker-built-in-algorithm)
[Deploying Object Detection Model with Amazon SageMaker Endpoint](#deploying-object-detection-model-with-amazon-sagemaker-endpoint)
[Running Object Detection](#running-object-detection)
[Stopping the Endpoint](#stopping-the-endpoint)
[Conclusion](#conclusion)

## Introduction
Hello, I'm Hosono from [UMITRON](https://umitron.com/ja/index.html).
Following [last year's article](https://qiita.com/hosonot/items/d1bd4f260ce59e1b9163), this is another article about object detection.

At UMITRON, several object detection algorithms are used depending on the requirements. When we want to easily verify object detection performances, Amazon SageMaker's built-in object detection algorithm is often used. Since the object detection algorithm is SSD[^1], there may be scenes where accuracy is difficult to achieve compared to the latest algorithms, but we can do everything from generating training data to deploying a model with a web interface. It's easy to build an object detection service.

In terms of ease of operation, it is often better to manage by source code with SDK rather than the web interface for tasks such as updating models. However, using the web interface allows those who are not familiar with object detection or AWS to easily verify, which is a significant advantage. Therefore, in this page, I will introduce a method that does not require code writing for all parts except for the inference execution part of object detection.

So, this page may be helpful for the following people:

- Those who have little knowledge of object detection but want to develop a service using object detection.
- Those who have experience with object detection but have not used Amazon SageMaker.

## Overview
In this page, I will introduce the dataset creation method for object detection model training using Amazon SageMaker, the deployment method as an API server of a model trained using that data, and how to call it. The overview is as follows:

1. Creating Training Data with Amazon SageMaker Ground Truth
2. Training Object Detection Model with Amazon SageMaker Built-in Algorithm
3. Deploying Object Detection Model with Amazon SageMaker Endpoint
4. Running Object Detection

Regarding the deployment of the object detection model, this page introduces the method using real-time inference[^2]. With real-time inference, you can host an API server that is available with low latency.

By the way, in Amazon SageMaker, other deployment methods such as serverless inference[^3] suitable for applications with sporadic requests and asynchronous inference[^4] suitable for processing large data can also be selected.

From now on, I will explain each step.

## Creating Training Data with Amazon SageMaker Ground Truth

In this article, I will introduce a method for labeling training data by ourselves. While it is possible to use Amazon Mechanical Turk for crowdsourcing, please be aware of the associated costs and the inability to handle confidential information.

### Creating a Labeling Workforce

To label data on your own, you need to create a labeling workforce in advance. The steps are as follows:

1. Select "SageMaker" -> "Ground Truth" -> "Labeling workforces" -> "Private" -> "Create private team". <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/4e12beaa-8ef3-8e42-6e80-7ea0fdb13cda.png)
2. Decide on a team name and create the team (leave everything else as default). <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/b6151aea-4807-9bf3-9403-4369b6611380.png)
3. Return to the "Labeling workforces" page and select "Invite new workers". <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/56fd35fa-3b99-945c-aa89-e201433b14a9.png)
4. Enter the email address of the person who will perform the labeling and select "Invite New Workers". <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/478b2eec-aecf-3d23-4e24-33bedbd058d8.png)
5. The registered worker will receive an email with content like the one below. They should log in to the worker portal from the link in the email and set their password. It's convenient to keep the URL for logging in to the worker portal. <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/a264a338-1adc-e548-feb0-0db31a14d06b.png)

### Uploading Images for Training Data to S3

Upload image data to any location in Amazon S3.

1. Go to "Amazon S3" -> Navigate to the folder where you want to upload images -> Upload. <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/496f6970-03a7-1de0-71d1-375bed114684.png)
2. Select images by dragging and dropping, etc., and upload them. <br> <img width="500" alt="image.png" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/6bba6789-1702-2729-af31-93277e3fe5e1.png">

### Creating a Labeling Job

1. Select "SageMaker" -> "Labeling jobs" -> "Create labeling job". <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/6de3fa9d-d4da-8094-4ff9-96fc79c0c7da.png)
2. Set each item in Job overview. Choose automated data setup for Input data setup, and enter the path of the folder where you uploaded the images in S3 location for input datasets. Also, choose image for data type. Specify one with AmazonSageMakerFullAccess for IAM Role. Then, click "Complete data setup". <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/4d7352ef-7843-ef55-6d83-c08e95b6336c.png)
3. After a successful data setup, the display will look like the image below. <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/30b83fad-92ca-45b0-13a3-261f02d807ce.png)
4. Change the Task type to bounding box and click "Next". <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/4e1c7944-84e4-1a41-2f1b-94e97f78b7fb.png)
5. Confirm that Worker types is set to private and set the team you created earlier to private teams. Adjust task timeout (time spent annotating one image) and task expiration time (deadline for completing annotation of all data) as needed. <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/ac2ac715-74ce-ee59-8b0f-74c5342be3bc.png)
6. Configure the bounding box labeling tool. Here, only labels are set. If you want to provide detailed instructions on the task to the members who will perform the labeling, you can describe examples or rules here. After setting, click "Create" to complete. <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/a8b0d677-3f26-602c-5aea-0328717246e0.png)

### Labeling

1. After logging into the Worker Portal, start labeling by selecting the task from the list and clicking on "Start Working." <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/388ec48b-fd68-3c6e-7d88-356b1c67028e.png)
2. Proceed with labeling (all fish images used in this page are from the DeepFish dataset[^5]). <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/2a4a233d-eef5-046e-f866-01770208d959.png)
3. Once completed, the status of the labeling job will change to "complete" after a short while. <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/c836f2e9-2dc8-7028-eb1e-ffd616869724.png)

## Training Object Detection Model with Amazon SageMaker Built-in Algorithm

### Creating a Training Job

1. Select "SageMaker" -> "Training Jobs" -> "Create Training Job". <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/9c5d7dab-7a1e-56a0-0dfc-2443abc8d258.png)
2. Configure the job settings. Set the IAM role to the one with AmazonSageMakerFullAccess. Choose Amazon SageMaker built-in algorithm for algorithm source, and select Vision - Object Detection (MxNet) for the algorithm. Input mode is file. <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/12c8fd66-e442-f6c0-4c2b-88180b81d757.png)
3. For the resource configuration, choose an instance type with GPU (such as p2 or g4dn). <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/cfe336b5-1ce9-3731-b1b1-c264d3ca7be2.png)
4. Configure hyperparameters. If you are not familiar with object detection, these may look complex. But, most of the defaults are fine. The num_classes and num_training_samples highlighted in red in the image below must be set. Specify the number of classes (types of labels) and the total number of images in the training data, respectively. Additionally, the base_network, epochs, and mini_batch_size highlighted in green may need adjustment. The base_network may provide slightly better accuracy with resnet-50, so it's worth trying first. Epochs can affect the learning process; too few may result in insufficient learning, while too many can increase training time. The mini_batch_size is often fine with the default value, but when the number of training data is small, it's better to keep it around 1/10 of the training data (setting it larger than num_training_samples will result in an error). If the number of num_training_samples is large, such as tens of thousands, you may consider setting it larger than the default (e.g., to 512). <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/5e58e7b6-a17b-14e1-49c0-ef8209002b13.png)
5. Set up the input data configuration. There are many changes from the default, so set them as shown in the image below. Set the job name of the labeling job in the second AugmentedManifestFile attribute names highlighted in red. In the S3 location highlighted in green, enter the S3 URI of the manifest/output/output.manifest generated under the output dataset location of the labeling job's folder. Then, click "Add channel". <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/c7d3914b-7502-184e-4e95-dd9c8395bcc2.png)
6. For the added channel, set the channel name to "validation," and enter the same things as "train" for the rest (ideally, it's better to prepare validation data separate from training data, but for simplicity, I'll omit it). <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/659cf7ed-da04-6072-e0c0-59c65c84b097.png)
7. For the output data configuration, specify the folder where you want to place the generated model file. Enabling managed spot training can make training longer but cheaper. Finally, click "Create training job" to start training. <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/9ff092a1-9075-69e6-fe3a-eee9326b3a1b.png)

## Checking Training Results

1. Confirm that the status of the training job created earlier is "completed" in SageMaker -> Training Jobs, then click to go to the job's details page. <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/0a6fd8e1-3bf5-5c09-2422-ab3fd54e1652.png)
2. In the monitor section of the job's details page, review various log values. Here, we'll briefly explain the validation:mAP and train:cross_entropy, which are indicators to adjust the number of epochs set during the creation of the training job.<br>The vertical axis of validation:mAP represents how accurately object detection is performed on the validation data, and higher values are better. In this case, with a small dataset of 42 images, the value may not be very high, but with more extensive and well-learned data, it should be around 0.8 (values may be lower for datasets with challenging object detection). The horizontal axis represents the training time, proportional to the number of epochs. The graph shows that the convergence is around 0.4 as the training progresses. If the convergence is insufficient, it is advisable to increase the number of epochs and retrain. Also, if the model continues to train for an extended period after convergence, when training with similar data next time, you can reduce the number of epochs to maintain accuracy while reducing training time.<br> The vertical axis of train:cross_entropy is an indicator of how well the learning is progressing, and lower values are better. The horizontal axis is the training time. This value also converges as the training progresses, allowing you to check the number of epochs is appropriate. <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/dbec830a-cb5e-6154-1432-c215b86e8d4b.png)

## Deploying Object Detection Model with Amazon SageMaker Endpoint

### Creating the Model

1. Select SageMaker -> Training Jobs -> The training job created earlier -> Create Model. <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/36f36629-8cf4-f618-6945-15e8b914204f.png)
2. Enter only the Model name and click create model. <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/759f87f2-641f-7259-a022-c729d594aba2.png)

### Creating the Endpoint

1. Select "SageMaker" -> "Models" -> The model created earlier -> "Create Endpoint". <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/71e89428-1f0c-f35a-6da5-97dd55c08a54.png)
2. Enter the endpoint name and endpoint configuration name, then click "Create endpoint configuration". <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/4ccb2e2e-2be0-6c8b-6533-d1ceb2e65d4d.png)
3. After the endpoint configuration is created, click "Create endpoint". <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/e92a96ca-ab17-0139-0b4a-8e5db4e39fb5.png)
4. The endpoint will be created in a few minutes. <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/36d4063a-25cd-be45-dd41-26e25d24f550.png)

## Running Object Detection

1\. Set up AWS SDK[^6] and OpenCV[^7] in a Python environment. Both can be installed with pip.
 ```shell
 $ pip install boto3
 $ pip install opencv-python
 ```
 2\. Write the code. Below is a sample function to call the endpoint:
 ```python
 import boto3
import cv2

def detect(img, endpoint_name, aws_profile_name):
    """Detect pellets using SageMaker endpoint
    Args:
        img (np.array): Image data loaded with OpenCV
        endpoint_name (str): SageMaker endpoint name 
        aws_profile_name (str): AWS profile name to access endpoint
    Return:
        dict: detection result json
            {"prediction":[[class id, score, xmin, ymin, xmax, ymax],...]}
    """
    _, buffer = cv2.imencode(".jpg", img)
    session = boto3.session.Session(profile_name=aws_profile_name)
    client = session.client("sagemaker-runtime")

    response = client.invoke_endpoint(
        EndpointName=endpoint_name,
        Body=buffer.tobytes(),
        ContentType="image/jpeg",
    )
    return json.loads(response["Body"].read())
 ```

Here is the result. Although trained with only 42 images, it detected quite well.
![7434_F1_f000073.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/8ed3a041-172a-dc3b-6a8a-84b2e0ebf862.jpeg)

## Stopping the Endpoint

Since endpoints incur charges for the time they are running, delete them when not in use. If you keep the endpoint configuration, you can easily recreate it from "SageMaker" -> "Endpoints" -> "Create Endpoint".

1. Select "SageMaker" -> "Endpoints" -> The endpoint created earlier -> "Delete". <br> ![Image](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2371662/728195ac-4185-c2bf-393c-dd482195e04b.png)

## Conclusion

This page introduced how to create an object detection server using Amazon SageMaker. It's easy to verify object detection if you can collect images, and if you achieve sufficient accuracy, you can deploy it as an object detection server for production. This makes it possible to develop services using object detection quickly. I hope this article serves as a helpful guide for those interested in developing services using object detection.

---
Umitron is recruiting colleagues to work with us. Under the mission of implementing sustainable aquaculture on Earth, why not join us in tackling aquaculture x technology?

[https://umitron.com/en/career.html](https://umitron.com/en/career.html)

[https://open.talentio.com/r/1/c/umitron/homes/3604](https://open.talentio.com/r/1/c/umitron/homes/3604)

[^1]:[Amazon SageMaker Developer Guide Object Detection-MXNet](https://docs.aws.amazon.com/sagemaker/latest/dg/object-detection.html)
[^2]:[Amazon SageMaker Developer Guide Real-time Inference](https://docs.aws.amazon.com/sagemaker/latest/dg/realtime-endpoints.html)
[^3]:[Amazon SageMaker Developer Guide Serverless Inference](https://docs.aws.amazon.com/sagemaker/latest/dg/serverless-endpoints.html)
[^4]:[Amazon SageMaker Developer Guide Asynchronous Inference](https://docs.aws.amazon.com/sagemaker/latest/dg/async-inference.html)
[^5]:[DeepFish](https://alzayats.github.io/DeepFish/)
[^6]:[Amazon SageMaker Developer Guide Setting Up the AWS SDKs](https://docs.aws.amazon.com/kendra/latest/dg/aws-kendra-set-up-sdks.html)
[^7]:[opencv-python](https://pypi.org/project/opencv-python/)