当前位置:首页>python>Python绘制多模型对比校准曲线

Python绘制多模型对比校准曲线

  • 2026-10-11 06:14:46
Python绘制多模型对比校准曲线

代码绘制成果展示

四种机器学习模型在训练集上的校准曲线,用于评估模型预测概率的准确性。图中的虚线对角线代表“完美校准”,即模型的预测概率与实际的正类完全一致。从图中可以看出,梯度提升模型的性能最好,其曲线在整个概率范围内都非常贴近完美校准线。相比之下,随机森林性能较差。
多种配色

代码解释

第一部分

库的导入以及字体设置
# =========================================================================================# ====================================== 1. 库的导入 =========================================# =========================================================================================import pandas as pdimport matplotlib.pyplot as pltfrom sklearn.model_selection import train_test_split, GridSearchCVfrom sklearn.preprocessing import StandardScalerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.svm import SVCfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifierfrom sklearn.calibration import calibration_curveplt.rcParams['font.family'] = 'serif'plt.rcParams['font.serif'] = ['Times New Roman']plt.rcParams['axes.unicode_minus'] = Falseimport matplotlibmatplotlib.rcParams['pdf.fonttype'] = 42matplotlib.rcParams['ps.fonttype'] = 42

第二部分

颜色库的设置以及配色方案的选择
# =========================================================================================# ======================================2.设置颜色库 =========================================# =========================================================================================color_schemes = {    1: {    },}selected_scheme = 20# 选择颜色方案SELECTED_COLORS = color_schemes[selected_scheme]  # 获取颜色方案

第三部分

校准曲线的绘制函数
这里需要对函数的最后面的保存地址进行修改
# =========================================================================================# ======================================3.绘图函数 =========================================# =========================================================================================def plot_calibration_curves(y_true, all_scores, plot_title, colors_dict, n_bins=10, filename=None):    fig, ax = plt.subplots(figsize=(8, 7))  # 画布    ax.set_facecolor(colors_dict['bg_color'])  # 设置的背景颜色    # 网格线    ax.grid(True,            which='both',            linestyle='--',            linewidth=2,            color='lightgrey',            dashes=(3, 5))    # 绘制对角虚线/参考线    ax.plot([0, 1], [0, 1], color=colors_dict['diag_line'], lw=2, linestyle='--')    ax.set_xlim([-0.02, 1.02])  # 设置X轴的范围    ax.set_ylim([-0.02, 1.02])  # 设置Y轴的范围    ax.set_xlabel('Mean Predicted Probability', fontsize=18, color=colors_dict['xy_label'])  # x轴标题    ax.set_ylabel('Fraction of Positives', fontsize=18, color=colors_dict['xy_label'])  # Y轴标题    ax.set_title(plot_title, fontsize=20, loc='left', pad=10)  # 设置主图标题    ax.xaxis.set_major_locator(plt.MultipleLocator(0.25))  # 设置X轴主刻度的间隔    ax.yaxis.set_major_locator(plt.MultipleLocator(0.25))  # 设置Y轴主刻度的间隔    ax.tick_params(axis='both', which='major', labelsize=14)  # 主刻度标签的字体大小    # 添加图例    ax.legend(loc='upper left', fontsize=14, frameon=True, edgecolor='black')    # 遍历图框    for spine in ax.spines.values():        spine.set_edgecolor('#6B8E23')  # 颜色        spine.set_linewidth(2)  # 图框的粗细设置    plt.tight_layout()  # 自动调整子图参数,使其填充整个图窗区域,防止标签重叠

第四部分

原始数据的加载与处理
主要的修改部分就在这里,包括原始数据的输入路径,特征数据和目标数据/标签的提取,训练数据和验证数据集的分离,特征数据的标准化处理,消除不同数据之间量纲的影响
# =========================================================================================# ======================================4.数据的加载与处理=========================================# =========================================================================================excel_filename = r'simulated_senescence_data.xlsx'  # 原始数据路径df = pd.read_excel(excel_filename, engine='openpyxl')  # 读取数据# 提取所有特征和标签y = df.iloc[:, 0].valuesX = df.iloc[:, 1:].values# 划分数据集为训练集和验证集X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.3, random_state=42, stratify=y)# 标准化处理scaler = StandardScaler()X_train_scaled = scaler.fit_transform(X_train)X_val_scaled = scaler.transform(X_val)

第五部分

