Classification#

kornia.metrics.accuracy(pred, target, topk=(1,))[source]#

Compute the top-k classification accuracy of class scores, in percent.

accs = accuracy(pred, target, topk=(1, 5)) takes (B, C) class scores and (B,) class indices, and returns one percentage in \([0, 100]\), not a fraction, per entry of topk.

Convention:
  • Only the order of the scores in a row matters. A sample counts for k when its target is among its k highest scores; a k above \(C\) counts as \(C\). Losses and metrics lists the scale of every task metric.

Parameters:
  • pred (Tensor) – class scores with shape (B, C).

  • target (Tensor) – ground-truth class indices with shape (B,) or (B, 1).

  • topk (Tuple[int, ...], optional) – the values of k, positive integers. Default: (1,)

Return type:

list[Tensor]

Returns:

a list with one 0-d float32 tensor per entry of topk, in that order.

See also

  • confusion_matrix(): counts of every target and predicted class pair, from hard labels.

  • AverageMeter: the running mean of these percentages over batches.

Example

>>> logits = torch.tensor([[0, 1, 0]])
>>> target = torch.tensor([[1]])
>>> accuracy(logits, target)
[tensor(100.)]