Spaces:
Sleeping
Sleeping
Upload 4 files
Browse files- DEPLOY_GUIDE.txt +63 -0
- README.md +40 -0
- app.py +946 -0
- requirements.txt +10 -0
DEPLOY_GUIDE.txt
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# FungalPep - Hugging Face Spaces 部署指南
|
| 2 |
+
# ==========================================
|
| 3 |
+
|
| 4 |
+
# ═══════════════ 第一步:注册 Hugging Face ═══════════════
|
| 5 |
+
# 1. 打开 https://huggingface.co/join
|
| 6 |
+
# 2. 注册账号(免费)
|
| 7 |
+
# 3. 登录后点击右上角头像 → Settings → Access Tokens
|
| 8 |
+
# 4. 创建一个 Token(选 Write 权限),复制保存
|
| 9 |
+
|
| 10 |
+
# ═══════════════ 第二步:安装 Git LFS ═══════════════
|
| 11 |
+
# 模型文件较大,需要 Git LFS(Large File Storage)
|
| 12 |
+
# Windows 下载: https://git-lfs.com/ 安装后运行:
|
| 13 |
+
# git lfs install
|
| 14 |
+
|
| 15 |
+
# ═══════════════ 第三步:创建 Space ═══════════════
|
| 16 |
+
# 1. 打开 https://huggingface.co/new-space
|
| 17 |
+
# 2. 填写:
|
| 18 |
+
# - Space name: fungalpep
|
| 19 |
+
# - License: MIT
|
| 20 |
+
# - SDK: Streamlit
|
| 21 |
+
# - Hardware: CPU basic(免费) 或 T4 small(更快,可能需付费)
|
| 22 |
+
# 3. 点击 Create Space
|
| 23 |
+
|
| 24 |
+
# ═══════════════ 第四步:上传文件 ═══════════════
|
| 25 |
+
# 在 E:\my_project 下运行以下命令:
|
| 26 |
+
|
| 27 |
+
# 克隆你的 Space 仓库
|
| 28 |
+
# git clone https://huggingface.co/spaces/你的用户名/fungalpep
|
| 29 |
+
# cd fungalpep
|
| 30 |
+
|
| 31 |
+
# 复制文件到仓库
|
| 32 |
+
# copy E:\my_project\hf_deploy\README.md .
|
| 33 |
+
# copy E:\my_project\hf_deploy\app.py .
|
| 34 |
+
# copy E:\my_project\hf_deploy\requirements.txt .
|
| 35 |
+
# mkdir checkpoints
|
| 36 |
+
# mkdir checkpoints_mic
|
| 37 |
+
# copy E:\my_project\checkpoints\best_model.pt checkpoints\
|
| 38 |
+
# copy E:\my_project\checkpoints_mic\best_mic_model.pt checkpoints_mic\
|
| 39 |
+
|
| 40 |
+
# 用 Git LFS 追踪大文件
|
| 41 |
+
# git lfs track "*.pt"
|
| 42 |
+
|
| 43 |
+
# 提交并推送
|
| 44 |
+
# git add .
|
| 45 |
+
# git commit -m "Initial deployment: FungalPep AMP + MIC prediction"
|
| 46 |
+
# git push
|
| 47 |
+
|
| 48 |
+
# 推送时会要求输入用户名和密码:
|
| 49 |
+
# 用户名: 你的 HuggingFace 用户名
|
| 50 |
+
# 密码: 你在第一步创建的 Access Token
|
| 51 |
+
|
| 52 |
+
# ═══════════════ 第五步:等待部署 ═══════════════
|
| 53 |
+
# 推送后 Hugging Face 会自动构建和部署
|
| 54 |
+
# 打开 https://huggingface.co/spaces/你的用户名/fungalpep 查看状态
|
| 55 |
+
# 首次构建约 5-10 分钟(需要安装依赖和下载 ESM-2)
|
| 56 |
+
# 构建成功后,你会看到 FungalPep 网页界面
|
| 57 |
+
|
| 58 |
+
# ═══════════════ 注意事项 ═══════════════
|
| 59 |
+
# 1. 免费 CPU 版本: ESM-2 推理较慢(约 10-30 秒/序列),但完全免费
|
| 60 |
+
# 2. 如需更快速度: 在 Space Settings 中升级到 T4 GPU(约 $0.60/小时)
|
| 61 |
+
# 3. 免费版会在不活跃时休眠,首次访问需要约 1 分钟唤醒
|
| 62 |
+
# 4. best_model.pt 和 best_mic_model.pt 加起来约几十 MB,不超限
|
| 63 |
+
# 5. ESM-2 模型会在首次运行时自动从 HuggingFace Hub 下载并缓存
|
README.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: ML Binary Classification Pipeline
|
| 3 |
+
emoji: 🧬
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 4.44.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
license: mit
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
# 🧬 ML Binary Classification Pipeline
|
| 14 |
+
|
| 15 |
+
Machine learning binary classification training & evaluation platform.
|
| 16 |
+
|
| 17 |
+
## Features
|
| 18 |
+
|
| 19 |
+
- **8 Models**: RF, DT, KNN, XGB, AdaBoost, LR, NB, SVM
|
| 20 |
+
- **Interactive Model Selection**: Choose any combination of models
|
| 21 |
+
- **Hyperparameter Tuning**: GridSearchCV with configurable folds
|
| 22 |
+
- **DeLong Test**: Statistical comparison between models
|
| 23 |
+
- **SHAP Analysis**: Feature importance with beeswarm plots
|
| 24 |
+
- **Feature Ablation**: Optimal feature subset selection
|
| 25 |
+
- **External Validation**: ROC, PR, DCA curves, confusion matrix
|
| 26 |
+
- **ZIP Download**: All results packaged for download
|
| 27 |
+
|
| 28 |
+
## Data Format
|
| 29 |
+
|
| 30 |
+
CSV files with:
|
| 31 |
+
- Column 1: Label (0/1)
|
| 32 |
+
- Column 2: Any (e.g., ID)
|
| 33 |
+
- Column 3+: Features
|
| 34 |
+
|
| 35 |
+
## Output Files
|
| 36 |
+
|
| 37 |
+
- PDF/PNG charts (ROC, PR, DCA, confusion matrices, SHAP plots)
|
| 38 |
+
- Excel files (model metrics, feature ablation, external validation)
|
| 39 |
+
- Best parameters text file
|
| 40 |
+
- Final model pickle file
|
app.py
ADDED
|
@@ -0,0 +1,946 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ZIP download.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import matplotlib
|
| 9 |
+
matplotlib.use('Agg')
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
|
| 12 |
+
from sklearn.tree import DecisionTreeClassifier
|
| 13 |
+
from sklearn.neighbors import KNeighborsClassifier
|
| 14 |
+
from sklearn.linear_model import LogisticRegression
|
| 15 |
+
from sklearn.naive_bayes import GaussianNB
|
| 16 |
+
from sklearn.svm import SVC
|
| 17 |
+
from xgboost import XGBClassifier
|
| 18 |
+
from sklearn.model_selection import StratifiedKFold, GridSearchCV
|
| 19 |
+
from sklearn.metrics import (
|
| 20 |
+
roc_auc_score, confusion_matrix, roc_curve,
|
| 21 |
+
auc as auc_score, precision_recall_curve
|
| 22 |
+
)
|
| 23 |
+
import seaborn as sns
|
| 24 |
+
import warnings
|
| 25 |
+
from scipy import stats
|
| 26 |
+
import os
|
| 27 |
+
import shap
|
| 28 |
+
import pickle
|
| 29 |
+
from copy import deepcopy
|
| 30 |
+
import zipfile
|
| 31 |
+
import tempfile
|
| 32 |
+
import gradio as gr
|
| 33 |
+
import io
|
| 34 |
+
import traceback
|
| 35 |
+
|
| 36 |
+
warnings.filterwarnings('ignore')
|
| 37 |
+
|
| 38 |
+
# Font settings
|
| 39 |
+
plt.rcParams['font.sans-serif'] = ['DejaVu Sans', 'SimHei']
|
| 40 |
+
plt.rcParams['axes.unicode_minus'] = False
|
| 41 |
+
|
| 42 |
+
# ============================================================================
|
| 43 |
+
# Helper Functions (from original script)
|
| 44 |
+
# ============================================================================
|
| 45 |
+
|
| 46 |
+
def compute_midrank(x):
|
| 47 |
+
J = np.argsort(x)
|
| 48 |
+
Z = x[J]
|
| 49 |
+
N = len(x)
|
| 50 |
+
T = np.zeros(N, dtype=float)
|
| 51 |
+
i = 0
|
| 52 |
+
while i < N:
|
| 53 |
+
j = i
|
| 54 |
+
while j < N and Z[j] == Z[i]:
|
| 55 |
+
j += 1
|
| 56 |
+
T[i:j] = 0.5 * (i + j - 1)
|
| 57 |
+
i = j
|
| 58 |
+
T2 = np.empty(N, dtype=float)
|
| 59 |
+
T2[J] = T + 1
|
| 60 |
+
return T2
|
| 61 |
+
|
| 62 |
+
def fastDeLong(predictions_sorted_transposed, label_1_count):
|
| 63 |
+
m = label_1_count
|
| 64 |
+
n = predictions_sorted_transposed.shape[1] - m
|
| 65 |
+
positive_examples = predictions_sorted_transposed[:, :m]
|
| 66 |
+
negative_examples = predictions_sorted_transposed[:, m:]
|
| 67 |
+
k = predictions_sorted_transposed.shape[0]
|
| 68 |
+
tx = np.empty([k, m], dtype=float)
|
| 69 |
+
ty = np.empty([k, n], dtype=float)
|
| 70 |
+
tz = np.empty([k, m + n], dtype=float)
|
| 71 |
+
for r in range(k):
|
| 72 |
+
tx[r, :] = compute_midrank(positive_examples[r, :])
|
| 73 |
+
ty[r, :] = compute_midrank(negative_examples[r, :])
|
| 74 |
+
tz[r, :] = compute_midrank(predictions_sorted_transposed[r, :])
|
| 75 |
+
aucs = tz[:, :m].sum(axis=1) / m / n - float(m + 1.0) / 2.0 / n
|
| 76 |
+
v01 = (tz[:, :m] - tx[:, :]) / n
|
| 77 |
+
v10 = 1.0 - (tz[:, m:] - ty[:, :]) / m
|
| 78 |
+
sx = np.cov(v01)
|
| 79 |
+
sy = np.cov(v10)
|
| 80 |
+
delongcov = sx / m + sy / n
|
| 81 |
+
return aucs, delongcov
|
| 82 |
+
|
| 83 |
+
def calc_pvalue(aucs, sigma):
|
| 84 |
+
l_mat = np.array([[1, -1]])
|
| 85 |
+
z = np.abs(np.diff(aucs)) / np.sqrt(np.dot(np.dot(l_mat, sigma), l_mat.T))
|
| 86 |
+
return np.log10(2) + stats.norm.logsf(z, loc=0, scale=1) / np.log(10)
|
| 87 |
+
|
| 88 |
+
def delong_roc_test(ground_truth, predictions_one, predictions_two):
|
| 89 |
+
order = (-ground_truth).argsort()
|
| 90 |
+
label_1_count = int(ground_truth.sum())
|
| 91 |
+
predictions_sorted_transposed = np.vstack([predictions_one, predictions_two])[:, order]
|
| 92 |
+
aucs, delongcov = fastDeLong(predictions_sorted_transposed, label_1_count)
|
| 93 |
+
p_value = 10 ** calc_pvalue(aucs, delongcov)[0][0]
|
| 94 |
+
return p_value, aucs[0], aucs[1]
|
| 95 |
+
|
| 96 |
+
def find_optimal_threshold(y_true, y_probs, method='youden'):
|
| 97 |
+
fpr, tpr, thresholds = roc_curve(y_true, y_probs)
|
| 98 |
+
if method == 'youden':
|
| 99 |
+
youden_index = tpr - fpr
|
| 100 |
+
optimal_idx = np.argmax(youden_index)
|
| 101 |
+
optimal_threshold = thresholds[optimal_idx]
|
| 102 |
+
metric_value = youden_index[optimal_idx]
|
| 103 |
+
elif method == 'f1':
|
| 104 |
+
f1_scores = []
|
| 105 |
+
for threshold in thresholds:
|
| 106 |
+
y_pred = (y_probs >= threshold).astype(int)
|
| 107 |
+
tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
|
| 108 |
+
precision = tp / (tp + fp) if (tp + fp) > 0 else 0
|
| 109 |
+
recall = tp / (tp + fn) if (tp + fn) > 0 else 0
|
| 110 |
+
f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0
|
| 111 |
+
f1_scores.append(f1)
|
| 112 |
+
optimal_idx = np.argmax(f1_scores)
|
| 113 |
+
optimal_threshold = thresholds[optimal_idx]
|
| 114 |
+
metric_value = f1_scores[optimal_idx]
|
| 115 |
+
elif method == 'gmean':
|
| 116 |
+
gmean = np.sqrt(tpr * (1 - fpr))
|
| 117 |
+
optimal_idx = np.argmax(gmean)
|
| 118 |
+
optimal_threshold = thresholds[optimal_idx]
|
| 119 |
+
metric_value = gmean[optimal_idx]
|
| 120 |
+
return optimal_threshold, metric_value, optimal_idx
|
| 121 |
+
|
| 122 |
+
def calculate_net_benefit(y_true, y_probs, threshold):
|
| 123 |
+
y_pred = (y_probs >= threshold).astype(int)
|
| 124 |
+
tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
|
| 125 |
+
n = len(y_true)
|
| 126 |
+
net_benefit = (tp / n) - (fp / n) * (threshold / (1 - threshold))
|
| 127 |
+
return net_benefit
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
# ============================================================================
|
| 131 |
+
# Model Configuration Builder
|
| 132 |
+
# ============================================================================
|
| 133 |
+
ALL_MODELS = ['RF', 'DT', 'KNN', 'XGB', 'AdaBoost', 'LR', 'NB', 'SVM']
|
| 134 |
+
|
| 135 |
+
def get_models_config(selected_models, random_state=42):
|
| 136 |
+
full_config = {
|
| 137 |
+
'RF': {
|
| 138 |
+
'model': RandomForestClassifier(random_state=random_state, n_jobs=-1),
|
| 139 |
+
'params': {
|
| 140 |
+
'n_estimators': [100, 200],
|
| 141 |
+
'max_depth': [20, 50],
|
| 142 |
+
'min_samples_split': [2, 5],
|
| 143 |
+
'max_features': ['sqrt']
|
| 144 |
+
},
|
| 145 |
+
},
|
| 146 |
+
'DT': {
|
| 147 |
+
'model': DecisionTreeClassifier(random_state=random_state),
|
| 148 |
+
'params': {
|
| 149 |
+
'max_depth': [20, 50],
|
| 150 |
+
'min_samples_split': [2, 10],
|
| 151 |
+
'min_samples_leaf': [1, 4],
|
| 152 |
+
'criterion': ['gini', 'entropy']
|
| 153 |
+
},
|
| 154 |
+
},
|
| 155 |
+
'KNN': {
|
| 156 |
+
'model': KNeighborsClassifier(n_jobs=-1),
|
| 157 |
+
'params': {
|
| 158 |
+
'n_neighbors': [3, 5, 7],
|
| 159 |
+
'weights': ['uniform', 'distance'],
|
| 160 |
+
'metric': ['euclidean', 'manhattan']
|
| 161 |
+
},
|
| 162 |
+
},
|
| 163 |
+
'XGB': {
|
| 164 |
+
'model': XGBClassifier(random_state=random_state, eval_metric='logloss', n_jobs=-1),
|
| 165 |
+
'params': {
|
| 166 |
+
'n_estimators': [100, 200],
|
| 167 |
+
'max_depth': [5, 7],
|
| 168 |
+
'learning_rate': [0.05, 0.1],
|
| 169 |
+
'subsample': [0.8, 1.0],
|
| 170 |
+
'colsample_bytree': [0.8, 1.0]
|
| 171 |
+
},
|
| 172 |
+
},
|
| 173 |
+
'AdaBoost': {
|
| 174 |
+
'model': AdaBoostClassifier(random_state=random_state),
|
| 175 |
+
'params': {
|
| 176 |
+
'n_estimators': [50, 100],
|
| 177 |
+
'learning_rate': [0.1, 0.5, 1.0]
|
| 178 |
+
},
|
| 179 |
+
},
|
| 180 |
+
'LR': {
|
| 181 |
+
'model': LogisticRegression(random_state=random_state, n_jobs=-1, max_iter=2000),
|
| 182 |
+
'params': {
|
| 183 |
+
'C': [0.1, 1, 10],
|
| 184 |
+
'penalty': ['l2'],
|
| 185 |
+
'solver': ['lbfgs', 'liblinear']
|
| 186 |
+
},
|
| 187 |
+
},
|
| 188 |
+
'NB': {
|
| 189 |
+
'model': GaussianNB(),
|
| 190 |
+
'params': {
|
| 191 |
+
'var_smoothing': [1e-9, 1e-7, 1e-5]
|
| 192 |
+
},
|
| 193 |
+
},
|
| 194 |
+
'SVM': {
|
| 195 |
+
'model': SVC(probability=True, random_state=random_state),
|
| 196 |
+
'params': {
|
| 197 |
+
'C': [1, 10],
|
| 198 |
+
'kernel': ['rbf', 'linear'],
|
| 199 |
+
'gamma': ['scale', 'auto']
|
| 200 |
+
},
|
| 201 |
+
}
|
| 202 |
+
}
|
| 203 |
+
return {k: v for k, v in full_config.items() if k in selected_models}
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# ============================================================================
|
| 207 |
+
# Main Pipeline
|
| 208 |
+
# ============================================================================
|
| 209 |
+
def run_pipeline(
|
| 210 |
+
train_file,
|
| 211 |
+
val_file,
|
| 212 |
+
selected_models,
|
| 213 |
+
enable_tuning,
|
| 214 |
+
cv_folds,
|
| 215 |
+
alpha,
|
| 216 |
+
top_n_features,
|
| 217 |
+
shap_sample_size,
|
| 218 |
+
progress=gr.Progress()
|
| 219 |
+
):
|
| 220 |
+
"""Main ML pipeline — returns (zip_path, log_text)"""
|
| 221 |
+
if train_file is None:
|
| 222 |
+
return None, "❌ 请上传训练集 CSV 文件!"
|
| 223 |
+
|
| 224 |
+
if not selected_models:
|
| 225 |
+
return None, "❌ 请至少选择一个模型!"
|
| 226 |
+
|
| 227 |
+
RANDOM_STATE = 42
|
| 228 |
+
CV_FOLDS = int(cv_folds)
|
| 229 |
+
ALPHA = float(alpha)
|
| 230 |
+
TOP_N_FEATURES = int(top_n_features)
|
| 231 |
+
SHAP_SAMPLE_SIZE = int(shap_sample_size)
|
| 232 |
+
ENABLE_HYPERPARAMETER_TUNING = enable_tuning
|
| 233 |
+
|
| 234 |
+
log_lines = []
|
| 235 |
+
def log(msg):
|
| 236 |
+
log_lines.append(msg)
|
| 237 |
+
|
| 238 |
+
# Create temp output folder
|
| 239 |
+
result_folder = tempfile.mkdtemp(prefix="ml_results_")
|
| 240 |
+
|
| 241 |
+
try:
|
| 242 |
+
# ======== Load Data ========
|
| 243 |
+
progress(0.02, desc="加载训练数据...")
|
| 244 |
+
log("=" * 70)
|
| 245 |
+
log("🚀 机器学习二分类模型训练与评估")
|
| 246 |
+
log("=" * 70)
|
| 247 |
+
|
| 248 |
+
data = pd.read_csv(train_file.name)
|
| 249 |
+
X = data.iloc[:, 2:]
|
| 250 |
+
y = data.iloc[:, 0]
|
| 251 |
+
feature_names = X.columns.tolist()
|
| 252 |
+
|
| 253 |
+
log(f"训练集: {X.shape[0]} 样本, {X.shape[1]} 特征")
|
| 254 |
+
log(f"标签分布: {dict(y.value_counts())}")
|
| 255 |
+
log(f"选择模型: {', '.join(selected_models)}")
|
| 256 |
+
log(f"超参数调优: {'启用' if ENABLE_HYPERPARAMETER_TUNING else '禁用'}")
|
| 257 |
+
log(f"交叉验证: {CV_FOLDS} 折")
|
| 258 |
+
|
| 259 |
+
models_config = get_models_config(selected_models, RANDOM_STATE)
|
| 260 |
+
skf = StratifiedKFold(n_splits=CV_FOLDS, shuffle=True, random_state=RANDOM_STATE)
|
| 261 |
+
|
| 262 |
+
# ======== Train All Models ========
|
| 263 |
+
best_params_dict = {}
|
| 264 |
+
all_model_results = {}
|
| 265 |
+
trained_models = {}
|
| 266 |
+
total_models = len(models_config)
|
| 267 |
+
|
| 268 |
+
for m_idx, (model_name, config) in enumerate(models_config.items()):
|
| 269 |
+
progress_val = 0.05 + 0.45 * (m_idx / total_models)
|
| 270 |
+
progress(progress_val, desc=f"训练模型 {model_name} ({m_idx+1}/{total_models})...")
|
| 271 |
+
log(f"\n{'*' * 50}")
|
| 272 |
+
log(f"模型: {model_name}")
|
| 273 |
+
|
| 274 |
+
X_scaled = X.values
|
| 275 |
+
|
| 276 |
+
if ENABLE_HYPERPARAMETER_TUNING:
|
| 277 |
+
log(f" 超参数调优 (GridSearchCV, CV={CV_FOLDS})...")
|
| 278 |
+
grid_search = GridSearchCV(
|
| 279 |
+
estimator=config['model'],
|
| 280 |
+
param_grid=config['params'],
|
| 281 |
+
cv=skf, scoring='roc_auc', n_jobs=-1, verbose=0
|
| 282 |
+
)
|
| 283 |
+
grid_search.fit(X_scaled, y)
|
| 284 |
+
best_params = grid_search.best_params_
|
| 285 |
+
best_params_dict[model_name] = best_params
|
| 286 |
+
log(f" ✓ 最佳参数: {best_params}")
|
| 287 |
+
log(f" ✓ 最佳CV AUC: {grid_search.best_score_:.4f}")
|
| 288 |
+
else:
|
| 289 |
+
best_params = {}
|
| 290 |
+
best_params_dict[model_name] = "默认参数"
|
| 291 |
+
|
| 292 |
+
model = deepcopy(config['model'])
|
| 293 |
+
if best_params:
|
| 294 |
+
model.set_params(**best_params)
|
| 295 |
+
model.fit(X_scaled, y)
|
| 296 |
+
trained_models[model_name] = {'model': model, 'scaler': None}
|
| 297 |
+
|
| 298 |
+
# Cross-validation
|
| 299 |
+
fold_results = []
|
| 300 |
+
all_y_true = []
|
| 301 |
+
all_y_probs = []
|
| 302 |
+
tprs = []
|
| 303 |
+
base_fpr = np.linspace(0, 1, 101)
|
| 304 |
+
|
| 305 |
+
for fold_idx, (train_idx, test_idx) in enumerate(skf.split(X, y), 1):
|
| 306 |
+
X_train_fold = X.iloc[train_idx].values
|
| 307 |
+
X_test_fold = X.iloc[test_idx].values
|
| 308 |
+
y_train_fold = y.iloc[train_idx]
|
| 309 |
+
y_test_fold = y.iloc[test_idx]
|
| 310 |
+
|
| 311 |
+
model_fold = deepcopy(config['model'])
|
| 312 |
+
if best_params:
|
| 313 |
+
model_fold.set_params(**best_params)
|
| 314 |
+
model_fold.fit(X_train_fold, y_train_fold)
|
| 315 |
+
|
| 316 |
+
y_pred_probs = model_fold.predict_proba(X_test_fold)[:, 1]
|
| 317 |
+
y_pred = (y_pred_probs > 0.5).astype(int)
|
| 318 |
+
|
| 319 |
+
tn, fp, fn, tp = confusion_matrix(y_test_fold, y_pred).ravel()
|
| 320 |
+
sensitivity = tp / (tp + fn) if (tp + fn) > 0 else 0
|
| 321 |
+
specificity = tn / (tn + fp) if (tn + fp) > 0 else 0
|
| 322 |
+
accuracy = (tp + tn) / (tp + tn + fp + fn)
|
| 323 |
+
prec = tp / (tp + fp) if (tp + fp) > 0 else 0
|
| 324 |
+
f1 = 2 * prec * sensitivity / (prec + sensitivity) if (prec + sensitivity) > 0 else 0
|
| 325 |
+
roc_auc = roc_auc_score(y_test_fold, y_pred_probs)
|
| 326 |
+
|
| 327 |
+
fold_results.append({
|
| 328 |
+
'Fold': fold_idx, 'AUC': roc_auc, 'Accuracy': accuracy,
|
| 329 |
+
'Sensitivity': sensitivity, 'Specificity': specificity,
|
| 330 |
+
'Precision': prec, 'F1 Score': f1,
|
| 331 |
+
'TP': tp, 'TN': tn, 'FP': fp, 'FN': fn
|
| 332 |
+
})
|
| 333 |
+
|
| 334 |
+
all_y_true.extend(y_test_fold)
|
| 335 |
+
all_y_probs.extend(y_pred_probs)
|
| 336 |
+
|
| 337 |
+
fpr_arr, tpr_arr, _ = roc_curve(y_test_fold, y_pred_probs)
|
| 338 |
+
tpr_interp = np.interp(base_fpr, fpr_arr, tpr_arr)
|
| 339 |
+
tpr_interp[0] = 0.0
|
| 340 |
+
tprs.append(tpr_interp)
|
| 341 |
+
|
| 342 |
+
results_df = pd.DataFrame(fold_results)
|
| 343 |
+
mean_row = {
|
| 344 |
+
'Fold': 'Mean±Std',
|
| 345 |
+
'AUC': results_df['AUC'].mean(),
|
| 346 |
+
'Accuracy': results_df['Accuracy'].mean(),
|
| 347 |
+
'Sensitivity': results_df['Sensitivity'].mean(),
|
| 348 |
+
'Specificity': results_df['Specificity'].mean(),
|
| 349 |
+
'Precision': results_df['Precision'].mean(),
|
| 350 |
+
'F1 Score': results_df['F1 Score'].mean(),
|
| 351 |
+
'TP': results_df['TP'].sum(), 'TN': results_df['TN'].sum(),
|
| 352 |
+
'FP': results_df['FP'].sum(), 'FN': results_df['FN'].sum()
|
| 353 |
+
}
|
| 354 |
+
results_df = pd.concat([results_df, pd.DataFrame([mean_row])], ignore_index=True)
|
| 355 |
+
|
| 356 |
+
all_model_results[model_name] = {
|
| 357 |
+
'results_df': results_df,
|
| 358 |
+
'mean_auc': results_df.iloc[-1]['AUC'],
|
| 359 |
+
'all_y_true': np.array(all_y_true),
|
| 360 |
+
'all_y_probs': np.array(all_y_probs),
|
| 361 |
+
'tprs': tprs,
|
| 362 |
+
'base_fpr': base_fpr
|
| 363 |
+
}
|
| 364 |
+
|
| 365 |
+
opt_thr, youden_val, _ = find_optimal_threshold(
|
| 366 |
+
np.array(all_y_true), np.array(all_y_probs), method='youden'
|
| 367 |
+
)
|
| 368 |
+
all_model_results[model_name]['optimal_threshold'] = opt_thr
|
| 369 |
+
all_model_results[model_name]['youden_index'] = youden_val
|
| 370 |
+
|
| 371 |
+
log(f" ✓ 平均AUC={mean_row['AUC']:.4f}, Acc={mean_row['Accuracy']:.4f}, 最佳阈值={opt_thr:.4f}")
|
| 372 |
+
|
| 373 |
+
log(f"\n{'=' * 70}")
|
| 374 |
+
log("所有模型训练完成!")
|
| 375 |
+
|
| 376 |
+
model_names = list(all_model_results.keys())
|
| 377 |
+
n_models = len(model_names)
|
| 378 |
+
|
| 379 |
+
# ======== ROC Curves (All Models - Internal CV) ========
|
| 380 |
+
progress(0.52, desc="绘制ROC曲线...")
|
| 381 |
+
colors_all = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f']
|
| 382 |
+
|
| 383 |
+
plt.figure(figsize=(12, 10))
|
| 384 |
+
for idx, mn in enumerate(model_names):
|
| 385 |
+
res = all_model_results[mn]
|
| 386 |
+
mean_tpr = np.mean(res['tprs'], axis=0)
|
| 387 |
+
mean_tpr[-1] = 1.0
|
| 388 |
+
mean_auc_val = auc_score(res['base_fpr'], mean_tpr)
|
| 389 |
+
std_auc = res['results_df'].iloc[:-1]['AUC'].std()
|
| 390 |
+
std_tpr = np.std(res['tprs'], axis=0)
|
| 391 |
+
tprs_upper = np.minimum(mean_tpr + std_tpr, 1)
|
| 392 |
+
tprs_lower = np.maximum(mean_tpr - std_tpr, 0)
|
| 393 |
+
plt.plot(res['base_fpr'], mean_tpr, color=colors_all[idx % 8], lw=2.5, alpha=0.8,
|
| 394 |
+
label=f'{mn} (AUC={mean_auc_val:.3f}±{std_auc:.3f})')
|
| 395 |
+
plt.plot(res['base_fpr'], tprs_upper, color=colors_all[idx % 8], lw=1, alpha=0.3, linestyle='--')
|
| 396 |
+
plt.plot(res['base_fpr'], tprs_lower, color=colors_all[idx % 8], lw=1, alpha=0.3, linestyle='--')
|
| 397 |
+
plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='gray', label='Chance', alpha=0.5)
|
| 398 |
+
plt.xlim([-0.05, 1.05]); plt.ylim([-0.05, 1.05])
|
| 399 |
+
plt.xlabel('FPR', fontsize=13); plt.ylabel('TPR', fontsize=13)
|
| 400 |
+
plt.title('ROC Curves (Internal CV)', fontsize=14, fontweight='bold')
|
| 401 |
+
plt.legend(loc="lower right", fontsize=10, framealpha=0.9)
|
| 402 |
+
plt.grid(True, alpha=0.3); plt.tight_layout()
|
| 403 |
+
plt.savefig(os.path.join(result_folder, 'roc_curves_all_models_internal_cv.pdf'), format='pdf', bbox_inches='tight', dpi=300)
|
| 404 |
+
plt.savefig(os.path.join(result_folder, 'roc_curves_all_models_internal_cv.png'), format='png', bbox_inches='tight', dpi=150)
|
| 405 |
+
plt.close()
|
| 406 |
+
|
| 407 |
+
# ======== PR Curves ========
|
| 408 |
+
progress(0.55, desc="绘制PR曲线...")
|
| 409 |
+
plt.figure(figsize=(12, 10))
|
| 410 |
+
for idx, mn in enumerate(model_names):
|
| 411 |
+
res = all_model_results[mn]
|
| 412 |
+
pr_aucs_fold = []
|
| 413 |
+
for train_idx, test_idx in skf.split(X, y):
|
| 414 |
+
cfg = models_config[mn]
|
| 415 |
+
X_tr = X.iloc[train_idx].values
|
| 416 |
+
X_te = X.iloc[test_idx].values
|
| 417 |
+
y_tr = y.iloc[train_idx]; y_te = y.iloc[test_idx]
|
| 418 |
+
m_pr = deepcopy(cfg['model'])
|
| 419 |
+
bp = best_params_dict[mn]
|
| 420 |
+
if isinstance(bp, dict) and bp:
|
| 421 |
+
m_pr.set_params(**bp)
|
| 422 |
+
m_pr.fit(X_tr, y_tr)
|
| 423 |
+
yp = m_pr.predict_proba(X_te)[:, 1]
|
| 424 |
+
prc, rec, _ = precision_recall_curve(y_te, yp)
|
| 425 |
+
pr_aucs_fold.append(auc_score(rec, prc))
|
| 426 |
+
mean_pr = np.mean(pr_aucs_fold); std_pr = np.std(pr_aucs_fold)
|
| 427 |
+
precision_all, recall_all, _ = precision_recall_curve(res['all_y_true'], res['all_y_probs'])
|
| 428 |
+
plt.plot(recall_all, precision_all, color=colors_all[idx % 8], lw=2.5, alpha=0.8,
|
| 429 |
+
label=f'{mn} (PR={mean_pr:.3f}±{std_pr:.3f})')
|
| 430 |
+
plt.xlim([-0.05, 1.05]); plt.ylim([-0.05, 1.05])
|
| 431 |
+
plt.xlabel('Recall', fontsize=13); plt.ylabel('Precision', fontsize=13)
|
| 432 |
+
plt.title('PR Curves (Internal CV)', fontsize=14, fontweight='bold')
|
| 433 |
+
plt.legend(loc="lower left", fontsize=10, framealpha=0.9)
|
| 434 |
+
plt.grid(True, alpha=0.3); plt.tight_layout()
|
| 435 |
+
plt.savefig(os.path.join(result_folder, 'pr_curves_all_models_internal_cv.pdf'), format='pdf', bbox_inches='tight', dpi=300)
|
| 436 |
+
plt.savefig(os.path.join(result_folder, 'pr_curves_all_models_internal_cv.png'), format='png', bbox_inches='tight', dpi=150)
|
| 437 |
+
plt.close()
|
| 438 |
+
|
| 439 |
+
# ======== Confusion Matrices ========
|
| 440 |
+
progress(0.58, desc="绘制混淆矩阵...")
|
| 441 |
+
n_rows = (n_models + 3) // 4
|
| 442 |
+
fig, axes = plt.subplots(n_rows, 4, figsize=(16, 4 * n_rows))
|
| 443 |
+
axes_flat = axes.flatten() if n_models > 1 else [axes]
|
| 444 |
+
for idx, mn in enumerate(model_names):
|
| 445 |
+
res = all_model_results[mn]
|
| 446 |
+
y_pred_cm = (res['all_y_probs'] >= res['optimal_threshold']).astype(int)
|
| 447 |
+
cm = confusion_matrix(res['all_y_true'], y_pred_cm)
|
| 448 |
+
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', cbar=False,
|
| 449 |
+
xticklabels=['Neg', 'Pos'], yticklabels=['Neg', 'Pos'],
|
| 450 |
+
ax=axes_flat[idx], annot_kws={'fontsize': 11})
|
| 451 |
+
axes_flat[idx].set_xlabel('Predicted', fontsize=11)
|
| 452 |
+
axes_flat[idx].set_ylabel('True', fontsize=11)
|
| 453 |
+
acc_cm = (cm[0, 0] + cm[1, 1]) / cm.sum()
|
| 454 |
+
axes_flat[idx].set_title(f'{mn}\n(Acc={acc_cm:.3f}, Thr={res["optimal_threshold"]:.3f})', fontsize=12, fontweight='bold')
|
| 455 |
+
for idx in range(n_models, len(axes_flat)):
|
| 456 |
+
axes_flat[idx].set_visible(False)
|
| 457 |
+
plt.suptitle('Confusion Matrices (Internal CV)', fontsize=15, fontweight='bold', y=1.00)
|
| 458 |
+
plt.tight_layout()
|
| 459 |
+
plt.savefig(os.path.join(result_folder, 'confusion_matrices_all_models.pdf'), format='pdf', bbox_inches='tight', dpi=300)
|
| 460 |
+
plt.savefig(os.path.join(result_folder, 'confusion_matrices_all_models.png'), format='png', bbox_inches='tight', dpi=150)
|
| 461 |
+
plt.close()
|
| 462 |
+
|
| 463 |
+
# ======== DeLong Test ========
|
| 464 |
+
progress(0.62, desc="DeLong检验...")
|
| 465 |
+
best_model_name = max(all_model_results, key=lambda x: all_model_results[x]['mean_auc'])
|
| 466 |
+
best_model_auc = all_model_results[best_model_name]['mean_auc']
|
| 467 |
+
log(f"\n最佳模型: {best_model_name} (AUC={best_model_auc:.4f})")
|
| 468 |
+
|
| 469 |
+
delong_results = []
|
| 470 |
+
retained_models = [best_model_name]
|
| 471 |
+
|
| 472 |
+
for other_model in model_names:
|
| 473 |
+
if other_model == best_model_name:
|
| 474 |
+
continue
|
| 475 |
+
y_true_dl = all_model_results[best_model_name]['all_y_true']
|
| 476 |
+
y_probs_best = all_model_results[best_model_name]['all_y_probs']
|
| 477 |
+
y_probs_other = all_model_results[other_model]['all_y_probs']
|
| 478 |
+
try:
|
| 479 |
+
p_value, auc1, auc2 = delong_roc_test(y_true_dl, y_probs_best, y_probs_other)
|
| 480 |
+
except:
|
| 481 |
+
p_value = 1.0; auc1 = best_model_auc; auc2 = all_model_results[other_model]['mean_auc']
|
| 482 |
+
if p_value >= ALPHA:
|
| 483 |
+
decision = f"保留 (P>={ALPHA})"
|
| 484 |
+
retained_models.append(other_model)
|
| 485 |
+
else:
|
| 486 |
+
decision = f"排除 (P<{ALPHA})"
|
| 487 |
+
delong_results.append({
|
| 488 |
+
'Model 1': best_model_name, 'AUC 1': auc1,
|
| 489 |
+
'Model 2': other_model, 'AUC 2': auc2,
|
| 490 |
+
'P-value': p_value, 'Decision': decision
|
| 491 |
+
})
|
| 492 |
+
log(f" {best_model_name} vs {other_model}: P={p_value:.4e} → {decision}")
|
| 493 |
+
|
| 494 |
+
delong_df = pd.DataFrame(delong_results).sort_values('P-value', ascending=False) if delong_results else pd.DataFrame()
|
| 495 |
+
log(f"保留模型: {', '.join(retained_models)}")
|
| 496 |
+
|
| 497 |
+
# ======== SHAP Analysis ========
|
| 498 |
+
progress(0.65, desc="SHAP特征重要性分析...")
|
| 499 |
+
shap_feature_importance = {}
|
| 500 |
+
|
| 501 |
+
for s_idx, mn in enumerate(retained_models):
|
| 502 |
+
progress(0.65 + 0.1 * (s_idx / len(retained_models)), desc=f"SHAP分析 {mn}...")
|
| 503 |
+
log(f"\n计算 {mn} 的SHAP值...")
|
| 504 |
+
model_obj = trained_models[mn]['model']
|
| 505 |
+
X_for_shap = X.values
|
| 506 |
+
n_samples = min(SHAP_SAMPLE_SIZE, X_for_shap.shape[0])
|
| 507 |
+
np.random.seed(RANDOM_STATE)
|
| 508 |
+
sample_indices = np.random.choice(X_for_shap.shape[0], n_samples, replace=False)
|
| 509 |
+
X_shap_sample = X_for_shap[sample_indices]
|
| 510 |
+
|
| 511 |
+
try:
|
| 512 |
+
if mn in ['RF', 'XGB', 'DT', 'AdaBoost']:
|
| 513 |
+
explainer = shap.TreeExplainer(model_obj)
|
| 514 |
+
shap_values = explainer.shap_values(X_shap_sample)
|
| 515 |
+
if isinstance(shap_values, list):
|
| 516 |
+
shap_values = shap_values[1]
|
| 517 |
+
else:
|
| 518 |
+
bg_size = min(100, n_samples)
|
| 519 |
+
bg_idx = np.random.choice(n_samples, bg_size, replace=False)
|
| 520 |
+
background = X_shap_sample[bg_idx]
|
| 521 |
+
def predict_fn(x, m=model_obj):
|
| 522 |
+
return m.predict_proba(x)[:, 1]
|
| 523 |
+
explainer = shap.KernelExplainer(predict_fn, background)
|
| 524 |
+
shap_values = explainer.shap_values(X_shap_sample)
|
| 525 |
+
|
| 526 |
+
if isinstance(shap_values, list):
|
| 527 |
+
shap_values = shap_values[0]
|
| 528 |
+
shap_values = np.array(shap_values)
|
| 529 |
+
if shap_values.ndim > 2:
|
| 530 |
+
shap_values = shap_values[0]
|
| 531 |
+
|
| 532 |
+
feature_importance = np.abs(shap_values).mean(axis=0)
|
| 533 |
+
if feature_importance.ndim > 1:
|
| 534 |
+
feature_importance = feature_importance.flatten()
|
| 535 |
+
if len(feature_importance) != len(feature_names):
|
| 536 |
+
feature_importance = feature_importance[:len(feature_names)] if len(feature_importance) > len(feature_names) else np.pad(feature_importance, (0, len(feature_names) - len(feature_importance)), 'constant')
|
| 537 |
+
|
| 538 |
+
importance_df = pd.DataFrame({'Feature': feature_names, 'Importance': feature_importance}).sort_values('Importance', ascending=False)
|
| 539 |
+
shap_feature_importance[mn] = importance_df
|
| 540 |
+
|
| 541 |
+
X_shap_df = pd.DataFrame(X_shap_sample, columns=feature_names)
|
| 542 |
+
if shap_values.shape[1] != X_shap_df.shape[1]:
|
| 543 |
+
if shap_values.shape[1] > X_shap_df.shape[1]:
|
| 544 |
+
shap_values = shap_values[:, :X_shap_df.shape[1]]
|
| 545 |
+
else:
|
| 546 |
+
padding = np.zeros((shap_values.shape[0], X_shap_df.shape[1] - shap_values.shape[1]))
|
| 547 |
+
shap_values = np.hstack([shap_values, padding])
|
| 548 |
+
|
| 549 |
+
plt.figure(figsize=(12, 8))
|
| 550 |
+
shap.summary_plot(shap_values, X_shap_df, plot_type="dot", show=False, max_display=TOP_N_FEATURES)
|
| 551 |
+
plt.title(f'SHAP Feature Importance - {mn} (Top {TOP_N_FEATURES})', fontsize=14, fontweight='bold')
|
| 552 |
+
plt.tight_layout()
|
| 553 |
+
plt.savefig(os.path.join(result_folder, f'shap_beeswarm_{mn}.pdf'), format='pdf', bbox_inches='tight')
|
| 554 |
+
plt.savefig(os.path.join(result_folder, f'shap_beeswarm_{mn}.png'), format='png', bbox_inches='tight', dpi=150)
|
| 555 |
+
plt.close()
|
| 556 |
+
log(f" ✓ {mn} SHAP完成, 前5特征: {', '.join(importance_df.head(5)['Feature'].tolist())}")
|
| 557 |
+
|
| 558 |
+
except Exception as e:
|
| 559 |
+
log(f" ✗ {mn} SHAP出错: {str(e)}")
|
| 560 |
+
traceback.print_exc()
|
| 561 |
+
|
| 562 |
+
# ======== Feature Ablation ========
|
| 563 |
+
progress(0.78, desc="特征消融分析...")
|
| 564 |
+
ablation_results = {}
|
| 565 |
+
for mn in retained_models:
|
| 566 |
+
if mn not in shap_feature_importance:
|
| 567 |
+
continue
|
| 568 |
+
log(f"\n特征消融: {mn}")
|
| 569 |
+
imp_df = shap_feature_importance[mn]
|
| 570 |
+
top_features = imp_df.head(TOP_N_FEATURES)['Feature'].tolist()
|
| 571 |
+
feature_counts = []; auc_scores_abl = []; all_subset_probs = {}
|
| 572 |
+
cfg = models_config[mn]
|
| 573 |
+
|
| 574 |
+
for n_feat in range(1, len(top_features) + 1):
|
| 575 |
+
sel_feats = top_features[:n_feat]
|
| 576 |
+
X_sub = X[sel_feats]
|
| 577 |
+
fold_aucs = []; sub_yt = []; sub_yp = []
|
| 578 |
+
for train_idx, test_idx in skf.split(X_sub, y):
|
| 579 |
+
X_tr = X_sub.iloc[train_idx].values; X_te = X_sub.iloc[test_idx].values
|
| 580 |
+
y_tr = y.iloc[train_idx]; y_te = y.iloc[test_idx]
|
| 581 |
+
m_f = deepcopy(cfg['model'])
|
| 582 |
+
bp = best_params_dict.get(mn, {})
|
| 583 |
+
if isinstance(bp, dict) and bp:
|
| 584 |
+
m_f.set_params(**bp)
|
| 585 |
+
m_f.fit(X_tr, y_tr)
|
| 586 |
+
yp = m_f.predict_proba(X_te)[:, 1]
|
| 587 |
+
sub_yt.extend(y_te); sub_yp.extend(yp)
|
| 588 |
+
fold_aucs.append(roc_auc_score(y_te, yp))
|
| 589 |
+
ma = np.mean(fold_aucs)
|
| 590 |
+
feature_counts.append(n_feat); auc_scores_abl.append(ma)
|
| 591 |
+
all_subset_probs[n_feat] = {'y_true': np.array(sub_yt), 'y_probs': np.array(sub_yp)}
|
| 592 |
+
|
| 593 |
+
# DeLong for ablation
|
| 594 |
+
full_probs = all_model_results[mn]['all_y_probs']
|
| 595 |
+
full_auc = all_model_results[mn]['mean_auc']
|
| 596 |
+
optimal_n = None
|
| 597 |
+
abl_delong = []
|
| 598 |
+
for n_feat in range(1, len(top_features) + 1):
|
| 599 |
+
sd = all_subset_probs[n_feat]
|
| 600 |
+
sauc = auc_scores_abl[n_feat - 1]
|
| 601 |
+
try:
|
| 602 |
+
if len(full_probs) == len(sd['y_probs']):
|
| 603 |
+
pv, _, _ = delong_roc_test(sd['y_true'], full_probs, sd['y_probs'])
|
| 604 |
+
else:
|
| 605 |
+
pv = 0.1 if abs(sauc - full_auc) <= 0.05 else 0.01
|
| 606 |
+
except:
|
| 607 |
+
pv = 0.1 if abs(sauc - full_auc) <= 0.05 else 0.01
|
| 608 |
+
sig = "有显著差异" if pv < ALPHA else "无显著差异"
|
| 609 |
+
abl_delong.append({'N_Features': n_feat, 'Subset_AUC': sauc, 'Full_AUC': full_auc, 'P_value': pv, 'Significance': sig})
|
| 610 |
+
if optimal_n is None and pv >= ALPHA:
|
| 611 |
+
optimal_n = n_feat
|
| 612 |
+
|
| 613 |
+
ablation_results[mn] = {
|
| 614 |
+
'feature_counts': feature_counts, 'auc_scores': auc_scores_abl,
|
| 615 |
+
'top_features': top_features, 'delong_results': pd.DataFrame(abl_delong),
|
| 616 |
+
'optimal_n_features': optimal_n if optimal_n else len(top_features),
|
| 617 |
+
'optimal_features': top_features[:optimal_n] if optimal_n else top_features
|
| 618 |
+
}
|
| 619 |
+
log(f" ✓ {mn} 最优特征数: {ablation_results[mn]['optimal_n_features']}")
|
| 620 |
+
|
| 621 |
+
# ======== Select Final Model ========
|
| 622 |
+
final_candidates = {}
|
| 623 |
+
for mn in retained_models:
|
| 624 |
+
if mn in ablation_results:
|
| 625 |
+
ar = ablation_results[mn]
|
| 626 |
+
final_candidates[mn] = {
|
| 627 |
+
'n_features': ar['optimal_n_features'],
|
| 628 |
+
'features': ar['optimal_features'],
|
| 629 |
+
'auc': ar['auc_scores'][ar['optimal_n_features'] - 1]
|
| 630 |
+
}
|
| 631 |
+
final_model_name = min(final_candidates, key=lambda x: final_candidates[x]['n_features']) if final_candidates else None
|
| 632 |
+
final_model_info = final_candidates.get(final_model_name) if final_model_name else None
|
| 633 |
+
|
| 634 |
+
if final_model_name:
|
| 635 |
+
log(f"\n★ 最终模型: {final_model_name}, 特征数={final_model_info['n_features']}, AUC={final_model_info['auc']:.4f}")
|
| 636 |
+
|
| 637 |
+
# ======== Ablation Plot ========
|
| 638 |
+
progress(0.83, desc="绘制消融曲线...")
|
| 639 |
+
plt.figure(figsize=(12, 8))
|
| 640 |
+
colors_abl = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'orange']
|
| 641 |
+
for idx, (mn, ar) in enumerate(ablation_results.items()):
|
| 642 |
+
plt.plot(ar['feature_counts'], ar['auc_scores'], marker='o', lw=2, ms=6,
|
| 643 |
+
color=colors_abl[idx % 8], label=mn)
|
| 644 |
+
opt_n = ar['optimal_n_features']
|
| 645 |
+
opt_auc = ar['auc_scores'][opt_n - 1]
|
| 646 |
+
plt.scatter([opt_n], [opt_auc], s=200, marker='*', color=colors_abl[idx % 8], edgecolors='black', lw=2, zorder=5)
|
| 647 |
+
plt.xlabel('Number of Features', fontsize=13); plt.ylabel('AUC', fontsize=13)
|
| 648 |
+
plt.title('Feature Ablation (★=Optimal)', fontsize=14, fontweight='bold')
|
| 649 |
+
plt.legend(loc='lower right', fontsize=11); plt.grid(True, alpha=0.3)
|
| 650 |
+
plt.tight_layout()
|
| 651 |
+
plt.savefig(os.path.join(result_folder, 'feature_ablation_curve.pdf'), format='pdf', bbox_inches='tight')
|
| 652 |
+
plt.savefig(os.path.join(result_folder, 'feature_ablation_curve.png'), format='png', bbox_inches='tight', dpi=150)
|
| 653 |
+
plt.close()
|
| 654 |
+
|
| 655 |
+
# ======== DCA Curves (Retained Models) ========
|
| 656 |
+
progress(0.85, desc="绘制DCA曲线...")
|
| 657 |
+
plt.figure(figsize=(12, 8))
|
| 658 |
+
threshold_range = np.linspace(0.01, 0.99, 100)
|
| 659 |
+
for idx, mn in enumerate(retained_models):
|
| 660 |
+
res = all_model_results[mn]
|
| 661 |
+
nbs = [calculate_net_benefit(res['all_y_true'], res['all_y_probs'], t) for t in threshold_range]
|
| 662 |
+
lbl = f'{mn} ★' if mn == final_model_name else mn
|
| 663 |
+
plt.plot(threshold_range, nbs, color=colors_abl[idx % 8], lw=2.5, alpha=0.8, label=lbl)
|
| 664 |
+
prevalence = np.mean(all_model_results[retained_models[0]]['all_y_true'])
|
| 665 |
+
treat_all = [(prevalence - (1 - prevalence) * (pt / (1 - pt))) for pt in threshold_range]
|
| 666 |
+
plt.plot(threshold_range, treat_all, 'k--', lw=2, alpha=0.5, label='Treat All')
|
| 667 |
+
plt.plot(threshold_range, [0] * len(threshold_range), 'gray', lw=2, alpha=0.5, label='Treat None')
|
| 668 |
+
plt.xlim([0, 1]); plt.xlabel('Threshold', fontsize=13); plt.ylabel('Net Benefit', fontsize=13)
|
| 669 |
+
plt.title('Decision Curve Analysis', fontsize=14, fontweight='bold')
|
| 670 |
+
plt.legend(loc="upper right", fontsize=11); plt.grid(True, alpha=0.3); plt.tight_layout()
|
| 671 |
+
plt.savefig(os.path.join(result_folder, 'dca_curve_retained_models.pdf'), format='pdf', bbox_inches='tight')
|
| 672 |
+
plt.savefig(os.path.join(result_folder, 'dca_curve_retained_models.png'), format='png', bbox_inches='tight', dpi=150)
|
| 673 |
+
plt.close()
|
| 674 |
+
|
| 675 |
+
# ======== External Validation ========
|
| 676 |
+
if val_file is not None and final_model_name:
|
| 677 |
+
progress(0.88, desc="外部验证...")
|
| 678 |
+
log(f"\n{'=' * 70}")
|
| 679 |
+
log("外部验证集评估")
|
| 680 |
+
|
| 681 |
+
ext_data = pd.read_csv(val_file.name)
|
| 682 |
+
X_ext = ext_data.iloc[:, 2:]
|
| 683 |
+
y_ext = ext_data.iloc[:, 0]
|
| 684 |
+
log(f"验证集: {X_ext.shape[0]} 样本, {X_ext.shape[1]} 特征")
|
| 685 |
+
|
| 686 |
+
X_ext_sel = X_ext[final_model_info['features']]
|
| 687 |
+
X_train_f = X[final_model_info['features']]
|
| 688 |
+
cfg = models_config[final_model_name]
|
| 689 |
+
|
| 690 |
+
final_m = deepcopy(cfg['model'])
|
| 691 |
+
bp = best_params_dict[final_model_name]
|
| 692 |
+
if isinstance(bp, dict) and bp:
|
| 693 |
+
final_m.set_params(**bp)
|
| 694 |
+
final_m.fit(X_train_f.values, y)
|
| 695 |
+
|
| 696 |
+
y_ext_probs = final_m.predict_proba(X_ext_sel.values)[:, 1]
|
| 697 |
+
y_ext_pred = (y_ext_probs > 0.5).astype(int)
|
| 698 |
+
|
| 699 |
+
tn, fp, fn, tp = confusion_matrix(y_ext, y_ext_pred).ravel()
|
| 700 |
+
sens = tp / (tp + fn) if (tp + fn) > 0 else 0
|
| 701 |
+
spec = tn / (tn + fp) if (tn + fp) > 0 else 0
|
| 702 |
+
acc = (tp + tn) / (tp + tn + fp + fn)
|
| 703 |
+
prec = tp / (tp + fp) if (tp + fp) > 0 else 0
|
| 704 |
+
f1 = 2 * prec * sens / (prec + sens) if (prec + sens) > 0 else 0
|
| 705 |
+
ext_auc = roc_auc_score(y_ext, y_ext_probs)
|
| 706 |
+
|
| 707 |
+
log(f" AUC={ext_auc:.4f}, Acc={acc:.4f}, Sens={sens:.4f}, Spec={spec:.4f}, F1={f1:.4f}")
|
| 708 |
+
|
| 709 |
+
# External ROC
|
| 710 |
+
fpr_e, tpr_e, _ = roc_curve(y_ext, y_ext_probs)
|
| 711 |
+
plt.figure(figsize=(10, 8))
|
| 712 |
+
plt.plot(fpr_e, tpr_e, 'b', lw=2.5, label=f'{final_model_name} (AUC={ext_auc:.3f})')
|
| 713 |
+
plt.plot([0, 1], [0, 1], '--', color='gray', alpha=0.5)
|
| 714 |
+
plt.xlabel('FPR'); plt.ylabel('TPR')
|
| 715 |
+
plt.title(f'ROC - External Validation ({final_model_name})', fontweight='bold')
|
| 716 |
+
plt.legend(loc="lower right"); plt.grid(True, alpha=0.3); plt.tight_layout()
|
| 717 |
+
plt.savefig(os.path.join(result_folder, 'roc_external_validation.pdf'), format='pdf', bbox_inches='tight')
|
| 718 |
+
plt.savefig(os.path.join(result_folder, 'roc_external_validation.png'), format='png', bbox_inches='tight', dpi=150)
|
| 719 |
+
plt.close()
|
| 720 |
+
|
| 721 |
+
# External CM
|
| 722 |
+
cm_ext = confusion_matrix(y_ext, y_ext_pred)
|
| 723 |
+
plt.figure(figsize=(8, 6))
|
| 724 |
+
sns.heatmap(cm_ext, annot=True, fmt='d', cmap='Blues', cbar=False,
|
| 725 |
+
xticklabels=['Neg', 'Pos'], yticklabels=['Neg', 'Pos'])
|
| 726 |
+
plt.xlabel('Predicted'); plt.ylabel('True')
|
| 727 |
+
plt.title(f'Confusion Matrix - External ({final_model_name})', fontweight='bold')
|
| 728 |
+
plt.tight_layout()
|
| 729 |
+
plt.savefig(os.path.join(result_folder, 'cm_external_validation.pdf'), format='pdf', bbox_inches='tight')
|
| 730 |
+
plt.savefig(os.path.join(result_folder, 'cm_external_validation.png'), format='png', bbox_inches='tight', dpi=150)
|
| 731 |
+
plt.close()
|
| 732 |
+
|
| 733 |
+
# External PR
|
| 734 |
+
pr_e, re_e, _ = precision_recall_curve(y_ext, y_ext_probs)
|
| 735 |
+
plt.figure(figsize=(10, 8))
|
| 736 |
+
plt.plot(re_e, pr_e, 'b', lw=2.5, label=final_model_name)
|
| 737 |
+
plt.xlabel('Recall'); plt.ylabel('Precision')
|
| 738 |
+
plt.title(f'PR Curve - External ({final_model_name})', fontweight='bold')
|
| 739 |
+
plt.legend(); plt.grid(True, alpha=0.3); plt.tight_layout()
|
| 740 |
+
plt.savefig(os.path.join(result_folder, 'pr_external_validation.pdf'), format='pdf', bbox_inches='tight')
|
| 741 |
+
plt.savefig(os.path.join(result_folder, 'pr_external_validation.png'), format='png', bbox_inches='tight', dpi=150)
|
| 742 |
+
plt.close()
|
| 743 |
+
|
| 744 |
+
# External DCA
|
| 745 |
+
opt_thr_e, _, _ = find_optimal_threshold(y_ext, y_ext_probs, method='youden')
|
| 746 |
+
nbs_ext = [calculate_net_benefit(y_ext, y_ext_probs, t) for t in threshold_range]
|
| 747 |
+
prev_e = np.mean(y_ext)
|
| 748 |
+
ta_e = [(prev_e - (1 - prev_e) * (pt / (1 - pt))) for pt in threshold_range]
|
| 749 |
+
plt.figure(figsize=(10, 8))
|
| 750 |
+
plt.plot(threshold_range, nbs_ext, 'b', lw=2.5, label=final_model_name)
|
| 751 |
+
plt.plot(threshold_range, ta_e, 'k--', lw=2, alpha=0.5, label='Treat All')
|
| 752 |
+
plt.plot(threshold_range, [0]*len(threshold_range), 'gray', lw=2, alpha=0.5, label='Treat None')
|
| 753 |
+
plt.xlabel('Threshold'); plt.ylabel('Net Benefit')
|
| 754 |
+
plt.title(f'DCA - External ({final_model_name})', fontweight='bold')
|
| 755 |
+
plt.legend(loc="upper right"); plt.grid(True, alpha=0.3); plt.tight_layout()
|
| 756 |
+
plt.savefig(os.path.join(result_folder, 'dca_external_validation.pdf'), format='pdf', bbox_inches='tight')
|
| 757 |
+
plt.savefig(os.path.join(result_folder, 'dca_external_validation.png'), format='png', bbox_inches='tight', dpi=150)
|
| 758 |
+
plt.close()
|
| 759 |
+
|
| 760 |
+
# Save external validation Excel
|
| 761 |
+
with pd.ExcelWriter(os.path.join(result_folder, 'external_validation_results.xlsx'), engine='openpyxl') as writer:
|
| 762 |
+
pd.DataFrame([{
|
| 763 |
+
'Model': final_model_name, 'N_Features': final_model_info['n_features'],
|
| 764 |
+
'AUC': ext_auc, 'Accuracy': acc, 'Sensitivity': sens,
|
| 765 |
+
'Specificity': spec, 'Precision': prec, 'F1 Score': f1
|
| 766 |
+
}]).to_excel(writer, sheet_name='Metrics', index=False)
|
| 767 |
+
pd.DataFrame({'Feature': final_model_info['features']}).to_excel(writer, sheet_name='Features', index=False)
|
| 768 |
+
pd.DataFrame({'True': y_ext, 'Predicted': y_ext_pred, 'Probability': y_ext_probs}).to_excel(writer, sheet_name='Predictions', index=False)
|
| 769 |
+
|
| 770 |
+
# ======== Save Excel Results ========
|
| 771 |
+
progress(0.92, desc="保存结果到Excel...")
|
| 772 |
+
|
| 773 |
+
# Model evaluation Excel
|
| 774 |
+
with pd.ExcelWriter(os.path.join(result_folder, 'model_evaluation_results.xlsx'), engine='openpyxl') as writer:
|
| 775 |
+
for mn, res in all_model_results.items():
|
| 776 |
+
res['results_df'].to_excel(writer, sheet_name=mn, index=False)
|
| 777 |
+
summary_data = []
|
| 778 |
+
for mn, res in all_model_results.items():
|
| 779 |
+
row = res['results_df'].iloc[-1].to_dict()
|
| 780 |
+
row['Model'] = mn
|
| 781 |
+
row['Retained'] = 'Yes' if mn in retained_models else 'No'
|
| 782 |
+
row['Is_Final'] = 'Yes' if mn == final_model_name else 'No'
|
| 783 |
+
summary_data.append(row)
|
| 784 |
+
summary_df = pd.DataFrame(summary_data)
|
| 785 |
+
cols = ['Model', 'Retained', 'Is_Final'] + [c for c in summary_df.columns if c not in ['Model', 'Fold', 'Retained', 'Is_Final']]
|
| 786 |
+
summary_df[cols].sort_values('AUC', ascending=False).to_excel(writer, sheet_name='Summary', index=False)
|
| 787 |
+
if len(delong_df) > 0:
|
| 788 |
+
delong_df.to_excel(writer, sheet_name='DeLong_Test', index=False)
|
| 789 |
+
|
| 790 |
+
# Feature ablation Excel
|
| 791 |
+
with pd.ExcelWriter(os.path.join(result_folder, 'feature_ablation_results.xlsx'), engine='openpyxl') as writer:
|
| 792 |
+
for mn, ar in ablation_results.items():
|
| 793 |
+
abl_df = pd.DataFrame({'Feature_Count': ar['feature_counts'], 'AUC': ar['auc_scores']})
|
| 794 |
+
abl_df.to_excel(writer, sheet_name=mn, index=False)
|
| 795 |
+
if 'delong_results' in ar:
|
| 796 |
+
ar['delong_results'].to_excel(writer, sheet_name=f'{mn}_DeLong', index=False)
|
| 797 |
+
for mn, imp_df in shap_feature_importance.items():
|
| 798 |
+
imp_df.to_excel(writer, sheet_name=f'{mn}_Importance', index=False)
|
| 799 |
+
|
| 800 |
+
# Save best params txt
|
| 801 |
+
with open(os.path.join(result_folder, 'best_parameters.txt'), 'w', encoding='utf-8') as f:
|
| 802 |
+
f.write("=" * 70 + "\n")
|
| 803 |
+
f.write("各模型最佳超参数\n")
|
| 804 |
+
f.write("=" * 70 + "\n\n")
|
| 805 |
+
for mn in models_config.keys():
|
| 806 |
+
f.write(f"\n模型: {mn}\n")
|
| 807 |
+
params = best_params_dict[mn]
|
| 808 |
+
if isinstance(params, dict):
|
| 809 |
+
for k, v in params.items():
|
| 810 |
+
f.write(f" {k}: {v}\n")
|
| 811 |
+
else:
|
| 812 |
+
f.write(f" {params}\n")
|
| 813 |
+
f.write(f" AUC: {all_model_results[mn]['mean_auc']:.4f}\n")
|
| 814 |
+
f.write(f" 保留: {'是' if mn in retained_models else '否'}\n")
|
| 815 |
+
if final_model_name:
|
| 816 |
+
f.write(f"\n\n最终模型: {final_model_name}\n")
|
| 817 |
+
f.write(f"特征数: {final_model_info['n_features']}\n")
|
| 818 |
+
f.write(f"特征: {', '.join(final_model_info['features'])}\n")
|
| 819 |
+
|
| 820 |
+
# Save final model pickle
|
| 821 |
+
if final_model_name:
|
| 822 |
+
pickle.dump({
|
| 823 |
+
'model_name': final_model_name,
|
| 824 |
+
'model': trained_models[final_model_name]['model'],
|
| 825 |
+
'best_params': best_params_dict[final_model_name],
|
| 826 |
+
'optimal_features': final_model_info['features'],
|
| 827 |
+
'n_features': final_model_info['n_features'],
|
| 828 |
+
'train_auc': final_model_info['auc'],
|
| 829 |
+
'optimal_threshold': all_model_results[final_model_name]['optimal_threshold']
|
| 830 |
+
}, open(os.path.join(result_folder, f'final_model_{final_model_name}.pkl'), 'wb'))
|
| 831 |
+
|
| 832 |
+
# ======== Create ZIP ========
|
| 833 |
+
progress(0.96, desc="打包为ZIP...")
|
| 834 |
+
zip_path = os.path.join(tempfile.gettempdir(), "ml_results.zip")
|
| 835 |
+
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 836 |
+
for root, dirs, files in os.walk(result_folder):
|
| 837 |
+
for file in files:
|
| 838 |
+
filepath = os.path.join(root, file)
|
| 839 |
+
arcname = os.path.relpath(filepath, result_folder)
|
| 840 |
+
zf.write(filepath, arcname)
|
| 841 |
+
|
| 842 |
+
n_files = len([f for _, _, files in os.walk(result_folder) for f in files])
|
| 843 |
+
log(f"\n{'=' * 70}")
|
| 844 |
+
log(f"✅ 分析完成! 共生成 {n_files} 个文件")
|
| 845 |
+
log(f"{'=' * 70}")
|
| 846 |
+
|
| 847 |
+
progress(1.0, desc="完成!")
|
| 848 |
+
return zip_path, "\n".join(log_lines)
|
| 849 |
+
|
| 850 |
+
except Exception as e:
|
| 851 |
+
log(f"\n❌ 运行出错: {str(e)}")
|
| 852 |
+
log(traceback.format_exc())
|
| 853 |
+
return None, "\n".join(log_lines)
|
| 854 |
+
|
| 855 |
+
|
| 856 |
+
# ============================================================================
|
| 857 |
+
# Gradio Interface
|
| 858 |
+
# ============================================================================
|
| 859 |
+
|
| 860 |
+
DESCRIPTION = """
|
| 861 |
+
# 🧬 ML 二分类模型训练与评估平台
|
| 862 |
+
|
| 863 |
+
上传训练集和验证集 CSV 文件,自动完成以下分析流程:
|
| 864 |
+
|
| 865 |
+
**📊 分析内容:** 8种机器学习模型训练 → 交叉验证 → DeLong检验筛选 → SHAP特征重要性 → 特征消融 → 外部验证
|
| 866 |
+
|
| 867 |
+
**📁 数据格式要求:** CSV文件,第1列为标签(0/1),第2列任意(如ID),第3列起为特征
|
| 868 |
+
|
| 869 |
+
**⬇️ 输出:** 所有结果打包为ZIP下载(含PDF图表 + PNG图表 + Excel数据 + 模型文件)
|
| 870 |
+
"""
|
| 871 |
+
|
| 872 |
+
with gr.Blocks(
|
| 873 |
+
title="ML Binary Classification Pipeline",
|
| 874 |
+
theme=gr.themes.Soft(
|
| 875 |
+
primary_hue="blue",
|
| 876 |
+
secondary_hue="slate",
|
| 877 |
+
),
|
| 878 |
+
css="""
|
| 879 |
+
.main-header { text-align: center; margin-bottom: 1rem; }
|
| 880 |
+
.model-selector label { font-weight: 600; }
|
| 881 |
+
footer { display: none !important; }
|
| 882 |
+
"""
|
| 883 |
+
) as demo:
|
| 884 |
+
|
| 885 |
+
gr.Markdown(DESCRIPTION)
|
| 886 |
+
|
| 887 |
+
with gr.Row():
|
| 888 |
+
with gr.Column(scale=1):
|
| 889 |
+
gr.Markdown("### 📂 数据上传")
|
| 890 |
+
train_file = gr.File(label="训练集 CSV(必需)", file_types=[".csv"])
|
| 891 |
+
val_file = gr.File(label="验证集 CSV(可选)", file_types=[".csv"])
|
| 892 |
+
|
| 893 |
+
gr.Markdown("### 🤖 模型选择")
|
| 894 |
+
model_selector = gr.CheckboxGroup(
|
| 895 |
+
choices=ALL_MODELS,
|
| 896 |
+
value=ALL_MODELS,
|
| 897 |
+
label="选择要运行的模型(可多选)",
|
| 898 |
+
info="默认全选8个模型,可取消不需要的"
|
| 899 |
+
)
|
| 900 |
+
|
| 901 |
+
gr.Markdown("### ⚙️ 参数设置")
|
| 902 |
+
enable_tuning = gr.Checkbox(value=True, label="启用超参数调优 (GridSearchCV)")
|
| 903 |
+
with gr.Row():
|
| 904 |
+
cv_folds = gr.Slider(minimum=3, maximum=10, value=5, step=1, label="交叉验证折数")
|
| 905 |
+
alpha = gr.Slider(minimum=0.01, maximum=0.10, value=0.05, step=0.01, label="DeLong显著性水平 α")
|
| 906 |
+
with gr.Row():
|
| 907 |
+
top_n = gr.Slider(minimum=5, maximum=50, value=20, step=1, label="SHAP前N个特征")
|
| 908 |
+
shap_samples = gr.Slider(minimum=30, maximum=200, value=80, step=10, label="SHAP采样数量")
|
| 909 |
+
|
| 910 |
+
run_btn = gr.Button("🚀 开始运行", variant="primary", size="lg")
|
| 911 |
+
|
| 912 |
+
with gr.Column(scale=1):
|
| 913 |
+
gr.Markdown("### 📋 运行日志")
|
| 914 |
+
log_output = gr.Textbox(label="实时日志", lines=25, max_lines=50, interactive=False)
|
| 915 |
+
|
| 916 |
+
gr.Markdown("### ⬇️ 结果下载")
|
| 917 |
+
zip_output = gr.File(label="下载结果 ZIP")
|
| 918 |
+
|
| 919 |
+
# Quick-select buttons
|
| 920 |
+
with gr.Row():
|
| 921 |
+
gr.Markdown("""
|
| 922 |
+
**💡 快捷模型组合:**
|
| 923 |
+
点击下方按钮快速选择常用组合
|
| 924 |
+
""")
|
| 925 |
+
|
| 926 |
+
with gr.Row():
|
| 927 |
+
btn_all = gr.Button("全选", size="sm")
|
| 928 |
+
btn_tree = gr.Button("树模型 (RF+DT+XGB+AdaBoost)", size="sm")
|
| 929 |
+
btn_linear = gr.Button("线性模型 (LR+SVM+NB)", size="sm")
|
| 930 |
+
btn_top4 = gr.Button("经典四模型 (RF+XGB+LR+SVM)", size="sm")
|
| 931 |
+
|
| 932 |
+
btn_all.click(lambda: ALL_MODELS, outputs=model_selector)
|
| 933 |
+
btn_tree.click(lambda: ['RF', 'DT', 'XGB', 'AdaBoost'], outputs=model_selector)
|
| 934 |
+
btn_linear.click(lambda: ['LR', 'SVM', 'NB'], outputs=model_selector)
|
| 935 |
+
btn_top4.click(lambda: ['RF', 'XGB', 'LR', 'SVM'], outputs=model_selector)
|
| 936 |
+
|
| 937 |
+
# Run
|
| 938 |
+
run_btn.click(
|
| 939 |
+
fn=run_pipeline,
|
| 940 |
+
inputs=[train_file, val_file, model_selector, enable_tuning, cv_folds, alpha, top_n, shap_samples],
|
| 941 |
+
outputs=[zip_output, log_output],
|
| 942 |
+
show_progress="full"
|
| 943 |
+
)
|
| 944 |
+
|
| 945 |
+
if __name__ == "__main__":
|
| 946 |
+
demo.queue().launch(server_name="0.0.0.0", server_port=7860)
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy>=1.24.0
|
| 2 |
+
pandas>=2.0.0
|
| 3 |
+
matplotlib>=3.7.0
|
| 4 |
+
scikit-learn>=1.3.0
|
| 5 |
+
xgboost>=2.0.0
|
| 6 |
+
seaborn>=0.12.0
|
| 7 |
+
scipy>=1.11.0
|
| 8 |
+
shap>=0.43.0
|
| 9 |
+
openpyxl>=3.1.0
|
| 10 |
+
gradio>=4.0.0
|