1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
|
import joblib import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from imblearn.over_sampling import SMOTE from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from lightgbm import LGBMClassifier from xgboost import XGBClassifier from sklearn.metrics import roc_auc_score from sklearn.svm import SVC from sklearn.naive_bayes import BernoulliNB from sklearn.ensemble import GradientBoostingClassifier from sklearn.model_selection import GridSearchCV from sklearn.metrics import roc_curve, auc as auc_func, f1_score, accuracy_score, precision_score, recall_score, confusion_matrix from sklearn.base import BaseEstimator, ClassifierMixin
plt.rcParams['font.family'] = 'Times New Roman' plt.rcParams['axes.unicode_minus'] = False import warnings warnings.filterwarnings("ignore")
def evaluate_model_performance(model, X_resampled, y_resampled, n_iterations = 1000, random_state = 42): """ 使用 Bootstrap 采样评估分类模型的性能,并计算多个指标的中位数和 95% 置信区间。 参数: model : 已训练的分类模型(例如 best_dt_model) X_resampled : 输入特征数据(已重采样的数据) y_resampled : 目标标签数据(已重采样的数据) n_iterations : Bootstrap 采样的次数,默认为 1000 random_state : 随机种子,用于保证每次采样结果可复现 返回: 包含各项性能指标中位数和95%置信区间的字典 """ y_pred = model.predict(X_resampled) y_probas = model.predict_proba(X_resampled) auc_scores = [] f1_scores = [] acc_scores = [] pre_scores = [] sen_scores = [] spe_scores = [] fprs = [] tprs = [] np.random.seed(random_state) for i in range(n_iterations): sample_indices = np.random.choice(len(y_resampled), size = len(y_resampled), replace = True) y_true_sample = y_resampled[sample_indices] y_pred_sample = y_pred[sample_indices] y_probas_sample = y_probas[sample_indices] fpr, tpr, _ = roc_curve(y_true_sample, y_probas_sample[:, 1]) auc_score = auc_func(fpr, tpr) auc_scores.append(auc_score) fprs.append(fpr) tprs.append(tpr) f1_scores.append(f1_score(y_true_sample, y_pred_sample)) acc_scores.append(accuracy_score(y_true_sample, y_pred_sample)) pre_scores.append(precision_score(y_true_sample, y_pred_sample)) sen_scores.append(recall_score(y_true_sample, y_pred_sample)) tn, fp, fn, tp = confusion_matrix(y_true_sample, y_pred_sample).ravel() spe_scores.append(tn / (tn + fp)) def compute_median_and_ci(scores): median = np.median(scores) lower = np.percentile(scores, 2.5) upper = np.percentile(scores, 97.5) return median, lower, upper auc_median, auc_lower, auc_upper = compute_median_and_ci(auc_scores) f1_median, f1_lower, f1_upper = compute_median_and_ci(f1_scores) acc_median, acc_lower, acc_upper = compute_median_and_ci(acc_scores) pre_median, pre_lower, pre_upper = compute_median_and_ci(pre_scores) sen_median, sen_lower, sen_upper = compute_median_and_ci(sen_scores) spe_median, spe_lower, spe_upper = compute_median_and_ci(spe_scores) result = { 'AUC': (auc_median, auc_lower, auc_upper), 'F1': (f1_median, f1_lower, f1_upper), 'ACC': (acc_median, acc_lower, acc_upper), 'PRE': (pre_median, pre_lower, pre_upper), 'SEN': (sen_median, sen_lower, sen_upper), 'SPE': (spe_median, spe_lower, spe_upper) } print(f"AUC: Median = {auc_median}, 95% CI = [{auc_lower}, {auc_upper}]") print(f"F1: Median = {f1_median}, 95% CI = [{f1_lower}, {f1_upper}]") print(f"ACC: Median = {acc_median}, 95% CI = [{acc_lower}, {acc_upper}]") print(f"PRE: Median = {pre_median}, 95% CI = [{pre_lower}, {pre_upper}]") print(f"SEN: Median = {sen_median}, 95% CI = [{sen_lower}, {sen_upper}]") print(f"SPE: Median = {spe_median}, 95% CI = [{spe_lower}, {spe_upper}]") print() return result
def func_1(x): return(x.max()-x)
def func_2(x,x_best): M = (abs(x-x_best)).max() return(1-abs(x-x_best)/M)
def func_3(x,a,b): M = max(a-min(x), max(x)-b) y = [] for i in x: if i < a: y.append(1-(a-i)/M) elif i > b: y.append(1-(i-b)/M) else: y.append(1) return(y)
def entropyWeight(data): """ 熵权法确定权重
:param data: 行为评价对象,列为一个个的指标的 DataFrame """ data = np.array(data) P = data / data.sum(axis = 0)
E = np.nansum(-P * np.log(P) / np.log(len(data)), axis = 0)
return (1 - E) / (1 - E).sum()
def topsis(data, weight = None): Z = pd.DataFrame([data.max(), data.min()], index = ['正理想解', '负理想解']) weight = entropyWeight(data) if weight is None else np.array(weight) Result = data.copy() Result['正理想解'] = np.sqrt(((data - Z.loc['正理想解']) ** 2 * weight).sum(axis = 1)) Result['负理想解'] = np.sqrt(((data - Z.loc['负理想解']) ** 2 * weight).sum(axis = 1)) Result['综合得分指数'] = Result['负理想解'] / (Result['负理想解'] + Result['正理想解']) Result['百分比占比'] = (Result['综合得分指数'] / Result['综合得分指数'].sum()) Result['排序'] = Result.rank(ascending = False)['综合得分指数'] return Result, Z, weight
if __name__ == '__main__': import os wkdir = 'C:/Users/Administrator/Desktop' os.chdir(wkdir) path = 'Z:/TData/big-data/sad41d8cd/251026_TOPSIS_Weighted_Model_Fusion.xlsx' df = pd.read_excel(path) if False: df.head() df.columns
if True: X = df.drop(['Electrical_cardioversion'], axis = 1) y = df['Electrical_cardioversion'] X_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.3, random_state = 42, stratify = df['Electrical_cardioversion'] )
if True: smote = SMOTE(sampling_strategy = 1, k_neighbors = 20, random_state = 42) X_SMOTE_train, y_SMOTE_train = smote.fit_resample(X_train, y_train)
if True: dt_model = DecisionTreeClassifier(random_state = 42) param_grid = { 'criterion': ['gini', 'entropy'], 'max_depth': [None, 10, 20, 30, 40], 'min_samples_split': [2, 5, 10], 'min_samples_leaf': [1, 2, 4], 'max_features': [None, 'sqrt', 'log2'] } grid_search = GridSearchCV(estimator = dt_model, param_grid = param_grid, cv = 5, n_jobs = -1, verbose = 1) grid_search.fit(X_SMOTE_train, y_SMOTE_train) print(f"最优参数:{grid_search.best_params_}\n") best_dt_model = grid_search.best_estimator_
dt_train = evaluate_model_performance(best_dt_model, X_SMOTE_train, y_SMOTE_train) dt_test = evaluate_model_performance(best_dt_model, X_test.reset_index(drop = True), y_test.reset_index(drop = True)) if True: rf_model = RandomForestClassifier(random_state = 42) param_grid = { 'n_estimators': [50, 100, 200], 'criterion': ['gini', 'entropy'], 'max_depth': [None, 10, 20, 30, 40], 'min_samples_split': [2, 5, 10], 'min_samples_leaf': [1, 2, 4], 'max_features': [None, 'sqrt', 'log2'] } grid_search = GridSearchCV(estimator=rf_model, param_grid=param_grid, cv = 5, n_jobs = -1, verbose = 1) grid_search.fit(X_SMOTE_train, y_SMOTE_train) print(f"最优参数:{grid_search.best_params_}\n") best_rf_model = grid_search.best_estimator_ rf_train = evaluate_model_performance(best_rf_model, X_SMOTE_train, y_SMOTE_train) rf_test = evaluate_model_performance(best_rf_model, X_test.reset_index(drop = True), y_test.reset_index(drop = True)) if True: xgb_model = XGBClassifier(random_state = 42, use_label_encoder = False, eval_metric = 'mlogloss') param_grid = { 'n_estimators': [50, 100], 'learning_rate': [0.01, 0.2], 'max_depth': [3, 5], 'min_child_weight': [1, 5], 'subsample': [0.8, 1.0], 'colsample_bytree': [0.8, 1.0], 'gamma': [0, 0.2] } grid_search = GridSearchCV(estimator = xgb_model, param_grid=param_grid, cv = 5, n_jobs = -1, verbose = 1) grid_search.fit(X_SMOTE_train, y_SMOTE_train) print(f"最优参数:{grid_search.best_params_}\n") best_xgb_model = grid_search.best_estimator_ xgb_train = evaluate_model_performance(best_xgb_model, X_SMOTE_train, y_SMOTE_train) xgb_test = evaluate_model_performance(best_xgb_model, X_test.reset_index(drop = True), y_test.reset_index(drop = True)) if True: lgbm_model = LGBMClassifier(random_state = 42, verbose = -1) param_grid = { 'n_estimators': [50, 200], 'learning_rate': [0.01, 0.2], 'max_depth': [3, 7], 'num_leaves': [31, 100] } grid_search = GridSearchCV(estimator = lgbm_model, param_grid=param_grid, cv = 5, n_jobs = -1, verbose = 1) grid_search.fit(X_SMOTE_train, y_SMOTE_train) print(f"最优参数:{grid_search.best_params_}\n") best_lgbm_model = grid_search.best_estimator_ lgbm_train = evaluate_model_performance(best_lgbm_model, X_SMOTE_train, y_SMOTE_train) lgbm_test = evaluate_model_performance(best_lgbm_model, X_test.reset_index(drop = True), y_test.reset_index(drop = True)) if True:
svm_model = SVC(random_state = 42, probability = True) param_grid = { 'C': [0.1, 1, 10], 'kernel': ['poly', 'rbf'], 'gamma': ['scale', 0.1, 1] } grid_search = GridSearchCV(estimator = svm_model, param_grid = param_grid, cv = 5, n_jobs = -1, verbose = 1) grid_search.fit(X_SMOTE_train, y_SMOTE_train) print(f"最优参数:{grid_search.best_params_}\n") best_svm_model = grid_search.best_estimator_ svm_train = evaluate_model_performance(best_svm_model, X_SMOTE_train, y_SMOTE_train) svm_test = evaluate_model_performance(best_svm_model, X_test.reset_index(drop = True), y_test.reset_index(drop = True)) if True: bnb_model = BernoulliNB() param_grid = { 'alpha': [0.1, 1, 10], 'binarize': [0.0, 0.1, 0.5, 1.0] } grid_search = GridSearchCV(estimator=bnb_model, param_grid = param_grid, cv = 5, n_jobs = -1, verbose = 1) grid_search.fit(X_SMOTE_train, y_SMOTE_train) print(f"最优参数:{grid_search.best_params_}\n") best_bnb_model = grid_search.best_estimator_ bnb_train = evaluate_model_performance(best_bnb_model, X_SMOTE_train, y_SMOTE_train) bnb_test = evaluate_model_performance(best_bnb_model, X_test.reset_index(drop = True), y_test.reset_index(drop = True)) if True: gbdt_model = GradientBoostingClassifier(random_state = 42) param_grid = { 'n_estimators': [50, 100, 200], 'learning_rate': [0.01, 0.1, 0.2], 'max_depth': [3, 5, 7], 'subsample': [0.8, 1.0], 'min_samples_split': [2, 5, 10], 'min_samples_leaf': [1, 2, 4] } grid_search = GridSearchCV(estimator=gbdt_model, param_grid=param_grid, cv = 5, n_jobs = -1, verbose = 1) grid_search.fit(X_SMOTE_train, y_SMOTE_train) print(f"最优参数:{grid_search.best_params_}\n") best_gbdt_model = grid_search.best_estimator_ gbdt_train = evaluate_model_performance(best_gbdt_model, X_SMOTE_train, y_SMOTE_train) gbdt_test = evaluate_model_performance(best_gbdt_model, X_test.reset_index(drop = True), y_test.reset_index(drop = True))
if True:
models = { 'DecisionTree': best_dt_model, 'RandomForest': best_rf_model, 'XGBoost': best_xgb_model, 'LightGBM': best_lgbm_model, 'SVM': best_svm_model, 'BernoulliNB': best_bnb_model, 'GradientBoosting': best_gbdt_model } metrics = ['AUC', 'F1', 'ACC', 'PRE', 'SEN', 'SPE'] results = {metric: [] for metric in metrics} for model_name, model in models.items(): y_pred = model.predict(X_test) y_prob = model.predict_proba(X_test)[:, 1] auc = roc_auc_score(y_test, y_prob) f1 = f1_score(y_test, y_pred) acc = accuracy_score(y_test, y_pred) precision = precision_score(y_test, y_pred) recall = recall_score(y_test, y_pred) tn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel() sensitivity = recall specificity = tn / (tn + fp) results['AUC'].append(auc) results['F1'].append(f1) results['ACC'].append(acc) results['PRE'].append(precision) results['SEN'].append(sensitivity) results['SPE'].append(specificity) results_df = pd.DataFrame(results, index = models.keys()) weight = [1/6, 1/6, 1/6, 1/6, 1/6, 1/6] Result, Z, weight = topsis(results_df, weight) if True: class EnsembleModel(BaseEstimator, ClassifierMixin): def __init__(self, models, weights): """ 初始化集成模型。 :param models: 字典类型,包含每个基学习器模型 :param weights: 模型权重数组(通过TOPSIS的百分比占比得到) """ self.models = models self.weights = np.array(weights) def fit(self, X, y): """ 集成模型的fit方法,基学习器会进行训练。 """ for model in self.models.values(): model.fit(X, y) return self def predict_proba(self, X): """ 返回加权后的预测概率。对于二分类问题,返回两个类别的加权概率。 :param X: 测试数据集 :return: 返回两个类别的加权预测概率,格式为 (n_samples, 2) """ probas = np.zeros((X.shape[0], 2)) for i, model in enumerate(self.models.values()): model_proba = model.predict_proba(X) probas[:, 0] += model_proba[:, 0] * self.weights[i] probas[:, 1] += model_proba[:, 1] * self.weights[i] return probas def predict(self, X): """ 返回预测结果,基于加权后的预测概率判断类别。 :param X: 测试数据集 :return: 返回最终预测类别(0 或 1) """ weighted_proba = self.predict_proba(X) return (weighted_proba[:, 1] >= 0.5).astype(int) ensemble_model = EnsembleModel(models = models, weights = Result['百分比占比']) ensemble_model.fit(X_SMOTE_train, y_SMOTE_train) ensemble_train = evaluate_model_performance(ensemble_model, X_SMOTE_train, y_SMOTE_train) ensemble_test = evaluate_model_performance(ensemble_model, X_test.reset_index(drop = True), y_test.reset_index(drop = True)) probs = ensemble_model.predict_proba(X_test) predictions = ensemble_model.predict(X_test)
if True: fpr_dt, tpr_dt, _ = roc_curve(y_test, best_dt_model.predict_proba(X_test)[:, 1]) auc_dt = roc_auc_score(y_test, best_dt_model.predict_proba(X_test)[:, 1]) fpr_rf, tpr_rf, _ = roc_curve(y_test, best_rf_model.predict_proba(X_test)[:, 1]) auc_rf = roc_auc_score(y_test, best_rf_model.predict_proba(X_test)[:, 1]) fpr_xgb, tpr_xgb, _ = roc_curve(y_test, best_xgb_model.predict_proba(X_test)[:, 1]) auc_xgb = roc_auc_score(y_test, best_xgb_model.predict_proba(X_test)[:, 1]) fpr_lgbm, tpr_lgbm, _ = roc_curve(y_test, best_lgbm_model.predict_proba(X_test)[:, 1]) auc_lgbm = roc_auc_score(y_test, best_lgbm_model.predict_proba(X_test)[:, 1]) fpr_svm, tpr_svm, _ = roc_curve(y_test, best_svm_model.predict_proba(X_test)[:, 1]) auc_svm = roc_auc_score(y_test, best_svm_model.predict_proba(X_test)[:, 1]) fpr_bnb, tpr_bnb, _ = roc_curve(y_test, best_bnb_model.predict_proba(X_test)[:, 1]) auc_bnb = roc_auc_score(y_test, best_bnb_model.predict_proba(X_test)[:, 1]) fpr_gbdt, tpr_gbdt, _ = roc_curve(y_test, best_gbdt_model.predict_proba(X_test)[:, 1]) auc_gbdt = roc_auc_score(y_test, best_gbdt_model.predict_proba(X_test)[:, 1]) fpr_ensemble, tpr_ensemble, _ = roc_curve(y_test, ensemble_model.predict_proba(X_test)[:, 1]) auc_ensemble = roc_auc_score(y_test, ensemble_model.predict_proba(X_test)[:, 1]) plt.figure(figsize = (8, 7)) plt.plot(fpr_dt, tpr_dt, color = 'gray', linestyle = '--', alpha = 0.6, label = f'DT (AUC = {auc_dt:.4f})') plt.plot(fpr_rf, tpr_rf, color = 'gray', linestyle = '--', alpha = 0.6, label = f'RF (AUC = {auc_rf:.4f})') plt.plot(fpr_xgb, tpr_xgb, color = 'gray', linestyle = '--', alpha = 0.6, label = f'XGB (AUC = {auc_xgb:.4f})') plt.plot(fpr_lgbm, tpr_lgbm, color = 'gray', linestyle = '--', alpha = 0.6, label = f'LGBM (AUC = {auc_lgbm:.4f})') plt.plot(fpr_svm, tpr_svm, color = 'gray', linestyle = '--', alpha = 0.6, label = f'SVM (AUC = {auc_svm:.4f})') plt.plot(fpr_bnb, tpr_bnb, color = 'gray', linestyle = '--', alpha = 0.6, label = f'NB (AUC = {auc_bnb:.4f})') plt.plot(fpr_gbdt, tpr_gbdt, color = 'gray', linestyle = '--', alpha = 0.6, label = f'GBDT (AUC = {auc_gbdt:.4f})') plt.plot(fpr_ensemble, tpr_ensemble, color = 'orange', label = f'Ensemble (AUC = {auc_ensemble:.4f})') plt.plot([0, 1], [0, 1], 'r--', linewidth = 1.5, alpha = 0.8) plt.xlabel("False Positive Rate (1-Specificity)", fontsize = 18) plt.ylabel("True Positive Rate (Sensitivity)", fontsize = 18) plt.xticks(fontsize = 16) plt.yticks(fontsize = 16) plt.legend(loc = "lower right", fontsize = 12, frameon = False) plt.gca().spines['top'].set_visible(False) plt.gca().spines['right'].set_visible(False) plt.gca().spines['left'].set_linewidth(1.5) plt.gca().spines['bottom'].set_linewidth(1.5) plt.grid(False) plt.tight_layout() plt.savefig("ROC-Ensemble.pdf", format = 'pdf', bbox_inches = 'tight', dpi = 1200) plt.show() if True: joblib.dump(best_dt_model, 'DecisionTree.pkl') joblib.dump(best_rf_model, 'RandomForest.pkl') joblib.dump(best_xgb_model, 'XGBoost.pkl') joblib.dump(best_lgbm_model, 'LightGBM.pkl') joblib.dump(best_svm_model, 'SVM.pkl') joblib.dump(best_bnb_model, 'BernoulliNB.pkl') joblib.dump(best_gbdt_model, 'GradientBoosting.pkl') joblib.dump(ensemble_model, 'ensemble_model.pkl')
|