如何使用scipy计算线性回归的斜率误差?



要计算线性回归的斜率误差(使用 scipy(,我想使用

slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
sd_slope = (len(x)*std_err**2)/(len(x)*(x**2).sum()-x.sum()**2)

.该方程取自维基百科。为什么这如此错误?

您最后尝试计算的是估计斜率的方差,即斜率标准误差的平方。事实证明,.linregress返回的std_err已经是斜率的std误差。

但是,如果您仍然想手动计算它,则需要将方程中的std_err替换为s(残差标准差的估计值(,该估计值sqrt(SSE / (n-2))n == len(x),样本量。因此,在代码中:

# Get the predicted values
yhat = intercept + slope * x
# Get SSE i.e. sum of squared errors (or RSS: residual sum of squares)
SSE = np.sum((y - yhat)**2)
# Calculate the "s" the estimate of standard deviation of residuals
s = np.sqrt(SSE / (n-2))
# Now your equation (it will give variance)
your_eq = (n*s**2) / (n*(x**2).sum() - x.sum()**2)
# Square root of the above value gives the std error
sd_slope = np.sqrt(your_eq)
# You can see that it is equal to (within precision) std_err of scipy
assert np.isclose(sd_slope, std_err)

最新更新