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[155]/validation[15] splits.
Starting fit without HPO
modified configs(<old> != <new>): {
root.dataset_root ~/.mxnet/datasets/ != auto
root.dataset voc_tiny != auto
root.valid.batch_size 16 != 8
root.train.seed 233 != 276
root.train.batch_size 16 != 8
root.train.early_stop_baseline 0.0 != -inf
root.train.early_stop_max_value 1.0 != inf
root.train.epochs 20 != 5
root.train.early_stop_patience -1 != 10
root.num_workers 4 != 8
root.ssd.data_shape 300 != 512
root.ssd.base_network vgg16_atrous != resnet50_v1
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/0051deab/.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.380765, CrossEntropy=3.792875, SmoothL1=1.062698
[Epoch 0] Validation:
cow=nan
dog=nan
car=1.0000000000000002
pottedplant=nan
bicycle=0.0
bus=1.0000000000000002
motorbike=0.8373577402989169
chair=nan
boat=nan
person=0.8893984228640086
mAP=0.7453512326325852
[Epoch 0] Current best map: 0.745351 vs previous 0.000000, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/0051deab/.trial_0/best_checkpoint.pkl
[Epoch 1] Training cost: 8.126496, CrossEntropy=2.456822, SmoothL1=1.042939
[Epoch 1] Validation:
cow=nan
dog=nan
car=1.0000000000000002
pottedplant=nan
bicycle=0.0
bus=1.0000000000000002
motorbike=0.8311355311355311
chair=nan
boat=nan
person=0.8263806900170537
mAP=0.731503244230517
[Epoch 2] Training cost: 8.666463, CrossEntropy=2.298794, SmoothL1=0.996099
[Epoch 2] Validation:
cow=nan
dog=nan
car=0.9090909090909091
pottedplant=nan
bicycle=0.0
bus=1.0000000000000002
motorbike=0.8256188256188255
chair=nan
boat=nan
person=0.7999423097563595
mAP=0.7069304088932189
[Epoch 3] Training cost: 7.961231, CrossEntropy=2.258920, SmoothL1=0.972762
[Epoch 3] Validation:
cow=nan
dog=nan
car=0.9454545454545457
pottedplant=nan
bicycle=0.0
bus=1.0000000000000002
motorbike=0.9090909090909093
chair=nan
boat=nan
person=0.8696033872288463
mAP=0.7448297683548604
[Epoch 4] Training cost: 8.101715, CrossEntropy=2.211277, SmoothL1=0.960873
[Epoch 4] Validation:
cow=nan
dog=nan
car=0.8636363636363636
pottedplant=nan
bicycle=0.0
bus=1.0000000000000002
motorbike=0.8430735930735931
chair=nan
boat=nan
person=0.9142228739002934
mAP=0.7241865661220501
Applying the state from the best checkpoint...
Finished, total runtime is 64.07 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/0051deab',
'lr': 0.001,
'ngpus_per_trial': 8,
'nthreads_per_trial': 128,
'num_trials': 1,
'num_workers': 8,
'scheduler': 'local',
'search_strategy': 'random',
'seed': 276,
'time_limits': 1800,
'transfer': 'ssd_512_resnet50_v1_coco',
'wall_clock_tick': 1624558116.5470297},
'total_time': 47.2263126373291,
'train_map': 0.7909779148259738,
'valid_map': 0.7453512326325852}
<autogluon.vision.detector.detector.ObjectDetector at 0x7f01f9d1a1d0>
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.03392521561126212
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.966625
1 motorbike 0.897586
2 person 0.236946
3 person 0.161338
4 person 0.142619
.. ... ...
88 person 0.024545
89 chair 0.024537
90 person 0.024441
91 person 0.024277
92 person 0.024225
predict_rois
0 {'xmin': 0.3883911073207855, 'ymin': 0.2853710...
1 {'xmin': 0.32461124658584595, 'ymin': 0.430736...
2 {'xmin': 0.9941485524177551, 'ymin': 0.5980668...
3 {'xmin': 0.3308553695678711, 'ymin': 0.4322595...
4 {'xmin': 0.9954673051834106, 'ymin': 0.8241726...
.. ...
88 {'xmin': 0.9907503724098206, 'ymin': 0.6771276...
89 {'xmin': 0.30692780017852783, 'ymin': 0.446932...
90 {'xmin': 0.8992050290107727, 'ymin': 0.0119361...
91 {'xmin': 0.9544028043746948, 'ymin': 0.3871219...
92 {'xmin': 0.9694010019302368, 'ymin': 0.2644164...
[93 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.966625
1 motorbike 0.897586
2 person 0.236946
3 person 0.161338
4 person 0.142619
... ... ...
4489 chair 0.018779
4490 person 0.018736
4491 chair 0.018437
4492 person 0.018423
4493 person 0.018311
predict_rois 0 {'xmin': 0.3883911073207855, 'ymin': 0.2853710...
1 {'xmin': 0.32461124658584595, 'ymin': 0.430736...
2 {'xmin': 0.9941485524177551, 'ymin': 0.5980668...
3 {'xmin': 0.3308553695678711, 'ymin': 0.4322595...
4 {'xmin': 0.9954673051834106, 'ymin': 0.8241726...
... ...
4489 {'xmin': 0.6117137670516968, 'ymin': 0.2451491...
4490 {'xmin': 0.14095193147659302, 'ymin': 0.455573...
4491 {'xmin': 0.6955369710922241, 'ymin': 0.2798658...
4492 {'xmin': 0.9132900834083557, 'ymin': 0.3606295...
4493 {'xmin': 0.18184493482112885, 'ymin': 0.501161...
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...
... ...
4489 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
4490 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
4491 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
4492 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
4493 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb...
[4494 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]