
代码绘制成果展示












代码解释


第一部分

# =========================================================================================# ====================================== 1. 环境设置 =======================================# =========================================================================================import matplotlib.pyplot as pltimport matplotlib.gridspec as gridspecimport seaborn as snsimport numpy as npimport pandas as pd

第二部分

# =========================================================================================# ======================================2.颜色库=======================================# =========================================================================================COLOR_SCHEMES = {1: ['#4a90e2', '#f35b5b', '#42b983'],}

第三部分

# =========================================================================================# ======================================3.绘图函数=======================================# =========================================================================================def plot_advanced_forest_chart(results_dict, scheme_id):colors = COLOR_SCHEMES[scheme_id] # 获取配色方案# 创建画布fig = plt.figure(figsize=(14, 12))gs = gridspec.GridSpec(3, # 3行3, # 列height_ratios=[1.2, 1.5, 1.5], # 高度比例hspace=0.25, # 垂直间距

第四部分

ax_bar = fig.add_subplot(gs[0, :]) # 柱状图子图rects2 = ax_bar.bar(x, # xtest_r2, # ywidth, # 宽label='Test $R^2$', # 图例标签color=colors[1], # 配色edgecolor='black', # 边框色alpha=0.9) # 透明度rects3 = ax_bar.bar(x + width, # xcv_r2, # ywidth, # 宽label='CV Val $R^2$', # 图例标签color=colors[2], # 配色edgecolor='black', # 边框色alpha=0.9) # 透明度

第五部分

# 柱状图的Y轴标题ax_bar.set_ylabel('$R^2$ Score', # 文本fontsize=16, # 字号weight='bold') # 加粗ax_bar.set_xticks(x) # X轴刻度位置# 网格线ax_bar.grid(axis='y', # 轴linestyle='-', # 实线alpha=0.3) # 透明度

第六部分

positions = [gs[1, 0], gs[1, 1], gs[1, 2], gs[2, 0], gs[2, 1], gs[2, 2]] # 回归拟合图位置titles = ['Linear Regression', 'RF', 'XGB', 'LGB', 'CAT', 'TabPFN'] # 子图标题# 遍历绘制拟合图for i, name in enumerate(model_names):min_lim = min(res['y_test'].min(), res['test_pred'].min()) - 0.1 # 下限max_lim = max(res['y_test'].max(), res['test_pred'].max()) + 0.1 # 上限# 绘制1:1参考线ax.plot([min_lim, max_lim], # x[min_lim, max_lim], # ylinestyle=':', # 样式color='black', # 颜色linewidth=1.5, # 粗细zorder=1) # 层

第七部分

# 子图标题ax.set_title(titles[i], # 文本color=colors[1], # 配色fontsize=16, # 字号weight='bold') # 加粗ax.set_xlim(min_lim, max_lim) # X轴范围ax.set_ylim(min_lim, max_lim) # Y轴范围# 图例ax.legend(loc='lower right', # 位置frameon=False, # 边框fontsize=13, # 字号markerscale=1.5) # 标记大小

第八部分

# =========================================================================================# ======================================4.执行部分=======================================# =========================================================================================if __name__ == '__main__':excel_path = r'data.xlsx'df = pd.read_excel(excel_path) # 读取X = df.drop(columns=['LGUE']) # x# 超参数param_grids = {'LR': {},'RF': {'n_estimators': [50, 100, 200],'max_depth': [5, 10]},'XGB': {'n_estimators': [50, 100, 200],'max_depth': [3, 5, 7],'learning_rate': [0.05, 0.1]},'LGB': {'n_estimators': [50, 100, 200],'max_depth': [3, 5, 7],'learning_rate': [0.05, 0.1]},'CAT': {'iterations': [50, 100, 200],'depth': [4, 6],'learning_rate': [0.05, 0.1]},'TabPFN': {}}

第九部分

results_dict = {} # 存储模型结果# 遍历定义好的模型for name, model in models_dict.items():# 保存分析结果results_dict[name] = {'r2_tr': r2_tr, 'r2_te': r2_te, 'cv_r2': cv_r2,'rmse_te': rmse_te, 'mae_te': mae_te,'y_train': y_train, 'train_pred': train_pred,'y_test': y_test, 'test_pred': test_pred}print(f"模型{name}| Best Params: {grid_search.best_params_} | CV Val R2: {cv_r2:.3f} | Test R2: {r2_te:.3f}")

第十部分

scheme_id = 1selected_hex_colors = COLOR_SCHEMES[scheme_id]print('正在绘制并保存方案:', scheme_id)plot_advanced_forest_chart(results_dict, scheme_id)

如何应用到你自己的数据

1.设置原始数据的保存路径,执行部分:
df = pd.read_excel(r'data.xlsx') # 读取2.读取特征数据及目标数据,执行部分:
X = df.drop(columns=['LGUE']) # xy = df['LGUE'] # y
3.划分数据集,执行部分:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 划分数据集4.定义要使用的模型及超参数,执行部分:
models_dict = {'LR': LinearRegression(),'RF': RandomForestRegressor(random_state=42),'XGB': xgb.XGBRegressor(random_state=42),'LGB': lgb.LGBMRegressor(random_state=42, verbose=-1),'CAT': cb.CatBoostRegressor(random_state=42, verbose=0),'TabPFN': tabpfn_model}# 超参数param_grids = {'LR': {},'RF': {'n_estimators': [50, 100, 200],'max_depth': [5, 10]},'XGB': {'n_estimators': [50, 100, 200],'max_depth': [3, 5, 7],'learning_rate': [0.05, 0.1]},'LGB': {'n_estimators': [50, 100, 200],'max_depth': [3, 5, 7],'learning_rate': [0.05, 0.1]},'CAT': {'iterations': [50, 100, 200],'depth': [4, 6],'learning_rate': [0.05, 0.1]},'TabPFN': {}}
5.实例化网格搜索对象,执行部分:
grid_search = GridSearchCV(estimator=pipe, param_grid=pipe_param_grid, cv=5, scoring='r2', n_jobs=current_n_jobs) 6.设置是否要进行批量绘图,执行部分:
plot_all = True7.设置绘图结果的保存地址,绘图函数部分:
plt.savefig(fr'scheme_{scheme_id}.png', dpi=300, bbox_inches='tight')
推荐


获取方式
