我不确定为什么我的简单OLS结果略有不同,具体取决于我是否通过panda's experimental rpy interface进行回归R
或是否使用{{3}在Python中。
import pandas
from rpy2.robjects import r
from functools import partial
loadcsv = partial(pandas.DataFrame.from_csv,
index_col="seqn", parse_dates=False)
demoq = loadcsv("csv/DEMO.csv")
rxq = loadcsv("csv/quest/RXQ_RX.csv")
num_rx = {}
for seqn, num in rxq.rxd295.iteritems():
try:
val = int(num)
except ValueError:
val = 0
num_rx[seqn] = val
series = pandas.Series(num_rx, name="num_rx")
demoq = demoq.join(series)
import pandas.rpy.common as com
df = com.convert_to_r_dataframe(demoq)
r.assign("demoq", df)
r('lmout <- lm(demoq$num_rx ~ demoq$ridageyr)') # run the regression
r('print(summary(lmout))') # print from R
从R
,我得到以下摘要:
Call:
lm(formula = demoq$num_rx ~ demoq$ridageyr)
Residuals:
Min 1Q Median 3Q Max
-2.9086 -0.6908 -0.2940 0.1358 15.7003
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.1358216 0.0241399 -5.626 1.89e-08 ***
demoq$ridageyr 0.0358161 0.0006232 57.469 < 2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 1.545 on 9963 degrees of freedom
Multiple R-squared: 0.249, Adjusted R-squared: 0.2489
F-statistic: 3303 on 1 and 9963 DF, p-value: < 2.2e-16
使用statsmodels.api
执行OLS:
import statsmodels.api as sm
results = sm.OLS(demoq.num_rx, demoq.ridageyr).fit()
results.summary()
结果类似于R的输出但不相同:
OLS Regression Results
Adj. R-squared: 0.247
Log-Likelihood: -18488.
No. Observations: 9965 AIC: 3.698e+04
Df Residuals: 9964 BIC: 3.698e+04
coef std err t P>|t| [95.0% Conf. Int.]
ridageyr 0.0331 0.000 82.787 0.000 0.032 0.034
安装过程有点麻烦。但是,有一个 ipython notebook statsmodels,它可以重现不一致。
答案 0 :(得分:16)
看起来Python默认情况下不会为您的表达式添加拦截,而R会在您使用公式界面时执行..
这意味着您确实适合了两种不同的型号。尝试
lm( y ~ x - 1, data)
在R中排除拦截,或者在你的情况下,用更标准的符号
lm(num_rx ~ ridageyr - 1, data=demoq)
答案 1 :(得分:6)
请注意,您仍然可以使用ols
中的statsmodels.formula.api
:
from statsmodels.formula.api import ols
results = ols('num_rx ~ ridageyr', demoq).fit()
results.summary()
我认为它在后端使用patsy
来翻译公式表达式,并自动添加拦截。