Numpy 简明教程
NumPy - Broadcasting
术语 broadcasting 指的是 NumPy 在算术运算期间处理不同形状的数组的能力。数组上的算术运算通常在对应元素上执行。如果两个数组的形状完全相同,那么这些运算就会顺畅执行。
The term broadcasting refers to the ability of NumPy to treat arrays of different shapes during arithmetic operations. Arithmetic operations on arrays are usually done on corresponding elements. If two arrays are of exactly the same shape, then these operations are smoothly performed.
Example 1
import numpy as np
a = np.array([1,2,3,4])
b = np.array([10,20,30,40])
c = a * b
print c
它的输出如下:
Its output is as follows −
[10 40 90 160]
如果两个数组的维度不同,则逐元素运算是不可能的。然而,由于广播功能,NumPy 中仍然可以对形状不相同的数组进行运算。较小的数组会被 broadcast 为较大数组的大小,以便它们具有兼容的形状。
If the dimensions of two arrays are dissimilar, element-to-element operations are not possible. However, operations on arrays of non-similar shapes is still possible in NumPy, because of the broadcasting capability. The smaller array is broadcast to the size of the larger array so that they have compatible shapes.
如果满足以下规则,广播是可能的 −
Broadcasting is possible if the following rules are satisfied −
-
Array with smaller ndim than the other is prepended with '1' in its shape.
-
Size in each dimension of the output shape is maximum of the input sizes in that dimension.
-
An input can be used in calculation, if its size in a particular dimension matches the output size or its value is exactly 1.
-
If an input has a dimension size of 1, the first data entry in that dimension is used for all calculations along that dimension.
如果上述规则产生了有效的结果,并且满足以下条件之一,则一组数组被称作 broadcastable −
A set of arrays is said to be broadcastable if the above rules produce a valid result and one of the following is true −
-
Arrays have exactly the same shape.
-
Arrays have the same number of dimensions and the length of each dimension is either a common length or 1.
-
Array having too few dimensions can have its shape prepended with a dimension of length 1, so that the above stated property is true.
以下程序展示了一个广播示例。
The following program shows an example of broadcasting.
Example 2
import numpy as np
a = np.array([[0.0,0.0,0.0],[10.0,10.0,10.0],[20.0,20.0,20.0],[30.0,30.0,30.0]])
b = np.array([1.0,2.0,3.0])
print 'First array:'
print a
print '\n'
print 'Second array:'
print b
print '\n'
print 'First Array + Second Array'
print a + b
此程序的输出如下:
The output of this program would be as follows −
First array:
[[ 0. 0. 0.]
[ 10. 10. 10.]
[ 20. 20. 20.]
[ 30. 30. 30.]]
Second array:
[ 1. 2. 3.]
First Array + Second Array
[[ 1. 2. 3.]
[ 11. 12. 13.]
[ 21. 22. 23.]
[ 31. 32. 33.]]
下图演示了如何将数组 b 广播为与 a 兼容。
The following figure demonstrates how array b is broadcast to become compatible with a.