使用多项式模型进行逆预测

时间:2014-10-02 11:15:36

标签: r regression prediction

我是一个线性,单变量回归的多项式模型,我可以从 y 预测新数据集的 x 。 该模型类似于

f22<- lm(y~I(x^2.0) + I(x^3.0) + I(x^0.5))

我在非常狭窄的 x 范围内使用此模型,其中模型是单调的。 我想我不能使用函数 predict.lm ...有什么建议吗? 感谢。

1 个答案:

答案 0 :(得分:2)

以下是基于uniroot的解决方案:

#some data
x <- 1:100
set.seed(42)
y <- 1.8*x^2 - 0.015*x^3 + 0.4*x^0.5 + rnorm(100)
plot(y~x)

#fitting the model
f22<- lm(y~I(x^2.0) + I(x^3.0) + I(x^0.5), data=data.frame(x, y))
f22

lines(x, predict(f22))

resulting plot

#function to pass to uniroot for inverse prediction
ynew <- 2000 + (1:10)*100 
fun <- function(x1, y1, mod) {
  predict(mod, newdata=data.frame(x=x1)) - y1
}    
#note how the interval is specified
xpred <- sapply(ynew, function(z) uniroot(fun, interval=c(20, 70), mod=f22, y1=z)$root)
#[1] 42.46892 43.86588 45.27242 46.69238 48.12992 49.58967 51.07714 52.59857 54.16165 55.77589

#check if it worked
predict(f22, newdata=data.frame(x=xpred))
#       1        2        3        4        5        6        7        8        9       10 
#2100.000 2200.000 2300.000 2400.001 2500.002 2599.999 2700.000 2800.000 2900.000 3000.000