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

后端 未结 1 1684
-上瘾入骨i
-上瘾入骨i 2020-12-04 04:08

In a montecarlo simulation I have the following 7 pokercards for 2 players and 3 different montecarlo runs.

self.cards:

array([[[  6.,  12.],
    [          


        
相关标签:
1条回答
  • 2020-12-04 04:41

    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!

    0 讨论(0)
提交回复
热议问题