尝试用 numpy 向量化迭代计算 [英] Trying to vectorize iterative calculation with numpy
问题描述
我试图通过在 numpy 中使用矢量化形式来使某些代码更高效.让我给你举个例子,让你明白我的意思.
I am trying to make some piece of code more efficient by using the vectorized form in numpy. Let me show you an example so you know what I mean.
给定以下代码:
a = np.zeros([4,4])
a[0] = [1., 2., 3., 4.]
for i in range(len(a)-1):
a[i+1] = 2*a[i]
print a
输出
[[ 1. 2. 3. 4.]
[ 2. 4. 6. 8.]
[ 4. 8. 12. 16.]
[ 8. 16. 24. 32.]]
当我现在尝试像这样矢量化代码时:
When I now try to vectorize the code like this:
a = np.zeros([4,4])
a[0] = [1., 2., 3., 4.]
a[1:] = 2*a[0:-1]
print a
我刚刚得到正确的第一次迭代:
I just get the first iteration correct:
[[ 1. 2. 3. 4.]
[ 2. 4. 6. 8.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
是否可以以矢量化形式(其中下一次迭代始终访问前一次迭代)有效地编写上述代码,还是必须保持 for
循环?
Is it possible to write the code above efficiently in a vectorized form (where the next iteration always accesses the previous iteration) or do I have to keep the for
loop?
推荐答案
可以使用 scipy.signal.lfilter
:
In [19]: from scipy.signal import lfilter
In [20]: num = np.array([1.0])
In [21]: alpha = 2.0
In [22]: den = np.array([1.0, -alpha])
In [23]: a = np.zeros((4,4))
In [24]: a[0,:] = [1,2,3,4]
In [25]: lfilter(num, den, a, axis=0)
Out[25]:
array([[ 1., 2., 3., 4.],
[ 2., 4., 6., 8.],
[ 4., 8., 12., 16.],
[ 8., 16., 24., 32.]])
有关更多详细信息,请参阅以下内容:python 递归向量化与时间序列, Pandas 中的递归定义
See the following for more details: python recursive vectorization with timeseries, Recursive definitions in Pandas
请注意,使用 lfilter
只有在解决非齐次问题时才有意义,例如 x[i+1] = alpha*x[i] + u[i]
,其中 u
是给定的输入数组.对于简单的递归a[i+1] = alpha*a[i]
,可以使用精确解a[i] = a[0]*alpha**i代码>.可以使用广播对多个初始值的解决方案进行矢量化.例如,
Note that using lfilter
really only makes sense if you are solving a nonhomogeneous problem such as x[i+1] = alpha*x[i] + u[i]
, where u
is a given input array. For the simple recurrence a[i+1] = alpha*a[i]
, you can use the exact solution a[i] = a[0]*alpha**i
. The solution for multiple initial values can be vectorized using broadcasting. For example,
In [271]: alpha = 2.0
In [272]: a0 = np.array([1, 2, 3, 4])
In [273]: n = 5
In [274]: a0 * (alpha**np.arange(n).reshape(-1, 1))
Out[274]:
array([[ 1., 2., 3., 4.],
[ 2., 4., 6., 8.],
[ 4., 8., 12., 16.],
[ 8., 16., 24., 32.],
[ 16., 32., 48., 64.]])
这篇关于尝试用 numpy 向量化迭代计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!