Implementation:Kornia Kornia Confusion Matrix
| Knowledge Sources | |
|---|---|
| Domains | Vision, Metrics |
| Last Updated | 2026-02-09 15:00 GMT |
Overview
Computes a batched confusion matrix to evaluate the accuracy of a classification model.
Description
The confusion_matrix function computes a confusion matrix for each sample in a batch, producing a tensor of shape (B, K, K) where B is the batch size and K is the number of classes. The confusion matrix is a fundamental evaluation tool in classification tasks, where element (i, j) represents the number of instances where class i was the true label and class j was predicted. The implementation uses a bincount-based approach to efficiently compute the matrix without requiring explicit loops over class pairs. An optional normalization parameter divides each row by its sum, yielding row-normalized probabilities. The implementation is inspired by PyTorch TNT's ConfusionMeter.
Usage
Import this metric when you need to evaluate classification performance at a per-class level, visualize prediction errors across classes, or compute derived metrics such as precision, recall, and F1-score from the confusion matrix.
Code Reference
Source Location
- Repository: Kornia
- File: kornia/metrics/confusion_matrix.py
- Lines: 1-87
Signature
def confusion_matrix(
pred: torch.Tensor,
target: torch.Tensor,
num_classes: int,
normalized: bool = False
) -> torch.Tensor:
Import
from kornia.metrics import confusion_matrix
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| pred | torch.Tensor | Yes | Tensor with estimated target values containing integer class indices between 0 and K-1. Shape can be (B, *). |
| target | torch.Tensor | Yes | Tensor with ground truth target values containing integer class indices between 0 and K-1. Shape can be (B, *) and must match pred shape. |
| num_classes | int | Yes | Total number of possible classes. Must be an integer greater than or equal to 2. |
| normalized | bool | No | Whether to return the confusion matrix normalized by row sums. Defaults to False. |
Outputs
| Name | Type | Description |
|---|---|---|
| confusion_mat | torch.Tensor | A tensor of shape (B, K, K) containing the confusion matrix for each batch element, cast to float32. If normalized, each row sums to approximately 1. |
Usage Examples
import torch
from kornia.metrics import confusion_matrix
# Simple 3-class example
logits = torch.tensor([[0, 1, 0]])
target = torch.tensor([[0, 1, 0]])
cm = confusion_matrix(logits, target, num_classes=3)
# cm: tensor([[[2., 0., 0.],
# [0., 1., 0.],
# [0., 0., 0.]]])
# Normalized confusion matrix
cm_norm = confusion_matrix(logits, target, num_classes=3, normalized=True)