Numpy operator for multiple outer products

末鹿安然 提交于 2020-01-30 06:10:05

问题


import numpy as np
mat1 = np.random.rand(2,3)
mat2 = np.random.rand(2,5)

I wish to get a 2x3x5 tensor, where each layer is the 3x5 outer product achieved by multiplying 3x1 transposed row of mat1 by 1x5 row of mat2.

Can it be done with numpy matmul?


回答1:


You can simply use broadcasting after extending their dimensions with np.newaxis/None -

mat1[...,None]*mat2[:,None]

This would be the most performant, as there's no sum-reduction needed here to warrant services from np.einsum or np.matmul.

If you still want to drag in np.matmul, it would be basically same as with the broadcasting one :

np.matmul(mat1[...,None],mat2[:,None])

With np.einsum, it might be look a bit more tidy than others, if you are familiar with its string notation -

np.einsum('ij,ik->ijk',mat1,mat2)
#          23,25->235  (to explain einsum's string notation using axes lens)


来源:https://stackoverflow.com/questions/44141966/numpy-operator-for-multiple-outer-products

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!