带数值的混淆矩阵画图代码
时间: 2023-07-09 15:04:41 浏览: 157
以下是Python代码,使用Matplotlib库绘制带数值的混淆矩阵图:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义混淆矩阵
confusion_matrix = np.array([[25, 5, 0], [5, 20, 5], [0, 5, 25]])
# 定义标签
labels = ['Class 0', 'Class 1', 'Class 2']
# 绘制混淆矩阵图
fig, ax = plt.subplots()
im = ax.imshow(confusion_matrix, cmap='Blues')
# 显示数值
for i in range(len(labels)):
for j in range(len(labels)):
text = ax.text(j, i, confusion_matrix[i, j],
ha="center", va="center", color="w")
# 设置标题、轴标签、刻度标签
ax.set_title("Confusion Matrix")
ax.set_xticks(np.arange(len(labels)))
ax.set_yticks(np.arange(len(labels)))
ax.set_xticklabels(labels)
ax.set_yticklabels(labels)
ax.set_xlabel("Predicted label")
ax.set_ylabel("True label")
# 旋转刻度标签以避免重叠
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
# 在混淆矩阵图旁添加颜色条
cbar = ax.figure.colorbar(im, ax=ax)
# 显示图形
plt.show()
```
运行以上代码,将得到带数值的混淆矩阵图。可以根据实际需要修改混淆矩阵、标签、标题和颜色映射等参数。
阅读全文