如何将numpy 2D数组广播到6D阵列

时间:2014-10-03 21:31:15

标签: python arrays numpy broadcast

我有三个六维 Numpy 数组(在python 3.4上运行)的表单

Weights 
MyValue 
WeightedValue  = Weight * MyValue

我想确定MyValue加权Weights的加权平均值。轴 - j(范围从0到4)跨越其他轴,但轴5是常量。

(因此,当j=2时,我们在0,1,3,4之间取得平均值。

然后我打算取这个平均值并乘以Weights并从WeightedValue中减去产品

我打算这样做

NewArray   = WeightedValue - Weight * fn( Weighted Value, Weights )
NewMyValue = NewArray / Weights

fn() MyValue的平均值定义为:

               the sum of Weighted Value using 4 axes ( all except j and 5 )
< divided by >---------------------------------------------------------------
               the sum of Weights across 4 axes       ( all except j and 5 )

我的问题如下:

平均值是2D数组,我需要fn()来生成6D阵列,即广播 2D结果而不是其他4维

我可以作为最后的手段创建一系列循环来迭代轴j和轴5。对于第二轴(j = 1),循环如下

import numpy as np
result = np.zeros((dim0,dim1,dim2,dim3,dim4,dim5))
for var1 in range(dim1):
    for var5 in range(dim5):
        result[:,dim1,:,:,:,dim5] = AverageValue[dim1,dim5]  

但我希望有一种更直接和更通用的方式

1 个答案:

答案 0 :(得分:1)

取代fn你可以使用:

j = 1;
axes = tuple({0,1,2,3,4} - {j})
fn = WeightedValue.sum(axes, keepdims=True) / Weights.sum(axes, keepdims=True)

显然关键是要传递keepdims=True,它会在求和轴的结果中保留单个维度,并使结果适合进一步广播。