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