如何将数据框或数字对象转换为R中的预测对象?

时间:2018-04-19 18:41:03

标签: r ggplot2 forecasting

我试图将R预测套餐的预测与R Facebook Prophet套餐的预测进行比较。

预测包附带一个方便的自动绘图功能,它似乎只适用于类预测中的对象。

当我尝试绘制先知生成的预测时,我收到以下错误:

> autoplot(forecast$yhat)
Error: Objects of type numeric not supported by autoplot.

如何将数据框或矢量转换为预测对象,然后使用自动曝光功能显示?

1 个答案:

答案 0 :(得分:1)

首先,as.forecast不存在,但是我找到了一个有用的替代方案

library(prophet)
library(dplyr)
df <- read.csv('https://raw.githubusercontent.com/facebook/prophet/master/examples/example_wp_peyton_manning.csv') %>% mutate(y = log(y))

这是先知对象

m <- prophet(df)
Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.
Initial log joint probability = -19.4685
Optimization terminated normally: 
  Convergence detected: relative gradient magnitude is below tolerance

future <- make_future_dataframe(m, periods = 365)
library(zoo)
serie <- zoo(df$y, order.by = as.Date(df$ds))
autoplot(serie)
forecast <- predict(m, future)
|======================================================================================|100% ~0 s remaining     > tail(forecast[c('ds', 'yhat', 'yhat_lower', 'yhat_upper')])
             ds     yhat yhat_lower yhat_upper
3265 2017-01-14 7.823991   7.092573   8.580624
3266 2017-01-15 8.205770   7.483129   8.946540
3267 2017-01-16 8.530798   7.791047   9.278295
3268 2017-01-17 8.318204   7.615776   9.016683
3269 2017-01-18 8.150827   7.462445   8.883549
3270 2017-01-19 8.162741   7.494982   8.846622

以下是您提及的错误

autoplot(forecast$yhat)
Error: Objects of type numeric not supported by autoplot.

使用预测库和ggfortify包的autoplot函数

plot(m, forecast)
library(forecast)
mod <- auto.arima(serie)
autoplot(forecast(mod, h = 365))

df2 <- data.frame(ds = c(as.Date(df$ds),as.Date(forecast$ds)), y = c(df$y,forecast$yhat))
par(mar=c(3,3,2,2),mgp=c(1.6,.6,0))
plot(df2$ds,df2$y, type = "n", ylab = "y", xlab = "ds", las = 1, cex.axis = 0.7)
rect(par("usr")[1], par("usr")[3],par("usr")[2],par("usr")[4],col=gray(.9,.9),
      border='white');grid(lty=1, col='white')
lines(as.Date(df$ds),df$y)
lines(as.Date(tail(forecast$ds, n = 365)),tail(forecast$yhat, n = 365), col = "blue4")
lines(as.Date(tail(forecast$ds, n = 365)),tail(forecast$yhat_lower, n = 365), col = "grey40")
lines(as.Date(tail(forecast$ds, n = 365)),tail(forecast$yhat_upper, n = 365), col = "grey40")

enter image description here

乍一看,这种差异很小,并且没有被注意到。虽然你可以使用ggplot2,但它与autoplot相同。