想要理解Numpy的广播(boardcast)机制最好的参考文档肯定是numpy自己写的,这里放上链接:添加链接描述
以下是Numpy官方文档对广播的解释
我对Numpy中广播机制的理解是:
Numpy在对两个数组进行操作时,它会从两个数组shape的最右侧开始比较,例如:
即A.shape中的每个元素与B.shape中的每个元素从最右侧开始比较,满足以下条件之一则可以触发广播机制:
1) A.shape 与B.shape中的对应元素值相等
2) A.shape 与B.shape中的对应元素值其中有一个为1
例如:
满足条件一的:
import numpy as np
x = np.arange(12)
xx = x.reshape(2,2,-1)
print(xx)
print(xx.shape)
#结果:
[[[ 0 1 2]
[ 3 4 5]]
[[ 6 7 8]
[ 9 10 11]]]
(2, 2, 3)
y = np.arange(3)
print(y)
print(y.shape)
#结果:
[0 1 2]
(3,)
# 此时对应最后一位元素值相等,可以进行广播
z = y+xx
print(z)
# 结果:
array([[ 0, 2, 4],
[ 3, 5, 7],
[ 6, 8, 10],
[ 9, 11, 13]])
满足条件二的:
#接上面的例子
yy = y.reshape(1,3)
print(yy.shape)
# 结果:
(1, 3)
# 与xx.shape (2, 2, 3)相比,最后一位相同,前一位一个为1,一个为2,满足条件二,也可以进行广播
zz = yy+xx
print(zz)
#结果:
array([[[ 0, 2, 4],
[ 3, 5, 7]],
[[ 6, 8, 10],
[ 9, 11, 13]]])
在举一些例子:
a = np.arange(120)
aa = a.reshape(2,3,4,-1)
print(aa)
array([[[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[ 10, 11, 12, 13, 14],
[ 15, 16, 17, 18, 19]],
[[ 20, 21, 22, 23, 24],
[ 25, 26, 27, 28, 29],
[ 30, 31, 32, 33, 34],
[ 35, 36, 37, 38, 39]],
[[ 40, 41, 42, 43, 44],
[ 45, 46, 47, 48, 49],
[ 50, 51, 52, 53, 54],
[ 55, 56, 57, 58, 59]]],
[[[ 60, 61, 62, 63, 64],
[ 65, 66, 67, 68, 69],
[ 70, 71, 72, 73, 74],
[ 75, 76, 77, 78, 79]],
[[ 80, 81, 82, 83, 84],
[ 85, 86, 87, 88, 89],
[ 90, 91, 92, 93, 94],
[ 95, 96, 97, 98, 99]],
[[100, 101, 102, 103, 104],
[105, 106, 107, 108, 109],
[110, 111, 112, 113, 114],
[115, 116, 117, 118, 119]]]])
print(aa.shape)
(2, 3, 4, 5)
b = np.arange(15)
bb = b.reshape(3,1,5)
print(bb.shape)
(3, 1, 5)
# 满足广播条件
c = aa+bb
print(c)
array([[[[ 0, 2, 4, 6, 8],
[ 5, 7, 9, 11, 13],
[ 10, 12, 14, 16, 18],
[ 15, 17, 19, 21, 23]],
[[ 25, 27, 29, 31, 33],
[ 30, 32, 34, 36, 38],
[ 35, 37, 39, 41, 43],
[ 40, 42, 44, 46, 48]],
[[ 50, 52, 54, 56, 58],
[ 55, 57, 59, 61, 63],
[ 60, 62, 64, 66, 68],
[ 65, 67, 69, 71, 73]]],
[[[ 60, 62, 64, 66, 68],
[ 65, 67, 69, 71, 73],
[ 70, 72, 74, 76, 78],
[ 75, 77, 79, 81, 83]],
[[ 85, 87, 89, 91, 93],
[ 90, 92, 94, 96, 98],
[ 95, 97, 99, 101, 103],
[100, 102, 104, 106, 108]],
[[110, 112, 114, 116, 118],
[115, 117, 119, 121, 123],
[120, 122, 124, 126, 128],
[125, 127, 129, 131, 133]]]])
举一个不满足广播条件的例子
e = np.arange(120)
ee = e.reshape(2,5,4,-1)
print(ee.shape)
# 结果:
(2, 5, 4, 3)
f = np.arange(3)
ff = f.reshape(3,1,1,1)
print(ff.shape)
# 结果:
(3, 1, 1, 1)
kk = ee+ff
报错: