
代码绘制成果展示












代码解释


第一部分

# =========================================================================================# ====================================== 1. 环境设置 =======================================# =========================================================================================import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom matplotlib.colors import LinearSegmentedColormapfrom sklearn.model_selection import train_test_split, GridSearchCV

第二部分

# =========================================================================================# ======================================2.颜色库=======================================# =========================================================================================COLOR_SCHEMES = {1: ["#39738A", "#D0DFE3", "#EB7125"],}

第三部分

# =========================================================================================# ======================================3.绘图函数=======================================# =========================================================================================def plot_confusion_matrices(matrix_data, scheme_id):current_colors = COLOR_SCHEMES.get(scheme_id, COLOR_SCHEMES[1]) #提取配色方案current_cmap = LinearSegmentedColormap.from_list("custom_cmap", current_colors) #创建线性渐变颜色映射#创建画布fig, axes = plt.subplots(3, 3, figsize=(14, 13))titles = ['Random Forest', 'XGBoost', 'CatBoost'] #模型标题letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] #子图编号

第四部分

#遍历每一个子图for i, ax in enumerate(axes.flat):ax.invert_yaxis() #翻转Y轴刻度#遍历边框线for _, spine in ax.spines.items():spine.set_visible(True) #可见spine.set_color('black') #颜色spine.set_linewidth(1.5) #粗细#设置刻度ax.tick_params(axis='both', #x、ywhich='major', #主刻度线width=2, #宽length=5, #长color='black') #颜色

第五部分

#遍历行for y in range(5):rgb = current_cmap(val / 100.0) #将百分比归一化到0-1,获取对应背景色的RGB值luminance = 0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2] #计算背景色的明暗程度text_color = 'white' if luminance < 0.5 else 'black' #若背景暗则采用白色,反之采用黑色#格子内文本ax.text(x + 0.5, #xy + 0.5, #yf"{int(np.round(val))}%", #文本ha='center', #水平va='center', #垂直color=text_color, #颜色fontsize=12, #字体大小fontweight='bold') #加粗

第六部分

ax.set_xticks(np.arange(5) + 0.5) #x轴的主刻度位置ax.set_xticklabels([0, 1, 2, 3, 4], fontsize=12) #x轴刻度标注ax.set_yticks(np.arange(5) + 0.5) #y轴刻度位置ax.set_yticklabels([0, 1, 2, 3, 4], fontsize=12) #y轴刻度标注ax.set_xlabel('True_Class', fontsize=16, labelpad=8) #x轴标题ax.set_ylabel('Predicted class', fontsize=16, labelpad=8) #y轴标题#子图编号ax.text(-0.15, #x1.02, #yletters[i], #字母transform=ax.transAxes, #坐标系fontsize=16, #字体大小fontweight='bold', #加粗va='bottom', #垂直ha='right') #水平

第七部分

#颜色条坐标轴cbar_ax = fig.add_axes([0.94, #左0.35, #下0.02, #宽0.3]) #高#构建一个数据到颜色的可映射对象sm = plt.cm.ScalarMappable(cmap=current_cmap,norm=plt.Normalize(vmin=0, vmax=100))cbar.outline.set_color('black') #外框线色cbar.outline.set_linewidth(1.5) #线宽cbar.ax.tick_params(length=0) #去掉颜色条刻度线

第八部分

# =========================================================================================# ======================================4.执行部分=======================================# =========================================================================================if __name__ == '__main__':excel_filename = r'microplastic_data.xlsx' #原始数据路径df_main = pd.read_excel(excel_filename) #读取X_main = df_main.drop(columns=['Target_Class']).values #特征y_main = df_main['Target_Class'].values #目标# 划分数据X_train, X_test, y_train, y_test = train_test_split(X_main, y_main, test_size=0.2, random_state=42)ind_excel_filename = r'independent_validation_data.xlsx' #独立验证数据df_ind = pd.read_excel(ind_excel_filename) #读取X_ind = df_ind.drop(columns=['Target_Class']).values #特征y_ind = df_ind['Target_Class'].values #目标

第九部分

# 保存筛选出来的带有最佳参数的三个模型best_models = {}# 模型名称model_names = ['Random Forest', 'XGBoost', 'CatBoost']# RF超参数网格rf_param = {'n_estimators': [50, 100],'max_depth': [5, 10, None]}# 配置网格搜索cb_grid = GridSearchCV(CatBoostClassifier(random_state=42, verbose=0), cb_param, cv=3, n_jobs=-1)cb_grid.fit(X_train, y_train)#拟合best_models['CatBoost'] = cb_grid.best_estimator_ #最佳CatBoost模型

第十部分

# 需要评估的数据集字典,训练集、测试集和独立验证集evaluation_datasets = [(X_train, y_train),(X_test, y_test),(X_ind, y_ind)]matrix_data = [] #存放混淆矩阵数据#遍历三种不同的评估数据集for X_eval, y_eval in evaluation_datasets:#遍历模型for name in model_names:#保存matrix_data.append(cm_percentage)

如何应用到你自己的数据

1.设置是一次绘制一张图还是一次性绘制出所有配色的图,执行部分:
plot_all = True2.设置训练集和测试集的全量数据集的保存路径,执行部分:
excel_filename = r'microplastic_data.xlsx' #原始数据路径3.设置独立验证数据集的保存路径,执行部分:
ind_excel_filename = r'independent_validation_data.xlsx' #独立验证数据4.提取特征数据,执行部分:
X_main = df_main.drop(columns=['Target_Class']).values #特征5.提取目标数据,执行部分:
y_main = df_main['Target_Class'].values #目标6.定义模型名称,执行部分:
model_names = ['Random Forest', 'XGBoost', 'CatBoost']7.设置模型超参数网格,执行部分:
rf_param = {'n_estimators': [50, 100],'max_depth': [5, 10, None]}
8.设置子图编号,执行部分:
etters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] #子图编号9.设置绘图结果的保存地址,执行部分:
plt.savefig(fr'confusion_matrices{scheme_id}.png', dpi=300, bbox_inches='tight')
推荐


获取方式
