如何在dplyr + purrr

时间:2019-03-12 19:05:05

标签: r dplyr tidyverse purrr

我有一个问题,在为训练和测试集复制数据后,我在Rstudio中显示了分配给我的用户的大量内存,但未在我的R会话中使用。我创建了一个小例子来重现我的处境:)

此代码根据我提供的不同公式,算法和参数集运行一堆模型。这是一个函数,但是我为reprex创建了一个简单的脚本。

library(dplyr)
library(purrr)
library(modelr)
library(tidyr)
library(pryr)

# set my inputs
data <- mtcars
formulas <- c(test1 = mpg ~ cyl + wt + hp,
              test2 = mpg ~ cyl + wt)
params = list()
methods <- "lm"

n <- 20 # num of cv splits
mult <- 10 # number of times I want to replicate some of the data
frac <- .25 # how much I want to cut down other data (fractional)

### the next few chunks get the unique combos of the inputs.
if (length(params) != 0) {
  cross_params <- params %>% 
    map(cross) %>% 
    map_df(enframe, name = "param_set", .id = "method") %>% 
    list
} else cross_params <- NULL

methods_df <- tibble(method = methods) %>% 
  list %>% 
  append(cross_params)  %>% 
  reduce(left_join, by = "method") %>% 
  split(1:nrow(.))

# wrangle formulas into a split dataframe
formulas_df <- tibble(formula = formulas,
                      name = names(formulas)) %>% 
  split(.$name)

# split out the data into n random train-test combos
cv_data <- data %>% 
  crossv_kfold(n) %>% # rsample?
  mutate_at(vars(train:test), ~map(.x, as_tibble))

# sample out if needed
cv_data_samp <- cv_data %>%
  mutate(train = modify(train, 
                        ~ .x %>% 
                          split(.$gear == 4) %>% 
                          # take a sample of the non-vo data
                          modify_at("FALSE", sample_frac, frac) %>% 
                          # multiply out the vo-on data
                          modify_at("TRUE", function(.df) {
                            map_df(seq_along(1:mult), ~ .df) 
                          }) %>% 
                          bind_rows))

# get all unique combos of formula and method
model_combos <- list(cv = list(cv_data_samp), 
                     form = formulas_df, 
                     meth = methods_df) %>% 
  cross %>%
  map_df(~ bind_cols(nest(.x$cv), .x$form, .x$meth)) %>% 
  unnest(data, .preserve = matches("formula|param|value")) %>% 
  {if ("value" %in% names(.)) . else mutate(., value = list(NULL))} 

# run the models
model_combos %>% 
  # put all arguments into a single params column
  mutate(params = pmap(list(formula = formula, data = train), list)) %>%
  mutate(params = map2(params, value, ~ append(.x, .y))) %>%
  mutate(params = modify(params, discard, is.null)) %>%
  # run the models
  mutate(model = invoke_map(method, params))  

mem_change(rm(data, cv_data, cv_data_samp))
mem_used()

现在,执行此操作后,我的mem_used达到了77.3mb,但是我看到分配给R用户的数据(160Mb)大约翻了一番。当我的数据为3 Gb时,这确实爆炸了,这是我的真实情况。我最终使用100Gb并绑定了整个服务器:(。

这是怎么回事,我该如何优化?

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

我知道了!问题是我将modelr resample对象序列转换为tibble s,即使随后进行采样降低了内存的爆炸性。解决方案?编写用于处理resample对象的方法,这样我就不必将resample对象转换为tibble。这些看起来像:

# this function just samples the indexes instead of the data
sample_frac.resample <- function(data, frac) {
  data$idx <- sample(data$idx, frac * length(data$idx))
  data
}

# this function replicates the indexes. I should probably call it something else.
augment.resample <- function(data, n) {
  data$idx <- unlist(map(seq_along(1:n), ~ data$idx))
  data
}

# This function does simple splitting (logical only) of resample obejcts
split.resample <- function(data, .p) {
  pos <- list(data = data$data, idx = which(.p, 1:nrow(data$data)))
  neg <- list(data = data$data, idx = which(!.p, 1:nrow(data$data)))
  class(pos) <- "resample"
  class(neg) <- "resample"
  list("TRUE" = pos,
       "FALSE" = neg)
}

# This function takes the equivalent of a `bind_rows` for resample objects.
# Since bind rows does not call `useMethod` I had to call it something else
bind <- function(data) {
  out <- list(data = data[[1]]$data, idx = unlist(map(data, pluck, "idx")))
  class(out) <- "resample"
  out
}

然后,我在同一个purrr闭包中转换为小标题,在该闭包中为该CV运行我的模型。问题解决了!我的内存使用量现在非常低。