Lon*_*guy 15 classification machine-learning scikit-learn logistic-regression
我LogisticRegression()在scikit-learn高度不平衡的数据集中使用该 方法.我甚至把这个class_weight功能变成了auto.
我知道在Logistic回归中,应该可以知道特定一对类的阈值是多少.
是否有可能知道该LogisticRegression()方法设计的每个一对一类的阈值是多少?
我没有在文档页面中找到任何内容.
它是否默认将0.5值作为所有类的阈值应用,而不管参数值如何?
小智 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)
最好!
是的,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)
我们可以使用包装器,如下所示:
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)
| 归档时间: |
|
| 查看次数: |
26003 次 |
| 最近记录: |