Numpy 二维矩阵 乘以 三维矩阵 (Numpy, 2D matrix multiplies 3D matrix)app
Learn to apply the broadcast rule in Numpy.spa
========code
goal: element-wise matrix multiplicationip
arguments:element
A: 2×3×4it
B: 2×4io
C = A*B (* means element-wise multiplication in Numpy)ast
========import
code:numpy
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!