首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >加速R中大数组的平方误差计算

加速R中大数组的平方误差计算
EN

Stack Overflow用户
提问于 2015-07-06 17:50:22
回答 1查看 44关注 0票数 1

基本上,我是在帮助某人为他们的研究写一些代码,但我通常的节省时间的策略并没有减少她的算法的运行时间,使其变得合理。我希望其他人可以根据我写的一个例子知道更好的方法来让函数快速运行,以避免包含有关研究的信息。

示例中的对象比她使用的对象小(但可以很容易地变大)。对于实际的算法,这一部分在小情况下大约需要3分钟,但在完整的情况下可能需要8-10分钟,并且需要运行1000-10000次。这就是我需要认真减少运行时间的原因。

我现在是如何做到这一点的(希望有足够的评论让我的思考过程变得显而易见):

代码语言:javascript
复制
example<-array(rnorm(100000), dim=c(5, 25, 40, 20))

observation <- array(rnorm(600), dim=c(5, 5, 12))

calc.err<-function(value, observation){
  #'This creates the squared error for each observation, and each point in the
  #'example array, across the five values in the first dimension of each

  sqError<-(value-observation)^2

  #'the apply function here sums up the squared error for each observation and
  #'point.  This is the value returned

  return(apply(sqError, c(2,3), function(x) sum(x)))
}

run<-apply(example, c(2,3,4), function(x) calc.err(x, observation))

#'It isn't returned in the right format (small problem) but reformatting is fast
format<-array(run, dim=c(5, 12, 25, 40, 20))

如有必要,我将予以澄清。

编辑: data.table包似乎非常有用。我将不得不学习这个包,但初学者似乎要快得多。我猜我是在使用数组,因为她给我的代码让我更快地将对象格式化为数组。我根本没想过要改变它

EN

回答 1

Stack Overflow用户

发布于 2015-07-07 00:44:56

这里有几个简单的重构和计时:

代码语言:javascript
复制
calc.err2 <- function(value, observation){
  #'This creates the squared error for each observation, and each point in the
  #'example array, across the five values in the first dimension of each

  sqError<-(value-observation)^2

  #' getting rid of the anonymous function

  apply(sqError, c(2,3), sum)
}

calc.err3 <- function(value, observation){
  #'This creates the squared error for each observation, and each point in the
  #'example array, across the five values in the first dimension of each

  sqError<-(value-observation)^2

  #' replacing with colSums

  colSums(sqError)
}


R>microbenchmark(times=8, apply(example, 2:4, calc.err, observation),
+   apply(example, 2:4, calc.err2, observation),
+   apply(example, 2:4, calc.err3, observation)
+ )
Unit: milliseconds
                                        expr         min          lq
  apply(example, 2:4, calc.err, observation) 2284.350162 2321.875878
 apply(example, 2:4, calc.err2, observation) 2194.316755 2257.007572
 apply(example, 2:4, calc.err3, observation)  645.004808  652.567611
         mean       median           uq         max neval
 2349.7524509 2336.6661645 2393.3452420 2409.894876     8
 2301.7896566 2298.9346090 2362.5479790 2383.020177     8
  681.3176878  667.9070175  720.7049605  723.177516     8

colSums比相应的apply快得多。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31242671

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档