Transfer learning for TensorFlow object detection models in Amazon SageMaker

Amazon SageMaker oferă o suită de algoritmi încorporați, modele pre-antrenate, și șabloane de soluții prefabricate pentru a ajuta oamenii de știință ai datelor și practicanții de învățare automată (ML) să înceapă pregătirea și implementarea rapidă a modelelor ML. Puteți utiliza acești algoritmi și modele atât pentru învățarea supravegheată, cât și pentru învățarea nesupravegheată. Ele pot procesa diferite tipuri de date de intrare, inclusiv tabelare, imagini și text.

This post is the second in a series on the new built-in algorithms in SageMaker. In the prima postare, we showed how SageMaker provides a built-in algorithm for image classification. Today, we announce that SageMaker provides a new built-in algorithm for object detection using TensorFlow. This supervised learning algorithm supports transfer learning for many pre-trained models available in TensorFlow. It takes an image as input and outputs the objects present in the image along with the bounding boxes. You can fine-tune these pre-trained models using transfer learning even when a large number of training images aren’t available. It’s available through the SageMaker algoritmi încorporați precum și prin intermediul SageMaker JumpStart UI in Amazon SageMaker Studio. Pentru mai multe informații, consultați Object Detection Tensorflow și caietul de exemplu Introduction to SageMaker Tensorflow – Object Detection.

Object detection with TensorFlow in SageMaker provides transfer learning on many pre-trained models available in TensorFlow Hub. According to the number of class labels in the training data, a new randomly initialized object detection head replaces the existing head of the TensorFlow model. Either the whole network, including the pre-trained model, or only the top layer (object detection head) can be fine-tuned on the new training data. In this transfer learning mode, you can achieve training even with a smaller dataset.

How to use the new TensorFlow object detection algorithm

This section describes how to use the TensorFlow object detection algorithm with the SageMaker Python SDK. Pentru informații despre cum să îl utilizați din interfața de utilizare Studio, consultați SageMaker JumpStart.

Algoritmul acceptă învățarea prin transfer pentru modelele pre-antrenate enumerate în TensorFlow models. Fiecare model este identificat printr-un unic model_id. The following code shows how to fine-tune a ResNet50 V1 FPN model identified by model_id tensorflow-od1-ssd-resnet50-v1-fpn-640x640-coco17-tpu-8 pe un set de date de antrenament personalizat. Pentru fiecare model_id, pentru a lansa un job de formare SageMaker prin intermediul Estimator class of the SageMaker Python SDK, you need to fetch the Docker image URI, training script URI, and pre-trained model URI through the utility functions provided in SageMaker. The training script URI contains all the necessary code for data processing, loading the pre-trained model, model training, and saving the trained model for inference. The pre-trained model URI contains the pre-trained model architecture definition and the model parameters. Note that the Docker image URI and the training script URI are the same for all the TensorFlow object detection models. The pre-trained model URI is specific to the particular model. The pre-trained model tarballs have been pre-downloaded from TensorFlow and saved with the appropriate model signature in Serviciul Amazon de stocare simplă (Amazon S3), astfel încât jobul de instruire să ruleze în izolare în rețea. Vezi următorul cod:

from sagemaker import image_uris, model_uris, script_urisfrom sagemaker.estimator import Estimator

model_id, model_version = "tensorflow-od1-ssd-resnet50-v1-fpn-640x640-coco17-tpu-8", "*"
training_instance_type = "ml.p3.2xlarge"
# Retrieve the docker image
train_image_uri = image_uris.retrieve(model_id=model_id,model_version=model_version,image_scope="training",instance_type=training_instance_type,region=None,framework=None)# Retrieve the training script
train_source_uri = script_uris.retrieve(model_id=model_id, model_version=model_version, script_scope="training")# Retrieve the pre-trained model tarball for transfer learning
train_model_uri = model_uris.retrieve(model_id=model_id, model_version=model_version, model_scope="training")

