Python 如何在Logistic回归中使用计算出的阈值?

Python 如何在Logistic回归中使用计算出的阈值?,python,logistic-regression,Python,Logistic Regression,我使用Python中的以下代码将最佳阈值计算为0.61以获得最高精度: # probability y_pred_prob = tv_lr.predict_proba(tv_x_test_vector) # fpr, tpr, threshold fpr, tpr, threshold = roc_curve(y_test, y_pred_prob[:,1]) # accuracy score for threshold accuracy_ls = [] for thresh in th

我使用Python中的以下代码将最佳阈值计算为0.61以获得最高精度:

# probability
y_pred_prob = tv_lr.predict_proba(tv_x_test_vector)  

# fpr, tpr, threshold
fpr, tpr, threshold = roc_curve(y_test, y_pred_prob[:,1])

# accuracy score for threshold
accuracy_ls = []
for thresh in threshold:
    y_pred = np.where(y_pred_prob[:,1]>thresh, 1, 0)
    accuracy_ls.append(accuracy_score(y_test, y_pred))

# Dataframe
acc_thr_df = pd.concat([pd.Series(threshold), pd.Series(accuracy_ls)], axis=1, )
acc_thr_df.columns = ['thresh', 'acc']
acc_thr_df.sort_values(by='acc', ascending=False) # Chose the 1st value
当我使用
tv\u lr.predict(tv\u x\u test\u vector)
时,它使用0.5作为阈值

请告知如何将阈值更改为0.61?此处显示的代码是否正确,而不是使用
tv\u lr.predict(tv\u x\u test\u vector)


LogisticRegression
估计器的
predict
方法不允许您将阈值作为参数传递,只允许您使用0.5作为阈值。所以,正如您所说,您必须自己将概率转换为自定义阈值的硬预测

您的代码似乎是正确的

y_pred = np.where(y_pred_prob[:,1]>0.61, 1, 0)