{"cells":[{"metadata":{},"cell_type":"markdown","source":"## Global Wheat with Pytorch\nThis notebook is made for basic understanding about the dataset and flow of the detection with pytorch.<br>\nThe reference notebook is [here.](https://www.kaggle.com/pestipeti/pytorch-starter-fasterrcnn-train)\n* Pytorch starter - FasterRCNN Train\n<br>\n\nThe goal of this competition [Global Wheat Detection](https://www.kaggle.com/c/global-wheat-detection/overview) is bounding box prediction around each wheat head in images that have them. <br>\nIf there are no wheat heads, there is no bounding boxes."},{"metadata":{},"cell_type":"markdown","source":"### **Files**\n* train.csv - the training data\n* sample_submission.csv - a sample submission file in the correct format\n* train.zip - training images\n* test.zip - test images"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport cv2\nimport os\nimport re\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nimport matplotlib.patches as patches\nimport seaborn as sns # plotting","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 1. Data Preprocessing\n### Load Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"path = '../input/global-wheat-detection'\ndir_train = os.path.join(path,'train')\ntrain_df=pd.read_csv(os.path.join(path,'train.csv'))\ntrain_df.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### **Columns**\n* image_id - the unique image ID\n* width, height - the width and height of the images\n* bbox - a bounding box, formatted as a Python-style list of [xmin, ymin, width, height]\n* etc.\n\nFrom the Data Explorer, the size of train images are same, 1024 x 1024.<br>\nTo make simple code, bounding box(bbox) is needed to be splited."},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(1)\nax.imshow(plt.imread(os.path.join(path,'train',(train_df['image_id'][3]+'.jpg'))))\nxy = [834.0,95.0]\nw = 74.0\nh = 160.0\nrect = patches.Rectangle(xy, w, h, linewidth=2, edgecolor='b', facecolor='none')\nax.add_patch(rect)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Split Bounding Boxes into X, Y, Width, Height Column"},{"metadata":{"trusted":true},"cell_type":"code","source":"#train_df['x'] = 0\n#train_df['y'] = 0\n#train_df['w'] = 0\n#train_df['h'] = 0\ntrain_df[['x','y','w','h']] = 0\ntrain_df[['x','y','w','h']]= np.stack(train_df['bbox'].apply(lambda x:np.fromstring(x[1:-1], sep=','))).astype(np.float)\n\ntrain_df.drop(columns=['bbox','source'], inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['class'] = \"wheat_head\"\ntrain_df.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Split train data into Train and Validation\nTo prevent same image going to train and validation dataset, the unique id value is used."},{"metadata":{"trusted":true},"cell_type":"code","source":"image_ids = train_df['image_id'].unique()\nprint(\"Total number of images = \",len(train_df['image_id']))\nprint(\"Number of Unique images = \",len(image_ids))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"split_len = round(len(image_ids)*0.8)\n\ntrain_ids = image_ids[:split_len]\nvalid_ids = image_ids[split_len:]\n\ntrain = train_df[train_df['image_id'].isin(train_ids)]\nvalid = train_df[train_df['image_id'].isin(valid_ids)]\n\nvalid.shape, train.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 2. Data EDA\n* Reference Notebook [Global Wheat Detection: Starter EDA](https://www.kaggle.com/kaushal2896/global-wheat-detection-starter-eda)"},{"metadata":{},"cell_type":"markdown","source":"### Number of images"},{"metadata":{"trusted":true},"cell_type":"code","source":"print(f'Minumum number of wheat heads: {max(train_df[\"image_id\"].value_counts())}')\nprint(f'Minimum number of wheat heads: {len(train_df)/train_df[\"image_id\"].nunique()}')\n\nprint(\"Total number of images = \",len(train_df['image_id']))\nprint(f'Number of Unique images: {len(image_ids)}')\nprint(f'Total number of images: {len(os.listdir(os.path.join(path, \"train\")))}')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"So there are 3422 images in traing directory and 3373 images are annotated, that means there are 49 images which do not have any wheat heads in it (without annotation)"},{"metadata":{},"cell_type":"markdown","source":"### Distribution of number of bbox"},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.displot(train_df['image_id'].value_counts(), kde=False)\nplt.xlabel('# of wheat heads')\nplt.ylabel('# of images')\nplt.title('# of wheat heads vs. # of images')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 3. Build Dataset\n\n### Options\n1. Add new dataset\n2. More augmentation\n3. MixUp\n4. Patch"},{"metadata":{"trusted":true},"cell_type":"code","source":"import 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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class WheatDataset(Dataset):\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        \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        # convert imreaded image BGR to RGB\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]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<code>iscrowd</code> means the condition of labeling, whether many objects with tiny size are treated as a grouping box or not. In image labeling, object could be hided or enclosed."},{"metadata":{},"cell_type":"markdown","source":"### Albumentations - fast image augmentation libarary<br>\n\n<code>Albumentations</code> is an image augmentation library. It can substitute <code>torchvision.transforms</code>. Albumentation is much faster and easily replace. "},{"metadata":{"trusted":true},"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']})","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Load Pretrained model on COCO"},{"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":"model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(model.roi_heads.box_predictor.cls_score.in_features)\nprint(model.roi_heads.box_predictor.cls_score)\nprint(model.roi_heads.box_predictor)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_classes = 2 # wheat or not(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 model's head with a new one\nmodel.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(model.roi_heads.box_predictor.cls_score.in_features)\nprint(model.roi_heads.box_predictor.cls_score)\nprint(model.roi_heads.box_predictor)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<code>out_features</code> becomes 2 which is as same as our target."},{"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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Python decorator <code>@property</code> make more direct expression than <code>get</code> and <code>set</code> method."},{"metadata":{"trusted":true},"cell_type":"code","source":"def collate_fn(batch):\n    return tuple(zip(*batch))\n\ntrain_dataset = WheatDataset(train, dir_train, get_train_transform())\nvalid_dataset = WheatDataset(valid, dir_train, get_valid_transform())\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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"If you have any gpu with cuda, make the profram running on GPU, otherwise running on CPU."},{"metadata":{"trusted":true},"cell_type":"code","source":"device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Check the loaded image"},{"metadata":{"trusted":true},"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]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"boxes = targets[2]['boxes'].cpu().numpy().astype(np.float32)\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)\nax.set_axis_off()\nax.imshow(sample)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 4. Train model"},{"metadata":{},"cell_type":"markdown","source":"### Set parameter\n\n* optimizer: SGD<br>\n* learning rate: 0.005<br>\n* momentum: 0.9<br>\n* weight decay: 0.0005<br>\n* learning scheduler: No<br>\n* number of epochs: 2"},{"metadata":{"trusted":true},"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)\nlr_scheduler = None\n\nnum_epochs = 2","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 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        # Set loss function\n        loss_dict = model(images, targets)\n        \n        losses = sum(loss for loss in loss_dict.values())\n        loss_value = losses.item()\n        loss_hist.send(loss_value)\n        \n        # Set parameters\n        optimizer.zero_grad()\n        losses.backward()\n        optimizer.step()\n        \n        # Display option\n        if itr % 50 == 0:\n            print(f\"Iteration #{itr} loss: {loss_value}\")\n        \n        itr += 1\n        \n    # Learning rate scheduler\n    if lr_scheduler is not None:\n        lr_scheduler.step()\n    \n    print(f\"Epoch #{epoch} loss: {loss_hist.value}\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images, 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]\n\nboxes = 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":"torch.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}