分类器混淆矩阵的画法
时间: 2023-06-21 09:07:41 浏览: 61
分类器的混淆矩阵是一种评估分类器性能的常用工具,它可以帮助我们了解分类器在不同类别上的分类情况。通常,混淆矩阵是一个 $n \times n$ 的矩阵,其中 $n$ 是类别的数量。下面是混淆矩阵的一般结构:
| | 预测为类别 1 | 预测为类别 2 | ... | 预测为类别 n |
|--------|--------------|--------------|-----|--------------|
| 类别 1 | True Positive | False Negative | ... | False Negative |
| 类别 2 | False Positive| True Positive | ... | False Negative |
| ... | ... | ... | ... | ... |
| 类别 n | False Positive| False Positive| ... | True Positive |
其中,True Positive 表示分类器正确地将一个样本分为类别 1,False Positive 表示分类器将一个非类别 1 的样本错误地分为类别 1,False Negative 表示分类器将一个类别 1 的样本错误地分为非类别 1,True Negative 表示分类器正确地将一个样本分为非类别 1。
下面是混淆矩阵的画法:
1. 首先,确定所有可能的类别。
2. 统计分类器在测试集上的预测结果,根据预测结果填写混淆矩阵。
3. 使用各种可视化工具(如 Matplotlib)将混淆矩阵可视化。
例如,下面是一个二元分类器的混淆矩阵的画法:
```python
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
# 假设 y_true, y_pred 是测试集上的真实标签和预测结果
classes = ['类别 1', '类别 2'] # 所有可能的类别
cm = confusion_matrix(y_true, y_pred) # 计算混淆矩阵
# 可视化混淆矩阵
fig, ax = plt.subplots()
im = ax.imshow(cm, cmap='Blues')
# 设置坐标轴标签
ax.set_xticks(range(len(classes)))
ax.set_yticks(range(len(classes)))
ax.set_xticklabels(classes)
ax.set_yticklabels(classes)
# 在矩阵中添加数值标签
for i in range(len(classes)):
for j in range(len(classes)):
text = ax.text(j, i, cm[i, j],
ha="center", va="center", color="w")
# 添加标题和颜色条
ax.set_title("混淆矩阵")
fig.colorbar(im)
plt.show()
```
相关推荐
![m](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)