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
|
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import warnings warnings.filterwarnings("ignore", message = ".*does not have valid feature names.*") from sklearn.ensemble import VotingClassifier, RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier from xgboost import XGBClassifier from lightgbm import LGBMClassifier from catboost import CatBoostClassifier from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import roc_curve, roc_auc_score plt.rcParams['font.family'] = 'Times New Roman' plt.rcParams['axes.unicode_minus'] = False
if __name__ == '__main__': import os wkdir = 'C:/Users/Administrator/Desktop' os.chdir(wkdir) path = 'Z:/TData/big-data/sad41d8cd/251030_voting_classifier_ensemble_learning.xlsx' df = pd.read_excel(path) if True: df.head() df.columns df.info() X = df.drop(['class'], axis = 1) y = df['class'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42, stratify = df['class']) if True: rf_clf = RandomForestClassifier(random_state = 42) xgb_clf = XGBClassifier(use_label_encoder = False, eval_metric = 'logloss', random_state = 42) lgbm_clf = LGBMClassifier(random_state = 42, verbose = -1) gbm_clf = GradientBoostingClassifier(random_state = 42) adaboost_clf = AdaBoostClassifier(random_state = 42, algorithm = 'SAMME') catboost_clf = CatBoostClassifier(verbose = 0, random_state = 42) if True: voting_hard = VotingClassifier( estimators = [ ('RandomForest', rf_clf), ('XGBoost', xgb_clf), ('LightGBM', lgbm_clf), ('GradientBoosting', gbm_clf), ('AdaBoost', adaboost_clf), ('CatBoost', catboost_clf) ], voting = 'hard' ) voting_hard.fit(X_train, y_train) if True: voting_soft = VotingClassifier( estimators = [ ('RandomForest', rf_clf), ('XGBoost', xgb_clf), ('LightGBM', lgbm_clf), ('GradientBoosting', gbm_clf), ('AdaBoost', adaboost_clf), ('CatBoost', catboost_clf) ], voting = 'soft', weights = [1, 1, 1, 1, 1, 1] ) voting_soft.fit(X_train, y_train) if True:
y_pred_hard = voting_hard.predict(X_test) print("Classification Report for Hard Voting:") print(classification_report(y_test, y_pred_hard)) y_pred_soft = voting_soft.predict(X_test) print("Classification Report for Soft Voting:") print(classification_report(y_test, y_pred_soft)) if True: conf_matrix_hard = confusion_matrix(y_test, y_pred_hard) conf_matrix_soft = confusion_matrix(y_test, y_pred_soft) fig, axes = plt.subplots(1, 2, figsize = (16, 6), dpi=1200) sns.heatmap(conf_matrix_hard, annot = True, annot_kws = {'size': 15}, fmt = 'd', cmap = 'YlGnBu', cbar_kws = {'shrink': 0.75}, ax = axes[0]) axes[0].set_title('Confusion Matrix (Hard Voting)', fontsize = 15) axes[0].set_xlabel('Predicted Label', fontsize = 15) axes[0].set_ylabel('True Label', fontsize = 15) sns.heatmap(conf_matrix_soft, annot = True, annot_kws = {'size': 15}, fmt = 'd', cmap = 'YlGnBu', cbar_kws = {'shrink': 0.75}, ax = axes[1]) axes[1].set_title('Confusion Matrix (Soft Voting)', fontsize = 15) axes[1].set_xlabel('Predicted Label', fontsize = 15) axes[1].set_ylabel('True Label', fontsize = 15) plt.tight_layout() plt.savefig("混淆矩阵_硬投票_软投票.png", bbox_inches = 'tight') plt.close() if True: models = { 'RandomForest': rf_clf, 'XGBoost': xgb_clf, 'LightGBM': lgbm_clf, 'GradientBoosting': gbm_clf, 'AdaBoost': adaboost_clf, 'CatBoost': catboost_clf } plt.figure(figsize = (10, 8)) for name, model in models.items(): y_proba = model.fit(X_train, y_train).predict_proba(X_test)[:, 1] fpr, tpr, _ = roc_curve(y_test, y_proba) auc_score = roc_auc_score(y_test, y_proba) plt.plot(fpr, tpr, label=f"{name} (AUC = {auc_score:.2f})") voting_hard.fit(X_train, y_train) y_pred_hard = voting_hard.predict(X_test) y_proba_hard = voting_hard.transform(X_test)[:, 1] fpr_hard, tpr_hard, _ = roc_curve(y_test, y_proba_hard) auc_score_hard = roc_auc_score(y_test, y_proba_hard) plt.plot(fpr_hard, tpr_hard, label = f"Voting (AUC = {auc_score_hard:.2f})", linestyle = '--') plt.plot([0, 1], [0, 1], 'k--', label = "Random Guessing") plt.xlabel('False Positive Rate (FPR)', fontsize = 18) plt.ylabel('True Positive Rate (TPR)', fontsize = 18) plt.title('ROC Curve of Base Models and Voting Classifier', fontsize = 18) plt.legend(loc = 'lower right') plt.grid() plt.savefig("ROC Curve of Base Models and Voting Classifier.png", bbox_inches = 'tight', dpi = 1200) plt.close() if True: y_proba_soft = voting_soft.predict_proba(X_test)[:, 1] fpr_soft, tpr_soft, _ = roc_curve(y_test, y_proba_soft) auc_score_soft = roc_auc_score(y_test, y_proba_soft) plt.figure(figsize = (8, 6)) plt.plot(fpr_soft, tpr_soft, label = f"Soft Voting (AUC = {auc_score_soft:.2f})") plt.plot([0, 1], [0, 1], 'k--', label = "Random Guessing") plt.xlabel('False Positive Rate (FPR)', fontsize = 18) plt.ylabel('True Positive Rate (TPR)', fontsize = 18) plt.title('ROC Curve of Soft Voting Classifier', fontsize = 18) plt.legend(loc='lower right') plt.grid() plt.savefig("ROC Curve of Soft Voting Classifier.png", bbox_inches = 'tight', dpi = 1200) plt.show()
|