python - Compare Items In A List Of Nested Dicts And Perform Simple Arithmetic Operations -
how can put list "image_list" function measure_accuracy have return number of times actual , predicted same? in case, return 3.
list:
image_list = [ { 'path':'1.jpg', 'actual':{'dog'}, 'predicted':{'dog'} }, { 'path':'2.jpg', 'actual':{'dog'}, 'predicted':{'cat'} }, { 'path':'3.jpg', 'actual':{'cat'}, 'predicted':{'cat'} }, { 'path':'4.jpg', 'actual':{'cat'}, 'predicted':{'dog'} }, { 'path':'5.jpg', 'actual':{'dog'}, 'predicted':{'dog'} } ]
so want compare each item in list , if if 2 items same add variable in end return variable. not know code there.
i thought maybe like
for actual, predicted in image_list: if actual == predicted: count = count + 1
in [7]: sum(x['actual'] == x['predicted'] x in image_list) out[7]: 3
so:
def measure_accuracy(image_list): return sum(x['actual'] == x['predicted'] x in image_list) total = measure_accuracy(image_list) average = total / len(image_list)
a brief explanation of what's happening here:
x['actual'] == x['predicted']
evaluates either true
or false
. in python, true == 1
, false == 0
, we're getting 1 each time predicted value equal actual value, otherwise 0. our list this:
[1, 0, 1, 0, 1]
then use sum
function add them 3.
Comments
Post a Comment