Object Detection - Quick Start

Object detection is the process of identifying and localizing objects in an image and is an important task in computer vision. Follow this tutorial to learn how to use AutoGluon for object detection.

Tip: If you are new to AutoGluon, review Image Prediction - Quick Start first to learn the basics of the AutoGluon API.

Our goal is to detect motorbike in images by YOLOv3 model. A tiny dataset is collected from VOC dataset, which only contains the motorbike category. The model pretrained on the COCO dataset is used to fine-tune our small dataset. With the help of AutoGluon, we are able to try many models with different hyperparameters automatically, and return the best one as our final model.

To start, import autogluon.vision and ObjectDetector:

import autogluon.core as ag
from autogluon.vision import ObjectDetector

Tiny_motorbike Dataset

We collect a toy dataset for detecting motorbikes in images. From the VOC dataset, images are randomly selected for training, validation, and testing - 120 images for training, 50 images for validation, and 50 for testing. This tiny dataset follows the same format as VOC.

Using the commands below, we can download this dataset, which is only 23M. The name of unzipped folder is called tiny_motorbike. Anyway, the task dataset helper can perform the download and extraction automatically, and load the dataset according to the detection formats.

url = 'https://autogluon.s3.amazonaws.com/datasets/tiny_motorbike.zip'
dataset_train = ObjectDetector.Dataset.from_voc(url, splits='trainval')
tiny_motorbike/
├── Annotations/
├── ImageSets/
└── JPEGImages/

Fit Models by AutoGluon

In this section, we demonstrate how to apply AutoGluon to fit our detection models. We use mobilenet as the backbone for the YOLOv3 model. Two different learning rates are used to fine-tune the network. The best model is the one that obtains the best performance on the validation dataset. You can also try using more networks and hyperparameters to create a larger searching space.

We fit a classifier using AutoGluon as follows. In each experiment (one trial in our searching space), we train the model for 5 epochs to avoid bursting our tutorial runtime.

time_limit = 60*30  # at most 0.5 hour
detector = ObjectDetector()
hyperparameters = {'epochs': 5, 'batch_size': 8}
hyperparamter_tune_kwargs={'num_trials': 2}
detector.fit(dataset_train, time_limit=time_limit, hyperparameters=hyperparameters, hyperparamter_tune_kwargs=hyperparamter_tune_kwargs)
WARNING:gluoncv.auto.tasks.object_detection:The number of requested GPUs is greater than the number of available GPUs.Reduce the number to 1
INFO:gluoncv.auto.tasks.object_detection:Randomly split train_data into train[158]/validation[12] splits.
INFO:gluoncv.auto.tasks.object_detection:Starting fit without HPO
INFO:SSDEstimator:modified configs(<old> != <new>): {
INFO:SSDEstimator:root.dataset         voc_tiny != auto
INFO:SSDEstimator:root.gpus            (0, 1, 2, 3) != (0,)
INFO:SSDEstimator:root.dataset_root    ~/.mxnet/datasets/ != auto
INFO:SSDEstimator:root.num_workers     4 != 8
INFO:SSDEstimator:root.ssd.base_network vgg16_atrous != resnet50_v1
INFO:SSDEstimator:root.ssd.data_shape  300 != 512
INFO:SSDEstimator:root.valid.batch_size 16 != 8
INFO:SSDEstimator:root.train.early_stop_patience -1 != 10
INFO:SSDEstimator:root.train.epochs    20 != 5
INFO:SSDEstimator:root.train.batch_size 16 != 8
INFO:SSDEstimator:root.train.seed      233 != 215
INFO:SSDEstimator:root.train.early_stop_baseline 0.0 != -inf
INFO:SSDEstimator:root.train.early_stop_max_value 1.0 != inf
INFO:SSDEstimator:}
INFO:SSDEstimator:Saved config to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/0707cbc2/.trial_0/config.yaml
INFO:SSDEstimator:Using transfer learning from ssd_512_resnet50_v1_coco, the other network parameters are ignored.
INFO:SSDEstimator:Start training from [Epoch 0]
INFO:SSDEstimator:[Epoch 0] Training cost: 10.192801, CrossEntropy=3.454734, SmoothL1=0.962861
INFO:SSDEstimator:[Epoch 0] Validation:
boat=1.0000000000000002
motorbike=0.8400588112868387
cow=0.5454545454545454
dog=0.0
pottedplant=0.0
person=0.7247915971595265
bicycle=0.06159614043245757
bus=0.6783216783216786
car=0.7022941216489603
chair=0.012500000000000002
mAP=0.45650168943040076
INFO:SSDEstimator:[Epoch 0] Current best map: 0.456502 vs previous 0.000000, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/0707cbc2/.trial_0/best_checkpoint.pkl
INFO:SSDEstimator:[Epoch 1] Training cost: 9.049835, CrossEntropy=2.617126, SmoothL1=1.157186
INFO:SSDEstimator:[Epoch 1] Validation:
boat=1.0000000000000002
motorbike=0.8385712874387491
cow=1.0000000000000002
dog=1.0000000000000002
pottedplant=0.007704160246533128
person=0.7829296184909087
bicycle=0.37755102040816335
bus=0.8181818181818181
car=0.7338180735131611
chair=0.0
mAP=0.6558755978279335
INFO:SSDEstimator:[Epoch 1] Current best map: 0.655876 vs previous 0.456502, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/0707cbc2/.trial_0/best_checkpoint.pkl
INFO:SSDEstimator:[Epoch 2] Training cost: 9.081720, CrossEntropy=2.388730, SmoothL1=1.080288
INFO:SSDEstimator:[Epoch 2] Validation:
boat=1.0000000000000002
motorbike=0.8574779772112063
cow=1.0000000000000002
dog=1.0000000000000002
pottedplant=0.0
person=0.8313422987170885
bicycle=0.19226215644820296
bus=1.0000000000000002
car=0.7999573748653425
chair=0.0
mAP=0.6681039807241841
INFO:SSDEstimator:[Epoch 2] Current best map: 0.668104 vs previous 0.655876, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/0707cbc2/.trial_0/best_checkpoint.pkl
INFO:SSDEstimator:[Epoch 3] Training cost: 9.578223, CrossEntropy=2.194199, SmoothL1=0.958734
INFO:SSDEstimator:[Epoch 3] Validation:
boat=1.0000000000000002
motorbike=0.8713905498070341
cow=1.0000000000000002
dog=1.0000000000000002
pottedplant=0.1456876456876457
person=0.8149657641562803
bicycle=0.2262018683071315
bus=1.0000000000000002
car=0.8309356312027513
chair=0.25000000000000006
mAP=0.7139181459160844
INFO:SSDEstimator:[Epoch 3] Current best map: 0.713918 vs previous 0.668104, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/0707cbc2/.trial_0/best_checkpoint.pkl
INFO:SSDEstimator:[Epoch 4] Training cost: 9.023939, CrossEntropy=2.159025, SmoothL1=0.954020
INFO:SSDEstimator:[Epoch 4] Validation:
boat=1.0000000000000002
motorbike=0.8885823654800267
cow=1.0000000000000002
dog=1.0000000000000002
pottedplant=0.35454545454545455
person=0.8046294947854538
bicycle=0.5808080808080808
bus=1.0000000000000002
car=0.8255651755651755
chair=0.01818181818181818
mAP=0.7472312389366011
INFO:SSDEstimator:[Epoch 4] Current best map: 0.747231 vs previous 0.713918, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/0707cbc2/.trial_0/best_checkpoint.pkl
INFO:SSDEstimator:Applying the state from the best checkpoint...
INFO:gluoncv.auto.tasks.object_detection:Finished, total runtime is 87.65 s
INFO:gluoncv.auto.tasks.object_detection:{ 'best_config': { 'batch_size': 8,
                   'dist_ip_addrs': None,
                   'early_stop_baseline': -inf,
                   'early_stop_max_value': inf,
                   'early_stop_patience': 10,
                   'epochs': 5,
                   'final_fit': False,
                   'gpus': [0],
                   'log_dir': '/var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/0707cbc2',
                   'lr': 0.001,
                   'ngpus_per_trial': 8,
                   'nthreads_per_trial': 128,
                   'num_trials': 1,
                   'num_workers': 8,
                   'search_strategy': 'random',
                   'seed': 215,
                   'time_limits': 1800,
                   'transfer': 'ssd_512_resnet50_v1_coco',
                   'wall_clock_tick': 1619659859.5794768},
  'total_time': 69.43584537506104,
  'train_map': 0.7472312389366011,
  'valid_map': 0.7472312389366011}
