{"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":"import os\nimport torch\nimport torch.nn as nn\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport pydicom as dicom\nimport cv2\nimport ast\nimport glob\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:40:06.969051Z","iopub.execute_input":"2026-07-10T10:40:06.969620Z","iopub.status.idle":"2026-07-10T10:40:11.608126Z","shell.execute_reply.started":"2026-07-10T10:40:06.969594Z","shell.execute_reply":"2026-07-10T10:40:11.607494Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"path = '/kaggle/input/rsna-miccai-brain-tumor-radiogenomic-classification/'\nos.listdir(path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:40:49.209671Z","iopub.execute_input":"2026-07-10T10:40:49.210680Z","iopub.status.idle":"2026-07-10T10:40:49.217276Z","shell.execute_reply.started":"2026-07-10T10:40:49.210647Z","shell.execute_reply":"2026-07-10T10:40:49.216433Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"path = '/kaggle/input/rsna-miccai-brain-tumor-radiogenomic-classification/'\nos.listdir(path)\ntrain_data = pd.read_csv(path+'train_labels.csv')\nsamp_subm = pd.read_csv(path+'sample_submission.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:40:52.813428Z","iopub.execute_input":"2026-07-10T10:40:52.814144Z","iopub.status.idle":"2026-07-10T10:40:52.836526Z","shell.execute_reply.started":"2026-07-10T10:40:52.814115Z","shell.execute_reply":"2026-07-10T10:40:52.835528Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print('Samples train:', len(train_data))\nprint('Samples test:', len(samp_subm))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:40:56.023753Z","iopub.execute_input":"2026-07-10T10:40:56.024560Z","iopub.status.idle":"2026-07-10T10:40:56.029424Z","shell.execute_reply.started":"2026-07-10T10:40:56.024532Z","shell.execute_reply":"2026-07-10T10:40:56.028433Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:40:59.079510Z","iopub.execute_input":"2026-07-10T10:40:59.080202Z","iopub.status.idle":"2026-07-10T10:40:59.094541Z","shell.execute_reply.started":"2026-07-10T10:40:59.080176Z","shell.execute_reply":"2026-07-10T10:40:59.093621Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data[\"MGMT_value\"].value_counts().head(2).plot(kind = 'pie', autopct='%1.1f%%', figsize=(8, 8)).legend()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:42:51.629338Z","iopub.execute_input":"2026-07-10T10:42:51.630250Z","iopub.status.idle":"2026-07-10T10:42:51.982382Z","shell.execute_reply.started":"2026-07-10T10:42:51.630223Z","shell.execute_reply":"2026-07-10T10:42:51.981655Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data[\"MGMT_value\"].value_counts()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:42:56.988122Z","iopub.execute_input":"2026-07-10T10:42:56.988858Z","iopub.status.idle":"2026-07-10T10:42:56.996785Z","shell.execute_reply.started":"2026-07-10T10:42:56.988832Z","shell.execute_reply":"2026-07-10T10:42:56.995972Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"samp_subm.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:43:00.558531Z","iopub.execute_input":"2026-07-10T10:43:00.559180Z","iopub.status.idle":"2026-07-10T10:43:00.567839Z","shell.execute_reply.started":"2026-07-10T10:43:00.559153Z","shell.execute_reply":"2026-07-10T10:43:00.566858Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"folder = str(train_data.loc[0, 'BraTS21ID']).zfill(5)\nfolder","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:43:05.053656Z","iopub.execute_input":"2026-07-10T10:43:05.054316Z","iopub.status.idle":"2026-07-10T10:43:05.060496Z","shell.execute_reply.started":"2026-07-10T10:43:05.054284Z","shell.execute_reply":"2026-07-10T10:43:05.059594Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"os.listdir(path+'train/'+folder)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:43:08.428027Z","iopub.execute_input":"2026-07-10T10:43:08.428707Z","iopub.status.idle":"2026-07-10T10:43:08.438135Z","shell.execute_reply.started":"2026-07-10T10:43:08.428680Z","shell.execute_reply":"2026-07-10T10:43:08.437240Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print('Number of FLAIR images:', len(os.listdir(path+'train/'+folder+'/'+'FLAIR')))\nprint('Number of T1w images:', len(os.listdir(path+'train/'+folder+'/'+'T1w')))\nprint('Number of T1wCE images:', len(os.listdir(path+'train/'+folder+'/'+'T1wCE')))\nprint('Number of T2w images:', len(os.listdir(path+'train/'+folder+'/'+'T2w')))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:43:11.563715Z","iopub.execute_input":"2026-07-10T10:43:11.564403Z","iopub.status.idle":"2026-07-10T10:43:11.605824Z","shell.execute_reply.started":"2026-07-10T10:43:11.564374Z","shell.execute_reply":"2026-07-10T10:43:11.604845Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"path_file = ''.join([path, 'train/', folder, '/', 'FLAIR/'])\nimage = os.listdir(path_file)[0]\ndata_file = dicom.dcmread(path_file+image)\nimg = data_file.pixel_array\nprint('Image shape:', img.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:43:14.668809Z","iopub.execute_input":"2026-07-10T10:43:14.669416Z","iopub.status.idle":"2026-07-10T10:43:14.683483Z","shell.execute_reply.started":"2026-07-10T10:43:14.669389Z","shell.execute_reply":"2026-07-10T10:43:14.682510Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Flair Image\ndef plot_examples(row = 0, cat = 'FLAIR'): \n    folder = str(train_data.loc[row, 'BraTS21ID']).zfill(5)\n    path_file = ''.join([path, 'train/', folder, '/', cat, '/'])\n    images = os.listdir(path_file)\n    \n    fig, axs = plt.subplots(1, 5, figsize=(30, 30))\n    fig.subplots_adjust(hspace = .2, wspace=.2)\n    axs = axs.ravel()\n    \n    for num in range(5):\n        data_file = dicom.dcmread(path_file+images[num])\n        img = data_file.pixel_array\n        axs[num].imshow(img, cmap='gray')\n        axs[num].set_title(cat+' '+images[num])\n        axs[num].set_xticklabels([])\n        axs[num].set_yticklabels([])\n        \nrow = 0\nplot_examples(row = row, cat = 'FLAIR')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:43:17.788842Z","iopub.execute_input":"2026-07-10T10:43:17.789275Z","iopub.status.idle":"2026-07-10T10:43:18.577902Z","shell.execute_reply.started":"2026-07-10T10:43:17.789243Z","shell.execute_reply":"2026-07-10T10:43:18.577168Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#T1w Images\nplot_examples(row = row, cat = 'T1w')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:43:23.528485Z","iopub.execute_input":"2026-07-10T10:43:23.528943Z","iopub.status.idle":"2026-07-10T10:43:24.268433Z","shell.execute_reply.started":"2026-07-10T10:43:23.528918Z","shell.execute_reply":"2026-07-10T10:43:24.267587Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#T1wCE Images\nplot_examples(row = row, cat = 'T1wCE')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:43:29.563464Z","iopub.execute_input":"2026-07-10T10:43:29.563742Z","iopub.status.idle":"2026-07-10T10:43:30.303839Z","shell.execute_reply.started":"2026-07-10T10:43:29.563724Z","shell.execute_reply":"2026-07-10T10:43:30.302991Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#T2w Images\nplot_examples(row = row, cat = 'T2w')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:43:37.468610Z","iopub.execute_input":"2026-07-10T10:43:37.469050Z","iopub.status.idle":"2026-07-10T10:43:38.235037Z","shell.execute_reply.started":"2026-07-10T10:43:37.469023Z","shell.execute_reply":"2026-07-10T10:43:38.234275Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nimport pydicom\nimport tensorflow as tf\nfrom tensorflow.keras import layers, models\nfrom sklearn.model_selection import train_test_split\nimport cv2\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import classification_report, confusion_matrix, roc_curve, auc\n\n# Path dataset\npath = '/kaggle/input/rsna-miccai-brain-tumor-radiogenomic-classification/'\ntrain_labels = pd.read_csv(path + 'train_labels.csv')\n\n# Konfigurasi\nIMG_SIZE = 128\nBATCH_SIZE = 8\nEPOCHS = 50\nMODALITIES = [\n    \"FLAIR\",\n    \"T1w\",\n    \"T1wCE\",\n    \"T2w\"\n]\n\n# Fungsi untuk membaca dan memproses gambar DICOM\ndef load_dicom_image(path):\n\n    dicom = pydicom.dcmread(path)\n\n    img = dicom.pixel_array.astype(np.float32)\n\n    img = cv2.normalize(img, None, 0, 1, cv2.NORM_MINMAX)\n\n    return img\n\n# Fungsi untuk memuat data pasien\n\n\nimport glob\n\ndef load_patient_data(patient_id, img_size=128, num_slices=32):\n\n    patient_id = str(patient_id).zfill(5)\n\n    patient_path = os.path.join(path, \"train\", patient_id)\n\n    modalities = [\"FLAIR\", \"T1w\", \"T1wCE\", \"T2w\"]\n\n    modality_volumes = []\n\n    for modality in modalities:\n\n        modality_folder = os.path.join(patient_path, modality)\n\n        if not os.path.exists(modality_folder):\n            return None\n\n        dicom_files = sorted(glob.glob(os.path.join(modality_folder, \"*.dcm\")))\n\n        if len(dicom_files) == 0:\n            return None\n\n        indices = np.linspace(\n            0,\n            len(dicom_files)-1,\n            num_slices\n        ).astype(int)\n\n        slices = []\n\n        for idx in indices:\n\n            img = load_dicom_image(dicom_files[idx])\n\n            img = cv2.resize(img, (img_size, img_size))\n\n            slices.append(img)\n\n        volume = np.stack(slices, axis=0)\n\n        modality_volumes.append(volume)\n\n    # (Slices, Height, Width, 4 modalités)\n    volume = np.stack(modality_volumes, axis=-1)\n    if np.random.rand() < 0.5:\n       volume = np.flip(volume, axis=1)\n\n    if np.random.rand() < 0.5:\n       volume = np.flip(volume, axis=2)\n\n    return volume.astype(np.float32)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T11:40:52.623958Z","iopub.execute_input":"2026-07-10T11:40:52.624759Z","iopub.status.idle":"2026-07-10T11:40:52.635922Z","shell.execute_reply.started":"2026-07-10T11:40:52.624727Z","shell.execute_reply":"2026-07-10T11:40:52.635319Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Membuat dataset\nX = []\ny = []\n\nprint(\"Memuat data training...\")\nfor idx, row in train_labels.iterrows():\n    patient_id = row['BraTS21ID']\n    label = row['MGMT_value']\n\n    patient_data = load_patient_data(patient_id)\n\n    if patient_data is not None:\n        X.append(patient_data)\n        y.append(label)\n\n# Konversi ke numpy array\nX = np.array(X, dtype=np.float32)\ny = np.array(y, dtype=np.float32)\n\nprint(f\"Total data yang dimuat: {len(X)} sampel\")\nprint(f\"Distribusi kelas: {np.sum(y == 1)} positif, {np.sum(y == 0)} negatif\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:44:27.049340Z","iopub.execute_input":"2026-07-10T10:44:27.049811Z","iopub.status.idle":"2026-07-10T10:55:51.676737Z","shell.execute_reply.started":"2026-07-10T10:44:27.049788Z","shell.execute_reply":"2026-07-10T10:55:51.675704Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Split data: training (60%), validation (20%), test (20%)\nfrom sklearn.model_selection import train_test_split\nX_train, X_temp, y_train, y_temp = train_test_split(\n    X, y, test_size=0.4, random_state=42, stratify=y\n)\nX_val, X_test, y_val, y_test = train_test_split(\n    X_temp, y_temp, test_size=0.5, random_state=42, stratify=y_temp\n)\n\nprint(\"\\nDistribusi dataset:\")\nprint(f\"Training:   {len(X_train)} sampel\")\nprint(f\"Validation: {len(X_val)} sampel\")\nprint(f\"Test:       {len(X_test)} sampel\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T10:58:12.674574Z","iopub.execute_input":"2026-07-10T10:58:12.675415Z","iopub.status.idle":"2026-07-10T10:58:15.540486Z","shell.execute_reply.started":"2026-07-10T10:58:12.675385Z","shell.execute_reply":"2026-07-10T10:58:15.539451Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras import regularizers\ndef build_3d_cnn(input_shape):\n\n    model = tf.keras.Sequential([\n\n        layers.Conv3D(\n            32, 3,\n            padding='same',\n            activation='relu',\n            kernel_regularizer=regularizers.l2(1e-4),\n            input_shape=input_shape\n        ),\n        layers.BatchNormalization(),\n        layers.MaxPooling3D(2),\n\n        layers.Conv3D(\n            64, 3,\n            padding='same',\n            activation='relu',\n            kernel_regularizer=regularizers.l2(1e-4)\n        ),\n        layers.BatchNormalization(),\n        layers.MaxPooling3D(2),\n\n        layers.Conv3D(\n            128, 3,\n            padding='same',\n            activation='relu',\n            kernel_regularizer=regularizers.l2(1e-4)\n        ),\n        layers.BatchNormalization(),\n        layers.MaxPooling3D(2),\n\n        layers.Conv3D(\n            256, 3,\n            padding='same',\n            activation='relu',\n            kernel_regularizer=regularizers.l2(1e-4)\n        ),\n        layers.BatchNormalization(),\n\n        layers.GlobalAveragePooling3D(),\n\n        layers.Dense(\n            256,\n            activation='relu',\n            kernel_regularizer=regularizers.l2(1e-4)\n        ),\n        layers.Dropout(0.4),\n\n        layers.Dense(\n            128,\n            activation='relu',\n            kernel_regularizer=regularizers.l2(1e-4)\n        ),\n        layers.Dropout(0.3),\n\n        layers.Dense(1, activation='sigmoid')\n\n    ])\n\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T11:02:58.959335Z","iopub.execute_input":"2026-07-10T11:02:58.960255Z","iopub.status.idle":"2026-07-10T11:02:58.967442Z","shell.execute_reply.started":"2026-07-10T11:02:58.960208Z","shell.execute_reply":"2026-07-10T11:02:58.966529Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Bangun model\ninput_shape = (X_train.shape[1], X_train.shape[2], X_train.shape[3], X_train.shape[4])\nprint(f\"\\nInput shape: {input_shape}\")\nmodel = build_3d_cnn(input_shape)\n\n# Ringkasan model\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T11:03:05.239042Z","iopub.execute_input":"2026-07-10T11:03:05.239918Z","iopub.status.idle":"2026-07-10T11:03:07.131907Z","shell.execute_reply.started":"2026-07-10T11:03:05.239892Z","shell.execute_reply":"2026-07-10T11:03:07.130916Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Kompilasi model\nmodel.compile(\n    optimizer=tf.keras.optimizers.AdamW(\n        learning_rate=5e-5,\n        weight_decay=1e-5\n    ),\n    loss='binary_crossentropy',\n    metrics=[\n        'accuracy',\n        tf.keras.metrics.AUC(name='auc')\n    ]\n)\n# Callback\n\"\"\"\"callbacks = [\n    #tf.keras.callbacks.EarlyStopping(\n        #patience=8, \n        #monitor='val_auc', \n        #mode='max', \n        #restore_best_weights=True,\n        #verbose=1\n    #),\n    tf.keras.callbacks.ReduceLROnPlateau(\n        monitor='val_loss', \n        factor=0.2, \n        patience=3, \n        min_lr=1e-6,\n        verbose=1\n    ),\n    tf.keras.callbacks.ModelCheckpoint(\n        filepath='best_model.h5',\n        save_best_only=True,\n        monitor='val_auc',\n        mode='max',\n        verbose=1\n    )\n]\"\"\"\ncallbacks = [\n    tf.keras.callbacks.EarlyStopping(\n        monitor='val_auc',\n        patience=10,\n        mode='max',\n        restore_best_weights=True,\n        verbose=1\n    ),\n\n    tf.keras.callbacks.ReduceLROnPlateau(\n        monitor='val_loss',\n        factor=0.2,\n        patience=3,\n        min_lr=1e-6,\n        verbose=1\n    ),\n\n    tf.keras.callbacks.ModelCheckpoint(\n        'best_model.h5',\n        monitor='val_auc',\n        mode='max',\n        save_best_only=True,\n        verbose=1\n    )\n]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T11:41:35.253875Z","iopub.execute_input":"2026-07-10T11:41:35.255701Z","iopub.status.idle":"2026-07-10T11:41:35.269811Z","shell.execute_reply.started":"2026-07-10T11:41:35.255671Z","shell.execute_reply":"2026-07-10T11:41:35.269158Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Training\nfrom sklearn.utils.class_weight import compute_class_weight\nimport numpy as np\n\nweights = compute_class_weight(\n    class_weight=\"balanced\",\n    classes=np.unique(y_train),\n    y=y_train\n)\n\nclass_weights = {\n    0: weights[0],\n    1: weights[1]\n}\nprint(\"\\nMemulai training...\")\nhistory = model.fit(\n    X_train, y_train,\n    validation_data=(X_val, y_val),\n    batch_size=BATCH_SIZE,\n    epochs=EPOCHS,\n    callbacks=callbacks,\n    class_weight=class_weights\n)\n\n# Plot history training\ndef plot_history(history):\n    plt.figure(figsize=(12, 5))\n    \n    # Plot loss\n    plt.subplot(1, 2, 1)\n    plt.plot(history.history['loss'], label='Training Loss')\n    plt.plot(history.history['val_loss'], label='Validation Loss')\n    plt.title('Training and Validation Loss')\n    plt.xlabel('Epoch')\n    plt.ylabel('Loss')\n    plt.legend()\n    \n    # Plot AUC\n    plt.subplot(1, 2, 2)\n    plt.plot(history.history['auc'], label='Training AUC')\n    plt.plot(history.history['val_auc'], label='Validation AUC')\n    plt.title('Training and Validation AUC')\n    plt.xlabel('Epoch')\n    plt.ylabel('AUC')\n    plt.legend()\n    \n    plt.tight_layout()\n    plt.savefig('training_history.png')\n    plt.show()\n\nplot_history(history)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T11:41:44.783653Z","iopub.execute_input":"2026-07-10T11:41:44.784497Z","iopub.status.idle":"2026-07-10T11:44:23.969594Z","shell.execute_reply.started":"2026-07-10T11:41:44.784468Z","shell.execute_reply":"2026-07-10T11:44:23.967561Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\n\nprint(tf.executing_eagerly())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T11:13:24.053333Z","iopub.execute_input":"2026-07-10T11:13:24.053636Z","iopub.status.idle":"2026-07-10T11:13:24.058340Z","shell.execute_reply.started":"2026-07-10T11:13:24.053616Z","shell.execute_reply":"2026-07-10T11:13:24.057494Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import accuracy_score, classification_report, confusion_matrix\nimport tensorflow as tf\n\n# Charger le meilleur modèle\nmodel = tf.keras.models.load_model(\"best_model.h5\")\n\n# ===========================\n# Evaluation sur le jeu de validation\n# ===========================\nval_loss, _, val_auc = model.evaluate(X_val, y_val, verbose=0)\n\nthreshold = 0.42  \n\nval_pred_prob = model.predict(X_val, batch_size=2).flatten()\nval_pred = (val_pred_prob >= threshold).astype(int)\n\nval_acc = accuracy_score(y_val, val_pred)\n\nprint(\"========== VALIDATION ==========\")\nprint(f\"Validation Loss     : {val_loss:.4f}\")\nprint(f\"Validation AUC      : {val_auc:.4f}\")\nprint(f\"Validation Accuracy : {val_acc:.4f}\")\nprint(classification_report(y_val, val_pred))\nprint(confusion_matrix(y_val, val_pred))\n\n\n# ===========================\n# Evaluation sur le jeu de test\n# ===========================\ntest_loss, _, test_auc = model.evaluate(X_test, y_test, verbose=0)\n\ntest_pred_prob = model.predict(X_test, batch_size=2).flatten()\ntest_pred = (test_pred_prob >= threshold).astype(int)\n\ntest_acc = accuracy_score(y_test, test_pred)\n\nprint(\"\\n========== TEST ==========\")\nprint(f\"Test Loss     : {test_loss:.4f}\")\nprint(f\"Test AUC      : {test_auc:.4f}\")\nprint(f\"Test Accuracy : {test_acc:.4f}\")\nprint(classification_report(y_test, test_pred))\nprint(confusion_matrix(y_test, test_pred))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T11:59:58.570024Z","iopub.execute_input":"2026-07-10T11:59:58.570919Z","iopub.status.idle":"2026-07-10T12:00:22.896546Z","shell.execute_reply.started":"2026-07-10T11:59:58.570888Z","shell.execute_reply":"2026-07-10T12:00:22.895290Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Prediksi pada test set\ny_pred_prob = model.predict(X_test).flatten()\ny_pred = (y_pred_prob > 0.42).astype(int)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T11:47:30.713557Z","iopub.execute_input":"2026-07-10T11:47:30.714258Z","iopub.status.idle":"2026-07-10T11:47:35.800274Z","shell.execute_reply.started":"2026-07-10T11:47:30.714185Z","shell.execute_reply":"2026-07-10T11:47:35.799529Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import accuracy_score\n\nprint(\"Accuracy sklearn :\", accuracy_score(y_test, y_pred))\nprint(\"Accuracy keras   :\", test_acc)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T11:47:40.948506Z","iopub.execute_input":"2026-07-10T11:47:40.948774Z","iopub.status.idle":"2026-07-10T11:47:40.956519Z","shell.execute_reply.started":"2026-07-10T11:47:40.948756Z","shell.execute_reply":"2026-07-10T11:47:40.955507Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Plot ROC curve\nfpr, tpr, thresholds = roc_curve(y_test, y_pred_prob)\nroc_auc = auc(fpr, tpr)\n\nplt.figure()\nplt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})')\nplt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver Operating Characteristic')\nplt.legend(loc=\"lower right\")\nplt.savefig('roc_curve.png')\nplt.show()","metadata":{"trusted":true,"execution":{"execution_failed":"2026-07-10T10:36:29.295Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Simpan model akhir\nmodel.save('final_model.h5')\nprint(\"\\nModel akhir disimpan sebagai 'final_model.h5'\")","metadata":{"trusted":true,"execution":{"execution_failed":"2026-07-10T10:36:29.295Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nprint(os.path.exists(\"best_model.h5\"))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-07-10T11:33:37.488395Z","iopub.execute_input":"2026-07-10T11:33:37.489081Z","iopub.status.idle":"2026-07-10T11:33:37.494129Z","shell.execute_reply.started":"2026-07-10T11:33:37.489054Z","shell.execute_reply":"2026-07-10T11:33:37.493055Z"}},"outputs":[],"execution_count":null}]}