广播规则:从最右侧开始广播。
Broadcasting — NumPy v1.25 Manual 截图
下面给出一些样例:
三维矩阵广播
a = np.array([[[0,0],
[0,0]],
[[0, 0],
[0, 0]]
])
print('-'*10, 'a', '-'*10)
print(a.shape)
print(a)
b = np.array([[[1]],
[[2]]])
print('-'*10, 'b', '-'*10)
print(b.shape)
print(b)
c = b - a
print('-'*10, 'a-b', '-'*10)
print(c.shape)
print(c)
运行结果:
---------- a ----------
(2, 2, 2)
[[[0 0]
[0 0]]
[[0 0]
[0 0]]]
---------- b ----------
(2, 1, 1)
[[[1]]
[[2]]]
---------- a-b ----------
(2, 2, 2)
[[[1 1]
[1 1]]
[[2 2]
[2 2]]]
三维矩阵向四维矩阵广播
a = np.array([[[[0,0],
[0,0]],
[[0, 0],
[0, 0]]],
[[[0,0],
[0,0]],
[[0, 0],
[0, 0]]]
])
print('-'*10, 'a', '-'*10)
print(a.shape)
print(a)
b = np.array([[[1]],
[[2]]])
print('-'*10, 'b', '-'*10)
print(b.shape)
print(b)
c = b - a
print('-'*10, 'a-b', '-'*10)
print(c.shape)
print(c)
运行结果:
---------- a ----------
(2, 2, 2, 2)
[[[[0 0]
[0 0]]
[[0 0]
[0 0]]]
[[[0 0]
[0 0]]
[[0 0]
[0 0]]]]
---------- b ----------
(2, 1, 1)
[[[1]]
[[2]]]
---------- a-b ----------
(2, 2, 2, 2)
[[[[1 1]
[1 1]]
[[2 2]
[2 2]]]
[[[1 1]
[1 1]]
[[2 2]
[2 2]]]]
四维矩阵广播
a = np.array([[[[0,0],
[0,0]],
[[0, 0],
[0, 0]]],
[[[0,0],
[0,0]],
[[0, 0],
[0, 0]]]
])
print('-'*10, 'a', '-'*10)
print(a.shape)
print(a)
b = np.array([[[[1]]],
[[[2]]]])
print('-'*10, 'b', '-'*10)
print(b.shape)
print(b)
c = b - a
print('-'*10, 'a-b', '-'*10)
print(c.shape)
print(c)
运行结果:
---------- a ----------
(2, 2, 2, 2)
[[[[0 0]
[0 0]]
[[0 0]
[0 0]]]
[[[0 0]
[0 0]]
[[0 0]
[0 0]]]]
---------- b ----------
(2, 1, 1, 1)
[[[[1]]]
[[[2]]]]
---------- a-b ----------
(2, 2, 2, 2)
[[[[1 1]
[1 1]]
[[1 1]
[1 1]]]
[[[2 2]
[2 2]]
[[2 2]
[2 2]]]]