output_bucket = sess.default_bucket()
output_prefix = "jumpstart-example-tensorflow-od-training"
s3_output_location = f"s3://{output_bucket}/{output_prefix}/output"

Cu aceste artefacte de antrenament specifice modelului, puteți construi un obiect al Estimator clasă:

# Create SageMaker Estimator instance
tf_od_estimator = Estimator(
    role=aws_role,
    image_uri=train_image_uri,
    source_dir=train_source_uri,
    model_uri=train_model_uri,
    entry_point="transfer_learning.py",
    instance_count=1,
    instance_type=training_instance_type,
    max_run=360000,
    hyperparameters=hyperparameters,
    output_path=s3_output_location,)

Apoi, pentru transferul de învățare pe setul de date personalizat, poate fi necesar să modificați valorile implicite ale hiperparametrilor de antrenament, care sunt listați în Hiperparametrele. Puteți obține un dicționar Python al acestor hiperparametri cu valorile lor implicite prin apelare hyperparameters.retrieve_default, actualizați-le după cum este necesar, apoi transmiteți-le la clasa Estimator. Rețineți că valorile implicite ale unora dintre hiperparametri sunt diferite pentru diferite modele. Pentru modelele mari, dimensiunea implicită a lotului este mai mică și train_only_top_layer hiperparametrul este setat la True. Hiperparametrul train_only_top_layer definește parametrii modelului care se modifică în timpul procesului de reglare fină. Dacă train_only_top_layer is True, parametrii straturilor de clasificare se modifică, iar restul parametrilor rămân constanți în timpul procesului de reglare fină. Pe de altă parte, dacă train_only_top_layer is False, toți parametrii modelului sunt reglați fin. Vezi următorul cod:

from sagemaker import hyperparameters# Retrieve the default hyper-parameters for fine-tuning the model
hyperparameters = hyperparameters.retrieve_default(model_id=model_id, model_version=model_version)# [Optional] Override default hyperparameters with custom values
hyperparameters["epochs"] = "5"

Noi oferim PennFudanPed dataset as a default dataset for fine-tuning the models. The dataset comprises images of pedestrians. The following code provides the default training dataset hosted in S3 buckets:

# Sample training data is available in this bucket
training_data_bucket = f"jumpstart-cache-prod-{aws_region}"
training_data_prefix = "training-datasets/PennFudanPed_COCO_format/"

training_dataset_s3_path = f"s3://{training_data_bucket}/{training_data_prefix}"

În cele din urmă, pentru a lansa jobul de instruire SageMaker pentru reglarea fină a modelului, sunați .fit pe obiectul clasei Estimator, în timp ce treceți locația S3 a setului de date de antrenament:

# Launch a SageMaker Training job by passing s3 path of the training data
tf_od_estimator.fit({"training": training_dataset_s3_path}, logs=True)

For more information about how to use the new SageMaker TensorFlow object detection algorithm for transfer learning on a custom dataset, deploy the fine-tuned model, run inference on the deployed model, and deploy the pre-trained model as is without first fine-tuning on a custom dataset, see the following example notebook: Introduction to SageMaker TensorFlow – Object Detection.

Input/output interface for the TensorFlow object detection algorithm

Puteți regla fin fiecare dintre modelele pre-antrenate enumerate în TensorFlow Models la orice set de date dat care cuprinde imagini aparținând oricărui număr de clase. Obiectivul este de a minimiza eroarea de predicție a datelor de intrare. Modelul returnat prin reglare fină poate fi implementat în continuare pentru inferență. Următoarele sunt instrucțiunile despre modul în care datele de antrenament ar trebui să fie formatate pentru a fi introduse în model:

  • Intrare – A directory with sub-directory images and a file annotations.json.
  • producție – There are two outputs. First is a fine-tuned model, which can be deployed for inference or further trained using incremental training. Second is a file which maps class indexes to class labels; this is saved along with the model.

The input directory should look like the following example:

input_directory
      | -- images
            |--abc.png
            |--def.png
      |--annotations.json

