计算线性回归线附近的置信区间

时间:2018-11-10 20:25:31

标签: python r

我正在尝试计算线性回归线附近的置信区间。对于我的研究,我必须知道回归线附近的上下95%置信区间曲线的方程。

我的数据的x和y是... x = [0.18 0.19 0.02 0.27 0.21 0.14 0.30 0.37 0.16 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.03 0.05 0.00]

and y = [115.74 212.91 114.30 182.58 92.71 235.60 160.05 230.11 89.60 31.29 77.27 41.42 121.40 37.42 42.52 45.71 89.13 94.68 94.51 91.64 44.39 125.87 67.09]

首先,我使用以下代码创建了95%的置信度曲线:

model1 <- lm(y ~ x, data=SSY)
newx <- seq(0.0000, 0.45000, by=0.01)
conf_interval <- predict(model1, newdata=data.frame(x=newx), interval="confidence",
                     level = 0.95)

我有一张漂亮的图,显示了95%的置信度曲线和回归线,但没有显示曲线的方程式。

因此,接下来,我尝试使用此公式手动计算置信区间: enter image description here

其中(s.e.)定义为回归线的标准误差乘以xk处的估计值的标准误差: enter image description here

# Extract fitted coefficients from model object
b0 <- model1$coefficients[1]
b1 <- model1$coefficients[2]
y <- SSY$y
x <- SSY$x

#Critical t-value
t.val <- qt(0.975, 21)


# Fit a new linear model that extends past the given data points (for plotting)
x_new <- seq(0.0000, 0.45000, by=0.01)
y.fit <- b1 * x_new + b0

se <- sqrt(sum((y - y.fit)^2) / (21)) * sqrt(1 / 21 + (x_new - mean(x))^2 / sum((x_new - mean(x))^2))

# Warnings of mismatched lengths are suppressed
slope.upper <- suppressWarnings(y.fit + t.val * se)
slope.lower <- suppressWarnings(y.fit - t.val * se)

但是,predict()函数和手动计算的结果不同:

  1. Predict()函数:
  

fit:73.5833 77.46624 81.34918 ... 248.31552

     

lwr:50.97287 55.75834 60.46065 ... 187.02017

     

upr:96.19373 99.17413 102.2377 ... 309.61086

  1. 手动计算:
  

fit:73.5833 77.46624 81.34918 ... 248.31552

     

lwr:0.61771 5.14366 9.59238 ... 134.71490

     

upr:146.5489 149.7888 153.1060 ... 361.9161

有人知道怎么了吗?

谢谢!

0 个答案:

没有答案
相关问题