{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.10","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":29653,"databundleVersionId":2420395,"sourceType":"competition"},{"sourceId":2541979,"sourceType":"datasetVersion","datasetId":1541400}],"dockerImageVersionId":30121,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# Import libraries\nimport numpy as np\nimport pandas as pd\nimport os\nimport cv2\nimport pydicom\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import f1_score, cohen_kappa_score, roc_auc_score, classification_report, roc_curve, auc\n\nimport tensorflow as tf\nfrom tensorflow.keras.applications import VGG16\nfrom tensorflow.keras.models import Model, Sequential\nfrom tensorflow.keras.layers import Dense, Flatten, Dropout\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import EarlyStopping\n\n# Set paths\ntrain_path = '/kaggle/input/rsna-miccai-brain-tumor-radiogenomic-classification/train/'\nlabels_path = '/kaggle/input/rsna-miccai-brain-tumor-radiogenomic-classification/train_labels.csv'\n\nlabels_df = pd.read_csv(labels_path)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T16:17:18.895845Z","iopub.execute_input":"2025-04-29T16:17:18.896231Z","iopub.status.idle":"2025-04-29T16:17:26.822528Z","shell.execute_reply.started":"2025-04-29T16:17:18.896144Z","shell.execute_reply":"2025-04-29T16:17:26.821653Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load one middle slice\ndef load_image(patient_id, img_size=(128,128)):\n    patient_folder = os.path.join(train_path, str(patient_id).zfill(5), \"T1w\")\n    if not os.path.exists(patient_folder):\n        return None\n    slices = sorted(os.listdir(patient_folder))\n    if len(slices) == 0:\n        return None\n    slice_path = os.path.join(patient_folder, slices[len(slices)//2])\n    dcm = pydicom.dcmread(slice_path)\n    img = dcm.pixel_array\n    img = cv2.resize(img, img_size)\n    img = img / 255.0\n    return img\n\n# Load dataset\nX = []\ny = []\n\nfor idx, 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)\nX = np.expand_dims(X, axis=-1)  # (batch, 128,128,1)\ny = np.array(y)\n\n# Train-test split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\nX_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.25, random_state=42, stratify=y_train)\n\n# Repeat channels if grayscale\nX_train = np.repeat(X_train, 3, axis=-1)\nX_val = np.repeat(X_val, 3, axis=-1)\nX_test = np.repeat(X_test, 3, axis=-1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T16:17:26.823630Z","iopub.execute_input":"2025-04-29T16:17:26.823878Z","iopub.status.idle":"2025-04-29T16:17:48.167812Z","shell.execute_reply.started":"2025-04-29T16:17:26.823853Z","shell.execute_reply":"2025-04-29T16:17:48.167193Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Data augmentation\ndatagen = ImageDataGenerator(\n    rotation_range=20,\n    zoom_range=0.2,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    horizontal_flip=True,\n    vertical_flip=True,\n    brightness_range=[0.8,1.2]\n)\ndatagen.fit(X_train)\n\n# Build improved VGG16\nbase_model = VGG16(weights=None, include_top=False, input_shape=(128,128,3))\n\n# Freeze VGG16 layers\nfor layer in base_model.layers:\n    layer.trainable = False\n\nmodel = Sequential()\nmodel.add(base_model)\nmodel.add(Flatten())\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1, activation='sigmoid'))\n\n# Compile\nmodel.compile(optimizer=Adam(learning_rate=1e-5), loss='binary_crossentropy', metrics=['accuracy'])\n\n# Early stopping\nearly_stop = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T16:17:48.168873Z","iopub.execute_input":"2025-04-29T16:17:48.169127Z","iopub.status.idle":"2025-04-29T16:17:51.048929Z","shell.execute_reply.started":"2025-04-29T16:17:48.169104Z","shell.execute_reply":"2025-04-29T16:17:51.048027Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Train model\nhistory = model.fit(datagen.flow(X_train, y_train, batch_size=32),\n                    validation_data=(X_val, y_val),\n                    epochs=50,\n                    callbacks=[early_stop])\n\n# Evaluate\ntest_loss, test_acc = model.evaluate(X_test, y_test, verbose=0)\n\n# Predictions\ny_pred = (model.predict(X_test) > 0.5).astype(\"int32\")\n\n# Metrics\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)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T16:17:51.050122Z","iopub.execute_input":"2025-04-29T16:17:51.050363Z","iopub.status.idle":"2025-04-29T16:18:14.106450Z","shell.execute_reply.started":"2025-04-29T16:17:51.050340Z","shell.execute_reply":"2025-04-29T16:18:14.105687Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Printing Results\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\n# Plot Accuracy and Loss\nplt.figure(figsize=(14,5))\n\nplt.subplot(1,2,1)\nplt.plot(history.history['accuracy'], label='Train Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.legend()\nplt.title('Model Accuracy')\n\nplt.subplot(1,2,2)\nplt.plot(history.history['loss'], label='Train Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.legend()\nplt.title('Model Loss')\n\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T16:18:14.107924Z","iopub.execute_input":"2025-04-29T16:18:14.108266Z","iopub.status.idle":"2025-04-29T16:18:14.393682Z","shell.execute_reply.started":"2025-04-29T16:18:14.108229Z","shell.execute_reply":"2025-04-29T16:18:14.392929Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Plot ROC Curve\nfpr, tpr, _ = roc_curve(y_test, y_pred)\nroc_auc_value = auc(fpr, tpr)\n\nplt.figure()\nplt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc_value:.2f})')\nplt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver Operating Characteristic (ROC)')\nplt.legend(loc=\"lower right\")\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T16:18:14.395772Z","iopub.execute_input":"2025-04-29T16:18:14.396133Z","iopub.status.idle":"2025-04-29T16:18:14.524901Z","shell.execute_reply.started":"2025-04-29T16:18:14.396097Z","shell.execute_reply":"2025-04-29T16:18:14.524180Z"}},"outputs":[],"execution_count":null}]}