
代码绘制成果展示




代码解释


第一部分

# =========================================================================================# ====================================== 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)

第五部分

# =========================================================================================# ======================================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']}
推荐


推荐



获取方式
