Skip to content

Instantly share code, notes, and snippets.

@robjhyndman
Last active March 8, 2024 23:56
Show Gist options
  • Save robjhyndman/86c8a26bcde0313ad02b9856c7b5bad1 to your computer and use it in GitHub Desktop.
Save robjhyndman/86c8a26bcde0313ad02b9856c7b5bad1 to your computer and use it in GitHub Desktop.
library(fpp3)
state_tourism <- tourism |>
group_by(State) |>
summarise(Trips = sum(Trips))
training <- state_tourism |>
filter(year(Quarter) <= 2014)
fit <- training |>
model(
ets = ETS(Trips),
arima = ARIMA(Trips),
snaive = SNAIVE(Trips)
)
fc <- fit |>
forecast(h = "3 years")
fc_accuracy <- accuracy(fc, state_tourism,
measures = list(
point_accuracy_measures,
interval_accuracy_measures,
distribution_accuracy_measures
)
)
model_performance <- fc_accuracy |>
group_by(State, .model) |>
summarise(
RMSE = mean(RMSE),
MAE = mean(MAE),
MAPE = mean(MAPE),
Winkler = mean(winkler),
CRPS = mean(CRPS)
) |>
ungroup() |>
arrange(MAPE)
#build table of best models based on MAE
best_models <- model_performance |>
group_by(State) |>
filter(MAE==min(MAE)) |>
select(State, .model)
best_fit <- fit |>
left_join(best_models, by = join_by(State))
best_fit <- best_fit |>
mutate(best_model = purrr::map2(row_number(), .model, ~best_fit[[.y]][[.x]]))
class(best_fit$best_model) <- class(best_fit$ets)
best_fit <- best_fit |>
select(State, best_model)
best_fit |>
forecast(h = "1 year")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment