用python写混淆矩阵代码
时间: 2023-12-17 19:54:26 浏览: 26
以下是用 Python 编写混淆矩阵代码的示例:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
# 随机生成样本分类结果
y_true = np.random.randint(0, 2, size=100)
y_pred = np.random.randint(0, 2, size=100)
# 计算混淆矩阵
cm = confusion_matrix(y_true, y_pred)
# 可视化混淆矩阵
fig, ax = plt.subplots()
im = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)
ax.set(xticks=np.arange(cm.shape[1]),
yticks=np.arange(cm.shape[0]),
xticklabels=['Negative', 'Positive'],
yticklabels=['Negative', 'Positive'],
title='Confusion Matrix',
ylabel='True label',
xlabel='Predicted label')
# 添加标签
thresh = cm.max() / 2.
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
ax.text(j, i, format(cm[i, j], 'd'),
ha="center", va="center",
color="white" if cm[i, j] > thresh else "black")
fig.tight_layout()
plt.show()
```
上述代码使用 Scikit-Learn 库中的 `confusion_matrix` 函数计算混淆矩阵,并使用 Matplotlib 库可视化混淆矩阵。在此示例中,我们随机生成了一个包含 100 个样本的分类结果,并且将该结果传递给 `confusion_matrix` 函数以计算混淆矩阵。在可视化混淆矩阵时,我们将真实标签和预测标签分别标记为行和列,用蓝色表示矩阵中的每个值,并使用白色和黑色来标记矩阵中的文本,以便更好地查看矩阵。