【问题标题】:Why is my confusion matrix returning only one number?为什么我的混淆矩阵只返回一个数字?
【发布时间】:2021-11-19 05:00:21
【问题描述】:

我正在做一个二元分类。每当我的预测等于基本事实时,我都会找到 sklearn.metrics.confusion_matrix 返回一个值。没有问题吗?

from sklearn.metrics import confusion_matrix
print(confusion_matrix([True, True], [True, True])
# [[2]]

我希望是这样的:

[[2 0]
 [0 0]]

【问题讨论】:

    标签: python scikit-learn confusion-matrix


    【解决方案1】:

    请填写labels=[True, False]:

    from sklearn.metrics import confusion_matrix
    
    cm = confusion_matrix(y_true=[True, True], y_pred=[True, True], labels=[True, False])
    print(cm)
    
    # [[2 0]
    #  [0 0]]
    

    为什么?

    docsconfusion_matrix(y_true, y_pred) 的输出是:

    C: ndarray of shape (n_classes, n_classes)

    变量n_classes 是:

    • 猜测为y_truey_pred中唯一值的数量
    • 取自可选参数的长度labels

    在你的情况下,因为你没有填写labels,所以变量n_classes是从[True, True]中唯一值的数量中猜测出来的,即1。因此是结果。

    【讨论】:

      【解决方案2】:

      您收到 1 个号码是因为您没有指定标签。我认为这段代码将帮助您获得 true_positives、truenegative、precesion、recall、f1-score 等

      代码

      from sklearn import metrics
      
      A     = [True, True]
      B     = [True, True]
      label = [True, False] 
      
      
      # True positives and False Negatives
      cm = metrics.confusion_matrix(y_true=A, y_pred=B, labels=label)
      print(cm)
      
      # Report (f1-score, precesion, recall, support)
      report = metrics.classification_report([True, False], [False, True], digits=3,output_dict=True)
      df = pd.DataFrame(report).transpose()
      df
      

      结果

      [[2 0]
       [0 0]]
      

      【讨论】:

      • 这是我之前发布的答案的明显副本,我显然也得到了反对。尽可能不公平?
      • 耶!我接受了您的回答并对其进行了修改以获取更多信息
      • 但是您添加的不是问题所要求的。
      猜你喜欢
      • 1970-01-01
      • 2019-11-14
      • 2020-05-21
      • 1970-01-01
      • 2020-05-03
      • 2018-11-20
      • 1970-01-01
      • 2023-04-05
      • 2019-09-28
      相关资源
      最近更新 更多