Object Detection - Quick Start¶
Note: AutoGluon ObjectDetector will be deprecated in v0.7. Please try our AutoGluon MultiModalPredictor for more functionalities and better support for your object detection need.
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.1+cu113 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. ' INFO:matplotlib.font_manager:generated new fontManager INFO:torch.distributed.nn.jit.instantiator:Created a temporary directory at /tmp/tmp5t84yk5e INFO:torch.distributed.nn.jit.instantiator:Writing /tmp/tmp5t84yk5e/_remote_module_non_scriptable.py
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, 18422.00KB/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/autogluon/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[154]/validation[16] splits.
Starting HPO experiments
0%| | 0/2 [00:00<?, ?it/s]
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%| | 86/181188 [00:00<04:13, 715.53KB/s][A
0%| | 509/181188 [00:00<01:17, 2329.12KB/s][A
1%| | 2173/181188 [00:00<00:23, 7462.84KB/s][A
4%|▍ | 8153/181188 [00:00<00:06, 25647.34KB/s][A
8%|▊ | 15332/181188 [00:00<00:04, 40952.50KB/s][A
13%|█▎ | 23878/181188 [00:00<00:02, 53966.65KB/s][A
18%|█▊ | 32658/181188 [00:00<00:02, 64441.73KB/s][A
22%|██▏ | 39969/181188 [00:00<00:02, 67098.99KB/s][A
27%|██▋ | 48486/181188 [00:00<00:01, 70991.65KB/s][A
32%|███▏ | 57445/181188 [00:01<00:01, 76539.78KB/s][A
36%|███▌ | 65180/181188 [00:01<00:01, 75812.79KB/s][A
41%|████ | 73449/181188 [00:01<00:01, 77192.88KB/s][A
45%|████▌ | 82310/181188 [00:01<00:01, 80568.60KB/s][A
50%|████▉ | 90403/181188 [00:01<00:01, 78649.87KB/s][A
54%|█████▍ | 98301/181188 [00:01<00:01, 78487.31KB/s][A
59%|█████▉ | 107079/181188 [00:01<00:00, 81219.93KB/s][A
64%|██████▎ | 115224/181188 [00:01<00:01, 61410.02KB/s][A
68%|██████▊ | 124093/181188 [00:02<00:00, 65573.69KB/s][A
73%|███████▎ | 132350/181188 [00:02<00:00, 69821.74KB/s][A
77%|███████▋ | 139806/181188 [00:02<00:00, 69957.97KB/s][A
82%|████████▏ | 148034/181188 [00:02<00:00, 72837.60KB/s][A
87%|████████▋ | 156837/181188 [00:02<00:00, 77047.14KB/s][A
91%|█████████ | 164759/181188 [00:02<00:00, 77371.44KB/s][A
181189KB [00:02, 66305.81KB/s]
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, 832.69KB/s][A
1%| | 505/57421 [00:00<00:24, 2279.42KB/s][A
4%|▍ | 2189/57421 [00:00<00:07, 7458.40KB/s][A
15%|█▌ | 8701/57421 [00:00<00:01, 27392.15KB/s][A
26%|██▋ | 15077/57421 [00:00<00:01, 39413.49KB/s][A
40%|███▉ | 22749/57421 [00:00<00:00, 49799.03KB/s][A
54%|█████▎ | 30754/57421 [00:00<00:00, 59101.24KB/s][A
65%|██████▌ | 37435/57421 [00:00<00:00, 61449.53KB/s][A
78%|███████▊ | 44923/57421 [00:00<00:00, 63725.83KB/s][A
100%|██████████| 57421/57421 [00:01<00:00, 50500.16KB/s]
Finished, total runtime is 75.16 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': 354,
'start_epoch': 0,
'wd': 0.0005},
'valid': { 'batch_size': 8,
'iou_thresh': 0.5,
'metric': 'voc07',
'val_interval': 1}},
'total_time': 75.15520191192627,
'train_map': 0.5566367074541787,
'valid_map': 0.6737077035219098}
<autogluon.vision.detector.detector.ObjectDetector at 0x7f9693b66bb0>
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.029805655337570236
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.967722 1 person 0.959702 2 person 0.419745 3 motorbike 0.342670 4 motorbike 0.342054 .. ... ... 81 person 0.029861 82 car 0.029857 83 person 0.029856 84 person 0.029729 85 person 0.029619 predict_rois 0 {'xmin': 0.31137406826019287, 'ymin': 0.430643... 1 {'xmin': 0.3941088318824768, 'ymin': 0.3023520... 2 {'xmin': 0.03708141669631004, 'ymin': 0.0, 'xm... 3 {'xmin': 0.7145042419433594, 'ymin': 0.3932311... 4 {'xmin': 0.3697831630706787, 'ymin': 0.3336802... .. ... 81 {'xmin': 0.9026026129722595, 'ymin': 0.0056145... 82 {'xmin': 0.7002421617507935, 'ymin': 0.1231089... 83 {'xmin': 0.9563814997673035, 'ymin': 0.0198556... 84 {'xmin': 0.9838224053382874, 'ymin': 0.9529601... 85 {'xmin': 1.0, 'ymin': 0.8152856826782227, 'xma... [86 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.967722 1 person 0.959702 2 person 0.419745 3 motorbike 0.342670 4 motorbike 0.342054 ... ... ... 3928 person 0.038407 3929 person 0.038276 3930 person 0.038260 3931 cow 0.038036 3932 person 0.037624 predict_rois 0 {'xmin': 0.31137406826019287, 'ymin': 0.430643... 1 {'xmin': 0.3941088318824768, 'ymin': 0.3023520... 2 {'xmin': 0.03708141669631004, 'ymin': 0.0, 'xm... 3 {'xmin': 0.7145042419433594, 'ymin': 0.3932311... 4 {'xmin': 0.3697831630706787, 'ymin': 0.3336802... ... ... 3928 {'xmin': 0.9336948394775391, 'ymin': 0.5461749... 3929 {'xmin': 0.9207127690315247, 'ymin': 0.5612320... 3930 {'xmin': 0.1027938649058342, 'ymin': 0.6384891... 3931 {'xmin': 0.04941064119338989, 'ymin': 0.303672... 3932 {'xmin': 0.8856835961341858, 'ymin': 0.5401898... 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... ... ... 3928 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... 3929 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... 3930 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... 3931 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... 3932 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... [3933 rows x 4 columns]
We can also save the trained model, and use it later.
Warning
ObjectDetector.load()
used pickle
module implicitly, which is
known to be insecure. It is possible to construct malicious pickle
data which will execute arbitrary code during unpickling. Never load
data that could have come from an untrusted source, or that could
have been tampered with. Only load data you trust.
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]