我有三个六维 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]
但我希望有一种更直接和更通用的方式
答案 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
,它会在求和轴的结果中保留单个维度,并使结果适合进一步广播。