numpy broadcasting with 3d arrays

↘锁芯ラ 提交于 2020-05-18 21:46:23

问题


Is it possible to apply numpy broadcasting (with 1D arrays),

x=np.arange(3)[:,np.newaxis]
y=np.arange(3)
x+y=
array([[0, 1, 2],
       [1, 2, 3],
       [2, 3, 4]])

to 3d matricies similar to the one below, such that each element in a[i] is treated as a 1D vector like in the example above?

a=np.zeros((2,2,2))
a[0]=1
b=a
result=a+b

resulting in

result[0,0]=array([[2, 2],
                   [2, 2]])

result[0,1]=array([[1, 1],
                   [1, 1]])

result[1,0]=array([[1, 1],
                   [1, 1]])

result[1,1]=array([[0, 0],
                   [0, 0]])

回答1:


You can do this in the same way as if they are 1d array, i.e, insert a new axis between axis 0 and axis 1 in either a or b:

a + b[:,None]    # or a[:,None] + b

(a + b[:,None])[0,0]
#array([[ 2.,  2.],
#       [ 2.,  2.]])

(a + b[:,None])[0,1]
#array([[ 1.,  1.],
#       [ 1.,  1.]])

(a + b[:,None])[1,0]
#array([[ 1.,  1.],
#       [ 1.,  1.]])

(a + b[:,None])[1,1]
#array([[ 0.,  0.],
#       [ 0.,  0.]])



回答2:


Since a and b are of same shape(2,2,2), a+b will indeed work. The way broadcasting works is it matches the dimension of the operands, starting from the last dimension and goes up. If the dimension match then next dimension is considered.

In case the dimensions don't match AND if one of the dimension is 1 then that operand's dimension is repeated to match the other operand(for e.g. if a.shape=(2,1,2) and b.shape=(2,2,2) then values at 1st dimension of a is repeated to make the shape=(2,2,2))



来源:https://stackoverflow.com/questions/46122743/numpy-broadcasting-with-3d-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!