使用R中的多项式回归预测未来值

时间:2016-07-08 06:37:05

标签: r regression prediction forecasting

尝试使用R中的多项式回归来预测样本的未来值。样本中的y值形成波形图案。 例如

x = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
y= 1,2,3,4,5,4,3,2,1,0,1,2,3,4,5,4

但是,当为未来值绘制图表时,结果y值与预期值完全不同。而不是波形模式,正在获得y值不断增加的图表。

futurY = 17,18,19,20,21,22

尝试了不同程度的多项式回归,但futurY的预测结果与预期的结果大不相同

以下是用于获得结果的示例R代码

dfram <- data.frame('x'=c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16))
dfram$y <- c(1,2,3,4,5,4,3,2,1,0,1,2,3,4,5,4)
plot(dfram,dfram$y,type="l", lwd=3)
pred <- data.frame('x'=c(17,18,19,20,21,22))
myFit <- lm(y ~ poly(x,5), data=dfram)
newdata <- predict(myFit, pred)
print(newdata)
plot(pred[,1],data.frame(newdata)[,1],type="l",col="red", lwd=3)

这是用于预测未知未来y值的正确技术还是我应该使用预测等其他技术?

1 个答案:

答案 0 :(得分:1)

# Reproducing your data frame
dfram <- data.frame("x" = c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16),
                    "y" = c(1,2,3,4,5,4,3,2,1,0,1,2,3,4,5,4))

从图表中我得到了信号的相位和周期。有更好的方法可以自动计算。

# Phase and period
fase = 1
per = 10

在线性模型函数中我放了三角形信号方程。

fit <- lm(y ~ I((((trunc((x-fase)/(per/2))%%2)*2)-1) * (x-fase)%%(per/2))
            + I((((trunc((x-fase)/(per/2))%%2)*2)-1) * ((per/2)-((x-fase)%%(per/2))))
          ,data=dfram)

# Predict the old data
p_olddata <- predict(fit,type="response")

# Predict the new data
newdata <- data.frame('x'=c(17,18,19,20,21,22))
p_newdata <- predict(fit,newdata,type="response")

# Ploting Old and new data
plot(x=c(dfram$x,newdata$x),
     y=c(p_olddata,p_newdata),
     col=c(rep("blue",length(p_olddata)),rep("green",length(p_olddata))),
     xlab="x",
     ylab="y")
lines(dfram)

enter image description here

黑线是原始信号,蓝色圆圈是原始点的预测,绿色圆圈是新数据的预测。

图表显示了模型的完美拟合,因为数据中没有噪音。在真实的数据集中,您可能会发现它的合体性不会那么好。

相关问题