绘制混淆矩阵,不使用估计器。

8

我试图使用 plot_confusion_matrix 函数,

from sklearn.metrics import confusion_matrix

y_true = [1, 1, 0, 1]
y_pred = [1, 1, 0, 0]

confusion_matrix(y_true, y_pred)

输出:

array([[1, 0],
       [1, 2]])

现在,使用以下内容时,可以使用“类”或不使用“类”

from sklearn.metrics import plot_confusion_matrix

plot_confusion_matrix(y_true, y_pred, classes=[0,1], title='Confusion matrix, without normalization')

或者

plot_confusion_matrix(y_true, y_pred, title='Confusion matrix, without normalization')

我希望我能得到类似于这个图像的输出结果,除了里面的数字以外。

enter image description here

绘制简单的图表不应该需要估算器。

使用mlxtend.plotting,

from mlxtend.plotting import plot_confusion_matrix
import matplotlib.pyplot as plt
import numpy as np

binary1 = np.array([[4, 1],
                   [1, 2]])

fig, ax = plot_confusion_matrix(conf_mat=binary1)
plt.show()

它提供相同的输出。

根据这个

它需要一个分类器,

disp = plot_confusion_matrix(classifier, X_test, y_test,
                                 display_labels=class_names,
                                 cmap=plt.cm.Blues,
                                 normalize=normalize)

我可以不使用分类器来绘制它吗?


我可以不使用分类器绘制它吗? - Rakibul Hassan
5个回答

10

plot_confusion_matrix 需要一个已经训练好的分类器。如果你查看 源代码,它会执行预测操作,并为您生成 y_pred

y_pred = estimator.predict(X)
    cm = confusion_matrix(y_true, y_pred, sample_weight=sample_weight,
                          labels=labels, normalize=normalize)

如果您想绘制混淆矩阵而不指定一个分类器,您需要使用其他工具或自己编写代码。一个简单的选项是使用seaborn:

import seaborn as sns

cm = confusion_matrix(y_true, y_pred)
f = sns.heatmap(cm, annot=True)

输入图像描述


谢谢。我必须使用pandas和seaborn来实现它。我可以使用scikit-learn的工具吗?我在这里看到,它是在没有分类器的情况下使用的(https://datascience.stackexchange.com/questions/40067/confusion-matrix-three-classes-python)。 - Rakibul Hassan
1
为什么不自己定义函数,而要使用链接中的自定义函数呢? - yatu
1
谢谢。我觉得它看起来很相似,我们不能使用ConfusionMatrixDisplay吗? - Rakibul Hassan

5

我来晚了,但我认为其他人也可能从我的回答中受益。

正如其他人提到的那样,如果没有分类器,使用 plot_confusion_matrix 是不可行的,但仍然可以使用 sklearn 来获取类似外观的混淆矩阵。下面的函数就是实现这个功能。

from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay

def confusion_ma(y_true, y_pred, class_names):
    cm = confusion_matrix(y_true, y_pred, normalize='true')
    disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=class_names)
    disp.plot(cmap=plt.cm.Blues)
    return plt.show()

confusion_matrix 函数返回一个简单的 ndarry 矩阵。将其与预测标签一起传递给 ConfusionMatrixDisplay 函数,可以获得类似的矩阵。在定义中,我添加了要显示的 class_names,而不是 0 和 1,选择规范化输出并指定了一种颜色映射 - 根据您的需要进行更改。


实际上,这应该是被接受的答案! - ashkan

1

由于plot_confusion_matrix要求参数'estimator'不能为None,所以答案是:不行。但是你可以用其他方式绘制混淆矩阵,例如查看这个答案:如何绘制混淆矩阵?


0
我解决了使用自定义分类器的问题;您可以构建任何自定义分类器并将其作为类传递给plot_confusion_matrix函数:
class MyModelPredict(object):
    def __init__(self, model):
        self._estimator_type = 'classifier'
        
    def predict(self, X):
        return your_custom_prediction

model = MyModelPredict()
plot_confusion_matrix(model, X, y_true)

0
我在运行Amazon SageMaker中的conda_python3内核的Jupyter笔记本中测试了以下“身份分类器”。原因是SageMaker的转换作业是异步的,因此不允许在plot_confusion_matrix的参数中使用分类器,必须在调用函数之前计算y_pred
IC = type('IdentityClassifier', (), {"predict": lambda i : i, "_estimator_type": "classifier"})
plot_confusion_matrix(IC, y_pred, y_test, normalize='true', values_format='.2%');

因此,虽然plot_confusion_matrix确实需要一个估计器,但如果这个解决方案适合您的用例,您不一定需要使用另一个工具,在我看来。

笔记本中的简化POC


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接