Python statsmodels OLS和R的lm的区别 [英] Difference in Python statsmodels OLS and R's lm

查看:418
本文介绍了Python statsmodels OLS和R的lm的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我是否通过统计模型.

I'm not sure why I'm getting slightly different results for a simple OLS, depending on whether I go through panda's experimental rpy interface to do the regression in R or whether I use statsmodels in 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中,我得到以下摘要:

From R, I get the following summary:

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的输出,但不相同:

The results are similar to R's output but not the same:

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笔记本

The install process is a a bit cumbersome. But, there is an ipython notebook here, that can reproduce the inconsistency.

推荐答案

在默认情况下,Python不会在表达式中添加截距,而R在使用公式接口时会添加截距..

Looks like Python does not add an intercept by default to your expression, whereas R does when you use the formula interface..

这意味着您确实适合两个不同的模型.试试

This means you did fit two different models. Try

lm( y ~ x - 1, data)

在R中以排除截距,或者在您的情况下使用标准符号来表示

in R to exclude the intercept, or in your case and with somewhat more standard notation

lm(num_rx ~ ridageyr - 1, data=demoq)

这篇关于Python statsmodels OLS和R的lm的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