{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# FasterRCNN (KR)","metadata":{}},{"cell_type":"markdown","source":"해당 문서는 Pytorch Starter - FasterRCNN Train (Peter) 의 Notebook을 공부하며 한국어 주석을 달아놓은 버전이다. <br>\n**Global Wheat Detection Competition**을 기반으로 하며, 원본 Notebook은 https://www.kaggle.com/code/pestipeti/pytorch-starter-fasterrcnn-train 에서 볼 수 있다. <br>","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\n# 이미지 augmentation 라이브러리\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\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-09-08T02:55:56.459104Z","iopub.execute_input":"2023-09-08T02:55:56.459510Z","iopub.status.idle":"2023-09-08T02:55:56.471094Z","shell.execute_reply.started":"2023-09-08T02:55:56.459443Z","shell.execute_reply":"2023-09-08T02:55:56.470061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 데이터 불러오기\ntrain_df = pd.read_csv(f'{DIR_INPUT}/train.csv')\ntrain_df.shape","metadata":{"execution":{"iopub.status.busy":"2023-09-08T02:55:56.473932Z","iopub.execute_input":"2023-09-08T02:55:56.474501Z","iopub.status.idle":"2023-09-08T02:55:56.755720Z","shell.execute_reply.started":"2023-09-08T02:55:56.474447Z","shell.execute_reply":"2023-09-08T02:55:56.754757Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# bbox를 좀 더 보기 편하게 x, y, w, h 열을 추가하기\ntrain_df['x'] = -1\ntrain_df['y'] = -1\ntrain_df['w'] = -1\ntrain_df['h'] = -1\n\n# bbox에서 x, y, w, h 추출\ndef expand_bbox(x):\n    \"\"\"\n    [0-9]+: 숫자가 하나이상 \n    [.]?: 소수점에 사용될 .이 0 or 1번 나타나야 함\n    [0-9]*: 소수점 다음에 오는 숫자가 0번이상\n    \"\"\"\n    r = np.array(re.findall(\"([0-9]+[.]?[0-9]*)\", x))\n    \n    # 데이터 없으면 -1 할당\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)))\n\n# bbox 열 삭제\ntrain_df.drop(columns=['bbox'], inplace=True)\n\n# 데이터 타입\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-09-08T02:55:56.757389Z","iopub.execute_input":"2023-09-08T02:55:56.757967Z","iopub.status.idle":"2023-09-08T02:55:58.611899Z","shell.execute_reply.started":"2023-09-08T02:55:56.757913Z","shell.execute_reply":"2023-09-08T02:55:58.610853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 서로 다른 이미지 개수\nimage_ids = train_df['image_id'].unique()\n\n# 20퍼 validation으로 사용\nvalid_ids = image_ids[-665:]\ntrain_ids = image_ids[:-665]","metadata":{"execution":{"iopub.status.busy":"2023-09-08T02:55:58.613390Z","iopub.execute_input":"2023-09-08T02:55:58.613825Z","iopub.status.idle":"2023-09-08T02:55:58.630108Z","shell.execute_reply.started":"2023-09-08T02:55:58.613749Z","shell.execute_reply":"2023-09-08T02:55:58.628796Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 같은 이미지 데이터, bbox가 다른 데이터가 있음을 인지\nvalid_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-09-08T02:55:58.634388Z","iopub.execute_input":"2023-09-08T02:55:58.634741Z","iopub.status.idle":"2023-09-08T02:55:58.678182Z","shell.execute_reply.started":"2023-09-08T02:55:58.634690Z","shell.execute_reply":"2023-09-08T02:55:58.677417Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid_df.shape, train_df.shape\nprint(train_df)","metadata":{"execution":{"iopub.status.busy":"2023-09-08T02:55:58.682089Z","iopub.execute_input":"2023-09-08T02:55:58.682398Z","iopub.status.idle":"2023-09-08T02:55:58.696131Z","shell.execute_reply.started":"2023-09-08T02:55:58.682349Z","shell.execute_reply":"2023-09-08T02:55:58.695068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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    def __getitem__(self, index: int):\n        image_id = self.image_ids[index]\n        \n        # 해당 image_id에 대한 모든 데이터 저장\n        records = self.df[self.df['image_id'] == image_id]\n        \n        # 이미지 불러오기 및 스케일 조정, 입력 데이터 [0, 1]로 맞춰줌으로써 학습 안정화\n        # 입력 데이터의 스케일이 크면 gradient 업데이트가 불안정\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        # xmin, ymin, width, height\n        boxes = records[['x', 'y', 'w', 'h']].values\n        \n        # boxes = xmin, ymin, xmax, ymax 꼴로 바꾸기, albumentation pascalvoc format 사용\n        boxes[:, 2] = boxes[:, 0] + boxes[:, 2] # xmax\n        boxes[:, 3] = boxes[:, 1] + boxes[:, 3] # ymax\n        \n        area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])\n        area = torch.as_tensor(area, dtype=torch.float32)\n        \n        # wheat or background\n        labels = torch.ones((records.shape[0],), dtype=torch.int64)\n        \n        # 본 프로젝트에서는 필요없으나 annotation 맞춰주기\n        iscrowd = torch.zeros((records.shape[0],), dtype=torch.int64)\n        \n        target = {}\n        target['boxes'] = boxes\n        target['labels'] = labels\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            \n            \"\"\"\n            딕셔너리를 transform 함수 호출의 키워드 인수로 분해\n            ex) self.transforms(image = image, bboxes = target['boxes'], labels = labels)\n            \"\"\"\n            sample = self.transforms(**sample)\n            image = sample['image']\n            \n            # 텐서로 바꾸기\n            target['boxes'] = torch.tensor(sample['bboxes'])\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-09-08T02:55:58.697975Z","iopub.execute_input":"2023-09-08T02:55:58.698737Z","iopub.status.idle":"2023-09-08T02:55:58.722026Z","shell.execute_reply.started":"2023-09-08T02:55:58.698668Z","shell.execute_reply":"2023-09-08T02:55:58.720813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# object detection에서의 ablumentations library에 대해 자세히 알고 싶다면 아래 링크를 확인\n# https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/\n\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']})","metadata":{"execution":{"iopub.status.busy":"2023-09-08T02:55:58.723776Z","iopub.execute_input":"2023-09-08T02:55:58.724467Z","iopub.status.idle":"2023-09-08T02:55:58.736092Z","shell.execute_reply.started":"2023-09-08T02:55:58.724183Z","shell.execute_reply":"2023-09-08T02:55:58.735214Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Create the model","metadata":{}},{"cell_type":"code","source":"# 모델 로드하기/ pretrained on COCO\nmodel = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)","metadata":{"execution":{"iopub.status.busy":"2023-09-08T02:55:58.739714Z","iopub.execute_input":"2023-09-08T02:55:58.740342Z","iopub.status.idle":"2023-09-08T02:56:09.972835Z","shell.execute_reply.started":"2023-09-08T02:55:58.740279Z","shell.execute_reply":"2023-09-08T02:56:09.971553Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 미리 학습된 모델로부터 미세조정, 자세한 내용은 https://tutorials.pytorch.kr/intermediate/torchvision_tutorial.html 확인\n\nnum_classes = 2 # wheat와 background\n\n# classifier에 들어갈 input feature 개수\nin_features = model.roi_heads.box_predictor.cls_score.in_features\n\n# pretrained head를 새로운 것으로 교체\nmodel.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)","metadata":{"execution":{"iopub.status.busy":"2023-09-08T02:56:09.974581Z","iopub.execute_input":"2023-09-08T02:56:09.975169Z","iopub.status.idle":"2023-09-08T02:56:09.987504Z","shell.execute_reply.started":"2023-09-08T02:56:09.974953Z","shell.execute_reply":"2023-09-08T02:56:09.986637Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# loss 히스토리 관리 함수\nclass 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":"2023-09-08T02:56:09.989336Z","iopub.execute_input":"2023-09-08T02:56:09.989894Z","iopub.status.idle":"2023-09-08T02:56:09.997806Z","shell.execute_reply.started":"2023-09-08T02:56:09.989696Z","shell.execute_reply":"2023-09-08T02:56:09.996867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 리스트 내의 데이터를 병렬처리하여 튜플로 묶기\ndef 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\ntrain_data_loader = DataLoader(\n    train_dataset,\n    batch_size=8,\n    shuffle=True,\n    num_workers=2,\n    collate_fn=collate_fn\n)\n\nvalid_data_loader = DataLoader(\n    valid_dataset,\n    batch_size=8,\n    shuffle=False,\n    num_workers=2,\n    collate_fn=collate_fn\n)","metadata":{"execution":{"iopub.status.busy":"2023-09-08T02:56:09.999058Z","iopub.execute_input":"2023-09-08T02:56:09.999612Z","iopub.status.idle":"2023-09-08T02:56:10.018795Z","shell.execute_reply.started":"2023-09-08T02:56:09.999561Z","shell.execute_reply":"2023-09-08T02:56:10.018018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\nprint(device)","metadata":{"execution":{"iopub.status.busy":"2023-09-08T02:56:10.020326Z","iopub.execute_input":"2023-09-08T02:56:10.020810Z","iopub.status.idle":"2023-09-08T02:56:10.051411Z","shell.execute_reply.started":"2023-09-08T02:56:10.020705Z","shell.execute_reply":"2023-09-08T02:56:10.050383Z"},"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-09-08T02:56:10.052912Z","iopub.execute_input":"2023-09-08T02:56:10.053534Z","iopub.status.idle":"2023-09-08T02:56:14.769406Z","shell.execute_reply.started":"2023-09-08T02:56:10.053477Z","shell.execute_reply":"2023-09-08T02:56:14.768382Z"},"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-09-08T02:56:14.771226Z","iopub.execute_input":"2023-09-08T02:56:14.771630Z","iopub.status.idle":"2023-09-08T02:56:14.791087Z","shell.execute_reply.started":"2023-09-08T02:56:14.771574Z","shell.execute_reply":"2023-09-08T02:56:14.790145Z"},"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-09-08T02:56:14.792590Z","iopub.execute_input":"2023-09-08T02:56:14.793133Z","iopub.status.idle":"2023-09-08T02:56:15.137958Z","shell.execute_reply.started":"2023-09-08T02:56:14.792931Z","shell.execute_reply":"2023-09-08T02:56:15.137041Z"},"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)\nlr_scheduler = None\n\nnum_epochs = 2","metadata":{"execution":{"iopub.status.busy":"2023-09-08T02:56:15.139064Z","iopub.execute_input":"2023-09-08T02:56:15.139391Z","iopub.status.idle":"2023-09-08T02:56:15.209545Z","shell.execute_reply.started":"2023-09-08T02:56:15.139349Z","shell.execute_reply":"2023-09-08T02:56:15.208745Z"},"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        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        # train mode(target 필수) -> loss_dict 반환\n        loss_dict = model(images, targets)\n        \n        # loss_classifier, loss_box_reg, loss_objectness, loss_rpn_box_reg 합치기\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    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-09-08T02:56:15.211176Z","iopub.execute_input":"2023-09-08T02:56:15.211729Z","iopub.status.idle":"2023-09-08T03:07:34.095177Z","shell.execute_reply.started":"2023-09-08T02:56:15.211532Z","shell.execute_reply":"2023-09-08T03:07:34.093012Z"},"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-09-08T03:07:34.097084Z","iopub.execute_input":"2023-09-08T03:07:34.097522Z","iopub.status.idle":"2023-09-08T03:07:35.124893Z","shell.execute_reply.started":"2023-09-08T03:07:34.097430Z","shell.execute_reply":"2023-09-08T03:07:35.123736Z"},"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-09-08T03:07:35.126816Z","iopub.execute_input":"2023-09-08T03:07:35.127227Z","iopub.status.idle":"2023-09-08T03:07:35.215778Z","shell.execute_reply.started":"2023-09-08T03:07:35.127171Z","shell.execute_reply":"2023-09-08T03:07:35.214913Z"},"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-09-08T03:07:35.218367Z","iopub.execute_input":"2023-09-08T03:07:35.218950Z","iopub.status.idle":"2023-09-08T03:07:35.227990Z","shell.execute_reply.started":"2023-09-08T03:07:35.218896Z","shell.execute_reply":"2023-09-08T03:07:35.227168Z"},"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-09-08T03:07:35.230455Z","iopub.execute_input":"2023-09-08T03:07:35.231063Z","iopub.status.idle":"2023-09-08T03:07:35.604295Z","shell.execute_reply.started":"2023-09-08T03:07:35.231011Z","shell.execute_reply":"2023-09-08T03:07:35.603352Z"},"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-09-08T03:07:35.606375Z","iopub.execute_input":"2023-09-08T03:07:35.606941Z","iopub.status.idle":"2023-09-08T03:07:35.963719Z","shell.execute_reply.started":"2023-09-08T03:07:35.606887Z","shell.execute_reply":"2023-09-08T03:07:35.962565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 모델 저장","metadata":{}},{"cell_type":"code","source":"# 모델 저장\ntorch.save(model.state_dict(), 'fasterrcnn_resnet50_fpn.pth')","metadata":{"execution":{"iopub.status.busy":"2023-09-08T03:07:35.965219Z","iopub.execute_input":"2023-09-08T03:07:35.965739Z","iopub.status.idle":"2023-09-08T03:07:36.193872Z","shell.execute_reply.started":"2023-09-08T03:07:35.965541Z","shell.execute_reply":"2023-09-08T03:07:36.192818Z"},"trusted":true},"execution_count":null,"outputs":[]}],"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"}}