我有兴趣预测一位医生是否会开一种特定的药物,并选择Logistic回归作为起点。
我有几个问题:
发布于 2019-07-15 15:13:51
我不会从(手动)特性选择开始。使用Lasso代替“自动”收缩/选择功能(这基本上是Logit与收缩功能)。洛吉特 (或在这里使用Lasso )适用于二进制情况,但您也可以执行“多项Logit”(sklearn中的选项multi_class='multinomial'
),它适用于两个以上的类。通常,您在Python中使用sklearn
来处理这些事情。还请参阅sklearn
文档中的示例。
确保你有一套测试和训练。还请确保您没有使用来自测试集的数据进行培训。仅在培训集上进行培训,并使用测试集查看您的模型如何处理培训期间未见的数据。
当你说“转移到生产”时,你的意思还不清楚。这取决于你的问题。您只需在这里进行预测,但实现当然取决于环境。
玩弄数据是没问题的。但是,如果您真的想从事严肃的数据科学,那么您应该看看所有这些魔术背后的方法。我推荐"统计学习导论“。这是一本非常好的书,包含了许多代码示例,而且并不是非常技术性的。
请注意,没有银弹。套索或Logit也许可以,但其他方法可能更好。这实际上取决于问题/数据。
以下是Lasso的一个小示例代码:
# Split test/train
from sklearn.model_selection import train_test_split
xtrain, xtest, ytrain, ytest = train_test_split(X, y, test_size=0.20, random_state=7)
from sklearn.metrics import roc_auc_score
from sklearn.metrics import confusion_matrix
from sklearn.linear_model import Lasso
from sklearn.linear_model import LassoCV
# Perform lasso CV to get the best parameter alpha for regulation
lasso = Lasso(max_iter=10000)
lassocv = LassoCV(alphas=None, cv=10, max_iter=10000)
lassocv.fit(xtrain, ytrain.values.ravel())
# Fit lasso using the best alpha
lasso.set_params(alpha=lassocv.alpha_)
lasso.fit(xtrain, ytrain)
# Look at results (coefficients)
la1 = pd.Series(abs(lasso.coef_), name="lasso")
la2 = pd.Series(X.columns, name="names")
dflasso = pd.concat([la2,la1], axis=1)
dflasso = dflasso.sort_values(by=['lasso'], ascending=False)
print(dflasso)
# Look at AUC
print("AUC Lasso: %.3f" %roc_auc_score(ytest.values, lasso.predict(xtest)))
# Predict probs
lasspreds0 = lasso.predict(xtest)
# Classes
lasspreds = np.round(lasspreds0)
# Confusion matrix
tnlog, fplog, fnlog, tplog = confusion_matrix(ytest, lasspreds).ravel() #y_true, y_pred
print("True negative: %s, False positive: %s, False negative: %s, True positive %s" %(tnlog, fplog, fnlog, tplog))
print("Share false %.2f" %(((fplog+fnlog)/(fplog+fnlog+tplog+tnlog))))
# Look at probs
print("Min. prob. of belonging to class 0: %.3f" %lasspreds0.min())
print("Max. prob. of belonging to class 0: %.3f" %lasspreds0.max())
请注意,如上所述的学习套索不做逻辑回归,这意味着预测可以是较小的零或更大的一个。要在Logit中使用Lasso (确保预测为0或1),可以使用LogisticRegression
:
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
log = LogisticRegression(penalty='l1', solver='liblinear')
log.fit(X, y)
发布于 2019-07-16 14:17:58
要添加@Peter的答案,可以使用方法:classifier.predict_proba(X_test)
来获得属于每个类的X_test
的概率。
这被称为软预测,很可能需要一些叫做概率校准的东西来获得可用的概率。硬预测是classifier.predict()
方法所做的。它以最高的概率接收类并将其标签分配给您的X_test
。
PS :如果你坚持Logistic回归,你将不需要概率校准,因为LR会自动优化逻辑损失概率。但是,如果您选择了另一个分类器,则需要对其进行校准。
https://datascience.stackexchange.com/questions/55699
复制相似问题