首页 > 解决方案 > 使用 bootstrap 获得线性回归系数的标准误差

问题描述

我想使用引导技术(100 个重采样)计算线性回归系数的标准误差,但我得到的结果为零,这是不正常的。我认为代码的引导部分有问题。你知道如何修复我的代码吗?

x, y = np.genfromtxt("input.txt", unpack=True) 

#regression part
slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
print std_err

#bootstrap part of the code
A = np.random.choice(x, size=100, replace=True)
B = np.random.choice(y, size=100, replace=True)
slope2, intercept2, r_value2, p_value2, std_err2 = stats.linregress(A,B)
print std_err2

输入.txt:

-1.08   -1.07
-2.62   -2.56
-2.84   -2.79
-2.22   -2.16
-3.47   -3.55
-2.81   -2.79
-2.86   -2.71
-3.41   -3.42
-4.18   -4.21
-3.50   -3.48
-5.67   -5.55
-6.83   -6.95
-6.13   -6.13
-8.34   -8.19
-7.82   -7.83
-9.86   -9.58
-8.67   -8.62
-9.81   -9.81
-8.39   -8.30

标签: pythonpython-2.7statistics-bootstrap

解决方案


我对您在 Python 3.6.1 中运行的上述代码没有任何问题。也许检查你的 scipy 版本是最新的?

from scipy import stats
import numpy as np

x, y = np.genfromtxt("./input.txt", unpack=True)
slope_1, intercept_1, r_val_1, p_val_1, stderr_1 = stats.linregress(x, y)
print(slope_1) # 0.9913080927081567
print(stderr_1) # 0.007414734102169809

A = np.random.choice(x, size=100, replace=True)
B = np.random.choice(y, size=100, replace=True)

slope_2, incercept_2, r_val_2, p_val_2, stderr_2 = stats.linregress(A, B)
print(slope_2) # 0.11429903085322253
print(stderr_2) # 0.10158283281966374

正确引导数据

正确的方法是使用resamplefrom 的方法sklearn.utils。此方法以一致的数组格式处理数据。由于您的数据是 x, y 对,因此 y 值取决于您的 x 值。如果您独立地对 x 和 y 进行随机抽样,您将失去这种依赖性,并且您的重新抽样数据将无法准确地代表您的总体。

from scipy import stats
from sklearn.utils import resample
import numpy as np

x, y = np.genfromtxt("./input.txt", unpack=True)
slope_1, intercept_1, r_val_1, p_val_1, stderr_1 = stats.linregress(x, y)
print(slope_1) # 0.9913080927081567
print(stderr_1) # 0.007414734102169809

A, B = resample(x, y, n_samples=100) # defaults to w/ replacement

slope_2, incercept_2, r_val_2, p_val_2, stderr_2 = stats.linregress(A, B)
print(slope_2) # 0.9864339054638176
print(stderr_2) # 0.002669659193615103

推荐阅读