{"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 os\nimport gc\nimport cv2\nimport copy\nimport time\nimport random\nimport string\nimport joblib\nimport tifffile\nimport numpy as np \nimport pandas as pd \nimport torch\nfrom torch import nn\nimport seaborn as sns\nfrom torchvision import models\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import Dataset, DataLoader\nfrom sklearn.model_selection import train_test_split\nfrom tqdm.notebook import tqdm\nfrom torch.optim import lr_scheduler\nimport warnings\nwarnings.filterwarnings(\"ignore\")\ngc.enable()","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-08-14T13:01:29.619297Z","iopub.execute_input":"2022-08-14T13:01:29.620204Z","iopub.status.idle":"2022-08-14T13:01:33.146748Z","shell.execute_reply.started":"2022-08-14T13:01:29.620095Z","shell.execute_reply":"2022-08-14T13:01:33.145603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"debug = False\ngenerate_new = True\ntest_df = pd.read_csv(\"../input/mayo-clinic-strip-ai/test.csv\")\ndirs = [\"../input/mayo-clinic-strip-ai/train/\", \"../input/mayo-clinic-strip-ai/test/\"]\ntest_df","metadata":{"execution":{"iopub.status.busy":"2022-08-14T13:01:33.149288Z","iopub.execute_input":"2022-08-14T13:01:33.150422Z","iopub.status.idle":"2022-08-14T13:01:33.188547Z","shell.execute_reply.started":"2022-08-14T13:01:33.150358Z","shell.execute_reply":"2022-08-14T13:01:33.187583Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    os.mkdir(\"../test/\")\nexcept:\n    pass\nfor i in tqdm(range(test_df.shape[0])):\n    img_id = test_df.iloc[i].image_id\n    try:\n        sz = os.path.getsize(dirs[1] + img_id + \".tif\")\n    except:\n        sz = 1000000000\n    if(sz > 8e8):\n        img = np.zeros((512,512,3), np.uint8)\n    else:\n        try:\n            img = cv2.resize(tifffile.imread(dirs[1] + img_id + \".tif\"), (512, 512))\n        except:\n            img = np.zeros((512,512,3), np.uint8)\n    cv2.imwrite(f\"../test/{img_id}.jpg\", img)\n    del img\n    gc.collect()","metadata":{"execution":{"iopub.status.busy":"2022-08-14T13:01:33.190002Z","iopub.execute_input":"2022-08-14T13:01:33.190474Z","iopub.status.idle":"2022-08-14T13:02:10.521775Z","shell.execute_reply.started":"2022-08-14T13:01:33.19044Z","shell.execute_reply":"2022-08-14T13:02:10.520703Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class ImgDataset(Dataset):\n    def __init__(self, df):\n        self.df = df \n        self.train = 'label' in df.columns\n    def __len__(self):\n        return len(self.df)\n    \n    def __getitem__(self, index):\n        if(generate_new):\n            paths = [\"../test/\", \"../train/\"]\n        else:\n            paths = [\"../input/jpg-images-strip-ai/test/\", \"../input/jpg-images-strip-ai/train/\"]\n        try:\n            image = cv2.imread(paths[self.train] + self.df.iloc[index].image_id + \".jpg\")\n        except:\n            image = np.zeros((512,512,3), np.uint8)\n        label = 0\n        try:\n            if len(image.shape) == 5:\n                image = image.squeeze().transpose(1, 2, 0)\n            image = cv2.resize(image, (512, 512)).transpose(2, 0, 1)\n        except:\n            image = np.zeros((3, 512, 512))\n        if(self.train):\n            label = {\"CE\" : 0, \"LAA\": 1}[self.df.iloc[index].label]\n        patient_id = self.df.iloc[index].patient_id\n        return image, label, patient_id","metadata":{"execution":{"iopub.status.busy":"2022-08-14T13:02:10.524379Z","iopub.execute_input":"2022-08-14T13:02:10.525317Z","iopub.status.idle":"2022-08-14T13:02:10.535293Z","shell.execute_reply.started":"2022-08-14T13:02:10.52528Z","shell.execute_reply":"2022-08-14T13:02:10.534318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def predict(model, dataloader):\n    model.cuda()\n    model.eval()\n    dataloader = dataloader\n    outputs = []\n    s = nn.Softmax(dim=1)\n    ids = []\n    for item in tqdm(dataloader, leave=False):\n        patient_id = item[2][0]\n        try:\n            images = item[0].cuda().float()\n            ids.append(patient_id)\n            output = model(images)\n            outputs.append(s(output.cpu()[:,:2])[0].detach().numpy())\n        except:\n            ids.append(patient_id)\n            outputs.append(s(torch.tensor([[1, 1]]).float())[0].detach().numpy())\n    return np.array(outputs), ids","metadata":{"execution":{"iopub.status.busy":"2022-08-14T13:02:10.536682Z","iopub.execute_input":"2022-08-14T13:02:10.537213Z","iopub.status.idle":"2022-08-14T13:02:10.549895Z","shell.execute_reply.started":"2022-08-14T13:02:10.53718Z","shell.execute_reply":"2022-08-14T13:02:10.548781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#model = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_efficientnet_b4', pretrained=True)\nmodel = torch.jit.load('../input/cnnstripai/model.pth')\nbatch_size = 1\ntest_loader = DataLoader(\n    ImgDataset(test_df), \n    batch_size=batch_size, \n    shuffle=False, \n    num_workers=1\n)","metadata":{"execution":{"iopub.status.busy":"2022-08-14T13:02:10.551415Z","iopub.execute_input":"2022-08-14T13:02:10.551793Z","iopub.status.idle":"2022-08-14T13:02:11.793961Z","shell.execute_reply.started":"2022-08-14T13:02:10.551759Z","shell.execute_reply":"2022-08-14T13:02:11.792952Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"anss, ids = predict(model, test_loader)","metadata":{"execution":{"iopub.status.busy":"2022-08-14T13:02:11.79537Z","iopub.execute_input":"2022-08-14T13:02:11.795739Z","iopub.status.idle":"2022-08-14T13:02:21.911804Z","shell.execute_reply.started":"2022-08-14T13:02:11.795706Z","shell.execute_reply":"2022-08-14T13:02:21.910591Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"prob = pd.DataFrame({\"CE\" : anss[:,0], \"LAA\" : anss[:,1], \"id\" : ids}).groupby(\"id\").mean()","metadata":{"execution":{"iopub.status.busy":"2022-08-14T13:02:21.913618Z","iopub.execute_input":"2022-08-14T13:02:21.914803Z","iopub.status.idle":"2022-08-14T13:02:21.930366Z","shell.execute_reply.started":"2022-08-14T13:02:21.914761Z","shell.execute_reply":"2022-08-14T13:02:21.929157Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.read_csv(\"../input/mayo-clinic-strip-ai/sample_submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2022-08-14T13:02:21.93168Z","iopub.execute_input":"2022-08-14T13:02:21.932694Z","iopub.status.idle":"2022-08-14T13:02:21.952434Z","shell.execute_reply.started":"2022-08-14T13:02:21.932659Z","shell.execute_reply":"2022-08-14T13:02:21.951583Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.CE = prob.CE.to_list()\nsubmission.LAA = prob.LAA.to_list()","metadata":{"execution":{"iopub.status.busy":"2022-08-14T13:02:21.955927Z","iopub.execute_input":"2022-08-14T13:02:21.956195Z","iopub.status.idle":"2022-08-14T13:02:21.961367Z","shell.execute_reply.started":"2022-08-14T13:02:21.956171Z","shell.execute_reply":"2022-08-14T13:02:21.960361Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission","metadata":{"execution":{"iopub.status.busy":"2022-08-14T13:02:21.963153Z","iopub.execute_input":"2022-08-14T13:02:21.964035Z","iopub.status.idle":"2022-08-14T13:02:21.97688Z","shell.execute_reply.started":"2022-08-14T13:02:21.963995Z","shell.execute_reply":"2022-08-14T13:02:21.975892Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.to_csv(\"submission.csv\", index = False)","metadata":{"execution":{"iopub.status.busy":"2022-08-14T13:02:21.97819Z","iopub.execute_input":"2022-08-14T13:02:21.979233Z","iopub.status.idle":"2022-08-14T13:02:21.988559Z","shell.execute_reply.started":"2022-08-14T13:02:21.9792Z","shell.execute_reply":"2022-08-14T13:02:21.987107Z"},"trusted":true},"execution_count":null,"outputs":[]}]}