将阵列提升到另一个阵列的功效-即扩展阵列的尺寸

时间:2019-11-26 19:05:58

标签: python arrays performance numpy matrix

是否有可能使用numpy将数组提升为另一个数组的幂,从而产生的结果的尺寸比输入的尺寸大-即不仅仅是简单地将元素明智地提高为幂。

作为一个简单的示例,我正在计算以下内容。下面是“长手”形式-实际上,这是通过在大型x数组上循环实现的,因此速度很慢。

x = np.arange(4)
t = np.random.rand(3,3)

y = np.empty_like(x)
y[0] = np.sum(x[0]**t)
y[1] = np.sum(x[1]**t)
y[2] = np.sum(x[2]**t)
y[3] = np.sum(x[3]**t)

我希望使用向量化的解决方案来代替每次执行y[i]。但是,由于x的形状为[4],而y的形状为[3,3],因此当我尝试计算x**t时会出现错误。

有没有快速优化的解决方案?

1 个答案:

答案 0 :(得分:2)

直接矢量化方法将与broadcasting-

y = (x[:,None,None]**t).sum((1,2)).astype(x.dtype)

或者使用内置的np.power.outer-

y = np.power.outer(x,t).sum((1,2)).astype(x.dtype)

对于大型阵列,请通过numexpr模块使用多核-

import numexpr as ne

y = ne.evaluate('sum(x3D**t1D,1)',{'x3D':x[:,None],'t1D':t.ravel()}).astype(x.dtype)