在Scikit Learn中控制Logistic回归中的阈值

Lon*_*guy 15 classification machine-learning scikit-learn logistic-regression

LogisticRegression()scikit-learn高度不平衡的数据集中使用该 方法.我甚至把这个class_weight功能变成了auto.

我知道在Logistic回归中,应该可以知道特定一对类的阈值是多少.

是否有可能知道该LogisticRegression()方法设计的每个一对一类的阈值是多少?

我没有在文档页面中找到任何内容.

它是否默认将0.5值作为所有类的阈值应用,而不管参数值如何?

Nik*_*sev 13

逻辑回归选择具有最大概率的类.在2类的情况下,阈值为0.5:如果P(Y = 0)> 0.5,则显然P(Y = 0)> P(Y = 1).同样代表多类设置:同样,它选择概率最大的类(参见例如Ng的讲座,底线).

引入特殊阈值仅影响误报/漏报的比例(因此在精确/召回权衡中),但它不是LR模型的参数.另见类似问题.


小智 8

我使用了一个小技巧,而不是model.predict(test_data)使用model.predict_proba(test_data).然后使用一系列阈值来分析对预测的影响;

pred_proba_df = pd.DataFrame(model.predict_proba(x_test))
threshold_list = [0.05,0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.55,0.6,0.65,.7,.75,.8,.85,.9,.95,.99]
for i in threshold_list:
    print ('\n******** For i = {} ******'.format(i))
    Y_test_pred = pred_proba_df.applymap(lambda x: 1 if x>i else 0)
    test_accuracy = metrics.accuracy_score(Y_test.as_matrix().reshape(Y_test.as_matrix().size,1),
                                           Y_test_pred.iloc[:,1].as_matrix().reshape(Y_test_pred.iloc[:,1].as_matrix().size,1))
    print('Our testing accuracy is {}'.format(test_accuracy))

    print(confusion_matrix(Y_test.as_matrix().reshape(Y_test.as_matrix().size,1),
                           Y_test_pred.iloc[:,1].as_matrix().reshape(Y_test_pred.iloc[:,1].as_matrix().size,1)))
Run Code Online (Sandbox Code Playgroud)

最好!

  • 我喜欢这个答案。我很难理解的是如何将其与 GridSearchCV 联系起来?当我运行 GridSearchCV 时,我在众多模型中找到了最好的模型。据推测,逻辑回归的默认阈值 0.5 正在内部使用,那么当进行评分以选择最佳模型时,我将如何覆盖此默认阈值。 (2认同)

sri*_*avi 7

是的,Sci-Kit学习对二进制分类使用的阈值P> 0.5。我将在已经发布的一些答案的基础上,用两个选项进行检查:

一个简单的选择是使用下面代码的model.predict_proba(test_x)段的输出以及类预测(下面代码的model.predict(test_x)段的输出)提取每种分类的概率。然后,将类别预测及其概率附加到您的测试数据框中以作为检查。

作为另一种选择,可以使用以下代码以图形方式查看各种阈值下的精度与召回率。

### Predict test_y values and probabilities based on fitted logistic 
regression model

pred_y=log.predict(test_x) 

probs_y=log.predict_proba(test_x) 
  # probs_y is a 2-D array of probability of being labeled as 0 (first 
  column of 
  array) vs 1 (2nd column in array)

from sklearn.metrics import precision_recall_curve
precision, recall, thresholds = precision_recall_curve(test_y, probs_y[:, 
1]) 
   #retrieve probability of being 1(in second column of probs_y)
pr_auc = metrics.auc(recall, precision)

plt.title("Precision-Recall vs Threshold Chart")
plt.plot(thresholds, precision[: -1], "b--", label="Precision")
plt.plot(thresholds, recall[: -1], "r--", label="Recall")
plt.ylabel("Precision, Recall")
plt.xlabel("Threshold")
plt.legend(loc="lower left")
plt.ylim([0,1])
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用“sklearn.metrics.plot_ precision_recall_curve”节省一些编码。 (2认同)
  • 函数plot_ precision_recall_curve 在 1.0 中已弃用,并将在 1.2 中删除。 (2认同)

Nab*_*rsi 5

我们可以使用包装器,如下所示:

model = LogisticRegression()
model.fit(X, y)

def custom_predict(X, threshold):
    probs = model.predict_proba(X) 
    return (probs[:, 1] > threshold).astype(int)
    
    
new_preds = custom_predict(X=X, threshold=0.4) 
Run Code Online (Sandbox Code Playgroud)