本文介绍了对依赖于先前元素的乘积计算进行矢量化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试加速/矢量化时间序列中的一些计算.我可以在依赖于早期迭代结果的 for 循环中矢量化计算吗?例如:

I'm trying to speed up/vectorize some calculations in a time series.Can I vectorize a calculation in a for loop which can depend on results from an earlier iteration? For example:

z <- c(1,1,0,0,0,0)
zi <- 2:6
for  (i in zi) {z[i] <- ifelse (z[i-1]== 1, 1, 0) }

使用在前面步骤中更新的 z[i] 值:

uses the z[i] values updated in earlier steps:

> z
[1] 1 1 1 1 1 1

我努力将其矢量化

z <- c(1,1,0,0,0,0)
z[zi] <- ifelse( z[zi-1] == 1, 1, 0)

逐个元素的操作不使用操作中更新的结果:

the element-by-element operations don't use results updated in the operation:

> z
[1] 1 1 1 0 0 0

所以这个向量化操作以并行"而不是迭代方式运行.有没有办法可以编写/向量化它以获得 for 循环的结果?

So this vectorized operation operates in 'parallel' rather than iterative fashion. Is there a way I can write/vectorize this to get the results of the for loop?

推荐答案

ifelse 是矢量化的,如果您在 for- 中一次在一个元素上使用它,则会受到一些惩罚 -环形.在您的示例中,您可以通过使用 if 而不是 ifelse 来获得相当不错的加速.

ifelse is vectorized and there's a bit of a penalty if you're using it on one element at a time in a for-loop. In your example, you can get a pretty good speedup by using if instead of ifelse.

fun1 <- function(z) {
  for(i in 2:NROW(z)) {
    z[i] <- ifelse(z[i-1]==1, 1, 0)
  }
  z
}

fun2 <- function(z) {
  for(i in 2:NROW(z)) {
    z[i] <- if(z[i-1]==1) 1 else 0
  }
  z
}

z <- c(1,1,0,0,0,0)
identical(fun1(z),fun2(z))
# [1] TRUE
system.time(replicate(10000, fun1(z)))
#   user  system elapsed 
#   1.13    0.00    1.32
system.time(replicate(10000, fun2(z)))
#   user  system elapsed 
#   0.27    0.00    0.26 

您可以通过编译 fun2 获得一些额外的速度提升.

You can get some additional speed gains out of fun2 by compiling it.

library(compiler)
cfun2 <- cmpfun(fun2)
system.time(replicate(10000, cfun2(z)))
#   user  system elapsed 
#   0.11    0.00    0.11

因此,无需矢量化即可实现 10 倍的加速.正如其他人所说(有些人已经说明),有一些方法可以对您的示例进行矢量化,但这可能不会转化为您的实际问题.希望这足够通用以适用.

So there's a 10x speedup without vectorization. As others have said (and some have illustrated) there are ways to vectorize your example, but that may not translate to your actual problem. Hopefully this is general enough to be applicable.

filter 函数也可能对您有用,如果您能弄清楚如何用自回归或移动平均过程来表达您的问题.

The filter function may be useful to you as well if you can figure out how to express your problem in terms of a autoregressive or moving average process.

这篇关于对依赖于先前元素的乘积计算进行矢量化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-17 01:01