Object Detection with TensorFlow Lite Model Maker

View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook

In this colab notebook, you'll learn how to use the TensorFlow Lite Model Maker library to train a custom object detection model capable of detecting salads within images on a mobile device.

The Model Maker library uses transfer learning to simplify the process of training a TensorFlow Lite model using a custom dataset. Retraining a TensorFlow Lite model with your own custom dataset reduces the amount of training data required and will shorten the training time.

You'll use the publicly available Salads dataset, which was created from the Open Images Dataset V4.

Each image in the dataset contains objects labeled as one of the following classes:

  • Baked Good
  • Cheese
  • Salad
  • Seafood
  • Tomato

The dataset contains the bounding-boxes specifying where each object locates, together with the object's label.

Here is an example image from the dataset:


Prerequisites

Install the required packages

Start by installing the required packages, including the Model Maker package from the GitHub repo and the pycocotools library you'll use for evaluation.

pip install -q tflite-model-maker
pip install -q pycocotools

Import the required packages.

import numpy as np
import os

from tflite_model_maker.config import ExportFormat
from tflite_model_maker import model_spec
from tflite_model_maker import object_detector

import tensorflow as tf
assert tf.__version__.startswith('2')

tf.get_logger().setLevel('ERROR')
from absl import logging
logging.set_verbosity(logging.ERROR)
/tmpfs/src/tf_docs_env/lib/python3.7/site-packages/numba/core/errors.py:154: UserWarning: Insufficiently recent colorama version found. Numba requires colorama >= 0.3.9
  warnings.warn(msg)

Prepare the dataset

Here you'll use the same dataset as the AutoML quickstart.

The Salads dataset is available at: gs://cloud-ml-data/img/openimage/csv/salads_ml_use.csv.

It contains 175 images for training, 25 images for validation, and 25 images for testing. The dataset has five classes: Salad, Seafood, Tomato, Baked goods, Cheese.


The dataset is provided in CSV format:

TRAINING,gs://cloud-ml-data/img/openimage/3/2520/3916261642_0a504acd60_o.jpg,Salad,0.0,0.0954,,,0.977,0.957,,
VALIDATION,gs://cloud-ml-data/img/openimage/3/2520/3916261642_0a504acd60_o.jpg,Seafood,0.0154,0.1538,,,1.0,0.802,,
TEST,gs://cloud-ml-data/img/openimage/3/2520/3916261642_0a504acd60_o.jpg,Tomato,0.0,0.655,,,0.231,0.839,,
  • Each row corresponds to an object localized inside a larger image, with each object specifically designated as test, train, or validation data. You'll learn more about what that means in a later stage in this notebook.
  • The three lines included here indicate three distinct objects located inside the same image available at gs://cloud-ml-data/img/openimage/3/2520/3916261642_0a504acd60_o.jpg.
  • Each row has a different label: Salad, Seafood, Tomato, etc.
  • Bounding boxes are specified for each image using the top left and bottom right vertices.

Here is a visualzation of these three lines:


If you want to know more about how to prepare your own CSV file and the minimum requirements for creating a valid dataset, see the Preparing your training data guide for more details.

If you are new to Google Cloud, you may wonder what the gs:// URL means. They are URLs of files stored on Google Cloud Storage (GCS). If you make your files on GCS public or authenticate your client, Model Maker can read those files similarly to your local files.

However, you don't need to keep your images on Google Cloud to use Model Maker. You can use a local path in your CSV file and Model Maker will just work.

Quickstart

There are six steps to training an object detection model:

Step 1. Choose an object detection model archiecture.

This tutorial uses the EfficientDet-Lite0 model. EfficientDet-Lite[0-4] are a family of mobile/IoT-friendly object detection models derived from the EfficientDet architecture.

Here is the performance of each EfficientDet-Lite models compared to each others.

Model architecture Size(MB)* Latency(ms)** Average Precision***
EfficientDet-Lite0 4.4 37 25.69%
EfficientDet-Lite1 5.8 49 30.55%
EfficientDet-Lite2 7.2 69 33.97%
EfficientDet-Lite3 11.4 116 37.70%
EfficientDet-Lite4 19.9 260 41.96%

* Size of the integer quantized models.
** Latency measured on Pixel 4 using 4 threads on CPU.
*** Average Precision is the mAP (mean Average Precision) on the COCO 2017 validation dataset.

spec = model_spec.get('efficientdet_lite0')

Step 2. Load the dataset.

Model Maker will take input data in the CSV format. Use the object_detector.DataLoader.from_csv method to load the dataset and split them into the training, validation and test images.

  • Training images: These images are used to train the object detection model to recognize salad ingredients.
  • Validation images: These are images that the model didn't see during the training process. You'll use them to decide when you should stop the training, to avoid overfitting.
  • Test images: These images are used to evaluate the final model performance.

You can load the CSV file directly from Google Cloud Storage, but you don't need to keep your images on Google Cloud to use Model Maker. You can specify a local CSV file on your computer, and Model Maker will work just fine.

train_data, validation_data, test_data = object_detector.DataLoader.from_csv('gs://cloud-ml-data/img/openimage/csv/salads_ml_use.csv')

