r - 如何在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)
输出(红线为拟合数据,蓝点为初始数据):
推荐阅读
- javascript - Netsuite:工作流操作脚本
- java - 这是单元测试还是集成测试?
- oracle - 保护 Oracle REST-Data-Services 中以 */private 结尾的每个端点
- c# - 如何从字节数据中获取位图视图?
- translation - Fairseq 翻译没有超出词汇量的单词
- arrays - “从 A 列中的列表创建工作表名称列表,在 B 列中标识”-错误:“下标超出范围”...选择多个工作表的组?
- python - Python 函数的占位符参数
- java - GWT noserver 该模块尚未编译。Intelijj
- python - Gitlab Python API - 共享项目日期的属性
- android - 如何频繁获取android memoryInfo