Loading

Food Recognition Benchmark 2022

Detectron2 training and submissions (Quick, Active)

v2 of baseline, now supports submissions via Colab for both quick and active participation

jerome_patel

🍕 Food Recognition Benchmark

Problem Statement

Detecting & Segmenting various kinds of food from an image. For ex. Someone got into new restaurent and get a food that he has never seen, well our DL model is in rescue, so our DL model will help indentifying which food it is from the class our model is being trained on!

Dataset

We will be using data from Food Recognition Challenge - A benchmark for image-based food recognition challange which is running since 2020.

https://www.aicrowd.com/challenges/food-recognition-benchmark-2022#datasets

We have a total of 39k training images with 3k validation set and 4k public-testing set. All the images are RGB and annotations exist in MS-COCO format.

Evaluation

The evaluation metrics is IOU aka. Intersection Over Union ( more about that later ).

The actualy metric is computed by averaging over all the precision and recall values for IOU which greater than 0.5.

https://www.aicrowd.com/challenges/food-recognition-challenge#evaluation-criteria

What does this notebook contains?

  1. Setting our Workspace 💼

  2. Data Exploration 🧐

    • Reading Dataset
    • Data Visualisations
  3. Image Visulisation 🖼️

    • Reading Images
  4. Creating our Dataset 🔨

    • Fixing the Dataset
    • Creating our dataset
  5. Creating our Model 🏭

    • Creating R-CNN Model
    • Setting up hyperparameters
  6. Training the Model 🚂

    • Setting up Tensorboard
    • Start Training!
  7. Evaluating the model 🧪

    • Evaluating our Model
  8. Testing the Model 💯

    • Testing the Model
  9. Submitting our predictions 📝

Setting our Workspace 💼

In this section we will be downloading our dataset, unzipping it & downliading detectron2 library and importing all libraries that we will be using

Downloading & Unzipping our Dataset

In [1]:
# Login to AIcrowd
!pip install aicrowd-cli > /dev/null
!aicrowd login
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
google-colab 1.0.0 requires requests~=2.23.0, but you have requests 2.27.1 which is incompatible.
datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.
Please login here: https://api.aicrowd.com/auth/4BofnkUZ7DvV7JilNhG4b3Jl1dK9gOITxhGqL8CEGic
/usr/bin/xdg-open: 851: /usr/bin/xdg-open: www-browser: not found
/usr/bin/xdg-open: 851: /usr/bin/xdg-open: links2: not found
/usr/bin/xdg-open: 851: /usr/bin/xdg-open: elinks: not found
/usr/bin/xdg-open: 851: /usr/bin/xdg-open: links: not found
/usr/bin/xdg-open: 851: /usr/bin/xdg-open: lynx: not found
/usr/bin/xdg-open: 851: /usr/bin/xdg-open: w3m: not found
xdg-open: no method available for opening 'https://api.aicrowd.com/auth/4BofnkUZ7DvV7JilNhG4b3Jl1dK9gOITxhGqL8CEGic'
API Key valid
Saved API Key successfully!
In [2]:
# List dataset for this challenge
!aicrowd dataset list -c food-recognition-benchmark-2022

# Download dataset
!aicrowd dataset download -c food-recognition-benchmark-2022
                          Datasets for challenge #962                           
┌───┬────────────────────────────────┬────────────────────────────────┬────────┐
│ #  Title                           Description                       Size │
├───┼────────────────────────────────┼────────────────────────────────┼────────┤
│ 0 │ public_validation_set_2.0.tar… │ Validation Dataset (contains   │    59M │
│   │                                │ 1000 images and 498            │        │
│   │                                │ categories, with annotations)  │        │
│ 1 │ public_test_release_2.0.tar.gz │ [Public] Testing Dataset       │   197M │
│   │                                │ (contains 3000 images and 498  │        │
│   │                                │ categories, without            │        │
│   │                                │ annotations)                   │        │
│ 2 │ public_training_set_release_2… │ Training Dataset (contains     │ 2.14GB │
│   │                                │ 39962 images and 498           │        │
│   │                                │ categories)                    │        │
└───┴────────────────────────────────┴────────────────────────────────┴────────┘
public_validation_set_2.0.tar.gz: 100% 62.4M/62.4M [00:02<00:00, 24.9MB/s]
public_test_release_2.0.tar.gz: 100% 207M/207M [00:07<00:00, 26.6MB/s]
public_training_set_release_2.0.tar.gz: 100% 2.30G/2.30G [02:03<00:00, 18.6MB/s]
In [3]:
# Create data directory
!mkdir -p data/ data/train data/val data/test
!cp *test* data/test && cd data/test && echo "Extracting test dataset" && tar -xvf *test* > /dev/null
!cp *val* data/val && cd data/val && echo "Extracting val dataset" &&  tar -xvf *val* > /dev/null
!cp *train* data/train && cd data/train && echo "Extracting train dataset" &&  tar -xvf *train* > /dev/null
Extracting test dataset
Extracting val dataset
Extracting train dataset

Mount the Google Drive

In [4]:
from google.colab import drive
drive.mount('/content/drive')
Mounted at /content/drive

So, the data directory is something like this:

Importing Necessary Libraries

In [5]:
# Making sure that we are using GPUs
!nvidia-smi
Mon Jan 31 10:59:51 2022       
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 495.46       Driver Version: 460.32.03    CUDA Version: 11.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |
| N/A   34C    P8    10W /  70W |      0MiB / 15109MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+
                                                                               
+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+
In [6]:
!pip install cython pyyaml==5.1
!pip install -U pycocotools

import torch
TORCH_VERSION = ".".join(torch.__version__.split(".")[:2])
CUDA_VERSION = torch.__version__.split("+")[-1]
print("torch: ", TORCH_VERSION, "; cuda: ", CUDA_VERSION)
# Install detectron2 that matches the above pytorch version
# See https://detectron2.readthedocs.io/tutorials/install.html for instructions
!pip install detectron2 -f https://dl.fbaipublicfiles.com/detectron2/wheels/$CUDA_VERSION/torch$TORCH_VERSION/index.html
# If there is not yet a detectron2 release that matches the given torch + CUDA version, you need to install a different pytorch.
#don't forget to restart the runtime
Requirement already satisfied: cython in /usr/local/lib/python3.7/dist-packages (0.29.26)
Collecting pyyaml==5.1
  Downloading PyYAML-5.1.tar.gz (274 kB)
     |████████████████████████████████| 274 kB 8.3 MB/s 
Building wheels for collected packages: pyyaml
  Building wheel for pyyaml (setup.py) ... done
  Created wheel for pyyaml: filename=PyYAML-5.1-cp37-cp37m-linux_x86_64.whl size=44092 sha256=a8c9ad069271ab72c32b727fb1ff7c5b4256da293f80533ef5cbbf79577fff6d
  Stored in directory: /root/.cache/pip/wheels/77/f5/10/d00a2bd30928b972790053b5de0c703ca87324f3fead0f2fd9
Successfully built pyyaml
Installing collected packages: pyyaml
  Attempting uninstall: pyyaml
    Found existing installation: PyYAML 3.13
    Uninstalling PyYAML-3.13:
      Successfully uninstalled PyYAML-3.13
Successfully installed pyyaml-5.1
Requirement already satisfied: pycocotools in /usr/local/lib/python3.7/dist-packages (2.0.4)
Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from pycocotools) (1.19.5)
Requirement already satisfied: matplotlib>=2.1.0 in /usr/local/lib/python3.7/dist-packages (from pycocotools) (3.2.2)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.1.0->pycocotools) (0.11.0)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.1.0->pycocotools) (3.0.7)
Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.1.0->pycocotools) (2.8.2)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.1.0->pycocotools) (1.3.2)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.1->matplotlib>=2.1.0->pycocotools) (1.15.0)
torch:  1.10 ; cuda:  cu111
Looking in links: https://dl.fbaipublicfiles.com/detectron2/wheels/cu111/torch1.10/index.html
Collecting detectron2
  Downloading https://dl.fbaipublicfiles.com/detectron2/wheels/cu111/torch1.10/detectron2-0.6%2Bcu111-cp37-cp37m-linux_x86_64.whl (7.0 MB)
     |████████████████████████████████| 7.0 MB 5.0 MB/s 
Requirement already satisfied: termcolor>=1.1 in /usr/local/lib/python3.7/dist-packages (from detectron2) (1.1.0)
Collecting hydra-core>=1.1
  Downloading hydra_core-1.1.1-py3-none-any.whl (145 kB)
     |████████████████████████████████| 145 kB 7.7 MB/s 
Requirement already satisfied: pydot in /usr/local/lib/python3.7/dist-packages (from detectron2) (1.3.0)
Collecting iopath<0.1.10,>=0.1.7
  Downloading iopath-0.1.9-py3-none-any.whl (27 kB)
Requirement already satisfied: cloudpickle in /usr/local/lib/python3.7/dist-packages (from detectron2) (1.3.0)
Collecting fvcore<0.1.6,>=0.1.5
  Downloading fvcore-0.1.5.post20220119.tar.gz (55 kB)
     |████████████████████████████████| 55 kB 4.2 MB/s 
Requirement already satisfied: tensorboard in /usr/local/lib/python3.7/dist-packages (from detectron2) (2.7.0)
Requirement already satisfied: Pillow>=7.1 in /usr/local/lib/python3.7/dist-packages (from detectron2) (7.1.2)
Requirement already satisfied: pycocotools>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from detectron2) (2.0.4)
Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from detectron2) (0.8.9)
Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from detectron2) (0.16.0)
Collecting black==21.4b2
  Downloading black-21.4b2-py3-none-any.whl (130 kB)
     |████████████████████████████████| 130 kB 62.3 MB/s 
Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from detectron2) (3.2.2)
Requirement already satisfied: tqdm>4.29.0 in /usr/local/lib/python3.7/dist-packages (from detectron2) (4.62.3)
Collecting omegaconf>=2.1
  Downloading omegaconf-2.1.1-py3-none-any.whl (74 kB)
     |████████████████████████████████| 74 kB 4.5 MB/s 
Collecting yacs>=0.1.8
  Downloading yacs-0.1.8-py3-none-any.whl (14 kB)
Requirement already satisfied: click>=7.1.2 in /usr/local/lib/python3.7/dist-packages (from black==21.4b2->detectron2) (7.1.2)
Requirement already satisfied: typing-extensions>=3.7.4 in /usr/local/lib/python3.7/dist-packages (from black==21.4b2->detectron2) (3.10.0.2)
Collecting pathspec<1,>=0.8.1
  Downloading pathspec-0.9.0-py2.py3-none-any.whl (31 kB)
Collecting typed-ast>=1.4.2
  Downloading typed_ast-1.5.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (843 kB)
     |████████████████████████████████| 843 kB 68.6 MB/s 
Requirement already satisfied: appdirs in /usr/local/lib/python3.7/dist-packages (from black==21.4b2->detectron2) (1.4.4)
Collecting mypy-extensions>=0.4.3
  Downloading mypy_extensions-0.4.3-py2.py3-none-any.whl (4.5 kB)
Requirement already satisfied: toml>=0.10.1 in /usr/local/lib/python3.7/dist-packages (from black==21.4b2->detectron2) (0.10.2)
Collecting regex>=2020.1.8
  Downloading regex-2022.1.18-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (748 kB)
     |████████████████████████████████| 748 kB 63.6 MB/s 
Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from fvcore<0.1.6,>=0.1.5->detectron2) (1.19.5)
Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.7/dist-packages (from fvcore<0.1.6,>=0.1.5->detectron2) (5.1)
Requirement already satisfied: importlib-resources in /usr/local/lib/python3.7/dist-packages (from hydra-core>=1.1->detectron2) (5.4.0)
Collecting antlr4-python3-runtime==4.8
  Downloading antlr4-python3-runtime-4.8.tar.gz (112 kB)
     |████████████████████████████████| 112 kB 72.9 MB/s 
Collecting portalocker
  Downloading portalocker-2.3.2-py2.py3-none-any.whl (15 kB)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->detectron2) (1.3.2)
Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->detectron2) (2.8.2)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->detectron2) (3.0.7)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->detectron2) (0.11.0)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.1->matplotlib->detectron2) (1.15.0)
Requirement already satisfied: zipp>=3.1.0 in /usr/local/lib/python3.7/dist-packages (from importlib-resources->hydra-core>=1.1->detectron2) (3.7.0)
Requirement already satisfied: grpcio>=1.24.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard->detectron2) (1.43.0)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard->detectron2) (1.8.1)
Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard->detectron2) (0.6.1)
Requirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard->detectron2) (2.27.1)
Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard->detectron2) (1.0.1)
Requirement already satisfied: protobuf>=3.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard->detectron2) (3.17.3)
Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard->detectron2) (57.4.0)
Requirement already satisfied: absl-py>=0.4 in /usr/local/lib/python3.7/dist-packages (from tensorboard->detectron2) (1.0.0)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard->detectron2) (0.4.6)
Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.7/dist-packages (from tensorboard->detectron2) (0.37.1)
Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard->detectron2) (3.3.6)
Requirement already satisfied: google-auth<3,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard->detectron2) (1.35.0)
Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard->detectron2) (4.8)
Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard->detectron2) (0.2.8)
Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard->detectron2) (4.2.4)
Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard->detectron2) (1.3.0)
Requirement already satisfied: importlib-metadata>=4.4 in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard->detectron2) (4.10.1)
Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard->detectron2) (0.4.8)
Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard->detectron2) (2.10)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard->detectron2) (2021.10.8)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard->detectron2) (1.24.3)
Requirement already satisfied: charset-normalizer~=2.0.0 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard->detectron2) (2.0.10)
Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard->detectron2) (3.1.1)
Building wheels for collected packages: fvcore, antlr4-python3-runtime
  Building wheel for fvcore (setup.py) ... done
  Created wheel for fvcore: filename=fvcore-0.1.5.post20220119-py3-none-any.whl size=65267 sha256=9305f35432399317848a54b5d1ac79b12bf07b2077bcb8ee502fd602a235eab0
  Stored in directory: /root/.cache/pip/wheels/f3/b8/eb/61ed840f80d7198725bc061872b6019a7b3e9db4dbadf68083
  Building wheel for antlr4-python3-runtime (setup.py) ... done
  Created wheel for antlr4-python3-runtime: filename=antlr4_python3_runtime-4.8-py3-none-any.whl size=141230 sha256=fc5882cd333378439e50114436e09e8ec843871558c35d36bb8ba6acffb0acaa
  Stored in directory: /root/.cache/pip/wheels/ca/33/b7/336836125fc9bb4ceaa4376d8abca10ca8bc84ddc824baea6c
Successfully built fvcore antlr4-python3-runtime
Installing collected packages: portalocker, antlr4-python3-runtime, yacs, typed-ast, regex, pathspec, omegaconf, mypy-extensions, iopath, hydra-core, fvcore, black, detectron2
  Attempting uninstall: regex
    Found existing installation: regex 2019.12.20
    Uninstalling regex-2019.12.20:
      Successfully uninstalled regex-2019.12.20
Successfully installed antlr4-python3-runtime-4.8 black-21.4b2 detectron2-0.6+cu111 fvcore-0.1.5.post20220119 hydra-core-1.1.1 iopath-0.1.9 mypy-extensions-0.4.3 omegaconf-2.1.1 pathspec-0.9.0 portalocker-2.3.2 regex-2022.1.18 typed-ast-1.5.2 yacs-0.1.8
In [7]:
# You may need to restart your runtime prior to this, to let your installation take effect
# Some basic setup:
# Setup detectron2 logger
import detectron2
from detectron2.utils.logger import setup_logger
setup_logger()

# import some common libraries
import numpy as np
import pandas as pd
import cv2
import json
from tqdm.notebook import tqdm
import subprocess
import time
from pathlib import Path


# import some common detectron2 utilities
from detectron2 import model_zoo
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.visualizer import Visualizer
from detectron2.data import MetadataCatalog
from detectron2.utils.visualizer import ColorMode
from detectron2.data.datasets import register_coco_instances
from detectron2.engine import DefaultTrainer
from detectron2.evaluation import COCOEvaluator, inference_on_dataset
from detectron2.data import build_detection_test_loader
from detectron2.structures import Boxes, BoxMode 
import pycocotools.mask as mask_util


# For reading annotations file
from pycocotools.coco import COCO

# utilities
from pprint import pprint # For beautiful print!
from collections import OrderedDict
import os 

# For data visualisation
import matplotlib.pyplot as plt
import plotly.graph_objects as go
import plotly.express as px
from google.colab.patches import cv2_imshow
/usr/local/lib/python3.7/dist-packages/distributed/config.py:20: YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.
  defaults = yaml.load(f)

Data Exploration 🧐

In this section we are going to read our dataset & doing some data visualisations

Reading Data

In [8]:
# Reading annotations.json
TRAIN_ANNOTATIONS_PATH = "data/train/annotations.json"
TRAIN_IMAGE_DIRECTIORY = "data/train/images/"

VAL_ANNOTATIONS_PATH = "data/val/annotations.json"
VAL_IMAGE_DIRECTIORY = "data/val/images/"