Step 3. Train the TensorFlow model with the training data.

  • The EfficientDet-Lite0 model uses epochs = 50 by default, which means it will go through the training dataset 50 times. You can look at the validation accuracy during training and stop early to avoid overfitting.
  • Set batch_size = 8 here so you will see that it takes 21 steps to go through the 175 images in the training dataset.
  • Set train_whole_model=True to fine-tune the whole model instead of just training the head layer to improve accuracy. The trade-off is that it may take longer to train the model.
model = object_detector.create(train_data, model_spec=spec, batch_size=8, train_whole_model=True, validation_data=validation_data)
Epoch 1/50
21/21 [==============================] - 38s 549ms/step - det_loss: 1.7530 - cls_loss: 1.1282 - box_loss: 0.0125 - reg_l2_loss: 0.0635 - loss: 1.8165 - learning_rate: 0.0090 - gradient_norm: 0.7150 - val_det_loss: 1.6620 - val_cls_loss: 1.0992 - val_box_loss: 0.0113 - val_reg_l2_loss: 0.0635 - val_loss: 1.7256
Epoch 2/50
21/21 [==============================] - 8s 389ms/step - det_loss: 1.6003 - cls_loss: 1.0620 - box_loss: 0.0108 - reg_l2_loss: 0.0635 - loss: 1.6638 - learning_rate: 0.0100 - gradient_norm: 0.9141 - val_det_loss: 1.5013 - val_cls_loss: 0.9806 - val_box_loss: 0.0104 - val_reg_l2_loss: 0.0635 - val_loss: 1.5648
Epoch 3/50
21/21 [==============================] - 8s 374ms/step - det_loss: 1.4079 - cls_loss: 0.9207 - box_loss: 0.0097 - reg_l2_loss: 0.0635 - loss: 1.4714 - learning_rate: 0.0099 - gradient_norm: 1.4177 - val_det_loss: 1.3774 - val_cls_loss: 0.8889 - val_box_loss: 0.0098 - val_reg_l2_loss: 0.0635 - val_loss: 1.4409
Epoch 4/50
21/21 [==============================] - 8s 370ms/step - det_loss: 1.2396 - cls_loss: 0.7963 - box_loss: 0.0089 - reg_l2_loss: 0.0635 - loss: 1.3031 - learning_rate: 0.0099 - gradient_norm: 1.7533 - val_det_loss: 1.5172 - val_cls_loss: 1.0633 - val_box_loss: 0.0091 - val_reg_l2_loss: 0.0635 - val_loss: 1.5807
Epoch 5/50
21/21 [==============================] - 8s 390ms/step - det_loss: 1.1858 - cls_loss: 0.7351 - box_loss: 0.0090 - reg_l2_loss: 0.0635 - loss: 1.2494 - learning_rate: 0.0098 - gradient_norm: 1.9116 - val_det_loss: 1.2644 - val_cls_loss: 0.8182 - val_box_loss: 0.0089 - val_reg_l2_loss: 0.0635 - val_loss: 1.3279
Epoch 6/50
21/21 [==============================] - 7s 347ms/step - det_loss: 1.0802 - cls_loss: 0.6945 - box_loss: 0.0077 - reg_l2_loss: 0.0635 - loss: 1.1437 - learning_rate: 0.0097 - gradient_norm: 1.9390 - val_det_loss: 1.2302 - val_cls_loss: 0.7889 - val_box_loss: 0.0088 - val_reg_l2_loss: 0.0635 - val_loss: 1.2937
Epoch 7/50
21/21 [==============================] - 8s 389ms/step - det_loss: 1.0491 - cls_loss: 0.6716 - box_loss: 0.0075 - reg_l2_loss: 0.0635 - loss: 1.1126 - learning_rate: 0.0096 - gradient_norm: 1.9816 - val_det_loss: 1.1043 - val_cls_loss: 0.6815 - val_box_loss: 0.0085 - val_reg_l2_loss: 0.0636 - val_loss: 1.1679
Epoch 8/50
21/21 [==============================] - 8s 396ms/step - det_loss: 0.9959 - cls_loss: 0.6383 - box_loss: 0.0072 - reg_l2_loss: 0.0636 - loss: 1.0594 - learning_rate: 0.0094 - gradient_norm: 2.1843 - val_det_loss: 1.1045 - val_cls_loss: 0.7051 - val_box_loss: 0.0080 - val_reg_l2_loss: 0.0636 - val_loss: 1.1681
Epoch 9/50
21/21 [==============================] - 8s 386ms/step - det_loss: 0.9746 - cls_loss: 0.6311 - box_loss: 0.0069 - reg_l2_loss: 0.0636 - loss: 1.0381 - learning_rate: 0.0093 - gradient_norm: 2.0273 - val_det_loss: 1.1609 - val_cls_loss: 0.7531 - val_box_loss: 0.0082 - val_reg_l2_loss: 0.0636 - val_loss: 1.2245
Epoch 10/50
21/21 [==============================] - 8s 389ms/step - det_loss: 0.9162 - cls_loss: 0.6018 - box_loss: 0.0063 - reg_l2_loss: 0.0636 - loss: 0.9798 - learning_rate: 0.0091 - gradient_norm: 1.9476 - val_det_loss: 1.1105 - val_cls_loss: 0.7288 - val_box_loss: 0.0076 - val_reg_l2_loss: 0.0636 - val_loss: 1.1741
Epoch 11/50
21/21 [==============================] - 8s 380ms/step - det_loss: 0.9303 - cls_loss: 0.6111 - box_loss: 0.0064 - reg_l2_loss: 0.0636 - loss: 0.9939 - learning_rate: 0.0089 - gradient_norm: 2.1184 - val_det_loss: 0.9739 - val_cls_loss: 0.6087 - val_box_loss: 0.0073 - val_reg_l2_loss: 0.0636 - val_loss: 1.0375
Epoch 12/50
21/21 [==============================] - 8s 409ms/step - det_loss: 0.8756 - cls_loss: 0.5683 - box_loss: 0.0061 - reg_l2_loss: 0.0636 - loss: 0.9392 - learning_rate: 0.0087 - gradient_norm: 1.8964 - val_det_loss: 0.9707 - val_cls_loss: 0.6038 - val_box_loss: 0.0073 - val_reg_l2_loss: 0.0636 - val_loss: 1.0343
Epoch 13/50
21/21 [==============================] - 8s 404ms/step - det_loss: 0.8492 - cls_loss: 0.5508 - box_loss: 0.0060 - reg_l2_loss: 0.0636 - loss: 0.9128 - learning_rate: 0.0085 - gradient_norm: 2.0299 - val_det_loss: 0.9393 - val_cls_loss: 0.5896 - val_box_loss: 0.0070 - val_reg_l2_loss: 0.0636 - val_loss: 1.0029
Epoch 14/50
21/21 [==============================] - 8s 395ms/step - det_loss: 0.8742 - cls_loss: 0.5632 - box_loss: 0.0062 - reg_l2_loss: 0.0636 - loss: 0.9378 - learning_rate: 0.0082 - gradient_norm: 2.2362 - val_det_loss: 0.9523 - val_cls_loss: 0.6120 - val_box_loss: 0.0068 - val_reg_l2_loss: 0.0636 - val_loss: 1.0159
Epoch 15/50
21/21 [==============================] - 8s 377ms/step - det_loss: 0.8488 - cls_loss: 0.5581 - box_loss: 0.0058 - reg_l2_loss: 0.0636 - loss: 0.9124 - learning_rate: 0.0080 - gradient_norm: 2.3419 - val_det_loss: 0.9951 - val_cls_loss: 0.6436 - val_box_loss: 0.0070 - val_reg_l2_loss: 0.0636 - val_loss: 1.0588
Epoch 16/50
21/21 [==============================] - 8s 370ms/step - det_loss: 0.8141 - cls_loss: 0.5252 - box_loss: 0.0058 - reg_l2_loss: 0.0636 - loss: 0.8777 - learning_rate: 0.0077 - gradient_norm: 2.1637 - val_det_loss: 1.0041 - val_cls_loss: 0.6464 - val_box_loss: 0.0072 - val_reg_l2_loss: 0.0636 - val_loss: 1.0677
Epoch 17/50
21/21 [==============================] - 8s 396ms/step - det_loss: 0.8011 - cls_loss: 0.5270 - box_loss: 0.0055 - reg_l2_loss: 0.0636 - loss: 0.8647 - learning_rate: 0.0075 - gradient_norm: 2.2853 - val_det_loss: 0.9154 - val_cls_loss: 0.5768 - val_box_loss: 0.0068 - val_reg_l2_loss: 0.0636 - val_loss: 0.9791
Epoch 18/50
21/21 [==============================] - 8s 382ms/step - det_loss: 0.7949 - cls_loss: 0.5132 - box_loss: 0.0056 - reg_l2_loss: 0.0636 - loss: 0.8586 - learning_rate: 0.0072 - gradient_norm: 2.1825 - val_det_loss: 0.8737 - val_cls_loss: 0.5648 - val_box_loss: 0.0062 - val_reg_l2_loss: 0.0636 - val_loss: 0.9373
Epoch 19/50
21/21 [==============================] - 8s 384ms/step - det_loss: 0.7672 - cls_loss: 0.4935 - box_loss: 0.0055 - reg_l2_loss: 0.0636 - loss: 0.8309 - learning_rate: 0.0069 - gradient_norm: 2.1202 - val_det_loss: 0.9175 - val_cls_loss: 0.5878 - val_box_loss: 0.0066 - val_reg_l2_loss: 0.0636 - val_loss: 0.9812
Epoch 20/50
21/21 [==============================] - 8s 384ms/step - det_loss: 0.7566 - cls_loss: 0.4933 - box_loss: 0.0053 - reg_l2_loss: 0.0636 - loss: 0.8202 - learning_rate: 0.0066 - gradient_norm: 2.2388 - val_det_loss: 0.9889 - val_cls_loss: 0.6390 - val_box_loss: 0.0070 - val_reg_l2_loss: 0.0636 - val_loss: 1.0525
Epoch 21/50
21/21 [==============================] - 8s 394ms/step - det_loss: 0.7754 - cls_loss: 0.5109 - box_loss: 0.0053 - reg_l2_loss: 0.0636 - loss: 0.8390 - learning_rate: 0.0063 - gradient_norm: 2.3627 - val_det_loss: 0.9527 - val_cls_loss: 0.6151 - val_box_loss: 0.0068 - val_reg_l2_loss: 0.0636 - val_loss: 1.0164
Epoch 22/50
21/21 [==============================] - 10s 508ms/step - det_loss: 0.7340 - cls_loss: 0.4941 - box_loss: 0.0048 - reg_l2_loss: 0.0637 - loss: 0.7976 - learning_rate: 0.0060 - gradient_norm: 2.3235 - val_det_loss: 0.9315 - val_cls_loss: 0.6086 - val_box_loss: 0.0065 - val_reg_l2_loss: 0.0637 - val_loss: 0.9952
Epoch 23/50
21/21 [==============================] - 8s 371ms/step - det_loss: 0.7316 - cls_loss: 0.4803 - box_loss: 0.0050 - reg_l2_loss: 0.0637 - loss: 0.7952 - learning_rate: 0.0056 - gradient_norm: 2.2284 - val_det_loss: 0.8832 - val_cls_loss: 0.5659 - val_box_loss: 0.0063 - val_reg_l2_loss: 0.0637 - val_loss: 0.9469
Epoch 24/50
21/21 [==============================] - 8s 378ms/step - det_loss: 0.7206 - cls_loss: 0.4837 - box_loss: 0.0047 - reg_l2_loss: 0.0637 - loss: 0.7843 - learning_rate: 0.0053 - gradient_norm: 2.3365 - val_det_loss: 0.8927 - val_cls_loss: 0.5768 - val_box_loss: 0.0063 - val_reg_l2_loss: 0.0637 - val_loss: 0.9564
Epoch 25/50
21/21 [==============================] - 8s 399ms/step - det_loss: 0.7100 - cls_loss: 0.4640 - box_loss: 0.0049 - reg_l2_loss: 0.0637 - loss: 0.7736 - learning_rate: 0.0050 - gradient_norm: 2.3680 - val_det_loss: 0.9477 - val_cls_loss: 0.6274 - val_box_loss: 0.0064 - val_reg_l2_loss: 0.0637 - val_loss: 1.0114
Epoch 26/50
21/21 [==============================] - 8s 387ms/step - det_loss: 0.7065 - cls_loss: 0.4660 - box_loss: 0.0048 - reg_l2_loss: 0.0637 - loss: 0.7702 - learning_rate: 0.0047 - gradient_norm: 2.4108 - val_det_loss: 0.9075 - val_cls_loss: 0.5840 - val_box_loss: 0.0065 - val_reg_l2_loss: 0.0637 - val_loss: 0.9712
Epoch 27/50
21/21 [==============================] - 7s 365ms/step - det_loss: 0.7179 - cls_loss: 0.4606 - box_loss: 0.0051 - reg_l2_loss: 0.0637 - loss: 0.7815 - learning_rate: 0.0044 - gradient_norm: 2.3896 - val_det_loss: 0.9088 - val_cls_loss: 0.5873 - val_box_loss: 0.0064 - val_reg_l2_loss: 0.0637 - val_loss: 0.9725
Epoch 28/50
21/21 [==============================] - 8s 379ms/step - det_loss: 0.7040 - cls_loss: 0.4654 - box_loss: 0.0048 - reg_l2_loss: 0.0637 - loss: 0.7677 - learning_rate: 0.0040 - gradient_norm: 2.4966 - val_det_loss: 0.8611 - val_cls_loss: 0.5596 - val_box_loss: 0.0060 - val_reg_l2_loss: 0.0637 - val_loss: 0.9247
Epoch 29/50
21/21 [==============================] - 7s 365ms/step - det_loss: 0.6524 - cls_loss: 0.4326 - box_loss: 0.0044 - reg_l2_loss: 0.0637 - loss: 0.7160 - learning_rate: 0.0037 - gradient_norm: 2.0710 - val_det_loss: 0.8648 - val_cls_loss: 0.5603 - val_box_loss: 0.0061 - val_reg_l2_loss: 0.0637 - val_loss: 0.9284
Epoch 30/50
21/21 [==============================] - 8s 358ms/step - det_loss: 0.6881 - cls_loss: 0.4439 - box_loss: 0.0049 - reg_l2_loss: 0.0637 - loss: 0.7518 - learning_rate: 0.0034 - gradient_norm: 2.3615 - val_det_loss: 0.8631 - val_cls_loss: 0.5599 - val_box_loss: 0.0061 - val_reg_l2_loss: 0.0637 - val_loss: 0.9268
Epoch 31/50
21/21 [==============================] - 8s 376ms/step - det_loss: 0.7087 - cls_loss: 0.4513 - box_loss: 0.0051 - reg_l2_loss: 0.0637 - loss: 0.7724 - learning_rate: 0.0031 - gradient_norm: 2.5183 - val_det_loss: 0.8697 - val_cls_loss: 0.5593 - val_box_loss: 0.0062 - val_reg_l2_loss: 0.0637 - val_loss: 0.9334
Epoch 32/50
21/21 [==============================] - 8s 402ms/step - det_loss: 0.6819 - cls_loss: 0.4426 - box_loss: 0.0048 - reg_l2_loss: 0.0637 - loss: 0.7456 - learning_rate: 0.0028 - gradient_norm: 2.4280 - val_det_loss: 0.8518 - val_cls_loss: 0.5504 - val_box_loss: 0.0060 - val_reg_l2_loss: 0.0637 - val_loss: 0.9155
Epoch 33/50
21/21 [==============================] - 9s 424ms/step - det_loss: 0.6640 - cls_loss: 0.4377 - box_loss: 0.0045 - reg_l2_loss: 0.0637 - loss: 0.7276 - learning_rate: 0.0025 - gradient_norm: 2.4404 - val_det_loss: 0.8487 - val_cls_loss: 0.5501 - val_box_loss: 0.0060 - val_reg_l2_loss: 0.0637 - val_loss: 0.9123
Epoch 34/50
21/21 [==============================] - 8s 368ms/step - det_loss: 0.6701 - cls_loss: 0.4409 - box_loss: 0.0046 - reg_l2_loss: 0.0637 - loss: 0.7338 - learning_rate: 0.0023 - gradient_norm: 2.5033 - val_det_loss: 0.8439 - val_cls_loss: 0.5463 - val_box_loss: 0.0060 - val_reg_l2_loss: 0.0637 - val_loss: 0.9075
Epoch 35/50
21/21 [==============================] - 8s 410ms/step - det_loss: 0.6696 - cls_loss: 0.4383 - box_loss: 0.0046 - reg_l2_loss: 0.0637 - loss: 0.7333 - learning_rate: 0.0020 - gradient_norm: 2.5512 - val_det_loss: 0.8672 - val_cls_loss: 0.5647 - val_box_loss: 0.0061 - val_reg_l2_loss: 0.0637 - val_loss: 0.9309
Epoch 36/50
21/21 [==============================] - 9s 423ms/step - det_loss: 0.6753 - cls_loss: 0.4385 - box_loss: 0.0047 - reg_l2_loss: 0.0637 - loss: 0.7389 - learning_rate: 0.0018 - gradient_norm: 2.5067 - val_det_loss: 0.8682 - val_cls_loss: 0.5699 - val_box_loss: 0.0060 - val_reg_l2_loss: 0.0637 - val_loss: 0.9318
Epoch 37/50
21/21 [==============================] - 7s 346ms/step - det_loss: 0.6479 - cls_loss: 0.4247 - box_loss: 0.0045 - reg_l2_loss: 0.0637 - loss: 0.7116 - learning_rate: 0.0015 - gradient_norm: 2.5669 - val_det_loss: 0.8547 - val_cls_loss: 0.5576 - val_box_loss: 0.0059 - val_reg_l2_loss: 0.0637 - val_loss: 0.9184
Epoch 38/50
21/21 [==============================] - 8s 380ms/step - det_loss: 0.6208 - cls_loss: 0.4119 - box_loss: 0.0042 - reg_l2_loss: 0.0637 - loss: 0.6844 - learning_rate: 0.0013 - gradient_norm: 2.3728 - val_det_loss: 0.8532 - val_cls_loss: 0.5541 - val_box_loss: 0.0060 - val_reg_l2_loss: 0.0637 - val_loss: 0.9169
Epoch 39/50
21/21 [==============================] - 8s 388ms/step - det_loss: 0.6322 - cls_loss: 0.4176 - box_loss: 0.0043 - reg_l2_loss: 0.0637 - loss: 0.6959 - learning_rate: 0.0011 - gradient_norm: 2.3884 - val_det_loss: 0.8623 - val_cls_loss: 0.5595 - val_box_loss: 0.0061 - val_reg_l2_loss: 0.0637 - val_loss: 0.9260
Epoch 40/50
21/21 [==============================] - 8s 380ms/step - det_loss: 0.6415 - cls_loss: 0.4180 - box_loss: 0.0045 - reg_l2_loss: 0.0637 - loss: 0.7052 - learning_rate: 9.0029e-04 - gradient_norm: 2.4224 - val_det_loss: 0.8597 - val_cls_loss: 0.5573 - val_box_loss: 0.0060 - val_reg_l2_loss: 0.0637 - val_loss: 0.9234
Epoch 41/50
21/21 [==============================] - 8s 400ms/step - det_loss: 0.6584 - cls_loss: 0.4235 - box_loss: 0.0047 - reg_l2_loss: 0.0637 - loss: 0.7220 - learning_rate: 7.2543e-04 - gradient_norm: 2.4889 - val_det_loss: 0.8523 - val_cls_loss: 0.5513 - val_box_loss: 0.0060 - val_reg_l2_loss: 0.0637 - val_loss: 0.9159
Epoch 42/50
21/21 [==============================] - 8s 408ms/step - det_loss: 0.6399 - cls_loss: 0.4172 - box_loss: 0.0045 - reg_l2_loss: 0.0637 - loss: 0.7036 - learning_rate: 5.6814e-04 - gradient_norm: 2.2832 - val_det_loss: 0.8451 - val_cls_loss: 0.5454 - val_box_loss: 0.0060 - val_reg_l2_loss: 0.0637 - val_loss: 0.9088
Epoch 43/50
21/21 [==============================] - 7s 361ms/step - det_loss: 0.6460 - cls_loss: 0.4275 - box_loss: 0.0044 - reg_l2_loss: 0.0637 - loss: 0.7097 - learning_rate: 4.2906e-04 - gradient_norm: 2.4440 - val_det_loss: 0.8473 - val_cls_loss: 0.5473 - val_box_loss: 0.0060 - val_reg_l2_loss: 0.0637 - val_loss: 0.9110
Epoch 44/50
21/21 [==============================] - 8s 379ms/step - det_loss: 0.6661 - cls_loss: 0.4317 - box_loss: 0.0047 - reg_l2_loss: 0.0637 - loss: 0.7298 - learning_rate: 3.0876e-04 - gradient_norm: 2.4835 - val_det_loss: 0.8467 - val_cls_loss: 0.5464 - val_box_loss: 0.0060 - val_reg_l2_loss: 0.0637 - val_loss: 0.9103
Epoch 45/50
21/21 [==============================] - 8s 408ms/step - det_loss: 0.6403 - cls_loss: 0.4304 - box_loss: 0.0042 - reg_l2_loss: 0.0637 - loss: 0.7040 - learning_rate: 2.0774e-04 - gradient_norm: 2.6497 - val_det_loss: 0.8475 - val_cls_loss: 0.5465 - val_box_loss: 0.0060 - val_reg_l2_loss: 0.0637 - val_loss: 0.9112
Epoch 46/50
21/21 [==============================] - 8s 384ms/step - det_loss: 0.6277 - cls_loss: 0.4124 - box_loss: 0.0043 - reg_l2_loss: 0.0637 - loss: 0.6913 - learning_rate: 1.2641e-04 - gradient_norm: 2.3634 - val_det_loss: 0.8471 - val_cls_loss: 0.5463 - val_box_loss: 0.0060 - val_reg_l2_loss: 0.0637 - val_loss: 0.9108
Epoch 47/50
21/21 [==============================] - 8s 371ms/step - det_loss: 0.6458 - cls_loss: 0.4292 - box_loss: 0.0043 - reg_l2_loss: 0.0637 - loss: 0.7094 - learning_rate: 6.5107e-05 - gradient_norm: 2.5238 - val_det_loss: 0.8461 - val_cls_loss: 0.5455 - val_box_loss: 0.0060 - val_reg_l2_loss: 0.0637 - val_loss: 0.9098
Epoch 48/50
21/21 [==============================] - 7s 356ms/step - det_loss: 0.6279 - cls_loss: 0.4131 - box_loss: 0.0043 - reg_l2_loss: 0.0637 - loss: 0.6915 - learning_rate: 2.4083e-05 - gradient_norm: 2.3091 - val_det_loss: 0.8457 - val_cls_loss: 0.5453 - val_box_loss: 0.0060 - val_reg_l2_loss: 0.0637 - val_loss: 0.9094
Epoch 49/50
21/21 [==============================] - 9s 426ms/step - det_loss: 0.6504 - cls_loss: 0.4219 - box_loss: 0.0046 - reg_l2_loss: 0.0637 - loss: 0.7140 - learning_rate: 3.5074e-06 - gradient_norm: 2.5416 - val_det_loss: 0.8445 - val_cls_loss: 0.5439 - val_box_loss: 0.0060 - val_reg_l2_loss: 0.0637 - val_loss: 0.9082
Epoch 50/50
21/21 [==============================] - 8s 396ms/step - det_loss: 0.6351 - cls_loss: 0.4163 - box_loss: 0.0044 - reg_l2_loss: 0.0637 - loss: 0.6988 - learning_rate: 3.4629e-06 - gradient_norm: 2.3083 - val_det_loss: 0.8438 - val_cls_loss: 0.5434 - val_box_loss: 0.0060 - val_reg_l2_loss: 0.0637 - val_loss: 0.9075

