{"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":"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","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","execution":{"iopub.status.busy":"2023-06-29T17:02:31.284629Z","iopub.execute_input":"2023-06-29T17:02:31.285526Z","iopub.status.idle":"2023-06-29T17:02:33.759030Z","shell.execute_reply.started":"2023-06-29T17:02:31.285137Z","shell.execute_reply":"2023-06-29T17:02:33.758064Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport random\nimport numpy as np\nimport torch\nfrom sklearn.model_selection import StratifiedKFold\n\n\n# call before train\nSEED = 42\ndef seed_everything(seed):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = True\n\n# dataset config\nDATA_DIR = '/kaggle/input/global-wheat-detection'\nTRAIN_ROOT_PATH = DATA_DIR + '/train'\n\n# train cache\nCACHE_DIR = './cache'\n\ndef 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    return \" \".join(pred_strings)\n","metadata":{"execution":{"iopub.status.busy":"2023-06-29T17:02:33.763559Z","iopub.execute_input":"2023-06-29T17:02:33.763865Z","iopub.status.idle":"2023-06-29T17:02:33.884479Z","shell.execute_reply.started":"2023-06-29T17:02:33.763817Z","shell.execute_reply":"2023-06-29T17:02:33.883563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"seed_everything(SEED)","metadata":{"execution":{"iopub.status.busy":"2023-06-29T17:02:33.886246Z","iopub.execute_input":"2023-06-29T17:02:33.886886Z","iopub.status.idle":"2023-06-29T17:02:33.893886Z","shell.execute_reply.started":"2023-06-29T17:02:33.886831Z","shell.execute_reply":"2023-06-29T17:02:33.892965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# prepare for dataset    \n# set fold for validation\nFOLD = 0\n# read dataset metadata\nmarking = pd.read_csv(DATA_DIR + '/train.csv')\n# convert string to int list\nbboxs = np.stack(marking['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=',')))\n# reformat the target bounding boxes for yolo format, F-RCNN format...\nfor i, column in enumerate(['x', 'y', 'w', 'h']):\n    marking[column] = bboxs[:, i]\nmarking.drop(columns=['bbox'], inplace=True)\nmarking['x_center'] = marking['x'] + marking['w']/2\nmarking['y_center'] = marking['y'] + marking['h']/2\n# single class in this dataset\nmarking['classes'] = 0\n\n# group data uniformly\nskf = StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED)\ndf_folds = marking[['image_id']].copy()\ndf_folds.loc[:, 'bbox_count'] = 1\ndf_folds = df_folds.groupby('image_id').count() # calculate the target frequency for each image\ndf_folds.loc[:, 'source'] = marking[['image_id', 'source']].groupby('image_id').min()['source'] # group by source\ndf_folds.loc[:, 'stratify_group'] = np.char.add(\n    df_folds['source'].values.astype(str),\n    df_folds['bbox_count'].apply(lambda x: f'_{x // 15}').values.astype(str)\n)\n# assign fold number\ndf_folds.loc[:, 'fold'] = 0\nfor fold_number, (train_index, val_index) in enumerate(skf.split(X=df_folds.index, y=df_folds['stratify_group'])):\n    df_folds.loc[df_folds.iloc[val_index].index, 'fold'] = fold_number\n","metadata":{"execution":{"iopub.status.busy":"2023-06-29T17:02:33.895822Z","iopub.execute_input":"2023-06-29T17:02:33.896564Z","iopub.status.idle":"2023-06-29T17:02:35.448448Z","shell.execute_reply.started":"2023-06-29T17:02:33.896199Z","shell.execute_reply":"2023-06-29T17:02:35.447498Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = df_folds[df_folds['fold'] != FOLD]\nvalid_df = df_folds[df_folds['fold'] == FOLD]\ntrain_df = marking[marking['image_id'].isin(train_df.index)]\nvalid_df = marking[marking['image_id'].isin(valid_df.index)]","metadata":{"execution":{"iopub.status.busy":"2023-06-29T17:02:35.451819Z","iopub.execute_input":"2023-06-29T17:02:35.452193Z","iopub.status.idle":"2023-06-29T17:02:35.494047Z","shell.execute_reply.started":"2023-06-29T17:02:35.452133Z","shell.execute_reply":"2023-06-29T17:02:35.493167Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df","metadata":{"execution":{"iopub.status.busy":"2023-06-29T17:02:35.495943Z","iopub.execute_input":"2023-06-29T17:02:35.496501Z","iopub.status.idle":"2023-06-29T17:02:35.526709Z","shell.execute_reply.started":"2023-06-29T17:02:35.496290Z","shell.execute_reply":"2023-06-29T17:02:35.525799Z"},"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        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            for i in range(10):\n                sample = self.transforms(**{\n                    'image': image,\n                    'bboxes': target['boxes'],\n                    'labels': labels\n                })\n                if len(sample['bboxes']) > 0:\n                    image = sample['image']\n                    target['boxes'] = torch.stack(tuple(map(torch.tensor, zip(*sample['bboxes'])))).permute(1, 0)\n                    break\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-06-29T17:02:35.528330Z","iopub.execute_input":"2023-06-29T17:02:35.528897Z","iopub.status.idle":"2023-06-29T17:02:35.550594Z","shell.execute_reply.started":"2023-06-29T17:02:35.528845Z","shell.execute_reply":"2023-06-29T17:02:35.549647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Albumentations\ndef get_train_transform():\n    return A.Compose([\n        ToTensorV2(p=1.0)\n    ], bbox_params={'format': 'pascal_voc', 'label_fields': ['labels']})\n\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-06-29T17:02:35.553856Z","iopub.execute_input":"2023-06-29T17:02:35.554292Z","iopub.status.idle":"2023-06-29T17:02:35.567376Z","shell.execute_reply.started":"2023-06-29T17:02:35.554209Z","shell.execute_reply":"2023-06-29T17:02:35.566393Z"},"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-06-29T17:02:35.568648Z","iopub.execute_input":"2023-06-29T17:02:35.569187Z","iopub.status.idle":"2023-06-29T17:02:39.042485Z","shell.execute_reply.started":"2023-06-29T17:02:35.569133Z","shell.execute_reply":"2023-06-29T17:02:39.041346Z"},"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-06-29T17:02:39.044260Z","iopub.execute_input":"2023-06-29T17:02:39.044807Z","iopub.status.idle":"2023-06-29T17:02:39.057314Z","shell.execute_reply.started":"2023-06-29T17:02:39.044601Z","shell.execute_reply":"2023-06-29T17:02:39.056203Z"},"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-06-29T17:02:39.058732Z","iopub.execute_input":"2023-06-29T17:02:39.059308Z","iopub.status.idle":"2023-06-29T17:02:39.067954Z","shell.execute_reply.started":"2023-06-29T17:02:39.059086Z","shell.execute_reply":"2023-06-29T17:02:39.066862Z"},"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, TRAIN_ROOT_PATH, get_train_transform())\nvalid_dataset = WheatDataset(valid_df, TRAIN_ROOT_PATH, 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-06-29T17:02:39.069773Z","iopub.execute_input":"2023-06-29T17:02:39.070628Z","iopub.status.idle":"2023-06-29T17:02:39.095637Z","shell.execute_reply.started":"2023-06-29T17:02:39.070167Z","shell.execute_reply":"2023-06-29T17:02:39.094798Z"},"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-06-29T17:02:39.098289Z","iopub.execute_input":"2023-06-29T17:02:39.098900Z","iopub.status.idle":"2023-06-29T17:02:39.125042Z","shell.execute_reply.started":"2023-06-29T17:02:39.098848Z","shell.execute_reply":"2023-06-29T17:02:39.124005Z"},"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 = 50","metadata":{"execution":{"iopub.status.busy":"2023-06-29T17:02:39.128786Z","iopub.execute_input":"2023-06-29T17:02:39.129290Z","iopub.status.idle":"2023-06-29T17:02:42.330239Z","shell.execute_reply.started":"2023-06-29T17:02:39.129040Z","shell.execute_reply":"2023-06-29T17:02:42.329219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss_hist = Averager()\nval_hist = Averager()\n\ntrain_his = pd.DataFrame(columns=['train_loss', 'val_loss'])\n\nbest_loss = 1e9\n\nfor epoch in range(num_epochs):\n    loss_hist.reset()\n    val_hist.reset()\n    for images, targets, image_ids in train_data_loader:\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    for images, targets, image_ids in valid_data_loader:\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        val_hist.send(loss_value)\n    \n    # update the learning rate\n    if lr_scheduler is not None:\n        lr_scheduler.step()\n        \n    if val_hist.value < best_loss:\n        best_loss = val_hist.value\n        torch.save(model.state_dict(), './best.pth')\n    \n    train_his = train_his.append(\n                {'epoch': epoch, 'train_loss': loss_hist.value, 'val_loss': val_hist.value}, ignore_index=True)\n    train_his.to_csv('train_his.csv')\n    print(f\"Epoch #{epoch} loss: {loss_hist.value}\")   ","metadata":{"execution":{"iopub.status.busy":"2023-06-29T17:10:17.866145Z","iopub.execute_input":"2023-06-29T17:10:17.866583Z","iopub.status.idle":"2023-06-29T17:23:45.222101Z","shell.execute_reply.started":"2023-06-29T17:10:17.866520Z","shell.execute_reply":"2023-06-29T17:23:45.221065Z"},"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-06-29T17:23:45.226136Z","iopub.execute_input":"2023-06-29T17:23:45.226494Z","iopub.status.idle":"2023-06-29T17:23:47.770363Z","shell.execute_reply.started":"2023-06-29T17:23:45.226433Z","shell.execute_reply":"2023-06-29T17:23:47.768974Z"},"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-06-29T17:23:47.772275Z","iopub.execute_input":"2023-06-29T17:23:47.772957Z","iopub.status.idle":"2023-06-29T17:23:47.874470Z","shell.execute_reply.started":"2023-06-29T17:23:47.772891Z","shell.execute_reply":"2023-06-29T17:23:47.873549Z"},"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-06-29T17:23:47.876307Z","iopub.execute_input":"2023-06-29T17:23:47.876696Z","iopub.status.idle":"2023-06-29T17:23:47.885546Z","shell.execute_reply.started":"2023-06-29T17:23:47.876643Z","shell.execute_reply":"2023-06-29T17:23:47.884361Z"},"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-06-29T17:23:47.888207Z","iopub.execute_input":"2023-06-29T17:23:47.889069Z","iopub.status.idle":"2023-06-29T17:23:48.279733Z","shell.execute_reply.started":"2023-06-29T17:23:47.888710Z","shell.execute_reply":"2023-06-29T17:23:48.278782Z"},"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-06-29T17:23:48.282346Z","iopub.execute_input":"2023-06-29T17:23:48.282921Z","iopub.status.idle":"2023-06-29T17:23:48.692642Z","shell.execute_reply.started":"2023-06-29T17:23:48.282866Z","shell.execute_reply":"2023-06-29T17:23:48.691680Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}