{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# About this Notebook\n\nObject Detection is a problem which is not only a bit complex but also computationally expensive, due to the number of components to it. I always wanted to learn it and I got really excited when I saw a Kaggle competition on it , although I was not able to fully concentrate on it due to other competitions up untill now. While I was learning all the different concepts in Object Detection , I came across Facebook's **Detection tranformer DETR** , launched in April 2020 . It's still quite new but the resuts are astonishing and the model itself is very fast . In this notebook, I explore this new architecture,its working and fine tune it for Wheat Detection competition Dataset.\n\nNote that for now this is just a baseline to demonstrate the architecture and its working ,it does not aim at getting very good results on lb,this will be a work in progress,and I will soon update with full training and a separate ","metadata":{}},{"cell_type":"markdown","source":"# Update Log\n\n### V2\n* As I was made aware that I was printing the target boxes instead of predicted boxes , I have corrected it , I am really sorry , It was an honest mistake\n* Thanks to PRVI and his valuable suggestions , I have incorporated the following changes :\n  * Normalizing bounding boxes\n  * Using label 0 for main class\n\nThe code for the changes has been taken from [here](https://www.kaggle.com/prokaj/end-to-end-object-detection-with-transformers-detr#Creating-Dataset)","metadata":{}},{"cell_type":"markdown","source":"# DETR (Detection Transformer)\n\nAttention is all you need,paper for Transformers,changed the state of NLP and has achieved great hieghts. Though mainly developed for NLP , the latest research around it focuses on how to leverage it across different verticals of deep learning. Transformer acrhitecture is very very powerful, and is something which is very close to my part,this is the reason I am motivated to explore anything that uses transformers , be it google's recently released Tabnet or OpenAI's ImageGPT .\n\nDetection Transformer leverages the transformer network(both encoder and the decoder) for Detecting Objects in Images . Facebook's researchers argue that for object detection one part of the image should be in contact with the other part of the image for greater result especially with ocluded objects and partially visible objects, and what's better than to use transformer for it.\n\n**The main motive behind DETR is effectively removing the need for many hand-designed components like a non-maximum suppression procedure or anchor generation that explicitly encode prior knowledge about the task and makes the process complex and computationally expensive**\n\nThe main ingredients of the new framework, called DEtection TRansformer or DETR, <font color='green'>are a set-based global loss that forces unique predictions via bipartite matching, and a transformer encoder-decoder architecture.</font>\n\n![](https://cdn.analyticsvidhya.com/wp-content/uploads/2020/05/Screenshot-from-2020-05-27-17-48-38.png)\n\n<font color='red'>Interesting Right?? Want to learn more please bare with me, as always I will try to explain everything</font>","metadata":{}},{"cell_type":"markdown","source":"For Fully understanding DETR I recommend read [this](https://ai.facebook.com/blog/end-to-end-object-detection-with-transformers/) blog<br><br>\nHowever if you want in-depth knowledge and are a video person like please see the video in the cell below\nYou can find the video in youtube [here](https://www.youtube.com/watch?v=T35ba_VXkMY)","metadata":{}},{"cell_type":"code","source":"# Standard imports\nimport os\nimport pandas as pd\nimport numpy as np\nimport plotly.express as px\nimport plotly.graph_objs as go\nfrom plotly.subplots import make_subplots\nimport matplotlib.pyplot as plt\nimport plotly.figure_factory as ff\nfrom skimage import io\nimport ast\n\nimport seaborn as sns\nfrom tqdm import trange, tqdm\nfrom colorama import Fore\nfrom glob import glob\nimport json\nfrom pprint import pprint\nimport time\nimport cv2\nfrom enum import Enum\nfrom IPython.display import display, HTML\nfrom pandas_profiling import ProfileReport\nimport random\nimport inspect\n\n# For Data preparation\nfrom sklearn.preprocessing import *\nfrom sklearn.model_selection import *\nfrom sklearn.metrics import *\n","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:13:25.80846Z","iopub.execute_input":"2022-03-19T15:13:25.808785Z","iopub.status.idle":"2022-03-19T15:13:29.319834Z","shell.execute_reply.started":"2022-03-19T15:13:25.808752Z","shell.execute_reply":"2022-03-19T15:13:29.318988Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Using DETR without Fine-Tuning\n\n* Before learning how to fine tune DETR if you want to use and play with DETR directly on some sample images , please refer the video [here](https://www.youtube.com/watch?v=LfUsGv-ESbc)\n* [Here](https://scontent.flko3-1.fna.fbcdn.net/v/t39.8562-6/101177000_245125840263462_1160672288488554496_n.pdf?_nc_cat=104&_nc_sid=ae5e01&_nc_ohc=KwU3i7_izOgAX9bxMVv&_nc_ht=scontent.flko3-1.fna&oh=64dad6ce7a7b4807bb3941690beaee69&oe=5F1E8347) is the link to the paper\n* [Here](https://github.com/facebookresearch/detr) is link to their github repo for code and model zoo\n* They recently added a wrapper to use DETR from Detectron2 API","metadata":{}},{"cell_type":"markdown","source":"# Wheat Detection Competition With DETR\n\nSo I wanted to try DETR and what could be greater oppurtunity than a kaggle competition to test a model's potential. I just joined two days ago and from what I have analyzed these are by far the best practices for this competition :-\n* Use Stratified Kfold because of different sources of Images\n* Use Cut-mix for better model generalization\n* Use WBF ensemble for unifying predictions of Kfold model\n\nBesides these I found gem of an EDA kernel , It gives very valuable insigts , you can have a look [here](https://www.kaggle.com/aleksandradeis/globalwheatdetection-eda) by aleksandra .Here are the conclusions derived from that kernel\n* Images are taken at different zoom levels. Crop and resize data augmentations to be used for model training.\n* Images are taken at various lighting conditions. Special filters should be used to address that.\n* Bounding boxes are messy!\n\n**There are some Giant bounding boxes and some micro bounding boxes removal of which have reported bad lb, so I assume the noise is present in the test setas well, hence keeping them would be more benificial**\n\nKeeping all this in find we start with coding DETR , **Note that this code can be used and easily modified to other object detection tasks**","metadata":{}},{"cell_type":"code","source":"!git clone https://github.com/facebookresearch/detr.git   #cloning github repo of detr to import its unique loss","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2022-03-19T15:13:29.323003Z","iopub.execute_input":"2022-03-19T15:13:29.323525Z","iopub.status.idle":"2022-03-19T15:13:32.050805Z","shell.execute_reply.started":"2022-03-19T15:13:29.323483Z","shell.execute_reply":"2022-03-19T15:13:32.049931Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* Now if you have seen the video , you know that DETR uses a special loss called Bipartite Matching loss where it assigns one ground truth bbox to a predicted box using a matcher , thus when fine tuning we need the matcher (hungarian matcher as used in paper) and also the fucntion SetCriterion which gives Bipartite matching loss for backpropogation. This is the reason for forking the github repo","metadata":{}},{"cell_type":"markdown","source":"* So I did not know that we can add the path to environment variables using sys , hence I was changine directories , but now I have made changes so I do not have to change directories and import detr easily. A big Thanks to @prvi for his help","metadata":{}},{"cell_type":"code","source":"import os\nimport numpy as np \nimport pandas as pd \nfrom datetime import datetime\nimport time\nimport random\nfrom tqdm.autonotebook import tqdm\n\n\n#Torch\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset,DataLoader\nfrom torch.utils.data.sampler import SequentialSampler, RandomSampler\n\n#sklearn\nfrom sklearn.model_selection import StratifiedKFold\n\n#CV\nimport cv2\n\n################# DETR FUCNTIONS FOR LOSS######################## \nimport sys\nsys.path.append('./detr/')\n\nfrom detr.models.matcher import HungarianMatcher\nfrom detr.models.detr import SetCriterion\n#################################################################\n\n#Albumenatations\nimport albumentations as A\nimport matplotlib.pyplot as plt\nfrom albumentations.pytorch.transforms import ToTensorV2\n\n#Glob\nfrom glob import glob","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-03-19T15:13:39.200698Z","iopub.execute_input":"2022-03-19T15:13:39.201085Z","iopub.status.idle":"2022-03-19T15:13:40.634599Z","shell.execute_reply.started":"2022-03-19T15:13:39.201052Z","shell.execute_reply":"2022-03-19T15:13:40.633807Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Utils\n\n* AverageMeter - class for averaging loss,metric,etc over epochs","metadata":{}},{"cell_type":"code","source":"class AverageMeter(object):\n    \"\"\"Computes and stores the average and current value\"\"\"\n    def __init__(self):\n        self.reset()\n\n    def reset(self):\n        self.val = 0\n        self.avg = 0\n        self.sum = 0\n        self.count = 0\n\n    def update(self, val, n=1):\n        self.val = val\n        self.sum += val * n\n        self.count += n\n        self.avg = self.sum / self.count","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:14:01.531195Z","iopub.execute_input":"2022-03-19T15:14:01.531526Z","iopub.status.idle":"2022-03-19T15:14:01.539105Z","shell.execute_reply.started":"2022-03-19T15:14:01.531495Z","shell.execute_reply":"2022-03-19T15:14:01.537661Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Configuration\n\nBasic configuration for this model","metadata":{}},{"cell_type":"code","source":"n_folds = 5\nseed = 42\nnum_classes = 2\nnum_queries = 100\nnull_class_coef = 0.5\nBATCH_SIZE = 8\nLR = 2e-5\nEPOCHS = 2","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:14:17.980627Z","iopub.execute_input":"2022-03-19T15:14:17.981122Z","iopub.status.idle":"2022-03-19T15:14:17.985668Z","shell.execute_reply.started":"2022-03-19T15:14:17.981084Z","shell.execute_reply":"2022-03-19T15:14:17.984814Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Seed Everything\n\nSeeding everything for reproducible results","metadata":{}},{"cell_type":"code","source":"def seed_everything(seed):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = True","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:14:23.223571Z","iopub.execute_input":"2022-03-19T15:14:23.223947Z","iopub.status.idle":"2022-03-19T15:14:23.229766Z","shell.execute_reply.started":"2022-03-19T15:14:23.223917Z","shell.execute_reply":"2022-03-19T15:14:23.228649Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"seed_everything(seed)","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:14:28.985602Z","iopub.execute_input":"2022-03-19T15:14:28.985968Z","iopub.status.idle":"2022-03-19T15:14:28.993296Z","shell.execute_reply.started":"2022-03-19T15:14:28.985938Z","shell.execute_reply":"2022-03-19T15:14:28.992206Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Preparing the Data\n\n* For preparation of data I use code from Alex's awesome kernel [here](https://www.kaggle.com/shonenkov/training-efficientdet)\n* The data can be split into any number of folds as you want , split is stratified based on number of boxes and source","metadata":{}},{"cell_type":"code","source":"marking = pd.read_csv('../input/global-wheat-detection/train.csv')\n\nbboxs = np.stack(marking['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=',')))\nfor i, column in enumerate(['x', 'y', 'w', 'h']):\n    marking[column] = bboxs[:,i]\nmarking.drop(columns=['bbox'], inplace=True)","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:14:32.931758Z","iopub.execute_input":"2022-03-19T15:14:32.932124Z","iopub.status.idle":"2022-03-19T15:14:33.860614Z","shell.execute_reply.started":"2022-03-19T15:14:32.932094Z","shell.execute_reply":"2022-03-19T15:14:33.859662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Creating Folds\nskf = StratifiedKFold(n_splits=n_folds, shuffle=True, random_state=seed)\n\ndf_folds = marking[['image_id']].copy()\ndf_folds.loc[:, 'bbox_count'] = 1\ndf_folds = df_folds.groupby('image_id').count()\ndf_folds.loc[:, 'source'] = marking[['image_id', 'source']].groupby('image_id').min()['source']\ndf_folds.loc[:, 'stratify_group'] = np.char.add(\n    df_folds['source'].values.astype(str),\n    df_folds['bbox_count'].apply(lambda x: f'_{x // 15}').values.astype(str)\n)\ndf_folds.loc[:, 'fold'] = 0\n\nfor fold_number, (train_index, val_index) in enumerate(skf.split(X=df_folds.index, y=df_folds['stratify_group'])):\n    df_folds.loc[df_folds.iloc[val_index].index, 'fold'] = fold_number","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:14:33.862138Z","iopub.execute_input":"2022-03-19T15:14:33.86248Z","iopub.status.idle":"2022-03-19T15:14:34.299949Z","shell.execute_reply.started":"2022-03-19T15:14:33.862442Z","shell.execute_reply":"2022-03-19T15:14:34.298118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Augmentations\n\n* As suggested by aleksendra in her kernel ,augentations will play a major role and hence took her up advice and use awesome augmentations , cut-mix and other will be included in future versions","metadata":{}},{"cell_type":"code","source":"def get_train_transforms():\n    return A.Compose([A.OneOf([A.HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit= 0.2, val_shift_limit=0.2, p=0.9),\n                               \n                      A.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.2, p=0.9)],p=0.9),\n                      \n                      A.ToGray(p=0.01),\n                      \n                      A.HorizontalFlip(p=0.5),\n                      \n                      A.VerticalFlip(p=0.5),\n                      \n                      A.Resize(height=512, width=512, p=1),\n                      \n                      A.Cutout(num_holes=8, max_h_size=64, max_w_size=64, fill_value=0, p=0.5),\n                      \n                      ToTensorV2(p=1.0)],\n                      \n                      p=1.0,\n                     \n                      bbox_params=A.BboxParams(format='coco',min_area=0, min_visibility=0,label_fields=['labels'])\n                      )\n\ndef get_valid_transforms():\n    return A.Compose([A.Resize(height=512, width=512, p=1.0),\n                      ToTensorV2(p=1.0)], \n                      p=1.0, \n                      bbox_params=A.BboxParams(format='coco',min_area=0, min_visibility=0,label_fields=['labels'])\n                      )","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:14:38.635362Z","iopub.execute_input":"2022-03-19T15:14:38.635693Z","iopub.status.idle":"2022-03-19T15:14:38.647189Z","shell.execute_reply.started":"2022-03-19T15:14:38.635662Z","shell.execute_reply":"2022-03-19T15:14:38.646173Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Creating Dataset\n\n* I hope you have the video by now , DETR accepts data in coco format which is (x,y,w,h)(for those who do not know there are two formats coco and pascal(smin,ymin,xmax,ymax) which are widely used) . So now we need to prepare data in that format","metadata":{}},{"cell_type":"code","source":"DIR_TRAIN = '../input/global-wheat-detection/train'\n\nclass WheatDataset(Dataset):\n    def __init__(self,image_ids,dataframe,transforms=None):\n        self.image_ids = image_ids\n        self.df = dataframe\n        self.transforms = transforms\n        \n        \n    def __len__(self) -> int:\n        return self.image_ids.shape[0]\n    \n    def __getitem__(self,index):\n        image_id = self.image_ids[index]\n        records = self.df[self.df['image_id'] == image_id]\n        \n        image = cv2.imread(f'{DIR_TRAIN}/{image_id}.jpg', cv2.IMREAD_COLOR)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)\n        image /= 255.0\n        \n        # DETR takes in data in coco format \n        boxes = records[['x', 'y', 'w', 'h']].values\n        \n        #Area of bb\n        area = boxes[:,2]*boxes[:,3]\n        area = torch.as_tensor(area, dtype=torch.float32)\n        \n        # AS pointed out by PRVI It works better if the main class is labelled as zero\n        labels =  np.zeros(len(boxes), dtype=np.int32)\n\n        \n        if self.transforms:\n            sample = {\n                'image': image,\n                'bboxes': boxes,\n                'labels': labels\n            }\n            sample = self.transforms(**sample)\n            image = sample['image']\n            boxes = sample['bboxes']\n            labels = sample['labels']\n            \n            \n        #Normalizing BBOXES\n            \n        _,h,w = image.shape\n        boxes = A.augmentations.bbox_utils.normalize_bboxes(sample['bboxes'],rows=h,cols=w)\n        target = {}\n        target['boxes'] = torch.as_tensor(boxes,dtype=torch.float32)\n        target['labels'] = torch.as_tensor(labels,dtype=torch.long)\n        target['image_id'] = torch.tensor([index])\n        target['area'] = area\n        \n        return image, target, image_id","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:14:43.104459Z","iopub.execute_input":"2022-03-19T15:14:43.104861Z","iopub.status.idle":"2022-03-19T15:14:43.119565Z","shell.execute_reply.started":"2022-03-19T15:14:43.104825Z","shell.execute_reply":"2022-03-19T15:14:43.118697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model\n\n* Initial DETR model is trained on coco dataset , which has 91 classes + 1 background class , hence we need to modify it to take our own number of classes\n* Also DETR model takes in 100 queries ie ,it outputs total of 100 bboxes for every image , we can very well change that too","metadata":{}},{"cell_type":"code","source":"class DETRModel(nn.Module):\n    def __init__(self,num_classes,num_queries):\n        super(DETRModel,self).__init__()\n        self.num_classes = num_classes\n        self.num_queries = num_queries\n        \n        self.model = torch.hub.load('facebookresearch/detr', 'detr_resnet50', pretrained=True)\n        self.in_features = self.model.class_embed.in_features\n        \n        self.model.class_embed = nn.Linear(in_features=self.in_features,out_features=self.num_classes)\n        self.model.num_queries = self.num_queries\n        \n    def forward(self,images):\n        return self.model(images)","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:14:46.107575Z","iopub.execute_input":"2022-03-19T15:14:46.108046Z","iopub.status.idle":"2022-03-19T15:14:46.116288Z","shell.execute_reply.started":"2022-03-19T15:14:46.108002Z","shell.execute_reply":"2022-03-19T15:14:46.115413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Matcher and Bipartite Matching Loss\n\nNow we make use of the unique loss that the model uses and for that we need to define the matcher. DETR calcuates three individual losses :\n* Classification Loss for labels(its weight can be set by loss_ce)\n* Bbox Loss (its weight can be set by loss_bbox)\n* Loss for Background class","metadata":{}},{"cell_type":"code","source":"'''\ncode taken from github repo detr , 'code present in engine.py'\n'''\n\nmatcher = HungarianMatcher()\n\nweight_dict = weight_dict = {'loss_ce': 1, 'loss_bbox': 1 , 'loss_giou': 1}\n\nlosses = ['labels', 'boxes', 'cardinality']","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:14:50.782404Z","iopub.execute_input":"2022-03-19T15:14:50.782773Z","iopub.status.idle":"2022-03-19T15:14:50.788056Z","shell.execute_reply.started":"2022-03-19T15:14:50.782737Z","shell.execute_reply":"2022-03-19T15:14:50.787177Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training Function\n\nTraining of DETR is unique and different from FasteRRcnn  and EfficientDET , as we train the criterion as well , the training function can be viewed here : https://github.com/facebookresearch/detr/blob/master/engine.py","metadata":{}},{"cell_type":"code","source":"def train_fn(data_loader,model,criterion,optimizer,device,scheduler,epoch):\n    model.train()\n    criterion.train()\n    \n    summary_loss = AverageMeter()\n    \n    tk0 = tqdm(data_loader, total=len(data_loader))\n    \n    for step, (images, targets, image_ids) in enumerate(tk0):\n        \n        images = list(image.to(device) for image in images)\n        targets = [{k: v.to(device) for k, v in t.items()} for t in targets]\n        \n\n        output = model(images)\n        \n        loss_dict = criterion(output, targets)\n        weight_dict = criterion.weight_dict\n        \n        losses = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict)\n        \n        optimizer.zero_grad()\n\n        losses.backward()\n        optimizer.step()\n        if scheduler is not None:\n            scheduler.step()\n        \n        summary_loss.update(losses.item(),BATCH_SIZE)\n        tk0.set_postfix(loss=summary_loss.avg)\n        \n    return summary_loss","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:14:54.923546Z","iopub.execute_input":"2022-03-19T15:14:54.923918Z","iopub.status.idle":"2022-03-19T15:14:54.934759Z","shell.execute_reply.started":"2022-03-19T15:14:54.923883Z","shell.execute_reply":"2022-03-19T15:14:54.9333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Eval Function","metadata":{}},{"cell_type":"code","source":"def eval_fn(data_loader, model,criterion, device):\n    model.eval()\n    criterion.eval()\n    summary_loss = AverageMeter()\n    \n    with torch.no_grad():\n        \n        tk0 = tqdm(data_loader, total=len(data_loader))\n        for step, (images, targets, image_ids) in enumerate(tk0):\n            \n            images = list(image.to(device) for image in images)\n            targets = [{k: v.to(device) for k, v in t.items()} for t in targets]\n\n            output = model(images)\n        \n            loss_dict = criterion(output, targets)\n            weight_dict = criterion.weight_dict\n        \n            losses = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict)\n            \n            summary_loss.update(losses.item(),BATCH_SIZE)\n            tk0.set_postfix(loss=summary_loss.avg)\n    \n    return summary_loss","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:14:58.237589Z","iopub.execute_input":"2022-03-19T15:14:58.238041Z","iopub.status.idle":"2022-03-19T15:14:58.248802Z","shell.execute_reply.started":"2022-03-19T15:14:58.238008Z","shell.execute_reply":"2022-03-19T15:14:58.247799Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Engine","metadata":{}},{"cell_type":"code","source":"def collate_fn(batch):\n    return tuple(zip(*batch))","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:15:01.811991Z","iopub.execute_input":"2022-03-19T15:15:01.812316Z","iopub.status.idle":"2022-03-19T15:15:01.816586Z","shell.execute_reply.started":"2022-03-19T15:15:01.812287Z","shell.execute_reply":"2022-03-19T15:15:01.81558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def run(fold):\n    \n    df_train = df_folds[df_folds['fold'] != fold]\n    df_valid = df_folds[df_folds['fold'] == fold]\n    \n    train_dataset = WheatDataset(\n    image_ids=df_train.index.values,\n    dataframe=marking,\n    transforms=get_train_transforms()\n    )\n\n    valid_dataset = WheatDataset(\n    image_ids=df_valid.index.values,\n    dataframe=marking,\n    transforms=get_valid_transforms()\n    )\n    \n    train_data_loader = DataLoader(\n    train_dataset,\n    batch_size=BATCH_SIZE,\n    shuffle=False,\n    num_workers=4,\n    collate_fn=collate_fn\n    )\n\n    valid_data_loader = DataLoader(\n    valid_dataset,\n    batch_size=BATCH_SIZE,\n    shuffle=False,\n    num_workers=4,\n    collate_fn=collate_fn\n    )\n    \n    device = torch.device('cuda')\n    model = DETRModel(num_classes=num_classes,num_queries=num_queries)\n    model = model.to(device)\n    criterion = SetCriterion(num_classes-1, matcher, weight_dict, eos_coef = null_class_coef, losses=losses)\n    criterion = criterion.to(device)\n    \n\n    optimizer = torch.optim.AdamW(model.parameters(), lr=LR)\n    \n    best_loss = 10**5\n    for epoch in range(EPOCHS):\n        train_loss = train_fn(train_data_loader, model,criterion, optimizer,device,scheduler=None,epoch=epoch)\n        valid_loss = eval_fn(valid_data_loader, model,criterion, device)\n        \n        print('|EPOCH {}| TRAIN_LOSS {}| VALID_LOSS {}|'.format(epoch+1,train_loss.avg,valid_loss.avg))\n        \n        if valid_loss.avg < best_loss:\n            best_loss = valid_loss.avg\n            print('Best model found for Fold {} in Epoch {}........Saving Model'.format(fold,epoch+1))\n            torch.save(model.state_dict(), f'detr_best_{fold}.pth')","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:15:02.163617Z","iopub.execute_input":"2022-03-19T15:15:02.164002Z","iopub.status.idle":"2022-03-19T15:15:02.180011Z","shell.execute_reply.started":"2022-03-19T15:15:02.163969Z","shell.execute_reply":"2022-03-19T15:15:02.177891Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run(fold=0)","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:15:08.154637Z","iopub.execute_input":"2022-03-19T15:15:08.155021Z","iopub.status.idle":"2022-03-19T15:23:47.387098Z","shell.execute_reply.started":"2022-03-19T15:15:08.154989Z","shell.execute_reply":"2022-03-19T15:23:47.385863Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Sample\n\n* I know we might be naive to visualize the model ouput just after one epoch but lets do that and see what are the results like","metadata":{}},{"cell_type":"code","source":"def view_sample(df_valid,model,device):\n    '''\n    Code taken from Peter's Kernel \n    https://www.kaggle.com/pestipeti/pytorch-starter-fasterrcnn-train\n    '''\n    valid_dataset = WheatDataset(image_ids=df_valid.index.values,\n                                 dataframe=marking,\n                                 transforms=get_valid_transforms()\n                                )\n     \n    valid_data_loader = DataLoader(\n                                    valid_dataset,\n                                    batch_size=BATCH_SIZE,\n                                    shuffle=False,\n                                   num_workers=4,\n                                   collate_fn=collate_fn)\n    \n    images, targets, image_ids = next(iter(valid_data_loader))\n    _,h,w = images[0].shape # for de normalizing images\n    \n    images = list(img.to(device) for img in images)\n    targets = [{k: v.to(device) for k, v in t.items()} for t in targets]\n    \n    boxes = targets[0]['boxes'].cpu().numpy()\n    boxes = [np.array(box).astype(np.int32) for box in A.augmentations.bbox_utils.denormalize_bboxes(boxes,h,w)]\n    sample = images[0].permute(1,2,0).cpu().numpy()\n    \n    model.eval()\n    model.to(device)\n    cpu_device = torch.device(\"cpu\")\n    \n    with torch.no_grad():\n        outputs = model(images)\n        \n    outputs = [{k: v.to(cpu_device) for k, v in outputs.items()}]\n    \n    fig, ax = plt.subplots(1, 1, figsize=(16, 8))\n\n    for box in boxes:\n        cv2.rectangle(sample,\n                  (box[0], box[1]),\n                  (box[2]+box[0], box[3]+box[1]),\n                  (220, 0, 0), 1)\n        \n\n    oboxes = outputs[0]['pred_boxes'][0].detach().cpu().numpy()\n    oboxes = [np.array(box).astype(np.int32) for box in A.augmentations.bbox_utils.denormalize_bboxes(oboxes,h,w)]\n    prob   = outputs[0]['pred_logits'][0].softmax(1).detach().cpu().numpy()[:,0]\n    \n    for box,p in zip(oboxes,prob):\n        \n        if p >0.5:\n            color = (0,0,220) #if p>0.5 else (0,0,0)\n            cv2.rectangle(sample,\n                  (box[0], box[1]),\n                  (box[2]+box[0], box[3]+box[1]),\n                  color, 1)\n    \n    ax.set_axis_off()\n    ax.imshow(sample)","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:23:47.390746Z","iopub.execute_input":"2022-03-19T15:23:47.391027Z","iopub.status.idle":"2022-03-19T15:23:47.410936Z","shell.execute_reply.started":"2022-03-19T15:23:47.390996Z","shell.execute_reply":"2022-03-19T15:23:47.410005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = DETRModel(num_classes=num_classes,num_queries=num_queries)\nmodel.load_state_dict(torch.load(\"./detr_best_0.pth\"))\nview_sample(df_folds[df_folds['fold'] == 0],model=model,device=torch.device('cuda'))","metadata":{"execution":{"iopub.status.busy":"2022-03-19T15:23:47.412731Z","iopub.execute_input":"2022-03-19T15:23:47.413141Z","iopub.status.idle":"2022-03-19T15:23:51.738258Z","shell.execute_reply.started":"2022-03-19T15:23:47.413102Z","shell.execute_reply":"2022-03-19T15:23:51.735869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# End Notes\n\nI will further add information about various losses that DETR uses , how is criterion declared , what are its parameters exactly,what is hungarian matcher , a little intuition\n\n* We trained one epoch that too for a single fold, but  Detr seems to work fairly well.\n* I hope you liked my effort , trying hands with this new model \n* If this kernel receives love,I plan to fine tune DETR,run all five folds and publish an inference kernel using WBF for this competition, I belive this can score above 0.74 without any pseudo labelling tricks\n* I also plan to include visualization of attentionn weights in the next version along with first fold fully trained on 30-35 epochs with a good lr scdeduler\n* I tried to write a genric code so that this can be used with any general object detection dataset and tasks\n\n\n<font color='red'>Please consider upvoting if my efforts helped you or made you excited about DETR</font>","metadata":{}}]}