以下是Python绘制二分类混淆矩阵的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
# 定义真实标签和预测标签
y_true = [0, 1, 0, 1, 1, 0, 0, 1, 1, 1]
y_pred = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
# 定义标签名称
class_names = ['Class 0', 'Class 1']
# 计算混淆矩阵
cnf_matrix = confusion_matrix(y_true, y_pred)
# 绘制混淆矩阵
plt.imshow(cnf_matrix, interpolation='nearest', cmap=plt.cm.Blues)
plt.title('Confusion Matrix')
plt.colorbar()
tick_marks = np.arange(len(class_names))
plt.xticks(tick_marks, class_names, rotation=45)
plt.yticks(tick_marks, class_names)
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
# 在混淆矩阵中添加数字标签
thresh = cnf_matrix.max() / 2.
for i, j in itertools.product(range(cnf_matrix.shape[0]), range(cnf_matrix.shape[1])):
plt.text(j, i, cnf_matrix[i, j],
horizontalalignment="center",
color="white" if cnf_matrix[i, j] > thresh else "black")
plt.tight_layout()
plt.show()
```
运行上述代码,即可绘制出二分类混淆矩阵。其中,`y_true`和`y_pred`分别表示真实标签和预测标签,`class_names`表示标签名称。在绘制混淆矩阵时,我们使用了`confusion_matrix`函数计算混淆矩阵,并使用`imshow`函数绘制混淆矩阵。最后,我们使用`text`函数在混淆矩阵中添加数字标签。