ufunc () function of the broadcast mechanism

Refers to a broadcasting mode performs arithmetic operation between an array of different shapes, to follow four principles:

1. The input arrays are all in line to the longest array shape, it is less than some shape preceded by a filled

2. The input array shape is the maximum value of the respective input shaft of the shape of the array

3. If the same axis corresponding to an axis of the input array and output array length or a length of 1, the array can be used to calculate, or error.

4. When the length of an axis of the input array is 1, along the axis of this computation with a first set of values ​​are from this axis.

import numpy as np

# 创建数组
arr1 = np.array([[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]])
print('arr1:', arr1)
print('arr1形状:', arr1.shape)

arr2 = np.array([[1, 2, 3, 4]])
print('arr2:', arr2)
print('arr2形状:', arr2.shape)

arr3 = np.array([[1, 2, 3, 4], [0, 1, 2, 3]])
print('arr3:', arr3)
print('arr3形状:', arr3.shape)

# 执行上述两个数组相加
arr_new = arr1 + arr2
print('arr_new:', arr_new)

# 不满足广播机制
arr_new = arr1 + arr3
print('arr_new:', arr_new)

"""
让所有的shape向最长的看齐
arr1 (2,4,5)
arr2 (4,1) 补齐 (1,4,1)
arr3 (5,)  补齐 (1,5,1)
"""

 

Guess you like

Origin blog.csdn.net/g_optimistic/article/details/92010819