Help with nested loop

Asked

Viewed 49 times

0

yhat_tr is a column of 500 items.

d_tr, tb with 500 elements, is another column, which I loaded separately from the first, are different sources, but with the same indexes. My code is this:

TP, FP, TN, FN = 0,0,0,0
    print(len(yhat_tr))
    print(len(d_tr))


    for i in yhat_tr:
      for a in d_tr: # d_tr = coluna do excel com as classes 1 ou -1
        if i > 0 and a > 0:
          TP += 1

        if i > 0 and a < 0:
          FP += 1

        if i < 0 and a < 0:
          TN += 1

        if i < 0 and a > 0:
          FN += 1

    print ('Totais:', '\nTP: ', TP, '\nFP: ', FP, '\nTN: ', TN, '\nFN: ', FN)

    # Cálculo da Acurácia
    accuracy = (TP + TN) / (TP + FP + TN + FN)
    print ('Acurácia (ACC): ', accuracy)

I’m thinking that this loop is wrong because of 1000 data I’m with adding results TP: 63000 FP: 63000 TN: 62000 FN: 62000, that is, has to be adding up more than once each item. It was for TP, Tn, FP, FN to give the total of 1000.

My attempt was to: Traverse line 1: if the value of the index iten 0 of y_hat > 0 and the same index of dr_tr > 0, sum 1 in TP (a counter) The same logic in the other variables, alternating the signal <, >.

1 answer

2


 for i in yhat_tr:
      for a in d_tr:

With these two lines you are iterating 500*500 times. For each value of i you iterate 500 values of a.

What you need is something like

for i, a in zip(yhat_tr, d_tr):
  • Perfect! I love you.

  • Correct comp mark, you’re welcome :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.