{"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\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# DIR_INPUT = '/kaggle/input/abs-detection-train'\nDIR_TRAIN = '/kaggle/input/data-train'\nDIR_TEST = '/kaggle/input/data-test'","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","execution":{"iopub.status.busy":"2023-09-22T12:16:40.456374Z","iopub.execute_input":"2023-09-22T12:16:40.456868Z","iopub.status.idle":"2023-09-22T12:16:40.467811Z","shell.execute_reply.started":"2023-09-22T12:16:40.456795Z","shell.execute_reply":"2023-09-22T12:16:40.466603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.read_csv('/kaggle/input/skskssk/all_data_model-051-2023-09-20T14-07-17-435Z.csv')\ntrain_df.shape","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:16:40.469925Z","iopub.execute_input":"2023-09-22T12:16:40.470534Z","iopub.status.idle":"2023-09-22T12:16:40.497481Z","shell.execute_reply.started":"2023-09-22T12:16:40.470470Z","shell.execute_reply":"2023-09-22T12:16:40.496611Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['image_id'] = train_df.index\ntrain_df.head()","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:16:40.499149Z","iopub.execute_input":"2023-09-22T12:16:40.499560Z","iopub.status.idle":"2023-09-22T12:16:40.522180Z","shell.execute_reply.started":"2023-09-22T12:16:40.499498Z","shell.execute_reply":"2023-09-22T12:16:40.521421Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":" train_df['bb'] = train_df['Image Name'].astype(str) + ', ' + train_df['Image Width'].astype(str) + ', ' + train_df['Image Height'].astype(str) + ', ' + train_df['bbox'].astype(str)","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:16:40.525290Z","iopub.execute_input":"2023-09-22T12:16:40.525631Z","iopub.status.idle":"2023-09-22T12:16:40.537050Z","shell.execute_reply.started":"2023-09-22T12:16:40.525580Z","shell.execute_reply":"2023-09-22T12:16:40.535916Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:16:40.539508Z","iopub.execute_input":"2023-09-22T12:16:40.539813Z","iopub.status.idle":"2023-09-22T12:16:40.562328Z","shell.execute_reply.started":"2023-09-22T12:16:40.539765Z","shell.execute_reply":"2023-09-22T12:16:40.561459Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = train_df.reset_index(drop=True)","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:16:40.564286Z","iopub.execute_input":"2023-09-22T12:16:40.564872Z","iopub.status.idle":"2023-09-22T12:16:40.570275Z","shell.execute_reply.started":"2023-09-22T12:16:40.564820Z","shell.execute_reply":"2023-09-22T12:16:40.569359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = train_df.drop(['Image Name', 'Image Width', 'Image Height', 'bbox'], axis=1)","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:16:40.571684Z","iopub.execute_input":"2023-09-22T12:16:40.572224Z","iopub.status.idle":"2023-09-22T12:16:40.585081Z","shell.execute_reply.started":"2023-09-22T12:16:40.572172Z","shell.execute_reply":"2023-09-22T12:16:40.584029Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df[['Column1', 'width', 'height']] = pd.DataFrame(train_df['image_id'].tolist(), index=train_df.index)","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:16:40.586789Z","iopub.execute_input":"2023-09-22T12:16:40.587537Z","iopub.status.idle":"2023-09-22T12:16:40.600155Z","shell.execute_reply.started":"2023-09-22T12:16:40.587472Z","shell.execute_reply":"2023-09-22T12:16:40.598976Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = train_df.drop(['image_id'], axis=1)\ntrain_df = train_df.rename(columns={'bb': 'bbox'})\ntrain_df = train_df.rename(columns={'Column1': 'image_id'})\ntrain_df.head()","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:16:40.601950Z","iopub.execute_input":"2023-09-22T12:16:40.602613Z","iopub.status.idle":"2023-09-22T12:16:40.621804Z","shell.execute_reply.started":"2023-09-22T12:16:40.602276Z","shell.execute_reply":"2023-09-22T12:16:40.621035Z"},"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[['w', 'x', 'h', 'y']] = 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) - train_df['x'].astype(np.float)\ntrain_df['h'] = train_df['h'].astype(np.float) - train_df['y'].astype(np.float)","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:16:40.623180Z","iopub.execute_input":"2023-09-22T12:16:40.623568Z","iopub.status.idle":"2023-09-22T12:16:40.648296Z","shell.execute_reply.started":"2023-09-22T12:16:40.623512Z","shell.execute_reply":"2023-09-22T12:16:40.646388Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:16:40.649794Z","iopub.execute_input":"2023-09-22T12:16:40.650329Z","iopub.status.idle":"2023-09-22T12:16:40.674884Z","shell.execute_reply.started":"2023-09-22T12:16:40.650277Z","shell.execute_reply":"2023-09-22T12:16:40.673886Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_ids = train_df['image_id'].unique()\nvalid_ids = image_ids[-10:]\ntrain_ids = image_ids[:-10]","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:16:40.678477Z","iopub.execute_input":"2023-09-22T12:16:40.678861Z","iopub.status.idle":"2023-09-22T12:16:40.687321Z","shell.execute_reply.started":"2023-09-22T12:16:40.678789Z","shell.execute_reply":"2023-09-22T12:16:40.686361Z"},"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-09-22T12:16:40.692877Z","iopub.execute_input":"2023-09-22T12:16:40.693207Z","iopub.status.idle":"2023-09-22T12:16:40.703413Z","shell.execute_reply.started":"2023-09-22T12:16:40.693154Z","shell.execute_reply":"2023-09-22T12:16:40.701023Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid_df.head()","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:16:40.706094Z","iopub.execute_input":"2023-09-22T12:16:40.706826Z","iopub.status.idle":"2023-09-22T12:16:40.728659Z","shell.execute_reply.started":"2023-09-22T12:16:40.706750Z","shell.execute_reply":"2023-09-22T12:16:40.727333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid_df.shape, train_df.shape","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:16:40.730692Z","iopub.execute_input":"2023-09-22T12:16:40.731473Z","iopub.status.idle":"2023-09-22T12:16:40.741273Z","shell.execute_reply.started":"2023-09-22T12:16:40.731096Z","shell.execute_reply":"2023-09-22T12:16:40.739996Z"},"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#         cv2.resize(image, (1024, 1024))\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-09-22T12:16:40.743322Z","iopub.execute_input":"2023-09-22T12:16:40.744232Z","iopub.status.idle":"2023-09-22T12:16:40.768012Z","shell.execute_reply.started":"2023-09-22T12:16:40.744085Z","shell.execute_reply":"2023-09-22T12:16:40.766767Z"},"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-09-22T12:16:40.770360Z","iopub.execute_input":"2023-09-22T12:16:40.770770Z","iopub.status.idle":"2023-09-22T12:16:40.785965Z","shell.execute_reply.started":"2023-09-22T12:16:40.770708Z","shell.execute_reply":"2023-09-22T12:16:40.784695Z"},"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-09-22T12:16:40.788635Z","iopub.execute_input":"2023-09-22T12:16:40.789327Z","iopub.status.idle":"2023-09-22T12:16:41.429287Z","shell.execute_reply.started":"2023-09-22T12:16:40.789265Z","shell.execute_reply":"2023-09-22T12:16:41.428308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_classes = 2  # 1 class (ABS) + 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-09-22T12:16:41.439324Z","iopub.execute_input":"2023-09-22T12:16:41.440012Z","iopub.status.idle":"2023-09-22T12:16:41.447552Z","shell.execute_reply.started":"2023-09-22T12:16:41.439913Z","shell.execute_reply":"2023-09-22T12:16:41.446783Z"},"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-09-22T12:16:41.450008Z","iopub.execute_input":"2023-09-22T12:16:41.450488Z","iopub.status.idle":"2023-09-22T12:16:41.461461Z","shell.execute_reply.started":"2023-09-22T12:16:41.450396Z","shell.execute_reply":"2023-09-22T12:16:41.460574Z"},"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=4,\n    shuffle=False,\n    num_workers=2,\n    collate_fn=collate_fn\n)\n\nvalid_data_loader = DataLoader(\n    valid_dataset,\n    batch_size=2,\n    shuffle=False,\n    num_workers=2,\n    collate_fn=collate_fn\n)","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:16:41.462947Z","iopub.execute_input":"2023-09-22T12:16:41.463471Z","iopub.status.idle":"2023-09-22T12:16:41.475297Z","shell.execute_reply.started":"2023-09-22T12:16:41.463346Z","shell.execute_reply":"2023-09-22T12:16:41.474284Z"},"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-09-22T12:16:41.476889Z","iopub.execute_input":"2023-09-22T12:16:41.477534Z","iopub.status.idle":"2023-09-22T12:16:41.487259Z","shell.execute_reply.started":"2023-09-22T12:16:41.477237Z","shell.execute_reply":"2023-09-22T12:16:41.486390Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(train_data_loader)","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:16:41.490477Z","iopub.execute_input":"2023-09-22T12:16:41.490796Z","iopub.status.idle":"2023-09-22T12:16:41.499200Z","shell.execute_reply.started":"2023-09-22T12:16:41.490744Z","shell.execute_reply":"2023-09-22T12:16:41.498305Z"},"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-22T12:16:41.500648Z","iopub.execute_input":"2023-09-22T12:16:41.501292Z","iopub.status.idle":"2023-09-22T12:16:46.404176Z","shell.execute_reply.started":"2023-09-22T12:16:41.501236Z","shell.execute_reply":"2023-09-22T12:16:46.401017Z"},"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-22T12:16:46.407218Z","iopub.execute_input":"2023-09-22T12:16:46.407866Z","iopub.status.idle":"2023-09-22T12:16:46.540962Z","shell.execute_reply.started":"2023-09-22T12:16:46.407777Z","shell.execute_reply":"2023-09-22T12:16:46.539967Z"},"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.circle(sample, (box[0], box[1]), 15, (0,255,0), 10)\n#     cv2.circle(sample, (box[2], box[3]), 15, (0,0,255), 10)\n    cv2.rectangle(sample, (box[0], box[1]), (box[2], box[3]), (220, 0, 0), 10)\n#     cv2.rectangle(sample, (120, 120), (500, 500), (220, 0, 0), 10)\n    \nax.set_axis_off()\nax.imshow(sample)","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:16:46.542636Z","iopub.execute_input":"2023-09-22T12:16:46.543036Z","iopub.status.idle":"2023-09-22T12:16:47.936919Z","shell.execute_reply.started":"2023-09-22T12:16:46.542982Z","shell.execute_reply":"2023-09-22T12:16:47.936016Z"},"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-09-22T12:16:47.938289Z","iopub.execute_input":"2023-09-22T12:16:47.938925Z","iopub.status.idle":"2023-09-22T12:16:48.001198Z","shell.execute_reply.started":"2023-09-22T12:16:47.938872Z","shell.execute_reply":"2023-09-22T12:16:48.000254Z"},"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":{"execution":{"iopub.status.busy":"2023-09-22T12:16:48.002914Z","iopub.execute_input":"2023-09-22T12:16:48.003458Z","iopub.status.idle":"2023-09-22T12:18:02.878309Z","shell.execute_reply.started":"2023-09-22T12:16:48.003265Z","shell.execute_reply":"2023-09-22T12:18:02.877268Z"},"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-22T12:18:02.880625Z","iopub.execute_input":"2023-09-22T12:18:02.881056Z","iopub.status.idle":"2023-09-22T12:18:05.554998Z","shell.execute_reply.started":"2023-09-22T12:18:02.880981Z","shell.execute_reply":"2023-09-22T12:18:05.553361Z"},"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-22T12:18:05.556779Z","iopub.execute_input":"2023-09-22T12:18:05.557199Z","iopub.status.idle":"2023-09-22T12:18:05.928686Z","shell.execute_reply.started":"2023-09-22T12:18:05.557136Z","shell.execute_reply":"2023-09-22T12:18:05.927579Z"},"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-22T12:18:05.930154Z","iopub.execute_input":"2023-09-22T12:18:05.930589Z","iopub.status.idle":"2023-09-22T12:18:06.059919Z","shell.execute_reply.started":"2023-09-22T12:18:05.930528Z","shell.execute_reply":"2023-09-22T12:18:06.059000Z"},"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-22T12:18:06.062586Z","iopub.execute_input":"2023-09-22T12:18:06.063223Z","iopub.status.idle":"2023-09-22T12:18:06.379897Z","shell.execute_reply.started":"2023-09-22T12:18:06.063161Z","shell.execute_reply":"2023-09-22T12:18:06.378073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(outputs)","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:24:38.116697Z","iopub.execute_input":"2023-09-22T12:24:38.117101Z","iopub.status.idle":"2023-09-22T12:24:38.152438Z","shell.execute_reply.started":"2023-09-22T12:24:38.117039Z","shell.execute_reply":"2023-09-22T12:24:38.151353Z"},"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), 10)\n    \nax.set_axis_off()\nax.imshow(sample)","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:18:06.381700Z","iopub.execute_input":"2023-09-22T12:18:06.382244Z","iopub.status.idle":"2023-09-22T12:18:07.781763Z","shell.execute_reply.started":"2023-09-22T12:18:06.382188Z","shell.execute_reply":"2023-09-22T12:18:07.780640Z"},"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-09-22T12:18:07.783678Z","iopub.execute_input":"2023-09-22T12:18:07.784331Z","iopub.status.idle":"2023-09-22T12:18:07.994315Z","shell.execute_reply.started":"2023-09-22T12:18:07.784270Z","shell.execute_reply":"2023-09-22T12:18:07.993291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(loss_hist.value)","metadata":{"execution":{"iopub.status.busy":"2023-09-22T12:18:07.996031Z","iopub.execute_input":"2023-09-22T12:18:07.996619Z","iopub.status.idle":"2023-09-22T12:18:08.002287Z","shell.execute_reply.started":"2023-09-22T12:18:07.996389Z","shell.execute_reply":"2023-09-22T12:18:08.001277Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.patches as patches\nimport time\nimage_path = '/kaggle/input/test-220923/10.jpg'\nimage = Image.open(image_path).convert(\"RGB\")\ntransform = T.Compose([T.ToTensor()])\nimage = transform(image)\nimage = image.to(device)\n\n# Make predictions using the loaded model\nstart_time = time.time()\nwith torch.no_grad():\n    prediction = model([image])\nend_time = time.time()\n\nprediction_time = end_time - start_time\nprint(f\"Prediction time: {prediction_time:.4f} seconds\")\n\n# Display the original image with bounding boxes\nimage = Image.open(image_path)\nplt.imshow(image)\n\nax = plt.gca()\n\nfor box, label, score in zip(prediction[0][\"boxes\"], prediction[0][\"labels\"], prediction[0][\"scores\"]):\n    box = box.tolist()\n    label = int(label)\n    score = score.item()\n    \n    confidence_threshold = 0.90\n    \n    if score >= confidence_threshold:\n        # Create a rectangle patch\n        rect = patches.Rectangle(\n            (box[0], box[1]),\n            box[2] - box[0],\n            box[3] - box[1],\n            linewidth=1,\n            edgecolor='r',\n            facecolor='none'\n        )\n\n        # Add the rectangle patch to the current axes\n        ax.add_patch(rect)\n\n        # Add label and score as text\n        plt.text(\n            box[0],\n            box[1],\n            f\"Class: {label}, Score: {score:.2f}\",\n            bbox=dict(fill=False, edgecolor='r', linewidth=2)\n        )\n\nplt.axis('off')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-22T13:33:19.689959Z","iopub.execute_input":"2023-09-22T13:33:19.690381Z","iopub.status.idle":"2023-09-22T13:33:21.419048Z","shell.execute_reply.started":"2023-09-22T13:33:19.690318Z","shell.execute_reply":"2023-09-22T13:33:21.418058Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}