Shortcuts

torcheval.metrics.functional.multiclass_confusion_matrix

torcheval.metrics.functional.multiclass_confusion_matrix(input: Tensor, target: Tensor, num_classes: int, *, normalize: str | None = None) Tensor

计算多类混淆矩阵,这是一个维度为num_classes x num_classes的矩阵,其中位置(i,j)处的元素表示真实类别为i但被预测为类别j的样本数量。

Parameters:
  • 输入 (张量) – 标签预测的张量。 它可以是预测的标签,形状为 (n_sample, )。 它也可以是概率或 logits,形状为 (n_sample, n_class)。 torch.argmax 将用于将输入转换为预测标签。

  • target (Tensor) – 形状为 (n_sample, ) 的真实标签张量。

  • num_classes (int) – 类别数量。

  • normalize

    • None [默认]:

      提供原始计数('none' 也默认为此)

    • 'pred':

      在预测类别上进行归一化,即使行加起来为一。

    • 'true':

      在条件正例上进行归一化,即使列加起来为一。

    • 'all'

      在所有示例上进行归一化,即使所有矩阵条目加起来为一。

示例:

>>> 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]])