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.0+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. '

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, 15339.49KB/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[153]/validation[17] splits.
Starting HPO experiments
  0%|          | 0/2 [00:00<?, ?it/s]
modified configs(<old> != <new>): {
root.dataset         voc_tiny != auto
root.gpus            (0, 1, 2, 3) != (0,)
root.ssd.base_network vgg16_atrous != resnet50_v1
root.ssd.data_shape  300 != 512
root.dataset_root    ~/.mxnet/datasets/ != auto
root.num_workers     4 != 8
root.valid.batch_size 16 != 8
root.train.early_stop_max_value 1.0 != inf
root.train.seed      233 != 667
root.train.batch_size 16 != 8
root.train.early_stop_patience -1 != 10
root.train.early_stop_baseline 0.0 != -inf
root.train.epochs    20 != 5
}
Saved config to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/26374810/.trial_0/config.yaml
Using transfer learning from ssd_512_resnet50_v1_coco, the other network parameters are ignored.
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]
  0%|          | 101/181188 [00:00<03:44, 807.06KB/s]
  0%|          | 507/181188 [00:00<01:21, 2217.20KB/s]
  1%|          | 2188/181188 [00:00<00:24, 7230.65KB/s]
  4%|▍         | 7916/181188 [00:00<00:07, 24193.28KB/s]
  7%|▋         | 12992/181188 [00:00<00:05, 32858.00KB/s]
 11%|█         | 19852/181188 [00:00<00:03, 41715.98KB/s]
 15%|█▌        | 27620/181188 [00:00<00:02, 52501.13KB/s]
 18%|█▊        | 33059/181188 [00:00<00:02, 52614.98KB/s]
 22%|██▏       | 40305/181188 [00:01<00:02, 55646.40KB/s]
 27%|██▋       | 48177/181188 [00:01<00:02, 62291.30KB/s]
 30%|███       | 54502/181188 [00:01<00:02, 61217.85KB/s]
 34%|███▍      | 61561/181188 [00:01<00:01, 61855.30KB/s]
 39%|███▊      | 69765/181188 [00:01<00:01, 67623.96KB/s]
 42%|████▏     | 76594/181188 [00:01<00:01, 67166.69KB/s]
 47%|████▋     | 84834/181188 [00:01<00:01, 69501.97KB/s]
 51%|█████▏    | 92910/181188 [00:01<00:01, 72737.07KB/s]
 55%|█████▌    | 100222/181188 [00:01<00:01, 72847.40KB/s]
 60%|█████▉    | 108675/181188 [00:01<00:00, 76277.00KB/s]
 64%|██████▍   | 116327/181188 [00:02<00:01, 60462.91KB/s]
 69%|██████▉   | 124794/181188 [00:02<00:00, 64921.37KB/s]
 73%|███████▎  | 131705/181188 [00:02<00:00, 52518.42KB/s]
 77%|███████▋  | 139813/181188 [00:02<00:00, 58087.96KB/s]
 81%|████████▏ | 147445/181188 [00:02<00:00, 61232.23KB/s]
 86%|████████▌ | 155418/181188 [00:02<00:00, 65912.12KB/s]
 90%|████████▉ | 162615/181188 [00:02<00:00, 59773.44KB/s]
 93%|█████████▎| 168965/181188 [00:03<00:00, 48325.41KB/s]
181189KB [00:03, 55329.57KB/s]
Start training from [Epoch 0]
[Epoch 0] Training cost: 11.782347, CrossEntropy=3.549968, SmoothL1=1.046254
[Epoch 0] Validation:
cow=nan
dog=nan
chair=nan
boat=nan
person=0.6269768433054437
car=0.6251082251082253
bus=nan
bicycle=nan
pottedplant=nan
motorbike=0.6494933858710948
mAP=0.6338594847615879
[Epoch 0] Current best map: 0.633859 vs previous 0.000000, saved to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/26374810/.trial_0/best_checkpoint.pkl
[Epoch 1] Training cost: 7.612479, CrossEntropy=2.678321, SmoothL1=1.164692
[Epoch 1] Validation:
cow=nan
dog=nan
chair=nan
boat=nan
person=0.6206287678532248
car=0.585858585858586
bus=nan
bicycle=nan
pottedplant=nan
motorbike=0.7395060131902238
mAP=0.6486644556340115
[Epoch 1] Current best map: 0.648664 vs previous 0.633859, saved to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/26374810/.trial_0/best_checkpoint.pkl
[Epoch 2] Training cost: 7.668273, CrossEntropy=2.369540, SmoothL1=1.069311
[Epoch 2] Validation:
cow=nan
dog=nan
chair=nan
boat=nan
person=0.6988482815533813
car=0.7878787878787881
bus=nan
bicycle=nan
pottedplant=nan
motorbike=0.7887131224135632
mAP=0.7584800639485776
[Epoch 2] Current best map: 0.758480 vs previous 0.648664, saved to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/26374810/.trial_0/best_checkpoint.pkl
[Epoch 3] Training cost: 7.678465, CrossEntropy=2.305239, SmoothL1=1.058896
[Epoch 3] Validation:
cow=nan
dog=nan
chair=nan
boat=nan
person=0.7015391168709247
car=0.6722325293753868
bus=nan
bicycle=nan
pottedplant=nan
motorbike=0.8054573799216657
mAP=0.7264096753893258
[Epoch 4] Training cost: 7.763921, CrossEntropy=2.280916, SmoothL1=0.999022
[Epoch 4] Validation:
cow=nan
dog=nan
chair=nan
boat=nan
person=0.7798857559552747
car=0.55
bus=nan
bicycle=nan
pottedplant=nan
motorbike=0.768074031231926
mAP=0.6993199290624003
Applying the state from the best checkpoint...
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]
  0%|          | 102/57421 [00:00<01:03, 895.95KB/s]
  1%|          | 516/57421 [00:00<00:22, 2476.50KB/s]
  4%|▍         | 2185/57421 [00:00<00:07, 7858.35KB/s]
 15%|█▍        | 8569/57421 [00:00<00:01, 26464.61KB/s]
 31%|███       | 17697/57421 [00:00<00:00, 47640.78KB/s]
 44%|████▍     | 25301/57421 [00:00<00:00, 56672.55KB/s]
 57%|█████▋    | 32881/57421 [00:00<00:00, 62642.94KB/s]
 73%|███████▎  | 42183/57421 [00:00<00:00, 70488.37KB/s]
100%|██████████| 57421/57421 [00:01<00:00, 54595.50KB/s]
Finished, total runtime is 77.49 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': 667,
                              'start_epoch': 0,
                              'wd': 0.0005},
                   'valid': { 'batch_size': 8,
                              'iou_thresh': 0.5,
                              'metric': 'voc07',
                              'val_interval': 1}},
  'total_time': 77.49094033241272,
  'train_map': 0.6945064419125325,
  'valid_map': 0.7584800639485776}
<autogluon.vision.detector.detector.ObjectDetector at 0x7f9f444a3c70>

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

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.994712
1         person       0.985832
2      motorbike       0.179652
3         person       0.103769
4            car       0.099792
..           ...            ...
85        person       0.027744
86        person       0.027608
87        person       0.027552
88        person       0.027396
89           car       0.027284

                                         predict_rois
0   {'xmin': 0.3323376178741455, 'ymin': 0.4279397...
1   {'xmin': 0.3869675397872925, 'ymin': 0.2909367...
2   {'xmin': 0.0011276870500296354, 'ymin': 0.6393...
3   {'xmin': 0.9191047549247742, 'ymin': 0.0055489...
4   {'xmin': 0.0, 'ymin': 0.6292139887809753, 'xma...
..                                                ...
85  {'xmin': 0.472634881734848, 'ymin': 0.30082464...
86  {'xmin': 0.6742066144943237, 'ymin': 0.0436715...
87  {'xmin': 0.7676824927330017, 'ymin': 0.4318469...
88  {'xmin': 0.1235024482011795, 'ymin': 0.0058807...
89  {'xmin': 0.6528046131134033, 'ymin': 0.4384836...

[90 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.994712
1           person       0.985832
2        motorbike       0.179652
3           person       0.103769
4              car       0.099792
...            ...            ...
3863        person       0.033929
3864        person       0.033875
3865        person       0.033843
3866     motorbike       0.033588
3867        person       0.033377

                                           predict_rois  0     {'xmin': 0.3323376178741455, 'ymin': 0.4279397...
1     {'xmin': 0.3869675397872925, 'ymin': 0.2909367...
2     {'xmin': 0.0011276870500296354, 'ymin': 0.6393...
3     {'xmin': 0.9191047549247742, 'ymin': 0.0055489...
4     {'xmin': 0.0, 'ymin': 0.6292139887809753, 'xma...
...                                                 ...
3863  {'xmin': 0.446552574634552, 'ymin': 0.25420239...
3864  {'xmin': 0.1938023418188095, 'ymin': 0.4296730...
3865  {'xmin': 0.9320743680000305, 'ymin': 0.5821830...
3866  {'xmin': 0.7003101110458374, 'ymin': 0.5587533...
3867  {'xmin': 0.22127439081668854, 'ymin': 0.402336...

                                                  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...
...                                                 ...
3863  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
3864  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
3865  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
3866  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
3867  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...

[3868 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)
/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]