【问题标题】:Polynomial regression prediction works but the formula is wrong [duplicate]多项式回归预测有效,但公式错误[重复]
【发布时间】:2021-06-25 14:20:20
【问题描述】:

为什么我使用 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))

【问题讨论】:

标签: r regression polynomials


【解决方案1】:

您需要使用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, 10, raw = TRUE)1  poly(x, 10, raw = TRUE)2 
#>             -1.502706e+00              2.081423e+00             -3.652070e-01 
#>  poly(x, 10, raw = TRUE)3  poly(x, 10, raw = TRUE)4  poly(x, 10, raw = TRUE)5 
#>              5.063552e-02             -1.219081e-03              3.267963e-05 
#>  poly(x, 10, raw = TRUE)6  poly(x, 10, raw = TRUE)7  poly(x, 10, raw = TRUE)8 
#>             -4.348967e-07              2.143856e-09              3.615717e-12 
#>  poly(x, 10, raw = TRUE)9 poly(x, 10, 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 日创建

【讨论】:

    猜你喜欢
    • 2019-07-29
    • 2017-04-11
    • 2012-12-03
    • 2019-01-24
    • 2018-10-19
    • 1970-01-01
    • 2017-04-23
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多