假设我们有一堆 3 x 3 矩阵以及一堆 3 维向量:
N = 100
matrices = np.random.rand(N, 3, 3) # shape: (100, 3, 3)
vectors = np.random.rand(N, 3) # shape: (100, 3)
Run Code Online (Sandbox Code Playgroud)
如何执行“逐元素”矩阵/向量乘法,以便eg是与 的result[0]
矩阵/向量乘法产生的3维向量。matrices[0]
vector[0]
由于形状不匹配,使用np.dot
、np.matmul
、 或直接失败。np.prod
是否有广播技巧可以实现此目的?
np.sum(matrices * vectors[:,:,None], axis=(0,1))
Run Code Online (Sandbox Code Playgroud)
None
将虚拟轴添加到将与 的第三个轴匹配的向量中matrices
。OPeinsum
中链接的方法似乎更快:
np.einsum('ijk,ij->k', matrices, vectors)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1922 次 |
最近记录: |