Object Detection with TensorFlow Lite Model Maker

Stay organized with collections Save and categorize content based on your preferences.

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.

sudo apt -y install libportaudio2
pip install -q --use-deprecated=legacy-resolver tflite-model-maker
pip install -q pycocotools
pip install -q opencv-python-headless==4.1.2.30
pip uninstall -y tensorflow && pip install -q tensorflow==2.8.0

Import the required packages.

import numpy as np
import os

from tflite_model_maker.config import QuantizationConfig
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)

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 [==============================] - 39s 411ms/step - det_loss: 1.7474 - cls_loss: 1.1230 - box_loss: 0.0125 - reg_l2_loss: 0.0636 - loss: 1.8110 - learning_rate: 0.0090 - gradient_norm: 0.7739 - val_det_loss: 1.6462 - val_cls_loss: 1.0971 - val_box_loss: 0.0110 - val_reg_l2_loss: 0.0636 - val_loss: 1.7097
Epoch 2/50
21/21 [==============================] - 5s 260ms/step - det_loss: 1.6174 - cls_loss: 1.0661 - box_loss: 0.0110 - reg_l2_loss: 0.0636 - loss: 1.6809 - learning_rate: 0.0100 - gradient_norm: 0.9871 - val_det_loss: 1.4184 - val_cls_loss: 0.9289 - val_box_loss: 0.0098 - val_reg_l2_loss: 0.0636 - val_loss: 1.4820
Epoch 3/50
21/21 [==============================] - 6s 278ms/step - det_loss: 1.4344 - cls_loss: 0.9374 - box_loss: 0.0099 - reg_l2_loss: 0.0636 - loss: 1.4980 - learning_rate: 0.0099 - gradient_norm: 1.4651 - val_det_loss: 1.4533 - val_cls_loss: 0.9994 - val_box_loss: 0.0091 - val_reg_l2_loss: 0.0636 - val_loss: 1.5169
Epoch 4/50
21/21 [==============================] - 6s 304ms/step - det_loss: 1.2824 - cls_loss: 0.8220 - box_loss: 0.0092 - reg_l2_loss: 0.0636 - loss: 1.3460 - learning_rate: 0.0099 - gradient_norm: 1.9227 - val_det_loss: 1.1660 - val_cls_loss: 0.7516 - val_box_loss: 0.0083 - val_reg_l2_loss: 0.0636 - val_loss: 1.2296
Epoch 5/50
21/21 [==============================] - 11s 557ms/step - det_loss: 1.1825 - cls_loss: 0.7559 - box_loss: 0.0085 - reg_l2_loss: 0.0636 - loss: 1.2461 - learning_rate: 0.0098 - gradient_norm: 1.6779 - val_det_loss: 1.0084 - val_cls_loss: 0.6182 - val_box_loss: 0.0078 - val_reg_l2_loss: 0.0636 - val_loss: 1.0720
Epoch 6/50
21/21 [==============================] - 6s 270ms/step - det_loss: 1.0722 - cls_loss: 0.6779 - box_loss: 0.0079 - reg_l2_loss: 0.0636 - loss: 1.1358 - learning_rate: 0.0097 - gradient_norm: 1.7327 - val_det_loss: 0.9644 - val_cls_loss: 0.5949 - val_box_loss: 0.0074 - val_reg_l2_loss: 0.0636 - val_loss: 1.0280
Epoch 7/50
21/21 [==============================] - 6s 309ms/step - det_loss: 1.0469 - cls_loss: 0.6601 - box_loss: 0.0077 - reg_l2_loss: 0.0636 - loss: 1.1105 - learning_rate: 0.0096 - gradient_norm: 1.8121 - val_det_loss: 0.9382 - val_cls_loss: 0.6045 - val_box_loss: 0.0067 - val_reg_l2_loss: 0.0636 - val_loss: 1.0018
Epoch 8/50
21/21 [==============================] - 6s 284ms/step - det_loss: 0.9855 - cls_loss: 0.6321 - box_loss: 0.0071 - reg_l2_loss: 0.0636 - loss: 1.0491 - learning_rate: 0.0094 - gradient_norm: 1.7325 - val_det_loss: 0.8654 - val_cls_loss: 0.5543 - val_box_loss: 0.0062 - val_reg_l2_loss: 0.0636 - val_loss: 0.9290
Epoch 9/50
21/21 [==============================] - 6s 281ms/step - det_loss: 0.9660 - cls_loss: 0.6040 - box_loss: 0.0072 - reg_l2_loss: 0.0636 - loss: 1.0296 - learning_rate: 0.0093 - gradient_norm: 1.8016 - val_det_loss: 0.8423 - val_cls_loss: 0.5172 - val_box_loss: 0.0065 - val_reg_l2_loss: 0.0636 - val_loss: 0.9059
Epoch 10/50
21/21 [==============================] - 7s 361ms/step - det_loss: 0.9223 - cls_loss: 0.5949 - box_loss: 0.0065 - reg_l2_loss: 0.0636 - loss: 0.9859 - learning_rate: 0.0091 - gradient_norm: 2.0456 - val_det_loss: 0.7967 - val_cls_loss: 0.5104 - val_box_loss: 0.0057 - val_reg_l2_loss: 0.0636 - val_loss: 0.8603
Epoch 11/50
21/21 [==============================] - 6s 294ms/step - det_loss: 0.8890 - cls_loss: 0.5605 - box_loss: 0.0066 - reg_l2_loss: 0.0636 - loss: 0.9527 - learning_rate: 0.0089 - gradient_norm: 2.0081 - val_det_loss: 0.7756 - val_cls_loss: 0.4909 - val_box_loss: 0.0057 - val_reg_l2_loss: 0.0636 - val_loss: 0.8392
Epoch 12/50
21/21 [==============================] - 6s 270ms/step - det_loss: 0.8618 - cls_loss: 0.5572 - box_loss: 0.0061 - reg_l2_loss: 0.0636 - loss: 0.9255 - learning_rate: 0.0087 - gradient_norm: 2.1186 - val_det_loss: 0.7889 - val_cls_loss: 0.5104 - val_box_loss: 0.0056 - val_reg_l2_loss: 0.0637 - val_loss: 0.8525
Epoch 13/50
21/21 [==============================] - 6s 281ms/step - det_loss: 0.8360 - cls_loss: 0.5445 - box_loss: 0.0058 - reg_l2_loss: 0.0637 - loss: 0.8997 - learning_rate: 0.0085 - gradient_norm: 2.1580 - val_det_loss: 0.8405 - val_cls_loss: 0.5270 - val_box_loss: 0.0063 - val_reg_l2_loss: 0.0637 - val_loss: 0.9042
Epoch 14/50
21/21 [==============================] - 6s 270ms/step - det_loss: 0.8477 - cls_loss: 0.5437 - box_loss: 0.0061 - reg_l2_loss: 0.0637 - loss: 0.9114 - learning_rate: 0.0082 - gradient_norm: 2.2634 - val_det_loss: 0.7654 - val_cls_loss: 0.4897 - val_box_loss: 0.0055 - val_reg_l2_loss: 0.0637 - val_loss: 0.8291
Epoch 15/50
21/21 [==============================] - 7s 360ms/step - det_loss: 0.8286 - cls_loss: 0.5213 - box_loss: 0.0061 - reg_l2_loss: 0.0637 - loss: 0.8922 - learning_rate: 0.0080 - gradient_norm: 2.3564 - val_det_loss: 0.8308 - val_cls_loss: 0.5487 - val_box_loss: 0.0056 - val_reg_l2_loss: 0.0637 - val_loss: 0.8944
Epoch 16/50
21/21 [==============================] - 6s 302ms/step - det_loss: 0.7976 - cls_loss: 0.5172 - box_loss: 0.0056 - reg_l2_loss: 0.0637 - loss: 0.8612 - learning_rate: 0.0077 - gradient_norm: 2.2103 - val_det_loss: 0.8538 - val_cls_loss: 0.5852 - val_box_loss: 0.0054 - val_reg_l2_loss: 0.0637 - val_loss: 0.9175
Epoch 17/50
21/21 [==============================] - 6s 274ms/step - det_loss: 0.7706 - cls_loss: 0.5079 - box_loss: 0.0053 - reg_l2_loss: 0.0637 - loss: 0.8343 - learning_rate: 0.0075 - gradient_norm: 2.2552 - val_det_loss: 0.8851 - val_cls_loss: 0.6183 - val_box_loss: 0.0053 - val_reg_l2_loss: 0.0637 - val_loss: 0.9488
Epoch 18/50
21/21 [==============================] - 6s 276ms/step - det_loss: 0.8076 - cls_loss: 0.5208 - box_loss: 0.0057 - reg_l2_loss: 0.0637 - loss: 0.8713 - learning_rate: 0.0072 - gradient_norm: 2.4394 - val_det_loss: 0.8797 - val_cls_loss: 0.6179 - val_box_loss: 0.0052 - val_reg_l2_loss: 0.0637 - val_loss: 0.9434
Epoch 19/50
21/21 [==============================] - 6s 286ms/step - det_loss: 0.7703 - cls_loss: 0.5002 - box_loss: 0.0054 - reg_l2_loss: 0.0637 - loss: 0.8341 - learning_rate: 0.0069 - gradient_norm: 2.3424 - val_det_loss: 0.8236 - val_cls_loss: 0.5766 - val_box_loss: 0.0049 - val_reg_l2_loss: 0.0637 - val_loss: 0.8873
Epoch 20/50
21/21 [==============================] - 8s 379ms/step - det_loss: 0.7465 - cls_loss: 0.4885 - box_loss: 0.0052 - reg_l2_loss: 0.0637 - loss: 0.8102 - learning_rate: 0.0066 - gradient_norm: 2.3388 - val_det_loss: 0.8089 - val_cls_loss: 0.5640 - val_box_loss: 0.0049 - val_reg_l2_loss: 0.0637 - val_loss: 0.8726
Epoch 21/50
21/21 [==============================] - 6s 274ms/step - det_loss: 0.7533 - cls_loss: 0.4860 - box_loss: 0.0053 - reg_l2_loss: 0.0637 - loss: 0.8170 - learning_rate: 0.0063 - gradient_norm: 2.3445 - val_det_loss: 0.8491 - val_cls_loss: 0.6045 - val_box_loss: 0.0049 - val_reg_l2_loss: 0.0637 - val_loss: 0.9128
Epoch 22/50
21/21 [==============================] - 6s 278ms/step - det_loss: 0.7106 - cls_loss: 0.4632 - box_loss: 0.0049 - reg_l2_loss: 0.0637 - loss: 0.7743 - learning_rate: 0.0060 - gradient_norm: 2.1750 - val_det_loss: 0.8053 - val_cls_loss: 0.5558 - val_box_loss: 0.0050 - val_reg_l2_loss: 0.0637 - val_loss: 0.8691
Epoch 23/50
21/21 [==============================] - 6s 272ms/step - det_loss: 0.7691 - cls_loss: 0.4855 - box_loss: 0.0057 - reg_l2_loss: 0.0637 - loss: 0.8329 - learning_rate: 0.0056 - gradient_norm: 2.5518 - val_det_loss: 0.8131 - val_cls_loss: 0.5676 - val_box_loss: 0.0049 - val_reg_l2_loss: 0.0637 - val_loss: 0.8768
Epoch 24/50
21/21 [==============================] - 6s 286ms/step - det_loss: 0.7229 - cls_loss: 0.4620 - box_loss: 0.0052 - reg_l2_loss: 0.0637 - loss: 0.7866 - learning_rate: 0.0053 - gradient_norm: 2.2530 - val_det_loss: 0.8211 - val_cls_loss: 0.5679 - val_box_loss: 0.0051 - val_reg_l2_loss: 0.0637 - val_loss: 0.8849
Epoch 25/50
21/21 [==============================] - 8s 376ms/step - det_loss: 0.6963 - cls_loss: 0.4492 - box_loss: 0.0049 - reg_l2_loss: 0.0637 - loss: 0.7600 - learning_rate: 0.0050 - gradient_norm: 2.4535 - val_det_loss: 0.7693 - val_cls_loss: 0.5176 - val_box_loss: 0.0050 - val_reg_l2_loss: 0.0637 - val_loss: 0.8331
Epoch 26/50
21/21 [==============================] - 6s 271ms/step - det_loss: 0.6844 - cls_loss: 0.4433 - box_loss: 0.0048 - reg_l2_loss: 0.0637 - loss: 0.7482 - learning_rate: 0.0047 - gradient_norm: 2.3528 - val_det_loss: 0.7792 - val_cls_loss: 0.5273 - val_box_loss: 0.0050 - val_reg_l2_loss: 0.0637 - val_loss: 0.8429
Epoch 27/50
21/21 [==============================] - 6s 282ms/step - det_loss: 0.7140 - cls_loss: 0.4558 - box_loss: 0.0052 - reg_l2_loss: 0.0637 - loss: 0.7777 - learning_rate: 0.0044 - gradient_norm: 2.5400 - val_det_loss: 0.7805 - val_cls_loss: 0.5194 - val_box_loss: 0.0052 - val_reg_l2_loss: 0.0637 - val_loss: 0.8442
Epoch 28/50
21/21 [==============================] - 6s 269ms/step - det_loss: 0.6703 - cls_loss: 0.4275 - box_loss: 0.0049 - reg_l2_loss: 0.0637 - loss: 0.7340 - learning_rate: 0.0040 - gradient_norm: 2.3317 - val_det_loss: 0.7635 - val_cls_loss: 0.5019 - val_box_loss: 0.0052 - val_reg_l2_loss: 0.0637 - val_loss: 0.8272
Epoch 29/50
21/21 [==============================] - 6s 305ms/step - det_loss: 0.6881 - cls_loss: 0.4412 - box_loss: 0.0049 - reg_l2_loss: 0.0637 - loss: 0.7519 - learning_rate: 0.0037 - gradient_norm: 2.3190 - val_det_loss: 0.7683 - val_cls_loss: 0.5194 - val_box_loss: 0.0050 - val_reg_l2_loss: 0.0637 - val_loss: 0.8321
Epoch 30/50
21/21 [==============================] - 7s 355ms/step - det_loss: 0.6753 - cls_loss: 0.4349 - box_loss: 0.0048 - reg_l2_loss: 0.0637 - loss: 0.7391 - learning_rate: 0.0034 - gradient_norm: 2.2789 - val_det_loss: 0.7705 - val_cls_loss: 0.5250 - val_box_loss: 0.0049 - val_reg_l2_loss: 0.0637 - val_loss: 0.8342
Epoch 31/50
21/21 [==============================] - 6s 273ms/step - det_loss: 0.6595 - cls_loss: 0.4272 - box_loss: 0.0046 - reg_l2_loss: 0.0637 - loss: 0.7232 - learning_rate: 0.0031 - gradient_norm: 2.5181 - val_det_loss: 0.7610 - val_cls_loss: 0.5100 - val_box_loss: 0.0050 - val_reg_l2_loss: 0.0637 - val_loss: 0.8247
Epoch 32/50
21/21 [==============================] - 6s 273ms/step - det_loss: 0.6540 - cls_loss: 0.4265 - box_loss: 0.0045 - reg_l2_loss: 0.0637 - loss: 0.7177 - learning_rate: 0.0028 - gradient_norm: 2.5248 - val_det_loss: 0.7742 - val_cls_loss: 0.5282 - val_box_loss: 0.0049 - val_reg_l2_loss: 0.0637 - val_loss: 0.8379
Epoch 33/50
21/21 [==============================] - 6s 308ms/step - det_loss: 0.6674 - cls_loss: 0.4263 - box_loss: 0.0048 - reg_l2_loss: 0.0637 - loss: 0.7311 - learning_rate: 0.0025 - gradient_norm: 2.6202 - val_det_loss: 0.7477 - val_cls_loss: 0.5090 - val_box_loss: 0.0048 - val_reg_l2_loss: 0.0637 - val_loss: 0.8114
Epoch 34/50
21/21 [==============================] - 6s 268ms/step - det_loss: 0.6744 - cls_loss: 0.4346 - box_loss: 0.0048 - reg_l2_loss: 0.0637 - loss: 0.7381 - learning_rate: 0.0023 - gradient_norm: 2.6862 - val_det_loss: 0.7555 - val_cls_loss: 0.5166 - val_box_loss: 0.0048 - val_reg_l2_loss: 0.0637 - val_loss: 0.8192
Epoch 35/50
21/21 [==============================] - 7s 359ms/step - det_loss: 0.6377 - cls_loss: 0.4126 - box_loss: 0.0045 - reg_l2_loss: 0.0637 - loss: 0.7014 - learning_rate: 0.0020 - gradient_norm: 2.4512 - val_det_loss: 0.7457 - val_cls_loss: 0.5021 - val_box_loss: 0.0049 - val_reg_l2_loss: 0.0637 - val_loss: 0.8095
Epoch 36/50
21/21 [==============================] - 6s 270ms/step - det_loss: 0.6404 - cls_loss: 0.4157 - box_loss: 0.0045 - reg_l2_loss: 0.0637 - loss: 0.7041 - learning_rate: 0.0018 - gradient_norm: 2.5129 - val_det_loss: 0.7545 - val_cls_loss: 0.5155 - val_box_loss: 0.0048 - val_reg_l2_loss: 0.0637 - val_loss: 0.8182
Epoch 37/50
21/21 [==============================] - 6s 279ms/step - det_loss: 0.6266 - cls_loss: 0.4023 - box_loss: 0.0045 - reg_l2_loss: 0.0637 - loss: 0.6903 - learning_rate: 0.0015 - gradient_norm: 2.3309 - val_det_loss: 0.7742 - val_cls_loss: 0.5293 - val_box_loss: 0.0049 - val_reg_l2_loss: 0.0637 - val_loss: 0.8379
Epoch 38/50
21/21 [==============================] - 6s 301ms/step - det_loss: 0.6588 - cls_loss: 0.4288 - box_loss: 0.0046 - reg_l2_loss: 0.0637 - loss: 0.7226 - learning_rate: 0.0013 - gradient_norm: 2.8020 - val_det_loss: 0.7961 - val_cls_loss: 0.5488 - val_box_loss: 0.0049 - val_reg_l2_loss: 0.0637 - val_loss: 0.8599
Epoch 39/50
21/21 [==============================] - 6s 277ms/step - det_loss: 0.6357 - cls_loss: 0.4130 - box_loss: 0.0045 - reg_l2_loss: 0.0637 - loss: 0.6994 - learning_rate: 0.0011 - gradient_norm: 2.4735 - val_det_loss: 0.7927 - val_cls_loss: 0.5451 - val_box_loss: 0.0050 - val_reg_l2_loss: 0.0637 - val_loss: 0.8564
Epoch 40/50
21/21 [==============================] - 7s 354ms/step - det_loss: 0.6330 - cls_loss: 0.4147 - box_loss: 0.0044 - reg_l2_loss: 0.0637 - loss: 0.6967 - learning_rate: 9.0029e-04 - gradient_norm: 2.4874 - val_det_loss: 0.7649 - val_cls_loss: 0.5206 - val_box_loss: 0.0049 - val_reg_l2_loss: 0.0637 - val_loss: 0.8286
Epoch 41/50
21/21 [==============================] - 6s 273ms/step - det_loss: 0.6331 - cls_loss: 0.4094 - box_loss: 0.0045 - reg_l2_loss: 0.0637 - loss: 0.6969 - learning_rate: 7.2543e-04 - gradient_norm: 2.6845 - val_det_loss: 0.7517 - val_cls_loss: 0.5118 - val_box_loss: 0.0048 - val_reg_l2_loss: 0.0637 - val_loss: 0.8155
Epoch 42/50
21/21 [==============================] - 6s 301ms/step - det_loss: 0.6435 - cls_loss: 0.4194 - box_loss: 0.0045 - reg_l2_loss: 0.0637 - loss: 0.7072 - learning_rate: 5.6814e-04 - gradient_norm: 2.5931 - val_det_loss: 0.7419 - val_cls_loss: 0.5031 - val_box_loss: 0.0048 - val_reg_l2_loss: 0.0637 - val_loss: 0.8056
Epoch 43/50
21/21 [==============================] - 6s 275ms/step - det_loss: 0.6358 - cls_loss: 0.4138 - box_loss: 0.0044 - reg_l2_loss: 0.0637 - loss: 0.6995 - learning_rate: 4.2906e-04 - gradient_norm: 2.4804 - val_det_loss: 0.7372 - val_cls_loss: 0.4990 - val_box_loss: 0.0048 - val_reg_l2_loss: 0.0637 - val_loss: 0.8009
Epoch 44/50
21/21 [==============================] - 6s 276ms/step - det_loss: 0.6271 - cls_loss: 0.4072 - box_loss: 0.0044 - reg_l2_loss: 0.0637 - loss: 0.6908 - learning_rate: 3.0876e-04 - gradient_norm: 2.4583 - val_det_loss: 0.7439 - val_cls_loss: 0.5031 - val_box_loss: 0.0048 - val_reg_l2_loss: 0.0637 - val_loss: 0.8077
Epoch 45/50
21/21 [==============================] - 7s 359ms/step - det_loss: 0.6353 - cls_loss: 0.4102 - box_loss: 0.0045 - reg_l2_loss: 0.0637 - loss: 0.6990 - learning_rate: 2.0774e-04 - gradient_norm: 2.4107 - val_det_loss: 0.7475 - val_cls_loss: 0.5065 - val_box_loss: 0.0048 - val_reg_l2_loss: 0.0637 - val_loss: 0.8112
Epoch 46/50
21/21 [==============================] - 6s 270ms/step - det_loss: 0.6118 - cls_loss: 0.3956 - box_loss: 0.0043 - reg_l2_loss: 0.0637 - loss: 0.6756 - learning_rate: 1.2641e-04 - gradient_norm: 2.3690 - val_det_loss: 0.7505 - val_cls_loss: 0.5085 - val_box_loss: 0.0048 - val_reg_l2_loss: 0.0637 - val_loss: 0.8142
Epoch 47/50
21/21 [==============================] - 6s 304ms/step - det_loss: 0.6239 - cls_loss: 0.4037 - box_loss: 0.0044 - reg_l2_loss: 0.0637 - loss: 0.6876 - learning_rate: 6.5107e-05 - gradient_norm: 2.4299 - val_det_loss: 0.7515 - val_cls_loss: 0.5087 - val_box_loss: 0.0049 - val_reg_l2_loss: 0.0637 - val_loss: 0.8153
Epoch 48/50
21/21 [==============================] - 6s 277ms/step - det_loss: 0.6440 - cls_loss: 0.4056 - box_loss: 0.0048 - reg_l2_loss: 0.0637 - loss: 0.7078 - learning_rate: 2.4083e-05 - gradient_norm: 2.5349 - val_det_loss: 0.7503 - val_cls_loss: 0.5078 - val_box_loss: 0.0049 - val_reg_l2_loss: 0.0637 - val_loss: 0.8141
Epoch 49/50
21/21 [==============================] - 6s 287ms/step - det_loss: 0.6104 - cls_loss: 0.3960 - box_loss: 0.0043 - reg_l2_loss: 0.0637 - loss: 0.6742 - learning_rate: 3.5074e-06 - gradient_norm: 2.3248 - val_det_loss: 0.7493 - val_cls_loss: 0.5070 - val_box_loss: 0.0048 - val_reg_l2_loss: 0.0637 - val_loss: 0.8131
Epoch 50/50
21/21 [==============================] - 7s 358ms/step - det_loss: 0.6214 - cls_loss: 0.4005 - box_loss: 0.0044 - reg_l2_loss: 0.0637 - loss: 0.6851 - learning_rate: 3.4629e-06 - gradient_norm: 2.5412 - val_det_loss: 0.7503 - val_cls_loss: 0.5076 - val_box_loss: 0.0049 - val_reg_l2_loss: 0.0637 - val_loss: 0.8141

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.20845057,
 'AP50': 0.37540185,
 'AP75': 0.20855291,
 'APs': -1.0,
 'APm': 0.30805188,
 'APl': 0.20889984,
 'ARmax1': 0.1649688,
 'ARmax10': 0.33914995,
 'ARmax100': 0.37784314,
 'ARs': -1.0,
 'ARm': 0.56666666,
 'ARl': 0.3763778,
 'AP_/Baked Goods': 0.029884448,
 'AP_/Salad': 0.54471725,
 'AP_/Cheese': 0.15850565,
 'AP_/Seafood': 0.048377268,
 'AP_/Tomato': 0.26076823}

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='.')
2022-10-20 12:33:36.713625: W tensorflow/python/util/util.cc:368] Sets are not currently considered sequences, but this may change in the future, so consider avoiding using them.
2022-10-20 12:34:01.641602: W tensorflow/core/common_runtime/graph_constructor.cc:803] Node 'resample_p7/PartitionedCall' has 1 outputs but the _output_shapes attribute specifies shapes for 3 outputs. Output shapes may be inaccurate.
2022-10-20 12:34:08.818368: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:357] Ignored output_format.
2022-10-20 12:34:08.818417: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:360] Ignored drop_control_dependency.
fully_quantize: 0, inference_type: 6, input_inference_type: 3, output_inference_type: 0

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)
INFO: Created TensorFlow Lite XNNPACK delegate for CPU.
25/25 [==============================] - 58s 2s/step
{'AP': 0.19380261,
 'AP50': 0.34041777,
 'AP75': 0.20666121,
 'APs': -1.0,
 'APm': 0.27612534,
 'APl': 0.19353507,
 'ARmax1': 0.14393827,
 'ARmax10': 0.25257465,
 'ARmax100': 0.26978052,
 'ARs': -1.0,
 'ARm': 0.41666666,
 'ARl': 0.26798788,
 'AP_/Baked Goods': 0.0,
 'AP_/Salad': 0.52511317,
 'AP_/Cheese': 0.13282518,
 'AP_/Seafood': 0.06435644,
 'AP_/Tomato': 0.24671832}

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

