NumPy - What is broadcasting?

后端 未结 5 2072
不思量自难忘°
不思量自难忘° 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:35

    Broadcasting is numpy trying to be smart when you tell it to perform an operation on arrays that aren't the same dimension. For example:

    2 + np.array([1,3,5]) == np.array([3, 5, 7])
    

    Here it decided you wanted to apply the operation using the lower dimensional array (0-D) on each item in the higher-dimensional array (1-D).

    You can also add a 0-D array (scalar) or 1-D array to a 2-D array. In the first case, you just add the scalar to all items in the 2-D array, as before. In the second case, numpy will add row-wise:

    In [34]: np.array([1,2]) + np.array([[3,4],[5,6]])
    Out[34]: 
    array([[4, 6],
           [6, 8]])
    

    There are ways to tell numpy to apply the operation along a different axis as well. This can be taken even further with applying an operation between a 3-D array and a 1-D, 2-D, or 0-D array.

提交回复
热议问题