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.10.2+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[148]/validation[22] splits.
Starting HPO experiments
0%| | 0/2 [00:00<?, ?it/s]
modified configs(<old> != <new>): {
root.dataset_root ~/.mxnet/datasets/ != auto
root.dataset voc_tiny != auto
root.train.batch_size 16 != 8
root.train.early_stop_patience -1 != 10
root.train.epochs 20 != 5
root.train.early_stop_baseline 0.0 != -inf
root.train.early_stop_max_value 1.0 != inf
root.train.seed 233 != 409
root.gpus (0, 1, 2, 3) != (0,)
root.num_workers 4 != 8
root.ssd.base_network vgg16_atrous != resnet50_v1
root.ssd.data_shape 300 != 512
root.valid.batch_size 16 != 8
}
Saved config to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/056ec2db/.trial_0/config.yaml
No gpu detected, fallback to cpu. You can ignore this warning if this is intended.
Using transfer learning from ssd_512_resnet50_v1_coco, the other network parameters are ignored.
Start training from [Epoch 0]
[Epoch 0] Training cost: 66.784484, CrossEntropy=3.814896, SmoothL1=1.099648
[Epoch 0] Validation:
chair=nan
person=0.7144378731393329
bicycle=nan
car=0.6704085780091742
motorbike=0.790986790986791
boat=nan
dog=nan
pottedplant=0.00802139037433155
cow=nan
bus=nan
mAP=0.5459636581274074
[Epoch 0] Current best map: 0.545964 vs previous 0.000000, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/056ec2db/.trial_0/best_checkpoint.pkl
[Epoch 1] Training cost: 70.069097, CrossEntropy=2.816050, SmoothL1=1.203322
[Epoch 1] Validation:
chair=nan
person=0.692227001368942
bicycle=nan
car=0.6193495052830091
motorbike=0.7381777757438465
boat=nan
dog=nan
pottedplant=0.0
cow=nan
bus=nan
mAP=0.5124385705989494
[Epoch 2] Training cost: 65.953285, CrossEntropy=2.473636, SmoothL1=1.084630
[Epoch 2] Validation:
chair=nan
person=0.6886954658844611
bicycle=nan
car=0.6818181818181819
motorbike=0.7078637271819092
boat=nan
dog=nan
pottedplant=0.0
cow=nan
bus=nan
mAP=0.519594343721138
[Epoch 3] Training cost: 68.609943, CrossEntropy=2.229116, SmoothL1=0.966308
[Epoch 3] Validation:
chair=nan
person=0.6564136620954802
bicycle=nan
car=1.0000000000000002
motorbike=0.823500216930344
boat=nan
dog=nan
pottedplant=0.0
cow=nan
bus=nan
mAP=0.6199784697564561
[Epoch 3] Current best map: 0.619978 vs previous 0.545964, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/056ec2db/.trial_0/best_checkpoint.pkl
[Epoch 4] Training cost: 65.505345, CrossEntropy=2.193415, SmoothL1=0.978995
[Epoch 4] Validation:
chair=nan
person=0.6915480604152169
bicycle=nan
car=0.7234848484848485
motorbike=0.8010638010638009
boat=nan
dog=nan
pottedplant=0.0
cow=nan
bus=nan
mAP=0.5540241774909667
Applying the state from the best checkpoint...
Finished, total runtime is 386.28 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': 409,
'start_epoch': 0,
'wd': 0.0005},
'valid': { 'batch_size': 8,
'iou_thresh': 0.5,
'metric': 'voc07',
'val_interval': 1}},
'total_time': 386.2827181816101,
'train_map': 0.7272349653862946,
'valid_map': 0.6199784697564561}
<autogluon.vision.detector.detector.ObjectDetector at 0x7fae8a325fd0>
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.5663367140669382
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.993426 1 person 0.984185 2 car 0.750799 3 car 0.169281 4 motorbike 0.165467 .. ... ... 67 car 0.023269 68 car 0.023256 69 person 0.023089 70 car 0.023036 71 car 0.023034 predict_rois 0 {'xmin': 0.31400594115257263, 'ymin': 0.423492... 1 {'xmin': 0.40062546730041504, 'ymin': 0.297083... 2 {'xmin': 0.0, 'ymin': 0.6154444813728333, 'xma... 3 {'xmin': 0.7174825668334961, 'ymin': 0.3963941... 4 {'xmin': 0.0, 'ymin': 0.6185303926467896, 'xma... .. ... 67 {'xmin': 0.6949290633201599, 'ymin': 0.4761260... 68 {'xmin': 0.03558524325489998, 'ymin': 0.368901... 69 {'xmin': 0.1387866586446762, 'ymin': 0.8483116... 70 {'xmin': 0.0, 'ymin': 0.7108750343322754, 'xma... 71 {'xmin': 0.053460072726011276, 'ymin': 0.40237... [72 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.993426 1 person 0.984185 2 car 0.750799 3 car 0.169281 4 motorbike 0.165467 ... ... ... 4331 person 0.030525 4332 person 0.030276 4333 person 0.030247 4334 person 0.030156 4335 chair 0.030064 predict_rois 0 {'xmin': 0.31400594115257263, 'ymin': 0.423492... 1 {'xmin': 0.40062546730041504, 'ymin': 0.297083... 2 {'xmin': 0.0, 'ymin': 0.6154444813728333, 'xma... 3 {'xmin': 0.7174825668334961, 'ymin': 0.3963941... 4 {'xmin': 0.0, 'ymin': 0.6185303926467896, 'xma... ... ... 4331 {'xmin': 0.5849460363388062, 'ymin': 0.0757173... 4332 {'xmin': 0.39304789900779724, 'ymin': 0.002860... 4333 {'xmin': 0.8782337307929993, 'ymin': 0.3585894... 4334 {'xmin': 0.9024809002876282, 'ymin': 0.1144954... 4335 {'xmin': 0.3000996708869934, 'ymin': 0.2109396... 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... ... ... 4331 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb... 4332 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb... 4333 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb... 4334 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb... 4335 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb... [4336 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]