簡體   English   中英

計算特定閾值的精度和召回率

[英]Calculating the precision and recall for a specific threshold

我創建了一個表現不佳的邏輯回歸 model。 但是,我仍然根據最高准確度得分計算出最佳閾值。 現在,我想使用 0.04 的閾值來計算精度和召回率。 不幸的是,我找不到任何關於如何確定這些值的示例。 如果您知道我需要使用的 function,您能幫忙嗎?

為了做你想做的事,我首先用我的 model 預測我的概率,然后我使用我想要的閾值將我的概率數組轉換為真/假 (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)

您可以使用 sci-kit 中的precision_scorerecall_score來計算精度和召回率。 您指定的閾值不是這些函數的先決條件參數。 下面我還包括了accuracy_score和confusion_matrix,因為通常這些go一起用於評估分類器的結果。

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")

示例 output:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM