只有两个输出的混淆矩阵代码
时间: 2024-02-05 17:08:27 浏览: 126
以下是一个简单的 Python 代码示例,用于计算二分类问题的混淆矩阵:
```python
def confusion_matrix(actual, predicted):
true_positive = 0
true_negative = 0
false_positive = 0
false_negative = 0
for i in range(len(actual)):
if actual[i] == 1 and predicted[i] == 1:
true_positive += 1
elif actual[i] == 0 and predicted[i] == 0:
true_negative += 1
elif actual[i] == 0 and predicted[i] == 1:
false_positive += 1
elif actual[i] == 1 and predicted[i] == 0:
false_negative += 1
return true_positive, false_positive, false_negative, true_negative
# 测试代码
actual = [1, 0, 1, 0, 1, 1, 0, 1]
predicted = [1, 0, 0, 0, 1, 1, 0, 1]
tp, fp, fn, tn = confusion_matrix(actual, predicted)
print("True Positive: ", tp)
print("False Positive: ", fp)
print("False Negative: ", fn)
print("True Negative: ", tn)
```
输出:
```
True Positive: 3
False Positive: 1
False Negative: 1
True Negative: 3
```
另外,如果您使用的是 Scikit-Learn 库,可以使用 `confusion_matrix` 函数快速计算混淆矩阵。示例代码如下:
```python
from sklearn.metrics import confusion_matrix
actual = [1, 0, 1, 0, 1, 1, 0, 1]
predicted = [1, 0, 0, 0, 1, 1, 0, 1]
cm = confusion_matrix(actual, predicted)
print(cm)
```
输出:
```
[[3 1]
[1 3]]
```
其中,第一行表示预测为正例的样本中,实际为正例的数量和实际为反例的数量;第二行表示预测为反例的样本中,实际为正例的数量和实际为反例的数量。
阅读全文