Numpy array broadcasting rules

后端 未结 2 1873
迷失自我
迷失自我 2020-12-14 07:47

I\'m having some trouble understanding the rules for array broadcasting in Numpy.

Obviously, if you perform element-wise multiplication on two arrays of the same dim

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-14 08:01

    From http://cs231n.github.io/python-numpy-tutorial/#numpy-broadcasting:

    Broadcasting two arrays together follows these rules:

    1. If the arrays do not have the same rank, prepend the shape of the lower rank array with 1s until both shapes have the same length.

    2. The two arrays are said to be compatible in a dimension if they have the same size in the dimension, or if one of the arrays has size 1 in that dimension.

    3. The arrays can be broadcast together if they are compatible in all dimensions.
    4. After broadcasting, each array behaves as if it had shape equal to the elementwise maximum of shapes of the two input arrays.
    5. In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension

    If this explanation does not make sense, try reading the explanation from the documentation or this explanation.

提交回复
热议问题