【问题标题】:Build confusion matrix from two vector从两个向量构建混淆矩阵
【发布时间】:2018-10-05 21:50:41
【问题描述】:

我需要定义一个生成混淆矩阵的函数。所以我有两个向量,y_labely_predict,它们的元素值为 0、1、2。该函数的目标是创建标签计数:

  | 0 | 1 | 2 |
--------------
0 |   |   |   |
--------------
1 |   |   |   |
--------------
2 |   |   |   |
--------------

例如,cm[0,1] 应包含每个 i 的 y_label[i] = 0 和 y_predict[i] = 1 的元素计数。

到目前为止,这就是我所做的:

def get_confusion_matrix(y_label, y_fit):

    cm = np.ndarray([3,3])

    for i in range(3):
        for j in range(3):
            cm[i, j] = ....

    return cm

当然,我可以轻松地进行多级 for 循环来计数,但如果 Python / numpy 中有捷径,我想避免这种情况。

我也在考虑将y_labely_predict 合并成一个元组数组,然后使用dict-zip 技术,类似于这里:

How to count the occurrence of certain item in an ndarray in Python?

但解决方案在我的脑海中仍然有点模糊。请确认这是否也可以。

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    您可以使用scikit learn 中的函数confusion_matrix。它似乎会产生你所追求的东西。

    from sklearn.metrics import confusion_matrix
    y_true = [2, 0, 2, 2, 0, 1]
    y_pred = [0, 0, 2, 2, 0, 2]
    confusion_matrix(y_true, y_pred)
    

    【讨论】:

      【解决方案2】:

      这是创建混淆矩阵的快速方法,使用numpy.add.at

      首先,这里有一些示例数据:

      In [93]: y_label
      Out[93]: array([2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0])
      
      In [94]: y_predict
      Out[94]: array([2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2])
      

      创建包含零的数组cm,然后在每个索引处加1 (y_label[i], y_predict[i])

      In [95]: cm = np.zeros((3, 3), dtype=int)
      
      In [96]: np.add.at(cm, (y_label, y_predict), 1)
      
      In [97]: cm
      Out[97]: 
      array([[4, 1, 2],
             [3, 0, 2],
             [1, 2, 1]])
      

      【讨论】:

        【解决方案3】:

        Scikit-learn 有一个confusion_matrix 函数:

        from sklearn.metrics import confusion_matrix
        y_actu = [2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0]
        y_pred = [2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]
        confusion_matrix(y_actu, y_pred)
        

        你会得到一个像这样的 Numpy 数组:

        array([[4, 1, 2],
               [3, 0, 2],
               [1, 2, 1]])
        

        为了获得更好的答案,您可以在 pandas 中使用crosstab 函数:

        import pandas as pd
        y_actu = pd.Series([2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0], name='Actual')
        y_pred = pd.Series([2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2], name='Predicted')
        df_confusion = pd.crosstab(y_actu, y_pred)
        

        像这样输出一个 Pandas DataFrame 对象:

        Predicted  0  1  2
        Actual            
        0          4  1  2
        1          3  0  2
        2          1  2  1
        

        你可以在这个问题下找到最完整的答案: How to write a confusion matrix in Python?

        【讨论】:

          猜你喜欢
          • 2020-08-13
          • 1970-01-01
          • 2021-03-02
          • 1970-01-01
          • 2020-07-09
          • 2017-10-28
          • 1970-01-01
          • 2017-02-19
          • 1970-01-01
          相关资源
          最近更新 更多