Step 4. Evaluate the model with the test data.

After training the object detection model using the images in the training dataset, use the remaining 25 images in the test dataset to evaluate how the model performs against new data it has never seen before.

As the default batch size is 64, it will take 1 step to go through the 25 images in the test dataset.

The evaluation metrics are same as COCO.

model.evaluate(test_data)
1/1 [==============================] - 6s 6s/step
{'AP': 0.2114988,
 'AP50': 0.3486598,
 'AP75': 0.24027638,
 'APs': -1.0,
 'APm': 0.43069783,
 'APl': 0.21045895,
 'ARmax1': 0.16639706,
 'ARmax10': 0.34017715,
 'ARmax100': 0.37929925,
 'ARs': -1.0,
 'ARm': 0.6333333,
 'ARl': 0.37672424,
 'AP_/Baked Goods': 0.0052776425,
 'AP_/Salad': 0.6010458,
 'AP_/Cheese': 0.14969672,
 'AP_/Seafood': 0.029953174,
 'AP_/Tomato': 0.27152067}

Step 5. Export as a TensorFlow Lite model.

Export the trained object detection model to the TensorFlow Lite format by specifying which folder you want to export the quantized model to. The default post-training quantization technique is full integer quantization.

model.export(export_dir='.')

Step 6. Evaluate the TensorFlow Lite model.

