Implementation:Kornia Kornia Accuracy Metric
| Knowledge Sources | |
|---|---|
| Domains | Vision, Metrics |
| Last Updated | 2026-02-09 15:00 GMT |
Overview
Computes the top-k classification accuracy between predicted logits and ground truth targets.
Description
The accuracy function evaluates classification performance by computing the percentage of correct predictions among the top-k predictions. For each sample in a batch, the function selects the top-k classes with the highest logit values and checks whether the ground truth label is among them. The result is expressed as a percentage (0 to 100). This is a standard metric used in image classification tasks, particularly when evaluating models on benchmarks such as ImageNet where top-1 and top-5 accuracy are commonly reported.
Usage
Import this metric when you need to evaluate classification model accuracy, especially when computing top-k accuracy for multi-class classification problems. It accepts raw logits (unnormalized scores) and integer target labels.
Code Reference
Source Location
- Repository: Kornia
- File: kornia/metrics/accuracy.py
- Lines: 1-44
Signature
def accuracy(
pred: torch.Tensor,
target: torch.Tensor,
topk: Tuple[int, ...] = (1,)
) -> List[torch.Tensor]:
Import
from kornia.metrics import accuracy
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| pred | torch.Tensor | Yes | The input tensor containing logits to evaluate. Shape is (B, C) where B is batch size and C is the number of classes. |
| target | torch.Tensor | Yes | The tensor containing ground truth class indices. Shape is (B,) or (B, 1). |
| topk | Tuple[int, ...] | No | A tuple of integers specifying which top-k accuracies to compute. Defaults to (1,). |
Outputs
| Name | Type | Description |
|---|---|---|
| result | List[torch.Tensor] | A list of scalar tensors, one per entry in topk, each representing the percentage accuracy (0-100) for that top-k value. |
Usage Examples
import torch
from kornia.metrics import accuracy
# Single sample, top-1 accuracy
logits = torch.tensor([[0, 1, 0]])
target = torch.tensor([[1]])
result = accuracy(logits, target)
# result: [tensor(100.)]
# Batch with top-1 and top-5 accuracy
logits = torch.randn(32, 1000) # 32 samples, 1000 classes
target = torch.randint(0, 1000, (32,))
top1, top5 = accuracy(logits, target, topk=(1, 5))
print(f"Top-1 accuracy: {top1.item():.1f}%")
print(f"Top-5 accuracy: {top5.item():.1f}%")