train_coco = COCO(TRAIN_ANNOTATIONS_PATH)
loading annotations into memory...
Done (t=3.48s)
creating index...
index created!
In [9]:
# Reading the annotation files
with open(TRAIN_ANNOTATIONS_PATH) as f:
  train_annotations_data = json.load(f)

with open(VAL_ANNOTATIONS_PATH) as f:
  val_annotations_data = json.load(f)
train_annotations_data['annotations'][0]
Out[9]:
{'area': 5059.0,
 'bbox': [39.5, 39.5, 167.0, 92.0],
 'category_id': 1352,
 'id': 184135,
 'image_id': 131094,
 'iscrowd': 0,
 'segmentation': [[115.0,
   206.5,
   98.0,
   204.5,
   74.5,
   182.0,
   65.0,
   167.5,
   47.5,
   156.0,
   39.5,
   137.0,
   39.5,
   130.0,
   51.0,
   118.5,
   62.00000000000001,
   112.5,
   76.0,
   113.5,
   121.5,
   151.0,
   130.5,
   169.0,
   131.5,
   185.0,
   128.5,
   195.0]]}

Data Format 🔍

Our COCO data format is something like this -

"info": {...},
"categories": [...],
"images": [...],
"annotations": [...],

In which categories is like this

[
  {'id': 2578,
  'name': 'water',
  'name_readable': 'Water',
  'supercategory': 'food'},
  {'id': 1157,
  'name': 'pear',
  'name_readable': 'Pear',
  'supercategory': 'food'},
  ...
  {'id': 1190,
  'name': 'peach',
  'name_readable': 'Peach',
  'supercategory': 'food'}
]

Info is empty ( not sure why )

images is like this

[
  {'file_name': '065537.jpg', 
  'height': 464, 
  'id': 65537, 
  'width': 464},
  {'file_name': '065539.jpg', 
  'height': 464, 
  'id': 65539, 
  'width': 464},
 ...
  {'file_name': '069900.jpg', 
  'height': 391, 
  'id': 69900, 
  'width': 392},
]

Annotations is like this

{'area': 44320.0,
 'bbox': [86.5, 127.49999999999999, 286.0, 170.0],
 'category_id': 2578,
 'id': 102434,
 'image_id': 65537,
 'iscrowd': 0,
 'segmentation': [[235.99999999999997,
   372.5,
   169.0,
   372.5,
   ...
   368.5,
   264.0,
   371.5]]}
In [10]:
# Reading all classes
category_ids = train_coco.loadCats(train_coco.getCatIds())
category_names = [_["name_readable"] for _ in category_ids]

print("## Categories\n-", "\n- ".join(category_names))
## Categories
- Bread, wholemeal
- Jam
- Water
- Bread, sourdough
- Banana
- Soft cheese
- Ham, raw
- Hard cheese
- Cottage cheese
- Bread, half white
- Coffee, with caffeine
- Fruit salad
- Pancakes
- Tea
- Salmon, smoked
- Avocado
- Spring onion / scallion
- Ristretto, with caffeine
- Ham
- Egg
- Bacon, frying
- Chips, french fries
- Juice, apple
- Chicken
- Tomato, raw 
- Broccoli
- Shrimp, boiled
- Beetroot, steamed, without addition of salt
- Carrot, raw
- Chickpeas
- French salad dressing
- Pasta, Hörnli
- Sauce, cream
- Meat balls
- Pasta
- Tomato sauce
- Cheese
- Pear
- Cashew nut
- Almonds
- Lentils
- Mixed vegetables
- Peanut butter
- Apple
- Blueberries
- Cucumber
- Cocoa powder
- Greek Yaourt, yahourt, yogourt ou yoghourt
- Maple syrup (Concentrate)
- Buckwheat, grain peeled
- Butter
- Herbal tea
- Mayonnaise
- Soup, vegetable
- Wine, red
- Wine, white
- Green bean, steamed, without addition of salt
- Sausage
- Pizza, Margherita, baked
- Salami
- Mushroom
- (bread, meat substitute, lettuce, sauce)
- Tart
- Tea, verveine
- Rice
- White coffee, with caffeine
- Linseeds
- Sunflower seeds
- Ham, cooked
- Bell pepper, red, raw 
- Zucchini
- Green asparagus
- Tartar sauce
- Lye pretzel (soft)
- Cucumber, pickled 
- Curry, vegetarian
- Yaourt, yahourt, yogourt ou yoghourt, natural
- Soup of lentils, Dahl (Dhal)
- Soup, cream of vegetables
- Balsamic vinegar
- Salmon
- Salt cake (vegetables, filled)
- Bacon
- Orange
- Pasta, noodles
- Cream
- Cake, chocolate
- Pasta, spaghetti
- Black olives
- Parmesan
- Spaetzle
- Salad, lambs' ear
- Salad, leaf / salad, green
- Potatoes steamed
- White cabbage
- Halloumi
- Beetroot, raw
- Bread, grain
- Applesauce, unsweetened, canned
- Cheese for raclette
- Mushrooms
- Bread, white
- Curds, natural, with at most 10% fidm
- Bagel (without filling)
- Quiche, with cheese, baked, with puff pastry
- Soup, potato
- Bouillon, vegetable
- Beef, sirloin steak
- Taboulé, prepared, with couscous
- Eggplant
- Bread
- Turnover with meat (small meat pie, empanadas)
- Mungbean sprouts
- Mozzarella
- Pasta, penne
- Lasagne, vegetable, prepared
- Mandarine
- Kiwi
- French beans
- Tartar (meat)
- Spring roll (fried)
- Pork, chop
- Caprese salad (Tomato Mozzarella)
- Leaf spinach
- Roll of half-white or white flour, with large void
- Pasta, ravioli, stuffing
- Omelette, plain
- Tuna
- Dark chocolate
- Sauce (savoury)
- Dried raisins
- Ice tea
- Kaki
- Macaroon
- Smoothie
- Crêpe, plain
- Chicken nuggets
- Chili con carne, prepared
- Veggie burger
- Cream spinach
- Cod
- Chinese cabbage
- Hamburger (Bread, meat, ketchup)
- Soup, pumpkin
- Sushi
- Chestnuts
- Coffee, decaffeinated
- Sauce, soya
- Balsamic salad dressing
- Pasta, twist
- Bolognaise sauce
- Leek
- Fajita (bread only)
- Potato-gnocchi
- Beef, cut into stripes (only meat)
- Rice noodles/vermicelli
- Tea, ginger
- Tea, green
- Bread, whole wheat
- Onion
- Garlic
- Hummus
- Pizza, with vegetables, baked
- Beer
- Glucose drink 50g
- Chicken, wing
- Ratatouille
- Peanut
- High protein pasta (made of lentils, peas, ...)
- Cauliflower
- Quiche, with spinach, baked, with cake dough
- Green olives
- Brazil nut
- Eggplant caviar
- Bread, pita
- Pasta, wholemeal
- Sauce, pesto
- Oil
- Couscous
- Sauce, roast
- Prosecco
- Crackers
- Bread, toast
- Shrimp / prawn (small)
- Panna cotta
- Romanesco
- Water with lemon juice
- Espresso, with caffeine
- Egg, scrambled, prepared
- Juice, orange
- Ice cubes
- Braided white loaf
- Emmental cheese
- Croissant, wholegrain
- Hazelnut-chocolate spread(Nutella, Ovomaltine, Caotina)
- Tomme
- Water, mineral
- Hazelnut
- Bacon, raw
- Bread, nut
- Black Forest Tart
- Soup, Miso
- Peach
- Figs
- Beef, filet
- Mustard, Dijon
- Rice, Basmati
- Mashed potatoes, prepared, with full fat milk, with butter
- Dumplings
- Pumpkin
- Swiss chard
- Red cabbage
- Spinach, raw
- Naan (indien bread)
- Chicken curry (cream/coconut milk. curry spices/paste))
- Crunch Müesli
- Biscuits
- Bread, French (white flour)
- Meatloaf
- Fresh cheese
- Honey
- Vegetable mix, peas and carrots
- Parsley
- Brownie
- Dairy ice cream
- Tea, black
- Carrot cake
- Fish fingers (breaded)
- Salad dressing
- Dried meat
- Chicken, breast
- Mixed salad (chopped without sauce)
- Feta
- Praline
- Tea, peppermint
- Walnut
- Potato salad, with mayonnaise yogurt dressing
- Kebab in pita bread
- Kolhrabi
- Alfa sprouts
- Brussel sprouts
- Bacon, cooking
- Gruyère
- Bulgur
- Grapes
- Pork, escalope
- Chocolate egg, small
- Cappuccino
- Zucchini, stewed, without addition of fat, without addition of salt
- Crisp bread, Wasa
- Bread, black
- Perch fillets (lake)
- Rosti
- Mango
- Sandwich (ham, cheese and butter)
- Müesli
- Spinach, steamed, without addition of salt
- Fish
- Risotto, without cheese, cooked
- Milk Chocolate with hazelnuts
- Cake (oblong)
- Crisps
- Pork
- Pomegranate
- Sweet corn, canned
- Flakes, oat
- Greek salad
- Cantonese fried rice
- Sesame seeds
- Bouillon
- Baked potato
- Fennel
- Meat
- Bread, olive
- Croutons
- Philadelphia
- Mushroom, (average), stewed, without addition of fat, without addition of salt
- Bell pepper, red, stewed, without addition of fat, without addition of salt
- White chocolate
- Mixed nuts
- Breadcrumbs (unspiced)
- Fondue
- Sauce, mushroom
- Tea, spice
- Strawberries
- Tea, rooibos
- Pie, plum, baked, with cake dough
- Potatoes au gratin, dauphinois, prepared
- Capers
- Vegetables
- Bread, wholemeal toast
- Red radish
- Fruit tart
- Beans, kidney
- Sauerkraut
- Mustard
- Country fries
- Ketchup
- Pasta, linguini, parpadelle, Tagliatelle
- Chicken, cut into stripes (only meat)
- Cookies
- Sun-dried tomatoe
- Bread, Ticino
- Semi-hard cheese
- Margarine
- Porridge, prepared, with partially skimmed milk
- Soya drink (soy milk)
- Juice, multifruit
- Popcorn salted
- Chocolate, filled
- Milk chocolate
- Bread, fruit
- Mix of dried fruits and nuts
- Corn
- Tête de Moine
- Dates
- Pistachio
- Celery
- White radish
- Oat milk
- Cream cheese
- Bread, rye
- Witloof chicory
- Apple crumble
- Goat cheese (soft)
- Grapefruit, pomelo
- Risotto, with mushrooms, cooked
- Blue mould cheese
- Biscuit with Butter
- Guacamole
- Pecan nut
- Tofu
- Cordon bleu, from pork schnitzel, fried
- Paprika chips
- Quinoa
- Kefir drink
- M&M's
- Salad, rocket
- Bread, spelt
- Pizza, with ham, with mushrooms, baked
- Fruit coulis
- Plums
- Beef, minced (only meat)
- Pizza, with ham, baked
- Pineapple
- Soup, tomato
- Cheddar
- Tea, fruit
- Rice, Jasmin
- Seeds
- Focaccia
- Milk
- Coleslaw (chopped without sauce)
- Pastry, flaky
- Curd
- Savoury puff pastry stick
- Sweet potato
- Chicken, leg
- Croissant
- Sour cream
- Ham, turkey
- Processed cheese
- Fruit compotes
- Cheesecake
- Pasta, tortelloni, stuffing
- Sauce, cocktail
- Croissant with chocolate filling
- Pumpkin seeds
- Artichoke
- Champagne
- Grissini
- Sweets / candies
- Brie
- Wienerli (Swiss sausage)
- Syrup (diluted, ready to drink)
- Apple pie
- White bread with butter, eggs and milk
- Savoury puff pastry
- Anchovies
- Tuna, in oil, drained
- Lemon pie
- Meat terrine, paté
- Coriander
- Falafel (balls)
- Berries
- Latte macchiato, with caffeine
- Faux-mage Cashew, vegan chers
- Beans, white
- Sugar Melon
- Mixed seeds
- Hamburger
- Hamburger bun
- Oil & vinegar salad dressing
- Soya Yaourt, yahourt, yogourt ou yoghourt
- Chocolate milk, chocolate drink
- Celeriac
- Chocolate mousse
- Cenovis, yeast spread
- Thickened cream (> 35%)
- Meringue
- Lamb, chop
- Shrimp / prawn (large)
- Beef
- Lemon
- Croque monsieur
- Chives
- Chocolate cookies
- Birchermüesli, prepared, no sugar added
- Fish crunchies (battered)
- Muffin
- Savoy cabbage, steamed, without addition of salt
- Pine nuts
- Chorizo
- Chia grains
- Frying sausage
- French pizza from Alsace, baked
- Chocolate
- Cooked sausage
- Grits, polenta, maize flour
- Gummi bears, fruit jellies, Jelly babies with fruit essence
- Wine, rosé
- Coca Cola
- Raspberries
- Roll with pieces of chocolate
- Goat, (average), raw
- Lemon Cake
- Coconut milk
- Rice, wild
- Gluten-free bread
- Pearl onions
- Buckwheat pancake
- Bread, 5-grain
- Light beer
- Sugar, glazing
- Tzatziki
- Butter, herb
- Ham croissant
- Corn crisps
- Lentils green (du Puy, du Berry)
- Cocktail
- Rice, whole-grain
- Veal sausage
- Cervelat
- Sorbet
- Aperitif, with alcohol, apérol, Spritz
- Dips
- Corn Flakes
- Peas
- Tiramisu
- Apricots
- Cake, marble
- Lamb
- Lasagne, meat, prepared
- Coca Cola Zero
- Cake, salted
- Dough (puff pastry, shortcrust, bread, pizza dough)
- Rice waffels
- Sekt
- Brioche
- Vegetable au gratin, baked
- Mango dried
- Processed meat, Charcuterie
- Mousse
- Sauce, sweet & sour
- Basil
- Butter, spread, puree almond
- Pie, apricot, baked, with cake dough
- Rusk, wholemeal
- Beef, roast
- Vanille cream, cooked, Custard, Crème dessert
- Pasta in conch form
- Nuts
- Sauce, carbonara
- Fig, dried
- Pasta in butterfly form, farfalle
- Minced meat
- Carrot, steamed, without addition of salt
- Ebly
- Damson plum
- Shoots
- Bouquet garni
- Coconut
- Banana cake
- Waffle
- Apricot, dried
- Sauce, curry
- Watermelon, fresh
- Sauce, sweet-salted (asian)
- Pork, roast
- Blackberry
- Smoked cooked sausage of pork and beef meat sausag
- bean seeds
- Italian salad dressing
- White asparagus
- Pie, rhubarb, baked, with cake dough
- Tomato, stewed, without addition of fat, without addition of salt
- Cherries
- Nectarine
In [11]:
# Getting all categoriy with respective to their total images
no_images_per_category = {}

for n, i in enumerate(train_coco.getCatIds()):
  imgIds = train_coco.getImgIds(catIds=i)
  label = category_names[n]
  no_images_per_category[label] = len(imgIds)

img_info = pd.DataFrame(train_coco.loadImgs(train_coco.getImgIds()))
no_images_per_category = OrderedDict(sorted(no_images_per_category.items(), key=lambda x: -1*x[1]))

# Top 30 categories, based on number of images
i = 0
for k, v in no_images_per_category.items():
  print(k, v)
  i += 1
  if i > 30:
    break
Water 2928
Salad, leaf / salad, green 2002
Bread, white 1891
Tomato, raw  1865
Butter 1601
Carrot, raw 1482
Bread, wholemeal 1452
Coffee, with caffeine 1406
Rice 1024
Egg 1015
Mixed vegetables 892
Apple 892
Jam 797
Cucumber 742
Wine, red 728
Banana 654
Cheese 646
Potatoes steamed 644
Bell pepper, red, raw  549
Hard cheese 547
Espresso, with caffeine 547
Tea 516
Bread, whole wheat 504
Mixed salad (chopped without sauce) 498
Avocado 480
White coffee, with caffeine 470
Tomato sauce 466
Wine, white 430
Broccoli 421
Strawberries 412
Pasta, spaghetti 398

Data Visualisations

In [12]:
fig = go.Figure([go.Bar(x=list(no_images_per_category.keys())[:50], y=list(no_images_per_category.values())[:50])])
fig.update_layout(
    title="No of Image per class",)

fig.show()

fig = go.Figure([go.Bar(x=list(no_images_per_category.keys())[50:200], y=list(no_images_per_category.values())[50:200])])
fig.update_layout(
    title="No of Image per class",)

fig.show()

fig = go.Figure([go.Bar(x=list(no_images_per_category.keys())[200:], y=list(no_images_per_category.values())[200:])])
fig.update_layout(
    title="No of Image per class",)

fig.show()
In [13]:
pprint(f"Average number of image per class : { sum(list(no_images_per_category.values())) / len(list(no_images_per_category.values())) }")
pprint(f"Highest number of image per class is : { list(no_images_per_category.keys())[0]} of { list(no_images_per_category.values())[0] }")
pprint(f"Lowest number of image per class is : Veggie Burger of { sorted(list(no_images_per_category.values()))[0] }")
'Average number of image per class : 141.359437751004'
'Highest number of image per class is : Water of 2928'
'Lowest number of image per class is : Veggie Burger of 12'
In [14]:
fig = go.Figure(data=[go.Pie(labels=list(no_images_per_category.keys())[:50], values=list(no_images_per_category.values())[:50], 
                             hole=.3, textposition='inside', )], )
