【问题标题】:getting the standard error of linear regression coefficient using bootstrap使用 bootstrap 获得线性回归系数的标准误差
【发布时间】:2018-09-06 12:11:06
【问题描述】:

我想使用自举技术(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

input.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

【问题讨论】:

  • 您从哪个库获得stats?请包含您的库导入,以便其他人可以轻松运行您的代码。
  • 我正在删除 matplotlib 标签。这与它无关
  • 当我运行你的代码时(假设 stats 来自 scipy)我得到 std_err 的 0.007415 和 std_err2 的 0.099598?两者都不是零。
  • 我收到了0.007414734102170.105542871364。 scipy版'0.19.1'

标签: python python-2.7 statistics-bootstrap


【解决方案1】:

我对您在 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

正确引导数据

正确的方法是使用sklearn.utils 中的resample 方法。此方法以一致的数组格式处理数据。由于您的数据是 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

【讨论】:

  • 嗯,输入文件中的 x 和 y 数组有 19 个 (x,y) 对。例程代码分别生成 100 x 和 100 个值,而不是 100 x 和 100 y 数组。我认为这是错误的。代码应该为二维数组生成 100 x 和 100 y 数组。如您所见,slope_1 和 slope_2 非常不同。这不正常。
  • @erhan 我已更新答案以正确回答您的问题。
猜你喜欢
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
  • 2018-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多