使用rpy2获取回归的标准误差

2 投票
2 回答
715 浏览
提问于 2025-04-17 10:16

我正在使用rpy2来进行回归分析。返回的对象里有一个列表,里面包括了系数、残差、拟合值、拟合模型的秩等信息。

不过我找不到标准误差(也没有R^2值)在这个拟合对象里。直接在R中运行lm模型时,使用summary命令可以显示标准误差,但我在模型的数据框里无法直接访问这些信息。

我该如何通过rpy2提取这些信息呢?

下面是一个示例的Python代码:

from scipy import random
from numpy import hstack, array, matrix
from rpy2 import robjects 
from rpy2.robjects.packages import importr

def test_regress():
    stats=importr('stats')
    x=random.uniform(0,1,100).reshape([100,1])
    y=1+x+random.uniform(0,1,100).reshape([100,1])
    x_in_r=create_r_matrix(x, x.shape[1])
    y_in_r=create_r_matrix(y, y.shape[1])
    formula=robjects.Formula('y~x')
    env = formula.environment
    env['x']=x_in_r
    env['y']=y_in_r
    fit=stats.lm(formula)
    coeffs=array(fit[0])
    resids=array(fit[1])
    fitted_vals=array(fit[4])
    return(coeffs, resids, fitted_vals) 

def create_r_matrix(py_array, ncols):
    if type(py_array)==type(matrix([1])) or type(py_array)==type(array([1])):
        py_array=py_array.tolist()
    r_vector=robjects.FloatVector(flatten_list(py_array))
    r_matrix=robjects.r['matrix'](r_vector, ncol=ncols)
    return r_matrix

def flatten_list(source):
    return([item for sublist in source for item in sublist])

test_regress()

2 个回答

1

@joran: 很不错。我觉得这基本上就是正确的做法。

from rpy2 import robjects 
from rpy2.robjects.packages import importr

base = importr('base')
stats = importr('stats') # import only once !

def test_regress():
    x = base.matrix(stats.runif(100), nrow = 100)
    y = (x.ro + base.matrix(stats.runif(100), nrow = 100)).ro + 1 # not so nice
    formula = robjects.Formula('y~x')
    env = formula.environment
    env['x'] = x
    env['y'] = y
    fit = stats.lm(formula)
    coefs = stats.coef(fit)
    resids = stats.residuals(fit)    
    fitted_vals = stats.fitted(fit)
    modsum = base.summary(fit)
    rsquared = modsum.rx2('r.squared')
    se = modsum.rx2('coefficients')[2:4]
    return (coefs, resids, fitted_vals, rsquared, se) 
3

这对我来说似乎有效:

def test_regress():
    stats=importr('stats')
    x=random.uniform(0,1,100).reshape([100,1])
    y=1+x+random.uniform(0,1,100).reshape([100,1])
    x_in_r=create_r_matrix(x, x.shape[1])
    y_in_r=create_r_matrix(y, y.shape[1])
    formula=robjects.Formula('y~x')
    env = formula.environment
    env['x']=x_in_r
    env['y']=y_in_r
    fit=stats.lm(formula)
    coeffs=array(fit[0])
    resids=array(fit[1])
    fitted_vals=array(fit[4])
    modsum = base.summary(fit)
    rsquared = array(modsum[7])
    se = array(modsum.rx2('coefficients')[2:4])
    return(coeffs, resids, fitted_vals, rsquared, se) 

不过,正如我所说的,这实际上是我第一次接触RPy2,所以可能还有更好的方法来实现这个。不过这个版本看起来可以输出包含R平方值和标准误差的数组。

你可以使用 print(modsum.names) 来查看R对象的组成部分的名称(有点像R中的 names(modsum)),然后 .rx.rx2 就相当于R中的 [[[

撰写回答