[英]Forecasting Time Series Groups with tslm() & tidyverse
我想將 tslm model 適合每個時間序列組。 我從這里跟隨示例,但我不想安裝 ets model,而是安裝 tslm。
我調整了代碼,使其看起來像這樣:
library(tidyverse)
library(timetk)
library(sweep)
library(forecast)
monthly_qty_by_cat2 <-
bike_sales %>%
mutate(order.month = as_date(as.yearmon(order.date))) %>%
group_by(category.secondary, order.month) %>%
summarise(total.qty = sum(quantity)) %>%
mutate(trendx = row_number())
monthly_qty_by_cat2_nest <-
monthly_qty_by_cat2 %>%
group_by(category.secondary) %>%
nest() %>%
mutate(data.ts = map(.x = data,
.f = tk_ts,
select = -order.month,
start = 2011,
freq = 12)) %>%
mutate(fit.ts = map(data.ts, ~tslm(total.qty ~ season, data=.x))) %>%
mutate(fcast.ts = map(fit.ts, forecast))
它有效,但是當我改變時
mutate(fit.ts = map(data.ts, ~tslm(total.qty ~ season, data=.x)))
至
mutate(fit.ts = map(data.ts, ~tslm(total.qty ~ trendx, data=.x)))
我收到一個錯誤:
錯誤:
mutate()
輸入fcast.ts
有問題。 x object 'trendx' not found 並且輸入fcast.ts
是map(fit.ts, forecast)
。
如何使用 tslm model 中的自定義預測器預測此數據?
編輯我重寫了代碼以使用寓言 package:
monthly_qty_by_cat2 <- bike_sales %>% mutate(order.month = as_date(as.yearmon(order.date))) %>% group_by(category.secondary, order.month) %>% summarise(total.qty = sum(quantity)) %>% mutate(trendx = row_number()) monthly_qty_by_cat2_nest <- monthly_qty_by_cat2 %>% group_by(category.secondary) %>% as_tsibble(key = category.secondary) monthly_qty_by_cat2_nest %>% model(tslm = TSLM(total.qty ~ trendx)) %>% forecast()
並收到錯誤:
錯誤:
mutate()
輸入tslm
有問題。 x object 'trendx' not found 無法從提供的new_data
計算所需的變量。 您的 model 是否需要額外的變量來生成預測?
library(tidyverse)
library(tsibble)
library(fable)
library(lubridate)
monthly_qty_by_cat2 <-
sweep::bike_sales %>%
mutate(order.month = yearmonth(order.date)) %>%
group_by(category.secondary, order.month) %>%
summarise(total.qty = sum(quantity)) %>%
as_tsibble(index=order.month, key=category.secondary) %>%
mutate(x = rnorm(length(total.qty)))
#> `summarise()` regrouping output by 'category.secondary' (override with `.groups` argument)
future_x <- new_data(monthly_qty_by_cat2) %>%
mutate(x = 2)
monthly_qty_by_cat2 %>%
model(tslm = TSLM(total.qty ~ trend() + x)) %>%
forecast(new_data=future_x)
#> # A fable: 9 x 6 [1M]
#> # Key: category.secondary, .model [9]
#> category.secondary .model order.month total.qty .mean x
#> <chr> <chr> <mth> <dist> <dbl> <dbl>
#> 1 Cross Country Race tslm 2016 Jan N(369, 187840) 369. 2
#> 2 Cyclocross tslm 2016 Jan N(-2.5, 75604) -2.50 2
#> 3 Elite Road tslm 2016 Jan N(784, 322470) 784. 2
#> 4 Endurance Road tslm 2016 Jan N(159, 117760) 159. 2
#> 5 Fat Bike tslm 2016 Jan N(95, 66320) 94.6 2
#> 6 Over Mountain tslm 2016 Jan N(194, 57732) 194. 2
#> 7 Sport tslm 2016 Jan N(120, 81568) 120. 2
#> 8 Trail tslm 2016 Jan N(214, 56269) 214. 2
#> 9 Triathalon tslm 2016 Jan N(102, 94449) 102. 2
由reprex package (v0.3.0) 於 2020 年 7 月 20 日創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.