NumPy's universal functions requires the input array shape to be consistent, and when the shape of the array is unequal, the broadcast mechanism is used, and the array is adjusted so that shape satisfies the rule, then it can be calculated, otherwise it will be wrong.
The four rules are as follows:
- Let all input arrays match the longest array in the shape, and the insufficient part of shape is padded with 1 in front
- The shape of the output array is the maximum value on each axis of the input array shape
- If an axis of an input array has the same length as the corresponding axis of an output array, or if its length is 1 o'clock, the array can be used to calculate, otherwise an error
- When an axis of an input array has a length of 1 o'clock, the first set of values on this axis are used along this axis
The following examples illustrate these issues
In general, NumPy are calculated using a one by one corresponding method (Element-by-element)
Example 1:
from numpy import array a = array([1.0,2.0,3.0])b = array([2.0,2.0,2.0])a * barray([ 2., 4., 6.])当不相等时,则会采用规则对齐from numpy import arraya = array([1.0,2.0,3.0])b = 2.0a * barray([ 2., 4., 6.])
A.shape Get is (3,) b is a floating-point number, if converted to an array, then B.shape is a (), a 1-axis alignment, the completion of 1,a.shape (3,1), b alignment, then the alignment is (3,1), and then calculated according to the one by one corresponding way
Perhaps the above example is not too clear, the following is a more precise example of the explanation:
import numpy as npa = np.arange(0, 6).reshape(6, 1)a #array([[ 0], [1], [2], [3], [4], [5]])a.shape #(6, 1)b = np.arange(0, 5)b.shape #(5,)c = a + bprint (c)[[0 1 2 3 4] [1 2 3 4 5] [2 3 4 5 6] [3 4 5 6 7] [4 5 6 7 8] [5 6 7 8 9]]
Broadcast in NumPy (broadcasting)