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, 18712.44KB/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[160]/validation[10] splits.
Starting HPO experiments
0%| | 0/2 [00:00<?, ?it/s]
modified configs(<old> != <new>): {
root.ssd.base_network vgg16_atrous != resnet50_v1
root.ssd.data_shape 300 != 512
root.train.seed 233 != 559
root.train.early_stop_baseline 0.0 != -inf
root.train.early_stop_max_value 1.0 != inf
root.train.batch_size 16 != 8
root.train.epochs 20 != 5
root.train.early_stop_patience -1 != 10
root.dataset_root ~/.mxnet/datasets/ != auto
root.gpus (0, 1, 2, 3) != (0,)
root.valid.batch_size 16 != 8
root.num_workers 4 != 8
root.dataset voc_tiny != auto
}
Saved config to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/d851feeb/.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][A
0%| | 87/181188 [00:00<04:12, 718.53KB/s][A
0%| | 512/181188 [00:00<01:17, 2336.88KB/s][A
1%| | 2178/181188 [00:00<00:24, 7438.23KB/s][A
5%|▍ | 8313/181188 [00:00<00:06, 26105.45KB/s][A
7%|▋ | 13533/181188 [00:00<00:04, 34738.78KB/s][A
12%|█▏ | 20873/181188 [00:00<00:03, 46825.74KB/s][A
16%|█▌ | 29068/181188 [00:00<00:02, 57815.04KB/s][A
20%|█▉ | 36219/181188 [00:00<00:02, 62044.87KB/s][A
25%|██▍ | 44436/181188 [00:00<00:02, 68205.53KB/s][A
29%|██▉ | 52703/181188 [00:01<00:01, 72359.86KB/s][A
34%|███▎ | 60872/181188 [00:01<00:01, 75077.85KB/s][A
38%|███▊ | 68947/181188 [00:01<00:01, 76783.38KB/s][A
43%|████▎ | 77471/181188 [00:01<00:01, 79326.36KB/s][A
47%|████▋ | 85435/181188 [00:01<00:01, 78965.40KB/s][A
52%|█████▏ | 93518/181188 [00:01<00:01, 79521.61KB/s][A
56%|█████▋ | 101951/181188 [00:01<00:00, 80956.57KB/s][A
61%|██████ | 110059/181188 [00:01<00:00, 80642.59KB/s][A
66%|██████▌ | 118796/181188 [00:01<00:00, 82651.80KB/s][A
70%|███████ | 127069/181188 [00:01<00:00, 81362.10KB/s][A
75%|███████▍ | 135215/181188 [00:02<00:00, 80775.03KB/s][A
79%|███████▉ | 143984/181188 [00:02<00:00, 82540.79KB/s][A
84%|████████▍ | 152244/181188 [00:02<00:00, 80172.95KB/s][A
88%|████████▊ | 160278/181188 [00:02<00:00, 79143.31KB/s][A
93%|█████████▎| 169409/181188 [00:02<00:00, 82461.96KB/s][A
181189KB [00:02, 68267.67KB/s]
Start training from [Epoch 0]
[Epoch 0] Training cost: 11.623797, CrossEntropy=3.477833, SmoothL1=0.999335
[Epoch 0] Validation:
motorbike=0.7364400305576777
dog=nan
chair=nan
bus=1.0000000000000002
boat=nan
bicycle=nan
car=1.0000000000000002
pottedplant=nan
person=0.4653756947827604
cow=nan
mAP=0.8004539313351097
[Epoch 0] Current best map: 0.800454 vs previous 0.000000, saved to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/d851feeb/.trial_0/best_checkpoint.pkl
[Epoch 1] Training cost: 8.043416, CrossEntropy=2.905452, SmoothL1=1.232674
[Epoch 1] Validation:
motorbike=0.8723599632690542
dog=nan
chair=nan
bus=1.0000000000000002
boat=nan
bicycle=nan
car=0.7727272727272726
pottedplant=nan
person=0.5924904476136342
cow=nan
mAP=0.8093944209024904
[Epoch 1] Current best map: 0.809394 vs previous 0.800454, saved to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/d851feeb/.trial_0/best_checkpoint.pkl
[Epoch 2] Training cost: 8.113708, CrossEntropy=2.558043, SmoothL1=1.165307
[Epoch 2] Validation:
motorbike=0.8609168609168609
dog=nan
chair=nan
bus=1.0000000000000002
boat=nan
bicycle=nan
car=0.8484848484848483
pottedplant=nan
person=0.8103896103896103
cow=nan
mAP=0.8799478299478299
[Epoch 2] Current best map: 0.879948 vs previous 0.809394, saved to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/d851feeb/.trial_0/best_checkpoint.pkl
[Epoch 3] Training cost: 8.098701, CrossEntropy=2.276939, SmoothL1=1.029039
[Epoch 3] Validation:
motorbike=0.9000000000000001
dog=nan
chair=nan
bus=1.0000000000000002
boat=nan
bicycle=nan
car=0.8484848484848483
pottedplant=nan
person=0.6706566161111615
cow=nan
mAP=0.8547853661490025
[Epoch 4] Training cost: 8.018461, CrossEntropy=2.140040, SmoothL1=0.913727
[Epoch 4] Validation:
motorbike=0.8636363636363638
dog=nan
chair=nan
bus=1.0000000000000002
boat=nan
bicycle=nan
car=1.0000000000000002
pottedplant=nan
person=0.6181660763478947
cow=nan
mAP=0.8704506099960647
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][A
0%| | 101/57421 [00:00<01:08, 834.77KB/s][A
1%| | 510/57421 [00:00<00:24, 2315.80KB/s][A
4%|▍ | 2187/57421 [00:00<00:07, 7503.35KB/s][A
14%|█▍ | 8255/57421 [00:00<00:01, 25981.19KB/s][A
25%|██▌ | 14446/57421 [00:00<00:01, 37898.76KB/s][A
38%|███▊ | 21810/57421 [00:00<00:00, 48077.98KB/s][A
54%|█████▎ | 30805/57421 [00:00<00:00, 61012.72KB/s][A
66%|██████▋ | 38182/57421 [00:00<00:00, 64915.17KB/s][A
81%|████████▏ | 46662/57421 [00:00<00:00, 69404.28KB/s][A
100%|██████████| 57421/57421 [00:01<00:00, 51536.31KB/s]
Finished, total runtime is 77.39 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': 559,
'start_epoch': 0,
'wd': 0.0005},
'valid': { 'batch_size': 8,
'iou_thresh': 0.5,
'metric': 'voc07',
'val_interval': 1}},
'total_time': 77.38539409637451,
'train_map': 0.6689091544795001,
'valid_map': 0.8799478299478299}
<autogluon.vision.detector.detector.ObjectDetector at 0x7fb8ef500070>
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.20307480342233608
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.978754 1 person 0.974033 2 motorbike 0.785656 3 motorbike 0.375339 4 car 0.307463 .. ... ... 70 car 0.047625 71 car 0.047448 72 car 0.046967 73 person 0.046943 74 person 0.046917 predict_rois 0 {'xmin': 0.32383882999420166, 'ymin': 0.424137... 1 {'xmin': 0.39464864134788513, 'ymin': 0.280243... 2 {'xmin': 0.005586221814155579, 'ymin': 0.63656... 3 {'xmin': 0.604659914970398, 'ymin': 0.11020074... 4 {'xmin': 1.8816566807799973e-05, 'ymin': 0.654... .. ... 70 {'xmin': 0.0012137467274442315, 'ymin': 0.6228... 71 {'xmin': 0.7455456852912903, 'ymin': 0.4412457... 72 {'xmin': 0.003545400220900774, 'ymin': 0.47952... 73 {'xmin': 0.1956995129585266, 'ymin': 0.0091462... 74 {'xmin': 0.0667409673333168, 'ymin': 0.0, 'xma... [75 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.978754 1 person 0.974033 2 motorbike 0.785656 3 motorbike 0.375339 4 car 0.307463 ... ... ... 4310 person 0.029772 4311 person 0.029758 4312 person 0.029529 4313 person 0.029462 4314 person 0.029453 predict_rois 0 {'xmin': 0.32383882999420166, 'ymin': 0.424137... 1 {'xmin': 0.39464864134788513, 'ymin': 0.280243... 2 {'xmin': 0.005586221814155579, 'ymin': 0.63656... 3 {'xmin': 0.604659914970398, 'ymin': 0.11020074... 4 {'xmin': 1.8816566807799973e-05, 'ymin': 0.654... ... ... 4310 {'xmin': 0.005453572608530521, 'ymin': 0.98426... 4311 {'xmin': 0.016683831810951233, 'ymin': 0.20650... 4312 {'xmin': 0.44923925399780273, 'ymin': 0.161095... 4313 {'xmin': 0.18606220185756683, 'ymin': 0.418832... 4314 {'xmin': 0.2801220118999481, 'ymin': 0.3936091... 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... ... ... 4310 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... 4311 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... 4312 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... 4313 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... 4314 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... [4315 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]