簡體   English   中英

模擬線性回歸中方差的同質性

[英]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 產生相同方差的代碼。

我認為這將有助於解決它。 我花了一段時間才看到它...

方差在 5 處最小,因為它是 model 的平均值(x1 值從 0 到 10)如果將 model 更改為例如。 1:20,那么 10 的方差最小。

您在 for 循環中訓練 model x 次。 每次預測的斜率都會發生一些變化,但大多數發生在末端(1 和 10)。 這就是它背后的原因。 回歸將始終通過中心 go。

下面是兩個測試樣本(循環中的兩次迭代)。

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM