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 ObjectDetector:

from autogluon.vision import ObjectDetector
/home/ci/opt/venv/lib/python3.8/site-packages/gluoncv/__init__.py:40: UserWarning: Both mxnet==1.9.1 and torch==1.12.1+cu102 are installed. You might encounter increased GPU memory footprint if both framework are used at the same time.
  warnings.warn(f'Both mxnet=={mx.__version__} and torch=={torch.__version__} are installed. '
INFO:matplotlib.font_manager:generated new fontManager
INFO:torch.distributed.nn.jit.instantiator:Created a temporary directory at /tmp/tmp36v0h9kc
INFO:torch.distributed.nn.jit.instantiator:Writing /tmp/tmp36v0h9kc/_remote_module_non_scriptable.py
INFO:root:Generating grammar tables from /usr/lib/python3.8/lib2to3/Grammar.txt
INFO:root:Generating grammar tables from /usr/lib/python3.8/lib2to3/PatternGrammar.txt
/home/ci/opt/venv/lib/python3.8/site-packages/mmcv/__init__.py:20: UserWarning: On January 1, 2023, MMCV will release v2.0.0, in which it will remove components related to the training process and add a data transformation module. In addition, it will rename the package names mmcv to mmcv-lite and mmcv-full to mmcv. See https://github.com/open-mmlab/mmcv/blob/master/docs/en/compatibility.md for more details.
  warnings.warn(

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')
Downloading /home/ci/.gluoncv/archive/tiny_motorbike.zip from https://autogluon.s3.amazonaws.com/datasets/tiny_motorbike.zip...
21273KB [00:01, 17887.72KB/s]
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}
hyperparameter_tune_kwargs={'num_trials': 2}
detector.fit(dataset_train, time_limit=time_limit, hyperparameters=hyperparameters, hyperparameter_tune_kwargs=hyperparameter_tune_kwargs)
=============================================================================
WARNING: ObjectDetector is deprecated as of v0.4.0 and may contain various bugs and issues!
In a future release ObjectDetector may be entirely reworked to use Torch as a backend.
This future change will likely be API breaking.Users should ensure they update their code that depends on ObjectDetector when upgrading to future AutoGluon releases.
For more information, refer to ObjectDetector refactor GitHub issue: https://github.com/awslabs/autogluon/issues/1559
=============================================================================

The number of requested GPUs is greater than the number of available GPUs.Reduce the number to 1
Randomly split train_data into train[157]/validation[13] splits.
Starting HPO experiments
  0%|          | 0/2 [00:00<?, ?it/s]
INFO:SSDEstimator:modified configs(<old> != <new>): {
INFO:SSDEstimator:root.dataset         voc_tiny != auto
INFO:SSDEstimator:root.ssd.data_shape  300 != 512
INFO:SSDEstimator:root.ssd.base_network vgg16_atrous != resnet50_v1
INFO:SSDEstimator:root.train.early_stop_baseline 0.0 != -inf
INFO:SSDEstimator:root.train.seed      233 != 505
INFO:SSDEstimator:root.train.early_stop_max_value 1.0 != inf
INFO:SSDEstimator:root.train.early_stop_patience -1 != 10
INFO:SSDEstimator:root.train.batch_size 16 != 8
INFO:SSDEstimator:root.train.epochs    20 != 5
INFO:SSDEstimator:root.dataset_root    ~/.mxnet/datasets/ != auto
INFO:SSDEstimator:root.num_workers     4 != 8
INFO:SSDEstimator:root.gpus            (0, 1, 2, 3) != (0,)
INFO:SSDEstimator:root.valid.batch_size 16 != 8
INFO:SSDEstimator:}
INFO:SSDEstimator:Saved config to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/ef15dbcf/.trial_0/config.yaml
INFO:SSDEstimator:Using transfer learning from ssd_512_resnet50_v1_coco, the other network parameters are ignored.
INFO:root:Model file not found. Downloading.
Downloading /home/ci/.mxnet/models/ssd_512_resnet50_v1_coco-c4835162.zip from https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/gluon/models/ssd_512_resnet50_v1_coco-c4835162.zip...
  0%|          | 0/181188 [00:00<?, ?KB/s]
  1%|          | 906/181188 [00:00<00:19, 9059.58KB/s]
  2%|▏         | 3772/181188 [00:00<00:08, 20588.48KB/s]
  6%|▌         | 11005/181188 [00:00<00:03, 44211.82KB/s]
 11%|█         | 19895/181188 [00:00<00:02, 61849.33KB/s]
 16%|█▌        | 28636/181188 [00:00<00:02, 71064.53KB/s]
 21%|██        | 38447/181188 [00:00<00:01, 80253.03KB/s]
 27%|██▋       | 48669/181188 [00:00<00:01, 87430.69KB/s]
 32%|███▏      | 58490/181188 [00:00<00:01, 90860.65KB/s]
 37%|███▋      | 67912/181188 [00:00<00:01, 91908.18KB/s]
 43%|████▎     | 78191/181188 [00:01<00:01, 95264.97KB/s]
 48%|████▊     | 87727/181188 [00:01<00:00, 95291.99KB/s]
 54%|█████▎    | 97257/181188 [00:01<00:00, 89320.83KB/s]
 59%|█████▊    | 106264/181188 [00:01<00:01, 67768.24KB/s]
 63%|██████▎   | 114680/181188 [00:01<00:00, 70257.98KB/s]
 68%|██████▊   | 124036/181188 [00:01<00:00, 76085.14KB/s]
 73%|███████▎  | 132699/181188 [00:01<00:00, 78859.60KB/s]
 79%|███████▉  | 142776/181188 [00:01<00:00, 84847.09KB/s]
 84%|████████▎ | 151613/181188 [00:01<00:00, 80738.22KB/s]
 88%|████████▊ | 160225/181188 [00:02<00:00, 82208.20KB/s]
 93%|█████████▎| 168653/181188 [00:02<00:00, 78463.85KB/s]
181189KB [00:02, 77141.48KB/s]
INFO:SSDEstimator:Start training from [Epoch 0]
INFO:SSDEstimator:[Epoch 0] Training cost: 11.144767, CrossEntropy=3.805459, SmoothL1=1.212089
INFO:SSDEstimator:[Epoch 0] Validation:
dog=nan
motorbike=0.9197518168106404
cow=nan
boat=nan
car=0.7515151515151517
bicycle=nan
bus=nan
chair=nan
person=0.7110389610389609
pottedplant=nan
mAP=0.7941019764549176
INFO:SSDEstimator:[Epoch 0] Current best map: 0.794102 vs previous 0.000000, saved to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/ef15dbcf/.trial_0/best_checkpoint.pkl
INFO:SSDEstimator:[Epoch 1] Training cost: 8.001718, CrossEntropy=2.886016, SmoothL1=1.291038
INFO:SSDEstimator:[Epoch 1] Validation:
dog=nan
motorbike=0.7843454305904899
cow=nan
boat=nan
car=0.5595238095238095
bicycle=nan
bus=nan
chair=nan
person=0.6017868602411621
pottedplant=nan
mAP=0.6485520334518204
INFO:SSDEstimator:[Epoch 2] Training cost: 7.596671, CrossEntropy=2.555668, SmoothL1=1.173760
INFO:SSDEstimator:[Epoch 2] Validation:
dog=nan
motorbike=0.779978354978355
cow=nan
boat=nan
car=0.6154545454545454
bicycle=nan
bus=nan
chair=nan
person=0.770654505137264
pottedplant=nan
mAP=0.7220291351900547
INFO:SSDEstimator:[Epoch 3] Training cost: 7.916990, CrossEntropy=2.385801, SmoothL1=1.162214
INFO:SSDEstimator:[Epoch 3] Validation:
dog=nan
motorbike=0.8708145115753813
cow=nan
boat=nan
car=0.9318181818181821
bicycle=nan
bus=nan
chair=nan
person=0.7896270396270397
pottedplant=nan
mAP=0.8640865776735344
INFO:SSDEstimator:[Epoch 3] Current best map: 0.864087 vs previous 0.794102, saved to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/ef15dbcf/.trial_0/best_checkpoint.pkl
INFO:SSDEstimator:[Epoch 4] Training cost: 7.810382, CrossEntropy=2.185688, SmoothL1=0.956306
INFO:SSDEstimator:[Epoch 4] Validation:
dog=nan
motorbike=0.8730152200740438
cow=nan
boat=nan
car=0.6539366265393664
bicycle=nan
bus=nan
chair=nan
person=0.8023582478127934
pottedplant=nan
mAP=0.7764366981420677
INFO:SSDEstimator:Applying the state from the best checkpoint...
INFO:root:Model file not found. Downloading.
Downloading /home/ci/.mxnet/models/resnet50_v1-cc729d95.zip from https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/gluon/models/resnet50_v1-cc729d95.zip...
  0%|          | 0/57421 [00:00<?, ?KB/s]
  2%|▏         | 920/57421 [00:00<00:06, 9147.64KB/s]
  8%|▊         | 4451/57421 [00:00<00:02, 24500.10KB/s]
 22%|██▏       | 12661/57421 [00:00<00:00, 50764.75KB/s]
 37%|███▋      | 21328/57421 [00:00<00:00, 64925.93KB/s]
 55%|█████▍    | 31341/57421 [00:00<00:00, 77612.29KB/s]
 72%|███████▏  | 41336/57421 [00:00<00:00, 85202.73KB/s]
100%|██████████| 57421/57421 [00:00<00:00, 72800.80KB/s]
Finished, total runtime is 75.52 s
{ 'best_config': { 'dataset': 'auto',
                   'dataset_root': 'auto',
                   'estimator': <class 'gluoncv.auto.estimators.ssd.ssd.SSDEstimator'>,
                   'gpus': [0],
                   'horovod': False,
                   'num_workers': 8,
                   'resume': '',
                   'save_interval': 1,
                   'ssd': { 'amp': False,
                            'base_network': 'resnet50_v1',
                            'data_shape': 512,
                            'filters': None,
                            'nms_thresh': 0.45,
                            'nms_topk': 400,
                            'ratios': ( [1, 2, 0.5],
                                        [1, 2, 0.5, 3, 0.3333333333333333],
                                        [1, 2, 0.5, 3, 0.3333333333333333],
                                        [1, 2, 0.5, 3, 0.3333333333333333],
                                        [1, 2, 0.5],
                                        [1, 2, 0.5]),
                            'sizes': (30, 60, 111, 162, 213, 264, 315),
                            'steps': (8, 16, 32, 64, 100, 300),
                            'syncbn': False,
                            'transfer': 'ssd_512_resnet50_v1_coco'},
                   'train': { 'batch_size': 8,
                              'dali': False,
                              'early_stop_baseline': -inf,
                              'early_stop_max_value': inf,
                              'early_stop_min_delta': 0.001,
                              'early_stop_patience': 10,
                              'epochs': 5,
                              'log_interval': 100,
                              'lr': 0.001,
                              'lr_decay': 0.1,
                              'lr_decay_epoch': (160, 200),
                              'momentum': 0.9,
                              'seed': 505,
                              'start_epoch': 0,
                              'wd': 0.0005},
                   'valid': { 'batch_size': 8,
                              'iou_thresh': 0.5,
                              'metric': 'voc07',
                              'val_interval': 1}},
  'total_time': 75.51968765258789,
  'train_map': 0.7016082830584256,
  'valid_map': 0.8640865776735344}
<autogluon.vision.detector.detector.ObjectDetector at 0x7fe1690b1730>

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.

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.06794181825386318

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.961029
1         person       0.765205
2            car       0.193960
3         person       0.172956
4         person       0.115426
..           ...            ...
68        person       0.033744
69           car       0.033347
70           car       0.033309
71           car       0.033101
72           car       0.032946

                                         predict_rois
0   {'xmin': 0.3091109097003937, 'ymin': 0.4206629...
1   {'xmin': 0.40335220098495483, 'ymin': 0.291491...
2   {'xmin': 0.7092502117156982, 'ymin': 0.0814163...
3   {'xmin': 0.0032731974497437477, 'ymin': 0.0, '...
4   {'xmin': 0.9939614534378052, 'ymin': 0.6036039...
..                                                ...
68  {'xmin': 0.4348425269126892, 'ymin': 0.3430321...
69  {'xmin': 0.8009289503097534, 'ymin': 0.0472413...
70  {'xmin': 0.0, 'ymin': 0.7102063298225403, 'xma...
71  {'xmin': 0.9919195771217346, 'ymin': 0.3513243...
72  {'xmin': 0.9730498790740967, 'ymin': 0.4242631...

[73 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.961029
1           person       0.765205
2              car       0.193960
3           person       0.172956
4           person       0.115426
...            ...            ...
4345        person       0.033570
4346        person       0.033557
4347     motorbike       0.033539
4348        person       0.033280
4349        person       0.033199

                                           predict_rois  0     {'xmin': 0.3091109097003937, 'ymin': 0.4206629...
1     {'xmin': 0.40335220098495483, 'ymin': 0.291491...
2     {'xmin': 0.7092502117156982, 'ymin': 0.0814163...
3     {'xmin': 0.0032731974497437477, 'ymin': 0.0, '...
4     {'xmin': 0.9939614534378052, 'ymin': 0.6036039...
...                                                 ...
4345  {'xmin': 0.25918978452682495, 'ymin': 0.166401...
4346  {'xmin': 0.12566807866096497, 'ymin': 0.079244...
4347  {'xmin': 0.050919413566589355, 'ymin': 0.65396...
4348  {'xmin': 0.5824605226516724, 'ymin': 0.1730046...
4349  {'xmin': 0.29298630356788635, 'ymin': 0.394789...

                                                  image
0     /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
1     /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
2     /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
3     /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
4     /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
...                                                 ...
4345  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
4346  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
4347  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
4348  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
4349  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...

[4350 rows x 4 columns]

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

Warning

ObjectDetector.load() used pickle module implicitly, which is known to be insecure. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling. Never load data that could have come from an untrusted source, or that could have been tampered with. Only load data you trust.

savefile = 'detector.ag'
detector.save(savefile)
new_detector = ObjectDetector.load(savefile)
/home/ci/opt/venv/lib/python3.8/site-packages/mxnet/gluon/block.py:1784: UserWarning: Cannot decide type for the following arguments. Consider providing them as input:
    data: None
  input_sym_arg_type = in_param.infer_type()[0]