模型的构建
本段代码的核心部分,训练了四种不同的二分类模型,包括逻辑回归模型、SVM模型、随机森林模型、梯度提升模型,通过交叉验证和网格搜索在训练集上寻找了模型的最佳超参数,以此来获取最佳模型。
# =========================================================================================# ======================================5.模型构建=========================================# =========================================================================================print(f"正在为 'Logistic Regression' 进行网格搜索")# ... (逻辑回归模型的网格搜索和训练) ...grid_search_lr.fit(X_train_scaled, y_train)best_model_lr = grid_search_lr.best_estimator_  # 最佳模型print(f"'Logistic Regression' 网格搜索完成!最佳超参数: {grid_search_lr.best_params_}")# 最佳逻辑回归模型预测正类的概率scores_lr_train = best_model_lr.predict_proba(X_train_scaled)[:, 1]scores_lr_val = best_model_lr.predict_proba(X_val_scaled)[:, 1]print(f"\n--- 正在为 'SVM (RBF Kernel)' 进行网格搜索")# ... (SVM 模型的网格搜索和训练) ...model_svm = SVC(random_state=42, probability=True) # 注意 probability=True# ...grid_search_svm.fit(X_train_scaled, y_train)best_model_svm = grid_search_svm.best_estimator_# ...scores_svm_train = best_model_svm.predict_proba(X_train_scaled)[:, 1]scores_svm_val = best_model_svm.predict_proba(X_val_scaled)[:, 1]print(f"\n--- 正在为 'Random Forest' 进行网格搜索")# ... (随机森林模型的网格搜索和训练) ...grid_search_rf.fit(X_train_scaled, y_train)best_model_rf = grid_search_rf.best_estimator_# ...scores_rf_train = best_model_rf.predict_proba(X_train_scaled)[:, 1]scores_rf_val = best_model_rf.predict_proba(X_val_scaled)[:, 1]print(f"\n--- 正在为 'Gradient Boosting' 进行网格搜索 ---")# ... (梯度提升模型的网格搜索和训练) ...grid_search_gbt.fit(X_train_scaled, y_train)best_model_gbt = grid_search_gbt.best_estimator_# ...scores_gbt_train = best_model_gbt.predict_proba(X_train_scaled)[:, 1]scores_gbt_val = best_model_gbt.predict_proba(X_val_scaled)[:, 1]

第六部分

结果绘图
利用上一步处理得到的最佳模型来进行绘图,为训练集和验证集都进行绘图
# =========================================================================================# ======================================6.绘图=========================================# =========================================================================================# 存储训练集上所有模型的预测分数train_scores_dict = {    "Logistic Regression": scores_lr_train,    "SVM (RBF Kernel)": scores_svm_train,    "Random Forest": scores_rf_train,    "Gradient Boosting": scores_gbt_train}# 存储验证集上所有模型的预测分数val_scores_dict = {    "Logistic Regression": scores_lr_val,    "SVM (RBF Kernel)": scores_svm_val,    "Random Forest": scores_rf_val,    "Gradient Boosting": scores_gbt_val}# 绘制训练集的校准曲线plot_calibration_curves(y_train,                        train_scores_dict,                        "(C) Calibration Curves on Training Set (Model Comparison)",                        SELECTED_COLORS,                        filename='train_calibration'                        )# 绘制验证集的校准曲线plot_calibration_curves(y_val,                        val_scores_dict,                        "(C) Calibration Curves on Validation Set (Model Comparison)",                        SELECTED_COLORS,                        filename='test_calibration'                        )

如何应用?

1.选择你想要使用到的配色方案:

selected_scheme = 20# 选择颜色方案

2.设置绘图结果的保存路径,保存为png和pdf格式,pdf格式的文件可以进行编辑修改:

fig.savefig(fr'{filename}_{selected_scheme}.pdf', bbox_inches='tight')

3.设置原始数据的输入路径:

excel_filename = r'simulated_senescence_data.xlsx'  

4.定义特征数据和标签:

y = df.iloc[:, 0].valuesX = df.iloc[:, 1:].values

5.设置模型的超参数网格:

param_grid_lr = {    'C': [0.01, 0.1, 1, 10, 100],    'penalty': ['l1', 'l2']}

推荐

期刊图片复现|Python绘制二维偏依赖PDP图
期刊复现|python绘制基于SHAP分析和GAM模型拟合的单特征依赖图
期刊图片复现|python绘制带有渐变颜色shap特征重要性组合图(条形图+蜂巢图)
期刊复现|用Python绘制SHAP特征重要性总览图、依赖图、双特征交互效应SHAP图,解锁XGBoost模型的终极奥秘
期刊图片复现|Python绘制shap重要性蜂巢图+单特征依赖图+交互效应强度气泡图+交互效应依赖图(回归+二分类+分类)

推荐

获取方式

需要的请后台私信我获取详细信息,注意只会分享练习数据和代码文件,不会提供答疑服务,代码文件中已经包含了每行代码的完整注释!!!

最新文章

随机文章