{"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":"try:\n    import pylibjpeg\nexcept:\n    !mkdir -p /root/.cache/torch/hub/checkpoints/\n    !cp ../input/rsna-2022-whl/efficientnet_v2_s-dd5fe13b.pth  /root/.cache/torch/hub/checkpoints/\n\n    !pip install /kaggle/input/rsna-2022-whl/{pydicom-2.3.0-py3-none-any.whl,pylibjpeg-1.4.0-py3-none-any.whl,python_gdcm-3.0.15-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl}\n    !pip install /kaggle/input/rsna-2022-whl/{torch-1.12.1-cp37-cp37m-manylinux1_x86_64.whl,torchvision-0.13.1-cp37-cp37m-manylinux1_x86_64.whl}","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-10-27T17:36:05.392468Z","iopub.execute_input":"2022-10-27T17:36:05.393138Z","iopub.status.idle":"2022-10-27T17:38:26.719555Z","shell.execute_reply.started":"2022-10-27T17:36:05.393032Z","shell.execute_reply":"2022-10-27T17:38:26.718403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import gc\nimport glob\nimport os\nimport re\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport pydicom as dicom\nimport torch\nimport torchvision as tv\nfrom sklearn.model_selection import GroupKFold\nfrom torch.cuda.amp import GradScaler, autocast\nfrom torchvision.models.feature_extraction import create_feature_extractor\nfrom tqdm.notebook import tqdm\n\nimport wandb\n\npd.set_option('display.max_rows', 1000)\npd.set_option('display.max_columns', 1000)\nplt.rcParams['figure.figsize'] = (20, 5)\n\n\n# Effnet\nWEIGHTS = tv.models.efficientnet.EfficientNet_V2_S_Weights.DEFAULT\nRSNA_2022_PATH = '../input/rsna-2022-cervical-spine-fracture-detection'\nTRAIN_IMAGES_PATH = f'{RSNA_2022_PATH}/train_images'\nTEST_IMAGES_PATH = f'{RSNA_2022_PATH}/test_images'\nEFFNET_CHECKPOINTS_PATH = '../input/new-effv2-tph'\n\n# MODEL_NAMES = [f'effnetv2']\n\n# This notebook supports ensembles and single model predictions. Uncomment to switch to ensemble prediction:\nMODEL_NAMES = [f'effnetv2-f{i}' for i in range(4)]\n\n# Common\nFRAC_COLS = [f'C{i}_effnet_frac' for i in range(1, 8)]\nVERT_COLS = [f'C{i}_effnet_vert' for i in range(1, 8)]\n\ntry:\n    from kaggle_secrets import UserSecretsClient\n    IS_KAGGLE = True\nexcept:\n    IS_KAGGLE = False\n\n\n# Switch to offline for submission\nos.environ[\"WANDB_MODE\"] = \"offline\"\n\nif os.environ[\"WANDB_MODE\"] == \"online\":\n    if IS_KAGGLE:\n        os.environ['WANDB_API_KEY'] = UserSecretsClient().get_secret(\"WANDB_API_KEY\")\n\nif not IS_KAGGLE:\n    print('Running locally')\n    RSNA_2022_PATH = '/mnt/rsna2022'\n    TRAIN_IMAGES_PATH = '/mnt/rsna2022/train_images'\n    TEST_IMAGES_PATH = '/mnt/rsna2022/test_images'\n    METADATA_PATH = '/home/vslaykovsky/Downloads/'\n    EFFNET_CHECKPOINTS_PATH = 'frac_checkpoints'\n    os.environ['WANDB_API_KEY'] = 'yourkeyhere'\n\n\nDEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'\nif DEVICE == 'cuda':\n    BATCH_SIZE = 32\nelse:\n    BATCH_SIZE = 2","metadata":{"execution":{"iopub.status.busy":"2022-10-27T17:48:04.418275Z","iopub.execute_input":"2022-10-27T17:48:04.418789Z","iopub.status.idle":"2022-10-27T17:48:08.027694Z","shell.execute_reply.started":"2022-10-27T17:48:04.418736Z","shell.execute_reply":"2022-10-27T17:48:08.026655Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_df_test():\n    df_test = pd.read_csv(f'{RSNA_2022_PATH}/test.csv')\n\n    if df_test.iloc[0].row_id == '1.2.826.0.1.3680043.10197_C1':\n        # test_images and test.csv are inconsistent in the dev dataset, fixing labels for the dev run.\n        df_test = pd.DataFrame({\n            \"row_id\": ['1.2.826.0.1.3680043.22327_C1', '1.2.826.0.1.3680043.25399_C1', '1.2.826.0.1.3680043.5876_C1'],\n            \"StudyInstanceUID\": ['1.2.826.0.1.3680043.22327', '1.2.826.0.1.3680043.25399', '1.2.826.0.1.3680043.5876'],\n            \"prediction_type\": [\"C1\", \"C1\", \"patient_overall\"]}\n        )\n    return df_test\n\ndf_test = load_df_test()\ndf_test","metadata":{"execution":{"iopub.status.busy":"2022-10-27T17:48:08.030082Z","iopub.execute_input":"2022-10-27T17:48:08.031238Z","iopub.status.idle":"2022-10-27T17:48:08.080745Z","shell.execute_reply.started":"2022-10-27T17:48:08.031193Z","shell.execute_reply":"2022-10-27T17:48:08.079828Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_slices = glob.glob(f'{TEST_IMAGES_PATH}/*/*')\ntest_slices = [re.findall(f'{TEST_IMAGES_PATH}/(.*)/(.*).dcm', s)[0] for s in test_slices]\ndf_test_slices = pd.DataFrame(data=test_slices, columns=['StudyInstanceUID', 'Slice']).astype({'Slice': int}).sort_values(['StudyInstanceUID', 'Slice']).reset_index(drop=True)\ndf_test_slices","metadata":{"execution":{"iopub.status.busy":"2022-10-27T17:48:08.082009Z","iopub.execute_input":"2022-10-27T17:48:08.08234Z","iopub.status.idle":"2022-10-27T17:48:08.222412Z","shell.execute_reply.started":"2022-10-27T17:48:08.082306Z","shell.execute_reply":"2022-10-27T17:48:08.221288Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_dicom(path):\n    dcm = dicom.dcmread(path, force = True)\n    ds = dicom.read_file(path)\n\n    window_level = 400\n    window_width = 1800\n\n    try:\n        intercept = dcm[0x28,0x1052].value\n        slope = dcm[0x28,0x1053].value\n        bits = ds.BitsStored\n    except:\n        intercept = -1024\n        slope = 1\n\n    img_out = dcm.pixel_array\n\n    ## DICOM --> HU 정규화\n    HUnorm_image = slope*img_out + intercept\n\n    low = window_level - window_width // 2\n    high = window_level + window_width // 2\n            \n    windowed_image = (HUnorm_image-low) / (high-low)\n\n    windowed_image[windowed_image < 0.] = 0\n    windowed_image[windowed_image > 1.] = 1\n    windowed_image = (windowed_image - 0.5) * 2\n\n    data=(windowed_image * 255).astype(np.uint8)\n\n    return cv2.cvtColor(data, cv2.COLOR_GRAY2RGB), data\n\n\nim, meta = load_dicom(f'{TRAIN_IMAGES_PATH}/1.2.826.0.1.3680043.10001/1.dcm')\nplt.figure()\nplt.imshow(im)\nplt.title('regular image')\n\nim, meta = load_dicom(f'{TRAIN_IMAGES_PATH}/1.2.826.0.1.3680043.10014/1.dcm')\nplt.figure()\nplt.imshow(im)\nplt.title('jpeg')","metadata":{"execution":{"iopub.status.busy":"2022-10-27T17:48:08.224843Z","iopub.execute_input":"2022-10-27T17:48:08.225669Z","iopub.status.idle":"2022-10-27T17:48:08.942985Z","shell.execute_reply.started":"2022-10-27T17:48:08.225633Z","shell.execute_reply":"2022-10-27T17:48:08.942068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class EffnetDataSet(torch.utils.data.Dataset):    \n    def __init__(self, df, path, transforms=None):\n        super().__init__()\n        self.df = df\n        self.path = path\n        self.transforms = transforms\n        \n    def __getitem__(self, i):\n        path = os.path.join(self.path, self.df.iloc[i].StudyInstanceUID, f'{self.df.iloc[i].Slice}.dcm')        \n        \n        try:\n            img = load_dicom(path)[0]         \n            img = np.transpose(img, (2, 0, 1))  # Pytorch uses (batch, channel, height, width) order. Converting (height, width, channel) -> (channel, height, width)\n            if self.transforms is not None:\n                img = self.transforms(torch.as_tensor(img))\n        except Exception as ex:\n            print(ex)\n            return None\n        \n        if 'C1_fracture' in self.df:\n            frac_targets = torch.as_tensor(self.df.iloc[i][['C1_fracture', 'C2_fracture', 'C3_fracture', 'C4_fracture', 'C5_fracture', 'C6_fracture', 'C7_fracture']].astype('float32').values)\n            vert_targets = torch.as_tensor(self.df.iloc[i][['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7']].astype('float32').values)\n            frac_targets = frac_targets * vert_targets   # we only enable targets that are visible on the current slice\n            return img, frac_targets, vert_targets\n        return img        \n    \n    def __len__(self):\n        return len(self.df)","metadata":{"execution":{"iopub.status.busy":"2022-10-27T17:48:08.944376Z","iopub.execute_input":"2022-10-27T17:48:08.945327Z","iopub.status.idle":"2022-10-27T17:48:08.956943Z","shell.execute_reply.started":"2022-10-27T17:48:08.94529Z","shell.execute_reply":"2022-10-27T17:48:08.955831Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ds_test = EffnetDataSet(df_test_slices, TEST_IMAGES_PATH, WEIGHTS.transforms())\nX = ds_test[42]\nX.shape","metadata":{"execution":{"iopub.status.busy":"2022-10-27T17:48:08.958393Z","iopub.execute_input":"2022-10-27T17:48:08.958876Z","iopub.status.idle":"2022-10-27T17:48:09.009228Z","shell.execute_reply.started":"2022-10-27T17:48:08.958841Z","shell.execute_reply":"2022-10-27T17:48:09.008163Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class EffnetModel(torch.nn.Module):\n    def __init__(self):\n        super().__init__()\n        effnet = tv.models.efficientnet_v2_s()\n        self.model = create_feature_extractor(effnet, ['flatten'])\n        self.nn_fracture = torch.nn.Sequential(\n            torch.nn.Linear(1280, 7),\n        )\n        self.nn_vertebrae = torch.nn.Sequential(\n            torch.nn.Linear(1280, 7),\n        )\n\n    def forward(self, x):\n        # returns logits\n        x = self.model(x)['flatten']\n        return self.nn_fracture(x), self.nn_vertebrae(x)\n\n    def predict(self, x):\n        frac, vert = self.forward(x)\n        return torch.sigmoid(frac), torch.sigmoid(vert)","metadata":{"execution":{"iopub.status.busy":"2022-10-27T17:48:09.011042Z","iopub.execute_input":"2022-10-27T17:48:09.01141Z","iopub.status.idle":"2022-10-27T17:48:09.018926Z","shell.execute_reply.started":"2022-10-27T17:48:09.011375Z","shell.execute_reply":"2022-10-27T17:48:09.017686Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_model(model, name, path='.'):\n    data = torch.load(os.path.join(path, f'{name}.tph'), map_location=DEVICE)\n    model.load_state_dict(data)\n    return model","metadata":{"execution":{"iopub.status.busy":"2022-10-27T17:48:09.021655Z","iopub.execute_input":"2022-10-27T17:48:09.022573Z","iopub.status.idle":"2022-10-27T17:48:09.03447Z","shell.execute_reply.started":"2022-10-27T17:48:09.022537Z","shell.execute_reply":"2022-10-27T17:48:09.033469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"effnet_models = [load_model(EffnetModel(), name, EFFNET_CHECKPOINTS_PATH).to(DEVICE) for name in MODEL_NAMES]","metadata":{"execution":{"iopub.status.busy":"2022-10-27T17:48:12.959867Z","iopub.execute_input":"2022-10-27T17:48:12.960306Z","iopub.status.idle":"2022-10-27T17:48:25.025972Z","shell.execute_reply.started":"2022-10-27T17:48:12.960268Z","shell.execute_reply":"2022-10-27T17:48:25.024844Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from typing import List\n\n\ndef predict_effnet(models: List[EffnetModel], ds, max_batches=1e9):\n    dl_test = torch.utils.data.DataLoader(ds, batch_size=BATCH_SIZE, shuffle=False, num_workers=os.cpu_count())\n    for m in models:\n        m.eval()\n\n    with torch.no_grad():\n        predictions = []\n        for idx, X in enumerate(tqdm(dl_test, miniters=10)):\n            pred = torch.zeros(len(X), 14).to(DEVICE)\n            for m in models:\n                y1, y2 = m.predict(X.to(DEVICE))\n                pred += torch.concat([y1, y2], dim=1) / len(models)\n            predictions.append(pred)\n            if idx >= max_batches:\n                break\n        return torch.concat(predictions).cpu().numpy()\n","metadata":{"execution":{"iopub.status.busy":"2022-10-27T17:48:25.028029Z","iopub.execute_input":"2022-10-27T17:48:25.028586Z","iopub.status.idle":"2022-10-27T17:48:25.039121Z","shell.execute_reply.started":"2022-10-27T17:48:25.028546Z","shell.execute_reply":"2022-10-27T17:48:25.037997Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"effnet_pred = predict_effnet(effnet_models, ds_test)\n\ndf_effnet_pred = pd.DataFrame(\n    data=effnet_pred, columns=[f'C{i}_effnet_frac' for i in range(1, 8)] + [f'C{i}_effnet_vert' for i in range(1, 8)]\n)","metadata":{"execution":{"iopub.status.busy":"2022-10-27T17:48:25.0407Z","iopub.execute_input":"2022-10-27T17:48:25.04143Z","iopub.status.idle":"2022-10-27T17:49:11.445499Z","shell.execute_reply.started":"2022-10-27T17:48:25.04138Z","shell.execute_reply":"2022-10-27T17:49:11.444456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test_pred = pd.concat([df_test_slices, df_effnet_pred], axis=1).sort_values(['StudyInstanceUID', 'Slice'])\ndf_test_pred","metadata":{"execution":{"iopub.status.busy":"2022-10-27T17:49:11.448328Z","iopub.execute_input":"2022-10-27T17:49:11.448747Z","iopub.status.idle":"2022-10-27T17:49:11.483466Z","shell.execute_reply.started":"2022-10-27T17:49:11.448702Z","shell.execute_reply":"2022-10-27T17:49:11.482498Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_sample_patient(df_pred):\n    patient = np.random.choice(df_pred.StudyInstanceUID)\n    df = df_pred.query('StudyInstanceUID == @patient').reset_index()\n\n    df[[f'C{i}_effnet_frac' for i in range(1, 8)]].plot(\n        title=f'Patient {patient}, fracture prediction',\n        ax=(plt.subplot(1, 2, 1)))\n\n    df[[f'C{i}_effnet_vert' for i in range(1, 8)]].plot(\n        title=f'Patient {patient}, vertebrae prediction',\n        ax=plt.subplot(1, 2, 2)\n    )\n\nplot_sample_patient(df_test_pred)","metadata":{"execution":{"iopub.status.busy":"2022-10-27T17:49:11.485057Z","iopub.execute_input":"2022-10-27T17:49:11.485446Z","iopub.status.idle":"2022-10-27T17:49:12.03034Z","shell.execute_reply.started":"2022-10-27T17:49:11.485408Z","shell.execute_reply":"2022-10-27T17:49:12.028807Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def patient_prediction(df):\n    c1c7 = np.average(df[FRAC_COLS].values, axis=0, weights=df[VERT_COLS].values)\n    pred_patient_overall = 1 - np.prod(1 - c1c7)\n    pred_patient_overall = 2*pred_patient_overall/(1+pred_patient_overall)\n    return pd.Series(data=np.concatenate([[pred_patient_overall], c1c7]), index=['patient_overall'] + [f'C{i}' for i in range(1, 8)])\n\ndf_patient_pred = df_test_pred.groupby('StudyInstanceUID').apply(lambda df: patient_prediction(df))\ndf_patient_pred","metadata":{"execution":{"iopub.status.busy":"2022-10-27T18:27:22.30011Z","iopub.execute_input":"2022-10-27T18:27:22.300474Z","iopub.status.idle":"2022-10-27T18:27:22.328767Z","shell.execute_reply.started":"2022-10-27T18:27:22.300436Z","shell.execute_reply":"2022-10-27T18:27:22.32775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_sub = df_test.copy()\ndf_sub = df_sub.set_index('StudyInstanceUID').join(df_patient_pred)\ndf_sub['fractured'] = df_sub.apply(lambda r: r[r.prediction_type], axis=1)\ndf_sub","metadata":{"execution":{"iopub.status.busy":"2022-10-27T18:27:23.769487Z","iopub.execute_input":"2022-10-27T18:27:23.770367Z","iopub.status.idle":"2022-10-27T18:27:23.789744Z","shell.execute_reply.started":"2022-10-27T18:27:23.770332Z","shell.execute_reply":"2022-10-27T18:27:23.788489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_sub[['row_id', 'fractured']].to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2022-10-27T18:27:27.47949Z","iopub.execute_input":"2022-10-27T18:27:27.479886Z","iopub.status.idle":"2022-10-27T18:27:27.494142Z","shell.execute_reply.started":"2022-10-27T18:27:27.479851Z","shell.execute_reply":"2022-10-27T18:27:27.49311Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}