init project
This commit is contained in:
commit
541d9279d9
4518
DataSet-Pasien_RawatInap_Jalan.csv
Normal file
4518
DataSet-Pasien_RawatInap_Jalan.csv
Normal file
File diff suppressed because it is too large
Load Diff
556
Klasifikasi_Rawat_Inap_Jalan_CBC.ipynb
Normal file
556
Klasifikasi_Rawat_Inap_Jalan_CBC.ipynb
Normal file
@ -0,0 +1,556 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Klasifikasi Rawat Inap vs Rawat Jalan dari Data CBC\n",
|
||||||
|
"**Algoritma yang dibandingkan:** Logistic Regression dan Gradient Boosting\n",
|
||||||
|
"\n",
|
||||||
|
"Alur notebook:\n",
|
||||||
|
"1. Setup dan load data\n",
|
||||||
|
"2. Exploratory Data Analysis (EDA)\n",
|
||||||
|
"3. Preprocessing dan stratified split 80/20\n",
|
||||||
|
"4. Training dan hyperparameter tuning (5-fold stratified CV)\n",
|
||||||
|
"5. Testing dan komparasi performa (termasuk Sensitivity/Recall dan Specificity)\n",
|
||||||
|
"6. Interpretasi model\n",
|
||||||
|
"7. Analisis threshold\n",
|
||||||
|
"8. Menyimpan model dan prediksi pasien baru\n",
|
||||||
|
"\n",
|
||||||
|
"> Kelas **positif = rawat inap (1)**, kelas negatif = rawat jalan (0).\n",
|
||||||
|
"> Model ini adalah alat bantu keputusan, bukan pengganti penilaian klinis dokter."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 1. Setup dan Load Data"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"import time, warnings\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"import matplotlib.pyplot as plt\n",
|
||||||
|
"import seaborn as sns\n",
|
||||||
|
"import joblib\n",
|
||||||
|
"\n",
|
||||||
|
"from sklearn.model_selection import train_test_split, StratifiedKFold, GridSearchCV, cross_validate\n",
|
||||||
|
"from sklearn.pipeline import Pipeline\n",
|
||||||
|
"from sklearn.preprocessing import StandardScaler\n",
|
||||||
|
"from sklearn.linear_model import LogisticRegression\n",
|
||||||
|
"from sklearn.ensemble import GradientBoostingClassifier\n",
|
||||||
|
"from sklearn.metrics import (accuracy_score, precision_score, recall_score, f1_score,\n",
|
||||||
|
" roc_auc_score, average_precision_score, balanced_accuracy_score,\n",
|
||||||
|
" confusion_matrix, classification_report,\n",
|
||||||
|
" RocCurveDisplay, PrecisionRecallDisplay)\n",
|
||||||
|
"\n",
|
||||||
|
"warnings.filterwarnings(\"ignore\")\n",
|
||||||
|
"sns.set_theme(style=\"whitegrid\")\n",
|
||||||
|
"RANDOM_STATE = 42"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Di Google Colab: akan muncul tombol upload. Pilih file DataSet-Pasien_RawatInap_Jalan.csv\n",
|
||||||
|
"# Di luar Colab: jalankan dengan CSV di folder yang sama, atau ubah CSV_PATH.\n",
|
||||||
|
"CSV_NAME = \"DataSet-Pasien_RawatInap_Jalan.csv\"\n",
|
||||||
|
"CSV_PATH = CSV_NAME\n",
|
||||||
|
"\n",
|
||||||
|
"try:\n",
|
||||||
|
" from google.colab import files\n",
|
||||||
|
" uploaded = files.upload()\n",
|
||||||
|
" CSV_PATH = list(uploaded.keys())[0]\n",
|
||||||
|
"except ImportError:\n",
|
||||||
|
" pass\n",
|
||||||
|
"\n",
|
||||||
|
"df = pd.read_csv(CSV_PATH)\n",
|
||||||
|
"print(\"Ukuran data:\", df.shape)\n",
|
||||||
|
"df.head()"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Pembersihan dasar\n",
|
||||||
|
"print(\"Missing values per kolom:\")\n",
|
||||||
|
"print(df.isna().sum(), \"\\n\")\n",
|
||||||
|
"\n",
|
||||||
|
"n_dup = df.duplicated().sum()\n",
|
||||||
|
"print(\"Jumlah baris duplikat:\", n_dup)\n",
|
||||||
|
"df = df.drop_duplicates().reset_index(drop=True)\n",
|
||||||
|
"\n",
|
||||||
|
"# Pastikan label konsisten, lalu encode target: rawat inap = 1, rawat jalan = 0\n",
|
||||||
|
"df[\"SOURCE\"] = df[\"SOURCE\"].str.strip().str.lower()\n",
|
||||||
|
"df[\"target\"] = (df[\"SOURCE\"] == \"rawat inap\").astype(int)\n",
|
||||||
|
"\n",
|
||||||
|
"FEATURES = [c for c in df.columns if c not in (\"SOURCE\", \"target\")]\n",
|
||||||
|
"print(\"\\nFitur:\", FEATURES)\n",
|
||||||
|
"print(\"Ukuran data setelah dibersihkan:\", df.shape)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 2. Exploratory Data Analysis"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"df[FEATURES].describe().T.round(2)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Proporsi kelas\n",
|
||||||
|
"counts = df[\"SOURCE\"].value_counts()\n",
|
||||||
|
"pct = df[\"SOURCE\"].value_counts(normalize=True).mul(100).round(1)\n",
|
||||||
|
"print(pd.DataFrame({\"jumlah\": counts, \"persen\": pct}))\n",
|
||||||
|
"\n",
|
||||||
|
"fig, ax = plt.subplots(figsize=(5, 3.5))\n",
|
||||||
|
"sns.countplot(data=df, x=\"SOURCE\", order=counts.index, ax=ax)\n",
|
||||||
|
"for p in ax.patches:\n",
|
||||||
|
" ax.annotate(int(p.get_height()), (p.get_x() + p.get_width()/2, p.get_height()),\n",
|
||||||
|
" ha=\"center\", va=\"bottom\")\n",
|
||||||
|
"ax.set_title(\"Distribusi Kelas Target\")\n",
|
||||||
|
"ax.set_xlabel(\"\")\n",
|
||||||
|
"plt.tight_layout(); plt.show()"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Distribusi tiap fitur per kelas\n",
|
||||||
|
"fig, axes = plt.subplots(2, 4, figsize=(18, 8))\n",
|
||||||
|
"for ax, col in zip(axes.ravel(), FEATURES):\n",
|
||||||
|
" sns.kdeplot(data=df, x=col, hue=\"SOURCE\", fill=True, common_norm=False, ax=ax)\n",
|
||||||
|
" ax.set_title(col)\n",
|
||||||
|
"plt.suptitle(\"Distribusi Fitur per Kelas\", y=1.02, fontsize=14)\n",
|
||||||
|
"plt.tight_layout(); plt.show()"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Boxplot untuk melihat outlier dan perbedaan antar kelas\n",
|
||||||
|
"fig, axes = plt.subplots(2, 4, figsize=(18, 8))\n",
|
||||||
|
"for ax, col in zip(axes.ravel(), FEATURES):\n",
|
||||||
|
" sns.boxplot(data=df, x=\"SOURCE\", y=col, ax=ax)\n",
|
||||||
|
" ax.set_xlabel(\"\")\n",
|
||||||
|
" ax.set_title(col)\n",
|
||||||
|
"plt.suptitle(\"Boxplot Fitur per Kelas\", y=1.02, fontsize=14)\n",
|
||||||
|
"plt.tight_layout(); plt.show()\n",
|
||||||
|
"\n",
|
||||||
|
"# Catatan: nilai ekstrem pada CBC bisa merupakan kondisi klinis nyata, sehingga TIDAK dibuang."
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Korelasi antar fitur\n",
|
||||||
|
"plt.figure(figsize=(8, 6.5))\n",
|
||||||
|
"sns.heatmap(df[FEATURES + [\"target\"]].corr(), annot=True, fmt=\".2f\", cmap=\"coolwarm\", center=0)\n",
|
||||||
|
"plt.title(\"Matriks Korelasi\")\n",
|
||||||
|
"plt.tight_layout(); plt.show()"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 3. Preprocessing dan Stratified Split (80% train / 20% test)\n",
|
||||||
|
"`stratify=y` menjaga proporsi rawat inap vs rawat jalan **tetap sama** di data training dan testing.\n",
|
||||||
|
"Scaling dilakukan di dalam `Pipeline` untuk Logistic Regression, sehingga statistik scaler hanya dihitung\n",
|
||||||
|
"dari data training (tidak ada kebocoran dari data test)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"X = df[FEATURES]\n",
|
||||||
|
"y = df[\"target\"]\n",
|
||||||
|
"\n",
|
||||||
|
"X_train, X_test, y_train, y_test = train_test_split(\n",
|
||||||
|
" X, y, test_size=0.20, stratify=y, random_state=RANDOM_STATE\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"def komposisi(nama, yy):\n",
|
||||||
|
" n = len(yy); inap = int(yy.sum())\n",
|
||||||
|
" print(f\"{nama:<10}: {n:>5} data | rawat inap {inap:>4} ({inap/n*100:.1f}%) | rawat jalan {n-inap:>4} ({(n-inap)/n*100:.1f}%)\")\n",
|
||||||
|
"\n",
|
||||||
|
"komposisi(\"Seluruh\", y)\n",
|
||||||
|
"komposisi(\"Training\", y_train)\n",
|
||||||
|
"komposisi(\"Testing\", y_test)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 4. Training dan Hyperparameter Tuning\n",
|
||||||
|
"Kedua model dilatih dan di-tuning dengan **stratified 5-fold cross-validation pada data training saja**.\n",
|
||||||
|
"Metrik tuning: ROC-AUC (tidak bergantung pada threshold dan tidak terpengaruh ketidakseimbangan kelas ringan)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=RANDOM_STATE)\n",
|
||||||
|
"\n",
|
||||||
|
"# --- Logistic Regression (butuh scaling) ---\n",
|
||||||
|
"pipe_lr = Pipeline([\n",
|
||||||
|
" (\"scaler\", StandardScaler()),\n",
|
||||||
|
" (\"clf\", LogisticRegression(max_iter=5000, random_state=RANDOM_STATE)),\n",
|
||||||
|
"])\n",
|
||||||
|
"grid_lr = {\"clf__C\": [0.01, 0.1, 1, 10, 100]}\n",
|
||||||
|
"\n",
|
||||||
|
"# --- Gradient Boosting (tidak sensitif terhadap skala fitur) ---\n",
|
||||||
|
"pipe_gb = Pipeline([\n",
|
||||||
|
" (\"clf\", GradientBoostingClassifier(random_state=RANDOM_STATE)),\n",
|
||||||
|
"])\n",
|
||||||
|
"grid_gb = {\n",
|
||||||
|
" \"clf__n_estimators\": [100, 200],\n",
|
||||||
|
" \"clf__learning_rate\": [0.05, 0.1],\n",
|
||||||
|
" \"clf__max_depth\": [2, 3, 4],\n",
|
||||||
|
" \"clf__subsample\": [0.8, 1.0],\n",
|
||||||
|
"}\n",
|
||||||
|
"\n",
|
||||||
|
"searches = {\n",
|
||||||
|
" \"Logistic Regression\": GridSearchCV(pipe_lr, grid_lr, cv=cv, scoring=\"roc_auc\", n_jobs=-1),\n",
|
||||||
|
" \"Gradient Boosting\": GridSearchCV(pipe_gb, grid_gb, cv=cv, scoring=\"roc_auc\", n_jobs=-1),\n",
|
||||||
|
"}\n",
|
||||||
|
"\n",
|
||||||
|
"train_time = {}\n",
|
||||||
|
"for name, gs in searches.items():\n",
|
||||||
|
" t0 = time.time()\n",
|
||||||
|
" gs.fit(X_train, y_train)\n",
|
||||||
|
" train_time[name] = time.time() - t0\n",
|
||||||
|
" print(f\"{name}\\n best params : {gs.best_params_}\\n CV ROC-AUC : {gs.best_score_:.4f}\\n waktu tuning: {train_time[name]:.1f} dtk\\n\")\n",
|
||||||
|
"\n",
|
||||||
|
"best_models = {name: gs.best_estimator_ for name, gs in searches.items()}"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Cross-validation 5-fold dengan beberapa metrik (pada data training) untuk melihat performa dan stabilitas\n",
|
||||||
|
"scoring = {\"accuracy\": \"accuracy\", \"precision\": \"precision\", \"recall\": \"recall\",\n",
|
||||||
|
" \"f1\": \"f1\", \"roc_auc\": \"roc_auc\"}\n",
|
||||||
|
"\n",
|
||||||
|
"rows = []\n",
|
||||||
|
"for name, model in best_models.items():\n",
|
||||||
|
" res = cross_validate(model, X_train, y_train, cv=cv, scoring=scoring, n_jobs=-1)\n",
|
||||||
|
" row = {\"Model\": name}\n",
|
||||||
|
" for m in scoring:\n",
|
||||||
|
" row[m] = f\"{res['test_' + m].mean():.3f} ± {res['test_' + m].std():.3f}\"\n",
|
||||||
|
" rows.append(row)\n",
|
||||||
|
"\n",
|
||||||
|
"cv_table = pd.DataFrame(rows).set_index(\"Model\")\n",
|
||||||
|
"print(\"Hasil 5-fold CV pada data training (mean ± std):\")\n",
|
||||||
|
"cv_table"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 5. Testing dan Komparasi Performa\n",
|
||||||
|
"Evaluasi dilakukan **satu kali** pada data test yang tidak pernah dipakai untuk training maupun tuning.\n",
|
||||||
|
"\n",
|
||||||
|
"Metrik yang dilaporkan:\n",
|
||||||
|
"- **Recall / Sensitivity** (kelas rawat inap): dari semua pasien yang memang butuh rawat inap, berapa yang terdeteksi.\n",
|
||||||
|
"- **Specificity** (kelas rawat jalan): dari semua pasien rawat jalan, berapa yang diprediksi benar sebagai rawat jalan. Specificity rendah berarti banyak rawat inap yang sebenarnya tidak perlu.\n",
|
||||||
|
"- **Precision**: dari semua prediksi rawat inap, berapa yang benar.\n",
|
||||||
|
"- **ROC-AUC dan PR-AUC**: kemampuan memisahkan kelas pada semua threshold."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"def evaluate(model, X_, y_, threshold=0.5):\n",
|
||||||
|
" proba = model.predict_proba(X_)[:, 1]\n",
|
||||||
|
" pred = (proba >= threshold).astype(int)\n",
|
||||||
|
" tn, fp, fn, tp = confusion_matrix(y_, pred).ravel()\n",
|
||||||
|
" return {\n",
|
||||||
|
" \"Accuracy\": accuracy_score(y_, pred),\n",
|
||||||
|
" \"Balanced Accuracy\": balanced_accuracy_score(y_, pred),\n",
|
||||||
|
" \"Precision\": precision_score(y_, pred),\n",
|
||||||
|
" \"Recall (Sensitivity)\": recall_score(y_, pred),\n",
|
||||||
|
" \"Specificity\": tn / (tn + fp),\n",
|
||||||
|
" \"F1-score\": f1_score(y_, pred),\n",
|
||||||
|
" \"ROC-AUC\": roc_auc_score(y_, proba),\n",
|
||||||
|
" \"PR-AUC\": average_precision_score(y_, proba),\n",
|
||||||
|
" \"TP\": tp, \"FN\": fn, \"TN\": tn, \"FP\": fp,\n",
|
||||||
|
" }\n",
|
||||||
|
"\n",
|
||||||
|
"results = {name: evaluate(m, X_test, y_test) for name, m in best_models.items()}\n",
|
||||||
|
"results_df = pd.DataFrame(results).T\n",
|
||||||
|
"results_df[\"Waktu tuning (dtk)\"] = pd.Series(train_time)\n",
|
||||||
|
"\n",
|
||||||
|
"metric_cols = [\"Accuracy\", \"Balanced Accuracy\", \"Precision\", \"Recall (Sensitivity)\",\n",
|
||||||
|
" \"Specificity\", \"F1-score\", \"ROC-AUC\", \"PR-AUC\"]\n",
|
||||||
|
"print(\"Hasil pada DATA TEST (threshold 0.5):\")\n",
|
||||||
|
"results_df[metric_cols + [\"Waktu tuning (dtk)\"]].round(4)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Visual komparasi metrik\n",
|
||||||
|
"plot_df = results_df[metric_cols].astype(float).T\n",
|
||||||
|
"ax = plot_df.plot(kind=\"bar\", figsize=(11, 5), rot=30)\n",
|
||||||
|
"ax.set_ylim(0, 1)\n",
|
||||||
|
"ax.set_title(\"Komparasi Performa pada Data Test\")\n",
|
||||||
|
"ax.set_ylabel(\"Skor\")\n",
|
||||||
|
"for c in ax.containers:\n",
|
||||||
|
" ax.bar_label(c, fmt=\"%.2f\", fontsize=8, padding=2)\n",
|
||||||
|
"plt.tight_layout(); plt.show()"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Confusion matrix\n",
|
||||||
|
"fig, axes = plt.subplots(1, 2, figsize=(11, 4.2))\n",
|
||||||
|
"labels = [\"Rawat Jalan\", \"Rawat Inap\"]\n",
|
||||||
|
"for ax, (name, m) in zip(axes, best_models.items()):\n",
|
||||||
|
" cm = confusion_matrix(y_test, m.predict(X_test))\n",
|
||||||
|
" sns.heatmap(cm, annot=True, fmt=\"d\", cmap=\"Blues\", cbar=False,\n",
|
||||||
|
" xticklabels=labels, yticklabels=labels, ax=ax)\n",
|
||||||
|
" ax.set_title(name); ax.set_xlabel(\"Prediksi\"); ax.set_ylabel(\"Aktual\")\n",
|
||||||
|
"plt.tight_layout(); plt.show()"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Kurva ROC dan Precision-Recall\n",
|
||||||
|
"fig, axes = plt.subplots(1, 2, figsize=(12, 4.8))\n",
|
||||||
|
"for name, m in best_models.items():\n",
|
||||||
|
" RocCurveDisplay.from_estimator(m, X_test, y_test, name=name, ax=axes[0])\n",
|
||||||
|
" PrecisionRecallDisplay.from_estimator(m, X_test, y_test, name=name, ax=axes[1])\n",
|
||||||
|
"axes[0].plot([0, 1], [0, 1], \"k--\", alpha=0.4)\n",
|
||||||
|
"axes[0].set_title(\"Kurva ROC\"); axes[1].set_title(\"Kurva Precision-Recall\")\n",
|
||||||
|
"plt.tight_layout(); plt.show()"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"for name, m in best_models.items():\n",
|
||||||
|
" print(\"=\" * 60, \"\\n\", name, \"\\n\" + \"=\" * 60)\n",
|
||||||
|
" print(classification_report(y_test, m.predict(X_test),\n",
|
||||||
|
" target_names=[\"Rawat Jalan\", \"Rawat Inap\"], digits=3))"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 6. Interpretasi Model"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Logistic Regression: koefisien pada fitur yang sudah di-standardisasi\n",
|
||||||
|
"lr_clf = best_models[\"Logistic Regression\"].named_steps[\"clf\"]\n",
|
||||||
|
"coef = pd.Series(lr_clf.coef_[0], index=FEATURES).sort_values()\n",
|
||||||
|
"\n",
|
||||||
|
"# Gradient Boosting: feature importance\n",
|
||||||
|
"gb_clf = best_models[\"Gradient Boosting\"].named_steps[\"clf\"]\n",
|
||||||
|
"imp = pd.Series(gb_clf.feature_importances_, index=FEATURES).sort_values()\n",
|
||||||
|
"\n",
|
||||||
|
"fig, axes = plt.subplots(1, 2, figsize=(14, 5))\n",
|
||||||
|
"coef.plot(kind=\"barh\", ax=axes[0], color=np.where(coef > 0, \"tab:red\", \"tab:blue\"))\n",
|
||||||
|
"axes[0].set_title(\"Logistic Regression: koefisien (fitur ter-standardisasi)\\nmerah = mendorong ke rawat inap\")\n",
|
||||||
|
"axes[0].axvline(0, color=\"k\", lw=0.8)\n",
|
||||||
|
"imp.plot(kind=\"barh\", ax=axes[1], color=\"tab:green\")\n",
|
||||||
|
"axes[1].set_title(\"Gradient Boosting: feature importance\")\n",
|
||||||
|
"plt.tight_layout(); plt.show()"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Permutation importance pada data test (perbandingan yang adil antar kedua model, berbasis ROC-AUC)\n",
|
||||||
|
"from sklearn.inspection import permutation_importance\n",
|
||||||
|
"\n",
|
||||||
|
"perm = {}\n",
|
||||||
|
"for name, m in best_models.items():\n",
|
||||||
|
" r = permutation_importance(m, X_test, y_test, scoring=\"roc_auc\",\n",
|
||||||
|
" n_repeats=20, random_state=RANDOM_STATE, n_jobs=-1)\n",
|
||||||
|
" perm[name] = pd.Series(r.importances_mean, index=FEATURES)\n",
|
||||||
|
"\n",
|
||||||
|
"perm_df = pd.DataFrame(perm).sort_values(\"Gradient Boosting\", ascending=False)\n",
|
||||||
|
"perm_df.plot(kind=\"bar\", figsize=(10, 4.5), rot=30)\n",
|
||||||
|
"plt.title(\"Permutation Importance (penurunan ROC-AUC saat fitur diacak)\")\n",
|
||||||
|
"plt.ylabel(\"Penurunan ROC-AUC\")\n",
|
||||||
|
"plt.tight_layout(); plt.show()\n",
|
||||||
|
"perm_df.round(4)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 7. Analisis Threshold\n",
|
||||||
|
"Default threshold 0.5 belum tentu optimal secara klinis. Menurunkan threshold menaikkan Recall (lebih sedikit\n",
|
||||||
|
"pasien rawat inap yang terlewat) dengan konsekuensi Specificity turun (lebih banyak rawat inap yang tidak perlu).\n",
|
||||||
|
"\n",
|
||||||
|
"> Tabel di bawah bersifat **ilustratif** untuk memahami trade-off. Pemilihan threshold final harus berdasarkan\n",
|
||||||
|
"> pertimbangan klinis dan dilakukan dengan data validasi, bukan dengan melihat data test."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"thresholds = [0.3, 0.4, 0.5, 0.6, 0.7]\n",
|
||||||
|
"rows = []\n",
|
||||||
|
"for name, m in best_models.items():\n",
|
||||||
|
" for t in thresholds:\n",
|
||||||
|
" r = evaluate(m, X_test, y_test, threshold=t)\n",
|
||||||
|
" rows.append({\"Model\": name, \"Threshold\": t,\n",
|
||||||
|
" \"Recall (Sensitivity)\": r[\"Recall (Sensitivity)\"],\n",
|
||||||
|
" \"Specificity\": r[\"Specificity\"],\n",
|
||||||
|
" \"Precision\": r[\"Precision\"], \"F1-score\": r[\"F1-score\"]})\n",
|
||||||
|
"pd.DataFrame(rows).round(3)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 8. Menyimpan Model dan Prediksi Pasien Baru\n",
|
||||||
|
"Model terbaik dipilih berdasarkan **ROC-AUC pada data test**."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"best_name = results_df[\"ROC-AUC\"].astype(float).idxmax()\n",
|
||||||
|
"print(\"Model terbaik berdasarkan ROC-AUC test:\", best_name)\n",
|
||||||
|
"\n",
|
||||||
|
"final_model = best_models[best_name]\n",
|
||||||
|
"joblib.dump({\"model\": final_model, \"features\": FEATURES, \"model_name\": best_name},\n",
|
||||||
|
" \"model_klasifikasi_rawat.joblib\")\n",
|
||||||
|
"print(\"Model disimpan: model_klasifikasi_rawat.joblib\")\n",
|
||||||
|
"\n",
|
||||||
|
"# Download otomatis jika berjalan di Colab\n",
|
||||||
|
"try:\n",
|
||||||
|
" from google.colab import files\n",
|
||||||
|
" files.download(\"model_klasifikasi_rawat.joblib\")\n",
|
||||||
|
"except ImportError:\n",
|
||||||
|
" pass"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"def prediksi_pasien(hematokrit, hemoglobin, eritrosit, lekosit, trombosit, mch, mchc, mcv,\n",
|
||||||
|
" model_path=\"model_klasifikasi_rawat.joblib\", threshold=0.5):\n",
|
||||||
|
" \"\"\"Memprediksi rawat inap/rawat jalan untuk satu pasien baru berdasarkan 8 parameter CBC.\"\"\"\n",
|
||||||
|
" bundle = joblib.load(model_path)\n",
|
||||||
|
" nilai = [hematokrit, hemoglobin, eritrosit, lekosit, trombosit, mch, mchc, mcv]\n",
|
||||||
|
" data = pd.DataFrame([nilai], columns=bundle[\"features\"])\n",
|
||||||
|
" p_inap = bundle[\"model\"].predict_proba(data)[0, 1]\n",
|
||||||
|
" return {\n",
|
||||||
|
" \"prediksi\": \"RAWAT INAP\" if p_inap >= threshold else \"RAWAT JALAN\",\n",
|
||||||
|
" \"probabilitas_rawat_inap\": round(float(p_inap), 4),\n",
|
||||||
|
" \"probabilitas_rawat_jalan\": round(float(1 - p_inap), 4),\n",
|
||||||
|
" \"model\": bundle[\"model_name\"],\n",
|
||||||
|
" }\n",
|
||||||
|
"\n",
|
||||||
|
"# Contoh: urutan input sama dengan kolom dataset\n",
|
||||||
|
"print(\"Urutan fitur:\", FEATURES)\n",
|
||||||
|
"contoh = X_test.iloc[0].tolist()\n",
|
||||||
|
"print(\"Nilai contoh:\", contoh, \"| label aktual:\", \"rawat inap\" if y_test.iloc[0] == 1 else \"rawat jalan\")\n",
|
||||||
|
"prediksi_pasien(*contoh)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"colab": {
|
||||||
|
"provenance": []
|
||||||
|
},
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"name": "python"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 0
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user