fig.update_layout(
    title="No of Image per class Top 50 ( In pie )",)
fig.show()
In [15]:
fig = go.Figure()
fig.add_trace(go.Histogram(x=img_info['height'],text='height'))
fig.add_trace(go.Histogram(x=img_info['width'],text='width'))

# Overlay both histograms
fig.update_layout(barmode='stack', title="Histogram of Image width & height",)


fig.show()

Image Visulisation 🖼️

In this section we are going to do image visualisations!

In [16]:
print(img_info)
print(img_info.describe())
           id   file_name  width  height
0      131094  131094.jpg    480     480
1      131097  131097.jpg    391     390
2      131098  131098.jpg    391     390
3      131100  131100.jpg    391     390
4      131101  131101.jpg    391     390
...       ...         ...    ...     ...
39957  131017  131017.jpg    480     480
39958  131021  131021.jpg    464     464
39959  131053  131053.jpg    391     390
39960  131066  131066.jpg    464     464
39961  131071  131071.jpg    464     464

[39962 rows x 4 columns]
                  id         width        height
count   39962.000000  39962.000000  39962.000000
mean    90858.920900    650.675792    652.695010
std     51044.060525    287.916148    295.307311
min      6316.000000    182.000000    183.000000
25%     46291.250000    464.000000    464.000000
50%     87042.000000    480.000000    480.000000
75%    136441.000000    853.000000    853.000000
max    185902.000000   4608.000000   4096.000000
In [17]:
len(train_annotations_data['annotations'][2]['segmentation']), len(train_annotations_data['annotations'][2]['bbox'])
Out[17]:
(1, 4)
In [18]:
img_no = 11

annIds = train_coco.getAnnIds(imgIds=train_annotations_data['images'][img_no]['id'])
anns = train_coco.loadAnns(annIds)

# load and render the image
plt.imshow(plt.imread(TRAIN_IMAGE_DIRECTIORY+train_annotations_data['images'][img_no]['file_name']))
plt.axis('off')
# Render annotations on top of the image
train_coco.showAnns(anns)
In [19]:
w, h = 15, 15 # Setting width and height of every image
rows, cols = 5, 5 # Setting the number of image rows & cols

fig = plt.figure(figsize=(15, 15)) # Making the figure with size 

plt.title("Images") 
plt.axis('off')

# Going thought every cell in rows and cols
for i in range(1, cols * rows+1):
  annIds = train_coco.getAnnIds(imgIds=img_info['id'][i])
  anns = train_coco.loadAnns(annIds)

  fig.add_subplot(rows, cols, i)

  # Show the image

  img = plt.imread(TRAIN_IMAGE_DIRECTIORY+img_info['file_name'][i])
  for i in anns:
    [x,y,w,h] = i['bbox']
    #create rectagle bbox of size given in dataset
    cv2.rectangle(img, (int(x), int(y)), (int(x+h), int(y+w)), (255,0,0), 2)
  plt.imshow(img)

  # Render annotations on top of the image
  train_coco.showAnns(anns)

  # Setting the axis off
  plt.axis("off")

# Showing the figure
plt.show()

Data Argumentation

Here, we provide an example with fastai library, another library to use is albumentations which provides wide range of augmentations for computer vision tasks.

In [20]:
!pip install --upgrade fastai
Requirement already satisfied: fastai in /usr/local/lib/python3.7/dist-packages (1.0.61)
Collecting fastai
  Downloading fastai-2.5.3-py3-none-any.whl (189 kB)
     |████████████████████████████████| 189 kB 7.0 MB/s 
Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from fastai) (1.0.2)
Requirement already satisfied: fastprogress>=0.2.4 in /usr/local/lib/python3.7/dist-packages (from fastai) (1.0.0)
Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from fastai) (2.27.1)
Requirement already satisfied: pyyaml in /usr/local/lib/python3.7/dist-packages (from fastai) (5.1)
Requirement already satisfied: torchvision>=0.8.2 in /usr/local/lib/python3.7/dist-packages (from fastai) (0.11.1+cu111)
Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from fastai) (21.3)
Collecting fastcore<1.4,>=1.3.22
  Downloading fastcore-1.3.27-py3-none-any.whl (56 kB)
     |████████████████████████████████| 56 kB 5.0 MB/s 
Collecting fastdownload<2,>=0.0.5
  Downloading fastdownload-0.0.5-py3-none-any.whl (13 kB)
Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from fastai) (1.4.1)
Requirement already satisfied: pip in /usr/local/lib/python3.7/dist-packages (from fastai) (21.1.3)
Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from fastai) (1.1.5)
Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from fastai) (3.2.2)
Requirement already satisfied: torch<1.11,>=1.7.0 in /usr/local/lib/python3.7/dist-packages (from fastai) (1.10.0+cu111)
Requirement already satisfied: pillow>6.0.0 in /usr/local/lib/python3.7/dist-packages (from fastai) (7.1.2)
Requirement already satisfied: spacy<4 in /usr/local/lib/python3.7/dist-packages (from fastai) (2.2.4)
Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from fastprogress>=0.2.4->fastai) (1.19.5)
Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from spacy<4->fastai) (57.4.0)
Requirement already satisfied: plac<1.2.0,>=0.9.6 in /usr/local/lib/python3.7/dist-packages (from spacy<4->fastai) (1.1.3)
Requirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /usr/local/lib/python3.7/dist-packages (from spacy<4->fastai) (1.0.6)
Requirement already satisfied: wasabi<1.1.0,>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy<4->fastai) (0.9.0)
Requirement already satisfied: tqdm<5.0.0,>=4.38.0 in /usr/local/lib/python3.7/dist-packages (from spacy<4->fastai) (4.62.3)
Requirement already satisfied: preshed<3.1.0,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy<4->fastai) (3.0.6)
Requirement already satisfied: catalogue<1.1.0,>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from spacy<4->fastai) (1.0.0)
Requirement already satisfied: blis<0.5.0,>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy<4->fastai) (0.4.1)
Requirement already satisfied: srsly<1.1.0,>=1.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy<4->fastai) (1.0.5)
Requirement already satisfied: thinc==7.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy<4->fastai) (7.4.0)
Requirement already satisfied: cymem<2.1.0,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy<4->fastai) (2.0.6)
Requirement already satisfied: importlib-metadata>=0.20 in /usr/local/lib/python3.7/dist-packages (from catalogue<1.1.0,>=0.0.7->spacy<4->fastai) (4.10.1)
Requirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=0.20->catalogue<1.1.0,>=0.0.7->spacy<4->fastai) (3.10.0.2)
Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=0.20->catalogue<1.1.0,>=0.0.7->spacy<4->fastai) (3.7.0)
Requirement already satisfied: charset-normalizer~=2.0.0 in /usr/local/lib/python3.7/dist-packages (from requests->fastai) (2.0.10)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->fastai) (2021.10.8)
Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->fastai) (2.10)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->fastai) (1.24.3)
Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->fastai) (2.8.2)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->fastai) (3.0.7)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->fastai) (1.3.2)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->fastai) (0.11.0)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.1->matplotlib->fastai) (1.15.0)
Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->fastai) (2018.9)
Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->fastai) (3.0.0)
Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->fastai) (1.1.0)
Installing collected packages: fastcore, fastdownload, fastai
  Attempting uninstall: fastai
    Found existing installation: fastai 1.0.61
    Uninstalling fastai-1.0.61:
      Successfully uninstalled fastai-1.0.61
Successfully installed fastai-2.5.3 fastcore-1.3.27 fastdownload-0.0.5
In [21]:
from fastai.vision.core import *
from fastai.vision.utils import *
from fastai.vision.augment import *
from fastai.data.core import *
from fastai.data.transforms import *
In [22]:
images, lbl_bbox = get_annotations('data/train/annotations.json')
In [23]:
idx=14
coco_fn,bbox = 'data/train/images/'+images[idx],lbl_bbox[idx]

def _coco_bb(x):  return TensorBBox.create(bbox[0])
def _coco_lbl(x): return bbox[1]
In [24]:
coco_dsrc = Datasets([coco_fn]*10, [PILImage.create, [_coco_bb,], [_coco_lbl, MultiCategorize(add_na=True)]], n_inp=1)
coco_tdl = TfmdDL(coco_dsrc, bs=9, after_item=[BBoxLabeler(), PointScaler(), ToTensor(), Resize(256)],
                  after_batch=[IntToFloatTensor(), *aug_transforms()])

coco_tdl.show_batch(max_n=9)
/usr/local/lib/python3.7/dist-packages/torch/_tensor.py:1051: UserWarning:

torch.solve is deprecated in favor of torch.linalg.solveand will be removed in a future PyTorch release.
torch.linalg.solve has its arguments reversed and does not return the LU factorization.
To get the LU factorization see torch.lu, which can be used with torch.lu_solve or torch.lu_unpack.
X = torch.solve(B, A).solution
should be replaced with
X = torch.linalg.solve(A, B) (Triggered internally at  ../aten/src/ATen/native/BatchLinearAlgebra.cpp:766.)

Creating our Dataset 🔨

