{"cells":[{"metadata":{},"cell_type":"markdown","source":"The original notebook is not mine but I have added 256 lines of my own code and comments. \n\n# Pytorch starter - FasterRCNN Train\nIn this notebook I enabled the GPU and the Internet access (needed for the pre-trained weights). We can not use Internet during inference, so I'll create another notebook for commiting. Stay tuned!\n\n\n- FasterRCNN from torchvision\n- Use Resnet50 backbone\n- Albumentation enabled (simple flip for now)\n"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport cv2\nimport os\nimport re\n\nfrom PIL import Image\n\nimport albumentations as A #Package of transformations\nfrom albumentations.pytorch.transforms import ToTensorV2\n\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 #Create an efficient dataloader set to feed images to the model\nfrom torch.utils.data.sampler import SequentialSampler\n\nfrom matplotlib import pyplot as plt #Allows us to create a sample image to test the model is working correctly\n\nDIR_INPUT = '/kaggle/input/global-wheat-detection' #Base directory for this challenge\nDIR_TRAIN = f'{DIR_INPUT}/train' #Base directory where both train images and train metadata is located\nDIR_TEST = f'{DIR_INPUT}/test' #Base directory where 10 test images are located. The rest is kept private by the organisers\nDIR_WEIGHTS = '/kaggle/input/fasterrcnn'\n\nWEIGHTS_FILE = f'{DIR_WEIGHTS}/fasterrcnn_resnet50_fpn_best.pth'","execution_count":null,"outputs":[]},{"metadata":{"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\n\n#Create a function to applies some list of transformations to each image with certain probabilities\n    #Be mindful that these transforms are not independent, the function may apply more than one.\n    #Two transforms each with 0.5 probability have a 0.5 * 0.5 probability (25%) of applying both transforms. \ndef get_train_transform():\n    return A.Compose([\n        A.Flip(p = 0.5),\n        A.Blur(p=0.5),\n        ToTensorV2(p=1.0)\n    ], bbox_params={'format': 'pascal_voc', 'label_fields': ['labels']})\n\ndef get_valid_transform():\n    return A.Compose([\n        ToTensorV2(p=1.0)\n    ], bbox_params={'format': 'pascal_voc', 'label_fields': ['labels']})\n\ndef get_test_transform():\n    return A.Compose([\n        # A.Resize(512, 512),\n        ToTensorV2(p=1.0)\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":"#Set device equal to GPU if GPU is selected in the \"settings\" tab on the right, under Accelerator, otherwise set device to CPU\ndevice = 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))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_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":"# Create Pseudo Labels"},{"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': image_id,\n                'width': 1024,\n                'height': 1024,\n                'source': 'nvnn',\n                'x': box[0],\n                'y': box[1],\n                'w': box[2],\n                'h': box[3]\n            }\n            testdf_psuedo.append(result)","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 the model with new pseudo labels"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv(f'{DIR_INPUT}/train.csv') #Concatinate the base directory and file name and create a dataframe\nprint(train_df) #Print the dataframe to check the import worked\n\n#Count the number of unique images in the training data\ntrain_df.image_id.nunique()\n\n#Add 4 new columns and set their value to -1.\n    #This is just a placeholder, we could use any value. It will get replaced by the expand_bbox function\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\n#Replace the values in the x, y, w, h columns by the values from the bbox column.\n    #Lambda x is saying \"for each x run the function expand_bbox\"\n    #We are setting \"x\" to be a cell in the train_df bbox column.\ntrain_df[['x', 'y', 'w', 'h']] = np.stack(train_df['bbox'].apply(lambda x: expand_bbox(x)))\n\n#We now have duplicated content, the original string of concatinated bounding box dimensions and the new seperated values.\n#Therefore, we can drop the original bbox column and just retain the 4 new columns.\ntrain_df.drop(columns=['bbox'], inplace=True)\n\n#Columns x, y, w, h are \"object\" types. We can convert these to floats as below...\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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Create a numpy array of only the unique image_ids. Most images have multiple bounding boxes so the original train_df...\n#...has repeated image_ids \nimage_ids = train_df['image_id'].unique()\n\n#Seperate those image ids into a training and validation set.\n    #The original dataset has 3373. 674 is approx 20%, a common split for train/valid is 80/20 as here.\nvalid_ids = image_ids[-674:]\ntrain_ids = image_ids #[:-674]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_ids.size","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#For those image ids that are in valid_ids we want the full info about each image from the original full train_df.\n    #This includes all the bounding boxes and the size of the image\nvalid_df = train_df[train_df['image_id'].isin(valid_ids)]\n\n#In the usual case the same is done for the training portion.\ntrain_df = train_df[train_df['image_id'].isin(train_ids)]\n    #However, now we have 10 more images with Pseudo labels we can add those to the training data\n\nframes = [train_df, test_df_pseudo]\nprint(frames)\ntrain_df = pd.concat(frames)\n#In this case we are using tail rather than head as we attached the test images to the end of the dataframe.\n    #This allows us to check that everything was joined correctly\ntrain_df.tail()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"valid_df.shape, train_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class WheatDataset(Dataset):\n\n    def __init__(self, dataframe, image_dir, transforms):\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        \n        #Standardise the image pixel data\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 (wheat or not)\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            sample = self.transforms(**sample)\n            image = sample['image']\n            \n            target['boxes'] = torch.stack(tuple(map(torch.tensor, zip(*sample['bboxes'])))).permute(1, 0)\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":{},"cell_type":"markdown","source":"# Create the model"},{"metadata":{"trusted":true},"cell_type":"code","source":"# load a model; pre-trained on COCO\nmodel = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)","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        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Create a training dataset.\n    #We pass the train_df (which now contains all information for the 80% of the images we randomly chose)...\n        #...we also pass the directory for the image jpg files, and the function to apply any transformations.\ntrain_dataset = WheatDataset(train_df, DIR_TRAIN, get_train_transform())\n\n#The same arguments are passed to the same function but this time it is for the validation portion of the whole dataset\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\n#Create a dataloader to efficiently load the data to the model. We send train_dataset that we just created to the Dataloader\ntrain_data_loader = DataLoader(\n    train_dataset,\n    batch_size=16,\n    shuffle=False,\n    num_workers=4, #num_workers defines how many cores of the device we want to use, in this case the GPU\n    collate_fn=collate_fn\n)\n\n#A dataloader is also created for the validation set.\nvalid_data_loader = DataLoader(\n    valid_dataset,\n    batch_size=8,\n    shuffle=False,\n    num_workers=4,\n    collate_fn=collate_fn\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Sample"},{"metadata":{"trusted":true},"cell_type":"code","source":"#Iterate through the train_data_loader object, row by row, and for each row we unpack the information into image, targets, and image_id\n    #images is a tuple where each item is a list of all the pixel values for a particular image\n    #targets is a tuple where each item is a list of the x, y, w, h dimensions for each bounding box\nimages, targets, image_ids = next(iter(train_data_loader))\n\n#For each image (as described above) we send the image to the device (likely CPU) and then add the values to a list.\nimages = list(image.to(device) for image in images)\n\ntargets = [{k: v.to(device) for k, v in t.items()} for t in targets]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"boxes = targets[2]['boxes'].cpu().numpy().astype(np.int32)\nsample = images[2].permute(1,2,0).cpu().numpy()","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), 3)\n    \nax.set_axis_off()\nax.imshow(sample)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Retrain Faster R-CNN\nHere we are now training the model using the original training data but in addition we have 10 test images that we have included predicted labels with."},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow import keras\n\nmodel.train()\n#Send the model to the device - GPU\nmodel.to(device)\n\n#Create a list of parameters to be used for calculating the loss under our optimizer.\n    #Only include parameters that require the gradient to be altered.\nparams = [p for p in model.parameters() if p.requires_grad]\n\n#Create a Stochastic Gradient Descent optimiser (SGD).\n    #all parameters can be changed but momentum is commonly 0.9.\noptimizer = torch.optim.SGD(params, lr=0.0075, momentum=0.9, weight_decay=0.0005)\n\n#Peter originally included the StepLR learning rate annealer but I added two more as optional choices for you.\n    #Only the final will be used so there is no benefit in choosing multiple\n    #Similar to the optimiser, these hyperparameters can be changed\nlr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.1)\n#lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max = 1)\n#lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience = 2, verbose = True)\n\n#An epoch is one full pass through the whole dataset by your model.\n    #Increasing epochs will increase accuracy, but at some point will lead to overfitting.\n    #There is a balance between too many and too few epochs which can be visualised when comparing the validation loss.\n    #More epochs will take longer and more importantaly use precious GPU allocation.\nnum_epochs = 5","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"loss_hist = Averager()\nitr = 1\n\nfor epoch in range(num_epochs):\n    loss_hist.reset()\n\n    #For each image in train_data perform the following actions...\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        #We must zero out the gradients after each image otherwise the gradients will accumulate\n        optimizer.zero_grad()\n        losses.backward()\n        optimizer.step()\n\n        #For every 50 iterations print a progress message\n        if itr % 50 == 0:\n            print(f\"Iteration #{itr} loss: {loss_value}\")\n\n        itr += 1\n\n    # update the learning rate if a learning rate annealer exists\n    if lr_scheduler is not None:\n        lr_scheduler.step(loss_value)\n\n    print(f\"Epoch #{epoch} loss: {loss_hist.value}\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Replace the values of images, targets, and image_ids from containing the training data to now contain only those images in the validation set\nimages, targets, image_ids = next(iter(valid_data_loader))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images = list(img.to(device) for img in images)\ntargets = [{k: v.to(device) for k, v in t.items()} for t in targets]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"boxes = targets[1]['boxes'].cpu().numpy().astype(np.int32)\nsample = images[1].permute(1,2,0).cpu().numpy()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.eval()\ncpu_device = torch.device(\"cpu\")\n\noutputs = model(images)\noutputs = [{k: v.to(cpu_device) for k, v in t.items()} for t in outputs]","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), 3)\n    \nax.set_axis_off()\nax.imshow(sample)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Saved the model, including its weights to a new file.\n    #This allows us to transfer the model to others without the need for them to also use GPU time to attain the weights\ntorch.save(model.state_dict(), 'fasterrcnn_resnet50_fpn.pth')","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}