multilabel_confusion_matrix#

sklearn.metrics.multilabel_confusion_matrix(y_true, y_pred, *, sample_weight=None, labels=None, samplewise=False)[source]#

计算每个类别或样本的混淆矩阵。

0.21 版本新增。

计算按类(默认)或按样本(samplewise=True)的多标签混淆矩阵,以评估分类的准确性,并输出每个类或每个样本的混淆矩阵。

在多标签混淆矩阵 \(MCM\) 中,真阴性的计数为 \(MCM_{:,0,0}\),假阴性为 \(MCM_{:,1,0}\),真阳性为 \(MCM_{:,1,1}\),假阳性为 \(MCM_{:,0,1}\)

多分类数据将被视为按“一对多”(one-vs-rest)转换进行二值化处理。返回的混淆矩阵将按照 (y_true, y_pred) 并集中唯一标签的排序顺序排列。

用户指南 中了解更多信息。

参数:
y_true{array-like, sparse matrix} of shape (n_samples, n_outputs) or (n_samples,)

真实(正确)的目标值。仅当标签属于 多标签 (multilabel) 类型时才支持稀疏矩阵。

y_pred{array-like, sparse matrix} of shape (n_samples, n_outputs) or (n_samples,)

由分类器返回的估计目标值。仅当标签属于 多标签 (multilabel) 类型时才支持稀疏矩阵。

sample_weightshape 为 (n_samples,) 的 array-like, default=None

样本权重。

labels形状为 (n_classes,) 的类数组对象, 默认为 None

用于选择部分类或列索引的列表(或强制包含数据中缺少的类)。

samplewisebool, default=False

在多标签情况下,此参数会按样本计算混淆矩阵。

返回:
multi_confusionndarray of shape (n_outputs, 2, 2)

对应输入中每个输出的 2x2 混淆矩阵。当计算按类的 multi_confusion(默认)时,n_outputs = n_labels;当计算按样本的 multi_confusion(samplewise=True)时,n_outputs = n_samples。如果定义了 labels,结果将按 labels 中指定的顺序返回,否则默认按排序顺序返回结果。

另请参阅

confusion_matrix

计算混淆矩阵以评估分类器的准确性。

注意事项

multilabel_confusion_matrix 计算按类或按样本的多标签混淆矩阵,且在多分类任务中,标签按“一对多”方式进行二值化;而 confusion_matrix 则计算每两个类之间混淆情况的单个混淆矩阵。

示例

多标签指示器情况

>>> import numpy as np
>>> from sklearn.metrics import multilabel_confusion_matrix
>>> y_true = np.array([[1, 0, 1],
...                    [0, 1, 0]])
>>> y_pred = np.array([[1, 0, 0],
...                    [0, 1, 1]])
>>> multilabel_confusion_matrix(y_true, y_pred)
array([[[1, 0],
        [0, 1]],

       [[1, 0],
        [0, 1]],

       [[0, 1],
        [1, 0]]])

多分类情况

>>> y_true = ["cat", "ant", "cat", "cat", "ant", "bird"]
>>> y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"]
>>> multilabel_confusion_matrix(y_true, y_pred,
...                             labels=["ant", "bird", "cat"])
array([[[3, 1],
        [0, 2]],

       [[5, 0],
        [1, 0]],

       [[2, 1],
        [1, 2]]])