【问题标题】:F1-score per class for multi-class classificationF1-score per class for multi-class classification
【发布时间】:2016-10-03 14:08:02
【问题描述】:

我正在使用 python 和 scikit-learn 解决多类分类问题。目前,我正在使用classification_report 函数来评估我的分类器的性能,获得如下报告:

>>> print(classification_report(y_true, y_pred, target_names=target_names))
             precision    recall  f1-score   support

    class 0       0.50      1.00      0.67         1
    class 1       0.00      0.00      0.00         1
    class 2       1.00      0.67      0.80         3

avg / total       0.70      0.60      0.61         5

为了做进一步的分析,我对获得每个可用类的每类 f1 分数很感兴趣。也许是这样的:

>>> print(calculate_f1_score(y_true, y_pred, target_class='class 0'))
0.67

scikit-learn 上有类似的东西吗?

【问题讨论】:

    标签: python machine-learning scikit-learn


    【解决方案1】:

    我会使用 f1_scorelabels 参数

    from sklearn.metrics import f1_score
    y_true = [0, 1, 2, 0, 1, 2]
    y_pred = [0, 2, 1, 0, 0, 1]
    labels = [0, 1, 2]
    
    f1_scores = f1_score(y_true, y_pred, average=None, labels=labels)
    f1_scores_with_labels = {label:score for label,score in zip(labels, f1_scores)}
    

    输出:

    {0: 0.8, 1: 0.0, 2: 0.0}
    

    【讨论】:

      【解决方案2】:

      您只需要使用 pos_label 作为参数并分配您要打印的类值。

      f1_score(ytest, ypred_prob, pos_label=0)# default is pos_label=1
      

      【讨论】:

        【解决方案3】:

        如果你只有混淆矩阵C,行对应预测,列对应真实,你可以使用以下函数计算F1分数:

        def f1(C):
            num_classes = np.shape(C)[0]
            f1_score = np.zeros(shape=(num_classes,), dtype='float32')
            weights = np.sum(C, axis=0)/np.sum(C)
        
            for j in range(num_classes):
                tp = np.sum(C[j, j])
                fp = np.sum(C[j, np.concatenate((np.arange(0, j), np.arange(j+1, num_classes)))])
                fn = np.sum(C[np.concatenate((np.arange(0, j), np.arange(j+1, num_classes))), j])
        #         tn = np.sum(C[np.concatenate((np.arange(0, j), np.arange(j+1, num_classes))), np.concatenate((np.arange(0, j), np.arange(j+1, num_classes)))])
        
                precision = tp/(tp+fp) if (tp+fp) > 0 else 0
                recall = tp/(tp+fn) if (tp+fn) > 0 else 0
                f1_score[j] = 2*precision*recall/(precision + recall)*weights[j] if (precision + recall) > 0 else 0
        
            f1_score = np.sum(f1_score)
            return f1_score
        

        【讨论】:

          【解决方案4】:

          取自f1_scoredocs

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

          输出:

          array([ 0.8,  0. ,  0. ])
          

          每门课的分数是多少。

          【讨论】:

          • 有没有办法得到哪个F1分数对应哪个Label的映射?
          猜你喜欢
          • 1970-01-01
          • 2014-05-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-05
          • 1970-01-01
          相关资源
          最近更新 更多