ONE - On-device Neural Engine
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
categorical_accuracy.py
Go to the documentation of this file.
1import numpy as np
2from .metric import Metric
3
4
6 """
7 Metric for computing categorical accuracy.
8 """
9 def __init__(self):
10 self.correct = 0
11 self.total = 0
12 self.axis = 0
13
14 def reset_state(self):
15 """
16 Reset the metric's state.
17 """
18 self.correct = 0
19 self.total = 0
20
21 def update_state(self, outputs, expecteds):
22 """
23 Update the metric's state based on the outputs and expecteds.
24 Args:
25 outputs (list of np.ndarray): List of model outputs for each output layer.
26 expecteds (list of np.ndarray): List of expected ground truth values for each output layer.
27 """
28 if len(outputs) != len(expecteds):
29 raise ValueError(
30 "The number of outputs and expecteds must match. "
31 f"Got {len(outputs)} outputs and {len(expecteds)} expecteds.")
32
33 for output, expected in zip(outputs, expecteds):
34 if output.shape[self.axis] != expected.shape[self.axis]:
35 raise ValueError(
36 f"Output and expected shapes must match along the specified axis {self.axis}. "
37 f"Got output shape {output.shape} and expected shape {expected.shape}."
38 )
39
40 batch_size = output.shape[self.axis]
41 for b in range(batch_size):
42 output_idx = np.argmax(output[b])
43 expected_idx = np.argmax(expected[b])
44 if output_idx == expected_idx:
45 self.correct += 1
46 self.total += batch_size
47
48 def result(self):
49 """
50 Compute and return the final metric value.
51 Returns:
52 float: Metric value.
53 """
54 if self.total == 0:
55 return 0.0
56 return self.correct / self.total