我想要创建一些预测,我选择auto.arima。经过训练后,我无法计算预测的2篇文章:
my_forecast <- ts(frc$sales_30, frequency = 12)
my_forecast <- tsclean(my_forecast)
fit <- auto.arima(my_forecast)
但我有100篇文章,我需要预测所有这些名称(格式:年份,月份,销售,文章)
发布于 2022-03-29 19:23:10
这个任务在R中的典型工作流是列表式的。这意味着您通过list-items
中的文章传播您的数据,并在这些项目上应用内容。您可能已经了解到,由于time-series
是由ts()
函数的频率变量生成的,所以年份和月份是无关的。
因此,这个样本只适用于A和B条,以及我们假设已经按日期分类的虚构的每月销售向量。
我将不深入研究time-series
分析/预测的技术,而主要关注于基于包含所有文章(或任何级别分组)和相应的销售历史的df进行多个预测的过程/代码。我没有使用tsclean()
函数,但是从工作流中可以清楚地看到如何包含它:
library(forecast)
library(tidyverse)
# set up some dummy data (has no clear pattern in terms of seasonality etc. but works for demo)
## bear in mind that this is randomly generated data therefore you most likely will not reproduce my data but with the help of a seed you can work arround this as well.
df <- data.frame(article = c(rep("A", 24), rep("B", 24)),
sales = c(sample(seq(from = 20, to = 50, by = 5), size = 24, replace = TRUE),
sample(seq(from = 20, to = 50, by = 5), size = 24, replace = TRUE)))
# build grouping inside de df/tibble
dfg <- df %>%
dplyr::group_by(article)
# split the new df by grouping criteria into list
dfl <- dfg %>%
dplyr::group_split(.keep = FALSE)
# set list names acording to article value (no needed but might be helpfull for you)
names(dfl) <- dplyr::group_keys(dfg)$article
# apply ts function with frequency 12 to the list items
dflt <- lapply(dfl, ts, frequency = 12)
# apply the auto.arima to build list of models
dfltm <- lapply(dflt, forecast::auto.arima)
# apply forecast with horizon 2 on the list of final models from auto.arima
predictions <- lapply(dfltm, forecast::forecast, h = 2)
# print results
predictions
$A
Point Forecast Lo 80 Hi 80 Lo 95 Hi 95
Jan 3 34.79167 22.47636 47.10697 15.95703 53.6263
Feb 3 34.79167 22.47636 47.10697 15.95703 53.6263
$B
Point Forecast Lo 80 Hi 80 Lo 95 Hi 95
Jan 3 34.58333 20.32802 48.83865 12.78171 56.38496
Feb 3 34.58333 20.32802 48.83865 12.78171 56.38496
做同样事情的一种现代方法是在tibble
中处理嵌套列表。
# build list inside the tibble/df by existing groupings
npd <- tidyr::nest(dfg) %>%
# generate new column of ts series data
dplyr::mutate(tsdata = purrr::map(data, ~ ts(.x, frequency = 12)),
# use auto.arima on the data to build new column of final auto.arima models
models = purrr::map(tsdata, ~ forecast::auto.arima(.x)),
# generate forecast as new column
predictions = purrr::map(models, ~ forecast::forecast(.x, h = 2)))
# print prediction results
npd$predictions
[[1]]
Point Forecast Lo 80 Hi 80 Lo 95 Hi 95
Jan 3 34.79167 22.47636 47.10697 15.95703 53.6263
Feb 3 34.79167 22.47636 47.10697 15.95703 53.6263
[[2]]
Point Forecast Lo 80 Hi 80 Lo 95 Hi 95
Jan 3 34.58333 20.32802 48.83865 12.78171 56.38496
Feb 3 34.58333 20.32802 48.83865 12.78171 56.38496
正如前面提到的,ts()
函数基于频率而不是日期列工作,这意味着您必须确保没有销售的月份被列出,并且所有的文章都有一个完整的数据时间线,并且越来越有序(面向时间)。在形成time-series
对象之前,必须包括缺少的值。
最后,我强烈推荐来自forecast
包作者的一本开放的书,可以在这里找到:https://otexts.com/fpp2/
https://stackoverflow.com/questions/71666587
复制相似问题