NumPy - What is broadcasting?

后端 未结 5 2059
不思量自难忘°
不思量自难忘° 2020-12-03 16:10

I don\'t understand broadcasting. The documentation explains the rules of broadcasting but doesn\'t seem to define it in English. My guess is that broadcasting is when NumPy

5条回答
  •  暖寄归人
    2020-12-03 16:43

    The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations.

    It's basically a way numpy can expand the domain of operations over arrays.

    The only requirement for broadcasting is a way aligning array dimensions such that either:

    • Aligned dimensions are equal.
    • One of the aligned dimensions is 1.

    So, for example if:

    x = np.ndarray(shape=(4,1,3))
    y = np.ndarray(shape=(3,3))
    

    You could not align x and y like so:

    4 x 1 x 3
    3 x 3
    

    But you could like so:

    4 x 1 x 3
        3 x 3
    

    How would an operation like this result?

    Suppose we have:

    x = np.ndarray(shape=(1,3), buffer=np.array([1,2,3]),dtype='int')
    array([[1, 2, 3]])
    
    y = np.ndarray(shape=(3,3), buffer=np.array([1,1,1,1,1,1,1,1,1]),dtype='int')
    array([[1, 1, 1],
           [1, 1, 1],
           [1, 1, 1]])
    

    The operation x + y would result in:

    array([[2, 3, 4],
           [2, 3, 4],
           [2, 3, 4]])
    

    I hope you caught the drift. If you did not, you can always check the official documentation here.

    Cheers!

提交回复
热议问题