如何解决多项式回归预测有效,但公式错误
当我使用 stats::predict() 和使用拟合多项式时,为什么会得到不同的结果?
set.seed(999999)
library(tidyverse)
fit <- tibble(rand = rbeta(1e6,5,2.5)) %>%
mutate(rand = cut(rand,150)) %>%
count(rand) %>%
mutate(x = 1:150) %>%
lm(n ~ poly(x,10),.)
plot(predict(fit),main = "prediction")
coef(fit)
poly_fn <- polynom::polynomial(coef(fit)) # convert to function
f <- as.function(poly_fn)
plot(f(1:150))
解决方法
您需要使用 poly(...,raw = TRUE)
以 polynom::polynomial
使用的形式获取系数:
set.seed(999999)
library(tidyverse)
fit <- tibble(rand = rbeta(1e6,5,2.5)) %>%
mutate(rand = cut(rand,150)) %>%
count(rand) %>%
mutate(x = 1:150) %>%
lm(n ~ poly(x,10,raw = TRUE),.)
plot(predict(fit),main = "prediction")
coef(fit)
#> (Intercept) poly(x,raw = TRUE)1 poly(x,raw = TRUE)2
#> -1.502706e+00 2.081423e+00 -3.652070e-01
#> poly(x,raw = TRUE)3 poly(x,raw = TRUE)4 poly(x,raw = TRUE)5
#> 5.063552e-02 -1.219081e-03 3.267963e-05
#> poly(x,raw = TRUE)6 poly(x,raw = TRUE)7 poly(x,raw = TRUE)8
#> -4.348967e-07 2.143856e-09 3.615717e-12
#> poly(x,raw = TRUE)9 poly(x,raw = TRUE)10
#> -7.321806e-14 1.996748e-16
poly_fn <- polynom::polynomial(coef(fit)) # convert to function
f <- as.function(poly_fn)
plot(f(1:150))
由 reprex package (v2.0.0) 于 2021 年 6 月 25 日创建
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。