【问题标题】:How to make purrr map function run faster?如何让 purrr map 函数运行得更快?
【发布时间】:2017-04-21 17:11:32
【问题描述】:

我正在使用purrr 库中的map 函数来应用segmented 函数(来自segmented 库),如下所示:

library(purrr)
library(dplyr)
library(segmented)

# Data frame is nested to create list column
by_veh28_101 <- df101 %>% 
  filter(LCType=="CFonly", Lane %in% c(1,2,3)) %>% 
  group_by(Vehicle.ID2) %>% 
  nest() %>% 
  ungroup()

# Functions:
segf2 <- function(df){
  try(segmented(lm(svel ~ Time, data=df), seg.Z = ~Time,
                psi = list(Time = df$Time[which(df$dssvel != 0)]),
                control = seg.control(seed=2)),
      silent=TRUE)
}


segf2p <- function(df){
  try(segmented(lm(PrecVehVel ~ Time, data=df), seg.Z = ~Time,
                psi = list(Time = df$Time[which(df$dspsvel != 0)]),
                control = seg.control(seed=2)),
      silent=TRUE)
}  

# map function:
models8_101 <- by_veh28_101 %>% 
  mutate(segs = map(data, segf2),
         segsp = map(data, segf2p))  

对象by_veh28_101 包含2457 个tibbles。最后一步,使用 map 函数,需要 16 分钟才能完成。有什么办法可以加快速度吗?

【问题讨论】:

  • 这里慢的不是purrr,而是segmented。您正在运行数千个模型,这需要一段时间。分析您的代码以确切了解瓶颈是什么。

标签: r dplyr purrr


【解决方案1】:

您可以使用函数future_map 代替map

此函数来自包furrr,是map 系列的并行选项。这是包的README 的链接。

由于您的代码问题不可重现,我无法在 mapfuture_map 函数之间准备基准测试。

带有future_map 函数的代码如下:

library(tidyverse)
library(segmented)
library(furrr)


# Data frame stuff....

# Your functions....

# future_map function

# this distribute over the different cores of your computer
# 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(strategy = multiprocess)

models8_101 <- by_veh28_101 %>% 
  mutate(segs = future_map(data, segf2),
         segsp = future_map(data, segf2p)) 

【讨论】:

  • 请注意,“多核”不再在 RStudio 中工作。从某些环境(例如 RStudio 环境)运行 R 时,分叉处理被认为是不稳定的。因此,自未来 1.13.0 以来,在这些情况下已禁用“多核”期货。 https://cran.case.edu/web/packages/future/NEWS
猜你喜欢
  • 1970-01-01
  • 2018-02-11
  • 2010-11-06
  • 2023-03-26
  • 1970-01-01
  • 2011-05-10
  • 1970-01-01
  • 2017-07-10
相关资源
最近更新 更多