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
/var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/venv/lib/python3.7/site-packages/gluoncv/__init__.py:40: UserWarning: Both mxnet==1.7.0 and torch==1.9.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')
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)
The number of requested GPUs is greater than the number of available GPUs.Reduce the number to 1
Randomly split train_data into train[151]/validation[19] splits.
Starting fit without HPO
modified configs(<old> != <new>): {
root.dataset_root    ~/.mxnet/datasets/ != auto
root.ssd.data_shape  300 != 512
root.ssd.base_network vgg16_atrous != resnet50_v1
root.dataset         voc_tiny != auto
root.train.epochs    20 != 5
root.train.early_stop_patience -1 != 10
root.train.early_stop_max_value 1.0 != inf
root.train.early_stop_baseline 0.0 != -inf
root.train.batch_size 16 != 8
root.train.seed      233 != 396
root.gpus            (0, 1, 2, 3) != (0,)
root.num_workers     4 != 8
root.valid.batch_size 16 != 8
}
Saved config to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/fccabd73/.trial_0/config.yaml
Using transfer learning from ssd_512_resnet50_v1_coco, the other network parameters are ignored.
Start training from [Epoch 0]
[Epoch 0] Training cost: 9.006707, CrossEntropy=3.544785, SmoothL1=0.944084
[Epoch 0] Validation:
bicycle=0.12500000000000003
chair=nan
cow=nan
pottedplant=0.0
person=0.771685450564761
boat=1.0000000000000002
motorbike=0.7690381044947524
bus=nan
dog=nan
car=0.6689723320158101
mAP=0.5557826478458873
[Epoch 0] Current best map: 0.555783 vs previous 0.000000, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/fccabd73/.trial_0/best_checkpoint.pkl
[Epoch 1] Training cost: 8.457563, CrossEntropy=2.716539, SmoothL1=1.115482
[Epoch 1] Validation:
bicycle=0.27272727272727276
chair=nan
cow=nan
pottedplant=0.0
person=0.5012527047427132
boat=1.0000000000000002
motorbike=0.8736959361959361
bus=nan
dog=nan
car=0.21419951729686243
mAP=0.4769792384937975
[Epoch 2] Training cost: 8.210499, CrossEntropy=2.444343, SmoothL1=1.091371
[Epoch 2] Validation:
bicycle=0.05454545454545456
chair=nan
cow=nan
pottedplant=0.0
person=0.6301658493309347
boat=1.0000000000000002
motorbike=0.8350857530699428
bus=nan
dog=nan
car=0.7922077922077922
mAP=0.5520008081923541
[Epoch 3] Training cost: 8.326100, CrossEntropy=2.316288, SmoothL1=1.059458
[Epoch 3] Validation:
bicycle=0.0
chair=nan
cow=nan
pottedplant=0.0
person=0.527853439595973
boat=1.0000000000000002
motorbike=0.9488549085323277
bus=nan
dog=nan
car=0.5454545454545455
mAP=0.503693815597141
[Epoch 4] Training cost: 8.290956, CrossEntropy=2.299304, SmoothL1=1.033035
[Epoch 4] Validation:
bicycle=0.10909090909090911
chair=nan
cow=nan
pottedplant=0.0
person=0.6823231778687195
boat=1.0000000000000002
motorbike=0.9445100354191264
bus=nan
dog=nan
car=0.6776859504132231
mAP=0.5689350121319964
[Epoch 4] Current best map: 0.568935 vs previous 0.555783, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/fccabd73/.trial_0/best_checkpoint.pkl
Applying the state from the best checkpoint...
Finished, total runtime is 65.16 s
{ '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/fccabd73',
                   'lr': 0.001,
                   'ngpus_per_trial': 8,
                   'nthreads_per_trial': 128,
                   'num_trials': 1,
                   'num_workers': 8,
                   'scheduler': 'local',
                   'search_strategy': 'random',
                   'seed': 396,
                   'time_limits': 1800,
                   'transfer': 'ssd_512_resnet50_v1_coco',
                   'wall_clock_tick': 1623902086.5124395},
  'total_time': 48.02509617805481,
  'train_map': 0.6561219384673393,
  'valid_map': 0.5689350121319964}
<autogluon.vision.detector.detector.ObjectDetector at 0x7f3c30244550>

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

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.969733
1         person       0.957862
2            car       0.661897
3        bicycle       0.274602
4      motorbike       0.154934
..           ...            ...
72           car       0.021670
73        person       0.021320
74           car       0.021130
75     motorbike       0.020965
76           car       0.020837

                                         predict_rois
0   {'xmin': 0.3231537938117981, 'ymin': 0.4609160...
1   {'xmin': 0.4078666865825653, 'ymin': 0.3072903...
2   {'xmin': 0.0023745261132717133, 'ymin': 0.6342...
3   {'xmin': 0.3038586378097534, 'ymin': 0.4679307...
4   {'xmin': 0.0, 'ymin': 0.6324851512908936, 'xma...
..                                                ...
72  {'xmin': 0.0, 'ymin': 0.6203244924545288, 'xma...
73  {'xmin': 0.31046223640441895, 'ymin': 0.277395...
74  {'xmin': 0.8404693007469177, 'ymin': 0.7085961...
75  {'xmin': 0.31517907977104187, 'ymin': 0.555794...
76  {'xmin': 0.0, 'ymin': 0.6924062967300415, 'xma...

[77 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.969733
1           person       0.957862
2              car       0.661897
3          bicycle       0.274602
4        motorbike       0.154934
...            ...            ...
3480        person       0.044874
3481        person       0.044859
3482        person       0.044641
3483        person       0.044215
3484        person       0.042963

                                           predict_rois  0     {'xmin': 0.3231537938117981, 'ymin': 0.4609160...
1     {'xmin': 0.4078666865825653, 'ymin': 0.3072903...
2     {'xmin': 0.0023745261132717133, 'ymin': 0.6342...
3     {'xmin': 0.3038586378097534, 'ymin': 0.4679307...
4     {'xmin': 0.0, 'ymin': 0.6324851512908936, 'xma...
...                                                 ...
3480  {'xmin': 0.9572221040725708, 'ymin': 0.7536423...
3481  {'xmin': 0.11333871632814407, 'ymin': 0.568686...
3482  {'xmin': 0.0, 'ymin': 0.3720257580280304, 'xma...
3483  {'xmin': 0.3677523136138916, 'ymin': 0.1521932...
3484  {'xmin': 0.0437404066324234, 'ymin': 0.5198150...

                                                  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...
...                                                 ...
3480  /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
3481  /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
3482  /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
3483  /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
3484  /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...

[3485 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]