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, 17891.52KB/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[156]/validation[14] 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.dataset voc_tiny != auto
root.gpus (0, 1, 2, 3) != (0,)
root.train.early_stop_max_value 1.0 != inf
root.train.early_stop_patience -1 != 10
root.train.batch_size 16 != 8
root.train.early_stop_baseline 0.0 != -inf
root.train.seed 233 != 40
root.train.epochs 20 != 5
root.valid.batch_size 16 != 8
root.num_workers 4 != 8
}
Saved config to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/2551e640/.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%| | 162/181188 [00:00<02:13, 1357.61KB/s][A
0%| | 893/181188 [00:00<00:44, 4077.51KB/s][A
2%|▏ | 3755/181188 [00:00<00:13, 12801.65KB/s][A
6%|▌ | 11068/181188 [00:00<00:05, 32606.95KB/s][A
10%|█ | 18451/181188 [00:00<00:03, 45950.02KB/s][A
14%|█▍ | 25767/181188 [00:00<00:02, 54553.27KB/s][A
18%|█▊ | 33506/181188 [00:00<00:02, 60005.02KB/s][A
23%|██▎ | 42102/181188 [00:00<00:02, 67841.77KB/s][A
27%|██▋ | 49029/181188 [00:00<00:01, 66995.21KB/s][A
31%|███ | 55827/181188 [00:01<00:02, 61429.51KB/s][A
35%|███▍ | 62848/181188 [00:01<00:01, 63437.91KB/s][A
38%|███▊ | 69308/181188 [00:01<00:01, 63191.98KB/s][A
42%|████▏ | 76614/181188 [00:01<00:01, 66019.09KB/s][A
46%|████▌ | 83288/181188 [00:01<00:01, 54251.29KB/s][A
50%|████▉ | 89944/181188 [00:01<00:01, 56075.26KB/s][A
54%|█████▍ | 98288/181188 [00:01<00:01, 59288.45KB/s][A
59%|█████▊ | 106100/181188 [00:01<00:01, 60454.28KB/s][A
63%|██████▎ | 114219/181188 [00:02<00:01, 65820.01KB/s][A
67%|██████▋ | 121430/181188 [00:02<00:00, 67516.65KB/s][A
71%|███████ | 128856/181188 [00:02<00:00, 67758.22KB/s][A
75%|███████▍ | 135890/181188 [00:02<00:00, 68478.68KB/s][A
79%|███████▉ | 142942/181188 [00:02<00:00, 68158.91KB/s][A
83%|████████▎ | 149811/181188 [00:02<00:00, 58345.27KB/s][A
86%|████████▌ | 156137/181188 [00:02<00:00, 59617.04KB/s][A
90%|█████████ | 163828/181188 [00:02<00:00, 62338.16KB/s][A
95%|█████████▌| 172829/181188 [00:02<00:00, 69872.59KB/s][A
181189KB [00:03, 59127.47KB/s]
Start training from [Epoch 0]
[Epoch 0] Training cost: 11.573714, CrossEntropy=3.728243, SmoothL1=1.127197
[Epoch 0] Validation:
person=0.44370850301169057
boat=nan
bus=1.0000000000000002
car=0.6983151983151985
pottedplant=nan
cow=nan
chair=nan
bicycle=nan
dog=nan
motorbike=0.7003396332664626
mAP=0.710590833648338
[Epoch 0] Current best map: 0.710591 vs previous 0.000000, saved to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/2551e640/.trial_0/best_checkpoint.pkl
[Epoch 1] Training cost: 8.108994, CrossEntropy=2.828909, SmoothL1=1.248964
[Epoch 1] Validation:
person=0.552212022385263
boat=nan
bus=1.0000000000000002
car=0.396969696969697
pottedplant=nan
cow=nan
chair=nan
bicycle=nan
dog=nan
motorbike=0.7501724209466595
mAP=0.6748385350754049
[Epoch 2] Training cost: 7.806643, CrossEntropy=2.589857, SmoothL1=1.244739
[Epoch 2] Validation:
person=0.5371307762005437
boat=nan
bus=1.0000000000000002
car=0.8181818181818181
pottedplant=nan
cow=nan
chair=nan
bicycle=nan
dog=nan
motorbike=0.9238535709123945
mAP=0.8197915413236891
[Epoch 2] Current best map: 0.819792 vs previous 0.710591, saved to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/2551e640/.trial_0/best_checkpoint.pkl
[Epoch 3] Training cost: 8.179725, CrossEntropy=2.457756, SmoothL1=1.088299
[Epoch 3] Validation:
person=0.6809658324132009
boat=nan
bus=1.0000000000000002
car=1.0000000000000002
pottedplant=nan
cow=nan
chair=nan
bicycle=nan
dog=nan
motorbike=0.7988149300591485
mAP=0.8699451906180874
[Epoch 3] Current best map: 0.869945 vs previous 0.819792, saved to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/2551e640/.trial_0/best_checkpoint.pkl
[Epoch 4] Training cost: 8.068190, CrossEntropy=2.243278, SmoothL1=1.012117
[Epoch 4] Validation:
person=0.6487583617675077
boat=nan
bus=1.0000000000000002
car=0.8787878787878787
pottedplant=nan
cow=nan
chair=nan
bicycle=nan
dog=nan
motorbike=0.9479773100462756
mAP=0.8688808876504155
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
15%|█▌ | 8789/57421 [00:00<00:00, 87886.94KB/s][A
31%|███ | 17578/57421 [00:00<00:00, 53205.24KB/s][A
43%|████▎ | 24841/57421 [00:00<00:00, 59752.76KB/s][A
59%|█████▉ | 33787/57421 [00:00<00:00, 69409.11KB/s][A
72%|███████▏ | 41508/57421 [00:00<00:00, 71881.32KB/s][A
100%|██████████| 57421/57421 [00:00<00:00, 71089.67KB/s]
Finished, total runtime is 78.05 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': 40,
'start_epoch': 0,
'wd': 0.0005},
'valid': { 'batch_size': 8,
'iou_thresh': 0.5,
'metric': 'voc07',
'val_interval': 1}},
'total_time': 78.05333757400513,
'train_map': 0.6654241711590699,
'valid_map': 0.8699451906180874}
<autogluon.vision.detector.detector.ObjectDetector at 0x7f857ef90760>
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.21606801260709574
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.987616 1 motorbike 0.911168 2 car 0.865318 3 motorbike 0.199677 4 person 0.169182 .. ... ... 83 car 0.035219 84 car 0.034392 85 person 0.034351 86 person 0.034132 87 person 0.033992 predict_rois 0 {'xmin': 0.39281681180000305, 'ymin': 0.282186... 1 {'xmin': 0.3272760510444641, 'ymin': 0.4486108... 2 {'xmin': 0.0, 'ymin': 0.6430342793464661, 'xma... 3 {'xmin': 0.3797168731689453, 'ymin': 0.3262959... 4 {'xmin': 0.4073413014411926, 'ymin': 0.2805775... .. ... 83 {'xmin': 0.7081144452095032, 'ymin': 0.4470243... 84 {'xmin': 0.750139594078064, 'ymin': 0.48699212... 85 {'xmin': 0.45876190066337585, 'ymin': 0.160163... 86 {'xmin': 0.027597859501838684, 'ymin': 0.14144... 87 {'xmin': 0.9942991733551025, 'ymin': 0.0762252... [88 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.987616 1 motorbike 0.911168 2 car 0.865318 3 motorbike 0.199677 4 person 0.169182 ... ... ... 3107 person 0.067728 3108 person 0.065110 3109 person 0.063336 3110 person 0.061514 3111 person 0.061129 predict_rois 0 {'xmin': 0.39281681180000305, 'ymin': 0.282186... 1 {'xmin': 0.3272760510444641, 'ymin': 0.4486108... 2 {'xmin': 0.0, 'ymin': 0.6430342793464661, 'xma... 3 {'xmin': 0.3797168731689453, 'ymin': 0.3262959... 4 {'xmin': 0.4073413014411926, 'ymin': 0.2805775... ... ... 3107 {'xmin': 0.4231966733932495, 'ymin': 0.5537188... 3108 {'xmin': 0.1777685582637787, 'ymin': 0.4085057... 3109 {'xmin': 0.272922545671463, 'ymin': 0.38768002... 3110 {'xmin': 0.7461000680923462, 'ymin': 0.4210445... 3111 {'xmin': 0.5460037589073181, 'ymin': 0.1245168... 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... ... ... 3107 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... 3108 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... 3109 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... 3110 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... 3111 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... [3112 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]