【问题标题】:R How to construct polynom with form c0 + c1 * x + .. + cn * x^n from orthogonal lm (with poly(raw=F))R如何从正交lm构造形式为c0 + c1 * x + .. + cn * x^n的多项式(使用poly(raw = F))
【发布时间】:2020-09-21 14:21:20
【问题描述】:

如何在 R 中提取正交多项式回归的系数?

它就像一个带有原始回归的魅力:

#create datas
set.seed(120)
x= 1:20
y=x^2 + rnorm(length(x),0,10)
datas = data.frame(x,y)

#compute raw model with function poly
mod= lm(data=datas, y~poly(x,2,raw=T))

#get coefficients with function coef()
coefficients = coef(mod)

#construct polynom and check fitted values
fitted_values = mod$fitted.values
x0 = datas$x[1]
solution = coefficients[1]+ coefficients[2]*x0^1 + coefficients[3]*x0^2
print(solution)
# 1.001596 
print(fitted_values[1])
# 1.001596
# 1.001596  == 1.001596

但是在正交lm上用函数coef得到的系数不起作用:

#create datas
set.seed(120)
x= 1:20
y=x^2 + rnorm(length(x),0,10)
datas = data.frame(x,y)

#compute raw model with function poly
mod = lm(data=datas, y~poly(x,2,raw=F))

#get coefficients with function coef()
coefficients = coef(mod)
fitted_values = mod$fitted.values

#construct polynom and check fitted values
x0 = datas$x[1]
solution = coefficients[1]+ coefficients[2]*x0^1 + coefficients[3]*x0^2
print(solution)
# 805.8476 
print(fitted_values[1])
# 1.001596
# 1.001596 != 805.8476 

是否有另一种方法可以获得正确的参数来构造形式为 c0 + c1 * x + .. + cn * x^n 的多项式并使用它来求解或预测?

我需要解方程,这意味着使用函数 base::solve 将 x 给定一个 y。

谢谢

【问题讨论】:

    标签: r lm poly


    【解决方案1】:

    问题是您不仅需要系数,还需要正交多项式(而不是您尝试使用的原始多项式)。后者由model.matrix构造:

    newdata <- model.matrix(~ poly(x, 2), data = datas)
    solution <- newdata %*% coefficients
    print(solution[1])
    # [1] 1.001596 
    print(fitted_values[1])
    #1.001596
    

    我不明白与solve 的联系,但相信您可以从这里获取。

    【讨论】:

    • 我需要求解 f(x) = 1.001596 并用我的示例模型找到 x=1。有时,当正交回归起作用时,原始回归会给出 x^2 系数的 NA。但我无法使用 base::solve() 函数解决正交回归。
    • 你为什么要使用solveen.wikipedia.org/wiki/…
    • 我使用了solve,因为它适用于非正交多项式系数列表,但不适用于正交多项式。我要么需要找到正交多项式的相应原始多项式,要么找到一种方法来解决 f(x) = y 与正交多项式。
    • 也许我只是错过了这样做的数学方法。我会检查你的链接
    • 数字方法就足够了吗? uniroot(function(x) predict(mod, newdata = list(x = x)) - y, c(0, 100)) 这只会找到一个根,而且如您所知,通常有两个。调整间隔以找到两者。绘图对此很有用。
    猜你喜欢
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 2014-12-30
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    相关资源
    最近更新 更多