import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import itertools
# 真实类别和模型预测的类别
true_labels = [2, 0, 2, 2, 0, 1]
predicted_labels = [2, 0, 2, 2, 1, 2]
# 计算混淆矩阵
confusion = confusion_matrix(true_labels, predicted_labels)
# 定义类别标签
class_names = ['Class 0', 'Class 1', 'Class 2']
# 创建混淆矩阵图像
plt.figure(figsize=(8, 6))
plt.imshow(confusion, interpolation='nearest', cmap=plt.cm.Blues)
plt.title('混淆矩阵')
plt.colorbar()
tick_marks = np.arange(len(class_names))
plt.xticks(tick_marks, class_names, rotation=45)
plt.yticks(tick_marks, class_names)
thresh = confusion.max() / 2.0
for i, j in itertools.product(range(confusion.shape[0]), range(confusion.shape[1)):
plt.text(j, i, format(confusion[i, j], 'd'), horizontalalignment="center", color="white" if confusion[i, j] > thresh else "black")
plt.ylabel('真实类别')
plt.xlabel('预测类别')
plt.tight_layout()
plt.show()
多分类计算混淆矩阵并绘图
最新推荐文章于 2024-07-22 20:35:33 发布