In this section we are goind to fix out dataset first ( because there is some issues with dataset ( size mismatch ) & creating our dataset to put into the model

Fixing the Data

In [25]:
#example print
np.array(train_annotations_data['annotations'][2]['segmentation']).shape , np.array(train_annotations_data['annotations'][2]['bbox']).shape
Out[25]:
((1, 38), (4,))
In [26]:
# Function for taking a annotation & directiory of images and returning new annoation json with fixed image size info
def fix_data(annotations, directiory, VERBOSE = False):
  for n, i in enumerate(tqdm((annotations['images']))):
   
      img = cv2.imread(directiory+i["file_name"])
 
      if img.shape[0] != i['height']:
          annotations['images'][n]['height'] = img.shape[0]
          if VERBOSE:
            print(i["file_name"])
            print(annotations['images'][n], img.shape)

      if img.shape[1] != i['width']:
          annotations['images'][n]['width'] = img.shape[1]
          if VERBOSE:
            print(i["file_name"])
            print(annotations['images'][n], img.shape)

  return annotations

#fix annotations for training dataset
train_annotations_data = fix_data(train_annotations_data, TRAIN_IMAGE_DIRECTIORY)

with open('data/train/new_ann.json', 'w') as f:
    json.dump(train_annotations_data, f)

#similar processing for validation data
val_annotations_data = fix_data(val_annotations_data, VAL_IMAGE_DIRECTIORY)

with open('data/val/new_ann.json', 'w') as f:
    json.dump(val_annotations_data, f)
In [ ]:
#mount the drive for logging and active submission
# from google.colab import drive
# drive.mount('/content/drive')
Mounted at /content/drive

Loading Dataset

Here comes the actual training part starting with first loading the datasets in coco format and registering them as instances

In [27]:
train_annotations_path = 'data/train/new_ann.json'
train_images_path = 'data/train/images'

val_annotations_path = 'data/val/new_ann.json'
val_images_path = 'data/val/images'
In [28]:
register_coco_instances("training_dataset", {},train_annotations_path, train_images_path)
register_coco_instances("validation_dataset", {},val_annotations_path, VAL_IMAGE_DIRECTIORY)

Creating our Detectron2 Model 🏭

We are going to make an Faster R-CNN Model with ResNeXt 101 backbone using Detectron2 libarary, and setting up hyperpamaters to train our model. Here at model_zoo page you can find available pretrained models to start your traning from.

Creating Mask R-CNN Model and Training on Our Dataset

we first load the configuration file for the model architecture, then load the pretrained model from model_zoo. Visit the model_zoo repo page for more details on configuration.

In [79]:
# Select your config from model_zoo, we have released pre-trained models for x101 and r50.

# Download available here: https://drive.google.com/drive/folders/10_JiikWP59vm2eGIxRenAXxvYLDjUOz0?usp=sharing (10k iters)
# Pre-trained with score of (0.030 AP, 0.050 AR)
# MODEL_ARCH = "COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml"

# Download available here: https://drive.google.com/drive/folders/1-LLFE8xFGOKkzPXF1DKF45c6O4W-38hu?usp=sharing (110k iters)
# Pre-trained with score of (0.082 AP, 0.128 AR)
MODEL_ARCH = "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"

cfg = get_cfg()
# Check the model zoo and use any of the models ( from detectron2 github repo)

# cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"))
# cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_101_FPN_3x.yaml"))
cfg.merge_from_file(model_zoo.get_config_file(MODEL_ARCH))

cfg.DATASETS.TRAIN = ("training_dataset",)
cfg.DATASETS.TEST = ()

cfg.DATALOADER.NUM_WORKERS = 2

# Loading pre trained weights
# cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")
# cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_R_101_FPN_3x.yaml")
cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(MODEL_ARCH)

Setting up hyperparameters

Modify the model configuration hyperparameters for our training

In [80]:
# No. of Batchs
cfg.SOLVER.IMS_PER_BATCH = 4     #for 16 GB GPU, reduce it to 2 for 12 GB GPU if you face CUDA memory error

# Learning Rate: 
cfg.SOLVER.BASE_LR = 0.0025

# No of Interations
cfg.SOLVER.MAX_ITER = 150000

# Options: WarmupMultiStepLR, WarmupCosineLR.
# See detectron2/solver/build.py for definition.
cfg.SOLVER.LR_SCHEDULER_NAME = "WarmupMultiStepLR"

#save every 1000 steps
cfg.SOLVER.CHECKPOINT_PERIOD = 1000

# Images per batch (Batch Size) 
cfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = 256  

# No of Categories(Classes) present
cfg.MODEL.ROI_HEADS.NUM_CLASSES = 498



#Output directory
#### NOTE: You can also download pre-trained folder from Google Drive and upload in your drive; links are shared in above cell.
# cfg.OUTPUT_DIR = "/content/drive/MyDrive/logs_detectron2_x101"
cfg.OUTPUT_DIR = "/content/drive/MyDrive/logs_detectron2_r50"

os.makedirs(cfg.OUTPUT_DIR, exist_ok=True)
In [81]:
#set if to true if you want to resume training
RESUME = True
trainer = DefaultTrainer(cfg) 

if RESUME:
  trainer.resume_or_load(resume=True)
else:
  trainer.resume_or_load(resume=False)
[01/31 12:31:56 d2.engine.defaults]: Model:
GeneralizedRCNN(
  (backbone): FPN(
    (fpn_lateral2): Conv2d(256, 256, kernel_size=(1, 1), stride=(1, 1))
    (fpn_output2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (fpn_lateral3): Conv2d(512, 256, kernel_size=(1, 1), stride=(1, 1))
    (fpn_output3): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (fpn_lateral4): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1))
    (fpn_output4): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (fpn_lateral5): Conv2d(2048, 256, kernel_size=(1, 1), stride=(1, 1))
    (fpn_output5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (top_block): LastLevelMaxPool()
    (bottom_up): ResNet(
      (stem): BasicStem(
        (conv1): Conv2d(
          3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False
          (norm): FrozenBatchNorm2d(num_features=64, eps=1e-05)
        )
      )
      (res2): Sequential(
        (0): BottleneckBlock(
          (shortcut): Conv2d(
            64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)
          )
          (conv1): Conv2d(
            64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=64, eps=1e-05)
          )
          (conv2): Conv2d(
            64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=64, eps=1e-05)
          )
          (conv3): Conv2d(
            64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)
          )
        )
        (1): BottleneckBlock(
          (conv1): Conv2d(
            256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=64, eps=1e-05)
          )
          (conv2): Conv2d(
            64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=64, eps=1e-05)
          )
          (conv3): Conv2d(
            64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)
          )
        )
        (2): BottleneckBlock(
          (conv1): Conv2d(
            256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=64, eps=1e-05)
          )
          (conv2): Conv2d(
            64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=64, eps=1e-05)
          )
          (conv3): Conv2d(
            64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)
          )
        )
      )
      (res3): Sequential(
        (0): BottleneckBlock(
          (shortcut): Conv2d(
            256, 512, kernel_size=(1, 1), stride=(2, 2), bias=False
            (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)
          )
          (conv1): Conv2d(
            256, 128, kernel_size=(1, 1), stride=(2, 2), bias=False
            (norm): FrozenBatchNorm2d(num_features=128, eps=1e-05)
          )
          (conv2): Conv2d(
            128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=128, eps=1e-05)
          )
          (conv3): Conv2d(
            128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)
          )
        )
        (1): BottleneckBlock(
          (conv1): Conv2d(
            512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=128, eps=1e-05)
          )
          (conv2): Conv2d(
            128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=128, eps=1e-05)
          )
          (conv3): Conv2d(
            128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)
          )
        )
        (2): BottleneckBlock(
          (conv1): Conv2d(
            512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=128, eps=1e-05)
          )
          (conv2): Conv2d(
            128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=128, eps=1e-05)
          )
          (conv3): Conv2d(
            128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)
          )
        )
        (3): BottleneckBlock(
          (conv1): Conv2d(
            512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=128, eps=1e-05)
          )
          (conv2): Conv2d(
            128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=128, eps=1e-05)
          )
          (conv3): Conv2d(
            128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)
          )
        )
      )
      (res4): Sequential(
        (0): BottleneckBlock(
          (shortcut): Conv2d(
            512, 1024, kernel_size=(1, 1), stride=(2, 2), bias=False
            (norm): FrozenBatchNorm2d(num_features=1024, eps=1e-05)
          )
          (conv1): Conv2d(
            512, 256, kernel_size=(1, 1), stride=(2, 2), bias=False
            (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)
          )
          (conv2): Conv2d(
            256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)
          )
          (conv3): Conv2d(
            256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=1024, eps=1e-05)
          )
        )
        (1): BottleneckBlock(
          (conv1): Conv2d(
            1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)
          )
          (conv2): Conv2d(
            256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)
          )
          (conv3): Conv2d(
            256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=1024, eps=1e-05)
          )
        )
        (2): BottleneckBlock(
          (conv1): Conv2d(
            1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)
          )
          (conv2): Conv2d(
            256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)
          )
          (conv3): Conv2d(
            256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=1024, eps=1e-05)
          )
        )
        (3): BottleneckBlock(
          (conv1): Conv2d(
            1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)
          )
          (conv2): Conv2d(
            256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)
          )
          (conv3): Conv2d(
            256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=1024, eps=1e-05)
          )
        )
        (4): BottleneckBlock(
          (conv1): Conv2d(
            1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)
          )
          (conv2): Conv2d(
            256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)
          )
          (conv3): Conv2d(
            256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=1024, eps=1e-05)
          )
        )
        (5): BottleneckBlock(
          (conv1): Conv2d(
            1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)
          )
          (conv2): Conv2d(
            256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)
          )
          (conv3): Conv2d(
            256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=1024, eps=1e-05)
          )
        )
      )
      (res5): Sequential(
        (0): BottleneckBlock(
          (shortcut): Conv2d(
            1024, 2048, kernel_size=(1, 1), stride=(2, 2), bias=False
            (norm): FrozenBatchNorm2d(num_features=2048, eps=1e-05)
          )
          (conv1): Conv2d(
            1024, 512, kernel_size=(1, 1), stride=(2, 2), bias=False
            (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)
          )
          (conv2): Conv2d(
            512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)
          )
          (conv3): Conv2d(
            512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=2048, eps=1e-05)
          )
        )
        (1): BottleneckBlock(
          (conv1): Conv2d(
            2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)
          )
          (conv2): Conv2d(
            512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)
          )
          (conv3): Conv2d(
            512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=2048, eps=1e-05)
          )
        )
        (2): BottleneckBlock(
          (conv1): Conv2d(
            2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)
          )
          (conv2): Conv2d(
            512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)
          )
          (conv3): Conv2d(
            512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False
            (norm): FrozenBatchNorm2d(num_features=2048, eps=1e-05)
          )
        )
      )
    )
  )
  (proposal_generator): RPN(
    (rpn_head): StandardRPNHead(
      (conv): Conv2d(
        256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)
        (activation): ReLU()
      )
      (objectness_logits): Conv2d(256, 3, kernel_size=(1, 1), stride=(1, 1))
      (anchor_deltas): Conv2d(256, 12, kernel_size=(1, 1), stride=(1, 1))
    )
    (anchor_generator): DefaultAnchorGenerator(
      (cell_anchors): BufferList()
    )
  )
  (roi_heads): StandardROIHeads(
    (box_pooler): ROIPooler(
      (level_poolers): ModuleList(
        (0): ROIAlign(output_size=(7, 7), spatial_scale=0.25, sampling_ratio=0, aligned=True)
        (1): ROIAlign(output_size=(7, 7), spatial_scale=0.125, sampling_ratio=0, aligned=True)
        (2): ROIAlign(output_size=(7, 7), spatial_scale=0.0625, sampling_ratio=0, aligned=True)
        (3): ROIAlign(output_size=(7, 7), spatial_scale=0.03125, sampling_ratio=0, aligned=True)
      )
    )
    (box_head): FastRCNNConvFCHead(
      (flatten): Flatten(start_dim=1, end_dim=-1)
      (fc1): Linear(in_features=12544, out_features=1024, bias=True)
      (fc_relu1): ReLU()
      (fc2): Linear(in_features=1024, out_features=1024, bias=True)
      (fc_relu2): ReLU()
    )
    (box_predictor): FastRCNNOutputLayers(
      (cls_score): Linear(in_features=1024, out_features=499, bias=True)
      (bbox_pred): Linear(in_features=1024, out_features=1992, bias=True)
    )
    (mask_pooler): ROIPooler(
      (level_poolers): ModuleList(
        (0): ROIAlign(output_size=(14, 14), spatial_scale=0.25, sampling_ratio=0, aligned=True)
        (1): ROIAlign(output_size=(14, 14), spatial_scale=0.125, sampling_ratio=0, aligned=True)
        (2): ROIAlign(output_size=(14, 14), spatial_scale=0.0625, sampling_ratio=0, aligned=True)
        (3): ROIAlign(output_size=(14, 14), spatial_scale=0.03125, sampling_ratio=0, aligned=True)
      )
    )
    (mask_head): MaskRCNNConvUpsampleHead(
      (mask_fcn1): Conv2d(
        256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)
        (activation): ReLU()
      )
      (mask_fcn2): Conv2d(
        256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)
        (activation): ReLU()
      )
      (mask_fcn3): Conv2d(
        256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)
        (activation): ReLU()
      )
      (mask_fcn4): Conv2d(
        256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)
        (activation): ReLU()
      )
      (deconv): ConvTranspose2d(256, 256, kernel_size=(2, 2), stride=(2, 2))
      (deconv_relu): ReLU()
      (predictor): Conv2d(256, 498, kernel_size=(1, 1), stride=(1, 1))
    )
  )
)
[01/31 12:31:59 d2.data.datasets.coco]: Loading data/train/new_ann.json takes 3.09 seconds.
WARNING [01/31 12:31:59 d2.data.datasets.coco]: 
Category ids in annotations are not in [1, #categories]! We'll apply a mapping for you.

[01/31 12:31:59 d2.data.datasets.coco]: Loaded 39962 images in COCO format from data/train/new_ann.json
[01/31 12:32:01 d2.data.build]: Removed 0 images with no usable annotations. 39962 images left.
[01/31 12:32:03 d2.data.dataset_mapper]: [DatasetMapper] Augmentations used in training: [ResizeShortestEdge(short_edge_length=(640, 672, 704, 736, 768, 800), max_size=1333, sample_style='choice'), RandomFlip()]
[01/31 12:32:03 d2.data.build]: Using training sampler TrainingSampler
[01/31 12:32:03 d2.data.common]: Serializing 39962 elements to byte tensors and concatenating them all ...
[01/31 12:32:03 d2.data.common]: Serialized dataset takes 117.68 MiB
WARNING [01/31 12:32:04 d2.solver.build]: SOLVER.STEPS contains values larger than SOLVER.MAX_ITER. These values will be ignored.
[01/31 12:32:04 d2.engine.hooks]: Loading scheduler from state_dict ...

Training the Model 🚂

Finally training our model!

Start Training!!!

In [ ]:
trainer.train()

Evaluating the Model on Validation Set!

In [82]:
# copy the trained model to content directory in colab
!cp '/content/drive/MyDrive/logs_detectron2_r50/model_final.pth' /content/model_final.pth
In [66]:
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.1

# cfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, "model_final.pth")
cfg.MODEL.WEIGHTS = '/content/model_final.pth'

evaluator = COCOEvaluator("validation_dataset", cfg, False, output_dir=cfg.OUTPUT_DIR)
val_loader = build_detection_test_loader(cfg, "validation_dataset")
valResults = inference_on_dataset(trainer.model, val_loader, evaluator)
WARNING [01/31 11:59:19 d2.evaluation.coco_evaluation]: COCO Evaluator instantiated using config, this is deprecated behavior. Please pass in explicit arguments instead.
WARNING [01/31 11:59:19 d2.data.datasets.coco]: 
Category ids in annotations are not in [1, #categories]! We'll apply a mapping for you.

[01/31 11:59:19 d2.data.datasets.coco]: Loaded 1000 images in COCO format from data/val/new_ann.json
[01/31 11:59:20 d2.data.dataset_mapper]: [DatasetMapper] Augmentations used in inference: [ResizeShortestEdge(short_edge_length=(800, 800), max_size=1333, sample_style='choice')]
[01/31 11:59:20 d2.data.common]: Serializing 1000 elements to byte tensors and concatenating them all ...
[01/31 11:59:20 d2.data.common]: Serialized dataset takes 1.58 MiB
[01/31 11:59:20 d2.evaluation.evaluator]: Start inference on 1000 batches
/usr/local/lib/python3.7/dist-packages/detectron2/structures/image_list.py:88: UserWarning:

__floordiv__ is deprecated, and its behavior will change in a future version of pytorch. It currently rounds toward 0 (like the 'trunc' function NOT 'floor'). This results in incorrect rounding for negative values. To keep the current behavior, use torch.div(a, b, rounding_mode='trunc'), or for actual floor division, use torch.div(a, b, rounding_mode='floor').

[01/31 11:59:22 d2.evaluation.evaluator]: Inference done 11/1000. Dataloading: 0.0022 s/iter. Inference: 0.1114 s/iter. Eval: 0.0237 s/iter. Total: 0.1373 s/iter. ETA=0:02:15
[01/31 11:59:27 d2.evaluation.evaluator]: Inference done 47/1000. Dataloading: 0.0032 s/iter. Inference: 0.1187 s/iter. Eval: 0.0178 s/iter. Total: 0.1399 s/iter. ETA=0:02:13
[01/31 11:59:32 d2.evaluation.evaluator]: Inference done 95/1000. Dataloading: 0.0023 s/iter. Inference: 0.1046 s/iter. Eval: 0.0144 s/iter. Total: 0.1214 s/iter. ETA=0:01:49
[01/31 11:59:37 d2.evaluation.evaluator]: Inference done 141/1000. Dataloading: 0.0021 s/iter. Inference: 0.1018 s/iter. Eval: 0.0136 s/iter. Total: 0.1176 s/iter. ETA=0:01:41
[01/31 11:59:42 d2.evaluation.evaluator]: Inference done 189/1000. Dataloading: 0.0019 s/iter. Inference: 0.1000 s/iter. Eval: 0.0124 s/iter. Total: 0.1144 s/iter. ETA=0:01:32
[01/31 11:59:47 d2.evaluation.evaluator]: Inference done 235/1000. Dataloading: 0.0020 s/iter. Inference: 0.0991 s/iter. Eval: 0.0122 s/iter. Total: 0.1134 s/iter. ETA=0:01:26
[01/31 11:59:52 d2.evaluation.evaluator]: Inference done 281/1000. Dataloading: 0.0020 s/iter. Inference: 0.0988 s/iter. Eval: 0.0118 s/iter. Total: 0.1127 s/iter. ETA=0:01:21
[01/31 11:59:57 d2.evaluation.evaluator]: Inference done 328/1000. Dataloading: 0.0020 s/iter. Inference: 0.0983 s/iter. Eval: 0.0116 s/iter. Total: 0.1119 s/iter. ETA=0:01:15
[01/31 12:00:02 d2.evaluation.evaluator]: Inference done 373/1000. Dataloading: 0.0020 s/iter. Inference: 0.0986 s/iter. Eval: 0.0113 s/iter. Total: 0.1119 s/iter. ETA=0:01:10
[01/31 12:00:07 d2.evaluation.evaluator]: Inference done 417/1000. Dataloading: 0.0020 s/iter. Inference: 0.0987 s/iter. Eval: 0.0116 s/iter. Total: 0.1124 s/iter. ETA=0:01:05
[01/31 12:00:12 d2.evaluation.evaluator]: Inference done 464/1000. Dataloading: 0.0019 s/iter. Inference: 0.0982 s/iter. Eval: 0.0116 s/iter. Total: 0.1119 s/iter. ETA=0:00:59
[01/31 12:00:17 d2.evaluation.evaluator]: Inference done 510/1000. Dataloading: 0.0020 s/iter. Inference: 0.0982 s/iter. Eval: 0.0114 s/iter. Total: 0.1116 s/iter. ETA=0:00:54
[01/31 12:00:22 d2.evaluation.evaluator]: Inference done 550/1000. Dataloading: 0.0021 s/iter. Inference: 0.0983 s/iter. Eval: 0.0122 s/iter. Total: 0.1127 s/iter. ETA=0:00:50
[01/31 12:00:27 d2.evaluation.evaluator]: Inference done 592/1000. Dataloading: 0.0021 s/iter. Inference: 0.0984 s/iter. Eval: 0.0125 s/iter. Total: 0.1131 s/iter. ETA=0:00:46
[01/31 12:00:32 d2.evaluation.evaluator]: Inference done 639/1000. Dataloading: 0.0021 s/iter. Inference: 0.0980 s/iter. Eval: 0.0125 s/iter. Total: 0.1127 s/iter. ETA=0:00:40
[01/31 12:00:37 d2.evaluation.evaluator]: Inference done 686/1000. Dataloading: 0.0021 s/iter. Inference: 0.0976 s/iter. Eval: 0.0127 s/iter. Total: 0.1125 s/iter. ETA=0:00:35
[01/31 12:00:42 d2.evaluation.evaluator]: Inference done 733/1000. Dataloading: 0.0021 s/iter. Inference: 0.0972 s/iter. Eval: 0.0128 s/iter. Total: 0.1122 s/iter. ETA=0:00:29
[01/31 12:00:47 d2.evaluation.evaluator]: Inference done 781/1000. Dataloading: 0.0021 s/iter. Inference: 0.0970 s/iter. Eval: 0.0126 s/iter. Total: 0.1118 s/iter. ETA=0:00:24
[01/31 12:00:53 d2.evaluation.evaluator]: Inference done 829/1000. Dataloading: 0.0020 s/iter. Inference: 0.0968 s/iter. Eval: 0.0125 s/iter. Total: 0.1114 s/iter. ETA=0:00:19
[01/31 12:00:58 d2.evaluation.evaluator]: Inference done 876/1000. Dataloading: 0.0020 s/iter. Inference: 0.0966 s/iter. Eval: 0.0125 s/iter. Total: 0.1112 s/iter. ETA=0:00:13
[01/31 12:01:03 d2.evaluation.evaluator]: Inference done 920/1000. Dataloading: 0.0021 s/iter. Inference: 0.0964 s/iter. Eval: 0.0128 s/iter. Total: 0.1114 s/iter. ETA=0:00:08
[01/31 12:01:08 d2.evaluation.evaluator]: Inference done 961/1000. Dataloading: 0.0021 s/iter. Inference: 0.0961 s/iter. Eval: 0.0136 s/iter. Total: 0.1119 s/iter. ETA=0:00:04
[01/31 12:01:13 d2.evaluation.evaluator]: Inference done 999/1000. Dataloading: 0.0021 s/iter. Inference: 0.0960 s/iter. Eval: 0.0145 s/iter. Total: 0.1126 s/iter. ETA=0:00:00
[01/31 12:01:13 d2.evaluation.evaluator]: Total inference time: 0:01:52.250462 (0.112815 s / iter per device, on 1 devices)
[01/31 12:01:13 d2.evaluation.evaluator]: Total inference pure compute time: 0:01:35 (0.096029 s / iter per device, on 1 devices)
[01/31 12:01:13 d2.evaluation.coco_evaluation]: Preparing results for COCO format ...
[01/31 12:01:13 d2.evaluation.coco_evaluation]: Saving results to /content/drive/MyDrive/logs_detectron2_r50/coco_instances_results.json
[01/31 12:01:13 d2.evaluation.coco_evaluation]: Evaluating predictions with unofficial COCO API...
Loading and preparing results...
DONE (t=0.02s)
creating index...
index created!
[01/31 12:01:13 d2.evaluation.fast_eval_api]: Evaluate annotation type *bbox*
[01/31 12:01:22 d2.evaluation.fast_eval_api]: COCOeval_opt.evaluate() finished in 9.17 seconds.
[01/31 12:01:22 d2.evaluation.fast_eval_api]: Accumulating evaluation results...
[01/31 12:01:24 d2.evaluation.fast_eval_api]: COCOeval_opt.accumulate() finished in 1.60 seconds.
 Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.065
 Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=100 ] = 0.130
 Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=100 ] = 0.057
 Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.000
 Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.025
 Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.070
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=  1 ] = 0.116
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets= 10 ] = 0.127
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.127
 Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.000
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.030
 Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.136
