【问题标题】:Calculating the precision and recall for a specific threshold计算特定阈值的精度和召回率
【发布时间】:2020-10-22 09:39:56
【问题描述】:

我创建了一个表现不佳的逻辑回归模型。但是,我仍然根据最高准确度得分计算出最佳阈值。现在,我想使用 0.04 的阈值来计算精度和召回率。不幸的是,我找不到任何关于如何确定这些值的示例。如果您知道我需要使用的功能,可以帮忙吗?

【问题讨论】:

    标签: python scikit-learn data-science precision precision-recall


    【解决方案1】:

    您可以使用 sci-kit 中的 precision_score 和 recall_score 来计算准确率和召回率。您指定的阈值不是这些函数的先决条件参数。下面我还包括了accuracy_score和confusion_matrix,因为它们通常一起用于评估分类器的结果。

    from sklearn.metrics import accuracy_score
    from sklearn.metrics import confusion_matrix
    from sklearn.metrics import precision_score
    from sklearn.metrics import recall_score
    import pandas as pd
    
    def my_classifier_results(model, x_test, y_test):
        y_true = y_test
        y_pred = model.predict(x_test)    
        accuracy = accuracy_score(y_true, y_pred)
        precision = precision_score(y_true, y_pred, average="weighted")
        sensitivity = recall_score(y_true, y_pred, average="weighted")    
        print(f"Accuracy: {accuracy}, precision: {round(precision,4)}, sensitivity: {round(sensitivity,4)}\n")
        cmtx = pd.DataFrame(
            confusion_matrix(y_true, y_pred, labels=[1,0]), 
            index=['true:bad', 'true:good'], 
            columns=['pred:bad','pred:good']
        )
        print(f"{cmtx}\n")
    

    示例输出:

    【讨论】:

      【解决方案2】:

      为了做你想做的事,我首先用我的模型预测我的概率,然后我使用我想要的阈值将我的概率数组转换为真/假 (0/1) 值数组,然后我计算通过将我的预测值数组与真实值进行比较来获得我想要的指标。

      例如:

      # import precision and recall function from scikit-learn learn
      from sklearn.metrics import precision_score, recall_score
      
      # compute the probabilities
      y_pred_prob = model.predict_proba(features)[:, 1]
      
      # for a threshold of 0.5
      precision0_5 = precision_score(true_labels, y_pred_prob > 0.5)
      recall0_5 = recall_score(true_labels, y_pred_prob > 0.5)
      
      # for a threshold of 0.04 (in your case)
      precision0_04 = precision_score(true_labels, y_pred_prob > 0.04)
      recall0_04 = recall_score(true_labels, y_pred_prob > 0.04)
      

      【讨论】:

        猜你喜欢
        • 2016-04-09
        • 2012-11-26
        • 1970-01-01
        • 2014-11-20
        • 1970-01-01
        • 2016-07-26
        • 2020-02-23
        • 2017-11-13
        • 2019-12-14
        相关资源
        最近更新 更多