{"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":"none","dataSources":[{"sourceId":29653,"databundleVersionId":2420395,"sourceType":"competition"}],"dockerImageVersionId":30918,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"InceptionV3","metadata":{}},{"cell_type":"code","source":"# Import libraries\nimport numpy as np\nimport pandas as pd\nimport os\nimport cv2\nimport pydicom\nimport warnings\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 InceptionV3\nfrom tensorflow.keras.callbacks import EarlyStopping\n\n# 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\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # Suppress TensorFlow warnings (INFO and WARNING)\nwarnings.filterwarnings('ignore')  # Suppress Python warnings in general\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-07T00:18:09.847285Z","iopub.execute_input":"2025-05-07T00:18:09.847659Z","iopub.status.idle":"2025-05-07T00:18:09.865478Z","shell.execute_reply.started":"2025-05-07T00:18:09.847631Z","shell.execute_reply":"2025-05-07T00:18:09.864375Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load images\ndef load_image(patient_id, img_size=(150,150)):\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,150,150,1)\ny = np.array(y)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-07T00:18:09.866869Z","iopub.execute_input":"2025-05-07T00:18:09.867172Z","iopub.status.idle":"2025-05-07T00:18:12.716803Z","shell.execute_reply.started":"2025-05-07T00:18:09.867149Z","shell.execute_reply":"2025-05-07T00:18:12.715704Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Prepare dataset\nX = np.repeat(X, 3, axis=-1)  # InceptionV3 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-05-07T00:18:12.718878Z","iopub.execute_input":"2025-05-07T00:18:12.719144Z","iopub.status.idle":"2025-05-07T00:18:13.034462Z","shell.execute_reply.started":"2025-05-07T00:18:12.719121Z","shell.execute_reply":"2025-05-07T00:18:13.033365Z"}},"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()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-07T00:18:13.035803Z","iopub.execute_input":"2025-05-07T00:18:13.036080Z","iopub.status.idle":"2025-05-07T00:18:13.737763Z","shell.execute_reply.started":"2025-05-07T00:18:13.036057Z","shell.execute_reply":"2025-05-07T00:18:13.736644Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-07T00:18:13.738867Z","iopub.execute_input":"2025-05-07T00:18:13.739142Z","iopub.status.idle":"2025-05-07T00:18:13.817191Z","shell.execute_reply.started":"2025-05-07T00:18:13.739122Z","shell.execute_reply":"2025-05-07T00:18:13.816369Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Build InceptionV3 model\nbase_model = InceptionV3(weights=None, include_top=False, input_shape=(150,150,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\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-07T00:18:13.818079Z","iopub.execute_input":"2025-05-07T00:18:13.818383Z","iopub.status.idle":"2025-05-07T00:18:15.085558Z","shell.execute_reply.started":"2025-05-07T00:18:13.818359Z","shell.execute_reply":"2025-05-07T00:18:15.084645Z"}},"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-05-07T00:18:15.086698Z","iopub.execute_input":"2025-05-07T00:18:15.087076Z","iopub.status.idle":"2025-05-07T00:22:39.613308Z","shell.execute_reply.started":"2025-05-07T00:18:15.087028Z","shell.execute_reply":"2025-05-07T00:22:39.612124Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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-05-07T00:22:39.616201Z","iopub.execute_input":"2025-05-07T00:22:39.616528Z","iopub.status.idle":"2025-05-07T00:22:48.908477Z","shell.execute_reply.started":"2025-05-07T00:22:39.616503Z","shell.execute_reply":"2025-05-07T00:22:48.907646Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-07T00:22:48.915318Z","iopub.execute_input":"2025-05-07T00:22:48.915647Z","iopub.status.idle":"2025-05-07T00:22:48.927473Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(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":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-07T00:22:48.931066Z","iopub.execute_input":"2025-05-07T00:22:48.931423Z","iopub.status.idle":"2025-05-07T00:22:48.948131Z"}},"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()\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-07T00:22:48.951428Z","iopub.execute_input":"2025-05-07T00:22:48.951738Z","iopub.status.idle":"2025-05-07T00:22:49.420667Z"}},"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 - InceptionV3')\nplt.legend()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-07T00:22:49.424267Z","iopub.execute_input":"2025-05-07T00:22:49.424654Z","iopub.status.idle":"2025-05-07T00:22:49.627459Z"}},"outputs":[],"execution_count":null}]}