需要某种numpy广播逆汇总操作

时间:2019-02-20 10:09:01

标签: python numpy numpy-broadcasting

我的问题如下:

import numpy as np

# given are two arrays of random, different shapes and sizes
a = np.array(...).reshape(?)
b = np.array(...).reshape(?)

# if broadcasting a and b works
c = a * b
# I want to guarantee that the assignment of the result works too
a += c

如果a.shape == (a * b).shape很明显, 但是如果b是较大的数组,则会失败。

因此,我希望在广播结果较大的情况下 而不是a,而是使用一些reduce运算符对广播的轴进行汇总。

我需要的新broadcast_inverse()函数的预期输出示例:

a = np.array(2)
b = np.ones(6).reshape(2, 3)

# broadcasting a to the shape of b
c = a * b

# now invert the broadcast by accumulating the excess axes
d = broadcast_inverse(c, a.shape, reduce_fun=np.sum)
assert a.shape == d.shape

print('a=', a) # a= 2
print('b=', b) # b= [[1 1 1] [1 1 1]]
print('c=', c) # c= [[2 2 2] [2 2 2]]
print('d=', d) # d= 12

使用2D数组和不同的reduce函数的第二个示例:

a = np.array([[2], [3]])
b = np.arange(2*3).reshape(2, 3) + 1

# broadcasting a to the shape of b
c = a * b

# broadcast inversion using the big product over the excess axes
d = broadcast_inverse(c, a.shape, reduce_fun=np.prod)
assert a.shape == d.shape

print('a=', a) # a= [[2] [3]]
print('b=', b) # b= [[1 2 3] [4 5 6]]
print('c=', c) # c= [[ 2  4  6] [12 15 18]]
print('d=', d) # d= [[  48], [3240]]

我尝试通过遍历形状来做到这一点,但事实证明它相当 很难做到没有错误。因此,我希望有人知道numpy是否公开它将在哪个轴上进行广播,或者有人可能知道其他有趣的有效技巧。我实际上也会对不支持标量数组和其他reduce函数的函数感到满意。 broadcast_inverse只需要支持大于0D的数组和总和减少功能。

0 个答案:

没有答案