I am trying to count the number of times the elements in my list 'predicted' equal the corresponding elements in my list 'actual' when said 'actual' elements equal 1 (the number of 'true positives').
Here's my code:
def F_approx(predicted, actual):
est_tp = np.sum([int(p == a) if a for p in predicted for a in actual])
est_fn = np.sum([int(p !=a) if a for p in predicted for a in actual])
est_recall = est_tp / (est_tp + est_fn)
pr_pred_1 = np.sum([int(p == 1) for p in predicted]) / len(predicted)
est_f = np.power(est_recall, 2) / pr_pred_1
return(est_f)
Which looks correct to my eye, but I get an error:
File "<ipython-input-17-3e11431566d6>", line 2
est_tp = np.sum([int(p == a) if a for p in predicted for a in actual])
^
SyntaxError: invalid syntax
Thanks for the help.
The if
goes after the looping expression:
[int(p == a) for p in predicted for a in actual if a]
However, it really looks like you want to zip
these together:
[int(p == a) for p, a in zip(predicted, actual)]
the if is placed at the end of the list comprehension
[int(p == a) for p in predicted for a in actual if a]
as a side note, with your particular construct you can add a ternary operation and have an else in your list comprehension
[int(p == a) if a else '' for p in predicted for a in actual if a]
adding else to the end of the list comprehension will throw a SyntaxError
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.