Several factors can affect the model accuracy when exporting to TFLite:

  • Quantization helps shrinking the model size by 4 times at the expense of some accuracy drop.
  • The original TensorFlow model uses per-class non-max supression (NMS) for post-processing, while the TFLite model uses global NMS that's much faster but less accurate. Keras outputs maximum 100 detections while tflite outputs maximum 25 detections.

Therefore you'll have to evaluate the exported TFLite model and compare its accuracy with the original TensorFlow model.

model.evaluate_tflite('model.tflite', test_data)
25/25 [==============================] - 57s 2s/step
{'AP': 0.18904369,
 'AP50': 0.3112651,
 'AP75': 0.21008497,
 'APs': -1.0,
 'APm': 0.3943723,
 'APl': 0.18786135,
 'ARmax1': 0.14203988,
 'ARmax10': 0.25574532,
 'ARmax100': 0.26657864,
 'ARs': -1.0,
 'ARm': 0.46666667,
 'ARl': 0.26415756,
 'AP_/Baked Goods': 0.0,
 'AP_/Salad': 0.56116146,
 'AP_/Cheese': 0.13825482,
 'AP_/Seafood': 0.0015808303,
 'AP_/Tomato': 0.24422134}

You can download the TensorFlow Lite model file using the left sidebar of Colab. Right-click on the model.tflite file and choose Download to download it to your local computer.

