.. _sec_object_detection_quick: 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 :ref:`sec_imgquick` 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: .. code:: python from autogluon.vision import ObjectDetector .. parsed-literal:: :class: output /var/lib/jenkins/miniconda3/envs/autogluon-tutorial-object-detection-v3/lib/python3.9/site-packages/gluoncv/__init__.py:40: UserWarning: Both `mxnet==1.7.0` and `torch==1.10.1+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. .. code:: python url = 'https://autogluon.s3.amazonaws.com/datasets/tiny_motorbike.zip' dataset_train = ObjectDetector.Dataset.from_voc(url, splits='trainval') .. parsed-literal:: :class: output 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. .. code:: python 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) .. parsed-literal:: :class: output The number of requested GPUs is greater than the number of available GPUs.Reduce the number to 1 Randomly split train_data into train[158]/validation[12] splits. Starting HPO experiments .. parsed-literal:: :class: output 0%| | 0/2 [00:00 != ): { root.gpus (0, 1, 2, 3) != (0,) root.valid.batch_size 16 != 8 root.ssd.base_network vgg16_atrous != resnet50_v1 root.ssd.data_shape 300 != 512 root.dataset_root ~/.mxnet/datasets/ != auto root.num_workers 4 != 8 root.train.epochs 20 != 5 root.train.seed 233 != 588 root.train.early_stop_patience -1 != 10 root.train.early_stop_max_value 1.0 != inf root.train.batch_size 16 != 8 root.train.early_stop_baseline 0.0 != -inf root.dataset voc_tiny != auto } Saved config to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/cea9627b/.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.329026, CrossEntropy=3.629686, SmoothL1=1.035936 [Epoch 0] Validation: bus=nan chair=0.0 pottedplant=nan person=0.6231751007613078 cow=nan dog=nan bicycle=0.0 boat=nan motorbike=0.4718204467312355 car=0.8831168831168833 mAP=0.39562248612188533 [Epoch 0] Current best map: 0.395622 vs previous 0.000000, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/cea9627b/.trial_0/best_checkpoint.pkl [Epoch 1] Training cost: 8.257013, CrossEntropy=2.783386, SmoothL1=1.261059 [Epoch 1] Validation: bus=nan chair=0.0 pottedplant=nan person=0.6296870217324763 cow=nan dog=nan bicycle=0.0 boat=nan motorbike=0.518920916481892 car=0.7537190082644629 mAP=0.38046538929576623 [Epoch 2] Training cost: 8.192107, CrossEntropy=2.691025, SmoothL1=1.179705 [Epoch 2] Validation: bus=nan chair=0.0 pottedplant=nan person=0.6974957912457911 cow=nan dog=nan bicycle=0.0 boat=nan motorbike=0.65718684167882 car=0.34090909090909094 mAP=0.3391183447667404 [Epoch 3] Training cost: 8.580774, CrossEntropy=2.307059, SmoothL1=1.003880 [Epoch 3] Validation: bus=nan chair=0.0 pottedplant=nan person=0.7572150072150072 cow=nan dog=nan bicycle=0.0 boat=nan motorbike=0.7360773634967183 car=0.7459893048128342 mAP=0.44785633510491196 [Epoch 3] Current best map: 0.447856 vs previous 0.395622, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/cea9627b/.trial_0/best_checkpoint.pkl [Epoch 4] Training cost: 8.084239, CrossEntropy=2.088778, SmoothL1=0.958997 [Epoch 4] Validation: bus=nan chair=0.0 pottedplant=nan person=0.7526355996944232 cow=nan dog=nan bicycle=0.0 boat=nan motorbike=0.6535268957517761 car=0.7142857142857143 mAP=0.42408964194638277 Applying the state from the best checkpoint... Finished, total runtime is 66.20 s { 'best_config': { 'dataset': 'auto', 'dataset_root': 'auto', 'estimator': , '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': 588, 'start_epoch': 0, 'wd': 0.0005}, 'valid': { 'batch_size': 8, 'iou_thresh': 0.5, 'metric': 'voc07', 'val_interval': 1}}, 'total_time': 66.1982650756836, 'train_map': 0.7848649650103364, 'valid_map': 0.44785633510491196} .. parsed-literal:: :class: output 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(). .. code:: python 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])) .. parsed-literal:: :class: output tiny_motorbike/ ├── Annotations/ ├── ImageSets/ └── JPEGImages/ mAP on test dataset: 0.024272081734926815 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. .. code:: python image_path = dataset_test.iloc[0]['image'] result = detector.predict(image_path) print(result) .. parsed-literal:: :class: output predict_class predict_score \ 0 person 0.994859 1 motorbike 0.897595 2 bicycle 0.159514 3 car 0.108762 4 motorbike 0.107096 .. ... ... 66 car 0.032677 67 person 0.032589 68 person 0.032493 69 person 0.032453 70 chair 0.032441 predict_rois 0 {'xmin': 0.40365543961524963, 'ymin': 0.278845... 1 {'xmin': 0.31720587611198425, 'ymin': 0.447850... 2 {'xmin': 0.3179326057434082, 'ymin': 0.4476031... 3 {'xmin': 0.0, 'ymin': 0.6284662485122681, 'xma... 4 {'xmin': 0.0, 'ymin': 0.6287426352500916, 'xma... .. ... 66 {'xmin': 0.3179326057434082, 'ymin': 0.4476031... 67 {'xmin': 0.3488602340221405, 'ymin': 0.2295106... 68 {'xmin': 0.4020317494869232, 'ymin': 0.3283315... 69 {'xmin': 0.3850856423377991, 'ymin': 0.3481267... 70 {'xmin': 0.9034497141838074, 'ymin': 0.0723451... [71 rows x 3 columns] Prediction with multiple images is permitted: .. code:: python bulk_result = detector.predict(dataset_test) print(bulk_result) .. parsed-literal:: :class: output predict_class predict_score \ 0 person 0.994859 1 motorbike 0.897595 2 bicycle 0.159514 3 car 0.108762 4 motorbike 0.107096 ... ... ... 4044 person 0.025370 4045 person 0.025097 4046 person 0.025089 4047 person 0.025078 4048 person 0.024939 predict_rois \ 0 {'xmin': 0.40365543961524963, 'ymin': 0.278845... 1 {'xmin': 0.31720587611198425, 'ymin': 0.447850... 2 {'xmin': 0.3179326057434082, 'ymin': 0.4476031... 3 {'xmin': 0.0, 'ymin': 0.6284662485122681, 'xma... 4 {'xmin': 0.0, 'ymin': 0.6287426352500916, 'xma... ... ... 4044 {'xmin': 0.3165423274040222, 'ymin': 0.6834895... 4045 {'xmin': 0.4035860300064087, 'ymin': 0.0868127... 4046 {'xmin': 0.2324240803718567, 'ymin': 0.0590429... 4047 {'xmin': 0.3869120478630066, 'ymin': 0.1109670... 4048 {'xmin': 0.2259625345468521, 'ymin': 0.9872213... 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... ... ... 4044 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb... 4045 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb... 4046 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb... 4047 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb... 4048 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb... [4049 rows x 4 columns] We can also save the trained model, and use it later. .. code:: python savefile = 'detector.ag' detector.save(savefile) new_detector = ObjectDetector.load(savefile) .. parsed-literal:: :class: output /var/lib/jenkins/miniconda3/envs/autogluon-tutorial-object-detection-v3/lib/python3.9/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]