如何重新创建一个画布并在新画布上画出混淆矩阵
时间: 2023-09-18 14:15:55 浏览: 59
您可以使用Python中的Matplotlib库来创建一个新的画布并在其上绘制混淆矩阵。以下是一个简单的示例代码:
```python
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
# 假设y_true和y_pred是您的真实标签和预测标签
cm = confusion_matrix(y_true, y_pred)
# 创建一个新的画布
fig, ax = plt.subplots()
# 绘制混淆矩阵
im = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)
ax.figure.colorbar(im, ax=ax)
# 添加标签
ax.set(xticks=np.arange(cm.shape[1]),
yticks=np.arange(cm.shape[0]),
xticklabels=classes, yticklabels=classes,
title='Confusion matrix',
ylabel='True label',
xlabel='Predicted label')
# 旋转x轴标签
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
# 在单元格中添加百分比
fmt = '.2f'
thresh = cm.max() / 2.
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
ax.text(j, i, format(cm[i, j], fmt),
ha="center", va="center",
color="white" if cm[i, j] > thresh else "black")
# 添加网格
ax.grid(False)
# 显示图像
plt.show()
```
请注意,此代码需要以下库:`matplotlib`和`sklearn.metrics`。您需要将`y_true`和`y_pred`替换为您的真实标签和预测标签,并将`classes`替换为您的类别名称列表。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)