python - Python 中多个类的混淆矩阵

标签 python confusion-matrix

我已经通过 python 代码生成了多类混淆矩阵:

import seaborn as sns
import matplotlib.pyplot as plt

### Confusion Matrix
from sklearn.metrics import confusion_matrix
predictions = model.predict(x_test, steps=len(x_test), verbose=0)
#y_pred=model.predict(x_test)
#y_pred = np.round(y_pred)
y_pred = np.argmax(predictions, axis=-1)

y_true=np.argmax(y_test, axis=-1)

cm = confusion_matrix(y_true, y_pred)

## Get Class Labels
labels = le.classes_
class_names = labels

# Plot confusion matrix in a beautiful manner
fig = plt.figure(figsize=(16, 14))
ax= plt.subplot()
sns.heatmap(cm, annot=True, ax = ax, fmt = 'g'); #annot=True to annotate cells
# labels, title and ticks
ax.set_xlabel('Predicted', fontsize=20)
ax.xaxis.set_label_position('bottom')
plt.xticks(rotation=90)
ax.xaxis.set_ticklabels(class_names, fontsize = 10)
ax.xaxis.tick_bottom()

ax.set_ylabel('True', fontsize=20)
ax.yaxis.set_ticklabels(class_names, fontsize = 10)
plt.yticks(rotation=0)

plt.title('Refined Confusion Matrix', fontsize=20)

plt.savefig('ConMat24.png')
plt.show()

此代码生成此图像:

enter image description here

我怎样才能得到像这样只有 4 个单元格的简单混淆矩阵:

enter image description here

最佳答案

写一个绘图函数:

import matplotlib.pyplot as plt

def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, cm[i, j],
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')

获取准确率报告和混淆矩阵

from sklearn import metrics
import itertools

score = metrics.accuracy_score(y_test, y_pred)
print("accuracy:   %0.3f" % score)

cm = metrics.confusion_matrix(y_test, y_pred)
plot_confusion_matrix(cm, classes=['True', 'False'])

它将以您需要的相同格式绘制混淆矩阵。

关于python - Python 中多个类的混淆矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65618137/

相关文章:

python - 如何在 GitPython 中创建 Git 拉取请求

azure - Azure ML Studio 中的评估模型节点不会获取混淆矩阵中数据集的所有行

缺少类别的 R 包插入符号混淆矩阵

python - 如何在 fastai 中改变混淆矩阵的大小?

python - 如何从多类分类的混淆矩阵中提取 False Positive、False Negative

machine-learning - 分类报告中的精确率和召回率是如何计算的?

python - 图片上传后出现错误

Python:为什么函数没有修改对象?

python - 如何汇总CSV列?

python - django.db.utils.ProgrammingError : relation "blogango_blog" does not exist