{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":10338,"databundleVersionId":862042,"sourceType":"competition"}],"dockerImageVersionId":30732,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\n/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_detailed_class_info.csv\n/kaggle/input/rsna-pneumonia-detection-challenge/GCP Credits Request Link - RSNA.txt\n\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-06-18T11:53:49.734053Z","iopub.execute_input":"2024-06-18T11:53:49.734509Z","iopub.status.idle":"2024-06-18T11:54:34.666536Z","shell.execute_reply.started":"2024-06-18T11:53:49.734475Z","shell.execute_reply":"2024-06-18T11:54:34.664638Z"},"scrolled":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from pathlib import Path\nimport pydicom\nimport numpy as np\nimport cv2\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom tqdm.notebook import tqdm","metadata":{"execution":{"iopub.status.busy":"2024-06-18T12:02:44.277502Z","iopub.execute_input":"2024-06-18T12:02:44.278026Z","iopub.status.idle":"2024-06-18T12:02:45.210511Z","shell.execute_reply.started":"2024-06-18T12:02:44.277989Z","shell.execute_reply":"2024-06-18T12:02:45.208862Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = pd.read_csv(\"/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_train_labels.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-06-18T12:03:27.152556Z","iopub.execute_input":"2024-06-18T12:03:27.15302Z","iopub.status.idle":"2024-06-18T12:03:27.237837Z","shell.execute_reply.started":"2024-06-18T12:03:27.152986Z","shell.execute_reply":"2024-06-18T12:03:27.236302Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-18T12:03:35.695274Z","iopub.execute_input":"2024-06-18T12:03:35.695734Z","iopub.status.idle":"2024-06-18T12:03:35.722565Z","shell.execute_reply.started":"2024-06-18T12:03:35.6957Z","shell.execute_reply":"2024-06-18T12:03:35.721135Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = labels.drop_duplicates(\"patientId\")","metadata":{"execution":{"iopub.status.busy":"2024-06-18T12:05:17.916482Z","iopub.execute_input":"2024-06-18T12:05:17.916983Z","iopub.status.idle":"2024-06-18T12:05:17.942232Z","shell.execute_reply.started":"2024-06-18T12:05:17.916948Z","shell.execute_reply":"2024-06-18T12:05:17.940474Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT_PATH = Path(\"/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_train_images/\")\nSAVE_PATH = Path(\"Processed\")","metadata":{"execution":{"iopub.status.busy":"2024-06-18T12:06:46.505494Z","iopub.execute_input":"2024-06-18T12:06:46.50667Z","iopub.status.idle":"2024-06-18T12:06:46.513255Z","shell.execute_reply.started":"2024-06-18T12:06:46.50663Z","shell.execute_reply":"2024-06-18T12:06:46.511353Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, axis = plt.subplots(3,3,figsize=(9,9))\nc = 0\nfor i in range(3):\n    for j in range(3):\n        patient_id = labels.patientId.iloc[c]\n        dcm_path = ROOT_PATH/patient_id\n        dcm_path = dcm_path.with_suffix(\".dcm\")\n        dcm = pydicom.read_file(dcm_path).pixel_array\n        \n        label = labels[\"Target\"].iloc[c]\n        \n        axis[i][j].imshow(dcm,cmap='bone')\n        axis[i][j].set_title(label)\n        c+=1","metadata":{"execution":{"iopub.status.busy":"2024-06-18T12:16:25.905017Z","iopub.execute_input":"2024-06-18T12:16:25.905572Z","iopub.status.idle":"2024-06-18T12:16:29.164437Z","shell.execute_reply.started":"2024-06-18T12:16:25.905533Z","shell.execute_reply":"2024-06-18T12:16:29.163003Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sums,sums_squared = 0,0\n\nfor c,patient_id in enumerate(tqdm(labels.patientId)):\n        patient_id = labels.patientId.iloc[c]\n        dcm_path = ROOT_PATH/patient_id\n        dcm_path = dcm_path.with_suffix(\".dcm\")\n        dcm = pydicom.read_file(dcm_path).pixel_array / 255\n        \n        dcm_array = cv2.resize(dcm, (224,224)).astype(np.float16)\n        \n        label = labels.Target.iloc[c]\n        \n        train_or_val = \"train\" if c < 24000 else \"val\"\n        current_save_path = SAVE_PATH/train_or_val/str(label)\n        current_save_path.mkdir(parents=True,exist_ok=True)\n        np.save(current_save_path/patient_id, dcm_array)\n        \n        normalizer = 224*224\n        if train_or_val == \"train\":\n            sums += np.sum(dcm_array) / normalizer\n            sums_squared += (dcm_array**2).sum() / normalizer","metadata":{"execution":{"iopub.status.busy":"2024-06-18T12:26:44.362938Z","iopub.execute_input":"2024-06-18T12:26:44.363398Z","iopub.status.idle":"2024-06-18T12:36:10.130565Z","shell.execute_reply.started":"2024-06-18T12:26:44.363363Z","shell.execute_reply":"2024-06-18T12:36:10.128701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mean = sums / 24000\nstd = np.sqrt((sums_squared / 24000) - mean**2)","metadata":{"execution":{"iopub.status.busy":"2024-06-18T12:39:25.903609Z","iopub.execute_input":"2024-06-18T12:39:25.904044Z","iopub.status.idle":"2024-06-18T12:39:25.911286Z","shell.execute_reply.started":"2024-06-18T12:39:25.904009Z","shell.execute_reply":"2024-06-18T12:39:25.91005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mean,std","metadata":{"execution":{"iopub.status.busy":"2024-06-18T12:39:37.643627Z","iopub.execute_input":"2024-06-18T12:39:37.644176Z","iopub.status.idle":"2024-06-18T12:39:37.653908Z","shell.execute_reply.started":"2024-06-18T12:39:37.644137Z","shell.execute_reply":"2024-06-18T12:39:37.652479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torchvision\nfrom torchvision import transforms\nimport torchmetrics\nimport pytorch_lightning as pl\nfrom pytorch_lightning.callbacks import ModelCheckpoint\nfrom pytorch_lightning.loggers import TensorBoardLogger\nfrom tqdm.notebook import tqdm","metadata":{"execution":{"iopub.status.busy":"2024-06-18T12:41:18.820006Z","iopub.execute_input":"2024-06-18T12:41:18.820616Z","iopub.status.idle":"2024-06-18T12:41:28.748432Z","shell.execute_reply.started":"2024-06-18T12:41:18.820562Z","shell.execute_reply":"2024-06-18T12:41:28.747104Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_file(path):\n    return np.load(path).astype(np.float32)","metadata":{"execution":{"iopub.status.busy":"2024-06-18T12:43:27.155107Z","iopub.execute_input":"2024-06-18T12:43:27.156021Z","iopub.status.idle":"2024-06-18T12:43:27.16226Z","shell.execute_reply.started":"2024-06-18T12:43:27.155972Z","shell.execute_reply":"2024-06-18T12:43:27.161042Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_transforms = transforms.Compose([\n    transforms.ToTensor(),\n    transforms.Normalize(0.49,0.248),\n    transforms.RandomAffine(degrees=(-5,5),translate=(0,0.05),scale=(0.9,1.1)),\n    transforms.RandomResizedCrop((224,224),scale=(0.35,1))\n])\n\nval_transforms = transforms.Compose([\n    transforms.ToTensor(),\n    transforms.Normalize(0.49,0.248)\n])","metadata":{"execution":{"iopub.status.busy":"2024-06-18T12:48:09.940731Z","iopub.execute_input":"2024-06-18T12:48:09.941265Z","iopub.status.idle":"2024-06-18T12:48:09.950761Z","shell.execute_reply.started":"2024-06-18T12:48:09.941224Z","shell.execute_reply":"2024-06-18T12:48:09.949071Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset = torchvision.datasets.DatasetFolder(\"Processed/train/\",loader=load_file,extensions=\"npy\",transform=train_transforms)\nval_dataset = torchvision.datasets.DatasetFolder(\"Processed/val/\",loader=load_file,extensions=\"npy\",transform=val_transforms)","metadata":{"execution":{"iopub.status.busy":"2024-06-18T12:58:48.628836Z","iopub.execute_input":"2024-06-18T12:58:48.629387Z","iopub.status.idle":"2024-06-18T12:58:48.788782Z","shell.execute_reply.started":"2024-06-18T12:58:48.629351Z","shell.execute_reply":"2024-06-18T12:58:48.787411Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, axis = plt.subplots(2,2, figsize=(9,9))\n\nfor i in range(2):\n    for j in range(2):\n        random_index = np.random.randint(0,24000)\n        x_ray, label = train_dataset[random_index]\n        axis[i][j].imshow(x_ray[0],cmap=\"bone\")\n        axis[i][j].set_title(label)","metadata":{"execution":{"iopub.status.busy":"2024-06-18T12:58:50.065656Z","iopub.execute_input":"2024-06-18T12:58:50.066086Z","iopub.status.idle":"2024-06-18T12:58:51.434694Z","shell.execute_reply.started":"2024-06-18T12:58:50.066052Z","shell.execute_reply":"2024-06-18T12:58:51.433217Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_size = 64\nnum_workers = 4\n\ntrain_loader = torch.utils.data.DataLoader(train_dataset,batch_size=batch_size,num_workers=num_workers,shuffle=True)\nval_loader = torch.utils.data.DataLoader(val_dataset,batch_size=batch_size,num_workers=num_workers,shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2024-06-18T12:59:06.804206Z","iopub.execute_input":"2024-06-18T12:59:06.805255Z","iopub.status.idle":"2024-06-18T12:59:06.813582Z","shell.execute_reply.started":"2024-06-18T12:59:06.805217Z","shell.execute_reply":"2024-06-18T12:59:06.812187Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class PneumoniaClassifier(pl.LightningModule):\n\n    def __init__(self):\n        super().__init__()\n        self.model = torchvision.models.resnet18()\n        self.model.conv1 = torch.nn.Conv2d(1,64,kernel_size=(7,7),stride=(2,2),padding=(3,3),bias=False)\n        self.model.fc = torch.nn.Linear(in_features=512,out_features=1,bias=True)\n        \n        self.optimizer = torch.optim.Adam(self.model.parameters(),lr=1e-4)\n        self.loss_fn = torch.nn.BCEWithLogitsLoss(pos_weight=torch.tensor([3]))\n        \n        self.train_acc = torchmetrics.Accuracy(task='binary')\n        self.val_acc = torchmetrics.Accuracy(task='binary')\n        \n    def forward(self,data):\n            pred = self.model(data)\n            return pred\n    def training_step(self,batch,batch_idx):\n            x_ray, label = batch\n            label = label.float()\n            pred = self(x_ray)[:,0]\n            loss = self.loss_fn(pred,label)\n            \n            self.log(\"Train Loss\", loss)\n            self.log(\"Step Train ACC\",self.train_acc(torch.sigmoid(pred),label.int()))\n            return loss\n        \n    def on_train_epoch_end(self,outs):\n            self.log(\"Train ACC\",self.train_acc.compute())\n            \n            \n    def validation_step(self,batch,batch_idx):\n            x_ray, label = batch\n            label = label.float()\n            pred = self(x_ray)[:,0]\n            loss = self.loss_fn(pred,label)\n            \n            self.log(\"Val Loss\", loss)\n            self.log(\"Step Val ACC\",self.train_acc(torch.sigmoid(pred),label.int()))\n    \n        \n    def on_validation_epoch_end(self,outs):\n            self.log(\"Val ACC\",self.val_acc.compute())\n            \n    def configure_optimizer(self):\n            return [self.optimizer]\n            \n","metadata":{"execution":{"iopub.status.busy":"2024-06-18T13:37:53.446112Z","iopub.execute_input":"2024-06-18T13:37:53.446648Z","iopub.status.idle":"2024-06-18T13:37:53.464145Z","shell.execute_reply.started":"2024-06-18T13:37:53.446612Z","shell.execute_reply":"2024-06-18T13:37:53.462697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = PneumoniaClassifier()","metadata":{"execution":{"iopub.status.busy":"2024-06-18T13:37:55.118919Z","iopub.execute_input":"2024-06-18T13:37:55.119359Z","iopub.status.idle":"2024-06-18T13:37:55.365421Z","shell.execute_reply.started":"2024-06-18T13:37:55.119325Z","shell.execute_reply":"2024-06-18T13:37:55.364235Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"checkpoint_callback = ModelCheckpoint(\nmonitor=\"Val ACC\",\nsave_top_k =10,\nmode=\"max\")","metadata":{"execution":{"iopub.status.busy":"2024-06-18T13:37:56.313999Z","iopub.execute_input":"2024-06-18T13:37:56.314449Z","iopub.status.idle":"2024-06-18T13:37:56.321079Z","shell.execute_reply.started":"2024-06-18T13:37:56.314414Z","shell.execute_reply":"2024-06-18T13:37:56.319407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gpus=1\ntrainer = pl.Trainer(accelerator=\"auto\",logger=TensorBoardLogger(save_dir=\"./logs\"),log_every_n_steps=1,callbacks=checkpoint_callback,max_epochs=35)","metadata":{"execution":{"iopub.status.busy":"2024-06-18T13:37:57.293732Z","iopub.execute_input":"2024-06-18T13:37:57.294191Z","iopub.status.idle":"2024-06-18T13:37:57.361285Z","shell.execute_reply.started":"2024-06-18T13:37:57.294154Z","shell.execute_reply":"2024-06-18T13:37:57.359904Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"trainer.fit(model,train_loader,val_loader)","metadata":{"execution":{"iopub.status.busy":"2024-06-18T13:37:58.188471Z","iopub.execute_input":"2024-06-18T13:37:58.189292Z","iopub.status.idle":"2024-06-18T13:37:58.334242Z","shell.execute_reply.started":"2024-06-18T13:37:58.189251Z","shell.execute_reply":"2024-06-18T13:37:58.332433Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}