This model can be integrated into an Android or an iOS app using the ObjectDetector API of the TensorFlow Lite Task Library.

See the TFLite Object Detection sample app for more details on how the model is used in an working app.

(Optional) Test the TFLite model on your image

You can test the trained TFLite model using images from the internet.

  • Replace the INPUT_IMAGE_URL below with your desired input image.
  • Adjust the DETECTION_THRESHOLD to change the sensitivity of the model. A lower threshold means the model will pickup more objects but there will also be more false detection. Meanwhile, a higher threshold means the model will only pickup objects that it has confidently detected.

Although it requires some of boilerplate code to run the model in Python at this moment, integrating the model into a mobile app only requires a few lines of code.

Load the trained TFLite model and define some visualization functions

Run object detection and show the detection results

png

(Optional) Compile For the Edge TPU

Now that you have a quantized EfficientDet Lite model, it is possible to compile and deploy to a Coral EdgeTPU.

Step 1. Install the EdgeTPU Compiler

 curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -

 echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list

 sudo apt-get update

 sudo apt-get install edgetpu-compiler
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  2537  100  2537    0     0   145k      0 --:--:-- --:--:-- --:--:--  145k
OK
deb https://packages.cloud.google.com/apt coral-edgetpu-stable main
Hit:1 http://asia-east1.gce.archive.ubuntu.com/ubuntu bionic InRelease
Get:2 http://asia-east1.gce.archive.ubuntu.com/ubuntu bionic-updates InRelease [88.7 kB]
Get:3 http://asia-east1.gce.archive.ubuntu.com/ubuntu bionic-backports InRelease [74.6 kB]
Hit:4 https://nvidia.github.io/libnvidia-container/stable/ubuntu18.04/amd64  InRelease
Hit:5 https://nvidia.github.io/nvidia-container-runtime/ubuntu18.04/amd64  InRelease
Hit:6 https://nvidia.github.io/nvidia-docker/ubuntu18.04/amd64  InRelease
Ign:7 http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64  InRelease
Hit:8 http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64  Release
Get:9 http://security.ubuntu.com/ubuntu bionic-security InRelease [88.7 kB]
Hit:10 http://archive.canonical.com/ubuntu bionic InRelease
Get:11 http://packages.cloud.google.com/apt google-cloud-logging-wheezy InRelease [5483 B]
Get:13 https://packages.cloud.google.com/apt coral-edgetpu-stable InRelease [6722 B]
Get:14 https://packages.cloud.google.com/apt eip-cloud-bionic InRelease [5419 B]
Get:15 https://packages.cloud.google.com/apt coral-edgetpu-stable/main amd64 Packages [2174 B]
Fetched 261 kB in 1s (246 kB/s)




