Numpy Broadcasting

只愿长相守 提交于 2019-12-31 04:04:09

问题


What happens when i make this operation in Numpy?

a = np.ones([500,1])
b = np.ones([5000,])/2
c = a + b 

# a.shape (500,1)
# b.shape (5000, )
# c.shape (500, 5000)

I'm having a hard time to figure out what is actually happening in this broadcast.


回答1:


Numpy assumes for 1 dimensional arrays row vectors, so your summation is indeed between shapes (500, 1) and (1, 5000), which leads to matrix summation.

Since this is not very clear, you should extend your dimensions explicitly:

>>> np.arange(5)[:, None] + np.arange(8)[None, :]
array([[ 0,  1,  2,  3,  4,  5,  6,  7],
       [ 1,  2,  3,  4,  5,  6,  7,  8],
       [ 2,  3,  4,  5,  6,  7,  8,  9],
       [ 3,  4,  5,  6,  7,  8,  9, 10],
       [ 4,  5,  6,  7,  8,  9, 10, 11]])


来源:https://stackoverflow.com/questions/42304313/numpy-broadcasting

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