<autogluon.vision.detector.detector.ObjectDetector at 0x7f9b66cad150>

Note that num_trials=2 above is only used to speed up the tutorial. In normal practice, it is common to only use time_limit and drop num_trials. Also note that hyperparameter tuning defaults to random search. Model-based variants, such as search_strategy='bayesopt' or search_strategy='bayesopt_hyperband' can be a lot more sample-efficient.

After fitting, AutoGluon automatically returns the best model among all models in the searching space. From the output, we know the best model is the one trained with the second learning rate. To see how well the returned model performed on test dataset, call detector.evaluate().

dataset_test = ObjectDetector.Dataset.from_voc(url, splits='test')

test_map = detector.evaluate(dataset_test)
print("mAP on test dataset: {}".format(test_map[1][-1]))
tiny_motorbike/
├── Annotations/
├── ImageSets/
└── JPEGImages/
mAP on test dataset: 0.0725467873099653

Below, we randomly select an image from test dataset and show the predicted class, box and probability over the origin image, stored in predict_class, predict_rois and predict_score columns, respectively. You can interpret predict_rois as a dict of (xmin, ymin, xmax, ymax) proportional to original image size.

image_path = dataset_test.iloc[0]['image']
result = detector.predict(image_path)
print(result)
   predict_class  predict_score  0      motorbike       0.992118
1         person       0.966366
2      motorbike       0.383774
3         person       0.246424
4         person       0.206470
..           ...            ...
95        person       0.018743
96           car       0.018648
97        person       0.018590
98        person       0.018514
99        person       0.018280

                                         predict_rois
0   {'xmin': 0.3116825222969055, 'ymin': 0.4782207...
1   {'xmin': 0.39210665225982666, 'ymin': 0.309239...
2   {'xmin': 0.364930123090744, 'ymin': 0.35418850...
3   {'xmin': 0.7199134826660156, 'ymin': 0.3906281...
4   {'xmin': 0.4888369143009186, 'ymin': 0.2891696...
..                                                ...
95  {'xmin': 0.9579000473022461, 'ymin': 0.0276650...
96  {'xmin': 0.9871337413787842, 'ymin': 0.0709608...
97  {'xmin': 0.8416514992713928, 'ymin': 0.3585470...
98  {'xmin': 0.9734511971473694, 'ymin': 0.0, 'xma...
99  {'xmin': 0.9618788361549377, 'ymin': 0.0, 'xma...

[100 rows x 3 columns]

Prediction with multiple images is permitted:

bulk_result = detector.predict(dataset_test)
print(bulk_result)
     predict_class  predict_score  0        motorbike       0.992118
1           person       0.966366
2        motorbike       0.383774
3           person       0.246424
4           person       0.206470
...            ...            ...
4756        person       0.046803
4757        person       0.046800
4758        person       0.046536
4759        person       0.046471
4760        person       0.046376

                                           predict_rois  0     {'xmin': 0.3116825222969055, 'ymin': 0.4782207...
1     {'xmin': 0.39210665225982666, 'ymin': 0.309239...
2     {'xmin': 0.364930123090744, 'ymin': 0.35418850...
3     {'xmin': 0.7199134826660156, 'ymin': 0.3906281...
4     {'xmin': 0.4888369143009186, 'ymin': 0.2891696...
...                                                 ...
4756  {'xmin': 0.27369779348373413, 'ymin': 0.076635...
4757  {'xmin': 0.030131647363305092, 'ymin': 0.37820...
4758  {'xmin': 0.18918216228485107, 'ymin': 0.951425...
4759  {'xmin': 0.5650653839111328, 'ymin': 0.0547036...
4760  {'xmin': 0.4090377688407898, 'ymin': 0.0669689...

                                                  image
0     /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
1     /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
2     /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
3     /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
4     /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
...                                                 ...
4756  /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
4757  /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
4758  /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
4759  /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
4760  /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...

[4761 rows x 4 columns]

We can also save the trained model, and use it later.

savefile = 'detector.ag'
detector.save(savefile)
new_detector = ObjectDetector.load(savefile)
/var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/venv/lib/python3.7/site-packages/mxnet/gluon/block.py:1512: UserWarning: Cannot decide type for the following arguments. Consider providing them as input:
    data: None
  input_sym_arg_type = in_param.infer_type()[0]