【问题标题】:SciKit learn predict_proba - move threshold from .5 to something elseSciKit 学习 predict_proba - 将阈值从 .5 移动到其他值
【发布时间】:2019-10-10 12:15:27
【问题描述】:

我是熊猫和 scikit 的新手。我已经能够组装一个简单的模型 - Bad & Good

df = pd.read_csv('pandas_model.csv', header=None, names=['label', 'resume'])
X = df.resume.astype('U').values
y = df.label

X_train, X_test, y_train, y_test = train_test_split(X,y, random_state=1)

vect = TfidfVectorizer()

vect.fit(X_train)
X_train_dtm = vect.transform(X_train)

## create test
X_test_dtm = vect.transform(X_test)

logreg = LogisticRegression()
logreg.fit(X_train_dtm, y_train)

y_pred_class = logreg.predict(X_test_dtm)
score = metrics.accuracy_score(y_test, y_pred_class)
# print('LogReg Accuracy Score: ' % str(score))
print(score)
log_reg_cf = metrics.confusion_matrix(y_test, y_pred_class)
print(log_reg_cf)

混淆矩阵:

[[2696  165]
 [ 742  424]]

当数据点本应为“是”时,它似乎将太多数据点猜测为“否”(742)。

我读到 SciKit learn 使用.5 作为阈值来根据predict_proba() 分数做出决定。

我正在尝试组合方式来“测试”各种阈值 - 即,而不是 .5,而是 .4,这会将一些猜测的数据点从 False Negative 移动到被正确猜测为 Good

logreg.predict_proba(X_test_dtm)

给我一​​个分数的二维数组(坏/好)

array([[0.59946085, 0.40053915], ## guessed as bad, but if the threshold was .6, it would be guessed as good. This is what I'm trying to run simulations on
       [0.89679281, 0.10320719],
       [0.328435  , 0.671565  ],
       ...,
       [0.50415322, 0.49584678],
       [0.84380259, 0.15619741],
       [0.85216752, 0.14783248]])

y_test.head() 给了我真正的价值(顺便说一句,5369 代表什么?行号?)

5369      Bad
11313     Bad
11899    Good
3856      Bad
1961      Bad

理想情况下,我正在尝试运行模拟以对所有 X_train_dtm 数据做某事:

if X_train_dtm[0] (bad score) > .6 (instead of .5):
    then 
        resut = bad
    else
        result = good

然后根据y_test()重新检查并重新检查准确性分数

似乎无论如何都无法移动 SciKit 学习中的 .5 阈值,并且看起来我必须手动进行。

基本上是试图让数据点“更难”被猜测为否

希望我对这个问题的措辞是有意义的

我收到标记为重复的问题的错误

from sklearn.metrics import precision_recall_curve
probs_y=logreg.predict_proba(X_test_dtm)
precision, recall, thresholds = precision_recall_curve(y_test, probs_y[:, 0])

ValueError: Data is not binary and pos_label is not specified

【问题讨论】:

标签: python scikit-learn


【解决方案1】:

IIUC 你可以用predict_proba 简单地做到这一点(至少对于二进制代码):

probabilities = logreg.predict_proba(X_test_dtm)

threshold = 0.4
good = probabilities[:, 1]
predicted_good = good > threshold

如果概率高于0.5,这将为您提供good 情况的二元预测。

您可以轻松地概括上面的代码,以使用您喜欢的任何需要二进制预测的指标来测试您喜欢的任何阈值。

【讨论】:

    猜你喜欢
    • 2018-01-10
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 2017-09-27
    • 2012-08-27
    • 1970-01-01
    • 2016-02-10
    • 2014-04-23
    相关资源
    最近更新 更多