向量和矩阵与numpy的逐元素乘法

element wise multiplication of a vector and a matrix with numpy

给定 python 代码与 numpy:

import numpy as np
a = np.arange(6).reshape(3, 2)   # a = [[0, 1], [2, 3], [4, 5]]; a.shape = (3, 2)
b = np.arange(3) + 1             # b = [1, 2, 3]               ; b.shape = (3,)

如何将 b 中的每个值与 a 中的每个对应行 ('vector') 相乘?所以在这里,我想要的结果是:

result = [[0, 1], [4, 6], [12, 15]]    # result.shape = (3, 2)

我可以使用循环来完成此操作,但我想知道矢量化方法。我找到了一个 Octave 解决方案 here。除此之外,我没有找到任何其他东西。有什么指示吗? 提前谢谢你。

可能最简单的就是执行以下操作。

import numpy as np
a = np.arange(6).reshape(3, 2)   # a = [[0, 1], [2, 3], [4, 5]]; a.shape = (3, 2)
b = np.arange(3) + 1  

ans = np.diag(b)@a

这是一个利用 numpy 乘法广播的方法:

ans = (b*a.T).T

这两个解决方案基本上采用相同的方法

ans = np.tile(b,(2,1)).T*a
ans = np.vstack([b for _ in range(a.shape[1])]).T*a
In [123]: a = np.arange(6).reshape(3, 2)   # a = [[0, 1], [2, 3], [4, 5]]; a.
     ...: shape = (3, 2)
     ...: b = np.arange(3) + 1             # b = [1, 2, 3]               ; b.
     ...: shape = (3,)
In [124]: a
Out[124]: 
array([[0, 1],
       [2, 3],
       [4, 5]])

A (3,1) 将通过 broadcasting:

乘以 (3,2)
In [125]: a*b[:,None]
Out[125]: 
array([[ 0,  1],
       [ 4,  6],
       [12, 15]])