我写了下面的代码,但是它指定了文件中的行数。我想知道如何更改它,以使其读取未知数量的行?
n = int(input("instance: "))
tp, tn, fp, fn = 0
for i in range(n):
real, predicted = map(int, input().split(' '))
for num in i:
if real == 1 and predicted == 1:
tp += 1
elif real == 0 and predicted == 0:
tn += 1
elif real == 1 and predicted == 0:
fn += 1
else:
fp += 1
pr = tp / (tp + fp)
rc = tp / (tp + fn)
f1 = 2 * ((pr * rc) / (pr + rc))
print("f1= ", f1)
我的代码读取这些行,并将每行中的数字相互比较,但不与其他行中的数字进行比较。
输入看起来像这样:
1 1
0 0
0 1
0 1
1 0
0 1
0 0
1 1
0 0
0 0
0 0
0 0
1 1
答案 0 :(得分:2)
保持阅读,直到抛出EOFError
:
tp, tn, fp, fn = 0
i = 0
try:
while True:
real, predicted = map(int, input().split(' '))
for num in i:
if real == 1 and predicted == 1:
tp += 1
elif real == 0 and predicted == 0:
tn += 1
elif real == 1 and predicted == 0:
fn += 1
else:
fp += 1
i += 1
except EOFError:
pass
pr = tp / (tp + fp)
rc = tp / (tp + fn)
f1 = 2 * ((pr * rc) / (pr + rc))
print("f1= ", f1)
您的代码也有错误:
range
。这应该解决它们:
tp = tn = fp = fn = 0
i = 0
try:
while True:
real, predicted = map(int, input().split(' '))
for num in range(i):
if real == 1 and predicted == 1:
tp += 1
elif real == 0 and predicted == 0:
tn += 1
elif real == 1 and predicted == 0:
fn += 1
else:
fp += 1
i += 1
except EOFError:
pass
pr = tp / (tp + fp)
rc = tp / (tp + fn)
f1 = 2 * ((pr * rc) / (pr + rc))
print("f1= ", f1)