[英]Block scalar-vector multiplication in numpy
I have a large 1-dimensional array x
which I've got by concatenation of smaller arrays x_0 ,..., x_m-1
of different length. 我有一个大的1维数组
x
,我通过串联不同长度的较小数组x_0 ,..., x_m-1
得到了这个数组。 I also know the list L
of the length of each x_i
. 我也知道每个
x_i
长度的列表L
Given an array a
of length m
, the goal is to compute a flat array [a[0]*x0, a[1]*x1,...]
. 给定长度为
m
的数组a
,目标是计算平面数组[a[0]*x0, a[1]*x1,...]
。
For example, if I have x = np.array([1,2,3,4,5])
and a=np.array([2,-1]), L = [2,3]
, then the result should be np.array([2,4,-3,-4,-5])
例如,如果我有
x = np.array([1,2,3,4,5])
和a=np.array([2,-1]), L = [2,3]
,那么结果应该是np.array([2,4,-3,-4,-5])
Is there any simpler (faster, more pythonic, etc.) way to do this in numpy, than this naive implementation? 有没有比这个天真的实现更简单(更快,更pythonic等)的方式来做这个numpy?
L.insert(0,0)
cs = np.cumsum(L)
y = np.empty(x.shape)
for i in range(m):
y[cs[i]:cs[i+1]] = a[i] * x[cs[i]:cs[i+1]]
I can also do this in Numba. 我也可以在Numba做到这一点。
m
is of order of hundreds, the length of each x_i
is around 1e6. m
大约为数百,每个x_i
的长度约为1e6。
重复的元素a
与np.repeat
和执行的elementwise乘法-
y = x*np.repeat(a,L)
Out of place Numba version 不合适的Numba版本
@nb.njit(fastmath=True)
def mult(x,a,L):
out=np.empty(x.shape[0],dtype=x.dtype)
ii=0
for i in range(L.shape[0]):
for j in range(L[i]):
out[ii]=x[ii]*a[i]
ii+=1
return out
In place Numba version 到位Numba版本
@nb.njit(fastmath=True)
def mult(x,a,L):
ii=0
for i in range(L.shape[0]):
for j in range(L[i]):
x[ii]=x[ii]*a[i]
ii+=1
return x
Timings 计时
L=np.random.randint(low=1000,high=2000,size=500)
x=np.random.rand(L.sum())
a=np.random.rand(L.shape[0])
Divakar's version: 6.4ms
Out of place Numba version: 2.8ms
In place Numba version: 1.2ms
Please note that the first call to the Numba versions takes longer (compilation overhead). 请注意,对Numba版本的第一次调用需要更长时间(编译开销)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.