r - 如何有效地扫描许多参数以在 R 中运行脚本?
问题描述
我在 R 中有一个脚本,它有 4 个可以变化的参数。我想用这些参数的一些组合来运行扫描,然后对这些运行时间进行比较。像这样的东西:
dim_map = c(10,40,80,120)
epochs = c(200,600,1000)
dim_input = c(3,80,400,1000,3000)
datapoints = c(15000,50000,100000)
results = data.frame(dim_map = c(),
epochs = c(),
dim_input = c(),
datapoints = c(),
time = c()
)
for(dim in dim_map){
for (epoch in epochs){
for (m in dim_input){
for (n in datapoints){
t = Sys.time() # Start time
## Run some script
elapsed_time = as.numeric(Sys.time() - t, units = 'secs')
results[nrow(results)+1,] = c(dim, epoch, m, n, elapsed_time)
}
}
}
}
有没有办法避免循环?我觉得这些嵌套循环正在减慢扫描速度,但我不知道这是否只是我的想象。或者也许是用这些参数变化来计时脚本的更好方法?
解决方案
我认为做这种事情最简单的方法之一是结合pmap
和cross_df
从purrr
. 我们可以轻松地创建所有参数组合,然后为每个参数运行我们的代码,将结果存储在一个新列中:
library(tidyverse)
params <- cross_df(list(
dim_map = c(10,40,80,120),
epochs = c(200,600,1000),
dim_input = c(3,80,400,1000,3000),
datapoints = c(15000,50000,100000)
))
timer <- function(dim_map, epochs, dim_input, datapoints){
start_time = Sys.time()
Sys.sleep(0.01) # your code to time here
end_time = Sys.time()
return(end_time - start_time)
}
params %>%
mutate(time = pmap_dbl(., timer))
#> # A tibble: 180 x 5
#> dim_map epochs dim_input datapoints time
#> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 10 200 3 15000 0.0110
#> 2 40 200 3 15000 0.0110
#> 3 80 200 3 15000 0.0110
#> 4 120 200 3 15000 0.0110
#> 5 10 600 3 15000 0.0110
#> 6 40 600 3 15000 0.0110
#> 7 80 600 3 15000 0.0110
#> 8 120 600 3 15000 0.0109
#> 9 10 1000 3 15000 0.0110
#> 10 40 1000 3 15000 0.0110
#> # ... with 170 more rows
由reprex 包(v0.2.0)于 2018 年 9 月 21 日创建。
推荐阅读
- database - 如何将android studio中制作的android应用程序与MongoDB atlas连接起来?
- popup - 需要一种方法来检查javascript中是否有任何打开的弹出窗口,如果关闭它们
- go - GStreamer 应用程序接收器比文件接收器慢得多
- reactjs - 在多个 API 调用循环后反应更新状态
- android - 约束布局中不同大小元素的Android xml样式
- javascript - 检查字符串是否不包含值
- c - 检查一个函数的返回值到另一个函数中
- java - SimpleDateFormat 无法正确解析
- javascript - 当 Canvas 被 Web Worker 中的 OffscreenCanvas 隐藏并绘制到其上时,HTMLCanvasElement 捕获的流在 Chrome 上滞后是否正常?
- visual-c++ - 将 CString::GetString() 与 CWnd::SendMessage() 一起使用是否安全?