[01/31 12:01:24 d2.evaluation.coco_evaluation]: Evaluation results for bbox: 
|  AP   |  AP50  |  AP75  |  APs  |  APm  |  APl  |
|:-----:|:------:|:------:|:-----:|:-----:|:-----:|
| 6.522 | 13.004 | 5.664  | 0.000 | 2.518 | 6.980 |
[01/31 12:01:24 d2.evaluation.coco_evaluation]: Per-category bbox AP: 
| category                                                                | AP     | category                                                         | AP     | category                                                                 | AP     |
|:------------------------------------------------------------------------|:-------|:-----------------------------------------------------------------|:-------|:-------------------------------------------------------------------------|:-------|
| beetroot-steamed-without-addition-of-salt                               | 11.469 | carrot-steamed-without-addition-of-salt                          | 0.000  | mushroom-average-stewed-without-addition-of-fat-without-addition-of-salt | 0.000  |
| savoy-cabbage-steamed-without-addition-of-salt                          | nan    | zucchini-stewed-without-addition-of-fat-without-addition-of-salt | nan    | vanille-cream-cooked-custard-creme-dessert                               | nan    |
| shrimp-boiled                                                           | 0.000  | spinach-steamed-without-addition-of-salt                         | 0.000  | spinach-raw                                                              | 0.000  |
| green-bean-steamed-without-addition-of-salt                             | 0.000  | sweet-corn-canned                                                | 0.000  | watermelon-fresh                                                         | 9.185  |
| pizza-with-ham-with-mushrooms-baked                                     | 0.000  | pizza-with-ham-baked                                             | 0.000  | pizza-with-vegetables-baked                                              | 2.805  |
| bell-pepper-red-stewed-without-addition-of-fat-without-addition-of-salt | 0.000  | applesauce-unsweetened-canned                                    | 0.000  | quiche-with-cheese-baked-with-puff-pastry                                | 0.000  |
| quiche-with-spinach-baked-with-cake-dough                               | 70.000 | risotto-with-mushrooms-cooked                                    | nan    | potato-salad-with-mayonnaise-yogurt-dressing                             | 0.000  |
| wienerli-swiss-sausage                                                  | 0.000  | curds-natural-with-at-most-10-fidm                               | 0.000  | tuna-in-oil-drained                                                      | nan    |
| tomato-stewed-without-addition-of-fat-without-addition-of-salt          | 0.000  | sweet-potato                                                     | 0.000  | country-fries                                                            | 3.366  |
| potato-gnocchi                                                          | 0.000  | potatoes-steamed                                                 | 2.868  | chips-french-fries                                                       | 23.028 |
| rosti                                                                   | 0.000  | vegetable-mix-peas-and-carrots                                   | 0.000  | coleslaw-chopped-without-sauce                                           | nan    |
| vegetables                                                              | 0.000  | mixed-vegetables                                                 | 2.523  | ratatouille                                                              | 0.000  |
| mixed-salad-chopped-without-sauce                                       | 10.651 | leaf-spinach                                                     | 1.037  | witloof-chicory                                                          | 0.000  |
| salad-rocket                                                            | 1.073  | salad-leaf-salad-green                                           | 25.492 | salad-lambs-ear                                                          | 25.050 |
| artichoke                                                               | nan    | eggplant                                                         | 0.000  | avocado                                                                  | 5.153  |
| french-beans                                                            | 10.066 | cucumber-pickled                                                 | 0.000  | cucumber                                                                 | 9.994  |
| capers                                                                  | 0.000  | pumpkin                                                          | 0.000  | bell-pepper-red-raw                                                      | 2.749  |
| tomato-raw                                                              | 4.378  | zucchini                                                         | 0.000  | red-radish                                                               | 1.545  |
| beetroot-raw                                                            | 0.000  | white-radish                                                     | nan    | carrot-raw                                                               | 9.086  |
| celeriac                                                                | nan    | cauliflower                                                      | 0.743  | broccoli                                                                 | 5.262  |
| chinese-cabbage                                                         | 0.000  | kolhrabi                                                         | 0.000  | romanesco                                                                | 0.000  |
| brussel-sprouts                                                         | 0.000  | red-cabbage                                                      | 12.500 | sauerkraut                                                               | 0.000  |
| white-cabbage                                                           | nan    | mushroom                                                         | 0.000  | mushrooms                                                                | 0.000  |
| peas                                                                    | 0.000  | corn                                                             | 15.149 | spring-onion-scallion                                                    | 0.000  |
| garlic                                                                  | 0.000  | leek                                                             | 0.000  | pearl-onions                                                             | nan    |
| onion                                                                   | 0.000  | fennel                                                           | 3.366  | swiss-chard                                                              | 0.000  |
| mungbean-sprouts                                                        | nan    | green-asparagus                                                  | 0.000  | white-asparagus                                                          | nan    |
| shoots                                                                  | 0.000  | alfa-sprouts                                                     | nan    | celery                                                                   | 0.000  |
| bean-seeds                                                              | nan    | beans-kidney                                                     | 0.000  | beans-white                                                              | 0.000  |
| chickpeas                                                               | 8.267  | lentils                                                          | 0.421  | pineapple                                                                | 0.000  |
| apple                                                                   | 21.625 | pomegranate                                                      | 0.000  | apricots                                                                 | 5.891  |
| banana                                                                  | 32.386 | berries                                                          | 0.000  | pear                                                                     | 12.067 |
| blackberry                                                              | nan    | dates                                                            | 12.634 | strawberries                                                             | 38.699 |
| figs                                                                    | 16.832 | fruit-salad                                                      | 80.000 | grapefruit-pomelo                                                        | 7.855  |
| blueberries                                                             | 16.393 | raspberries                                                      | 4.455  | kaki                                                                     | 1.443  |
| cherries                                                                | 0.000  | kiwi                                                             | 18.869 | mandarine                                                                | 18.469 |
| mango                                                                   | 10.000 | sugar-melon                                                      | 31.832 | nectarine                                                                | 0.000  |
| orange                                                                  | 9.407  | peach                                                            | 19.632 | plums                                                                    | 7.904  |
| grapes                                                                  | 18.994 | dried-raisins                                                    | 0.000  | lemon                                                                    | 0.000  |
| damson-plum                                                             | 0.000  | peanut-butter                                                    | 0.000  | chestnuts                                                                | 7.723  |
| seeds                                                                   | 0.000  | pumpkin-seeds                                                    | 0.000  | pine-nuts                                                                | 0.000  |
| sunflower-seeds                                                         | 0.000  | mixed-seeds                                                      | nan    | almonds                                                                  | 40.495 |
| nuts                                                                    | nan    | walnut                                                           | 32.970 | cashew-nut                                                               | 5.050  |
| peanut                                                                  | 0.000  | hazelnut                                                         | 11.535 | coconut                                                                  | 0.000  |
| brazil-nut                                                              | 0.000  | pecan-nut                                                        | 80.000 | mixed-nuts                                                               | 19.337 |
| pistachio                                                               | 30.297 | linseeds                                                         | 0.000  | sesame-seeds                                                             | 0.000  |
| green-olives                                                            | 0.000  | black-olives                                                     | 0.099  | milk                                                                     | 2.055  |
| kefir-drink                                                             | 0.000  | coconut-milk                                                     | 0.000  | soya-drink-soy-milk                                                      | 0.000  |
| soya-yaourt-yahourt-yogourt-ou-yoghourt                                 | 0.000  | cottage-cheese                                                   | 0.000  | curd                                                                     | nan    |
| blue-mould-cheese                                                       | 0.000  | brie                                                             | 0.000  | cheddar                                                                  | 0.000  |
| emmental-cheese                                                         | 0.000  | feta                                                             | 0.000  | fondue                                                                   | 29.109 |
| fresh-cheese                                                            | 0.000  | gruyere                                                          | 0.426  | semi-hard-cheese                                                         | 0.000  |
| halloumi                                                                | 0.000  | hard-cheese                                                      | 2.263  | cheese                                                                   | 1.055  |
| mozzarella                                                              | 0.000  | parmesan                                                         | 2.873  | philadelphia                                                             | 0.000  |
| cheese-for-raclette                                                     | 16.667 | cream-cheese                                                     | 0.000  | processed-cheese                                                         | 0.000  |
| tete-de-moine                                                           | 0.000  | tomme                                                            | 0.000  | soft-cheese                                                              | 0.000  |
| mousse                                                                  | nan    | panna-cotta                                                      | nan    | tiramisu                                                                 | 80.000 |
| cream                                                                   | 0.000  | sour-cream                                                       | 0.000  | thickened-cream-35                                                       | nan    |
| dairy-ice-cream                                                         | 1.160  | sorbet                                                           | 0.000  | flakes-oat                                                               | 0.000  |
| rice-noodles-vermicelli                                                 | 0.000  | bulgur                                                           | 0.000  | couscous                                                                 | 0.000  |
| ebly                                                                    | 0.000  | grits-polenta-maize-flour                                        | 3.805  | quinoa                                                                   | 2.693  |
| rice                                                                    | 8.469  | rice-basmati                                                     | 8.531  | rice-jasmin                                                              | nan    |
| rice-whole-grain                                                        | 0.000  | rice-wild                                                        | 0.000  | spaetzle                                                                 | 5.050  |
| pasta                                                                   | 8.720  | pasta-hornli                                                     | 0.000  | pasta-in-butterfly-form-farfalle                                         | 0.000  |
| pasta-linguini-parpadelle-tagliatelle                                   | 15.446 | pasta-in-conch-form                                              | 0.000  | pasta-noodles                                                            | 19.685 |
| pasta-penne                                                             | 3.196  | pasta-ravioli-stuffing                                           | 0.000  | pasta-spaghetti                                                          | 20.693 |
| pasta-twist                                                             | 26.733 | pasta-tortelloni-stuffing                                        | nan    | pasta-wholemeal                                                          | 0.000  |
| bagel-without-filling                                                   | 0.000  | bread-french-white-flour                                         | 6.059  | bread                                                                    | 0.000  |
| bread-5-grain                                                           | nan    | bread-spelt                                                      | 0.000  | bread-fruit                                                              | 0.000  |
| bread-half-white                                                        | 1.136  | bread-grain                                                      | 6.335  | bread-nut                                                                | nan    |
| bread-olive                                                             | 0.000  | bread-pita                                                       | 0.000  | bread-rye                                                                | 25.248 |
| bread-whole-wheat                                                       | 4.367  | bread-sourdough                                                  | 3.366  | bread-black                                                              | 0.000  |
| bread-ticino                                                            | 60.000 | bread-toast                                                      | 8.158  | bread-wholemeal-toast                                                    | 11.584 |
| bread-wholemeal                                                         | 10.127 | bread-white                                                      | 18.696 | brioche                                                                  | 0.000  |
| roll-of-half-white-or-white-flour-with-large-void                       | 36.898 | hamburger-bun                                                    | 0.000  | roll-with-pieces-of-chocolate                                            | 3.030  |
| white-bread-with-butter-eggs-and-milk                                   | 0.000  | focaccia                                                         | 0.000  | croissant                                                                | 38.350 |
| croissant-wholegrain                                                    | 0.000  | lye-pretzel-soft                                                 | 17.756 | braided-white-loaf                                                       | 15.445 |
| crisp-bread-wasa                                                        | nan    | breadcrumbs-unspiced                                             | 0.000  | rice-waffels                                                             | 0.000  |
| grissini                                                                | 70.000 | rusk-wholemeal                                                   | 0.000  | corn-flakes                                                              | nan    |
| crunch-muesli                                                           | 34.389 | muesli                                                           | 26.766 | dough-puff-pastry-shortcrust-bread-pizza-dough                           | nan    |
| pastry-flaky                                                            | nan    | meat                                                             | 0.000  | minced-meat                                                              | nan    |
| beef                                                                    | 0.000  | beef-roast                                                       | 0.000  | beef-sirloin-steak                                                       | 3.030  |
| beef-filet                                                              | nan    | beef-minced-only-meat                                            | 0.000  | beef-cut-into-stripes-only-meat                                          | 0.000  |
| pork                                                                    | 0.000  | pork-roast                                                       | 0.000  | pork-chop                                                                | nan    |
| pork-escalope                                                           | nan    | lamb                                                             | nan    | lamb-chop                                                                | 0.000  |
| chicken                                                                 | 0.000  | chicken-breast                                                   | 0.000  | chicken-wing                                                             | nan    |
| chicken-cut-into-stripes-only-meat                                      | 0.000  | chicken-leg                                                      | 0.000  | frying-sausage                                                           | 16.667 |
| cervelat                                                                | 0.000  | chicken-nuggets                                                  | 0.000  | chorizo                                                                  | 0.000  |
| meatloaf                                                                | 0.000  | hamburger                                                        | 0.000  | dried-meat                                                               | 20.561 |
| veal-sausage                                                            | 0.000  | processed-meat-charcuterie                                       | nan    | salami                                                                   | 5.050  |
| cooked-sausage                                                          | nan    | ham                                                              | 0.000  | ham-cooked                                                               | 0.000  |
| ham-raw                                                                 | 4.301  | ham-turkey                                                       | 0.000  | smoked-cooked-sausage-of-pork-and-beef-meat-sausag                       | nan    |
| bacon                                                                   | nan    | bacon-frying                                                     | 0.000  | bacon-cooking                                                            | 0.000  |
| bacon-raw                                                               | 0.000  | meat-terrine-pate                                                | 0.000  | sausage                                                                  | 0.000  |
| veggie-burger                                                           | 0.000  | tofu                                                             | 0.000  | fish                                                                     | 0.000  |
| cod                                                                     | 0.000  | salmon                                                           | 0.000  | anchovies                                                                | 0.000  |
| tuna                                                                    | nan    | shrimp-prawn-small                                               | nan    | shrimp-prawn-large                                                       | 0.000  |
| fish-crunchies-battered                                                 | nan    | fish-fingers-breaded                                             | 0.000  | egg                                                                      | 4.906  |
| oil                                                                     | 0.000  | butter                                                           | 9.019  | butter-herb                                                              | 0.000  |
| margarine                                                               | 0.000  | praline                                                          | 1.250  | jam                                                                      | 18.228 |
| honey                                                                   | 5.041  | sugar-glazing                                                    | nan    | maple-syrup-concentrate                                                  | 0.000  |
| dark-chocolate                                                          | 15.024 | milk-chocolate                                                   | 40.886 | white-chocolate                                                          | nan    |
| chocolate                                                               | 1.443  | chocolate-filled                                                 | nan    | cocoa-powder                                                             | nan    |
| hazelnut-chocolate-spread-nutella-ovomaltine-caotina                    | 4.158  | m-m-s                                                            | 11.023 | chocolate-egg-small                                                      | 50.000 |
| sweets-candies                                                          | 0.000  | gummi-bears-fruit-jellies-jelly-babies-with-fruit-essence        | nan    | apple-pie                                                                | 0.000  |
| brownie                                                                 | nan    | cake-oblong                                                      | 0.000  | lemon-cake                                                               | nan    |
| crepe-plain                                                             | 21.490 | fruit-tart                                                       | 20.000 | cake-marble                                                              | 0.000  |
| cake-chocolate                                                          | 6.312  | muffin                                                           | 5.170  | omelette-plain                                                           | 0.000  |
| carrot-cake                                                             | 0.000  | black-forest-tart                                                | 0.000  | tart                                                                     | 25.000 |
| waffle                                                                  | nan    | croissant-with-chocolate-filling                                 | 0.000  | cookies                                                                  | 26.312 |
| biscuits                                                                | 1.063  | macaroon                                                         | 0.000  | meringue                                                                 | 0.000  |
| biscuit-with-butter                                                     | 0.000  | chocolate-cookies                                                | 16.584 | juice-apple                                                              | 1.056  |
| juice-multifruit                                                        | 0.000  | juice-orange                                                     | nan    | smoothie                                                                 | nan    |
| coca-cola                                                               | nan    | coca-cola-zero                                                   | 19.472 | ice-tea                                                                  | nan    |
| syrup-diluted-ready-to-drink                                            | 0.833  | tea                                                              | 7.909  | cappuccino                                                               | 18.663 |
| espresso-with-caffeine                                                  | 5.474  | coffee-with-caffeine                                             | 12.061 | coffee-decaffeinated                                                     | 0.000  |
| latte-macchiato-with-caffeine                                           | 0.000  | white-coffee-with-caffeine                                       | 10.765 | ristretto-with-caffeine                                                  | 2.394  |
| tea-green                                                               | 0.187  | tea-black                                                        | nan    | tea-verveine                                                             | nan    |
| tea-fruit                                                               | nan    | tea-spice                                                        | nan    | tea-ginger                                                               | nan    |
| herbal-tea                                                              | 5.445  | tea-peppermint                                                   | 5.014  | tea-rooibos                                                              | 0.000  |
| ice-cubes                                                               | nan    | water                                                            | 28.784 | water-mineral                                                            | 8.465  |
| aperitif-with-alcohol-aperol-spritz                                     | nan    | cocktail                                                         | 70.000 | champagne                                                                | 0.000  |
| prosecco                                                                | 0.000  | sekt                                                             | 0.000  | wine-rose                                                                | 27.211 |
| wine-red                                                                | 49.726 | wine-white                                                       | 12.893 | beer                                                                     | 7.942  |
| light-beer                                                              | 0.000  | sauce-savoury                                                    | 0.000  | sauce-roast                                                              | 0.000  |
| sauce-carbonara                                                         | nan    | sauce-cocktail                                                   | 0.000  | sauce-curry                                                              | 0.000  |
| sauce-pesto                                                             | 0.000  | sauce-mushroom                                                   | 0.000  | sauce-cream                                                              | 0.000  |
| sauce-sweet-sour                                                        | 0.000  | ketchup                                                          | 0.000  | bolognaise-sauce                                                         | 13.465 |
| tomato-sauce                                                            | 0.715  | dips                                                             | nan    | salad-dressing                                                           | 0.000  |
| balsamic-salad-dressing                                                 | 0.000  | french-salad-dressing                                            | 5.047  | italian-salad-dressing                                                   | 0.000  |
| oil-vinegar-salad-dressing                                              | 0.000  | guacamole                                                        | 0.000  | mayonnaise                                                               | 0.000  |
| tartar-sauce                                                            | 0.000  | tzatziki                                                         | 0.000  | basil                                                                    | 0.000  |
| coriander                                                               | 0.000  | bouquet-garni                                                    | 0.000  | parsley                                                                  | 0.000  |
| chives                                                                  | 0.000  | cenovis-yeast-spread                                             | nan    | sauce-soya                                                               | 0.000  |
| mustard                                                                 | 0.000  | mustard-dijon                                                    | nan    | balsamic-vinegar                                                         | nan    |
| soup-vegetable                                                          | 24.491 | soup-cream-of-vegetables                                         | 25.248 | soup-potato                                                              | 8.333  |
| soup-pumpkin                                                            | 19.279 | soup-miso                                                        | 16.667 | soup-tomato                                                              | 10.099 |
| bouillon                                                                | 0.000  | bouillon-vegetable                                               | 0.000  | falafel-balls                                                            | 0.000  |
| savoury-puff-pastry                                                     | nan    | savoury-puff-pastry-stick                                        | 0.000  | corn-crisps                                                              | nan    |
| crackers                                                                | 0.000  | croutons                                                         | 0.000  | crisps                                                                   | 0.259  |
| popcorn-salted                                                          | 37.884 | croque-monsieur                                                  | 0.000  | spring-roll-fried                                                        | 0.000  |
| ham-croissant                                                           | nan    | salt-cake-vegetables-filled                                      | nan    | hamburger-bread-meat-ketchup                                             | 6.796  |
| cordon-bleu-from-pork-schnitzel-fried                                   | 3.366  | lasagne-meat-prepared                                            | 28.317 | mashed-potatoes-prepared-with-full-fat-milk-with-butter                  | 0.000  |
| pizza-margherita-baked                                                  | 11.169 | sandwich-ham-cheese-and-butter                                   | nan    | sushi                                                                    | 2.079  |
| kebab-in-pita-bread                                                     | 0.000  | pancakes                                                         | nan    | hummus                                                                   | 0.000  |
| greek-salad                                                             | 0.000  | dumplings                                                        | nan    | apricot-dried                                                            | 0.000  |
| chocolate-mousse                                                        | nan    | cheesecake                                                       | 0.000  | caprese-salad-tomato-mozzarella                                          | 0.000  |
| chili-con-carne-prepared                                                | 60.000 | taboule-prepared-with-couscous                                   | nan    | perch-fillets-lake                                                       | nan    |
| risotto-without-cheese-cooked                                           | 14.543 | salmon-smoked                                                    | 1.545  | pie-apricot-baked-with-cake-dough                                        | 0.000  |
| eggplant-caviar                                                         | 0.000  | apple-crumble                                                    | nan    | egg-scrambled-prepared                                                   | 5.891  |
| oat-milk                                                                | 0.000  | lemon-pie                                                        | nan    | glucose-drink-50g                                                        | 7.539  |
| goat-average-raw                                                        | nan    | pie-rhubarb-baked-with-cake-dough                                | nan    | chicken-curry-cream-coconut-milk-curry-spices-paste                      | nan    |
| pie-plum-baked-with-cake-dough                                          | 31.149 | potatoes-au-gratin-dauphinois-prepared                           | 0.000  | buckwheat-grain-peeled                                                   | nan    |
| birchermuesli-prepared-no-sugar-added                                   | 3.432  | fajita-bread-only                                                | 0.000  | mango-dried                                                              | 0.000  |
| lentils-green-du-puy-du-berry                                           | 0.000  | naan-indien-bread                                                | nan    | butter-spread-puree-almond                                               | 0.000  |
| chocolate-milk-chocolate-drink                                          | nan    | water-with-lemon-juice                                           | 2.459  | sun-dried-tomatoe                                                        | 0.000  |
| gluten-free-bread                                                       | 0.000  | fruit-coulis                                                     | 0.000  | greek-yaourt-yahourt-yogourt-ou-yoghourt                                 | 0.000  |
| cake-salted                                                             | 0.000  | soup-of-lentils-dahl-dhal                                        | nan    | fig-dried                                                                | 0.000  |
| turnover-with-meat-small-meat-pie-empanadas                             | 0.000  | lasagne-vegetable-prepared                                       | 0.000  | sauce-sweet-salted-asian                                                 | 0.000  |
| french-pizza-from-alsace-baked                                          | 0.000  | fruit-compotes                                                   | nan    | vegetable-au-gratin-baked                                                | 0.000  |
| porridge-prepared-with-partially-skimmed-milk                           | nan    | curry-vegetarian                                                 | nan    | bread-meat-substitute-lettuce-sauce                                      | 8.079  |
| tartar-meat                                                             | 0.000  | chia-grains                                                      | nan    | faux-mage-cashew-vegan-chers                                             | 0.000  |
| milk-chocolate-with-hazelnuts                                           | 38.020 | yaourt-yahourt-yogourt-ou-yoghourt-natural                       | 10.612 | paprika-chips                                                            | nan    |
| banana-cake                                                             | 14.554 | cream-spinach                                                    | nan    | cantonese-fried-rice                                                     | 0.000  |
| goat-cheese-soft                                                        | 0.000  | buckwheat-pancake                                                | 0.000  | meat-balls                                                               | 0.000  |
| high-protein-pasta-made-of-lentils-peas                                 | 0.000  | mix-of-dried-fruits-and-nuts                                     | 60.000 | baked-potato                                                             | 3.465  |
Loading and preparing results...
DONE (t=0.19s)
creating index...
index created!
[01/31 12:01:25 d2.evaluation.fast_eval_api]: Evaluate annotation type *segm*
[01/31 12:01:33 d2.evaluation.fast_eval_api]: COCOeval_opt.evaluate() finished in 7.89 seconds.
[01/31 12:01:33 d2.evaluation.fast_eval_api]: Accumulating evaluation results...
[01/31 12:01:34 d2.evaluation.fast_eval_api]: COCOeval_opt.accumulate() finished in 1.60 seconds.
 Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.092
 Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=100 ] = 0.148
 Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=100 ] = 0.095
 Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.000
 Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.016
 Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.099
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=  1 ] = 0.165
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets= 10 ] = 0.175
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.175
 Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.000
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.032
 Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.188
