解决方案
只需将模型创建行更改为
model = LogisticRegression(C=100000, fit_intercept=False)
问题分析
默认情况下,sklearn 解决正则化 LogisticRegression,具有拟合强度C=1
(小 C-大正则化,大 C-小正则化)。
此类使用 liblinear 库、newton-cg 和 lbfgs 求解器实现正则化逻辑回归。它可以处理密集和稀疏输入。使用包含 64 位浮点数的 C 有序数组或 CSR 矩阵以获得最佳性能;任何其他输入格式都将被转换(和复制)。
因此,要获得他们的模型,您应该适合
model = LogisticRegression(C=1000000)
这使
Intercept -2.038853 # this is actually half the intercept
study_hrs 1.504643 # this is correct
此外,问题还在于您在 patsy 中处理数据的方式,请参阅简化的正确示例
import numpy as np
from sklearn.linear_model import LogisticRegression
X = [0.5,0.75,1.0,1.25,1.5,1.75,1.75,2.0,2.25,2.5,2.75,3.0,3.25,
3.5,4.0,4.25,4.5,4.75,5.0,5.5]
y = [0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1]
X = np.array([[x] for x in X])
y = np.ravel(y)
model = LogisticRegression(C=1000000.)
model = model.fit(X,y)
print('coef', model.coef_)
print('intercept', model.intercept_)
给
coef [[ 1.50464059]]
intercept [-4.07769916]
究竟是什么问题?默认情况下,将dmatrices
输入数据嵌入一列(偏差)
X = [0.5,0.75,1.0,1.25,1.5,1.75,1.75,2.0,2.25,2.5,2.75,3.0,3.25,
3.5,4.0,4.25,4.5,4.75,5.0,5.5]
y = [0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1]
zipped = list(zip(X,y))
df = pd.DataFrame(zipped,columns = ['study_hrs','p_or_f'])
y, X = dmatrices('p_or_f ~ study_hrs',
df, return_type="dataframe")
print(X)
这导致
Intercept study_hrs
0 1 0.50
1 1 0.75
2 1 1.00
3 1 1.25
4 1 1.50
5 1 1.75
6 1 1.75
7 1 2.00
8 1 2.25
9 1 2.50
10 1 2.75
11 1 3.00
12 1 3.25
13 1 3.50
14 1 4.00
15 1 4.25
16 1 4.50
17 1 4.75
18 1 5.00
19 1 5.50
这就是为什么产生的偏差只是真正的一半的原因 - scikit 学习还添加了一列...所以你现在有两个偏差,因此最佳解决方案是给每个偏差一半的权重,这将是给一个人。
那你能做什么?
- 不要以这种方式使用 patsy
- 禁止 patsy 添加偏见
- 告诉 sklearn 不要添加偏见
.
import numpy as np
import pandas as pd
from patsy import dmatrices
from sklearn.linear_model import LogisticRegression
X = [0.5,0.75,1.0,1.25,1.5,1.75,1.75,2.0,2.25,2.5,2.75,3.0,3.25,
3.5,4.0,4.25,4.5,4.75,5.0,5.5]
y = [0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1]
zipped = list(zip(X,y))
df = pd.DataFrame(zipped,columns = ['study_hrs','p_or_f'])
y, X = dmatrices('p_or_f ~ study_hrs',
df, return_type="dataframe")
y = np.ravel(y)
model = LogisticRegression(C=100000, fit_intercept=False)
model = model.fit(X,y)
print(pd.DataFrame(np.transpose(model.coef_),X.columns))
给
Intercept -4.077571
study_hrs 1.504597
如预期的