【问题标题】:How to get the threshold from a specific precision and recall如何从特定的精度和召回率中获得阈值
【发布时间】:2022-02-03 01:39:51
【问题描述】:

我正在尝试获取特定精度和召回率的阈值。假设我想以 60% 的精度和 40% 的召回率获得阈值。有没有使用 sklearn 包的直接方法?

precision, recall, threshold = precision_recall_curve(y_val, y_e)
df_pr = pd.DataFrame()
df_pr['precision'] = precision
df_pr['recall'] = recall
df_pr['threshold'] = list(threshold) + [1]

    precision   recall  threshold
0   0.247543    1.000000    0.059483
1   0.247486    0.999692    0.059489
2   0.247504    0.999692    0.059512
3   0.247523    0.999692    0.059542

【问题讨论】:

  • 你显示的df_pr 看起来有点奇怪。为什么不是最后一个threshold = 1?
  • Imo 你的精确度和召回率不一定像你暗示的那样耦合。这就是说,您可以确定您获得的索引 - 我会说 - 您的预期精度值或预期召回值,从而获得相应的阈值。

标签: scikit-learn precision threshold


【解决方案1】:

假设我已经正确理解了您的问题,imo,需要强调的一点是精确度和召回率不一定像您暗示的那样耦合。这是一个玩具示例:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_recall_curve

X, y = make_classification(n_samples=1000, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=7)
lr = LogisticRegression(random_state=42)
lr.fit(X_train, y_train)
y_scores = lr.predict_proba(X_test)
precision, recall, threshold = precision_recall_curve(y_test, y_scores[:, 1])

plt.plot(threshold, precision[:-1], 'b--', label='Precision')
plt.plot(threshold, recall[:-1], 'r--', label='Recall')
plt.xlabel('Threshold')
plt.legend(loc='lower left')
plt.ylim([0,1])

这就是说,根据您的“设置”,您可以使用 numpypandas 轻松解决问题。例如,这是一个玩具函数,它返回达到条件的索引处的精度、召回率和阈值。

def prt(arr, value):
    array = np.asarray(arr)
    idx = np.where(array[:-1] == value)[0][0]
    return precision[idx], recall[idx], threshold[idx]

prt(precision, 0.6)   # I checked ex-ante that precision=0.6 is attained. Differently you'll have to go with something custom.
(0.6, 0.9622641509433962, 0.052229434776723364)

否则,使用 pandas DataFrame 类似于您的设置:

df = pd.DataFrame()
df['precision'] = precision[:-1]
df['recall'] = recall[:-1]
df['threshold'] = threshold
df[df.loc[:, 'precision'] == 0.6]

我建议您 sklearn precision_recall_curve and threshold 试图解释 .precision_recall_curve() 是如何在幕后工作的,而 Why does precision_recall_curve() return different values than confusion matrix? 可能有某种关联。

【讨论】:

    猜你喜欢
    • 2020-10-22
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 2021-03-04
    • 2019-09-06
    • 2019-02-12
    相关资源
    最近更新 更多