如何更改加载的逻辑回归模型的决策阈值

How to change decision threshold on a loaded logistic regression model

我正在使用 Python 研究逻辑回归模型,我设法手动调整了阈值。但是,当我使用 pickle 保存模型时,阈值似乎没有改变。对于不同的阈值,我得到完全相同的结果。这是代码:

filename = 'model202104.sav'
pickle.dump(logreg, open(filename, 'wb'))
loaded_model2 = pickle.load(open(filename, 'rb'))
result = loaded_model2.score(X_test, y_pred)
print(result)

这是我用来手动更改阈值的代码:

X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=.2,random_state=7)
logreg = LogisticRegression(max_iter=10000)
logreg.fit(X_train,y_train)
#y_pred=logreg.predict(X_test)
THRESHOLD=0.5
y_pred=np.where(logreg.predict_proba(X_test)[:,1] > THRESHOLD, 1, 0)

提前致谢:)

score 的第二个参数应该是真实的观测值,而不是 y_pred

# Load model
loaded_model2 = pickle.load(open('model202104.sav', 'rb'))

# Score model with `y_test`
result = loaded_model2.score(X_test, y_test) # You had `y_pred` here
print(result)

此外,您始终必须在 sklearn 中手动设置阈值。否则,如果预测概率大于或等于 0.5LogisticRegression 总是分类为 1。因此,要使用自定义阈值对您的模型进行评分:

# Import accuracy score function
from sklearn.metrics import accuracy_score

# Classify with custom threshold (for example, 0.85)
thr = 0.85
y_pred = np.where(loaded_model2.predict_proba(X_test)[:, 1] >= thr, 1, 0)

# Score
print('Accuracy with threshold set to', str(thr) + ':', accuracy_score(y_test, y_pred))