混淆矩阵Python
时间: 2023-11-19 16:16:24 浏览: 35
混淆矩阵是一种用于评估分类模型性能的工具。它显示了模型对每个类别的分类结果与实际标签之间的关系。
在Python中,可以使用sklearn.metrics库中的confusion_matrix函数来计算混淆矩阵。首先,需要导入相应的库,并将预测结果和真实标签存储在y_pred和y_true两个变量中。然后,使用confusion_matrix函数传入y_true和y_pred以及类别列表来计算混淆矩阵C。
接下来,可以使用matplotlib.pyplot库来绘制混淆矩阵。使用plt.matshow函数将混淆矩阵以矩阵的形式显示出来,并可以根据需要选择颜色映射。使用plt.annotate函数在每个格子中显示对应的值。最后,使用plt.ylabel和plt.xlabel函数来设置y轴和x轴的标签。
以下是一个示例代码,可以根据实际情况进行修改和调整:
```python
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
y_pred = [] # 预测结果
y_true = [] # 真实标签
C = confusion_matrix(y_true, y_pred, labels=['0','1','2','3','4'])
plt.matshow(C, cmap=plt.cm.Reds)
for i in range(len(C)):
for j in range(len(C)):
plt.annotate(C[j, i], xy=(i, j), horizontalalignment='center', verticalalignment='center')
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()
```
请注意,这只是一个示例代码,你需要根据自己的实际情况进行相应的修改和适配。希望对你有所帮助!<span class="em">1</span><span class="em">2</span>
#### 引用[.reference_title]
- *1* *2* [利用python绘制混淆矩阵](https://blog.csdn.net/weixin_43818631/article/details/121309660)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]