Publishing 2019 R1 content
[platform/upstream/dldt.git] / tools / accuracy_checker / accuracy_checker / metrics / average_meter.py
1 """
2 Copyright (c) 2019 Intel Corporation
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8       http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 """
16
17 import numpy as np
18
19
20 class AverageMeter:
21     def __init__(self, loss=None, counter=None):
22         self.loss = loss or (lambda x, y: int(x == y))
23         self.counter = counter or (lambda x: 1)
24         self.accumulator = None
25         self.total_count = None
26
27     def update(self, annotation_val, prediction_val):
28         loss = self.loss(annotation_val, prediction_val)
29         increment = self.counter(annotation_val)
30
31         if self.accumulator is None and self.total_count is None:
32             # wrap in array for using numpy.divide with where attribute
33             # and support cases when loss function returns list-like object
34             self.accumulator = np.array(loss, dtype=float)
35             self.total_count = np.array(increment, dtype=float)
36         else:
37             self.accumulator += loss
38             self.total_count += increment
39
40     def evaluate(self):
41         if self.total_count is None:
42             return 0.0
43
44         return np.divide(
45             self.accumulator, self.total_count, out=np.zeros_like(self.accumulator), where=self.total_count != 0
46         )