[英]Simulating homogeneity of variance in linear regression
我想形象化一些關於回歸理論的假設。 起點是這個總體和線性回歸:
set.seed(1234)
runifdisc <- function(n, min = 0, max = 1) sample(min:max, n, replace = T)
x1 <- runifdisc(100000, 1, 10)
e <- runifdisc(100000, 0, 20)
y <- 4 + 2 * x1 + e
dat_pop <- data.frame(x1, e, y)
m_pop <- lm(y ~ x1, data = dat_pop)
由於 x1 有 10 個值,因此 m_pop 對給定 x 的 y 產生 10 種不同的預測。
> table(round(predict(m_pop)))
16 18 20 22 24 26 28 30 32 34
10096 10081 9864 10078 9927 9914 9915 10124 10018 9983
如果我沒記錯的話,在大量樣本中,給定 x1 的 y 的預測對於 x1 的每個特定值應該具有相同的方差。 也可以應用於殘差的假設。 但是,在我的代碼中,方差隨給定 x1 的不同 y 值而變化:
n <- 1000
vec_y1 <- rep(0, n)
vec_y2 <- rep(0, n)
vec_y3 <- rep(0, n)
vec_y4 <- rep(0, n)
vec_y5 <- rep(0, n)
vec_y6 <- rep(0, n)
vec_y7 <- rep(0, n)
vec_y8 <- rep(0, n)
vec_y9 <- rep(0, n)
vec_y10 <- rep(0, n)
#Draw 1000 samples from dat_pop; in each sample, save the prediction of y given x1
#in vectors vec_y1-vec_y10.
for (i in 1:n){
s <- dat_pop[sample(nrow(dat_pop), 1000), ]
m <- lm(y ~ x1, data = s)
#Prediction for y given x1 == 1
vec_y1[i] <- m$coefficients[1] + 1 * m$coefficients[2]
#Prediction for y given x1 == 2
vec_y2[i] <- m$coefficients[1] + 2 * m$coefficients[2]
#Prediction for y given x1 == 3
vec_y3[i] <- m$coefficients[1] + 3 * m$coefficients[2]
#Prediction for y given x1 == ...
vec_y4[i] <- m$coefficients[1] + 4 * m$coefficients[2]
vec_y5[i] <- m$coefficients[1] + 5 * m$coefficients[2]
vec_y6[i] <- m$coefficients[1] + 6 * m$coefficients[2]
vec_y7[i] <- m$coefficients[1] + 7 * m$coefficients[2]
vec_y8[i] <- m$coefficients[1] + 8 * m$coefficients[2]
vec_y9[i] <- m$coefficients[1] + 9 * m$coefficients[2]
vec_y10[i] <- m$coefficients[1] + 10 * m$coefficients[2]
}
#Variance of different predictions for y given x1 in the samples above.
#This variance should be equal for all vectors vec_y1-vec_y10.
var(vec_y1)
var(vec_y3)
var(vec_y5)
var(vec_y8)
var(vec_y10)
x1 的下限值和上限值的方差較大。
> var(vec_y1)
[1] 0.1234933
> var(vec_y3)
[1] 0.06295427
> var(vec_y5)
[1] 0.03637214
> var(vec_y8)
[1] 0.06016804
> var(vec_y10)
[1] 0.118478
一方面,我的問題解決了我對回歸理論假設的理解。 或許我這邊有誤會。 另一方面,問題在於對於給定 x1 的所有 y 產生相同方差的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.