利用python中的matplotlib打印混淆矩阵实例
时间: 2023-09-09 17:01:13 浏览: 63
使用Python中的Matplotlib库可以很方便地打印混淆矩阵。首先,我们需要导入必要的库和数据。
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
# 定义真实标签和预测结果
y_true = [1, 0, 0, 1, 1, 0, 2, 1, 2, 0]
y_pred = [1, 0, 1, 1, 0, 0, 2, 1, 2, 2]
# 计算混淆矩阵
cm = confusion_matrix(y_true, y_pred)
```
然后,我们可以使用Matplotlib库中的imshow函数来可视化混淆矩阵。
```python
# 可视化混淆矩阵
plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Greens)
plt.title('Confusion Matrix')
plt.colorbar()
# 设置坐标轴标签
classes = ['Class 0', 'Class 1', 'Class 2']
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
# 设置颜色标签
thresh = cm.max() / 2.
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
plt.text(j, i, cm[i, j], ha="center", va="center", color="white" if cm[i, j] > thresh else "black")
# 设置坐标轴标签
plt.tight_layout()
plt.ylabel('True Label')
plt.xlabel('Predicted Label')
# 显示混淆矩阵
plt.show()
```
运行上述代码后,将会显示一个带有颜色标注的混淆矩阵,横坐标表示预测结果,纵坐标表示真实标签。每个单元格中的数字表示对应真实标签和预测结果的样本数量。颜色越深表示数量越多,颜色越浅表示数量越少。通过这个混淆矩阵,我们可以直观地了解分类模型的预测情况。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)