{"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-06T07:47:17.859349Z","iopub.execute_input":"2023-11-06T07:47:17.859759Z","iopub.status.idle":"2023-11-06T07:47:17.869045Z","shell.execute_reply.started":"2023-11-06T07:47:17.859705Z","shell.execute_reply":"2023-11-06T07:47:17.867938Z"},"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-06T07:47:17.870897Z","iopub.execute_input":"2023-11-06T07:47:17.871313Z","iopub.status.idle":"2023-11-06T07:47:18.067111Z","shell.execute_reply.started":"2023-11-06T07:47:17.871257Z","shell.execute_reply":"2023-11-06T07:47:18.066284Z"},"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-06T07:47:18.068304Z","iopub.execute_input":"2023-11-06T07:47:18.068611Z","iopub.status.idle":"2023-11-06T07:47:19.869914Z","shell.execute_reply.started":"2023-11-06T07:47:18.068558Z","shell.execute_reply":"2023-11-06T07:47:19.869107Z"},"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-06T07:47:19.871545Z","iopub.execute_input":"2023-11-06T07:47:19.872116Z","iopub.status.idle":"2023-11-06T07:47:19.886487Z","shell.execute_reply.started":"2023-11-06T07:47:19.871918Z","shell.execute_reply":"2023-11-06T07:47:19.885530Z"},"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-06T07:47:19.889918Z","iopub.execute_input":"2023-11-06T07:47:19.890362Z","iopub.status.idle":"2023-11-06T07:47:19.931689Z","shell.execute_reply.started":"2023-11-06T07:47:19.890310Z","shell.execute_reply":"2023-11-06T07:47:19.930935Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid_df.shape, train_df.shape","metadata":{"execution":{"iopub.status.busy":"2023-11-06T07:47:19.934693Z","iopub.execute_input":"2023-11-06T07:47:19.935005Z","iopub.status.idle":"2023-11-06T07:47:19.940333Z","shell.execute_reply.started":"2023-11-06T07:47:19.934945Z","shell.execute_reply":"2023-11-06T07:47:19.939317Z"},"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-06T07:47:19.941610Z","iopub.execute_input":"2023-11-06T07:47:19.941994Z","iopub.status.idle":"2023-11-06T07:47:19.961120Z","shell.execute_reply.started":"2023-11-06T07:47:19.941835Z","shell.execute_reply":"2023-11-06T07:47:19.960186Z"},"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-06T07:47:19.962308Z","iopub.execute_input":"2023-11-06T07:47:19.962616Z","iopub.status.idle":"2023-11-06T07:47:19.976511Z","shell.execute_reply.started":"2023-11-06T07:47:19.962567Z","shell.execute_reply":"2023-11-06T07:47:19.975649Z"},"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=True)","metadata":{"execution":{"iopub.status.busy":"2023-11-06T07:47:19.978064Z","iopub.execute_input":"2023-11-06T07:47:19.978433Z","iopub.status.idle":"2023-11-06T07:47:20.626401Z","shell.execute_reply.started":"2023-11-06T07:47:19.978376Z","shell.execute_reply":"2023-11-06T07:47:20.625571Z"},"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-06T07:47:20.628132Z","iopub.execute_input":"2023-11-06T07:47:20.628568Z","iopub.status.idle":"2023-11-06T07:47:20.634916Z","shell.execute_reply.started":"2023-11-06T07:47:20.628502Z","shell.execute_reply":"2023-11-06T07:47:20.634078Z"},"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-06T07:47:20.636013Z","iopub.execute_input":"2023-11-06T07:47:20.636384Z","iopub.status.idle":"2023-11-06T07:47:20.645582Z","shell.execute_reply.started":"2023-11-06T07:47:20.636290Z","shell.execute_reply":"2023-11-06T07:47:20.644541Z"},"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-06T07:47:20.646888Z","iopub.execute_input":"2023-11-06T07:47:20.647287Z","iopub.status.idle":"2023-11-06T07:47:20.670320Z","shell.execute_reply.started":"2023-11-06T07:47:20.647241Z","shell.execute_reply":"2023-11-06T07:47:20.669578Z"},"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-06T07:47:20.671761Z","iopub.execute_input":"2023-11-06T07:47:20.672161Z","iopub.status.idle":"2023-11-06T07:47:20.677128Z","shell.execute_reply.started":"2023-11-06T07:47:20.672104Z","shell.execute_reply":"2023-11-06T07:47:20.676251Z"},"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-06T07:47:20.678661Z","iopub.execute_input":"2023-11-06T07:47:20.679085Z","iopub.status.idle":"2023-11-06T07:47:23.620416Z","shell.execute_reply.started":"2023-11-06T07:47:20.679028Z","shell.execute_reply":"2023-11-06T07:47:23.619301Z"},"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-06T07:47:23.622348Z","iopub.execute_input":"2023-11-06T07:47:23.622797Z","iopub.status.idle":"2023-11-06T07:47:23.634918Z","shell.execute_reply.started":"2023-11-06T07:47:23.622720Z","shell.execute_reply":"2023-11-06T07:47:23.634012Z"},"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-06T07:47:23.636423Z","iopub.execute_input":"2023-11-06T07:47:23.636946Z","iopub.status.idle":"2023-11-06T07:47:24.006255Z","shell.execute_reply.started":"2023-11-06T07:47:23.636742Z","shell.execute_reply":"2023-11-06T07:47:24.005308Z"},"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 = 5","metadata":{"execution":{"iopub.status.busy":"2023-11-06T07:47:24.007463Z","iopub.execute_input":"2023-11-06T07:47:24.007737Z","iopub.status.idle":"2023-11-06T07:47:24.072178Z","shell.execute_reply.started":"2023-11-06T07:47:24.007698Z","shell.execute_reply":"2023-11-06T07:47:24.071419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\ndef showplot(list,title,step):\n    x= range(0,len(list),step)\n    y = [list[i] for i in range(0,len(list),step)]\n    plt.plot(x, y, color='blue', label='Loss')\n    \n    plt.title(title)\n    plt.xlabel('epoch')\n    plt.ylabel('loss')\n    \n    # 显示图例\n    plt.legend()\n\n    # 显示图形\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-06T07:47:24.073281Z","iopub.execute_input":"2023-11-06T07:47:24.073545Z","iopub.status.idle":"2023-11-06T07:47:24.080953Z","shell.execute_reply.started":"2023-11-06T07:47:24.073507Z","shell.execute_reply":"2023-11-06T07:47:24.080149Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss_hist = Averager()\nitr = 1\nloss_list = []\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 % 10 == 0:\n            print(f\"Iteration #{itr} loss: {loss_value}\")\n        loss_list.append(loss_value)\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":"2023-11-06T07:47:24.082193Z","iopub.execute_input":"2023-11-06T07:47:24.082516Z","iopub.status.idle":"2023-11-06T08:39:08.627413Z","shell.execute_reply.started":"2023-11-06T07:47:24.082473Z","shell.execute_reply":"2023-11-06T08:39:08.626205Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"showplot(loss_list,'train loss',1)","metadata":{"execution":{"iopub.status.busy":"2023-11-06T08:39:08.629534Z","iopub.execute_input":"2023-11-06T08:39:08.630009Z","iopub.status.idle":"2023-11-06T08:39:08.827144Z","shell.execute_reply.started":"2023-11-06T08:39:08.629923Z","shell.execute_reply":"2023-11-06T08:39:08.826336Z"},"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-06T08:50:49.441478Z","iopub.execute_input":"2023-11-06T08:50:49.441793Z","iopub.status.idle":"2023-11-06T08:50:50.710245Z","shell.execute_reply.started":"2023-11-06T08:50:49.441741Z","shell.execute_reply":"2023-11-06T08:50:50.709124Z"},"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":"2023-11-06T08:50:50.713229Z","iopub.execute_input":"2023-11-06T08:50:50.713635Z","iopub.status.idle":"2023-11-06T08:50:50.782825Z","shell.execute_reply.started":"2023-11-06T08:50:50.713573Z","shell.execute_reply":"2023-11-06T08:50:50.782008Z"},"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":"2023-11-06T08:50:50.784380Z","iopub.execute_input":"2023-11-06T08:50:50.784762Z","iopub.status.idle":"2023-11-06T08:50:50.793666Z","shell.execute_reply.started":"2023-11-06T08:50:50.784702Z","shell.execute_reply":"2023-11-06T08:50:50.792816Z"},"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":"2023-11-06T08:50:50.795288Z","iopub.execute_input":"2023-11-06T08:50:50.795781Z","iopub.status.idle":"2023-11-06T08:50:51.474159Z","shell.execute_reply.started":"2023-11-06T08:50:50.795543Z","shell.execute_reply":"2023-11-06T08:50:51.473107Z"},"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-06T08:50:51.475531Z","iopub.execute_input":"2023-11-06T08:50:51.475826Z","iopub.status.idle":"2023-11-06T08:50:51.834305Z","shell.execute_reply.started":"2023-11-06T08:50:51.475784Z","shell.execute_reply":"2023-11-06T08:50:51.833262Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"torch.save(model.state_dict(), 'fasterrcnn_resnet50_fpn.pth')","metadata":{"execution":{"iopub.status.busy":"2023-11-06T08:50:51.835688Z","iopub.execute_input":"2023-11-06T08:50:51.836072Z","iopub.status.idle":"2023-11-06T08:50:52.029687Z","shell.execute_reply.started":"2023-11-06T08:50:51.835956Z","shell.execute_reply":"2023-11-06T08:50:52.028677Z"},"trusted":true},"execution_count":null,"outputs":[]}]}