{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":29653,"databundleVersionId":2420395,"sourceType":"competition"}],"dockerImageVersionId":31040,"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\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","trusted":true,"_kg_hide-output":true,"scrolled":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport nibabel as nib\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom tqdm.notebook import tqdm\n\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n!pip install -q pydicom\nimport pydicom\nimport glob\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-16T10:34:59.426285Z","iopub.execute_input":"2025-06-16T10:34:59.427376Z","iopub.status.idle":"2025-06-16T10:35:03.671011Z","shell.execute_reply.started":"2025-06-16T10:34:59.427342Z","shell.execute_reply":"2025-06-16T10:35:03.669555Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\n\n# Read the labels\ndf = pd.read_csv('/kaggle/input/rsna-miccai-brain-tumor-radiogenomic-classification/train_labels.csv')\ndf['BraTS21ID'] = df['BraTS21ID'].astype(str).str.zfill(5)\ndf.head()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-16T10:25:01.269643Z","iopub.execute_input":"2025-06-16T10:25:01.269928Z","iopub.status.idle":"2025-06-16T10:25:01.293125Z","shell.execute_reply.started":"2025-06-16T10:25:01.269901Z","shell.execute_reply":"2025-06-16T10:25:01.292086Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def load_dicom_volume(patient_id, modality):\n    # Folder path: e.g., train/00753/T1w/*\n    base = f'/kaggle/input/rsna-miccai-brain-tumor-radiogenomic-classification/train/{patient_id}/{modality}/'\n    dicom_files = sorted(glob.glob(base + \"*.dcm\"), key=lambda x: int(x.split('-')[-1].split('.')[0]))\n\n    slices = []\n    for file in dicom_files:\n        ds = pydicom.dcmread(file)\n        img = ds.pixel_array.astype(np.float32)\n        slices.append(img)\n    \n    volume = np.stack(slices, axis=-1)  # shape: (H, W, D)\n    return volume","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-16T10:34:46.538815Z","iopub.execute_input":"2025-06-16T10:34:46.539190Z","iopub.status.idle":"2025-06-16T10:34:46.546996Z","shell.execute_reply.started":"2025-06-16T10:34:46.539162Z","shell.execute_reply":"2025-06-16T10:34:46.546068Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def load_multichannel_slice(patient_id, target_shape=(224, 224)):\n    modalities = ['T1w', 'T1wCE', 'T2w', 'FLAIR']\n    slices = []\n    for mod in modalities:\n        vol = load_dicom_volume(patient_id, mod)  # shape: (H, W, D)\n        vol = np.nan_to_num(vol)\n        vol = (vol - vol.mean()) / (vol.std() + 1e-5)\n        mid = vol.shape[2] // 2\n        slice_img = vol[:, :, mid]\n        # Resize to target_shape\n        slice_img = cv2.resize(slice_img, target_shape, interpolation=cv2.INTER_LINEAR)\n        slices.append(slice_img)\n    stacked = np.stack(slices, axis=0)  # (4, 224, 224)\n    return stacked.astype(np.float32)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-16T10:34:48.236752Z","iopub.execute_input":"2025-06-16T10:34:48.237081Z","iopub.status.idle":"2025-06-16T10:34:48.252969Z","shell.execute_reply.started":"2025-06-16T10:34:48.237056Z","shell.execute_reply":"2025-06-16T10:34:48.250589Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_id = '00753'\nsample = load_multichannel_slice(test_id)\nprint(\"Shape:\", sample.shape)  # should be (4, 224, 224)\n\n# Visualize each modality\nimport matplotlib.pyplot as plt\n\nfor i, mod in enumerate(['T1w', 'T1wCE', 'T2w', 'FLAIR']):\n    plt.subplot(1, 4, i+1)\n    plt.imshow(sample[i], cmap='gray')\n    plt.title(mod)\n    plt.axis('off')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-16T10:35:08.995903Z","iopub.execute_input":"2025-06-16T10:35:08.996294Z","iopub.status.idle":"2025-06-16T10:35:32.518638Z","shell.execute_reply.started":"2025-06-16T10:35:08.996258Z","shell.execute_reply":"2025-06-16T10:35:32.517645Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class MultiModalityDataset(Dataset):\n    def __init__(self, df):\n        self.df = df\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        pid = self.df.iloc[idx]['BraTS21ID']\n        label = self.df.iloc[idx]['MGMT_value']\n        img = load_multichannel_slice(pid)\n        return torch.tensor(img), torch.tensor(label, dtype=torch.float32)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-16T10:35:39.376300Z","iopub.execute_input":"2025-06-16T10:35:39.377334Z","iopub.status.idle":"2025-06-16T10:35:39.383153Z","shell.execute_reply.started":"2025-06-16T10:35:39.377299Z","shell.execute_reply":"2025-06-16T10:35:39.382140Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class FourModalityCNN(nn.Module):\n    def __init__(self):\n        super(FourModalityCNN, self).__init__()\n        self.conv1 = nn.Conv2d(4, 16, 3, padding=1)\n        self.conv2 = nn.Conv2d(16, 32, 3, padding=1)\n        self.pool = nn.MaxPool2d(2)\n        self.gap = nn.AdaptiveAvgPool2d((1, 1))  # new\n        self.fc1 = nn.Linear(32, 128)\n        self.fc2 = nn.Linear(128, 1)\n\n    def forward(self, x):\n        x = self.pool(F.relu(self.conv1(x)))  # (B, 16, 112, 112)\n        x = self.pool(F.relu(self.conv2(x)))  # (B, 32, 56, 56)\n        x = self.gap(x)                       # (B, 32, 1, 1)\n        x = x.view(x.size(0), -1)             # (B, 32)\n        x = F.relu(self.fc1(x))               # (B, 128)\n        return torch.sigmoid(self.fc2(x)).squeeze()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-16T10:45:46.862199Z","iopub.execute_input":"2025-06-16T10:45:46.863242Z","iopub.status.idle":"2025-06-16T10:45:46.876391Z","shell.execute_reply.started":"2025-06-16T10:45:46.863198Z","shell.execute_reply":"2025-06-16T10:45:46.874783Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df, val_df = train_test_split(df, test_size=0.2, random_state=42)\n\ntrain_ds = MultiModalityDataset(train_df)\nval_ds = MultiModalityDataset(val_df)\n\ntrain_loader = DataLoader(train_ds, batch_size=16, shuffle=True)\nval_loader = DataLoader(val_ds, batch_size=16)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-16T10:35:44.721313Z","iopub.execute_input":"2025-06-16T10:35:44.721897Z","iopub.status.idle":"2025-06-16T10:35:44.731011Z","shell.execute_reply.started":"2025-06-16T10:35:44.721867Z","shell.execute_reply":"2025-06-16T10:35:44.729778Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sample = next(iter(train_loader))\nprint(\"Sample loaded:\", sample[0].shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-16T11:04:25.717735Z","iopub.execute_input":"2025-06-16T11:04:25.718138Z","iopub.status.idle":"2025-06-16T11:05:49.770024Z","shell.execute_reply.started":"2025-06-16T11:04:25.718104Z","shell.execute_reply":"2025-06-16T11:05:49.768637Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel = FourModalityCNN().to(device)\n\ncriterion = nn.BCELoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=1e-4)\n\nfor epoch in range(5):\n    model.train()\n    train_loss = 0\n    for X, y in train_loader:\n        X, y = X.to(device), y.to(device)\n        optimizer.zero_grad()\n        outputs = model(X)\n        loss = criterion(outputs, y)\n        loss.backward()\n        optimizer.step()\n        train_loss += loss.item()\n\n    model.eval()\n    correct, total = 0, 0\n    with torch.no_grad():\n        for X, y in val_loader:\n            X, y = X.to(device), y.to(device)\n            preds = model(X) > 0.5\n            correct += (preds == y.bool()).sum().item()\n            total += y.size(0)\n\n    acc = correct / total\n    print(f\"Epoch {epoch+1} | Loss: {train_loss:.4f} | Val Acc: {acc:.4f}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-16T10:45:53.720789Z","iopub.execute_input":"2025-06-16T10:45:53.721152Z","iopub.status.idle":"2025-06-16T11:04:18.296942Z","shell.execute_reply.started":"2025-06-16T10:45:53.721127Z","shell.execute_reply":"2025-06-16T11:04:18.294874Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}