{"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":"# 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\nYou can find the [inference notebook here](https://www.kaggle.com/pestipeti/pytorch-starter-fasterrcnn-inference)\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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","execution":{"iopub.status.busy":"2023-11-05T07:45:18.648099Z","iopub.execute_input":"2023-11-05T07:45:18.648475Z","iopub.status.idle":"2023-11-05T07:45:18.657210Z","shell.execute_reply.started":"2023-11-05T07:45:18.648431Z","shell.execute_reply":"2023-11-05T07:45:18.656292Z"},"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":"2023-11-05T07:45:18.659097Z","iopub.execute_input":"2023-11-05T07:45:18.659380Z","iopub.status.idle":"2023-11-05T07:45:18.854109Z","shell.execute_reply.started":"2023-11-05T07:45:18.659341Z","shell.execute_reply":"2023-11-05T07:45:18.853145Z"},"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(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)","metadata":{"execution":{"iopub.status.busy":"2023-11-05T07:45:18.855432Z","iopub.execute_input":"2023-11-05T07:45:18.855752Z","iopub.status.idle":"2023-11-05T07:45:20.650453Z","shell.execute_reply.started":"2023-11-05T07:45:18.855708Z","shell.execute_reply":"2023-11-05T07:45:20.649562Z"},"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":"2023-11-05T07:45:20.651788Z","iopub.execute_input":"2023-11-05T07:45:20.652137Z","iopub.status.idle":"2023-11-05T07:45:20.665373Z","shell.execute_reply.started":"2023-11-05T07:45:20.652086Z","shell.execute_reply":"2023-11-05T07:45:20.664592Z"},"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":"2023-11-05T07:45:20.669488Z","iopub.execute_input":"2023-11-05T07:45:20.669765Z","iopub.status.idle":"2023-11-05T07:45:20.710710Z","shell.execute_reply.started":"2023-11-05T07:45:20.669725Z","shell.execute_reply":"2023-11-05T07:45:20.710030Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid_df.shape, train_df.shape","metadata":{"execution":{"iopub.status.busy":"2023-11-05T07:45:20.712894Z","iopub.execute_input":"2023-11-05T07:45:20.713230Z","iopub.status.idle":"2023-11-05T07:45:20.718869Z","shell.execute_reply.started":"2023-11-05T07:45:20.713178Z","shell.execute_reply":"2023-11-05T07:45:20.717961Z"},"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":"2023-11-05T07:45:20.720503Z","iopub.execute_input":"2023-11-05T07:45:20.721004Z","iopub.status.idle":"2023-11-05T07:45:20.739836Z","shell.execute_reply.started":"2023-11-05T07:45:20.720897Z","shell.execute_reply":"2023-11-05T07:45:20.738735Z"},"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":"2023-11-05T07:45:20.741436Z","iopub.execute_input":"2023-11-05T07:45:20.741814Z","iopub.status.idle":"2023-11-05T07:45:20.749840Z","shell.execute_reply.started":"2023-11-05T07:45:20.741755Z","shell.execute_reply":"2023-11-05T07:45:20.749172Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Create the model","metadata":{}},{"cell_type":"code","source":"# load a model; pre-trained on COCO\nmodel = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=False, pretrained_backbone=False)\nmodel.load_state_dict(torch.load('/kaggle/input/fasterrcnn-resnet50-fpt/fasterrcnn_resnet50_fpn_coco-258fb6c6.pth'))\n# model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)","metadata":{"execution":{"iopub.status.busy":"2023-11-05T08:22:29.486010Z","iopub.execute_input":"2023-11-05T08:22:29.486379Z","iopub.status.idle":"2023-11-05T08:22:30.149262Z","shell.execute_reply.started":"2023-11-05T08:22:29.486339Z","shell.execute_reply":"2023-11-05T08:22:30.148351Z"},"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":"2023-11-05T07:45:21.386449Z","iopub.execute_input":"2023-11-05T07:45:21.386726Z","iopub.status.idle":"2023-11-05T07:45:21.392431Z","shell.execute_reply.started":"2023-11-05T07:45:21.386675Z","shell.execute_reply":"2023-11-05T07:45:21.391412Z"},"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\n","metadata":{"execution":{"iopub.status.busy":"2023-11-05T07:45:21.393798Z","iopub.execute_input":"2023-11-05T07:45:21.394201Z","iopub.status.idle":"2023-11-05T07:45:21.403011Z","shell.execute_reply.started":"2023-11-05T07:45:21.394146Z","shell.execute_reply":"2023-11-05T07:45:21.402250Z"},"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":"2023-11-05T07:45:21.404606Z","iopub.execute_input":"2023-11-05T07:45:21.404937Z","iopub.status.idle":"2023-11-05T07:45:21.424947Z","shell.execute_reply.started":"2023-11-05T07:45:21.404872Z","shell.execute_reply":"2023-11-05T07:45:21.424183Z"},"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":"2023-11-05T07:45:21.426175Z","iopub.execute_input":"2023-11-05T07:45:21.426575Z","iopub.status.idle":"2023-11-05T07:45:21.430677Z","shell.execute_reply.started":"2023-11-05T07:45:21.426507Z","shell.execute_reply":"2023-11-05T07:45:21.429859Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Sample","metadata":{}},{"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":"2023-11-05T07:45:21.432032Z","iopub.execute_input":"2023-11-05T07:45:21.432339Z","iopub.status.idle":"2023-11-05T07:45:24.408139Z","shell.execute_reply.started":"2023-11-05T07:45:21.432280Z","shell.execute_reply":"2023-11-05T07:45:24.406631Z"},"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":"2023-11-05T07:45:24.409915Z","iopub.execute_input":"2023-11-05T07:45:24.410306Z","iopub.status.idle":"2023-11-05T07:45:24.419981Z","shell.execute_reply.started":"2023-11-05T07:45:24.410249Z","shell.execute_reply":"2023-11-05T07:45:24.418905Z"},"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":"2023-11-05T07:45:24.421087Z","iopub.execute_input":"2023-11-05T07:45:24.421613Z","iopub.status.idle":"2023-11-05T07:45:24.814543Z","shell.execute_reply.started":"2023-11-05T07:45:24.421555Z","shell.execute_reply":"2023-11-05T07:45:24.813575Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train","metadata":{}},{"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":"2023-11-05T07:45:24.815831Z","iopub.execute_input":"2023-11-05T07:45:24.816171Z","iopub.status.idle":"2023-11-05T07:45:24.876345Z","shell.execute_reply.started":"2023-11-05T07:45:24.816122Z","shell.execute_reply":"2023-11-05T07:45:24.875374Z"},"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images, targets, image_ids = next(iter(valid_data_loader))","metadata":{"execution":{"iopub.status.busy":"2023-11-05T07:46:26.804947Z","iopub.status.idle":"2023-11-05T07:46:26.805853Z"},"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]\nprint(len(images))","metadata":{"execution":{"iopub.status.busy":"2023-11-05T09:46:26.161488Z","iopub.execute_input":"2023-11-05T09:46:26.161871Z","iopub.status.idle":"2023-11-05T09:46:26.176939Z","shell.execute_reply.started":"2023-11-05T09:46:26.161825Z","shell.execute_reply":"2023-11-05T09:46:26.175567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in range(1,len(images)):\n    boxes = targets[i]['boxes'].cpu().numpy().astype(np.int32)\n    sample = images[i].permute(1,2,0).cpu().numpy()\n    model.eval()\n    cpu_device = torch.device(\"cpu\")\n    outputs = model(images)\n    outputs = [{k: v.to(cpu_device) for k, v in t.items()} for t in outputs]\n    fig, ax = plt.subplots(1, 1, figsize=(16, 8))\n    for box in boxes:\n        cv2.rectangle(sample,\n                      (box[0], box[1]),\n                      (box[2], box[3]),\n                      (220, 0, 0), 3)\n    ax.set_axis_off()\n    ax.imshow(sample)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"torch.save(model.state_dict(), 'fasterrcnn_resnet50_fpn.pth')","metadata":{"execution":{"iopub.status.busy":"2023-11-05T07:46:26.816270Z","iopub.status.idle":"2023-11-05T07:46:26.817240Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Predict","metadata":{}}]}