[01/31 12:01:35 d2.evaluation.coco_evaluation]: Evaluation results for segm: 
|  AP   |  AP50  |  AP75  |  APs  |  APm  |  APl  |
|:-----:|:------:|:------:|:-----:|:-----:|:-----:|
| 9.197 | 14.805 | 9.489  | 0.000 | 1.623 | 9.941 |
[01/31 12:01:35 d2.evaluation.coco_evaluation]: Per-category segm AP: 
| category                                                                | AP     | category                                                         | AP      | category                                                                 | AP     |
|:------------------------------------------------------------------------|:-------|:-----------------------------------------------------------------|:--------|:-------------------------------------------------------------------------|:-------|
| beetroot-steamed-without-addition-of-salt                               | 8.880  | carrot-steamed-without-addition-of-salt                          | 0.000   | mushroom-average-stewed-without-addition-of-fat-without-addition-of-salt | 0.000  |
| savoy-cabbage-steamed-without-addition-of-salt                          | nan    | zucchini-stewed-without-addition-of-fat-without-addition-of-salt | nan     | vanille-cream-cooked-custard-creme-dessert                               | nan    |
| shrimp-boiled                                                           | 0.000  | spinach-steamed-without-addition-of-salt                         | 0.000   | spinach-raw                                                              | 0.000  |
| green-bean-steamed-without-addition-of-salt                             | 0.000  | sweet-corn-canned                                                | 0.000   | watermelon-fresh                                                         | 24.995 |
| pizza-with-ham-with-mushrooms-baked                                     | 0.000  | pizza-with-ham-baked                                             | 0.000   | pizza-with-vegetables-baked                                              | 3.927  |
| bell-pepper-red-stewed-without-addition-of-fat-without-addition-of-salt | 0.000  | applesauce-unsweetened-canned                                    | 0.000   | quiche-with-cheese-baked-with-puff-pastry                                | 0.000  |
| quiche-with-spinach-baked-with-cake-dough                               | 40.000 | risotto-with-mushrooms-cooked                                    | nan     | potato-salad-with-mayonnaise-yogurt-dressing                             | 0.000  |
| wienerli-swiss-sausage                                                  | 0.000  | curds-natural-with-at-most-10-fidm                               | 0.000   | tuna-in-oil-drained                                                      | nan    |
| tomato-stewed-without-addition-of-fat-without-addition-of-salt          | 0.000  | sweet-potato                                                     | 0.000   | country-fries                                                            | 3.366  |
| potato-gnocchi                                                          | 0.000  | potatoes-steamed                                                 | 12.805  | chips-french-fries                                                       | 39.535 |
| rosti                                                                   | 0.000  | vegetable-mix-peas-and-carrots                                   | 0.000   | coleslaw-chopped-without-sauce                                           | nan    |
| vegetables                                                              | 0.000  | mixed-vegetables                                                 | 1.289   | ratatouille                                                              | 0.000  |
| mixed-salad-chopped-without-sauce                                       | 23.891 | leaf-spinach                                                     | 6.007   | witloof-chicory                                                          | 0.000  |
| salad-rocket                                                            | 2.919  | salad-leaf-salad-green                                           | 27.667  | salad-lambs-ear                                                          | 46.278 |
| artichoke                                                               | nan    | eggplant                                                         | 0.000   | avocado                                                                  | 9.851  |
| french-beans                                                            | 16.013 | cucumber-pickled                                                 | 0.000   | cucumber                                                                 | 12.092 |
| capers                                                                  | 0.000  | pumpkin                                                          | 0.000   | bell-pepper-red-raw                                                      | 0.911  |
| tomato-raw                                                              | 8.917  | zucchini                                                         | 7.129   | red-radish                                                               | 8.495  |
| beetroot-raw                                                            | 0.000  | white-radish                                                     | nan     | carrot-raw                                                               | 8.166  |
| celeriac                                                                | nan    | cauliflower                                                      | 0.000   | broccoli                                                                 | 5.261  |
| chinese-cabbage                                                         | 0.000  | kolhrabi                                                         | 6.733   | romanesco                                                                | 0.000  |
| brussel-sprouts                                                         | 0.000  | red-cabbage                                                      | 20.000  | sauerkraut                                                               | 0.000  |
| white-cabbage                                                           | nan    | mushroom                                                         | 0.000   | mushrooms                                                                | 0.000  |
| peas                                                                    | 0.000  | corn                                                             | 23.564  | spring-onion-scallion                                                    | 0.000  |
| garlic                                                                  | 0.000  | leek                                                             | 0.000   | pearl-onions                                                             | nan    |
| onion                                                                   | 0.000  | fennel                                                           | 16.832  | swiss-chard                                                              | 0.000  |
| mungbean-sprouts                                                        | nan    | green-asparagus                                                  | 0.000   | white-asparagus                                                          | nan    |
| shoots                                                                  | 0.000  | alfa-sprouts                                                     | nan     | celery                                                                   | 0.000  |
| bean-seeds                                                              | nan    | beans-kidney                                                     | 0.000   | beans-white                                                              | 0.000  |
| chickpeas                                                               | 7.096  | lentils                                                          | 0.842   | pineapple                                                                | 0.000  |
| apple                                                                   | 35.492 | pomegranate                                                      | 0.000   | apricots                                                                 | 7.574  |
| banana                                                                  | 36.262 | berries                                                          | 0.000   | pear                                                                     | 19.546 |
| blackberry                                                              | nan    | dates                                                            | 14.653  | strawberries                                                             | 45.928 |
| figs                                                                    | 26.931 | fruit-salad                                                      | 100.000 | grapefruit-pomelo                                                        | 6.733  |
| blueberries                                                             | 11.879 | raspberries                                                      | 7.354   | kaki                                                                     | 2.885  |
| cherries                                                                | 13.465 | kiwi                                                             | 24.373  | mandarine                                                                | 36.373 |
| mango                                                                   | 70.000 | sugar-melon                                                      | 37.030  | nectarine                                                                | 0.000  |
| orange                                                                  | 16.459 | peach                                                            | 37.765  | plums                                                                    | 6.922  |
| grapes                                                                  | 36.125 | dried-raisins                                                    | 0.000   | lemon                                                                    | 0.000  |
| damson-plum                                                             | 0.000  | peanut-butter                                                    | 0.000   | chestnuts                                                                | 7.723  |
| seeds                                                                   | 0.000  | pumpkin-seeds                                                    | 0.000   | pine-nuts                                                                | 0.000  |
| sunflower-seeds                                                         | 0.000  | mixed-seeds                                                      | nan     | almonds                                                                  | 47.070 |
| nuts                                                                    | nan    | walnut                                                           | 36.634  | cashew-nut                                                               | 10.099 |
| peanut                                                                  | 0.000  | hazelnut                                                         | 6.040   | coconut                                                                  | 0.000  |
| brazil-nut                                                              | 0.000  | pecan-nut                                                        | 80.000  | mixed-nuts                                                               | 55.040 |
| pistachio                                                               | 45.446 | linseeds                                                         | 0.000   | sesame-seeds                                                             | 0.000  |
| green-olives                                                            | 3.366  | black-olives                                                     | 0.594   | milk                                                                     | 1.683  |
| kefir-drink                                                             | 0.000  | coconut-milk                                                     | 0.000   | soya-drink-soy-milk                                                      | 0.000  |
| soya-yaourt-yahourt-yogourt-ou-yoghourt                                 | 0.000  | cottage-cheese                                                   | 0.000   | curd                                                                     | nan    |
| blue-mould-cheese                                                       | 0.000  | brie                                                             | 0.000   | cheddar                                                                  | 0.000  |
| emmental-cheese                                                         | 0.000  | feta                                                             | 0.000   | fondue                                                                   | 26.436 |
| fresh-cheese                                                            | 0.000  | gruyere                                                          | 4.625   | semi-hard-cheese                                                         | 0.000  |
| halloumi                                                                | 0.000  | hard-cheese                                                      | 2.994   | cheese                                                                   | 2.284  |
| mozzarella                                                              | 0.000  | parmesan                                                         | 14.208  | philadelphia                                                             | 0.000  |
| cheese-for-raclette                                                     | 26.667 | cream-cheese                                                     | 0.000   | processed-cheese                                                         | 0.000  |
| tete-de-moine                                                           | 0.000  | tomme                                                            | 0.000   | soft-cheese                                                              | 0.000  |
| mousse                                                                  | nan    | panna-cotta                                                      | nan     | tiramisu                                                                 | 70.000 |
| cream                                                                   | 0.000  | sour-cream                                                       | 0.000   | thickened-cream-35                                                       | nan    |
| dairy-ice-cream                                                         | 5.180  | sorbet                                                           | 0.000   | flakes-oat                                                               | 0.000  |
| rice-noodles-vermicelli                                                 | 0.000  | bulgur                                                           | 0.000   | couscous                                                                 | 0.000  |
| ebly                                                                    | 0.000  | grits-polenta-maize-flour                                        | 7.016   | quinoa                                                                   | 2.693  |
| rice                                                                    | 6.316  | rice-basmati                                                     | 13.231  | rice-jasmin                                                              | nan    |
| rice-whole-grain                                                        | 0.000  | rice-wild                                                        | 0.000   | spaetzle                                                                 | 30.297 |
| pasta                                                                   | 6.481  | pasta-hornli                                                     | 0.000   | pasta-in-butterfly-form-farfalle                                         | 0.000  |
| pasta-linguini-parpadelle-tagliatelle                                   | 20.594 | pasta-in-conch-form                                              | 0.000   | pasta-noodles                                                            | 31.584 |
| pasta-penne                                                             | 4.471  | pasta-ravioli-stuffing                                           | 0.000   | pasta-spaghetti                                                          | 35.205 |
| pasta-twist                                                             | 53.168 | pasta-tortelloni-stuffing                                        | nan     | pasta-wholemeal                                                          | 0.000  |
| bagel-without-filling                                                   | 0.000  | bread-french-white-flour                                         | 4.040   | bread                                                                    | 0.000  |
| bread-5-grain                                                           | nan    | bread-spelt                                                      | 0.000   | bread-fruit                                                              | 0.000  |
| bread-half-white                                                        | 2.045  | bread-grain                                                      | 6.445   | bread-nut                                                                | nan    |
| bread-olive                                                             | 0.000  | bread-pita                                                       | 0.000   | bread-rye                                                                | 20.198 |
| bread-whole-wheat                                                       | 4.538  | bread-sourdough                                                  | 10.099  | bread-black                                                              | 0.000  |
| bread-ticino                                                            | 90.000 | bread-toast                                                      | 3.221   | bread-wholemeal-toast                                                    | 11.584 |
| bread-wholemeal                                                         | 14.391 | bread-white                                                      | 27.513  | brioche                                                                  | 0.000  |
| roll-of-half-white-or-white-flour-with-large-void                       | 63.696 | hamburger-bun                                                    | 0.000   | roll-with-pieces-of-chocolate                                            | 8.079  |
| white-bread-with-butter-eggs-and-milk                                   | 0.000  | focaccia                                                         | 0.000   | croissant                                                                | 52.970 |
| croissant-wholegrain                                                    | 0.000  | lye-pretzel-soft                                                 | 24.340  | braided-white-loaf                                                       | 14.637 |
| crisp-bread-wasa                                                        | nan    | breadcrumbs-unspiced                                             | 0.000   | rice-waffels                                                             | 0.000  |
| grissini                                                                | 0.000  | rusk-wholemeal                                                   | 0.000   | corn-flakes                                                              | nan    |
| crunch-muesli                                                           | 34.934 | muesli                                                           | 25.545  | dough-puff-pastry-shortcrust-bread-pizza-dough                           | nan    |
| pastry-flaky                                                            | nan    | meat                                                             | 0.000   | minced-meat                                                              | nan    |
| beef                                                                    | 0.000  | beef-roast                                                       | 0.000   | beef-sirloin-steak                                                       | 5.050  |
| beef-filet                                                              | nan    | beef-minced-only-meat                                            | 0.000   | beef-cut-into-stripes-only-meat                                          | 0.000  |
| pork                                                                    | 0.000  | pork-roast                                                       | 0.000   | pork-chop                                                                | nan    |
| pork-escalope                                                           | nan    | lamb                                                             | nan     | lamb-chop                                                                | 0.000  |
| chicken                                                                 | 0.000  | chicken-breast                                                   | 0.000   | chicken-wing                                                             | nan    |
| chicken-cut-into-stripes-only-meat                                      | 0.000  | chicken-leg                                                      | 0.000   | frying-sausage                                                           | 10.000 |
| cervelat                                                                | 0.000  | chicken-nuggets                                                  | 0.000   | chorizo                                                                  | 0.000  |
| meatloaf                                                                | 0.000  | hamburger                                                        | 0.000   | dried-meat                                                               | 30.297 |
| veal-sausage                                                            | 0.000  | processed-meat-charcuterie                                       | nan     | salami                                                                   | 5.050  |
| cooked-sausage                                                          | nan    | ham                                                              | 0.000   | ham-cooked                                                               | 0.000  |
| ham-raw                                                                 | 8.977  | ham-turkey                                                       | 0.000   | smoked-cooked-sausage-of-pork-and-beef-meat-sausag                       | nan    |
| bacon                                                                   | nan    | bacon-frying                                                     | 0.000   | bacon-cooking                                                            | 0.000  |
| bacon-raw                                                               | 0.000  | meat-terrine-pate                                                | 0.000   | sausage                                                                  | 0.000  |
| veggie-burger                                                           | 0.000  | tofu                                                             | 0.000   | fish                                                                     | 0.000  |
| cod                                                                     | 0.000  | salmon                                                           | 0.000   | anchovies                                                                | 0.000  |
| tuna                                                                    | nan    | shrimp-prawn-small                                               | nan     | shrimp-prawn-large                                                       | 0.000  |
| fish-crunchies-battered                                                 | nan    | fish-fingers-breaded                                             | 0.000   | egg                                                                      | 13.587 |
| oil                                                                     | 0.000  | butter                                                           | 7.457   | butter-herb                                                              | 0.000  |
| margarine                                                               | 0.000  | praline                                                          | 11.250  | jam                                                                      | 23.774 |
| honey                                                                   | 5.347  | sugar-glazing                                                    | nan     | maple-syrup-concentrate                                                  | 0.000  |
| dark-chocolate                                                          | 22.674 | milk-chocolate                                                   | 44.986  | white-chocolate                                                          | nan    |
| chocolate                                                               | 6.492  | chocolate-filled                                                 | nan     | cocoa-powder                                                             | nan    |
| hazelnut-chocolate-spread-nutella-ovomaltine-caotina                    | 15.304 | m-m-s                                                            | 37.723  | chocolate-egg-small                                                      | 51.818 |
| sweets-candies                                                          | 0.000  | gummi-bears-fruit-jellies-jelly-babies-with-fruit-essence        | nan     | apple-pie                                                                | 0.000  |
| brownie                                                                 | nan    | cake-oblong                                                      | 0.000   | lemon-cake                                                               | nan    |
| crepe-plain                                                             | 33.546 | fruit-tart                                                       | 16.667  | cake-marble                                                              | 0.000  |
| cake-chocolate                                                          | 8.837  | muffin                                                           | 9.618   | omelette-plain                                                           | 50.000 |
| carrot-cake                                                             | 0.000  | black-forest-tart                                                | 0.000   | tart                                                                     | 40.000 |
| waffle                                                                  | nan    | croissant-with-chocolate-filling                                 | 0.000   | cookies                                                                  | 36.262 |
| biscuits                                                                | 1.240  | macaroon                                                         | 0.000   | meringue                                                                 | 0.000  |
| biscuit-with-butter                                                     | 0.000  | chocolate-cookies                                                | 38.119  | juice-apple                                                              | 1.040  |
| juice-multifruit                                                        | 0.000  | juice-orange                                                     | nan     | smoothie                                                                 | nan    |
| coca-cola                                                               | nan    | coca-cola-zero                                                   | 19.472  | ice-tea                                                                  | nan    |
| syrup-diluted-ready-to-drink                                            | 0.985  | tea                                                              | 8.273   | cappuccino                                                               | 14.048 |
| espresso-with-caffeine                                                  | 6.521  | coffee-with-caffeine                                             | 23.747  | coffee-decaffeinated                                                     | 0.000  |
| latte-macchiato-with-caffeine                                           | 10.000 | white-coffee-with-caffeine                                       | 13.662  | ristretto-with-caffeine                                                  | 4.453  |
| tea-green                                                               | 0.420  | tea-black                                                        | nan     | tea-verveine                                                             | nan    |
| tea-fruit                                                               | nan    | tea-spice                                                        | nan     | tea-ginger                                                               | nan    |
| herbal-tea                                                              | 7.127  | tea-peppermint                                                   | 10.909  | tea-rooibos                                                              | 0.000  |
| ice-cubes                                                               | nan    | water                                                            | 35.033  | water-mineral                                                            | 13.406 |
| aperitif-with-alcohol-aperol-spritz                                     | nan    | cocktail                                                         | 40.000  | champagne                                                                | 0.000  |
| prosecco                                                                | 0.000  | sekt                                                             | 0.000   | wine-rose                                                                | 54.950 |
| wine-red                                                                | 52.995 | wine-white                                                       | 23.787  | beer                                                                     | 7.061  |
| light-beer                                                              | 0.000  | sauce-savoury                                                    | 0.000   | sauce-roast                                                              | 0.000  |
| sauce-carbonara                                                         | nan    | sauce-cocktail                                                   | 0.000   | sauce-curry                                                              | 0.000  |
| sauce-pesto                                                             | 0.000  | sauce-mushroom                                                   | 0.000   | sauce-cream                                                              | 0.000  |
| sauce-sweet-sour                                                        | 0.000  | ketchup                                                          | 1.856   | bolognaise-sauce                                                         | 13.465 |
| tomato-sauce                                                            | 7.382  | dips                                                             | nan     | salad-dressing                                                           | 0.000  |
| balsamic-salad-dressing                                                 | 0.000  | french-salad-dressing                                            | 0.412   | italian-salad-dressing                                                   | 0.000  |
| oil-vinegar-salad-dressing                                              | 0.000  | guacamole                                                        | 0.000   | mayonnaise                                                               | 0.000  |
| tartar-sauce                                                            | 0.000  | tzatziki                                                         | 0.000   | basil                                                                    | 0.000  |
| coriander                                                               | 0.000  | bouquet-garni                                                    | 0.000   | parsley                                                                  | 0.000  |
| chives                                                                  | 0.000  | cenovis-yeast-spread                                             | nan     | sauce-soya                                                               | 0.000  |
| mustard                                                                 | 0.000  | mustard-dijon                                                    | nan     | balsamic-vinegar                                                         | nan    |
| soup-vegetable                                                          | 32.306 | soup-cream-of-vegetables                                         | 40.396  | soup-potato                                                              | 13.333 |
| soup-pumpkin                                                            | 26.584 | soup-miso                                                        | 26.667  | soup-tomato                                                              | 1.683  |
| bouillon                                                                | 0.000  | bouillon-vegetable                                               | 0.000   | falafel-balls                                                            | 0.000  |
| savoury-puff-pastry                                                     | nan    | savoury-puff-pastry-stick                                        | 0.000   | corn-crisps                                                              | nan    |
| crackers                                                                | 0.000  | croutons                                                         | 0.000   | crisps                                                                   | 2.934  |
| popcorn-salted                                                          | 39.422 | croque-monsieur                                                  | 0.000   | spring-roll-fried                                                        | 0.000  |
| ham-croissant                                                           | nan    | salt-cake-vegetables-filled                                      | nan     | hamburger-bread-meat-ketchup                                             | 28.630 |
| cordon-bleu-from-pork-schnitzel-fried                                   | 11.782 | lasagne-meat-prepared                                            | 40.495  | mashed-potatoes-prepared-with-full-fat-milk-with-butter                  | 3.366  |
| pizza-margherita-baked                                                  | 17.377 | sandwich-ham-cheese-and-butter                                   | nan     | sushi                                                                    | 6.188  |
| kebab-in-pita-bread                                                     | 0.000  | pancakes                                                         | nan     | hummus                                                                   | 0.000  |
| greek-salad                                                             | 0.000  | dumplings                                                        | nan     | apricot-dried                                                            | 0.000  |
| chocolate-mousse                                                        | nan    | cheesecake                                                       | 0.000   | caprese-salad-tomato-mozzarella                                          | 70.000 |
| chili-con-carne-prepared                                                | 70.000 | taboule-prepared-with-couscous                                   | nan     | perch-fillets-lake                                                       | nan    |
| risotto-without-cheese-cooked                                           | 54.246 | salmon-smoked                                                    | 8.259   | pie-apricot-baked-with-cake-dough                                        | 0.000  |
| eggplant-caviar                                                         | 0.000  | apple-crumble                                                    | nan     | egg-scrambled-prepared                                                   | 11.902 |
| oat-milk                                                                | 0.000  | lemon-pie                                                        | nan     | glucose-drink-50g                                                        | 17.023 |
| goat-average-raw                                                        | nan    | pie-rhubarb-baked-with-cake-dough                                | nan     | chicken-curry-cream-coconut-milk-curry-spices-paste                      | nan    |
| pie-plum-baked-with-cake-dough                                          | 65.050 | potatoes-au-gratin-dauphinois-prepared                           | 0.000   | buckwheat-grain-peeled                                                   | nan    |
| birchermuesli-prepared-no-sugar-added                                   | 5.528  | fajita-bread-only                                                | 0.000   | mango-dried                                                              | 0.000  |
| lentils-green-du-puy-du-berry                                           | 0.000  | naan-indien-bread                                                | nan     | butter-spread-puree-almond                                               | 0.000  |
| chocolate-milk-chocolate-drink                                          | nan    | water-with-lemon-juice                                           | 3.371   | sun-dried-tomatoe                                                        | 0.000  |
| gluten-free-bread                                                       | 0.000  | fruit-coulis                                                     | 0.000   | greek-yaourt-yahourt-yogourt-ou-yoghourt                                 | 0.000  |
| cake-salted                                                             | 0.000  | soup-of-lentils-dahl-dhal                                        | nan     | fig-dried                                                                | 0.000  |
| turnover-with-meat-small-meat-pie-empanadas                             | 0.000  | lasagne-vegetable-prepared                                       | 0.000   | sauce-sweet-salted-asian                                                 | 0.000  |
| french-pizza-from-alsace-baked                                          | 0.000  | fruit-compotes                                                   | nan     | vegetable-au-gratin-baked                                                | 0.000  |
| porridge-prepared-with-partially-skimmed-milk                           | nan    | curry-vegetarian                                                 | nan     | bread-meat-substitute-lettuce-sauce                                      | 7.069  |
| tartar-meat                                                             | 0.000  | chia-grains                                                      | nan     | faux-mage-cashew-vegan-chers                                             | 0.000  |
| milk-chocolate-with-hazelnuts                                           | 36.634 | yaourt-yahourt-yogourt-ou-yoghourt-natural                       | 11.337  | paprika-chips                                                            | nan    |
| banana-cake                                                             | 18.527 | cream-spinach                                                    | nan     | cantonese-fried-rice                                                     | 0.000  |
| goat-cheese-soft                                                        | 0.000  | buckwheat-pancake                                                | 0.000   | meat-balls                                                               | 0.000  |
| high-protein-pasta-made-of-lentils-peas                                 | 0.000  | mix-of-dried-fruits-and-nuts                                     | 80.000  | baked-potato                                                             | 16.040 |
In [67]:
# cfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, "model_final.pth")
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.2
cfg.MODEL.ROI_HEADS.NUM_CLASSES = 498

cfg.DATASETS.TEST = ("validation_dataset", )
predictor = DefaultPredictor(cfg)
In [85]:
val_metadata = MetadataCatalog.get("val_dataset")

#sample image 
image_id = '008536'
im = cv2.imread(f"data/val/images/{image_id}.jpg")

outputs = predictor(im)

v = Visualizer(im[:, :, ::-1],
                   metadata=val_metadata, 
                   scale=2,
                   instance_mode=ColorMode.IMAGE_BW
    )

out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
cv2_imshow(out.get_image()[:, :, ::-1])
/usr/local/lib/python3.7/dist-packages/detectron2/structures/image_list.py:88: UserWarning:

__floordiv__ is deprecated, and its behavior will change in a future version of pytorch. It currently rounds toward 0 (like the 'trunc' function NOT 'floor'). This results in incorrect rounding for negative values. To keep the current behavior, use torch.div(a, b, rounding_mode='trunc'), or for actual floor division, use torch.div(a, b, rounding_mode='floor').

Create Class_to_category mapping to get correct predictions after inference.

In [70]:
#generate class category ids from detectron2 internal dictinary mappings
category_ids = sorted(train_coco.getCatIds())
categories = train_coco.loadCats(category_ids)

class_to_category = { int(class_id): int(category_id) for class_id, category_id in enumerate(category_ids) }

with open("class_to_category.json", "w") as fp:
  json.dump(class_to_category, fp)

Quick Submission 💪

Inference on the public test set

  • loading the model config and setting up related paths
  • running inference and generating json file for submission
In [86]:
#setting the paths and threshold
test_images_dir = "/content/data/test/images"
output_filepath = "/content/predictions_detectron2.json"

#path of trained model
model_path = '/content/model_final.pth'
# model_path = os.path.join(cfg.OUTPUT_DIR, "model_final.pth")

#threshold
threshold = 0.1
In [74]:
import os
import json
# import aicrowd_helpers
import importlib
import numpy as np
import cv2
import torch
from detectron2.engine import DefaultPredictor

from detectron2.evaluation import COCOEvaluator, inference_on_dataset
from detectron2.data import build_detection_test_loader
from detectron2.structures import Boxes, BoxMode
from detectron2.config import get_cfg
import pycocotools.mask as mask_util


class_to_category = {}
with open("class_to_category.json") as fp:
    class_to_category = json.load(fp)


def run():
    model_name = "model_zoo"
    model = importlib.import_module(f"detectron2.{model_name}")

    #set the config parameters, including the architecture which was previously used
    cfg = get_cfg()
    cfg.merge_from_file(model.get_config_file(MODEL_ARCH))
    cfg.MODEL.WEIGHTS = model_path

    #set the threshold 
    cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = threshold   # set the testing threshold for this model
    cfg.MODEL.ROI_HEADS.NUM_CLASSES = 498

    cfg.MODEL.DEVICE = "cuda"
    predictor = DefaultPredictor(cfg)

    results = []
    for img_file in tqdm(os.listdir(test_images_dir)):
        filename = os.path.join(test_images_dir, img_file)
        img = cv2.imread(filename)
        prediction = predictor(img)

        instances = prediction["instances"]
        if len(instances) > 0:
            scores = instances.scores.tolist()
            classes = instances.pred_classes.tolist()
            bboxes = BoxMode.convert(
                instances.pred_boxes.tensor.cpu(),
                BoxMode.XYXY_ABS,
                BoxMode.XYWH_ABS,
            ).tolist()

            masks = []
            if instances.has("pred_masks"):
                for mask in instances.pred_masks.cpu():
                    _mask = mask_util.encode(np.array(mask[:, :, None], order="F", dtype="uint8"))[0]
                    _mask["counts"] = _mask["counts"].decode("utf-8")
                    masks.append(_mask)

            for idx in range(len(instances)):
                category_id = class_to_category[str(classes[idx])] # json converts int keys to str
                output = {
                    "image_id": int(img_file.split(".")[0]),
                    "category_id": category_id,
                    "bbox": bboxes[idx],
                    "score": scores[idx],
                }
                if len(masks) > 0:
                    output["segmentation"] = masks[idx]
                results.append(output)

        with open(output_filepath, "w") as fp:
            json.dump(results, fp)


#run the inference which generates predictions as json file
run()
/usr/local/lib/python3.7/dist-packages/detectron2/structures/image_list.py:88: UserWarning:

__floordiv__ is deprecated, and its behavior will change in a future version of pytorch. It currently rounds toward 0 (like the 'trunc' function NOT 'floor'). This results in incorrect rounding for negative values. To keep the current behavior, use torch.div(a, b, rounding_mode='trunc'), or for actual floor division, use torch.div(a, b, rounding_mode='floor').