The following packages were automatically installed and are no longer required:
  linux-gcp-5.4-headers-5.4.0-1025 linux-headers-5.4.0-1025-gcp
  linux-image-5.4.0-1025-gcp linux-modules-5.4.0-1025-gcp
  linux-modules-extra-5.4.0-1025-gcp
Use 'sudo apt autoremove' to remove them.
The following NEW packages will be installed:
  edgetpu-compiler
0 upgraded, 1 newly installed, 0 to remove and 113 not upgraded.
Need to get 7865 kB of archives.
After this operation, 31.2 MB of additional disk space will be used.
Get:1 https://packages.cloud.google.com/apt coral-edgetpu-stable/main amd64 edgetpu-compiler amd64 15.0 [7865 kB]
Fetched 7865 kB in 1s (10.9 MB/s)
Selecting previously unselected package edgetpu-compiler.
(Reading database ... 228679 files and directories currently installed.)
Preparing to unpack .../edgetpu-compiler_15.0_amd64.deb ...
Unpacking edgetpu-compiler (15.0) ...
Setting up edgetpu-compiler (15.0) ...
Processing triggers for libc-bin (2.27-3ubuntu1.2) ...

Step 2. Select number of Edge TPUs, Compile

The EdgeTPU has 8MB of SRAM for caching model paramaters (more info). This means that for models that are larger than 8MB, inference time will be increased in order to transfer over model paramaters. One way to avoid this is Model Pipelining - splitting the model into segments that can have a dedicated EdgeTPU. This can significantly improve latency.

