首页 > 解决方案 > 如何在R中进行多项式回归?

问题描述

要做一个[多重]线性回归模型,使用 lm

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

标签: rnon-linear-regression

解决方案


你可以做到,请看下面的例子。只需添加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)

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

在此处输入图像描述


推荐阅读