Now that the prediction file is generated for public test set, To make quick submission:

  • Use AIcrowd CLL aicrowd submit command to do a quick submission. </br>

Alternatively:

  • download the predictions_x101.json file by running below cell
  • visit the create submission page
  • Upload the predictions_x101.json file
  • Voila!! You just made your first submission!
In [78]:
#use aicrowd CLI to make quick submission
!aicrowd submission create -c food-recognition-benchmark-2022 -f $output_filepath
predictions_detectron2.json ━━━━━━━━━━━ 100.0%8.1/8.1 MB2.5 MB/s0:00:00
                                               ╭─────────────────────────╮                                               
                                               │ Successfully submitted! │                                               
                                               ╰─────────────────────────╯                                               
                                                     Important links                                                     
┌──────────────────┬────────────────────────────────────────────────────────────────────────────────────────────────────┐
│  This submission │ https://www.aicrowd.com/challenges/food-recognition-benchmark-2022/submissions/172533              │
│                  │                                                                                                    │
│  All submissions │ https://www.aicrowd.com/challenges/food-recognition-benchmark-2022/submissions?my_submissions=true │
│                  │                                                                                                    │
│      Leaderboard │ https://www.aicrowd.com/challenges/food-recognition-benchmark-2022/leaderboards                    │
│                  │                                                                                                    │
│ Discussion forum │ https://discourse.aicrowd.com/c/food-recognition-benchmark-2022                                    │
│                  │                                                                                                    │
│   Challenge page │ https://www.aicrowd.com/challenges/food-recognition-benchmark-2022                                 │
└──────────────────┴────────────────────────────────────────────────────────────────────────────────────────────────────┘
{'submission_id': 172533, 'created_at': '2022-01-31T12:23:30.347Z'}
In [ ]:
!cp '/content/drive/MyDrive/AIcrowd Challenge - Food Recognition/food-recognition-challenge-starter-kit/logs_x101/model_final.pth' model_final.pth

Active submission 🤩

Step 0 : Fork the baseline to make your own changes to it. Go to settings and make the repo private.

Step 1 : For first time setup, Setting up SSH to login to Gitlab.

  1. Run the next cell to check if you already have SSH keys in your drive, if yes, skip this step.
  2. Run ssh-keygen -t ecdsa -b 521
  3. Run cat ~./ssh/id_ecdsa.pub and copy the output
  4. Go to Gitlab SSH Keys and then paste the output inside the key and use whaever title you like.

Step 2: Clone your forked Repo & Add Models & Push Changes

  1. Run git clone git@gitlab.aicrowd.com:[Your Username]/food-recognition-2022-detectron2-baseline.git
  2. Put your model inside the models directioary and then run git-lfs track "*.pth"
  3. Run git add . then git commit -m " adding model"
  4. Run git push origin master

Step 3. Create Submission

  1. Go to the repo and then tags and then New Tag.
  2. In the tag name,you can use submission_v1, ( Everytime you make a new submission, just increase the no. like - submission_v2, submission_v3 )
  3. A new issue will be created with showing the process. Enjoy!

If you do not have SSH Keys, Check this Page

Add your SSH Keys to your GitLab account by following the instructions here

In [140]:
%%bash
SSH_PRIV_KEY=/content/drive/MyDrive/id_ecdsa
SSH_PUB_KEY=/content/drive/MyDrive/id_ecdsa.pub
if [ -f "$SSH_PRIV_KEY" ]; then
    echo "SSH Key found! ✅\n"
    mkdir -p /root/.ssh
    cp /content/drive/MyDrive/id_ecdsa ~/.ssh/id_ecdsa
    cp /content/drive/MyDrive/id_ecdsa.pub ~/.ssh/id_ecdsa.pub
    echo "SSH key successfully copied to local!"
else
    echo "SSH Key does not exist."
    ssh-keygen -t ecdsa -b521 -f ~/.ssh/id_ecdsa
    cat ~/.ssh/id_ecdsa.pub
    echo "❗️Please open https://gitlab.aicrowd.com/profile/keys and copy-paste the above text in the **key** textbox."
    cp  ~/.ssh/id_ecdsa /content/drive/MyDrive/id_ecdsa
    cp  ~/.ssh/id_ecdsa.pub /content/drive/MyDrive/id_ecdsa.pub
    echo "SSH key successfully created and copied to drive!"
fi
SSH Key found! ✅\n
SSH key successfully copied to local!
In [139]:
import IPython

html = "<b>Copy paste below SSH key in your GitLab account here (one time):</b><br/>"
html += '<a href="https://gitlab.aicrowd.com/-/profile/keys" target="_blank">https://gitlab.aicrowd.com/-/profile/keys</a><br><br>'

public_key = open("/content/drive/MyDrive/id_ecdsa.pub").read()
html += '<br/><textarea>'+public_key+'</textarea><button onclick="navigator.clipboard.writeText(\''+public_key.strip()+'\');this.innerHTML=\'Copied ✅\'">Click to copy</button>'
IPython.display.HTML(html)
Out[139]:
Copy paste below SSH key in your GitLab account here (one time):
https://gitlab.aicrowd.com/-/profile/keys


Clone the gitlab starter repo and add submission files

In [213]:
# Set your AIcrowd username for action submission.
# This username will store repository and used for submitter's username, etc
username = "jerome_patel"
!echo -n {username} > author.txt
In [ ]:
%%bash
username=$(cat author.txt)
echo "Username $username"

git config --global user.name "$username"
git config --global user.email "$username@noreply.gitlab.aicrowd.com"

touch ${HOME}/.ssh/known_hosts
ssh-keyscan -H gitlab.aicrowd.com >> ${HOME}/.ssh/known_hosts 2> /dev/null


apt install -qq -y jq git-lfs &> /dev/null

git lfs install
cd /content/

echo "Checking if repository already exist, otherwise create one"
export SUBMISSION_REPO="git@gitlab.aicrowd.com:$username/food-recognition-2022-detectron2-baseline.git"
echo "cloning the $SUBMISSION_REPO"
git clone $SUBMISSION_REPO food-recognition-2022-detectron2-baseline
ALREADYEXIST=$?

if [ $ALREADYEXIST -ne 0 ]; then
  echo "Project didn't exist, forking from upstream"
  git clone https://github.com/AIcrowd/food-recognition-benchmark-starter-kit.git food-recognition-2022-detectron2-baseline
fi

cd /content/food-recognition-2022-detectron2-baseline
git remote remove origin
git remote add origin "$SUBMISSION_REPO"

Active Submission Repo structure:

  • Required Files are aicrowd.json, apt.txt, requirements.txt, predict.py
  • Copy detectron2 trained model and class_to_category.json to repo
  • Modify requirements.txt and predict.py for detectron2
  • Modify aicrowd.json for your submission
In [ ]:
#@title Modify Requirements.txt (modify and run only if you changed torch/detectron2 or any other library python) { display-mode: "form" }
%%writefile /content/food-recognition-2022-detectron2-baseline/requirements.txt
boto3
cython
numpy
Pillow
pycocotools
pandas
aicrowd-repo2docker
aicrowd-api
opencv-python
pyyaml==5.1

-f https://download.pytorch.org/whl/cu111/torch_stable.html
torch==1.10
torchvision==0.11.1

-f https://dl.fbaipublicfiles.com/detectron2/wheels/cu111/index.html
detectron2==0.6
Overwriting /content/food-recognition-2022-detectron2-baseline/requirements.txt

Set "debug"=false for actual submission and true for debug, "gpu"=true for using the GPU, in our case it's required for detectron2. Modify the authors , SCORE_THRESH_TEST and model_config_file as per your setup.

In [208]:
threshold = 0.15
num_classes = cfg.MODEL.ROI_HEADS.NUM_CLASSES
# MODEL_ARCH = "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"

aicrowd_json = {
  "challenge_id" : "food-recognition-benchmark-2022",
  "authors" : ["jerome_patel"],
  "description" : "Food Recognition Benchmark 2022 Submission",
  "license" : "MIT",
  "gpu": True,
  "debug": False,
  "model_path": "models/model_final.pth",
  "model_type": "model_zoo",
  "model_config_file": MODEL_ARCH,
  "detectron_model_config": {
      "ROI_HEADS": {
        "SCORE_THRESH_TEST": threshold,
        "NUM_CLASSES": num_classes
      }
    }   
}

import json
with open('/content/food-recognition-2022-detectron2-baseline/aicrowd.json', 'w') as fp:
  fp.write(json.dumps(aicrowd_json, indent=4))
In [ ]:
#@title Predict_detectron2 Script, Run only if you modified prediction code
%%writefile /content/food-recognition-2022-detectron2-baseline/predict_detectron2.py

#!/usr/bin/env python
#
# This file uses Detectron2 for instance segmentation.
# It is one of the official baselines for the Food Recognition benchmark 2022 challenge.
#
# NOTE: Detectron2 needs the model and **its** aicrowd.json file to be submitted along with your code.
#
# Making submission using Detectron2:
# 1. Copy the aicrowd_detectron2.json from utils to home directory:
#    #> cp utils/aicrowd_detectron2_example.json aicrowd.json
# 2. Change the model in `predict.py` to Detectron2Predictor.
# 3. Download the pre-trained model from google drive into the folder `./models` using:
#    #> mkdir models
#    #> cd models
#    #> pip install gdown
#    ## To download model trained with "COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml" architecture and score of 0.03 on leaderboard
#    #> gdown --id 1ylaOzaI6qBfZbICA844uD74dKxLwcd0K --output model_final_mrcnn_x101.pth
#    ## Next line will download "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml" achitecture and score of 0.08
#    #> gdown --id 1p5babyX6H80Rt8P8O2ts4g7SJihN2KtV --output model_final_mrcnn_resnet50.pth
# 3. Submit your code using git-lfs
#    #> git lfs install
#    #> git lfs track "*.pth"
#    #> git add .gitattributes
#    #> git add models
#

import os
import json
import glob
from PIL import Image
import importlib
import numpy as np
import cv2
import torch

import pycocotools.mask as mask_util
from detectron2.config import get_cfg
from detectron2.engine import DefaultPredictor
from detectron2.structures import Boxes, BoxMode

from detectron2.data import build_detection_test_loader
from detectron2.evaluation import COCOEvaluator, inference_on_dataset

from evaluator.food_challenge import FoodChallengePredictor


"""
Expected ENVIRONMENT Variables
* AICROWD_TEST_IMAGES_PATH : abs path to  folder containing all the test images
* AICROWD_PREDICTIONS_OUTPUT_PATH : path where you are supposed to write the output predictions.json
"""

class Detectron2Predictor(FoodChallengePredictor):

    """
    PARTICIPANT_TODO:
    You can do any preprocessing required for your codebase here like loading up models into memory, etc.
    """
    def prediction_setup(self):
        # self.PADDING = 50
        # self.SEGMENTATION_LENGTH = 10
        # self.MAX_NUMBER_OF_ANNOTATIONS = 10

        #set the config parameters, including the architecture which was previously used
        self.config = self.get_detectron_config()
        self.model_name = self.config["model_type"]
        self.model = importlib.import_module(f"detectron2.{self.model_name}")
        self.class_to_category = self.get_class_to_category()

        self.cfg = get_cfg()
        self.cfg.merge_from_file(self.model.get_config_file(self.config["model_config_file"]))
        self.cfg.MODEL.WEIGHTS = self.config["model_path"]

        #set the threshold & num classes
        self.cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = self.config["detectron_model_config"]["ROI_HEADS"]["SCORE_THRESH_TEST"]   # set the testing threshold for this model
        self.cfg.MODEL.ROI_HEADS.NUM_CLASSES = 498

        self.cfg.MODEL.DEVICE = "cuda"
        self.predictor = DefaultPredictor(self.cfg)


    """
    PARTICIPANT_TODO:
    During the evaluation all image file path will be provided one by one.
    NOTE: In case you want to load your model, please do so in `predict_setup` function.
    """
    def prediction(self, image_path):
        print("Generating for", image_path)
        # read the image
        img = cv2.imread(image_path)
        prediction = self.predictor(img)
        
        annotations = []
        instances = prediction["instances"]
        if len(instances) > 0:
            scores = instances.scores.tolist()
            classes = instances.pred_classes.tolist()
            bboxes = BoxMode.convert(
                instances.pred_boxes.tensor.cpu(),
                BoxMode.XYXY_ABS,
                BoxMode.XYWH_ABS,
            ).tolist()

            masks = []
            if instances.has("pred_masks"):
                for mask in instances.pred_masks.cpu():
                    _mask = mask_util.encode(np.array(mask[:, :, None], order="F", dtype="uint8"))[0]
                    _mask["counts"] = _mask["counts"].decode("utf-8")
                    masks.append(_mask)

            for idx in range(len(instances)):
                category_id = self.class_to_category[str(classes[idx])] # json converts int keys to str
                output = {
                    "image_id": int(os.path.basename(image_path).split(".")[0]),
                    "category_id": category_id,
                    "bbox": bboxes[idx],
                    "score": scores[idx],
                }
                if len(masks) > 0:
                    output["segmentation"] = masks[idx]
                annotations.append(output)
        
        # You can return single annotation or array of annotations in your code.
        return annotations

    def get_class_to_category(self):
        class_to_category = {}
        with open("utils/class_to_category.json") as fp:
            class_to_category = json.load(fp)
        return class_to_category

    def get_detectron_config(self):
        with open("aicrowd.json") as fp:
            config = json.load(fp)
        return config


if __name__ == "__main__":
    submission = Detectron2Predictor()
    submission.run()
    print("Successfully generated predictions!")
Overwriting /content/food-recognition-2022-detectron2-baseline/predict_detectron2.py

Copy the Trained model file, class_to_category.json and install git-lfs and push the repo with submission tag

In [209]:
%%bash

## Set your unique tag for this submission (no spaces), example:
# export MSG="v1"
# export MSG="v2" ...
# or something more informative...
export MSG="detectron2_submission_v1"


username=$(cat author.txt)
echo "Username $username"

sed -i 's/^submission = .*$/submission = detectron2_predictor/g' predict.py

mkdir -p /content/food-recognition-2022-detectron2-baseline/models
cp /content/class_to_category.json /content/food-recognition-2022-detectron2-baseline/utils/class_to_category.json
cp /content/model_final.pth /content/food-recognition-2022-detectron2-baseline/models/model_final.pth

cd /content/food-recognition-2022-detectron2-baseline
git lfs track "*.pth"
git add .gitattributes
git add --all
git commit -m "$MSG" || true

find . -type f -size +5M -exec git lfs migrate import --include={} &> /dev/null \;

git tag -am "submission_$MSG" "submission_$MSG"
git config lfs.https://gitlab.aicrowd.com/$username/food-recognition-2022-detectron2-baseline.git/info/lfs.locksverify false

git remote remove origin
git remote add origin git@gitlab.aicrowd.com:$username/food-recognition-2022-detectron2-baseline.git

git lfs push origin master
git push origin master
git push origin "submission_$MSG"

echo "Track your submission status here: https://gitlab.aicrowd.com/$username/food-recognition-2022-detectron2-baseline/issues"
Username shivam
Tracking "*.pth"
[master 62ca19a] detectron2_submission_v1
 3 files changed, 23 insertions(+), 7 deletions(-)
 create mode 100644 .gitattributes
 rewrite aicrowd.json (98%)
 create mode 100644 models/model_final.pth
Git LFS: (1 of 1 files) 178.25 MB / 178.25 MB                                  
Git LFS: (0 of 0 files, 1 skipped) 0 B / 0 B, 178.25 MB skipped                
remote: 
remote: 
remote: The private project shivam/food-recognition-2022-detectron2-baseline was successfully created.        
remote: 
remote: To configure the remote, run:        
remote:   git remote add origin git@gitlab.aicrowd.com:shivam/food-recognition-2022-detectron2-baseline.git        
remote: 
remote: To view the project, visit:
remote:   http://gitlab.aicrowd.com/shivam/food-recognition-2022-detectron2-baseline        
remote: 
remote: 
remote: 
To gitlab.aicrowd.com:shivam/food-recognition-2022-detectron2-baseline.git
 * [new branch]      master -> master
remote: 
remote:           #///(            )///#        
remote:          ////      ///      ////        
remote:         /////   //////////   ////        
remote:         /////////////////////////        
remote:      /// /////////////////////// ///        
remote:    ///////////////////////////////////        
remote:   /////////////////////////////////////        
remote:     )////////////////////////////////(        
remote:      /////                      /////        
remote:    (///////   ///       ///    //////)        
remote:   ///////////    ///////     //////////        
remote: (///////////////////////////////////////)        
remote:           /////           /////        
remote:             /////////////////        
remote:                ///////////        
remote: 
To gitlab.aicrowd.com:shivam/food-recognition-2022-detectron2-baseline.git
 * [new tag]         submission_detectron2_submission_v1 -> submission_detectron2_submission_v1

Local Evaluation for Active Submission Repo

In [210]:
%cd /content/food-recognition-2022-detectron2-baseline
/content/food-recognition-2022-detectron2-baseline
In [ ]:
%%bash

export TEST_DATASET_PATH='../data/test/images'
export RESULTS_DATASET_PATH='../data'
./run.sh

Comments

You must login before you can post a comment.

Execute