/tmpfs/tmp/ipykernel_47917/1212634245.py:10: DeprecationWarning: ANTIALIAS is deprecated and will be removed in Pillow 10 (2023-07-01). Use Resampling.LANCZOS instead.
  im.thumbnail((512, 512), Image.ANTIALIAS)

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   154k      0 --:--:-- --:--:-- --:--:--  154k
OK
deb https://packages.cloud.google.com/apt coral-edgetpu-stable main
Hit:1 http://us-west1.gce.archive.ubuntu.com/ubuntu focal InRelease
Hit:2 http://us-west1.gce.archive.ubuntu.com/ubuntu focal-updates InRelease
Hit:3 http://us-west1.gce.archive.ubuntu.com/ubuntu focal-backports InRelease
Hit:4 https://nvidia.github.io/libnvidia-container/stable/ubuntu18.04/amd64  InRelease
Hit:5 https://download.docker.com/linux/ubuntu focal InRelease
Hit:6 https://nvidia.github.io/nvidia-container-runtime/stable/ubuntu18.04/amd64  InRelease
Hit:7 https://nvidia.github.io/nvidia-docker/ubuntu18.04/amd64  InRelease
Hit:8 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64  InRelease
Get:9 https://packages.cloud.google.com/apt coral-edgetpu-stable InRelease [6722 B]
Hit:10 https://apt.llvm.org/focal llvm-toolchain-focal-14 InRelease
Get:11 http://security.ubuntu.com/ubuntu focal-security InRelease [114 kB]
Hit:12 http://ppa.launchpad.net/deadsnakes/ppa/ubuntu focal InRelease
Hit:13 http://ppa.launchpad.net/longsleep/golang-backports/ubuntu focal InRelease
Hit:14 http://ppa.launchpad.net/openjdk-r/ppa/ubuntu focal InRelease
Get:15 https://packages.cloud.google.com/apt coral-edgetpu-stable/main amd64 Packages [2317 B]
Fetched 123 kB in 1s (85.7 kB/s)




The following packages were automatically installed and are no longer required:
  libatasmart4 libblockdev-fs2 libblockdev-loop2 libblockdev-part-err2
  libblockdev-part2 libblockdev-swap2 libblockdev-utils2 libblockdev2
  libparted-fs-resize0
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 47 not upgraded.
Need to get 7913 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 16.0 [7913 kB]
Fetched 7913 kB in 1s (8618 kB/s)
Selecting previously unselected package edgetpu-compiler.
(Reading database ... 140260 files and directories currently installed.)
Preparing to unpack .../edgetpu-compiler_16.0_amd64.deb ...
Unpacking edgetpu-compiler (16.0) ...
Setting up edgetpu-compiler (16.0) ...
Processing triggers for libc-bin (2.31-0ubuntu9.9) ...

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 16.0.384591198
Started a compilation timeout timer of 180 seconds.

Model compiled successfully in 4216 ms.

Input model: model.tflite
Input size: 4.24MiB
Output model: model_edgetpu.tflite
Output size: 5.61MiB
On-chip memory used for caching model parameters: 4.24MiB
On-chip memory remaining for caching model parameters: 3.27MiB
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.
Compilation child process completed within timeout period.
Compilation succeeded!

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: