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
/var/lib/jenkins/miniconda3/envs/autogluon-tutorial-object-detection-v3/lib/python3.9/site-packages/gluoncv/__init__.py:40: UserWarning: Both mxnet==1.9.1 and torch==1.11.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}
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[161]/validation[9] splits.
Starting HPO experiments
0%| | 0/2 [00:00<?, ?it/s]
modified configs(<old> != <new>): {
root.ssd.data_shape 300 != 512
root.ssd.base_network vgg16_atrous != resnet50_v1
root.dataset_root ~/.mxnet/datasets/ != auto
root.train.epochs 20 != 5
root.train.early_stop_baseline 0.0 != -inf
root.train.early_stop_patience -1 != 10
root.train.seed 233 != 639
root.train.early_stop_max_value 1.0 != inf
root.train.batch_size 16 != 8
root.valid.batch_size 16 != 8
root.dataset voc_tiny != auto
root.num_workers 4 != 8
root.gpus (0, 1, 2, 3) != (0,)
}
Saved config to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/58c50b4b/.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: 12.044612, CrossEntropy=3.582205, SmoothL1=1.077815
[Epoch 0] Validation:
boat=nan
cow=nan
dog=nan
person=0.7954022988505749
chair=nan
bicycle=nan
pottedplant=nan
motorbike=0.36910691818856656
car=0.0
bus=nan
mAP=0.3881697390130472
[Epoch 0] Current best map: 0.388170 vs previous 0.000000, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/58c50b4b/.trial_0/best_checkpoint.pkl
[Epoch 1] Training cost: 8.080611, CrossEntropy=2.809763, SmoothL1=1.234455
[Epoch 1] Validation:
boat=nan
cow=nan
dog=nan
person=0.8935064935064936
chair=nan
bicycle=nan
pottedplant=nan
motorbike=0.6428296919736363
car=0.5454545454545455
bus=nan
mAP=0.6939302436448918
[Epoch 1] Current best map: 0.693930 vs previous 0.388170, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/58c50b4b/.trial_0/best_checkpoint.pkl
[Epoch 2] Training cost: 7.943115, CrossEntropy=2.501885, SmoothL1=1.078471
[Epoch 2] Validation:
boat=nan
cow=nan
dog=nan
person=1.0000000000000002
chair=nan
bicycle=nan
pottedplant=nan
motorbike=0.8181868405192619
car=0.8484848484848483
bus=nan
mAP=0.88889056300137
[Epoch 2] Current best map: 0.888891 vs previous 0.693930, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/58c50b4b/.trial_0/best_checkpoint.pkl
[Epoch 3] Training cost: 7.942341, CrossEntropy=2.266479, SmoothL1=0.989386
[Epoch 3] Validation:
boat=nan
cow=nan
dog=nan
person=0.7020767450595522
chair=nan
bicycle=nan
pottedplant=nan
motorbike=0.8978864272981922
car=0.45454545454545464
bus=nan
mAP=0.684836208967733
[Epoch 4] Training cost: 7.868770, CrossEntropy=2.138340, SmoothL1=0.938136
[Epoch 4] Validation:
boat=nan
cow=nan
dog=nan
person=0.9772727272727275
chair=nan
bicycle=nan
pottedplant=nan
motorbike=0.7875993132910128
car=0.6153846153846153
bus=nan
mAP=0.7934188853161186
Applying the state from the best checkpoint...
Finished, total runtime is 70.68 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': 639,
'start_epoch': 0,
'wd': 0.0005},
'valid': { 'batch_size': 8,
'iou_thresh': 0.5,
'metric': 'voc07',
'val_interval': 1}},
'total_time': 70.67626285552979,
'train_map': 0.7875849538160618,
'valid_map': 0.88889056300137}
<autogluon.vision.detector.detector.ObjectDetector at 0x7fdf8a934430>
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.025391932225852478
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 person 0.974653
1 motorbike 0.944522
2 car 0.570145
3 person 0.162251
4 car 0.138353
.. ... ...
71 car 0.032979
72 motorbike 0.032574
73 person 0.032338
74 car 0.032276
75 motorbike 0.032164
predict_rois
0 {'xmin': 0.40379223227500916, 'ymin': 0.279169...
1 {'xmin': 0.3315899074077606, 'ymin': 0.4289079...
2 {'xmin': 0.0005976061220280826, 'ymin': 0.6380...
3 {'xmin': 0.6507402658462524, 'ymin': 0.0071541...
4 {'xmin': 0.7942018508911133, 'ymin': 0.8768404...
.. ...
71 {'xmin': 0.027659373357892036, 'ymin': 0.36514...
72 {'xmin': 0.7484190464019775, 'ymin': 0.8785464...
73 {'xmin': 0.30867108702659607, 'ymin': 0.305013...
74 {'xmin': 0.0, 'ymin': 0.6255235075950623, 'xma...
75 {'xmin': 0.3157336711883545, 'ymin': 0.4645764...
[76 rows x 3 columns]
Prediction with multiple images is permitted:
bulk_result = detector.predict(dataset_test)
print(bulk_result)
predict_class predict_score 0 person 0.974653
1 motorbike 0.944522
2 car 0.570145
3 person 0.162251
4 car 0.138353
... ... ...
3351 motorbike 0.034022
3352 person 0.033459
3353 person 0.033070
3354 person 0.032404
3355 person 0.032285
predict_rois 0 {'xmin': 0.40379223227500916, 'ymin': 0.279169...
1 {'xmin': 0.3315899074077606, 'ymin': 0.4289079...
2 {'xmin': 0.0005976061220280826, 'ymin': 0.6380...
3 {'xmin': 0.6507402658462524, 'ymin': 0.0071541...
4 {'xmin': 0.7942018508911133, 'ymin': 0.8768404...
... ...
3351 {'xmin': 0.5266619324684143, 'ymin': 0.3252114...
3352 {'xmin': 0.2939976155757904, 'ymin': 0.0575568...
3353 {'xmin': 0.35572755336761475, 'ymin': 0.156040...
3354 {'xmin': 0.212220698595047, 'ymin': 0.35478591...
3355 {'xmin': 0.22767341136932373, 'ymin': 0.266247...
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...
... ...
3351 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
3352 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
3353 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
3354 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
3355 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
[3356 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/miniconda3/envs/autogluon-tutorial-object-detection-v3/lib/python3.9/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]