NumPy - What is broadcasting?

后端 未结 5 2073
不思量自难忘°
不思量自难忘° 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条回答
  •  旧时难觅i
    2020-12-03 16:39

    >>> x = np.array([1,3,5])
    >>> y = np.array([2,4])
    >>> x+y
    *** ValueError: operands could not be broadcast together with shapes (3,) (2,)
    

    Broadcasting is how numpy do math operations with array of different shapes. Shapes are the format the array has, for example the array you used, x , has 3 elements of 1 dimension; y has 2 elements and 1 dimension.

    To perform broadcasting there are 2 rules: 1) Array have the same dimensions(shape) or 2)The dimension that doesn't match equals one.

    for example x has shape(2,3) [or 2 lines and 3 columns]; y has shape(2,1) [or 2 lines and 1 column]

    Can you add them? x + y? Answer: Yes, because the mismatched dimension is equal to 1 (the column in y). If y had shape(2,4) broadcasting would not be possible, because the mismatched dimension is not 1.

    In the case you posted: operands could not be broadcast together with shapes (3,) (2,); it is because 3 and 2 mismatched altough both have 1 line.

提交回复
热议问题