彼得的问题真好。这是你的答案:
import numpy as np
def get_broadcast_shape(*shapes):
'''
Given a set of array shapes, return the shape of the output when arrays of those
shapes are broadcast together
'''
max_nim = max(len(s) for s in shapes)
equal_len_shapes = np.array([(1, )*(max_nim-len(s))+s for s in shapes])
max_dim_shapes = np.max(equal_len_shapes, axis = 0)
assert np.all(np.bitwise_or(equal_len_shapes==1, equal_len_shapes == max_dim_shapes[None, :])), \
'Shapes %s are not broadcastable together' % (shapes, )
return tuple(max_dim_shapes)
def get_broadcast_indeces(*shapes):
'''
Given a set of shapes of arrays that you could broadcast together, return:
output_shape: The shape of the resulting output array
broadcast_shape_iterator: An iterator that returns a len(shapes)+1 tuple
of the indeces of each input array and their corresponding index in the
output array
'''
output_shape = get_broadcast_shape(*shapes)
base_iter = np.ndindex(output_shape)
def broadcast_shape_iterator():
for out_ix in base_iter:
in_ixs = tuple(tuple(0 if s[i] == 1 else ix for i, ix in enumerate(out_ix[-len(s):])) for s in shapes)
yield in_ixs + (out_ix, )
return output_shape, broadcast_shape_iterator()
output_shape, ix_iter = get_broadcast_indeces((2, 2, 1), (2, 3))
assert output_shape == (2, 2, 3)
for in1_ix, in_2_ix, out_ix in ix_iter:
print (in1_ix, in_2_ix, out_ix)
返回
((0, 0, 0), (0, 0), (0, 0, 0))
((0, 0, 0), (0, 1), (0, 0, 1))
((0, 0, 0), (0, 2), (0, 0, 2))
((0, 1, 0), (1, 0), (0, 1, 0))
((0, 1, 0), (1, 1), (0, 1, 1))
((0, 1, 0), (1, 2), (0, 1, 2))
((1, 0, 0), (0, 0), (1, 0, 0))
((1, 0, 0), (0, 1), (1, 0, 1))
((1, 0, 0), (0, 2), (1, 0, 2))
((1, 1, 0), (1, 0), (1, 1, 0))
((1, 1, 0), (1, 1), (1, 1, 1))
((1, 1, 0), (1, 2), (1, 1, 2))
如果有人知道任何解决此问题的 numpy 内置函数,那会更好。