使用 plot_confusion_matrix 绘制多个混淆矩阵 [英] Plot multiple confusion matrices with plot_confusion_matrix

查看:42
本文介绍了使用 plot_confusion_matrix 绘制多个混淆矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 sklearn.metrics 中的 plot_confusion_matrix.我想像子图一样表示这些混淆矩阵,我该怎么做?

解决方案

让我们使用 good'ol iris 数据集重现这一点,并拟合多个分类器以使用

I am using plot_confusion_matrix from sklearn.metrics. I want to represent those confusion matrices next to each other like subplots, how could I do this?

解决方案

Let's use the good'ol iris dataset to reproduce this, and fit several classifiers to plot their respective confusion matrices with plot_confusion_matrix:

from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from matplotlib import pyplot as plt
from sklearn.datasets import load_iris
from sklearn.metrics import plot_confusion_matrix

data = load_iris()
X = data.data
y = data.target

Set up -

X_train, X_test, y_train, y_test = train_test_split(X, y)
classifiers = [LogisticRegression(solver='lbfgs'), 
               AdaBoostClassifier(),
               GradientBoostingClassifier(), 
               SVC()]
for cls in classifiers:
    cls.fit(X_train, y_train)

So the way you could compare all matrices at simple sight, is by creating a set of subplots with plt.subplots. Then iterate both over the axes objects and the trained classifiers (plot_confusion_matrix expects the as input) and plot the individual confusion matrices:

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(15,10))

for cls, ax in zip(classifiers, axes.flatten()):
    plot_confusion_matrix(cls, 
                          X_test, 
                          y_test, 
                          ax=ax, 
                          cmap='Blues',
                         display_labels=data.target_names)
    ax.title.set_text(type(cls).__name__)
plt.tight_layout()  
plt.show()


这篇关于使用 plot_confusion_matrix 绘制多个混淆矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