{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":29653,"databundleVersionId":2420395,"sourceType":"competition"},{"sourceId":6408692,"sourceType":"datasetVersion","datasetId":3695764}],"dockerImageVersionId":30559,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# Install dependencies\n!pip install -q pydicom tensorflow\n\n# Imports\nimport os, cv2, pydicom\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import f1_score, cohen_kappa_score, roc_auc_score, roc_curve, auc\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\n# Load and preprocess RSNA-MICCAI MRI data \nlabels_df = pd.read_csv('/kaggle/input/rsna-miccai-brain-tumor-radiogenomic-classification/train_labels.csv')\ntrain_path = '/kaggle/input/rsna-miccai-brain-tumor-radiogenomic-classification/train/'\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-30T06:20:07.214456Z","iopub.execute_input":"2025-04-30T06:20:07.215001Z","iopub.status.idle":"2025-04-30T06:20:59.075785Z","shell.execute_reply.started":"2025-04-30T06:20:07.214969Z","shell.execute_reply":"2025-04-30T06:20:59.074781Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def load_image(patient_id, img_size=(128, 128)):\n    folder = os.path.join(train_path, str(patient_id).zfill(5), \"T1w\")\n    if not os.path.exists(folder): return None\n    files = sorted(os.listdir(folder))\n    if len(files) == 0: return None\n    path = os.path.join(folder, files[len(files)//2])\n    dcm = pydicom.dcmread(path)\n    img = dcm.pixel_array\n    img = cv2.resize(img, img_size)\n    img = img / 255.0\n    return np.expand_dims(img, -1)\n\nX, y = [], []\nfor _, row in labels_df.iterrows():\n    img = load_image(row['BraTS21ID'])\n    if img is not None:\n        X.append(img)\n        y.append(row['MGMT_value'])\n\nX = np.array(X)\ny = np.array(y)\n\n# Train/Validation/Test Split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)\nX_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.25, stratify=y_train, random_state=42)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-30T06:20:59.077722Z","iopub.execute_input":"2025-04-30T06:20:59.078070Z","iopub.status.idle":"2025-04-30T06:21:11.859821Z","shell.execute_reply.started":"2025-04-30T06:20:59.078035Z","shell.execute_reply":"2025-04-30T06:21:11.859044Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n# Define EANet Block \ndef eanet_block(x, filters):\n    conv = layers.Conv2D(filters, (3, 3), padding='same')(x)\n    conv = layers.BatchNormalization()(conv)\n    conv = layers.ReLU()(conv)\n    \n    spatial_att = layers.Conv2D(1, (1, 1), activation='sigmoid')(conv)\n    channel_avg = tf.reduce_mean(conv, axis=[1, 2], keepdims=True)\n    channel_max = tf.reduce_max(conv, axis=[1, 2], keepdims=True)\n    channel_att = layers.Conv2D(filters, (1, 1), activation='sigmoid')(channel_avg + channel_max)\n    \n    x = conv * spatial_att * channel_att\n    return x\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-30T06:21:11.861083Z","iopub.execute_input":"2025-04-30T06:21:11.861427Z","iopub.status.idle":"2025-04-30T06:21:11.867718Z","shell.execute_reply.started":"2025-04-30T06:21:11.861389Z","shell.execute_reply":"2025-04-30T06:21:11.866906Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define EANet Model\ndef build_eanet(input_shape=(128, 128, 1)):\n    inputs = keras.Input(shape=input_shape)\n    \n    x = eanet_block(inputs, 32)\n    x = layers.MaxPooling2D()(x)\n\n    x = eanet_block(x, 64)\n    x = layers.MaxPooling2D()(x)\n\n    x = eanet_block(x, 128)\n    x = layers.GlobalAveragePooling2D()(x)\n\n    x = layers.Dense(64, activation='relu')(x)\n    x = layers.Dropout(0.5)(x)\n    outputs = layers.Dense(1, activation='sigmoid')(x)\n\n    model = keras.Model(inputs, outputs)\n    return model\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-30T06:21:11.868960Z","iopub.execute_input":"2025-04-30T06:21:11.869187Z","iopub.status.idle":"2025-04-30T06:21:11.885729Z","shell.execute_reply.started":"2025-04-30T06:21:11.869166Z","shell.execute_reply":"2025-04-30T06:21:11.884997Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Compile and Train EANet\neanet_model = build_eanet()\neanet_model.compile(optimizer=keras.optimizers.Adam(1e-4),\n                    loss=\"binary_crossentropy\",\n                    metrics=[\"accuracy\"])\n\nearly_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)\n\nhistory = eanet_model.fit(X_train, y_train,\n                          validation_data=(X_val, y_val),\n                          epochs=30,\n                          batch_size=16,\n                          callbacks=[early_stop],\n                          verbose=1)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-30T06:21:11.887851Z","iopub.execute_input":"2025-04-30T06:21:11.888181Z","iopub.status.idle":"2025-04-30T06:21:27.218615Z","shell.execute_reply.started":"2025-04-30T06:21:11.888160Z","shell.execute_reply":"2025-04-30T06:21:27.217872Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Evaluate Model\ntest_loss, test_acc = eanet_model.evaluate(X_test, y_test, verbose=0)\ny_pred_prob = eanet_model.predict(X_test)\ny_pred = (y_pred_prob > 0.5).astype(int)\n\ntrain_acc = history.history['accuracy'][-1]\nval_acc = history.history['val_accuracy'][-1]\nf1 = f1_score(y_test, y_pred)\nkappa = cohen_kappa_score(y_test, y_pred)\nroc_auc = roc_auc_score(y_test, y_pred_prob)\n\nprint(f\"Training Accuracy: {train_acc:.4f}\")\nprint(f\"Validation Accuracy: {val_acc:.4f}\")\nprint(f\"Test Accuracy: {test_acc:.4f}\")\nprint(f\"F1 Score: {f1:.4f}\")\nprint(f\"Cohen's Kappa: {kappa:.4f}\")\nprint(f\"AUC: {roc_auc:.4f}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-30T06:21:27.219656Z","iopub.execute_input":"2025-04-30T06:21:27.219956Z","iopub.status.idle":"2025-04-30T06:21:28.075374Z","shell.execute_reply.started":"2025-04-30T06:21:27.219931Z","shell.execute_reply":"2025-04-30T06:21:28.074534Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Plot Accuracy & Loss\nplt.figure(figsize=(14, 5))\nplt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'], label='Train Acc')\nplt.plot(history.history['val_accuracy'], label='Val Acc')\nplt.title('Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend()\n\nplt.subplot(1, 2, 2)\nplt.plot(history.history['loss'], label='Train Loss')\nplt.plot(history.history['val_loss'], label='Val Loss')\nplt.title('Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()\nplt.tight_layout()\nplt.show()\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-30T06:21:28.076615Z","iopub.execute_input":"2025-04-30T06:21:28.076967Z","iopub.status.idle":"2025-04-30T06:21:28.646135Z","shell.execute_reply.started":"2025-04-30T06:21:28.076931Z","shell.execute_reply":"2025-04-30T06:21:28.645309Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ROC Curve\nfpr, tpr, _ = roc_curve(y_test, y_pred_prob)\nroc_val = auc(fpr, tpr)\n\nplt.figure()\nplt.plot(fpr, tpr, label=f'ROC (AUC = {roc_val:.2f})')\nplt.plot([0, 1], [0, 1], linestyle='--', color='gray')\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('ROC Curve - EANet (New Method V)')\nplt.legend()\nplt.grid()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-30T06:21:28.647257Z","iopub.execute_input":"2025-04-30T06:21:28.647508Z","iopub.status.idle":"2025-04-30T06:21:28.896229Z","shell.execute_reply.started":"2025-04-30T06:21:28.647486Z","shell.execute_reply":"2025-04-30T06:21:28.895390Z"}},"outputs":[],"execution_count":null}]}