{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# # Jacob Morin - COS 432\n\nOriginal Pseudo Labeling Notebook: https://www.kaggle.com/nvnnghia/fasterrcnn-pseudo-labeling\n"},{"metadata":{},"cell_type":"markdown","source":"My changes to this file were made to include the augementations from my previous training notebook. Some augmentations were removed because I wanted to submit this notebook and interent would have been required to update the albumentations."},{"metadata":{"trusted":true},"cell_type":"code","source":"#!pip freeze\n#! pip install --upgrade albumentations","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport cv2\nimport os\nimport re\nimport math\nimport random\n\nfrom PIL import Image\n\nimport albumentations as A\nfrom albumentations.pytorch.transforms import ToTensorV2\n\nimport ast\nimport torch\nimport torchvision\n\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor\nfrom torchvision.models.detection import FasterRCNN\nfrom torchvision.models.detection.rpn import AnchorGenerator\n\nfrom torch.utils.data import DataLoader, Dataset\nfrom torch.utils.data.sampler import SequentialSampler\n\nfrom matplotlib import pyplot as plt\n\n\nDIR_INPUT = '/kaggle/input/global-wheat-detection'\nDIR_TRAIN = f'{DIR_INPUT}/train'\nDIR_TEST = f'{DIR_INPUT}/test'\n\nDIR_WEIGHTS = '/kaggle/input/rcnn12152'\n\nWEIGHTS_FILE = f'{DIR_WEIGHTS}/fasterrcnn_resnet50_fpn-12152.pth'","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"test_df = pd.read_csv(f'{DIR_INPUT}/sample_submission.csv')\ntest_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class WheatTestDataset(Dataset):\n\n    def __init__(self, dataframe, image_dir, transforms=None):\n        super().__init__()\n\n        self.image_ids = dataframe['image_id'].unique()\n        self.df = dataframe\n        self.image_dir = image_dir\n        self.transforms = transforms\n\n    def __getitem__(self, index: int):\n\n        image_id = self.image_ids[index]\n        records = self.df[self.df['image_id'] == image_id]\n\n        image = cv2.imread(f'{self.image_dir}/{image_id}.jpg', cv2.IMREAD_COLOR)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)\n        image /= 255.0\n\n        if self.transforms:\n            sample = {\n                'image': image,\n            }\n            sample = self.transforms(**sample)\n            image = sample['image']\n\n        return image, image_id\n\n    def __len__(self) -> int:\n        return self.image_ids.shape[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Albumentations\ndef get_train_transform():\n    return A.Compose([\n        #A.Resize(1024, 1024),\n        #A.ShiftScaleRotate (shift_limit=0.0625, scale_limit=0.0, rotate_limit=360, interpolation=1, border_mode=cv2.BORDER_CONSTANT, value=None, mask_value=None, always_apply=False, p=.5),\n        \n        #Enable these\n        A.Flip(0.5),\n        A.ShiftScaleRotate (shift_limit=0.0, scale_limit=0.0, rotate_limit=10, interpolation=1, border_mode=cv2.BORDER_CONSTANT, value=None, mask_value=None, always_apply=False, p=.5),\n        A.RandomSizedCrop (min_max_height=[768,1024], height=1024, width=1024, w2h_ratio=1.0, interpolation=1, always_apply=False, p=.5),\n        #A.ColorJitter (brightness=0.3, contrast=0.2, saturation=0.1, hue=0.1, always_apply=False, p=.5),\n        \n        \n        #A.HueSaturationValue(hue_shift_limit=1, sat_shift_limit=1, val_shift_limit=1, always_apply=False, p=.5),\n        #A.Resize(512, 512),\n        #A.CenterCrop (10, 10, always_apply=False, p=1.0), #For testing use, will generate samples with mostly zero boxes\n        ToTensorV2(p=1.0)\n    ], bbox_params={'format': 'pascal_voc', 'label_fields': ['labels']})\n\ndef get_valid_transform():\n    return A.Compose([\n        #A.Resize(512, 512),\n        ToTensorV2(p=1.0)\n    ], bbox_params={'format': 'pascal_voc', 'label_fields': ['labels']})\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Albumentations\ndef get_test_transform():\n    return A.Compose([\n        # A.Resize(512, 512),\n        ToTensorV2(p=1.0)\n    ])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# load a model; pre-trained on COCO\nmodel = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=False, pretrained_backbone=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\nnum_classes = 2  # 1 class (wheat) + background\n\n# get number of input features for the classifier\nin_features = model.roi_heads.box_predictor.cls_score.in_features\n\n# replace the pre-trained head with a new one\nmodel.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)\n\n# Load the trained weights\nmodel.load_state_dict(torch.load(WEIGHTS_FILE))\nmodel.eval()\n\nx = model.to(device)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def collate_fn(batch):\n    return tuple(zip(*batch))\n\ntest_dataset = WheatTestDataset(test_df, DIR_TEST, get_test_transform())\n\ntest_data_loader = DataLoader(\n    test_dataset,\n    batch_size=4,\n    shuffle=False,\n    num_workers=4,\n    drop_last=False,\n    collate_fn=collate_fn\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def format_prediction_string(boxes, scores):\n    pred_strings = []\n    for j in zip(scores, boxes):\n        pred_strings.append(\"{0:.4f} {1} {2} {3} {4}\".format(j[0], j[1][0], j[1][1], j[1][2], j[1][3]))\n\n    return \" \".join(pred_strings)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# # **Detection and make Pseudo labels for test dataset**"},{"metadata":{"trusted":true},"cell_type":"code","source":"detection_threshold = 0.5\nresults = []\n\ntestdf_psuedo = []\nfor images, image_ids in test_data_loader:\n\n    images = list(image.to(device) for image in images)\n    outputs = model(images)\n\n    for i, image in enumerate(images):\n\n        boxes = outputs[i]['boxes'].data.cpu().numpy()\n        scores = outputs[i]['scores'].data.cpu().numpy()\n        \n        boxes = boxes[scores >= detection_threshold].astype(np.int32)\n        scores = scores[scores >= detection_threshold]\n        image_id = image_ids[i]\n        \n        boxes[:, 2] = boxes[:, 2] - boxes[:, 0]\n        boxes[:, 3] = boxes[:, 3] - boxes[:, 1]\n        \n        for box in boxes:\n            #print(box)\n            result = {\n                'image_id': 'pred'+image_id,\n                'width': 1024,\n                'height': 1024,\n                'source': 'pred',\n                'x': box[0],\n                'y': box[1],\n                'w': box[2],\n                'h': box[3]\n            }\n            testdf_psuedo.append(result)\n            \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df_pseudo = pd.DataFrame(testdf_psuedo, columns=['image_id', 'width', 'height', 'source', 'x', 'y', 'w', 'h'])\ntest_df_pseudo.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# # **Retrain model with pseudo labels"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv(f'{DIR_INPUT}/train.csv')\ntrain_df['x'] = -1\ntrain_df['y'] = -1\ntrain_df['w'] = -1\ntrain_df['h'] = -1\n\ndef expand_bbox(x):\n    r = np.array(re.findall(\"([0-9]+[.]?[0-9]*)\", x))\n    if len(r) == 0:\n        r = [-1, -1, -1, -1]\n    return r\n\ntrain_df[['x', 'y', 'w', 'h']] = np.stack(train_df['bbox'].apply(lambda x: expand_bbox(x)))\ntrain_df.drop(columns=['bbox'], inplace=True)\ntrain_df['x'] = train_df['x'].astype(np.float)\ntrain_df['y'] = train_df['y'].astype(np.float)\ntrain_df['w'] = train_df['w'].astype(np.float)\ntrain_df['h'] = train_df['h'].astype(np.float)\n\ntrain_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_ids = train_df['image_id'].unique()\nvalid_ids = image_ids[-665:]\ntrain_ids = image_ids #[:-665]\n\nvalid_df = train_df[train_df['image_id'].isin(valid_ids)]\n#train_df = train_df[train_df['image_id'].isin(train_ids)]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"frames = [train_df, test_df_pseudo]\n\ntrain_df = pd.concat(frames)\ntrain_df.tail()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# # **Wheat dataset for Training**"},{"metadata":{"trusted":true},"cell_type":"code","source":"class WheatDataset(Dataset):\n\n    def __init__(self, dataframe, image_dir, transforms=None):\n        super().__init__()\n\n        self.image_ids = dataframe['image_id'].unique()\n        self.df = dataframe\n        self.image_dir = image_dir\n        self.transforms = transforms\n        \n\n    def __getitem__(self, index: int):\n        \n        #self.mosaic=True;\n        #if random.randint(0,1) ==0:\n            #self.mosaic = False\n            \n        rnd = random.random()\n        #rnd = .4\n        if rnd< 0.33:\n            # Load mosaic image\n            image, target, image_id = load_mosaic(self, index)\n        \n        elif (rnd > 0.33 and rnd < 0.66):\n            image, target, image_id = load_mixup(self, index)\n        \n        else:\n            # Load image normally\n            image, target, image_id = load_image(self, index,)\n        \n        return image, target, image_id\n\n    def __len__(self) -> int:\n        return self.image_ids.shape[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_image(self, index):\n    image_id = self.image_ids[index]\n    records = self.df[self.df['image_id'] == image_id]\n\n    if 'pred' in image_id:\n        image_id = image_id[4:]\n        image = cv2.imread(f'{DIR_TEST}/{image_id}.jpg', cv2.IMREAD_COLOR)\n    else:\n        image = cv2.imread(f'{self.image_dir}/{image_id}.jpg', cv2.IMREAD_COLOR)\n        \n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)\n    image /= 255.0\n\n    boxes = records[['x', 'y', 'w', 'h']].values\n    boxes[:, 2] = boxes[:, 0] + boxes[:, 2]\n    boxes[:, 3] = boxes[:, 1] + boxes[:, 3]\n\n    area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])\n    area = torch.as_tensor(area, dtype=torch.float32)\n\n    # there is only one class\n    labels = torch.ones((records.shape[0],), dtype=torch.int64)\n\n    # suppose all instances are not crowd\n    iscrowd = torch.zeros((records.shape[0],), dtype=torch.int64)\n\n    target = {}\n    target['boxes'] = boxes\n    target['labels'] = labels\n    # target['masks'] = None\n    target['image_id'] = torch.tensor([index])\n    target['area'] = area\n    target['iscrowd'] = iscrowd\n\n    if self.transforms:\n        sample = {\n            'image': image,\n            'bboxes': target['boxes'],\n            'labels': labels\n        }\n        sampleTrans = self.transforms(**sample)\n        \n        #make sure there is at least one box in a sample, break the code otherwise\n        while len(sampleTrans['bboxes'])==0:\n            #print(\"No boxes, rerun\")\n            sampleTrans = self.transforms(**sample)\n\n        #for loop to remove excessively narrow boxes, effectively only along the edges after albumentations\n        bs = sampleTrans['bboxes']\n        thresh = 4.5\n        pix = 15;\n        #print(bs)\n        for box in bs:\n            #print(box)\n            height = box[2]-box[0]\n            width = box[3]-box[1]\n            prop = height/width\n            #print(prop)\n            if( (height<pix or width< pix or prop>thresh or prop<(1/thresh)) and len(bs)>1):\n                #print('remove {0}'.format(box))\n                bs.remove(box)\n\n        if(len(bs)>=1):\n            sampleTrans['bboxes'] = bs\n        \n        sample = sampleTrans\n        image = sample['image']\n        target['boxes'] = torch.stack(tuple(map(torch.tensor, zip(*sample['bboxes'])))).permute(1, 0)\n\n    return image, target, image_id\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_mixup(self, index):\n    # loads 2 images\n    imglist = []\n    idlist = []\n    allboxes = [[0,0,0,0]]\n    \n    for i in range(2):\n        if(i == 0):\n            #load initial image normally\n            image_id = self.image_ids[index]\n            \n        else:\n            #load random next image\n            image_id = self.image_ids[random.randint(0, len(self.image_ids) - 1)]\n\n                \n        #idlist.append(image_id)\n        records = self.df[self.df['image_id'] == image_id]\n        boxes = records[['x', 'y', 'w', 'h']].values\n        #print(boxes)\n        boxes[:, 2] = boxes[:, 0] + boxes[:, 2] \n        boxes[:, 3] = boxes[:, 1] + boxes[:, 3]\n        \n        allboxes = np.vstack((allboxes, boxes))\n\n        if 'pred' in image_id:\n            image_id = image_id[4:]\n            image = cv2.imread(f'{DIR_TEST}/{image_id}.jpg', cv2.IMREAD_COLOR)\n        else:\n            image = cv2.imread(f'{self.image_dir}/{image_id}.jpg', cv2.IMREAD_COLOR)\n            \n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)\n        image /= 255.0\n        imglist.append(image)\n    \n        \n    #print(allboxes)\n    allboxes = allboxes[1:]\n    \n    #combine the two images\n    mix_img = np.add(imglist[0],(imglist[1]))/2\n        \n    #print(mix_img)\n        \n    area = (allboxes[:, 3] - allboxes[:, 1]) * (allboxes[:, 2] - allboxes[:, 0])\n    area = torch.as_tensor(area, dtype=torch.float32)\n\n    # there is only one class\n    labels = torch.ones((allboxes.shape[0],), dtype=torch.int64)\n\n    # suppose all instances are not crowd\n    iscrowd = torch.zeros((allboxes.shape[0],), dtype=torch.int64)\n\n    target = {}\n    target['boxes'] = allboxes\n    target['labels'] = labels\n    # target['masks'] = None\n    target['image_id'] = torch.tensor([index])\n    target['area'] = area\n    target['iscrowd'] = iscrowd\n\n    sample = {\n            'image': mix_img,\n            'bboxes': target['boxes'],\n            'labels': labels\n        }\n    \n    if self.transforms:\n        \n        sampleTrans = self.transforms(**sample)\n        #sample = self.transforms(**sample)\n        \n        while len(sampleTrans['bboxes'])==0:\n            #print(\"No boxes, rerun\")\n            sampleTrans = self.transforms(**sample)\n            \n        #for loop to remove excessively narrow boxes, effectively only along the edges after albumentations\n        bs = sampleTrans['bboxes']\n        thresh = 4.5\n        pix = 15;\n        #print(bs)\n        for box in bs:\n            #print(box)\n            height = box[2]-box[0]\n            width = box[3]-box[1]\n            prop = height/width\n            #print(prop)\n            if( (height<pix or width< pix or prop>thresh or prop<(1/thresh)) and len(bs)>1):\n                #print('remove {0}'.format(box))\n                bs.remove(box)\n\n        if(len(bs)>=1):\n            sampleTrans['bboxes'] = bs\n            \n        sample = sampleTrans\n        mix_img = sample['image']\n        \n        target['boxes'] = torch.stack(tuple(map(torch.tensor, zip(*sample['bboxes'])))).permute(1, 0)\n            \n    return mix_img, target, image_id","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_mosaic(self, index):\n    # loads images in a mosaic by loading them into a 2x2 grid first, then cropping to move the center\n    imglist = []\n    idlist = []\n    allboxes = [[0,0,0,0]]\n    \n    for i in range(4):\n        if(i == 0):\n            #load initial image normally\n            image_id = self.image_ids[index]\n            \n            padw, padh = 0, 0\n            \n        else:\n            #load random next image\n            image_id = self.image_ids[random.randint(0, len(self.image_ids) - 1)]\n            \n            if(i==1):\n                padw, padh = 1024, 0\n            if(i==2):\n                padw, padh = 0, 1024\n            if(i==3):\n                padw, padh = 1024, 1024\n                \n        #idlist.append(image_id)\n        records = self.df[self.df['image_id'] == image_id]\n        boxes = records[['x', 'y', 'w', 'h']].values\n        boxes[:, 0] = boxes[:, 0] + padw\n        boxes[:, 1] = boxes[:, 1] + padh\n        boxes[:, 2] = boxes[:, 0] + boxes[:, 2] \n        boxes[:, 3] = boxes[:, 1] + boxes[:, 3]\n        \n        #print(boxes)\n        \n        allboxes = np.vstack((allboxes, boxes))\n\n        if 'pred' in image_id:\n            image_id = image_id[4:]\n            image = cv2.imread(f'{DIR_TEST}/{image_id}.jpg', cv2.IMREAD_COLOR)\n        else:\n            image = cv2.imread(f'{self.image_dir}/{image_id}.jpg', cv2.IMREAD_COLOR)\n            \n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)\n        image /= 255.0\n        imglist.append(image)\n    \n        \n    #print(allboxes)\n    allboxes = allboxes[1:]\n    grid_img = make_grid(imglist)\n\n    area = (allboxes[:, 3] - allboxes[:, 1]) * (allboxes[:, 2] - allboxes[:, 0])\n    area = torch.as_tensor(area, dtype=torch.float32)\n\n    # there is only one class\n    labels = torch.ones((allboxes.shape[0],), dtype=torch.int64)\n\n    # suppose all instances are not crowd\n    iscrowd = torch.zeros((allboxes.shape[0],), dtype=torch.int64)\n\n    target = {}\n    target['boxes'] = allboxes\n    target['labels'] = labels\n    # target['masks'] = None\n    target['image_id'] = torch.tensor([index])\n    target['area'] = area\n    target['iscrowd'] = iscrowd\n\n    sample = {\n            'image': grid_img,\n            'bboxes': target['boxes'],\n            'labels': labels\n        }\n    aug = crop_mosaic()\n    sample = aug(**sample)\n    \n    if self.transforms:\n        \n        sampleTrans = self.transforms(**sample)\n        #sample = self.transforms(**sample)\n        \n        while len(sampleTrans['bboxes'])==0:\n            #print(\"No boxes, rerun\")\n            sampleTrans = self.transforms(**sample)\n            \n        #for loop to remove excessively narrow boxes, effectively only along the edges after albumentations\n        bs = sampleTrans['bboxes']\n        thresh = 4.5\n        pix = 15;\n        #print(bs)\n        for box in bs:\n            #print(box)\n            height = box[2]-box[0]\n            width = box[3]-box[1]\n            prop = height/width\n            #print(prop)\n            if( (height<pix or width< pix or prop>thresh or prop<(1/thresh)) and len(bs)>1):\n                #print('remove {0}'.format(box))\n                bs.remove(box)\n\n        if(len(bs)>=1):\n            sampleTrans['bboxes'] = bs\n            \n        sample = sampleTrans\n        grid_img = sample['image']\n        target['boxes'] = torch.stack(tuple(map(torch.tensor, zip(*sample['bboxes'])))).permute(1, 0)\n            \n    return grid_img, target, image_id","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def crop_mosaic():\n    return A.Compose([\n        A.RandomSizedCrop (min_max_height=[900,1100], height=1024, width=1024, w2h_ratio=1.0, interpolation=1, always_apply=True, p=1.0),\n        #ToTensorV2(p=1.0)\n    ], bbox_params={'format': 'pascal_voc', 'label_fields': ['labels']})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def make_grid(imagelist):\n    #stacks the 4 images in the list to form a 2x2 grid\n    lrt = np.hstack((imagelist[0],imagelist[1]))\n    lrb = np.hstack((imagelist[2],imagelist[3]))\n    grid_image = np.vstack((lrt,lrb))\n    #print(grid_image.shape)\n    return grid_image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class Averager:\n    def __init__(self):\n        self.current_total = 0.0\n        self.iterations = 0.0\n\n    def send(self, value):\n        self.current_total += value\n        self.iterations += 1\n\n    @property\n    def value(self):\n        if self.iterations == 0:\n            return 0\n        else:\n            return 1.0 * self.current_total / self.iterations\n\n    def reset(self):\n        self.current_total = 0.0\n        self.iterations = 0.0\n        \n        \ndef collate_fn(batch):\n    return tuple(zip(*batch))\n\ntrain_dataset = WheatDataset(train_df, DIR_TRAIN, get_train_transform())\nvalid_dataset = WheatDataset(valid_df, DIR_TRAIN, get_valid_transform())\n\n\n# split the dataset in train and test set\nindices = torch.randperm(len(train_dataset)).tolist()\n\ntrain_data_loader = DataLoader(\n    train_dataset,\n    batch_size=6,\n    shuffle=True,\n    num_workers=4,\n    collate_fn=collate_fn\n)\n\nvalid_data_loader = DataLoader(\n    valid_dataset,\n    batch_size=3,\n    shuffle=True,\n    num_workers=4,\n    collate_fn=collate_fn\n)\n\ndevice = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# **Show a sample**"},{"metadata":{"trusted":true},"cell_type":"code","source":"images, targets, image_ids = next(iter(train_data_loader))\nimages = list(image.to(device) for image in images)\ntargets = [{k: v.to(device) for k, v in t.items()} for t in targets]\n\nboxes = targets[2]['boxes'].cpu().numpy().astype(np.int32)\nsample = images[2].permute(1,2,0).cpu().numpy()\n\nfig, ax = plt.subplots(1, 1, figsize=(16, 8))\n\nfor box in boxes:\n    cv2.rectangle(sample,\n                  (box[0], box[1]),\n                  (box[2], box[3]),\n                  (220, 0, 0), 3)\n    \nax.set_axis_off()\nax.imshow(sample)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# # ****retrain Faster RCNN****"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.train()\nmodel.to(device)\nparams = [p for p in model.parameters() if p.requires_grad]\noptimizer = torch.optim.SGD(params, lr=0.01, momentum=0.9, weight_decay=0.0001)\nlr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.5)\n#lr_scheduler = None\n\nnum_epochs = 5\n\nloss_hist = Averager()\nitr = 1\n\nfor epoch in range(num_epochs):\n    loss_hist.reset()\n    \n    for images, targets, image_ids in train_data_loader:\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        loss_dict = model(images, targets)\n\n        losses = sum(loss for loss in loss_dict.values())\n        loss_value = losses.item()\n\n        loss_hist.send(loss_value)\n\n        optimizer.zero_grad()\n        losses.backward()\n        optimizer.step()\n\n        if itr % 50 == 0:\n            print(f\"Iteration #{itr} loss: {loss_value}\")\n\n        itr += 1\n    \n    # update the learning rate\n    if lr_scheduler is not None:\n        lr_scheduler.step()\n\n    print(f\"Epoch #{epoch} loss: {loss_hist.value}\")\n    \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"torch.save(model.state_dict(), 'fasterrcnn_resnet50_fpn2nd.pth')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# **final Inference and submission"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.eval()\n\nfor images, image_ids in test_data_loader:\n\n    images = list(image.to(device) for image in images)\n    outputs = model(images)\n\n    for i, image in enumerate(images):\n\n        boxes = outputs[i]['boxes'].data.cpu().numpy()\n        scores = outputs[i]['scores'].data.cpu().numpy()\n        \n        boxes = boxes[scores >= detection_threshold].astype(np.int32)\n        scores = scores[scores >= detection_threshold]\n        image_id = image_ids[i]\n        \n        boxes[:, 2] = boxes[:, 2] - boxes[:, 0]\n        boxes[:, 3] = boxes[:, 3] - boxes[:, 1]\n        \n        \n            \n        result = {\n            'image_id': image_id,\n            'PredictionString': format_prediction_string(boxes, scores)\n        }\n\n        \n        results.append(result)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])\ntest_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample = images[1].permute(1,2,0).cpu().numpy()\nboxes = outputs[1]['boxes'].data.cpu().numpy()\nscores = outputs[1]['scores'].data.cpu().numpy()\n\nboxes = boxes[scores >= detection_threshold].astype(np.int32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(1, 1, figsize=(16, 8))\n\nfor box in boxes:\n    cv2.rectangle(sample,\n                  (box[0], box[1]),\n                  (box[2], box[3]),\n                  (220, 0, 0), 2)\n    \nax.set_axis_off()\nax.imshow(sample)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}