{"cells":[{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","collapsed":true,"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":false},"cell_type":"markdown","source":"# PyTorch starter - FasterRCNN Inference"},{"metadata":{},"cell_type":"markdown","source":"```\n********************************************************************************************\n         __           _                                _       _                 _    \n        / _|         | |                              | |     | |               | |   \n       | |_ ___  _ __| | ___ __ ___  _   _ _ __   ___ | |_ ___| |__   ___   ___ | | __\n       |  _/ _ \\| '__| |/ / '_ ` _ \\| | | | '_ \\ / _ \\| __/ _ \\ '_ \\ / _ \\ / _ \\| |/ /\n       | || (_) | |  |   <| | | | | | |_| | | | | (_) | ||  __/ |_) | (_) | (_) |   < \n       |_| \\___/|_|  |_|\\_\\_| |_| |_|\\__, |_| |_|\\___/ \\__\\___|_.__/ \\___/ \\___/|_|\\_\\\n                                      __/ |                                           \n                                     |___/                                    \n********************************************************************************************\n                    If you'd like to publish a forked version of this notebook,\n                            please do not remove this notice.\n--------------------------------------------------------------------------------------------\n                                      Original Notebook\n--------------------------------------------------------------------------------------------\nTitle...............: VinBigData FasterRCNN Pytorch - Inference\nLink................: https://kaggle.com/pestipeti/vinbigdata-fasterrcnn-pytorch-inference\nAuthor..............: Peter (https://kaggle.com/pestipeti)\nVersion.............: 8\n\n\n--------------------------------------------------------------------------------------------\n                                          Fork #1                   \n--------------------------------------------------------------------------------------------\nTitle...............: Chest X-ray Abnormalities Detection(Submission)\n```"},{"metadata":{},"cell_type":"markdown","source":"## Link to the Training Model Notebook\n\n\nYou can find the [train notebook here](https://www.kaggle.com/basu369victor/chest-x-ray-abnormalities-detection)\n\n- FasterRCNN from torchvision\n- Uses Resnet50+FPN backbone\n- Normalization of the X-ray images\n- Visualization of Model performance over validation images"},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport cv2\nimport os\nimport re\nimport warnings\n\nfrom PIL import Image\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nfrom glob import glob\nfrom skimage import exposure\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\nwarnings.filterwarnings(\"ignore\")\n\nDIR_INPUT = '/kaggle/input/vinbigdata-chest-xray-abnormalities-detection'\nDIR_TRAIN = f'{DIR_INPUT}/train'\nDIR_TEST = f'{DIR_INPUT}/test'\nDIR_WEIGHTS = '../input/chest-x-ray-abnormalities-detection'\n\nWEIGHTS_FILE = f'{DIR_WEIGHTS}/model_state.pth'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = pd.read_csv(f'{DIR_INPUT}/sample_submission.csv')\ntest_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class VinBigTestDataset(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):\n        \n        image_id = self.image_ids[index]\n        image_id = self.image_ids[index]\n        records = self.df[self.df['image_id'] == image_id]\n        \n        dcm_data = pydicom.read_file(f'{self.image_dir}/{image_id}.dicom')\n        image = apply_voi_lut(dcm_data.pixel_array, dcm_data)\n        # depending on this value, X-ray may look inverted - fix that:\n        if dcm_data.PhotometricInterpretation == \"MONOCHROME1\":\n            image = np.amax(image) - image\n            \n        #intercept = dcm_data.RescaleIntercept if \"RescaleIntercept\" in dcm_data else 0.0\n        #slope = dcm_data.RescaleSlope if \"RescaleSlope\" in dcm_data else 1.0\n        \n        #if slope != 1:\n        #    image = slope * image.astype(np.float64)\n        #    image = image.astype(np.int16)\n            \n        #image += np.int16(intercept)\n        image = np.stack([image, image, image])\n        image = image - np.min(image)\n\n        image = image / image.max()\n        #image = image * 255.0\n        #image = image.astype('float32')\n        image = exposure.equalize_hist(image)\n        image = image.astype('float32')\n\n        image = image.transpose(1,2,0)\n       \n        if self.transforms:\n            sample = {\n                'image': image,\n            }\n            sample = self.transforms(**sample)\n            image = sample['image']\n\n        return image, image_id\n    \n    def __len__(self):\n        return self.image_ids.shape[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Albumentations\ndef get_test_transform():\n    return A.Compose([\n        ToTensorV2()\n    ])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# load a model; pre-trained on COCO\nmodel = torchvision.models.detection.fasterrcnn_resnet50_fpn(\n    pretrained=False,\n    pretrained_backbone=False,\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\nnum_classes = 15\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)\n\n# Load the trained weights\nmodel.load_state_dict(torch.load(WEIGHTS_FILE, map_location=device))\nmodel.eval()\n\nx = model.to(device)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def collate_fn(batch):\n    return tuple(zip(*batch))\n\ntest_dataset = VinBigTestDataset(test_df, DIR_TEST, get_test_transform())\n\ntest_data_loader = DataLoader(\n    test_dataset,\n    batch_size=6,\n    shuffle=False,\n    num_workers=4,\n    drop_last=False,\n    collate_fn=collate_fn\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def format_prediction_string(labels, boxes, scores):\n    pred_strings = []\n    for j in zip(labels, scores, boxes):\n        pred_strings.append(\"{0} {1:.4f} {2} {3} {4} {5}\".format(\n            j[0], j[1], j[2][0], j[2][1], j[2][2], j[2][3]))\n\n    return \" \".join(pred_strings)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"detection_threshold = 0.2\nresults = []\n\nwith torch.no_grad():\n\n    for images, image_ids in test_data_loader:\n\n        images = list(image.to(device) for image in images)\n        outputs = model(images)\n\n        for i, image in enumerate(images):\n\n            image_id = image_ids[i]\n\n            result = {\n                'image_id': image_id,\n                'PredictionString': '14 1.0 0 0 1 1'\n            }\n\n            boxes = outputs[i]['boxes'].data.cpu().numpy()\n            labels = outputs[i]['labels'].data.cpu().numpy()\n            scores = outputs[i]['scores'].data.cpu().numpy()\n\n            if len(boxes) > 0:\n\n                labels = labels - 1\n                labels[labels == -1] = 14\n\n                selected = scores >= detection_threshold\n\n                boxes = boxes[selected].astype(np.int32)\n                scores = scores[selected]\n                labels = labels[selected]\n\n                if len(boxes) > 0:\n                    result = {\n                        'image_id': image_id,\n                        'PredictionString': format_prediction_string(labels, boxes, scores)\n                    }\n\n\n            results.append(result)\n        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])\ntest_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.to_csv('submission.csv', index=False)","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}