Error in `fabletools::autoplot()`: ! Provided data contains a different key structure to the forecasts

241 views Asked by At

I just began working with cross validation forecasting. I can't seem to use autoplot() correctly. I'm trying to have only the last 4 years of the data be forecasted and plot it over the entire data set. When I don't specify the autoplot(), it plot the graph below. I tried filter_index(. ~ "2014"), filter(Country=="United States") nested within the autoplot() but didn't work, so I left it out of the code below. I'm using the global_economy data set in the tsibble library trying to forecast US GDP. If I leave autoplot() empty, it plots the forecast for the entire time period.

econ <- global_economy
model <- econ %>%
  filter(Country=="United States") %>%
  stretch_tsibble(.init=15, .step=1) %>%
  model(NAIVE(GDP),NNETAR(GDP)) %>%
  fabletools::forecast(h="1 year")


model  %>%
  group_by(.id,.model) %>%
  mutate(h = row_number()) %>%
  ungroup() %>%
  as_fable(response = "GDP", distribution = GDP) %>%
  filter(h==1) %>%
  as_fable(key=c(.model)) %>%
fabletools::autoplot(econ)

enter image description here

1

There are 1 answers

0
Mitchell O'Hara-Wild On

The econ dataset has Country as a key variable, which is needed in the <fable> to match the appropriate series for plotting. Also if you only want to forecast the last 4 years with cross validation, you would increase the .init for the cross-validation stretching folds to 54.

library(fpp3)
#> ── Attaching packages ──────────────────────────────────────────── fpp3 0.4.0 ──
#> ✔ tibble      3.1.8          ✔ tsibble     1.1.3     
#> ✔ dplyr       1.0.10         ✔ tsibbledata 0.4.1     
#> ✔ tidyr       1.2.1          ✔ feasts      0.3.0     
#> ✔ lubridate   1.9.0          ✔ fable       0.3.2.9000
#> ✔ ggplot2     3.4.0
#> ── Conflicts ───────────────────────────────────────────────── fpp3_conflicts ──
#> ✖ lubridate::date()    masks base::date()
#> ✖ dplyr::filter()      masks stats::filter()
#> ✖ tsibble::intersect() masks base::intersect()
#> ✖ tsibble::interval()  masks lubridate::interval()
#> ✖ dplyr::lag()         masks stats::lag()
#> ✖ tsibble::setdiff()   masks base::setdiff()
#> ✖ tsibble::union()     masks base::union()
econ <- global_economy
model <- econ %>%
  filter(Country=="United States") %>%
  stretch_tsibble(.init=54, .step=1) %>%
  model(NAIVE(GDP),NNETAR(GDP)) %>%
  fabletools::forecast(h="1 year")

model  %>%
  group_by(.id,.model) %>%
  mutate(h = row_number()) %>%
  filter(h==1) %>%
  ungroup() %>% 
  update_tsibble(key=c(.model, Country)) %>% 
  as_fable(response = "GDP", distribution = GDP) %>%
  fabletools::autoplot(econ)

Created on 2023-01-11 with reprex v2.0.2