torch_ecg.utils.top_n_accuracy¶
- torch_ecg.utils.top_n_accuracy(labels: Union[numpy.ndarray, torch.Tensor], outputs: Union[numpy.ndarray, torch.Tensor], n: Union[int, Sequence[int]] = 1) Union[float, Dict[str, float]] [source]¶
Compute top n accuracy.
- Parameters
labels (numpy.ndarray or torch.Tensor) – Labels of class indices, of shape
(batch_size,)
or(batch_size, d_1, ..., d_m)
.outputs (numpy.ndarray or torch.Tensor) – Predicted probabilities, of shape
(batch_size, num_classes)
or(batch_size, d_1, ..., d_m, num_classes)
or(batch_size, num_classes, d_1, ..., d_m)
.
- Returns
acc – Top n accuracy.
- Return type
float or dict of float
Examples
>>> from torch_ecg.cfg import DEFAULTS >>> labels, outputs = DEFAULTS.RNG_randint(0, 9, (100)), DEFAULTS.RNG.uniform(0, 1, (100, 10)) # 100 samples, 10 classes >>> top_n_accuracy(labels, outputs, 3) 0.32 >>> top_n_accuracy(labels, outputs, [1,3,5]) {'top_1_acc': 0.12, 'top_3_acc': 0.32, 'top_5_acc': 0.52}