【问题标题】:How to broadcast a numpy 2D-array to a 6D-array如何将 numpy 2D 数组广播到 6D 数组
【发布时间】:2014-10-03 21:31:14
【问题描述】:

我有三个六维 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 )

我的问题如下:

平均值是一个二维数组,我需要 fn() 来生成一个 6 维数组,即广播其他 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]  

但我希望有更直接和通用的方法

【问题讨论】:

  • 考虑添加独立运行的示例代码。如果您知道如何使用循环执行此操作,请使用它们,我们可以帮助您删除它们。查看'how to ask a good question'
  • 一个我们可以运行的小例子,以及你想要的那个例子的输出,会很有帮助。这样,潜在的回答者就会确切地知道您要做什么。

标签: python arrays numpy broadcast


【解决方案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,它会在求和轴的结果中保留单一维度,并使结果适合进一步广播。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-18
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2012-06-08
    • 1970-01-01
    相关资源
    最近更新 更多