The below table can be used as a reference for the number of Edge TPUs to use - the larger models will not compile for a single TPU as the intermediate tensors can't fit in on-chip memory.

Model architecture Minimum TPUs Recommended TPUs
EfficientDet-Lite0 1 1
EfficientDet-Lite1 1 1
EfficientDet-Lite2 1 2
EfficientDet-Lite3 2 2
EfficientDet-Lite4 2 3

Edge TPU Compiler version 15.0.340273435

Model compiled successfully in 3516 ms.

Input model: model.tflite
Input size: 4.22MiB
Output model: model_edgetpu.tflite
Output size: 5.62MiB
On-chip memory used for caching model parameters: 4.25MiB
On-chip memory remaining for caching model parameters: 3.38MiB
Off-chip memory used for streaming uncached model parameters: 0.00B
Number of Edge TPU subgraphs: 1
Total number of operations: 267
Operation log: model_edgetpu.log

Model successfully compiled but not all operations are supported by the Edge TPU. A percentage of the model will instead run on the CPU, which is slower. If possible, consider updating your model to use only operations supported by the Edge TPU. For details, visit g.co/coral/model-reqs.
Number of operations that will run on Edge TPU: 264
Number of operations that will run on CPU: 3
See the operation log file for individual operation details.

Step 3. Download, Run Model

