如何在 R 中进行多项式回归?

How to do multiple polynomial regression in R?

要建立[多重]线性回归模型,可以使用 lm

是否可以推导多元多项式回归模型?其中每个系数是多项式函数?

你可以做到,请看下面的例子。只需添加 poly 函数参数 raw = TRUE 即可获得易于解释的系数:

set.seed(123)

x <- seq(-10, 10, by = 0.1)
y <- 0.5 * x ^ 3 + rnorm(length(x), 0, sd = 10)

df <- data.frame(x, y)

m <- lm(y ~ poly(x,3, raw = TRUE), data = df)
summary(m)

# Coefficients:
#   Estimate Std. Error t value Pr(>|t|)    
# (Intercept)             -0.337708   1.015189  -0.333    0.740    
# poly(x, 3, raw = TRUE)1 -0.156641   0.291625  -0.537    0.592    
# poly(x, 3, raw = TRUE)2  0.010747   0.022476   0.478    0.633    
# poly(x, 3, raw = TRUE)3  0.501871   0.004411 113.783   <2e-16 ***
#  ---
#  Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

plot(df$x, df$y, col = "blue", xlab = "x", ylab = "y")
df$fitted <- fitted(m, data.frame(x))
lines(df$x, df$fitted, col = "red", lwd = 2)

输出(红线为拟合数据,蓝点为初始数据):