上述代码绘制混淆矩阵实现
时间: 2023-08-14 07:05:53 浏览: 101
要绘制混淆矩阵热力图,可以参考以下代码实现:
```python
import seaborn as sn
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
def plot_matrix(y_true, y_pred, title_name):
cm = confusion_matrix(y_true, y_pred) # 计算混淆矩阵
ax = sn.heatmap(cm, annot=True, fmt='g', xticklabels=\['1', '2', '3'\], yticklabels=\['1', '2', '3'\]) # 绘制热力图
ax.set_title(title_name) # 设置标题
ax.set_xlabel('predict') # 设置x轴标签
ax.set_ylabel('true') # 设置y轴标签
plt.show() # 显示图像
T_test = \[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3\]
adb_pre = \[3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3\]
plot_matrix(T_test, adb_pre, 'example-confusion matrix')
```
这段代码首先计算了混淆矩阵`cm`,然后使用seaborn的heatmap函数绘制了热力图,其中`annot=True`表示在热力图上显示数字,`fmt='g'`表示显示的数字格式,`xticklabels`和`yticklabels`指定了横纵轴的标签。`plt.show()`用于显示图像。最后,通过调用`plot_matrix`函数并传入真实标签列表`T_test`和预测标签列表`adb_pre`,以及设置标题名字`'example-confusion matrix'`来绘制混淆矩阵热力图。
#### 引用[.reference_title]
- *1* [Matplotlib交互式图表——混淆矩阵可视化](https://blog.csdn.net/weixin_39982537/article/details/111842150)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_tab","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.null"}} ] [.reference_item]
- *2* [Matplotlib交互式图表——混淆矩阵可视化](https://blog.csdn.net/weixin_39982537/article/details/111842150)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_tab","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.null"}} ] [.reference_item]
- *3* [Python画混淆矩阵热力图(简单示例)](https://blog.csdn.net/qq_45163716/article/details/121036203)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_tab","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.null"}} ] [.reference_item]
- *4* [【论文必用】Python绘制混淆矩阵](https://blog.csdn.net/qq_40968179/article/details/129548439)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_tab","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.null"}} ] [.reference_item]
- *5* [使用python库绘制混淆矩阵(数字不居中,精度显示问题的解决)](https://blog.csdn.net/jtyjaykkk/article/details/122390455)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_tab","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.null"}} ] [.reference_item]
[ .reference_list ]
阅读全文