fudan-renjun commited on
Commit
f685ac7
·
verified ·
1 Parent(s): 5a463e9

Upload 4 files

Browse files
Files changed (4) hide show
  1. README .md +41 -0
  2. app.py +738 -0
  3. hospital_logo.png +0 -0
  4. requirements.txt +10 -0
README .md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: ML Binary Classification Pipeline
3
+ emoji: 🧬
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 5.12.0
8
+ app_file: app.py
9
+ python_version: 3.11.11
10
+ pinned: false
11
+ license: mit
12
+ ---
13
+
14
+ # 🧬 ML Binary Classification Pipeline
15
+
16
+ Machine learning binary classification training & evaluation platform.
17
+
18
+ ## Features
19
+
20
+ - **8 Models**: RF, DT, KNN, XGB, AdaBoost, LR, NB, SVM
21
+ - **Interactive Model Selection**: Choose any combination of models
22
+ - **Hyperparameter Tuning**: GridSearchCV with configurable folds
23
+ - **DeLong Test**: Statistical comparison between models
24
+ - **SHAP Analysis**: Feature importance with beeswarm plots
25
+ - **Feature Ablation**: Optimal feature subset selection
26
+ - **External Validation**: ROC, PR, DCA curves, confusion matrix
27
+ - **ZIP Download**: All results packaged for download
28
+
29
+ ## Data Format
30
+
31
+ CSV files with:
32
+ - Column 1: Label (0/1)
33
+ - Column 2: Any (e.g., ID)
34
+ - Column 3+: Features
35
+
36
+ ## Output Files
37
+
38
+ - PDF/PNG charts (ROC, PR, DCA, confusion matrices, SHAP plots)
39
+ - Excel files (model metrics, feature ablation, external validation)
40
+ - Best parameters text file
41
+ - Final model pickle file
app.py ADDED
@@ -0,0 +1,738 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ML Binary Classification Pipeline
3
+ Eye & ENT Hospital of Fudan University — Laboratory Medicine, Ren Jun
4
+ Gradio 5.12.0 + Python 3.11
5
+ """
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ import matplotlib
10
+ matplotlib.use('Agg')
11
+ import matplotlib.pyplot as plt
12
+ from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
13
+ from sklearn.tree import DecisionTreeClassifier
14
+ from sklearn.neighbors import KNeighborsClassifier
15
+ from sklearn.linear_model import LogisticRegression
16
+ from sklearn.naive_bayes import GaussianNB
17
+ from sklearn.svm import SVC
18
+ from xgboost import XGBClassifier
19
+ from sklearn.model_selection import StratifiedKFold, GridSearchCV
20
+ from sklearn.metrics import (
21
+ roc_auc_score, confusion_matrix, roc_curve,
22
+ auc as auc_score, precision_recall_curve
23
+ )
24
+ import seaborn as sns
25
+ import warnings
26
+ from scipy import stats
27
+ import os
28
+ import shap
29
+ import pickle
30
+ from copy import deepcopy
31
+ import zipfile
32
+ import tempfile
33
+ import traceback
34
+ import gradio as gr
35
+
36
+ warnings.filterwarnings('ignore')
37
+ plt.rcParams['font.sans-serif'] = ['DejaVu Sans']
38
+ plt.rcParams['axes.unicode_minus'] = False
39
+
40
+ # ============================================================================
41
+ # Helper Functions
42
+ # ============================================================================
43
+ def compute_midrank(x):
44
+ J = np.argsort(x); Z = x[J]; N = len(x)
45
+ T = np.zeros(N, dtype=float); i = 0
46
+ while i < N:
47
+ j = i
48
+ while j < N and Z[j] == Z[i]: j += 1
49
+ T[i:j] = 0.5 * (i + j - 1); i = j
50
+ T2 = np.empty(N, dtype=float); T2[J] = T + 1
51
+ return T2
52
+
53
+ def fastDeLong(pst, m):
54
+ n = pst.shape[1] - m; k = pst.shape[0]
55
+ tx = np.empty([k, m]); ty = np.empty([k, n]); tz = np.empty([k, m + n])
56
+ for r in range(k):
57
+ tx[r] = compute_midrank(pst[r, :m]); ty[r] = compute_midrank(pst[r, m:])
58
+ tz[r] = compute_midrank(pst[r])
59
+ aucs = tz[:, :m].sum(1) / m / n - (m + 1.0) / 2.0 / n
60
+ v01 = (tz[:, :m] - tx) / n; v10 = 1.0 - (tz[:, m:] - ty) / m
61
+ return aucs, np.cov(v01) / m + np.cov(v10) / n
62
+
63
+ def delong_roc_test(gt, p1, p2):
64
+ order = (-gt).argsort(); m = int(gt.sum())
65
+ pst = np.vstack([p1, p2])[:, order]
66
+ aucs, cov = fastDeLong(pst, m)
67
+ l = np.array([[1, -1]])
68
+ z = np.abs(np.diff(aucs)) / np.sqrt(np.dot(np.dot(l, cov), l.T))
69
+ log10p = np.log10(2) + stats.norm.logsf(z, 0, 1) / np.log(10)
70
+ return 10 ** log10p[0][0], aucs[0], aucs[1]
71
+
72
+ def find_optimal_threshold(y_true, y_probs, method='youden'):
73
+ fpr, tpr, th = roc_curve(y_true, y_probs)
74
+ idx = np.argmax(tpr - fpr)
75
+ return th[idx], (tpr - fpr)[idx], idx
76
+
77
+ def calculate_net_benefit(y_true, y_probs, threshold):
78
+ yp = (y_probs >= threshold).astype(int)
79
+ tn, fp, fn, tp = confusion_matrix(y_true, yp).ravel()
80
+ n = len(y_true)
81
+ return (tp / n) - (fp / n) * (threshold / (1 - threshold))
82
+
83
+ # ============================================================================
84
+ # Model configs
85
+ # ============================================================================
86
+ ALL_MODEL_NAMES = ['RF', 'DT', 'KNN', 'XGB', 'AdaBoost', 'LR', 'NB', 'SVM']
87
+
88
+ def get_models_config(selected, rs=42):
89
+ cfg = {
90
+ 'RF': {'model': RandomForestClassifier(random_state=rs, n_jobs=-1),
91
+ 'params': {'n_estimators': [100,200], 'max_depth': [20,50], 'min_samples_split': [2,5], 'max_features': ['sqrt']}},
92
+ 'DT': {'model': DecisionTreeClassifier(random_state=rs),
93
+ 'params': {'max_depth': [20,50], 'min_samples_split': [2,10], 'min_samples_leaf': [1,4], 'criterion': ['gini','entropy']}},
94
+ 'KNN': {'model': KNeighborsClassifier(n_jobs=-1),
95
+ 'params': {'n_neighbors': [3,5,7], 'weights': ['uniform','distance'], 'metric': ['euclidean','manhattan']}},
96
+ 'XGB': {'model': XGBClassifier(random_state=rs, eval_metric='logloss', n_jobs=-1),
97
+ 'params': {'n_estimators': [100,200], 'max_depth': [5,7], 'learning_rate': [0.05,0.1], 'subsample': [0.8,1.0], 'colsample_bytree': [0.8,1.0]}},
98
+ 'AdaBoost': {'model': AdaBoostClassifier(random_state=rs),
99
+ 'params': {'n_estimators': [50,100], 'learning_rate': [0.1,0.5,1.0]}},
100
+ 'LR': {'model': LogisticRegression(random_state=rs, n_jobs=-1, max_iter=2000),
101
+ 'params': {'C': [0.1,1,10], 'penalty': ['l2'], 'solver': ['lbfgs','liblinear']}},
102
+ 'NB': {'model': GaussianNB(),
103
+ 'params': {'var_smoothing': [1e-9,1e-7,1e-5]}},
104
+ 'SVM': {'model': SVC(probability=True, random_state=rs),
105
+ 'params': {'C': [1,10], 'kernel': ['rbf','linear'], 'gamma': ['scale','auto']}},
106
+ }
107
+ return {k: v for k, v in cfg.items() if k in selected}
108
+
109
+ # ============================================================================
110
+ # Main Pipeline with Progress
111
+ # ============================================================================
112
+ def run_pipeline(
113
+ train_file, val_file, selected_models, enable_tuning,
114
+ cv_folds, alpha, top_n_features, shap_sample_size,
115
+ progress=gr.Progress(track_tqdm=True),
116
+ ):
117
+ if train_file is None:
118
+ return None, "❌ 请先上传训练集 CSV 文件"
119
+ sel = selected_models if isinstance(selected_models, list) else [s.strip() for s in str(selected_models).split(",") if s.strip()]
120
+ if not sel:
121
+ return None, "❌ 请至少选择一个模型"
122
+
123
+ RS = 42; CVF = int(cv_folds); ALP = float(alpha)
124
+ TOPN = int(top_n_features); SHAPSZ = int(shap_sample_size)
125
+ TUNING = bool(enable_tuning)
126
+
127
+ L = []
128
+ def log(m): L.append(str(m))
129
+
130
+ rf = tempfile.mkdtemp(prefix="ml_")
131
+
132
+ try:
133
+ # ── Load ──
134
+ progress(0.02, desc="📂 加载数据...")
135
+ log("━" * 50)
136
+ log(" 🧬 ML 二分类模型训练与评估系统")
137
+ log("━" * 50)
138
+
139
+ tp = train_file if isinstance(train_file, str) else getattr(train_file, 'name', str(train_file))
140
+ data = pd.read_csv(tp)
141
+ X = data.iloc[:, 2:]; y = data.iloc[:, 0]
142
+ fnames = X.columns.tolist()
143
+
144
+ # Auto 0/1
145
+ ul = sorted(y.unique())
146
+ if set(ul) != {0, 1}:
147
+ lm = {ul[0]: 0, ul[1]: 1}; y = y.map(lm)
148
+ log(f" ⚙ 标签已自动转换: {lm}")
149
+
150
+ log(f" 📊 训练集: {X.shape[0]} 样本 × {X.shape[1]} 特征")
151
+ log(f" 📊 标签: {dict(y.value_counts())}")
152
+ log(f" 🤖 模型: {', '.join(sel)}")
153
+ log(f" 🔧 调优: {'开启' if TUNING else '关闭'} | CV: {CVF}折")
154
+
155
+ mcfg = get_models_config(sel, RS)
156
+ skf = StratifiedKFold(n_splits=CVF, shuffle=True, random_state=RS)
157
+
158
+ # ── Train ──
159
+ bpd = {}; amr = {}; tms = {}
160
+ total = len(mcfg)
161
+ COLORS = ['#2563eb','#f59e0b','#10b981','#ef4444','#8b5cf6','#ec4899','#06b6d4','#6b7280']
162
+
163
+ for mi, (mn, cf) in enumerate(mcfg.items()):
164
+ pv = 0.05 + 0.40 * mi / total
165
+ progress(pv, desc=f"🏋️ [{mi+1}/{total}] 训练 {mn}...")
166
+ log(f"\n{'─'*40}")
167
+ log(f" 🔄 [{mi+1}/{total}] {mn}")
168
+
169
+ Xv = X.values
170
+ if TUNING:
171
+ log(f" ⏳ GridSearchCV (CV={CVF})...")
172
+ gs = GridSearchCV(cf['model'], cf['params'], cv=skf, scoring='roc_auc', n_jobs=-1, verbose=0)
173
+ gs.fit(Xv, y)
174
+ bp = gs.best_params_; bpd[mn] = bp
175
+ log(f" ✓ 最佳AUC: {gs.best_score_:.4f}")
176
+ else:
177
+ bp = {}; bpd[mn] = "默认参数"
178
+
179
+ mdl = deepcopy(cf['model'])
180
+ if bp: mdl.set_params(**bp)
181
+ mdl.fit(Xv, y)
182
+ tms[mn] = {'model': mdl, 'scaler': None}
183
+
184
+ # CV eval
185
+ folds = []; ayt = []; ayp = []; tprs = []
186
+ bfpr = np.linspace(0, 1, 101)
187
+ for fi, (tri, tei) in enumerate(skf.split(X, y), 1):
188
+ Xtr, Xte = X.iloc[tri].values, X.iloc[tei].values
189
+ ytr, yte = y.iloc[tri], y.iloc[tei]
190
+ mf = deepcopy(cf['model'])
191
+ if bp: mf.set_params(**bp)
192
+ mf.fit(Xtr, ytr)
193
+ ypp = mf.predict_proba(Xte)[:, 1]
194
+ ypd = (ypp > 0.5).astype(int)
195
+ tn, fp, fn, tp = confusion_matrix(yte, ypd).ravel()
196
+ se = tp/(tp+fn) if tp+fn else 0; sp = tn/(tn+fp) if tn+fp else 0
197
+ ac = (tp+tn)/(tp+tn+fp+fn); pr = tp/(tp+fp) if tp+fp else 0
198
+ f1 = 2*pr*se/(pr+se) if pr+se else 0
199
+ auc_v = roc_auc_score(yte, ypp)
200
+ folds.append({'Fold': fi, 'AUC': auc_v, 'Accuracy': ac, 'Sensitivity': se,
201
+ 'Specificity': sp, 'Precision': pr, 'F1': f1, 'TP': tp, 'TN': tn, 'FP': fp, 'FN': fn})
202
+ ayt.extend(yte); ayp.extend(ypp)
203
+ fa, ta, _ = roc_curve(yte, ypp)
204
+ ti = np.interp(bfpr, fa, ta); ti[0] = 0.0; tprs.append(ti)
205
+
206
+ rdf = pd.DataFrame(folds)
207
+ mr = {'Fold': 'Mean', 'AUC': rdf['AUC'].mean(), 'Accuracy': rdf['Accuracy'].mean(),
208
+ 'Sensitivity': rdf['Sensitivity'].mean(), 'Specificity': rdf['Specificity'].mean(),
209
+ 'Precision': rdf['Precision'].mean(), 'F1': rdf['F1'].mean(),
210
+ 'TP': rdf['TP'].sum(), 'TN': rdf['TN'].sum(), 'FP': rdf['FP'].sum(), 'FN': rdf['FN'].sum()}
211
+ rdf = pd.concat([rdf, pd.DataFrame([mr])], ignore_index=True)
212
+ ot, yv, _ = find_optimal_threshold(np.array(ayt), np.array(ayp))
213
+ amr[mn] = {'results_df': rdf, 'mean_auc': mr['AUC'], 'all_y_true': np.array(ayt),
214
+ 'all_y_probs': np.array(ayp), 'tprs': tprs, 'base_fpr': bfpr,
215
+ 'optimal_threshold': ot, 'youden_index': yv}
216
+ log(f" ✅ AUC={mr['AUC']:.4f} Acc={mr['Accuracy']:.4f} 阈值={ot:.4f}")
217
+
218
+ mnames = list(amr.keys()); nm = len(mnames)
219
+ log(f"\n{'━'*50}")
220
+ log(f" ✅ {nm} 个模型训练完成")
221
+
222
+ # ── ROC ──
223
+ progress(0.48, desc="📈 绘制ROC曲线...")
224
+ log(f"\n 📈 绘���图表...")
225
+ plt.figure(figsize=(12, 10))
226
+ for i, mn in enumerate(mnames):
227
+ r = amr[mn]; mt = np.mean(r['tprs'], axis=0); mt[-1] = 1.0
228
+ ma = auc_score(r['base_fpr'], mt); sa = r['results_df'].iloc[:-1]['AUC'].std()
229
+ st = np.std(r['tprs'], axis=0)
230
+ c = COLORS[i % 8]
231
+ plt.plot(r['base_fpr'], mt, color=c, lw=2.5, alpha=0.85, label=f'{mn} (AUC={ma:.3f}±{sa:.3f})')
232
+ plt.fill_between(r['base_fpr'], np.maximum(mt-st, 0), np.minimum(mt+st, 1), color=c, alpha=0.08)
233
+ plt.plot([0,1],[0,1],'--',lw=2,color='#9ca3af',alpha=0.5)
234
+ plt.xlim([-0.02,1.02]); plt.ylim([-0.02,1.02])
235
+ plt.xlabel('False Positive Rate',fontsize=13); plt.ylabel('True Positive Rate',fontsize=13)
236
+ plt.title('ROC Curves — Internal Cross-Validation',fontsize=15,fontweight='bold')
237
+ plt.legend(loc="lower right",fontsize=10); plt.grid(True,alpha=0.2); plt.tight_layout()
238
+ plt.savefig(os.path.join(rf,'roc_all.pdf'),format='pdf',bbox_inches='tight',dpi=300)
239
+ plt.savefig(os.path.join(rf,'roc_all.png'),format='png',bbox_inches='tight',dpi=150)
240
+ plt.close()
241
+
242
+ # ── PR ──
243
+ progress(0.52, desc="📈 绘制PR曲线...")
244
+ plt.figure(figsize=(12, 10))
245
+ for i, mn in enumerate(mnames):
246
+ r = amr[mn]; pra = []
247
+ for tri, tei in skf.split(X, y):
248
+ cf2 = mcfg[mn]; mpr = deepcopy(cf2['model'])
249
+ bp2 = bpd[mn]
250
+ if isinstance(bp2, dict) and bp2: mpr.set_params(**bp2)
251
+ mpr.fit(X.iloc[tri].values, y.iloc[tri])
252
+ yp2 = mpr.predict_proba(X.iloc[tei].values)[:,1]
253
+ pc, rc, _ = precision_recall_curve(y.iloc[tei], yp2)
254
+ pra.append(auc_score(rc, pc))
255
+ mpr_v = np.mean(pra); spr = np.std(pra)
256
+ pa, ra, _ = precision_recall_curve(r['all_y_true'], r['all_y_probs'])
257
+ plt.plot(ra, pa, color=COLORS[i%8], lw=2.5, alpha=0.85, label=f'{mn} (AUPRC={mpr_v:.3f}±{spr:.3f})')
258
+ plt.xlim([-0.02,1.02]); plt.ylim([-0.02,1.02])
259
+ plt.xlabel('Recall',fontsize=13); plt.ylabel('Precision',fontsize=13)
260
+ plt.title('Precision-Recall Curves — Internal CV',fontsize=15,fontweight='bold')
261
+ plt.legend(loc="lower left",fontsize=10); plt.grid(True,alpha=0.2); plt.tight_layout()
262
+ plt.savefig(os.path.join(rf,'pr_all.pdf'),format='pdf',bbox_inches='tight',dpi=300)
263
+ plt.savefig(os.path.join(rf,'pr_all.png'),format='png',bbox_inches='tight',dpi=150)
264
+ plt.close()
265
+
266
+ # ── CM ──
267
+ progress(0.55, desc="📊 绘制混淆矩阵...")
268
+ nc = min(4, nm); nr = (nm+nc-1)//nc
269
+ fig, axes = plt.subplots(nr, nc, figsize=(4.2*nc, 4.2*nr))
270
+ if nm == 1: axes = np.array([axes])
271
+ af = axes.flatten()
272
+ for i, mn in enumerate(mnames):
273
+ r = amr[mn]; ypc = (r['all_y_probs']>=r['optimal_threshold']).astype(int)
274
+ cm = confusion_matrix(r['all_y_true'], ypc)
275
+ sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', cbar=False,
276
+ xticklabels=['Neg','Pos'], yticklabels=['Neg','Pos'], ax=af[i], annot_kws={'fontsize':12})
277
+ af[i].set_xlabel('Predicted'); af[i].set_ylabel('True')
278
+ acc = (cm[0,0]+cm[1,1])/cm.sum()
279
+ af[i].set_title(f'{mn} (Acc={acc:.3f})',fontsize=12,fontweight='bold')
280
+ for i in range(nm, len(af)): af[i].set_visible(False)
281
+ plt.suptitle('Confusion Matrices',fontsize=15,fontweight='bold',y=1.0)
282
+ plt.tight_layout()
283
+ plt.savefig(os.path.join(rf,'confusion_matrices.pdf'),format='pdf',bbox_inches='tight',dpi=300)
284
+ plt.savefig(os.path.join(rf,'confusion_matrices.png'),format='png',bbox_inches='tight',dpi=150)
285
+ plt.close()
286
+
287
+ # ── DeLong ──
288
+ progress(0.58, desc="🔬 DeLong检验...")
289
+ bmn = max(amr, key=lambda x: amr[x]['mean_auc'])
290
+ bma = amr[bmn]['mean_auc']
291
+ log(f"\n 🏆 最佳模型: {bmn} (AUC={bma:.4f})")
292
+ dlr = []; retained = [bmn]
293
+ for om in mnames:
294
+ if om == bmn: continue
295
+ try: pv, a1, a2 = delong_roc_test(amr[bmn]['all_y_true'], amr[bmn]['all_y_probs'], amr[om]['all_y_probs'])
296
+ except: pv=1.0; a1=bma; a2=amr[om]['mean_auc']
297
+ if pv >= ALP: retained.append(om); dec = "保留"
298
+ else: dec = "排除"
299
+ dlr.append({'Model1': bmn, 'AUC1': a1, 'Model2': om, 'AUC2': a2, 'P': pv, 'Decision': dec})
300
+ log(f" {bmn} vs {om}: P={pv:.2e} → {dec}")
301
+ dldf = pd.DataFrame(dlr).sort_values('P', ascending=False) if dlr else pd.DataFrame()
302
+ log(f" ✅ 保留 {len(retained)} 个模型: {', '.join(retained)}")
303
+
304
+ # ── SHAP ──
305
+ progress(0.62, desc="🔥 SHAP分析...")
306
+ log(f"\n 🔥 SHAP特征分析...")
307
+ shap_imp = {}
308
+ for si, mn in enumerate(retained):
309
+ progress(0.62+0.10*si/len(retained), desc=f"🔥 SHAP: {mn}...")
310
+ mo = tms[mn]['model']; Xshap = X.values
311
+ ns = min(SHAPSZ, Xshap.shape[0])
312
+ np.random.seed(RS); sidx = np.random.choice(Xshap.shape[0], ns, replace=False)
313
+ Xs = Xshap[sidx]
314
+ try:
315
+ if mn in ['RF','XGB','DT','AdaBoost']:
316
+ exp = shap.TreeExplainer(mo); sv = exp.shap_values(Xs)
317
+ if isinstance(sv, list): sv = sv[1]
318
+ else:
319
+ bg = Xs[np.random.choice(ns, min(100,ns), replace=False)]
320
+ exp = shap.KernelExplainer(lambda x, m=mo: m.predict_proba(x)[:,1], bg)
321
+ sv = exp.shap_values(Xs)
322
+ if isinstance(sv, list): sv = sv[0]
323
+ sv = np.array(sv)
324
+ if sv.ndim > 2: sv = sv[0]
325
+ fi = np.abs(sv).mean(0)
326
+ if fi.ndim > 1: fi = fi.flatten()
327
+ if len(fi) > len(fnames): fi = fi[:len(fnames)]
328
+ elif len(fi) < len(fnames): fi = np.pad(fi, (0, len(fnames)-len(fi)))
329
+ idf = pd.DataFrame({'Feature': fnames, 'Importance': fi}).sort_values('Importance', ascending=False)
330
+ shap_imp[mn] = idf
331
+ Xdf = pd.DataFrame(Xs, columns=fnames)
332
+ if sv.shape[1] > Xdf.shape[1]: sv = sv[:,:Xdf.shape[1]]
333
+ elif sv.shape[1] < Xdf.shape[1]: sv = np.hstack([sv, np.zeros((sv.shape[0], Xdf.shape[1]-sv.shape[1]))])
334
+ plt.figure(figsize=(12,8))
335
+ shap.summary_plot(sv, Xdf, plot_type="dot", show=False, max_display=TOPN)
336
+ plt.title(f'SHAP — {mn} (Top {TOPN})',fontsize=14,fontweight='bold'); plt.tight_layout()
337
+ plt.savefig(os.path.join(rf,f'shap_{mn}.pdf'),format='pdf',bbox_inches='tight')
338
+ plt.savefig(os.path.join(rf,f'shap_{mn}.png'),format='png',bbox_inches='tight',dpi=150)
339
+ plt.close()
340
+ log(f" ✅ {mn} Top3: {', '.join(idf.head(3)['Feature'].tolist())}")
341
+ except Exception as e:
342
+ log(f" ⚠ {mn} SHAP失败: {e}")
343
+
344
+ # ── Ablation ──
345
+ progress(0.75, desc="🧪 特征消融...")
346
+ log(f"\n 🧪 特征消融研究...")
347
+ ablr = {}
348
+ for mn in retained:
349
+ if mn not in shap_imp: continue
350
+ tfs = shap_imp[mn].head(TOPN)['Feature'].tolist()
351
+ fcs = []; aucs_a = []; asp = {}
352
+ for nf in range(1, len(tfs)+1):
353
+ Xsub = X[tfs[:nf]]
354
+ fa = []; syt = []; syp = []
355
+ for tri, tei in skf.split(Xsub, y):
356
+ mf = deepcopy(mcfg[mn]['model'])
357
+ bp2 = bpd.get(mn, {})
358
+ if isinstance(bp2, dict) and bp2: mf.set_params(**bp2)
359
+ mf.fit(Xsub.iloc[tri].values, y.iloc[tri])
360
+ yp2 = mf.predict_proba(Xsub.iloc[tei].values)[:,1]
361
+ syt.extend(y.iloc[tei]); syp.extend(yp2)
362
+ fa.append(roc_auc_score(y.iloc[tei], yp2))
363
+ fcs.append(nf); aucs_a.append(np.mean(fa))
364
+ asp[nf] = {'yt': np.array(syt), 'yp': np.array(syp)}
365
+ fp = amr[mn]['all_y_probs']; fauc = amr[mn]['mean_auc']; optn = None; adl = []
366
+ for nf in range(1, len(tfs)+1):
367
+ sd = asp[nf]; sa = aucs_a[nf-1]
368
+ try:
369
+ pv = delong_roc_test(sd['yt'], fp, sd['yp'])[0] if len(fp)==len(sd['yp']) else (0.1 if abs(sa-fauc)<=0.05 else 0.01)
370
+ except: pv = 0.1 if abs(sa-fauc)<=0.05 else 0.01
371
+ sig = "Sig" if pv < ALP else "NS"
372
+ adl.append({'N': nf, 'AUC': sa, 'Full_AUC': fauc, 'P': pv, 'Sig': sig})
373
+ if optn is None and pv >= ALP: optn = nf
374
+ ablr[mn] = {'fcs': fcs, 'aucs': aucs_a, 'tfs': tfs, 'dl': pd.DataFrame(adl),
375
+ 'optn': optn or len(tfs), 'optf': tfs[:optn] if optn else tfs}
376
+ log(f" {mn}: 最优 {ablr[mn]['optn']} 个特征")
377
+
378
+ # Final model
379
+ fcands = {}
380
+ for mn in retained:
381
+ if mn in ablr:
382
+ ar = ablr[mn]
383
+ fcands[mn] = {'nf': ar['optn'], 'feats': ar['optf'], 'auc': ar['aucs'][ar['optn']-1]}
384
+ fmn = min(fcands, key=lambda x: fcands[x]['nf']) if fcands else None
385
+ fmi = fcands.get(fmn) if fmn else None
386
+ if fmn: log(f"\n ⭐ 最终模型: {fmn} ({fmi['nf']}特征, AUC={fmi['auc']:.4f})")
387
+
388
+ # Ablation plot
389
+ progress(0.80, desc="📈 消融曲线...")
390
+ plt.figure(figsize=(12,8))
391
+ for i, (mn, ar) in enumerate(ablr.items()):
392
+ c = COLORS[i%8]
393
+ plt.plot(ar['fcs'], ar['aucs'], marker='o', lw=2, ms=5, color=c, label=mn)
394
+ on = ar['optn']; oa = ar['aucs'][on-1]
395
+ plt.scatter([on],[oa], s=200, marker='*', color=c, edgecolors='black', lw=2, zorder=5)
396
+ plt.xlabel('Number of Features',fontsize=13); plt.ylabel('AUC',fontsize=13)
397
+ plt.title('Feature Ablation (★=Optimal)',fontsize=15,fontweight='bold')
398
+ plt.legend(fontsize=11); plt.grid(True,alpha=0.2); plt.tight_layout()
399
+ plt.savefig(os.path.join(rf,'ablation.pdf'),format='pdf',bbox_inches='tight')
400
+ plt.savefig(os.path.join(rf,'ablation.png'),format='png',bbox_inches='tight',dpi=150)
401
+ plt.close()
402
+
403
+ # DCA
404
+ progress(0.83, desc="📈 DCA曲线...")
405
+ plt.figure(figsize=(12,8))
406
+ thr = np.linspace(0.01,0.99,100)
407
+ for i, mn in enumerate(retained):
408
+ r = amr[mn]
409
+ nbs = [calculate_net_benefit(r['all_y_true'], r['all_y_probs'], t) for t in thr]
410
+ lbl = f'{mn} ⭐' if mn == fmn else mn
411
+ plt.plot(thr, nbs, color=COLORS[i%8], lw=2.5, alpha=0.85, label=lbl)
412
+ prev = np.mean(amr[retained[0]]['all_y_true'])
413
+ ta = [prev-(1-prev)*(pt/(1-pt)) for pt in thr]
414
+ plt.plot(thr, ta, 'k--', lw=2, alpha=0.5, label='Treat All')
415
+ plt.plot(thr, [0]*len(thr), 'gray', lw=2, alpha=0.5, label='Treat None')
416
+ plt.xlim([0,1]); plt.xlabel('Threshold',fontsize=13); plt.ylabel('Net Benefit',fontsize=13)
417
+ plt.title('Decision Curve Analysis',fontsize=15,fontweight='bold')
418
+ plt.legend(loc="upper right",fontsize=11); plt.grid(True,alpha=0.2); plt.tight_layout()
419
+ plt.savefig(os.path.join(rf,'dca.pdf'),format='pdf',bbox_inches='tight')
420
+ plt.savefig(os.path.join(rf,'dca.png'),format='png',bbox_inches='tight',dpi=150)
421
+ plt.close()
422
+
423
+ # ── External Validation ──
424
+ if val_file is not None and fmn:
425
+ progress(0.86, desc="🧪 外部验证...")
426
+ log(f"\n{'━'*50}")
427
+ log(f" 🧪 外部验证")
428
+ vp = val_file if isinstance(val_file, str) else getattr(val_file, 'name', str(val_file))
429
+ ed = pd.read_csv(vp); Xe = ed.iloc[:,2:]; ye = ed.iloc[:,0]
430
+ ule = sorted(ye.unique())
431
+ if set(ule)!={0,1}: lme={ule[0]:0,ule[1]:1}; ye=ye.map(lme)
432
+ log(f" 📊 验证集: {Xe.shape[0]} 样本")
433
+
434
+ Xes = Xe[fmi['feats']]; Xtf = X[fmi['feats']]
435
+ fm = deepcopy(mcfg[fmn]['model'])
436
+ bp3 = bpd[fmn]
437
+ if isinstance(bp3, dict) and bp3: fm.set_params(**bp3)
438
+ fm.fit(Xtf.values, y)
439
+ yep = fm.predict_proba(Xes.values)[:,1]; yed = (yep>0.5).astype(int)
440
+ tn,fp,fn,tp = confusion_matrix(ye,yed).ravel()
441
+ se=tp/(tp+fn) if tp+fn else 0; sp=tn/(tn+fp) if tn+fp else 0
442
+ ac=(tp+tn)/(tp+tn+fp+fn); pr=tp/(tp+fp) if tp+fp else 0
443
+ f1v=2*pr*se/(pr+se) if pr+se else 0; ea=roc_auc_score(ye,yep)
444
+ log(f" ✅ AUC={ea:.4f} Acc={ac:.4f} Sens={se:.4f} Spec={sp:.4f} F1={f1v:.4f}")
445
+
446
+ for pname, pfunc in [('roc_ext', lambda: (lambda fe,te,_: (plt.plot(fe,te,'#2563eb',lw=2.5,label=f'{fmn} (AUC={ea:.3f})'), plt.plot([0,1],[0,1],'--',color='gray'), plt.xlabel('FPR'), plt.ylabel('TPR'), plt.title(f'ROC — External ({fmn})',fontweight='bold'), plt.legend(), plt.grid(True,alpha=0.2)))(*roc_curve(ye,yep))),
447
+ ('pr_ext', lambda: (lambda pe,re,_: (plt.plot(re,pe,'#2563eb',lw=2.5,label=fmn), plt.xlabel('Recall'), plt.ylabel('Precision'), plt.title(f'PR — External ({fmn})',fontweight='bold'), plt.legend(), plt.grid(True,alpha=0.2)))(*precision_recall_curve(ye,yep))),]:
448
+ plt.figure(figsize=(10,8)); pfunc(); plt.tight_layout()
449
+ plt.savefig(os.path.join(rf,f'{pname}.pdf'),format='pdf',bbox_inches='tight')
450
+ plt.savefig(os.path.join(rf,f'{pname}.png'),format='png',bbox_inches='tight',dpi=150)
451
+ plt.close()
452
+
453
+ # ext CM
454
+ cme = confusion_matrix(ye,yed)
455
+ plt.figure(figsize=(8,6))
456
+ sns.heatmap(cme,annot=True,fmt='d',cmap='Blues',cbar=False,xticklabels=['Neg','Pos'],yticklabels=['Neg','Pos'])
457
+ plt.xlabel('Predicted'); plt.ylabel('True')
458
+ plt.title(f'CM — External ({fmn})',fontweight='bold'); plt.tight_layout()
459
+ plt.savefig(os.path.join(rf,'cm_ext.pdf'),format='pdf',bbox_inches='tight')
460
+ plt.savefig(os.path.join(rf,'cm_ext.png'),format='png',bbox_inches='tight',dpi=150)
461
+ plt.close()
462
+
463
+ # ext DCA
464
+ nbe = [calculate_net_benefit(ye,yep,t) for t in thr]
465
+ pe = np.mean(ye); tae = [pe-(1-pe)*(pt/(1-pt)) for pt in thr]
466
+ plt.figure(figsize=(10,8))
467
+ plt.plot(thr,nbe,'#2563eb',lw=2.5,label=fmn)
468
+ plt.plot(thr,tae,'k--',lw=2,alpha=0.5,label='Treat All')
469
+ plt.plot(thr,[0]*len(thr),'gray',lw=2,alpha=0.5,label='Treat None')
470
+ plt.xlabel('Threshold'); plt.ylabel('Net Benefit')
471
+ plt.title(f'DCA — External ({fmn})',fontweight='bold')
472
+ plt.legend(loc="upper right"); plt.grid(True,alpha=0.2); plt.tight_layout()
473
+ plt.savefig(os.path.join(rf,'dca_ext.pdf'),format='pdf',bbox_inches='tight')
474
+ plt.savefig(os.path.join(rf,'dca_ext.png'),format='png',bbox_inches='tight',dpi=150)
475
+ plt.close()
476
+
477
+ with pd.ExcelWriter(os.path.join(rf,'external_validation.xlsx'),engine='openpyxl') as w:
478
+ pd.DataFrame([{'Model':fmn,'N_Features':fmi['nf'],'AUC':ea,'Accuracy':ac,
479
+ 'Sensitivity':se,'Specificity':sp,'Precision':pr,'F1':f1v}]).to_excel(w,sheet_name='Metrics',index=False)
480
+ pd.DataFrame({'Feature':fmi['feats']}).to_excel(w,sheet_name='Features',index=False)
481
+
482
+ # ── Save Excels ──
483
+ progress(0.92, desc="💾 保存结果...")
484
+ log(f"\n 💾 保存结果文件...")
485
+ with pd.ExcelWriter(os.path.join(rf,'model_evaluation.xlsx'),engine='openpyxl') as w:
486
+ for mn, r in amr.items(): r['results_df'].to_excel(w,sheet_name=mn,index=False)
487
+ sd = []
488
+ for mn, r in amr.items():
489
+ rw = r['results_df'].iloc[-1].to_dict()
490
+ rw.update({'Model':mn,'Retained':'Yes' if mn in retained else 'No','Final':'Yes' if mn==fmn else 'No'})
491
+ sd.append(rw)
492
+ sdf = pd.DataFrame(sd)
493
+ cols = ['Model','Retained','Final']+[c for c in sdf.columns if c not in ['Model','Fold','Retained','Final']]
494
+ sdf[cols].sort_values('AUC',ascending=False).to_excel(w,sheet_name='Summary',index=False)
495
+ if len(dldf)>0: dldf.to_excel(w,sheet_name='DeLong',index=False)
496
+
497
+ with pd.ExcelWriter(os.path.join(rf,'feature_ablation.xlsx'),engine='openpyxl') as w:
498
+ for mn, ar in ablr.items():
499
+ pd.DataFrame({'N':ar['fcs'],'AUC':ar['aucs']}).to_excel(w,sheet_name=mn,index=False)
500
+ if 'dl' in ar: ar['dl'].to_excel(w,sheet_name=f'{mn}_DL',index=False)
501
+ for mn, idf in shap_imp.items():
502
+ idf.to_excel(w,sheet_name=f'{mn}_Imp',index=False)
503
+
504
+ with open(os.path.join(rf,'best_params.txt'),'w',encoding='utf-8') as f:
505
+ f.write("模型最佳超参数\n"+"="*50+"\n\n")
506
+ for mn in mcfg:
507
+ f.write(f"模型: {mn}\n")
508
+ bp = bpd[mn]
509
+ if isinstance(bp,dict):
510
+ for k,v in bp.items(): f.write(f" {k}: {v}\n")
511
+ else: f.write(f" {bp}\n")
512
+ f.write(f" AUC: {amr[mn]['mean_auc']:.4f}\n 保留: {'是' if mn in retained else '否'}\n\n")
513
+ if fmn: f.write(f"\n最终模型: {fmn}\n特征({fmi['nf']}): {', '.join(fmi['feats'])}\n")
514
+
515
+ if fmn:
516
+ pickle.dump({'model_name':fmn,'model':tms[fmn]['model'],'best_params':bpd[fmn],
517
+ 'features':fmi['feats'],'n_features':fmi['nf'],'auc':fmi['auc'],
518
+ 'threshold':amr[fmn]['optimal_threshold']},
519
+ open(os.path.join(rf,f'model_{fmn}.pkl'),'wb'))
520
+
521
+ # ── ZIP ──
522
+ progress(0.97, desc="📦 打包ZIP...")
523
+ zp = os.path.join(tempfile.gettempdir(),"ml_results.zip")
524
+ with zipfile.ZipFile(zp,'w',zipfile.ZIP_DEFLATED) as zf:
525
+ for root,_,files in os.walk(rf):
526
+ for fn in files: zf.write(os.path.join(root,fn), os.path.relpath(os.path.join(root,fn),rf))
527
+
528
+ nf = sum(len(f) for _,_,f in os.walk(rf))
529
+ log(f"\n{'━'*50}")
530
+ log(f" 🎉 分析完成!共 {nf} 个文件已打包")
531
+ log(f"{'━'*50}")
532
+ progress(1.0, desc="✅ 完成!")
533
+ return zp, "\n".join(L)
534
+
535
+ except Exception as e:
536
+ log(f"\n❌ 错误: {e}")
537
+ log(traceback.format_exc())
538
+ return None, "\n".join(L)
539
+
540
+
541
+ # ============================================================================
542
+ # Beautiful Gradio UI
543
+ # ============================================================================
544
+ CUSTOM_CSS = """
545
+ /* ── Header Banner ── */
546
+ .header-banner {
547
+ background: linear-gradient(135deg, #1a1a2e 0%, #16213e 40%, #0f3460 100%);
548
+ border-radius: 16px;
549
+ padding: 28px 36px;
550
+ margin-bottom: 20px;
551
+ box-shadow: 0 8px 32px rgba(0,0,0,0.18);
552
+ position: relative;
553
+ overflow: hidden;
554
+ }
555
+ .header-banner::before {
556
+ content: '';
557
+ position: absolute;
558
+ top: -50%;
559
+ right: -20%;
560
+ width: 400px;
561
+ height: 400px;
562
+ background: radial-gradient(circle, rgba(37,99,235,0.15) 0%, transparent 70%);
563
+ border-radius: 50%;
564
+ }
565
+ .header-banner img {
566
+ max-height: 52px;
567
+ border-radius: 6px;
568
+ margin-bottom: 12px;
569
+ }
570
+ .header-banner h1 {
571
+ color: #e2e8f0 !important;
572
+ font-size: 1.7em !important;
573
+ margin: 4px 0 6px 0 !important;
574
+ font-weight: 700 !important;
575
+ letter-spacing: 0.5px;
576
+ }
577
+ .header-banner p {
578
+ color: #94a3b8 !important;
579
+ font-size: 0.92em !important;
580
+ margin: 2px 0 !important;
581
+ line-height: 1.6;
582
+ }
583
+ .header-banner .credit {
584
+ color: #64748b !important;
585
+ font-size: 0.82em !important;
586
+ margin-top: 10px !important;
587
+ border-top: 1px solid rgba(148,163,184,0.15);
588
+ padding-top: 10px;
589
+ }
590
+
591
+ /* ── Section Cards ── */
592
+ .section-title {
593
+ background: linear-gradient(90deg, #2563eb 0%, #3b82f6 100%);
594
+ color: white !important;
595
+ padding: 8px 16px;
596
+ border-radius: 8px;
597
+ font-size: 0.95em !important;
598
+ font-weight: 600 !important;
599
+ margin: 12px 0 8px 0;
600
+ letter-spacing: 0.3px;
601
+ }
602
+
603
+ /* ── Pipeline Steps ── */
604
+ .pipeline-box {
605
+ background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
606
+ border: 1px solid #bae6fd;
607
+ border-radius: 12px;
608
+ padding: 14px 18px;
609
+ margin: 8px 0;
610
+ font-size: 0.88em;
611
+ }
612
+ .pipeline-box code {
613
+ background: #2563eb;
614
+ color: white;
615
+ padding: 2px 8px;
616
+ border-radius: 4px;
617
+ font-size: 0.85em;
618
+ margin: 0 2px;
619
+ }
620
+
621
+ /* ── Buttons ── */
622
+ .quick-btn {
623
+ border-radius: 8px !important;
624
+ font-weight: 500 !important;
625
+ transition: all 0.2s ease !important;
626
+ }
627
+ .quick-btn:hover {
628
+ transform: translateY(-1px) !important;
629
+ box-shadow: 0 4px 12px rgba(0,0,0,0.1) !important;
630
+ }
631
+
632
+ /* ── Log Area ── */
633
+ .log-area textarea {
634
+ font-family: 'Menlo', 'Consolas', 'Monaco', monospace !important;
635
+ font-size: 12.5px !important;
636
+ line-height: 1.5 !important;
637
+ background: #0f172a !important;
638
+ color: #e2e8f0 !important;
639
+ border-radius: 10px !important;
640
+ padding: 16px !important;
641
+ border: 1px solid #1e293b !important;
642
+ }
643
+
644
+ /* ── General Polish ── */
645
+ .gradio-container {
646
+ max-width: 1280px !important;
647
+ }
648
+ footer { display: none !important; }
649
+ """
650
+
651
+ with gr.Blocks(
652
+ title="ML 二分类模型平台 — 复旦大学附属眼耳鼻喉科医院",
653
+ theme=gr.themes.Soft(primary_hue="blue", secondary_hue="slate", neutral_hue="slate"),
654
+ css=CUSTOM_CSS,
655
+ ) as demo:
656
+
657
+ # ── Header ──
658
+ gr.HTML("""
659
+ <div class="header-banner">
660
+ <img src="https://huggingface.co/spaces/fudan-renjun/machine-learning-2/resolve/main/hospital_logo.png"
661
+ alt="Logo" onerror="this.style.display='none'"/>
662
+ <h1>🧬 ML 二分类模型训练与评估平台</h1>
663
+ <p>上传训练集与验证集 CSV,自动完成模型训练、交叉验证、统计检验、特征分析,结果打包下载</p>
664
+ <p class="credit">复旦大学附属眼耳鼻喉科医院 · 检验科 · 任俊</p>
665
+ </div>
666
+ """)
667
+
668
+ # ── Pipeline Info ──
669
+ gr.HTML("""
670
+ <div class="pipeline-box">
671
+ <strong>📋 分析流程:</strong>
672
+ <code>模型训练</code> → <code>交叉验证</code> → <code>DeLong检验</code> →
673
+ <code>SHAP分析</code> → <code>特征消融</code> → <code>外部验证</code>
674
+ &nbsp;&nbsp;|&nbsp;&nbsp;
675
+ <strong>CSV格式:</strong> 第1列=标签, 第2列=ID, 第3列起=特征
676
+ </div>
677
+ """)
678
+
679
+ with gr.Row(equal_height=False):
680
+ # ══ Left Panel ══
681
+ with gr.Column(scale=5):
682
+
683
+ gr.HTML('<div class="section-title">📂 数据上传</div>')
684
+ with gr.Row():
685
+ train_file = gr.File(label="训练集 CSV(必需)", file_types=[".csv"], scale=1)
686
+ val_file = gr.File(label="验证集 CSV(可选)", file_types=[".csv"], scale=1)
687
+
688
+ gr.HTML('<div class="section-title">🤖 模型选择</div>')
689
+ model_selector = gr.Dropdown(
690
+ choices=ALL_MODEL_NAMES,
691
+ value=ALL_MODEL_NAMES,
692
+ multiselect=True,
693
+ label="选择模型(可多选,默认全部)",
694
+ info="RF=随机森林 DT=决策树 KNN=K近邻 XGB=极限梯度提升 AdaBoost=自适应提升 LR=逻辑回归 NB=朴素贝叶斯 SVM=支持向量机",
695
+ )
696
+ with gr.Row():
697
+ btn_all = gr.Button("🔘 全选", size="sm", variant="secondary", elem_classes="quick-btn")
698
+ btn_tree = gr.Button("🌲 树模型", size="sm", variant="secondary", elem_classes="quick-btn")
699
+ btn_linear = gr.Button("📐 线性模型", size="sm", variant="secondary", elem_classes="quick-btn")
700
+ btn_top4 = gr.Button("⚡ 经典四模型", size="sm", variant="secondary", elem_classes="quick-btn")
701
+ btn_all.click(lambda: ALL_MODEL_NAMES, outputs=model_selector)
702
+ btn_tree.click(lambda: ['RF','DT','XGB','AdaBoost'], outputs=model_selector)
703
+ btn_linear.click(lambda: ['LR','SVM','NB'], outputs=model_selector)
704
+ btn_top4.click(lambda: ['RF','XGB','LR','SVM'], outputs=model_selector)
705
+
706
+ gr.HTML('<div class="section-title">⚙️ 参数配置</div>')
707
+ enable_tuning = gr.Checkbox(value=False, label="启用超参数调优 (GridSearchCV) ⚠️ 开启后运行时间显著增加")
708
+ with gr.Row():
709
+ cv_folds = gr.Slider(3, 10, value=5, step=1, label="交叉验证折数")
710
+ alpha_sl = gr.Slider(0.01, 0.10, value=0.05, step=0.01, label="DeLong 显著性水平 α")
711
+ with gr.Row():
712
+ top_n = gr.Slider(5, 50, value=20, step=1, label="SHAP 前 N 个特征")
713
+ shap_sz = gr.Slider(30, 200, value=80, step=10, label="SHAP 采样数量")
714
+
715
+ run_btn = gr.Button("🚀 开始分析", variant="primary", size="lg")
716
+
717
+ # ══ Right Panel ══
718
+ with gr.Column(scale=5):
719
+ gr.HTML('<div class="section-title">📋 运行���志</div>')
720
+ log_output = gr.Textbox(
721
+ label="", lines=22, max_lines=50, interactive=False,
722
+ placeholder="点击「开始分析」后,运行日志将在此实时显示...",
723
+ elem_classes="log-area",
724
+ )
725
+
726
+ gr.HTML('<div class="section-title">⬇️ 结果下载</div>')
727
+ zip_output = gr.File(label="分析结果 ZIP 压缩包")
728
+
729
+ # ── Connect ──
730
+ run_btn.click(
731
+ fn=run_pipeline,
732
+ inputs=[train_file, val_file, model_selector, enable_tuning, cv_folds, alpha_sl, top_n, shap_sz],
733
+ outputs=[zip_output, log_output],
734
+ api_name="run",
735
+ )
736
+
737
+ demo.queue()
738
+ demo.launch(server_name="0.0.0.0", server_port=7860)
hospital_logo.png ADDED
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ pydantic==2.10.6
2
+ numpy>=1.24.0
3
+ pandas>=2.0.0
4
+ matplotlib>=3.7.0
5
+ scikit-learn>=1.3.0
6
+ xgboost>=2.0.0
7
+ seaborn>=0.12.0
8
+ scipy>=1.11.0
9
+ shap>=0.43.0
10
+ openpyxl>=3.1.0