Numpy 二维矩阵 乘以 三维矩阵 (Numpy, 2D matrix multiplies 3D matrix)
Learn to apply the broadcast rule in Numpy.
========
goal: element-wise matrix multiplication
arguments:
A: 2×3×4
B: 2×4
C = A*B (* means element-wise multiplication in Numpy)
========
code:
import numpy as np
A = np.ones([2, 3, 4])
B = np.ones([2, 4])
C = A*B[:, None, :]
Because the dimension of B[:, None, :] is thus 2×1×4, in which the second axis is 1, so it's ok to apply broadcast rule.
That's all!