【问题标题】:Increase speed of batch forecast with purrr用 purrr 提高批量预测的速度
【发布时间】:2018-08-01 20:11:58
【问题描述】:

我正在阅读关于批量预测的blog post,并希望提高速度。我尝试使用purrr,但只减少了不到一半的时间。下面是一个可重现的示例,显示了 Hyndman 博客文章中的示例,并显示了 purrr 替代方案。我怎样才能减少这个时间?

library(forecast)
library(tidyverse)
library(purrr)
#read file
retail <- read.csv("https://robjhyndman.com/data/ausretail.csv",header=FALSE)

# hyndmans loop
retail <- ts(retail[,-1],f=12,s=1982+3/12)
ns <- ncol(retail)
h <- 24
fcast <- matrix(NA,nrow=h,ncol=ns)
system.time(
for(i in 1:ns)
  fcast[,i] <- forecast(retail[,i],h=h)$mean
)

#   user  system elapsed 
#  60.14    0.17   61.72 

# purrr try
system.time(
retail_forecast <- retail %>% 
  as_tibble() %>% 
  map(~ts(.,frequency = 7)) %>% 
  map_dfc(~forecast(.,h=h)$mean))

#   user  system elapsed 
#  32.23    0.03   35.32 

【问题讨论】:

  • 改变频率会改变计算时间。较小的频率更快。使频率=12,发出的呼噜声几乎与循环相同。

标签: r forecasting purrr


【解决方案1】:

您可以使用 furrr 包并行化 purrr 函数。这是包页面的摘录

furrr 的目标是简化purrr 的映射函数族和future 的并行处理能力的组合。已经定义了一组新的future_map_*() 函数,可以(希望)用作相应map_*() 函数的替代品。

代码大量借鉴了purrr 和future.apply 的实现

使用furrr 我能够在我的 Linux 机器上将计算时间减少 3 倍以上

library(forecast)
library(tidyverse)

### read file
retail <- read.csv("https://robjhyndman.com/data/ausretail.csv", header = FALSE)

海德曼循环

retail <- ts(retail[, -1], f = 12, s = 1982 + 3 / 12)
ns <- ncol(retail)
h <- 24
fcast <- matrix(NA, nrow = h, ncol = ns)
system.time(
  for (i in 1:ns)
    fcast[, i] <- forecast(retail[, i], h = h)$mean
)

# user  system elapsed 
# 50.592   0.016  50.599
#

咕噜试试

system.time(
  retail_forecast <- retail %>%
    as_tibble() %>%
    map(~ts(., frequency = 12)) %>%
    map_dfc(~ forecast(., h = h)$mean)
)

# user  system elapsed 
# 50.232   0.000  50.224 
#

咕咕咕试试

library(furrr)
#> Loading required package: future
# You set a "plan" for how the code should run. The easiest is `multiprocess`
# On Mac this picks plan(multicore) and on Windows this picks plan(multisession)
plan(multiprocess)

system.time(
  retail_forecast <- retail %>%
    as_tibble() %>%
    future_map(~ts(., frequency = 12)) %>%
    future_map_dfc(~ forecast(., h = h)$mean)
)

# user  system elapsed 
# 0.172   0.080  14.702
#

由reprex package (v0.2.0.9000) 于 2018 年 8 月 1 日创建。

【讨论】:

  • 如果您使用频率 = 12 而不是不正确的频率 = 7,则 purrr 几乎与使用循环相同。 furrr 仍然快得多
猜你喜欢
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 2021-04-06
  • 2012-09-15
  • 1970-01-01
  • 1970-01-01
  • 2014-07-28
  • 1970-01-01
相关资源
最近更新 更多