读取两个列表完成带数值的混淆矩阵画图代码
时间: 2023-12-03 12:45:59 浏览: 35
以下是Python代码:
```python
import matplotlib.pyplot as plt
import numpy as np
# 两个列表,分别表示预测值和真实值
predicted = [1, 0, 1, 1, 0, 1, 1, 0, 1, 0]
actual = [1, 0, 0, 1, 1, 1, 0, 0, 1, 0]
# 计算混淆矩阵
confusion_matrix = np.zeros((2, 2))
for p, a in zip(predicted, actual):
confusion_matrix[p][a] += 1
# 画图
fig, ax = plt.subplots(figsize=(5, 5))
ax.matshow(confusion_matrix, cmap=plt.cm.Blues)
for i in range(confusion_matrix.shape[0]):
for j in range(confusion_matrix.shape[1]):
ax.text(x=j, y=i, s=int(confusion_matrix[i, j]), va='center', ha='center')
ax.set_xlabel('True label')
ax.set_ylabel('Predicted label')
plt.show()
```
解释一下代码的过程:
- 首先定义了两个列表 `predicted` 和 `actual`,分别表示模型的预测结果和真实结果。
- 接着使用 NumPy 库创建了一个 2x2 的全零数组 `confusion_matrix`,用于记录混淆矩阵。
- 遍历 `predicted` 和 `actual` 列表,根据预测结果和真实结果更新混淆矩阵。
- 最后使用 Matplotlib 库画出混淆矩阵的图像,其中 `ax.matshow()` 函数用于显示矩阵,`ax.text()` 函数用于在每个单元格中添加数值标签。