Numpy, python: automatically expand dimensions of arrays when broadcasting

后端 未结 2 933
再見小時候
再見小時候 2021-02-19 21:36

Consider the following exercise in Numpy array broadcasting.

import numpy as np
v = np.array([[1.0, 2.0]]).T # column array

A2 = np.random.randn(2,10) # 2D arra         


        
相关标签:
2条回答
  • 2021-02-19 21:56

    NumPy broadcasting adds additional axes on the left.

    So if you arrange your arrays so the shared axes are on the right and the broadcastable axes are on the left, then you can use broadcasting with no problem:

    import numpy as np
    v = np.array([[1.0, 2.0]])  # shape (1, 2)
    
    A2 = np.random.randn(10,2) # shape (10, 2)
    A3 = np.random.randn(10,10,2) # shape (10, 10, 2)
    
    v * A2  # shape (10, 2)
    
    v * A3 # shape (10, 10, 2)
    
    0 讨论(0)
  • 2021-02-19 22:22

    It's ugly, but this will work:

    (v.T * A3.T).T
    

    If you don't give it any arguments, transposing reverses the shape tuple, so you can now rely on the broadcasting rules to do their magic. The last transpose returns everything to the right order.

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