Numpy 简单教程(四)详解Numpy中的广播(broadca
2020-08-16 本文已影响0人
超级超级小天才
更过的Numpy教程连载内容:https://www.jianshu.com/nb/47449944
详解Numpy中的广播(broadcasting)
广播(broadcasting)是指当两个形状不同的数组进行运算时,Numpy有能力灵活地改变其中某个(些)数组的形状从而使得运算可以正常的进行。一个非常简单的例子是:
a = np.array([1.0, 2.0, 3.0])
b = np.array([2.0, 2.0, 2.0])
print(a * b)
------
array([ 2., 4., 6.])
当使用一个标量作为b进行运算时依然可以得到相同的效果:
a = np.array([1.0, 2.0, 3.0])
b = 2.0
print(a * b)
------
array([ 2., 4., 6.])
这里其实就是广播的结果,而且第二种比第一种更高效
而广播遵循一定的规则,当两个数组所有对应的维度都满足如下的任意条件则两个维度是兼容的(compatible):
- 两个维度的大小相等
- 其中一个维度大小为1
如果两个维度大小一致,自然可以进行一一对应的运算;如果其中一个维度大小为1,而另一个不是1(比如是N),则前者会将该维度沿着其他轴的方向复制N次使其与后者一致。




一些例子:
>>> x = np.arange(4)
>>> xx = x.reshape(4,1)
>>> y = np.ones(5)
>>> z = np.ones((3,4))
>>> x.shape
(4,)
>>> y.shape
(5,)
>>> x + y
ValueError: operands could not be broadcast together with shapes (4,) (5,)
>>> xx.shape
(4, 1)
>>> y.shape
(5,)
>>> (xx + y).shape
(4, 5)
>>> xx + y
array([[ 1., 1., 1., 1., 1.],
[ 2., 2., 2., 2., 2.],
[ 3., 3., 3., 3., 3.],
[ 4., 4., 4., 4., 4.]])
>>> x.shape
(4,)
>>> z.shape
(3, 4)
>>> (x + z).shape
(3, 4)
>>> x + z
array([[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.]])