[英]sklearn check_estimator error for a custom estimator WLS from statsmodels
[英]Logit estimator in `statsmodels` and `sklearn`
我很確定它是一個功能,而不是一個bug,但我想知道是否有辦法讓sklearn
和statsmodels
在logit估計中匹配。 一個非常簡單的例子:
import numpy as np
import statsmodels.formula.api as sm
from sklearn.linear_model import LogisticRegression
np.random.seed(123)
n = 100
y = np.random.random_integers(0, 1, n)
x = np.random.random((n, 2))
# Constant term
x[:, 0] = 1.
statsmodels
的估計值:
sm_lgt = sm.Logit(y, x).fit()
Optimization terminated successfully.
Current function value: 0.675320
Iterations 4
print sm_lgt.params
[ 0.38442 -1.1429183]
和sklearn
的估計:
sk_lgt = LogisticRegression(fit_intercept=False).fit(x, y)
print sk_lgt.coef_
[[ 0.16546794 -0.72637982]]
我認為這與sklearn
的實現sklearn
,它使用某種正則化。 有沒有選擇來估計一個statsmodels
logit,就像在statsmodels
(它的速度更快,擴展性更好)。 另外, sklearn
提供推理(標准錯誤)或邊際效應?
是否可以選擇在
statsmodels
估計准系統logit
您可以將C
(反正則化強度)參數設置為任意高的常數,只要它是有限的:
>>> sk_lgt = LogisticRegression(fit_intercept=False, C=1e9).fit(x, y)
>>> print(sk_lgt.coef_)
[[ 0.38440594 -1.14287175]]
關閉正則化是不可能的,因為底層求解器Liblinear不支持這一點。
另外,
sklearn
提供推理(標准錯誤)或邊際效應?
沒有。有一個建議添加這個,但它還沒有在主代碼庫中。
另外需要注意的是,當我的矩陣共線時,我正在努力克服結果的差異。 顯然這意味着應該有一些額外的預處理來獲得可靠的結果,但我仍然希望找出為什么我得到sklearn的結果但是statsmodels出錯了。
簡短回答:在statsmodels中調用fit
時設置solver='bfgs'
會給sklearn模型提供幾乎相同的結果,即使在共線變量的情況下(一旦注意到sm的默認值沒有攔截這一事實,默認為sklearn適合攔截)
示例(改編自OLS上的類似問題 ):
import numpy as np
import statsmodels.api as sm
from sklearn.linear_model import LogisticRegression
np.random.seed = 237
num_samples=1000
X=np.random.random((num_samples, 2))
X[:, 1] = 2*X[:, 0]
X_sm = sm.add_constant(X)
beta = [1, -2, .5]
error = np.random.random(num_samples)
y = np.round(1/(1+np.exp( -(np.dot(X_sm, beta)) + error ))) # y = 1/(1+exp(-beta*x))
lr = LogisticRegression(C=1e9).fit(X, y)
print "sklearn:"
print lr.intercept_
print lr.coef_
print "statsmodels:"
print sm.Logit(y, X_sm).fit(method='bfgs').params # method='nm' or default method errors out
(PS如果有人對這兩個求解器背后的數學和結果的可靠性有任何意見,我很樂意聽到它!我覺得有趣的是,sklearn甚至沒有對此發出警告......)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.