Numpy broadcasting to the 4th dimension: … vs. : vs None

走远了吗. 提交于 2019-11-27 16:25:09

You are stacking the indivdual card results along axis=0. So, when porting to a broadcasting based solution, we can create a range array of those scalars 1, 2, 3, 4 in a 4D array with all axes being singleton dimensions (dims with length = 1) except the first one. There could be different ways to create such a 4D array. One way would be : np.arange(1,5)[:,None,None,None], where we create a 1D array with np.arange and simply add three singleton dims as the last three ones with np.newaxis/None.

We perform equality comparison with this 4D array against b, which would allow internally broadcasting of b elements along the last three dims. Then, we multiply it with a as also done in the original code and get the desired output.

Thus, the implementation would be -

out = a*(b == np.arange(1,5)[:,None,None,None]) 

When/how to use ...(ellipsis) :

We use ...(ellipsis), when trying to add new axes into a multi-dimensional array and we don't want to specify colons per dim. Thus, to make a a 4D array with the last dim being a singleton, we would do : a[:,:,:,None]. Too much of typing! So, we use ... there to help us out : a[...,None]. Please note that this ... notation is used irrespective of the number of dimensions. So, if a were a 5D array and to add a new axis into it as the last one, we would do a[:,:,:,:,:,None] or simply with ellipsis : a[...,None]. Neat huh!

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