Shortcuts

torcheval.metrics.functional.multiclass_confusion_matrix

torcheval.metrics.functional.multiclass_confusion_matrix(input: Tensor, target: Tensor, num_classes: int, *, normalize: Optional[str] = None) Tensor[source]

Compute multi-class confusion matrix, a matrix of dimension num_classes x num_classes where each element at position (i,j) is the number of examples with true class i that were predicted to be class j. See also binary_confusion_matrix

Parameters:
  • input (Tensor) – Tensor of label predictions. It could be the predicted labels, with shape of (n_sample, ). It could also be probabilities or logits with shape of (n_sample, n_class). torch.argmax will be used to convert input into predicted labels.
  • target (Tensor) – Tensor of ground truth labels with shape of (n_sample, ).
  • num_classes (int) – Number of classes.
  • normalize
    • None [default]:
      Give raw counts (‘none’ also defaults to this)
    • 'pred':
      Normalize across the prediction class, i.e. such that the rows add to one.
    • 'true':
      Normalize across the condition positive, i.e. such that the columns add to one.
    • 'all'
      Normalize across all examples, i.e. such that all matrix entries add to one.

Examples:

>>> import torch
>>> from torcheval.metrics.functional import multiclass_confusion_matrix
>>> input = torch.tensor([0, 2, 1, 3])
>>> target = torch.tensor([0, 1, 2, 3])
>>> multiclass_confusion_matrix(input, target, 4)
tensor([[1, 0, 0, 0],
        [0, 0, 1, 0],
        [0, 1, 0, 0],
        [0, 0, 0, 1]])

>>> input = torch.tensor([0, 0, 1, 1, 1])
>>> target = torch.tensor([0, 0, 0, 0, 1])
>>> multiclass_confusion_matrix(input, target, 2)
tensor([[2, 2],
        [0, 1]])

>>> input = torch.tensor([0, 0, 1, 1, 1, 2, 1, 2])
>>> target = torch.tensor([2, 0, 2, 0, 1, 2, 1, 0])
>>> multiclass_confusion_matrix(input, target, 3)
tensor([[1, 1, 1],
        [0, 2, 0],
        [1, 1, 1]])

>>> input = torch.tensor([0, 0, 1, 1, 1, 2, 1, 2])
>>> target = torch.tensor([2, 0, 2, 0, 1, 2, 1, 0])
>>> multiclass_confusion_matrix(input, target, 3, normalize="pred")
tensor([[0.5000, 0.2500, 0.5000],
        [0.0000, 0.5000, 0.0000],
        [0.5000, 0.2500, 0.5000]])


>>> input = torch.tensor([0, 0, 1, 1, 1])
>>> target = torch.tensor([0, 0, 0, 0, 1])
>>> multiclass_confusion_matrix(input, target, 4)
tensor([[2, 2, 0, 0],
        [0, 1, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0]])

>>> input = torch.tensor([[0.9, 0.1, 0, 0], [0.1, 0.2, 0.4, 0.3], [0, 1.0, 0, 0], [0, 0, 0.2, 0.8]])
>>> target = torch.tensor([0, 1, 2, 3])
>>> multiclass_confusion_matrix(input, target, 4)
tensor([[1, 0, 0, 0],
        [0, 0, 1, 0],
        [0, 1, 0, 0],
        [0, 0, 0, 1]])

Docs

Access comprehensive developer documentation for PyTorch

View Docs

Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

Resources

Find development resources and get your questions answered

View Resources