With the model(s) compiled, they can now be run on EdgeTPU(s) for object detection. First, download the compiled TensorFlow Lite model file using the left sidebar of Colab. Right-click on the model_edgetpu.tflite file and choose Download to download it to your local computer.

Now you can run the model in your preferred manner. Examples of detection include:

Advanced Usage

This section covers advanced usage topics like adjusting the model and the training hyperparameters.

Load the dataset

Load your own data

You can upload your own dataset to work through this tutorial. Upload your dataset by using the left sidebar in Colab.

Upload File

If you prefer not to upload your dataset to the cloud, you can also locally run the library by following the guide.

Load your data with a different data format

The Model Maker library also supports the object_detector.DataLoader.from_pascal_voc method to load data with PASCAL VOC format. makesense.ai and LabelImg are the tools that can annotate the image and save annotations as XML files in PASCAL VOC data format:

object_detector.DataLoader.from_pascal_voc(image_dir, annotations_dir, label_map={1: "person", 2: "notperson"})

Customize the EfficientDet model hyperparameters

The model and training pipline parameters you can adjust are:

  • model_dir: The location to save the model checkpoint files. If not set, a temporary directory will be used.
  • steps_per_execution: Number of steps per training execution.
  • moving_average_decay: Float. The decay to use for maintaining moving averages of the trained parameters.
  • var_freeze_expr: The regular expression to map the prefix name of variables to be frozen which means remaining the same during training. More specific, use re.match(var_freeze_expr, variable_name) in the codebase to map the variables to be frozen.
  • tflite_max_detections: integer, 25 by default. The max number of output detections in the TFLite model.
  • strategy: A string specifying which distribution strategy to use. Accepted values are 'tpu', 'gpus', None. tpu' means to use TPUStrategy. 'gpus' mean to use MirroredStrategy for multi-gpus. If None, use TF default with OneDeviceStrategy.
  • tpu: The Cloud TPU to use for training. This should be either the name used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 url.
  • use_xla: Use XLA even if strategy is not tpu. If strategy is tpu, always use XLA, and this flag has no effect.
  • profile: Enable profile mode.
  • debug: Enable debug mode.

Other parameters that can be adjusted is shown in hparams_config.py.

For instance, you can set the var_freeze_expr='efficientnet' which freezes the variables with name prefix efficientnet (default is '(efficientnet|fpn_cells|resample_p6)'). This allows the model to freeze untrainable variables and keep their value the same through training.

spec = model_spec.get('efficientdet-lite0')
spec.config.var_freeze_expr = 'efficientnet'

Change the Model Architecture

You can change the model architecture by changing the model_spec. For instance, change the model_spec to the EfficientDet-Lite4 model.

spec = model_spec.get('efficientdet-lite4')

Tune the training hyperparameters

The create function is the driver function that the Model Maker library uses to create models. The model_spec parameter defines the model specification. The object_detector.EfficientDetSpec class is currently supported. The create function comprises of the following steps:

  1. Creates the model for the object detection according to model_spec.
  2. Trains the model. The default epochs and the default batch size are set by the epochs and batch_size variables in the model_spec object. You can also tune the training hyperparameters like epochs and batch_size that affect the model accuracy. For instance,
  • epochs: Integer, 50 by default. More epochs could achieve better accuracy, but may lead to overfitting.
  • batch_size: Integer, 64 by default. The number of samples to use in one training step.
  • train_whole_model: Boolean, False by default. If true, train the whole model. Otherwise, only train the layers that do not match var_freeze_expr.

For example, you can train with less epochs and only the head layer. You can increase the number of epochs for better results.

model = object_detector.create(train_data, model_spec=spec, epochs=10, validation_data=validation_data)

Export to different formats

The export formats can be one or a list of the following:

By default, it exports only the TensorFlow Lite model file containing the model metadata so that you can later use in an on-device ML application. The label file is embedded in metadata.

In many on-device ML application, the model size is an important factor. Therefore, it is recommended that you quantize the model to make it smaller and potentially run faster. As for EfficientDet-Lite models, full integer quantization is used to quantize the model by default. Please refer to Post-training quantization for more detail.

model.export(export_dir='.')

You can also choose to export other files related to the model for better examination. For instance, exporting both the saved model and the label file as follows:

model.export(export_dir='.', export_format=[ExportFormat.SAVED_MODEL, ExportFormat.LABEL])

Customize Post-training quantization on the TensorFlow Lite model

Post-training quantization is a conversion technique that can reduce model size and inference latency, while also improving CPU and hardware accelerator inference speed, with a little degradation in model accuracy. Thus, it's widely used to optimize the model.

Model Maker library applies a default post-training quantization techique when exporting the model. If you want to customize post-training quantization, Model Maker supports multiple post-training quantization options using QuantizationConfig as well. Let's take float16 quantization as an instance. First, define the quantization config.

config = QuantizationConfig.for_float16()

Then we export the TensorFlow Lite model with such configuration.

model.export(export_dir='.', tflite_filename='model_fp16.tflite', quantization_config=config)

Read more

You can read our object detection example to learn technical details. For more information, please refer to: