利用并行计算对tidymodels建模过程进行加速计算

代码原始地址
https://tune.tidymodels.org/articles/extras/optimizations.html
以下为其代码的makrdown,笔者翻译为了中文并加入了部分自己的理解,请多指教哈

Title: "Optimizations and parallel processing" 优化和并行处理

knitr::opts_chunk$set(echo = TRUE)
library(tidymodels)

Sub-model speed-ups

For some types of models, such as boosted models or regularized models, the number of models that are actually fit can be far less than the number of models evaluated. For example, suppose a boosted tree is fit with 1000 trees. Many boosting implementations let the user make predictions for any number of trees less than what was originally fit (1000 in this example). This "sub-model trick" can greatly speed up the training time for many models (e.g. see this example in the caret documentation).

机器学习的有一种算法为集成学习,比如随机森林。随机森林是由许多的决策树所组成的,每个决策树可以单独进行计算,然后再进行汇总,这种情况下可以用并行计算加快速度。

In order to know what models allow this, the parsnip package contains a multi_predict() function that enables this feature. Printing the S3 methods for it lists the possible models:

我们可以用multi_predict()函数查看parsnip包里面有哪些函数支持这种加速

library(tidymodels)
methods("multi_predict")
# There are arguments for the parameter(s) that can create multiple predictions.
# For xgboost, `trees` are cheap to evaluate: 
parsnip:::multi_predict._xgb.Booster %>% 
  formals() %>% 
  names()
对于xgb.booster来说支持的并行计算方法

The same feature does not exist for recipes though.
recipes的过程不支持并行计算

Expensive pre-processing

When tuning a recipe and a model, it makes sense to avoid recreating the recipe for each model.

For example, suppose that Isomap multi-dimensional scaling is used to pre-process the data prior to tuning a K-nearest neighbor regression:

比如,在进行K最近邻回归前,我们先对数据预处理,对其进行了降纬(Isomap是一种非线性降维方法。

data(Chicago)#数据
#数据预处理
iso_rec <- 
  recipe(ridership ~ ., data = Chicago) %>% #回归方程
  step_dummy(all_nominal()) %>% #设定虚拟变量
  step_isomap(all_predictors(), num_terms = tune())#数据姜维
#构建模型
knn_mod <- 
  nearest_neighbor(neighbors = tune(), weight_func = tune()) %>% #确定模型及超参数
  set_engine("kknn") %>% #设定算法
  set_mode("regression")#设定结果变量

With the following grid:

grid <- 
  parameters(num_terms(c(1, 9)), neighbors(), weight_func()) %>% 
  grid_regular(levels = c(5, 10, 7)) %>% 
  arrange(num_terms, neighbors, weight_func)
grid 

To evaluate these r nrow(grid) candidate models, we would have to compute the same recipe 70 times per resample. Since Isomap is expensive, this is really inefficient.

tune_grid() determines when this occurs and fits all 70 candidate models for each unique configuration of the recipe. In essence, it nests the model parameters inside the unique parameters of the recipe:

alt_grid <- tidyr::nest(grid, data = c(-num_terms))
alt_grid

Only r nrow(alt_grid) recipes are prepared and, within each, all of the appropriate models are fit from the same recipe. In this example, once the recipe with num_terms = 1 is created, the model parameters are iteratively tuned:

alt_grid$data[[1]]

The same will be true for post-processing parameters being tuned. For each unique set of recipe and model parameters, the post-processing parameters will be evaluated without unnecessary re-fitting.

Also, when using a model formula, the model matrix is only created once per resample.

Parallel Processing

tune allows users, when possible, to use multiple cores or separate machines fit models. Currently, the package parallelizes the resampling loop of grid search^[There will be more options in the future to control this since the current implementation doesn't help for cases when many models are fit over a single resample of the data (such as a validation set).].

The foreach package is used to facilitate parallel computations. foreach can use a variety of technologies to share the computations and the choice of technology is determined by which parallel backend package is chosen (aka the do{technology} packages). For example, the doMC package uses the forking mechanism on *unix systems to split the computations across multiple cores. As of this writing, the backend packages are doFuture, doMC, doMPI, doParallel, doRedis, doRNG, doSNOW, and doAzureParallel (GitHub only). Of these, doFuture and doParallel are probably the most comprehensive and best supported.

Registering a parallel backend is also somewhat dependent of the package. For doParallel, one could use:

all_cores <- parallel::detectCores(logical = FALSE)
library(doParallel)
cl <- makePSOCKcluster(all_cores)
registerDoParallel(cl)

Other options exist in doParallel.

doFuture uses a function called plan to declare the method:

all_cores <- parallel::detectCores(logical = FALSE)
library(doFuture)
registerDoFuture()
cl <- makeCluster(all_cores)
plan(cluster, workers = cl)

One downside to parallel processing is that the different technologies handle inputs and outputs differently. For example, multicore forking tends to carry the loaded packages and objects into the worker processes. Others do not. To make sure that the correct packages are loaded (but not attached) in the workers is to use the pkg option in control_grid().

Some helpful advice to avoid errors in parallel processing is to not use variables in the global environment. These may not be found when the code is run inside of a worker process. For example:

num_pcs <- 3
recipe(mpg ~ ., data = mtcars) %>% 
  # Bad since num_pcs might not be found by a worker process
  step_pca(all_predictors(), num_comp = num_pcs)
recipe(mpg ~ ., data = mtcars) %>% 
  # Good since the value is injected into the object
  step_pca(all_predictors(), num_comp = !!num_pcs)

This issue is likely to occur if dplyr::one_of() is used as a sector.

Also note that almost all of the logging provided by tune_grid() will not be seen when running in parallel. Again, this is dependent on the backend package and technology being used.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,732评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,496评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,264评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,807评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,806评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,675评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,029评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,683评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,704评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,666评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,773评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,413评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,016评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,978评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,204评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,083评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,503评论 2 343

推荐阅读更多精彩内容