ConfusionMatrixDisplay,在图中添加title,修改label等的方法

记录一下关于python使用sklearn中的混淆矩阵库ConfusionMatrixDisplay,在图中添加title,修改label等的方法

本科没有写什么,研究生期间第一篇记录

由于ConfusionMatrixDisplay库会隐式调用plt.subplots(),导致用户不能获取到figure或者ax不能使用内部函数进行修改,通过观察源码,我们发现ConfusionMatrixDisplay类中有一个plot函数(这也是我们绘制混淆矩阵所需要调用的),函数的参数表有ax变量。
ConfusionMatrixDisplay类内函数plot的参数表
相信有些朋友已经知道如何解决了。
是的通过传入外部的ax,使用外部的ax添加其他内容即可,代码如下:

confusion_matrix_figure=ConfusionMatrixDisplay(confusion_matrix=cm,display_labels=[0,1])
ax=plt.figure().subplots()
accuracy = (cm[0, 0] + cm[1, 1]) * 1.0 / np.sum(cm)
ax.set(title="Accuracy = %0.2f" % accuracy)
confusion_matrix_figure.plot(ax=ax)
plt.show()
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import classification_report, confusion_matrix, ConfusionMatrixDisplay from sklearn.pipeline import make_pipeline # 选择5个分类器 selected_classifiers = { "Random Forest": RandomForestClassifier(n_estimators=100, random_state=42), "Logistic Regression": LogisticRegression(max_iter=1000, random_state=42), "XGBoost": XGBClassifier(use_label_encoder=False, eval_metric='logloss'), "SVM": SVC(kernel='rbf', probability=True, random_state=42), "Neural Network": MLPClassifier(hidden_layer_sizes=(50,), max_iter=1000, random_state=42) } # 数据准备 df = pd.read_csv('credictcard-reduced.csv') X = df.drop(['Time', 'Class'], axis=1) # 移除时间和标签列 y = df['Class'] # 划分数据集 X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, stratify=y, random_state=42 ) # 标准化处理 scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) # 创建可视化画布 fig, axes = plt.subplots(2, 5, figsize=(25, 10)) plt.subplots_adjust(wspace=0.4, hspace=0.4) # 训练和评估模型 for idx, (name, clf) in enumerate(selected_classifiers.items()): # 训练模型 clf.fit(X_train, y_train) y_pred = clf.predict(X_test) # 计算评估指标 report = classification_report(y_test, y_pred, output_dict=True) metrics_df = pd.DataFrame(report).transpose() # 绘制混淆矩阵 cm = confusion_matrix(y_test, y_pred) disp = ConfusionMatrixDisplay(confusion_matrix=cm) disp.plot(ax=axes[0, idx], cmap='Blues') axes[0, idx].set_title(f'{name}\nConfusion Matrix') # 显示指标表格 cell_text = [[f"{metrics_df.loc['1']['precision']:.2f}", f"{metrics_df.loc['1']['recall']:.2f}", f"{metrics_df.loc['1']['f1-score']:.2f}"]] table = axes[1, idx].table(cellText=cell_text, colLabels=['Precision', 'Recall', 'F1'], loc='center', cellLoc='center') table.set_fontsize(14) table.scale(1, 2) axes[1, idx].axis('off') axes[1, idx].set_title('Class 1 Metrics') plt.show() # 输出详细评估报告 print("\n\033[1m综合性能报告:\033[0m") for name, clf in selected_classifiers.items(): y_pred = clf.predict(X_test) print(f"\n\033[1m{name}\033[0m") print(classification_report(y_test, y_pred, target_names=['0', '1'])) 将这一段的代码里面的XGBoost 改成decision tree ,jiang svm改成 adaboots,并且增加之前没有的from sklearn ... 的没有预先导入的内容
最新发布
03-13
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

广阔天地,大有可为

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值