如何解释R中的predict.lm现象

时间:2018-03-13 06:52:41

标签: r

n = 10 #number of points
i = 1:n
x = (i-1)/n 
set.seed(777)
e = rnorm(10, 0, 1)
y = sin(2*pi*x) + e #the true model
curve_x_true = pretty(c(0, 0.9), 100) # a sequence of points used to draw the sin graph
curve_y_true = sin(2*pi*curve_x_true) # a sequence of points used to draw the sin graph
m.x = data.frame(as.matrix(poly(x, 9))) # polynomial matrix
poly.fit = lm(y~., data = m.x) # the fitted model
par(mfrow=c(2,3))

for (p in c(10, 100, 1000)){
  curve_x = pretty(c(0, 0.9), p) # a sequence of points used to draw poly graph
  plot(x, y)
  curve_hat_y = predict(poly.fit, 
                        newdata = data.frame(poly(curve_x, 9)), 
                        type = "response")
  lines(curve_x_true, curve_y_true, col = "red", lwd = 3)
  lines(curve_x, curve_hat_y, col = 'blue', lwd = 2)
}

for (p in 1:3){
  plot(y, 
       predict(poly.fit), 
       xlab = "True Value", 
       ylab = "Fitted Value", lwd = 2)
}

我在代码中所做的是使用sin函数和rnorm函数生成一系列点以实现多项式回归。奇怪的是,当我尝试使用lines()predict()绘制多元回归的预测线时,不同数量的点会绘制明显不同的图形形状。此外,随着点数的增加,图形变得更加平滑,这是令人困惑的。有没有人可以解释这种现象?非常感谢你!

enter image description here

0 个答案:

没有答案