.. _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 autogluon.vision and ObjectDetector: .. code:: python import autogluon.core as ag from autogluon.vision import ObjectDetector 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} hyperparamter_tune_kwargs={'num_trials': 2} detector.fit(dataset_train, time_limit=time_limit, hyperparameters=hyperparameters, hyperparamter_tune_kwargs=hyperparamter_tune_kwargs) .. parsed-literal:: :class: output WARNING:gluoncv.auto.tasks.object_detection:The number of requested GPUs is greater than the number of available GPUs.Reduce the number to 1 INFO:gluoncv.auto.tasks.object_detection:Randomly split train_data into train[148]/validation[22] splits. INFO:gluoncv.auto.tasks.object_detection:Starting fit without HPO INFO:SSDEstimator:modified configs( != ): { INFO:SSDEstimator:root.dataset_root ~/.mxnet/datasets/ != auto INFO:SSDEstimator:root.ssd.base_network vgg16_atrous != resnet50_v1 INFO:SSDEstimator:root.ssd.data_shape 300 != 512 INFO:SSDEstimator:root.num_workers 4 != 8 INFO:SSDEstimator:root.valid.batch_size 16 != 8 INFO:SSDEstimator:root.gpus (0, 1, 2, 3) != (0,) INFO:SSDEstimator:root.train.epochs 20 != 5 INFO:SSDEstimator:root.train.seed 233 != 256 INFO:SSDEstimator:root.train.batch_size 16 != 8 INFO:SSDEstimator:root.dataset voc_tiny != auto INFO:SSDEstimator:} INFO:SSDEstimator:Saved config to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/5ae7eb85/.trial_0/config.yaml INFO:SSDEstimator:Using transfer learning from ssd_512_resnet50_v1_coco, the other network parameters are ignored. INFO:SSDEstimator:Start training from [Epoch 0] INFO:SSDEstimator:[Epoch 0] Training cost: 10.727367, CrossEntropy=3.513595, SmoothL1=1.035403 INFO:SSDEstimator:[Epoch 0] Validation: bus=0.3727272727272728 boat=1.0000000000000002 pottedplant=0.0 cow=0.4431818181818181 car=0.6532630194193811 chair=0.0 motorbike=0.7352613830220521 person=0.7560912501754332 dog=1.0000000000000002 bicycle=0.053592649180884466 mAP=0.5014117392706842 INFO:SSDEstimator:[Epoch 0] Current best map: 0.501412 vs previous 0.000000, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/5ae7eb85/.trial_0/best_checkpoint.pkl INFO:SSDEstimator:Pickled to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/5ae7eb85/.trial_0/best_checkpoint.pkl INFO:SSDEstimator:[Epoch 1] Training cost: 9.157554, CrossEntropy=2.535531, SmoothL1=1.147917 INFO:SSDEstimator:[Epoch 1] Validation: bus=0.6799999999999999 boat=0.12500000000000003 pottedplant=0.007575757575757575 cow=0.8409090909090906 car=0.8040419211181666 chair=0.022727272727272728 motorbike=0.8464332532458806 person=0.7817982254778224 dog=1.0000000000000002 bicycle=0.07726198151730068 mAP=0.5185747502571291 INFO:SSDEstimator:[Epoch 1] Current best map: 0.518575 vs previous 0.501412, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/5ae7eb85/.trial_0/best_checkpoint.pkl INFO:SSDEstimator:Pickled to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/5ae7eb85/.trial_0/best_checkpoint.pkl INFO:SSDEstimator:[Epoch 2] Training cost: 9.182029, CrossEntropy=2.489080, SmoothL1=1.128329 INFO:SSDEstimator:[Epoch 2] Validation: bus=0.8545454545454547 boat=0.012658227848101264 pottedplant=0.09090909090909093 cow=0.6611570247933887 car=0.8334340078526126 chair=0.016393442622950817 motorbike=0.8787759049291193 person=0.8082931401027106 dog=0.5000000000000001 bicycle=0.2622969506982047 mAP=0.4918463244301633 INFO:SSDEstimator:[Epoch 3] Training cost: 9.914636, CrossEntropy=2.297858, SmoothL1=1.044861 INFO:SSDEstimator:[Epoch 3] Validation: bus=1.0000000000000002 boat=1.0000000000000002 pottedplant=0.45783132530120485 cow=0.909090909090909 car=0.8540152657799717 chair=0.0 motorbike=0.8721004298512463 person=0.8368825737656028 dog=1.0000000000000002 bicycle=0.3424136838770985 mAP=0.7272334187666034 INFO:SSDEstimator:[Epoch 3] Current best map: 0.727233 vs previous 0.518575, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/5ae7eb85/.trial_0/best_checkpoint.pkl INFO:SSDEstimator:Pickled to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/5ae7eb85/.trial_0/best_checkpoint.pkl INFO:SSDEstimator:[Epoch 4] Training cost: 9.352062, CrossEntropy=2.141819, SmoothL1=1.035096 INFO:SSDEstimator:[Epoch 4] Validation: bus=0.909090909090909 boat=1.0000000000000002 pottedplant=0.34545454545454546 cow=0.909090909090909 car=0.8543414151702923 chair=0.20000000000000004 motorbike=0.8639876259319788 person=0.8326804296623781 dog=1.0000000000000002 bicycle=0.6236933797909409 mAP=0.7538339214191954 INFO:SSDEstimator:[Epoch 4] Current best map: 0.753834 vs previous 0.727233, saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/5ae7eb85/.trial_0/best_checkpoint.pkl INFO:SSDEstimator:Pickled to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-object-detection-v3/docs/_build/eval/tutorials/object_detection/5ae7eb85/.trial_0/best_checkpoint.pkl INFO:gluoncv.auto.tasks.object_detection:Finished, total runtime is 85.85 s INFO:gluoncv.auto.tasks.object_detection:{ 'best_config': { 'batch_size': 8, 'dist_ip_addrs': None, '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/5ae7eb85', 'lr': 0.001, 'ngpus_per_trial': 8, 'nthreads_per_trial': 128, 'num_trials': 1, 'num_workers': 8, 'search_strategy': 'random', 'seed': 256, 'time_limits': 1800, 'transfer': 'ssd_512_resnet50_v1_coco', 'wall_clock_tick': 1615352931.185964}, 'total_time': 70.9633002281189, 'train_map': 0.7538339214191954, 'valid_map': 0.7538339214191954} .. 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. 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(). .. 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.09756356213049126 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 INFO:numexpr.utils:NumExpr defaulting to 8 threads. .. parsed-literal:: :class: output predict_class predict_score \ 0 person 0.991635 1 motorbike 0.961137 2 motorbike 0.388443 3 motorbike 0.224987 4 person 0.145723 .. ... ... 93 car 0.018262 94 car 0.018070 95 chair 0.018025 96 bicycle 0.018009 97 person 0.017947 predict_rois 0 {'xmin': 0.38058650493621826, 'ymin': 0.297392... 1 {'xmin': 0.29545846581459045, 'ymin': 0.434530... 2 {'xmin': 0.35542112588882446, 'ymin': 0.360992... 3 {'xmin': 0.0, 'ymin': 0.6330187320709229, 'xma... 4 {'xmin': 0.9954492449760437, 'ymin': 0.4819799... .. ... 93 {'xmin': 0.7400792241096497, 'ymin': 0.4255206... 94 {'xmin': 0.9942001700401306, 'ymin': 0.6661317... 95 {'xmin': 0.35813114047050476, 'ymin': 0.001968... 96 {'xmin': 0.4280034899711609, 'ymin': 0.5494390... 97 {'xmin': 0.9175676703453064, 'ymin': 0.4559347... [98 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.991635 1 motorbike 0.961137 2 motorbike 0.388443 3 motorbike 0.224987 4 person 0.145723 ... ... ... 4151 person 0.020871 4152 person 0.020866 4153 person 0.020838 4154 person 0.020715 4155 car 0.020637 predict_rois \ 0 {'xmin': 0.38058650493621826, 'ymin': 0.297392... 1 {'xmin': 0.29545846581459045, 'ymin': 0.434530... 2 {'xmin': 0.35542112588882446, 'ymin': 0.360992... 3 {'xmin': 0.0, 'ymin': 0.6330187320709229, 'xma... 4 {'xmin': 0.9954492449760437, 'ymin': 0.4819799... ... ... 4151 {'xmin': 0.9317517876625061, 'ymin': 0.1451122... 4152 {'xmin': 0.46750766038894653, 'ymin': 0.198774... 4153 {'xmin': 0.9516244530677795, 'ymin': 0.1586815... 4154 {'xmin': 0.9207784533500671, 'ymin': 0.1214014... 4155 {'xmin': 0.2580762505531311, 'ymin': 0.2674473... 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... ... ... 4151 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb... 4152 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb... 4153 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb... 4154 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb... 4155 /var/lib/jenkins/.gluoncv/datasets/tiny_motorb... [4156 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/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]