{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":19989,"databundleVersionId":1160143,"sourceType":"competition"}],"dockerImageVersionId":30733,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Pytorch - FasterRCNN Train\n\n- FasterRCNN from torchvision\n- Use Resnet50 backbone\n- Albumentation enabled (simple flip for now)\n","metadata":{}},{"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\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\nfrom torch.utils.data.sampler import SequentialSampler\n\nfrom matplotlib import pyplot as plt\n\nDIR_INPUT = '/kaggle/input/global-wheat-detection'\nDIR_TRAIN = f'{DIR_INPUT}/train'\nDIR_TEST = f'{DIR_INPUT}/test'","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:23.889348Z","iopub.execute_input":"2024-07-22T16:52:23.890080Z","iopub.status.idle":"2024-07-22T16:52:31.634012Z","shell.execute_reply.started":"2024-07-22T16:52:23.890043Z","shell.execute_reply":"2024-07-22T16:52:31.633202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.read_csv(f'{DIR_INPUT}/train.csv')\ntrain_df.shape","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:31.635445Z","iopub.execute_input":"2024-07-22T16:52:31.635846Z","iopub.status.idle":"2024-07-22T16:52:31.916989Z","shell.execute_reply.started":"2024-07-22T16:52:31.635821Z","shell.execute_reply":"2024-07-22T16:52:31.915572Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_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(float)\ntrain_df['y'] = train_df['y'].astype(float)\ntrain_df['w'] = train_df['w'].astype(float)\ntrain_df['h'] = train_df['h'].astype(float)","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:31.918069Z","iopub.execute_input":"2024-07-22T16:52:31.918386Z","iopub.status.idle":"2024-07-22T16:52:33.373482Z","shell.execute_reply.started":"2024-07-22T16:52:31.918362Z","shell.execute_reply":"2024-07-22T16:52:33.372663Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_ids = train_df['image_id'].unique()\nvalid_ids = image_ids[-665:]\ntrain_ids = image_ids[:-665]","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:33.375583Z","iopub.execute_input":"2024-07-22T16:52:33.375871Z","iopub.status.idle":"2024-07-22T16:52:33.393150Z","shell.execute_reply.started":"2024-07-22T16:52:33.375846Z","shell.execute_reply":"2024-07-22T16:52:33.392384Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid_df = train_df[train_df['image_id'].isin(valid_ids)]\ntrain_df = train_df[train_df['image_id'].isin(train_ids)]","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:33.394176Z","iopub.execute_input":"2024-07-22T16:52:33.394481Z","iopub.status.idle":"2024-07-22T16:52:33.434580Z","shell.execute_reply.started":"2024-07-22T16:52:33.394456Z","shell.execute_reply":"2024-07-22T16:52:33.433846Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid_df.shape, train_df.shape","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:33.435584Z","iopub.execute_input":"2024-07-22T16:52:33.435852Z","iopub.status.idle":"2024-07-22T16:52:33.441839Z","shell.execute_reply.started":"2024-07-22T16:52:33.435828Z","shell.execute_reply":"2024-07-22T16:52:33.440848Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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    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        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            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]","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:33.443224Z","iopub.execute_input":"2024-07-22T16:52:33.443640Z","iopub.status.idle":"2024-07-22T16:52:33.458437Z","shell.execute_reply.started":"2024-07-22T16:52:33.443608Z","shell.execute_reply":"2024-07-22T16:52:33.457519Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Albumentations\ndef get_train_transform():\n    return A.Compose([\n        A.Flip(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","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:33.459423Z","iopub.execute_input":"2024-07-22T16:52:33.460433Z","iopub.status.idle":"2024-07-22T16:52:33.471792Z","shell.execute_reply.started":"2024-07-22T16:52:33.460396Z","shell.execute_reply":"2024-07-22T16:52:33.471091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# load a model; pre-trained on COCO\nmodel = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:33.472921Z","iopub.execute_input":"2024-07-22T16:52:33.473220Z","iopub.status.idle":"2024-07-22T16:52:35.529828Z","shell.execute_reply.started":"2024-07-22T16:52:33.473189Z","shell.execute_reply":"2024-07-22T16:52:35.528815Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_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)","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:35.533147Z","iopub.execute_input":"2024-07-22T16:52:35.533465Z","iopub.status.idle":"2024-07-22T16:52:35.539131Z","shell.execute_reply.started":"2024-07-22T16:52:35.533439Z","shell.execute_reply":"2024-07-22T16:52:35.538180Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:35.540320Z","iopub.execute_input":"2024-07-22T16:52:35.540587Z","iopub.status.idle":"2024-07-22T16:52:35.549231Z","shell.execute_reply.started":"2024-07-22T16:52:35.540563Z","shell.execute_reply":"2024-07-22T16:52:35.548449Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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=16,\n    shuffle=False,\n    num_workers=4,\n    collate_fn=collate_fn\n)\n\nvalid_data_loader = DataLoader(\n    valid_dataset,\n    batch_size=8,\n    shuffle=False,\n    num_workers=4,\n    collate_fn=collate_fn\n)","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:35.550383Z","iopub.execute_input":"2024-07-22T16:52:35.550720Z","iopub.status.idle":"2024-07-22T16:52:35.577489Z","shell.execute_reply.started":"2024-07-22T16:52:35.550686Z","shell.execute_reply":"2024-07-22T16:52:35.576696Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:35.578565Z","iopub.execute_input":"2024-07-22T16:52:35.578884Z","iopub.status.idle":"2024-07-22T16:52:35.612530Z","shell.execute_reply.started":"2024-07-22T16:52:35.578852Z","shell.execute_reply":"2024-07-22T16:52:35.611654Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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]","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:35.613631Z","iopub.execute_input":"2024-07-22T16:52:35.613884Z","iopub.status.idle":"2024-07-22T16:52:38.379848Z","shell.execute_reply.started":"2024-07-22T16:52:35.613863Z","shell.execute_reply":"2024-07-22T16:52:38.378701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"boxes = targets[2]['boxes'].cpu().numpy().astype(np.int32)\nsample = images[2].permute(1,2,0).cpu().numpy()","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:38.381560Z","iopub.execute_input":"2024-07-22T16:52:38.381944Z","iopub.status.idle":"2024-07-22T16:52:38.400171Z","shell.execute_reply.started":"2024-07-22T16:52:38.381906Z","shell.execute_reply":"2024-07-22T16:52:38.399493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:38.401182Z","iopub.execute_input":"2024-07-22T16:52:38.401494Z","iopub.status.idle":"2024-07-22T16:52:39.119533Z","shell.execute_reply.started":"2024-07-22T16:52:38.401469Z","shell.execute_reply":"2024-07-22T16:52:39.118572Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.to(device)\nparams = [p for p in model.parameters() if p.requires_grad]\noptimizer = torch.optim.SGD(params, lr=0.005, momentum=0.9, weight_decay=0.0005)\n# lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.1)\nlr_scheduler = None\n\nnum_epochs = 2","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:39.120752Z","iopub.execute_input":"2024-07-22T16:52:39.121047Z","iopub.status.idle":"2024-07-22T16:52:39.189476Z","shell.execute_reply.started":"2024-07-22T16:52:39.121019Z","shell.execute_reply":"2024-07-22T16:52:39.188681Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss_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}\")   ","metadata":{"execution":{"iopub.status.busy":"2024-07-22T16:52:39.190579Z","iopub.execute_input":"2024-07-22T16:52:39.190876Z","iopub.status.idle":"2024-07-22T17:01:50.801663Z","shell.execute_reply.started":"2024-07-22T16:52:39.190851Z","shell.execute_reply":"2024-07-22T17:01:50.800445Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images, targets, image_ids = next(iter(valid_data_loader))","metadata":{"execution":{"iopub.status.busy":"2024-07-22T17:01:50.803185Z","iopub.execute_input":"2024-07-22T17:01:50.803536Z","iopub.status.idle":"2024-07-22T17:01:51.747145Z","shell.execute_reply.started":"2024-07-22T17:01:50.803501Z","shell.execute_reply":"2024-07-22T17:01:51.745877Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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]","metadata":{"execution":{"iopub.status.busy":"2024-07-22T17:01:51.748687Z","iopub.execute_input":"2024-07-22T17:01:51.749007Z","iopub.status.idle":"2024-07-22T17:01:51.801016Z","shell.execute_reply.started":"2024-07-22T17:01:51.748976Z","shell.execute_reply":"2024-07-22T17:01:51.800216Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"boxes = targets[1]['boxes'].cpu().numpy().astype(np.int32)\nsample = images[1].permute(1,2,0).cpu().numpy()","metadata":{"execution":{"iopub.status.busy":"2024-07-22T17:01:51.802555Z","iopub.execute_input":"2024-07-22T17:01:51.802921Z","iopub.status.idle":"2024-07-22T17:01:51.818336Z","shell.execute_reply.started":"2024-07-22T17:01:51.802886Z","shell.execute_reply":"2024-07-22T17:01:51.817216Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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]","metadata":{"execution":{"iopub.status.busy":"2024-07-22T17:01:51.821622Z","iopub.execute_input":"2024-07-22T17:01:51.821920Z","iopub.status.idle":"2024-07-22T17:01:52.224038Z","shell.execute_reply.started":"2024-07-22T17:01:51.821894Z","shell.execute_reply":"2024-07-22T17:01:52.223200Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"execution":{"iopub.status.busy":"2024-07-22T17:01:52.225206Z","iopub.execute_input":"2024-07-22T17:01:52.225513Z","iopub.status.idle":"2024-07-22T17:01:52.948202Z","shell.execute_reply.started":"2024-07-22T17:01:52.225486Z","shell.execute_reply":"2024-07-22T17:01:52.947305Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"torch.save(model.state_dict(), 'fasterrcnn_resnet50_fpn.pth')","metadata":{"execution":{"iopub.status.busy":"2024-07-22T17:01:52.949452Z","iopub.execute_input":"2024-07-22T17:01:52.949779Z","iopub.status.idle":"2024-07-22T17:01:53.231199Z","shell.execute_reply.started":"2024-07-22T17:01:52.949750Z","shell.execute_reply":"2024-07-22T17:01:53.230371Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}