{"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":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","papermill":{"duration":3.063995,"end_time":"2022-07-08T14:24:41.045696","exception":false,"start_time":"2022-07-08T14:24:37.981701","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-08-09T11:39:24.373678Z","iopub.execute_input":"2022-08-09T11:39:24.374394Z","iopub.status.idle":"2022-08-09T11:39:24.381336Z","shell.execute_reply.started":"2022-08-09T11:39:24.374358Z","shell.execute_reply":"2022-08-09T11:39:24.380344Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nsys.path.append('../input/timm-pytorch-image-models/pytorch-image-models-master')\nimport timm","metadata":{"execution":{"iopub.status.busy":"2022-08-09T11:41:27.460543Z","iopub.execute_input":"2022-08-09T11:41:27.461529Z","iopub.status.idle":"2022-08-09T11:41:33.322379Z","shell.execute_reply.started":"2022-08-09T11:41:27.461493Z","shell.execute_reply":"2022-08-09T11:41:33.321208Z"},"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":{"papermill":{"duration":0.02504,"end_time":"2022-07-08T14:24:41.073811","exception":false,"start_time":"2022-07-08T14:24:41.048771","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-08-09T11:39:25.109929Z","iopub.execute_input":"2022-08-09T11:39:25.112269Z","iopub.status.idle":"2022-08-09T11:39:25.126513Z","shell.execute_reply.started":"2022-08-09T11:39:25.112217Z","shell.execute_reply":"2022-08-09T11:39:25.125559Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMG_SIZE = 384\n","metadata":{"execution":{"iopub.status.busy":"2022-08-09T11:39:25.971485Z","iopub.execute_input":"2022-08-09T11:39:25.972196Z","iopub.status.idle":"2022-08-09T11:39:25.976997Z","shell.execute_reply.started":"2022-08-09T11:39:25.972161Z","shell.execute_reply":"2022-08-09T11:39:25.975683Z"},"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((IMG_SIZE,IMG_SIZE,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((IMG_SIZE,IMG_SIZE,3), np.uint8)\n    cv2.imwrite(f\"../test/{img_id}.jpg\", img)\n    del img\n    gc.collect()","metadata":{"papermill":{"duration":69.477711,"end_time":"2022-07-08T14:25:50.554416","exception":false,"start_time":"2022-07-08T14:24:41.076705","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-08-09T11:39:26.843636Z","iopub.execute_input":"2022-08-09T11:39:26.844267Z","iopub.status.idle":"2022-08-09T11:39:55.773135Z","shell.execute_reply.started":"2022-08-09T11:39:26.844233Z","shell.execute_reply":"2022-08-09T11:39:55.772097Z"},"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((IMG_SIZE,IMG_SIZE,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, (IMG_SIZE, IMG_SIZE)).transpose(2, 0, 1)\n        except:\n            image = np.zeros((3, IMG_SIZE, IMG_SIZE))\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":{"papermill":{"duration":null,"end_time":null,"exception":null,"start_time":null,"status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-08-09T11:39:55.774982Z","iopub.execute_input":"2022-08-09T11:39:55.776161Z","iopub.status.idle":"2022-08-09T11:39:55.78719Z","shell.execute_reply.started":"2022-08-09T11:39:55.776124Z","shell.execute_reply":"2022-08-09T11:39:55.786104Z"},"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":{"papermill":{"duration":null,"end_time":null,"exception":null,"start_time":null,"status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-08-09T11:39:55.788375Z","iopub.execute_input":"2022-08-09T11:39:55.789039Z","iopub.status.idle":"2022-08-09T11:39:55.799194Z","shell.execute_reply.started":"2022-08-09T11:39:55.789003Z","shell.execute_reply":"2022-08-09T11:39:55.798279Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#model = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_efficientnet_b4', pretrained=True)\nmodel = torch.load('../input/facebook-deit-torch-lightning-starter-train/Deit-best-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":{"papermill":{"duration":null,"end_time":null,"exception":null,"start_time":null,"status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-08-09T11:41:39.251119Z","iopub.execute_input":"2022-08-09T11:41:39.251497Z","iopub.status.idle":"2022-08-09T11:41:47.045876Z","shell.execute_reply.started":"2022-08-09T11:41:39.251466Z","shell.execute_reply":"2022-08-09T11:41:47.044903Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"anss, ids = predict(model, test_loader)","metadata":{"papermill":{"duration":null,"end_time":null,"exception":null,"start_time":null,"status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-08-09T11:41:51.398709Z","iopub.execute_input":"2022-08-09T11:41:51.399283Z","iopub.status.idle":"2022-08-09T11:41:57.678924Z","shell.execute_reply.started":"2022-08-09T11:41:51.39925Z","shell.execute_reply":"2022-08-09T11:41:57.67773Z"},"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-09T11:41:59.289715Z","iopub.execute_input":"2022-08-09T11:41:59.290807Z","iopub.status.idle":"2022-08-09T11:41:59.308459Z","shell.execute_reply.started":"2022-08-09T11:41:59.290769Z","shell.execute_reply":"2022-08-09T11:41:59.307296Z"},"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-09T11:42:04.55974Z","iopub.execute_input":"2022-08-09T11:42:04.560102Z","iopub.status.idle":"2022-08-09T11:42:04.570283Z","shell.execute_reply.started":"2022-08-09T11:42:04.560075Z","shell.execute_reply":"2022-08-09T11:42:04.569016Z"},"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-09T11:42:05.688586Z","iopub.execute_input":"2022-08-09T11:42:05.689487Z","iopub.status.idle":"2022-08-09T11:42:05.696059Z","shell.execute_reply.started":"2022-08-09T11:42:05.689451Z","shell.execute_reply":"2022-08-09T11:42:05.694826Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission","metadata":{"execution":{"iopub.status.busy":"2022-08-09T11:42:08.702522Z","iopub.execute_input":"2022-08-09T11:42:08.703205Z","iopub.status.idle":"2022-08-09T11:42:08.714649Z","shell.execute_reply.started":"2022-08-09T11:42:08.703169Z","shell.execute_reply":"2022-08-09T11:42:08.713557Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.to_csv(\"submission.csv\", index = False)","metadata":{"execution":{"iopub.status.busy":"2022-08-09T11:42:15.546285Z","iopub.execute_input":"2022-08-09T11:42:15.546666Z","iopub.status.idle":"2022-08-09T11:42:15.555761Z","shell.execute_reply.started":"2022-08-09T11:42:15.546616Z","shell.execute_reply":"2022-08-09T11:42:15.554343Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}