python二分类计算tp,fp, tn, fn代码
时间: 2023-08-29 22:12:40 浏览: 319
以下是一个简单的Python程序用于计算二分类中的TP、FP、TN、FN:
```python
def calculate_metrics(actual, predicted):
tp = 0
fp = 0
tn = 0
fn = 0
for i in range(len(actual)):
if actual[i] == 1 and predicted[i] == 1:
tp += 1
elif actual[i] == 0 and predicted[i] == 1:
fp += 1
elif actual[i] == 0 and predicted[i] == 0:
tn += 1
elif actual[i] == 1 and predicted[i] == 0:
fn += 1
return tp, fp, tn, fn
actual = [0, 1, 0, 1, 1, 0, 0, 1]
predicted = [0, 1, 1, 1, 1, 0, 0, 0]
tp, fp, tn, fn = calculate_metrics(actual, predicted)
print("TP:", tp)
print("FP:", fp)
print("TN:", tn)
print("FN:", fn)
```
输出结果:
```
TP: 3
FP: 1
TN: 2
FN: 2
```
其中`actual`表示实际的分类结果,`predicted`表示预测的分类结果。根据分类结果的不同组合,程序计算出TP、FP、TN、FN的个数,并返回结果。
阅读全文