{"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":848739,"sourceType":"datasetVersion","datasetId":251095},{"sourceId":2425289,"sourceType":"datasetVersion","datasetId":1467572}],"dockerImageVersionId":30121,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Import things","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-07-18T04:22:55.955919Z","iopub.execute_input":"2021-07-18T04:22:55.956524Z","iopub.status.idle":"2021-07-18T04:22:56.527271Z","shell.execute_reply.started":"2021-07-18T04:22:55.956406Z","shell.execute_reply":"2021-07-18T04:22:56.526277Z"}}},{"cell_type":"code","source":"# Suppress warnings (Optional - for clean output)\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# Import libraries\nimport numpy as np\nimport pandas as pd\nimport os\nimport cv2\nimport pydicom\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\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, GlobalAveragePooling2D\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import MobileNet\nfrom tensorflow.keras.callbacks import EarlyStopping\n\n# 1. Load labels\ntrain_path = '/kaggle/input/rsna-miccai-brain-tumor-radiogenomic-classification/train/'\nlabels_path = '/kaggle/input/rsna-miccai-brain-tumor-radiogenomic-classification/train_labels.csv'\nlabels_df = pd.read_csv(labels_path)\n","metadata":{"execution":{"iopub.status.busy":"2025-04-30T00:26:27.129564Z","iopub.execute_input":"2025-04-30T00:26:27.129968Z","iopub.status.idle":"2025-04-30T00:26:33.862605Z","shell.execute_reply.started":"2025-04-30T00:26:27.129857Z","shell.execute_reply":"2025-04-30T00:26:33.861950Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load images\ndef 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 not files: return None\n    dcm = pydicom.dcmread(os.path.join(folder, files[len(files)//2]))\n    img = dcm.pixel_array\n    img = cv2.resize(img, img_size)\n    return img / 255.0\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.expand_dims(np.array(X), axis=-1)  # Shape: (N,128,128,1)\ny = np.array(y)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-30T00:26:33.863993Z","iopub.execute_input":"2025-04-30T00:26:33.864322Z","iopub.status.idle":"2025-04-30T00:26:50.980596Z","shell.execute_reply.started":"2025-04-30T00:26:33.864287Z","shell.execute_reply":"2025-04-30T00:26:50.979911Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Prepare dataset\nX = np.repeat(X, 3, axis=-1)  # MobileNet expects 3 channels\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-30T00:26:50.982003Z","iopub.execute_input":"2025-04-30T00:26:50.982233Z","iopub.status.idle":"2025-04-30T00:26:51.263214Z","shell.execute_reply.started":"2025-04-30T00:26:50.982211Z","shell.execute_reply":"2025-04-30T00:26:51.262271Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(12,8))\nfor i in range(9):\n    idx = np.random.randint(0, len(X_train))\n    plt.subplot(3, 3, i+1)\n    plt.imshow(X_train[idx])\n    plt.title(f\"Label: {y_train[idx]}\")\n    plt.axis('off')\nplt.suptitle('Sample Training MRI Slices', fontsize=16)\nplt.tight_layout()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2025-04-30T00:26:51.264709Z","iopub.execute_input":"2025-04-30T00:26:51.265099Z","iopub.status.idle":"2025-04-30T00:26:51.971530Z","shell.execute_reply.started":"2025-04-30T00:26:51.265060Z","shell.execute_reply":"2025-04-30T00:26:51.970721Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Model","metadata":{}},{"cell_type":"code","source":"\n# Data augmentation\naug = ImageDataGenerator(\n    rotation_range=15,\n    width_shift_range=0.1,\n    height_shift_range=0.1,\n    zoom_range=0.1,\n    horizontal_flip=True\n)\naug.fit(X_train)","metadata":{"execution":{"iopub.status.busy":"2025-04-30T00:26:51.972846Z","iopub.execute_input":"2025-04-30T00:26:51.973209Z","iopub.status.idle":"2025-04-30T00:26:52.031941Z","shell.execute_reply.started":"2025-04-30T00:26:51.973173Z","shell.execute_reply":"2025-04-30T00:26:52.031242Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Build MobileNet model\nbase_model = MobileNet(weights=None, include_top=False, input_shape=(128,128,3))\n\nmodel = Sequential([\n    base_model,\n    GlobalAveragePooling2D(),\n    Dense(256, activation='relu'),\n    Dropout(0.5),\n    Dense(1, activation='sigmoid')\n])\n\nmodel.compile(optimizer=Adam(1e-4), loss='binary_crossentropy', metrics=['accuracy'])\n\n# Early stopping\nearly_stop = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)\n","metadata":{"execution":{"iopub.status.busy":"2025-04-30T00:26:52.032938Z","iopub.execute_input":"2025-04-30T00:26:52.033149Z","iopub.status.idle":"2025-04-30T00:26:54.732620Z","shell.execute_reply.started":"2025-04-30T00:26:52.033129Z","shell.execute_reply":"2025-04-30T00:26:54.731759Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Train model\nhistory = model.fit(\n    aug.flow(X_train, y_train, batch_size=32),\n    validation_data=(X_val, y_val),\n    epochs=30,\n    callbacks=[early_stop]\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-30T00:26:54.733808Z","iopub.execute_input":"2025-04-30T00:26:54.734151Z","iopub.status.idle":"2025-04-30T00:27:13.052554Z","shell.execute_reply.started":"2025-04-30T00:26:54.734118Z","shell.execute_reply":"2025-04-30T00:27:13.051745Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 8. Evaluate model\ntest_loss, test_acc = model.evaluate(X_test, y_test, verbose=0)\ny_pred = (model.predict(X_test) > 0.5).astype(\"int32\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-30T00:27:13.053817Z","iopub.execute_input":"2025-04-30T00:27:13.054069Z","iopub.status.idle":"2025-04-30T00:27:13.641360Z","shell.execute_reply.started":"2025-04-30T00:27:13.054043Z","shell.execute_reply":"2025-04-30T00:27:13.640590Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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\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}\")","metadata":{"execution":{"iopub.status.busy":"2025-04-30T00:27:13.643282Z","iopub.execute_input":"2025-04-30T00:27:13.643531Z","iopub.status.idle":"2025-04-30T00:27:13.654254Z","shell.execute_reply.started":"2025-04-30T00:27:13.643504Z","shell.execute_reply":"2025-04-30T00:27:13.653475Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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.title('Training and Validation 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='Validation Loss')\nplt.title('Training and Validation Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-30T00:27:13.655412Z","iopub.execute_input":"2025-04-30T00:27:13.655730Z","iopub.status.idle":"2025-04-30T00:27:14.041919Z","shell.execute_reply.started":"2025-04-30T00:27:13.655690Z","shell.execute_reply":"2025-04-30T00:27:14.040913Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ROC Curve\nfpr, tpr, _ = roc_curve(y_test, y_pred)\nroc_val = auc(fpr, tpr)\n\nplt.figure()\nplt.plot(fpr, tpr, label=f'ROC curve (area = {roc_val:.2f})')\nplt.plot([0, 1], [0, 1], 'k--')\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('ROC Curve - MobileNet')\nplt.legend()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2025-04-30T00:27:14.043375Z","iopub.execute_input":"2025-04-30T00:27:14.043711Z","iopub.status.idle":"2025-04-30T00:27:14.188916Z","shell.execute_reply.started":"2025-04-30T00:27:14.043676Z","shell.execute_reply":"2025-04-30T00:27:14.187980Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"###### ","metadata":{}}]}