annotations.json file should have information for bounding_boxes and their class labels. It should have a dictionary with the keys "images" și "annotations". The value for the "images" key should be a list of entries, one for each image of the form {"file_name": image_name, "height": height, "width": width, "id": image_id}. Valoarea "annotations" key should be a list of entries, one for each bounding box of the form {"image_id": image_id, "bbox": [xmin, ymin, xmax, ymax], "category_id": bbox_label}.

Inference with the TensorFlow object detection algorithm

Modelele generate pot fi găzduite pentru inferență și acceptă formatele de imagine codificate .jpg, .jpeg și .png ca application/x-image content type. The input image is resized automatically. The output contains the boxes, predicted classes, and scores for each prediction. The TensorFlow object detection model processes a single image per request and outputs only one line in the JSON. The following is an example of a response in JSON:

accept: application/json;verbose

{"normalized_boxes":[[xmin1, xmax1, ymin1, ymax1],....], "classes":[classidx1, class_idx2,...], "scores":[score_1, score_2,...], "labels": [label1, label2, ...], "tensorflow_model_output":}

If accept este setat la application/json, then the model only outputs predicted boxes, classes, and scores. For more details on training and inference, see the sample notebook Introduction to SageMaker TensorFlow – Object Detection.

Utilizați algoritmi încorporați SageMaker prin interfața de utilizare JumpStart

You can also use SageMaker TensorFlow object detection and any of the other built-in algorithms with a few clicks via the JumpStart UI. JumpStart is a SageMaker feature that allows you to train and deploy built-in algorithms and pre-trained models from various ML frameworks and model hubs through a graphical interface. It also allows you to deploy fully fledged ML solutions that string together ML models and various other AWS services to solve a targeted use case.

Following are two videos that show how you can replicate the same fine-tuning and deployment process we just went through with a few clicks via the JumpStart UI.

Reglați fin modelul pre-antrenat

Here is the process to fine-tune the same pre-trained object detection model.

Deploy the finetuned model

After model training is finished, you can directly deploy the model to a persistent, real-time endpoint with one click.

Concluzie

In this post, we announced the launch of the SageMaker TensorFlow object detection built-in algorithm. We provided example code on how to do transfer learning on a custom dataset using a pre-trained model from TensorFlow using this algorithm.

Pentru mai multe informații, consultați documentaţie si exemplu caiet.


Despre autori

Transfer learning for TensorFlow object detection models in Amazon SageMaker PlatoBlockchain Data Intelligence. Vertical Search. Ai.Dr. Vivek Madan este un om de știință aplicat cu Echipa Amazon SageMaker JumpStart. He got his PhD from University of Illinois at Urbana-Champaign and was a Post Doctoral Researcher at Georgia Tech. He is an active researcher in machine learning and algorithm design and has published papers in EMNLP, ICLR, COLT, FOCS, and SODA conferences.

Transfer learning for TensorFlow object detection models in Amazon SageMaker PlatoBlockchain Data Intelligence. Vertical Search. Ai.João Moura este arhitect specializat în soluții AI/ML la Amazon Web Services. El se concentrează în principal pe cazuri de utilizare a NLP și ajută clienții să optimizeze instruirea și implementarea modelului de deep learning. El este, de asemenea, un susținător activ al soluțiilor ML low-code și al hardware-ului specializat în ML.

Transfer learning for TensorFlow object detection models in Amazon SageMaker PlatoBlockchain Data Intelligence. Vertical Search. Ai.Dr. Ashish Khetan este un Senior Applied Scientist cu Algoritmi încorporați Amazon SageMaker și ajută la dezvoltarea algoritmilor de învățare automată. Și-a luat doctoratul la Universitatea din Illinois Urbana Champaign. Este un cercetător activ în învățarea automată și inferența statistică și a publicat multe lucrări în conferințele NeurIPS, ICML, ICLR, JMLR, ACL și EMNLP.

Timestamp-ul:

Mai mult de la Învățare automată AWS