多个外积的 Numpy 运算符 [英] Numpy operator for multiple outer products

查看:50
本文介绍了多个外积的 Numpy 运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我希望得到一个 2x3x5 的张量,其中每一层都是通过将 mat1 的 3x1 转置行乘以 mat2 的 1x5 行获得的 3x5 外积.

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.

用 numpy matmul 可以吗?

Can it be done with numpy matmul?

推荐答案

您可以简单地使用 broadcasting 在使用 np.newaxis/None -

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

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

这将是最高效的,因为这里不需要 sum-reduction 来保证 np.einsumnp.matmul 的服务.

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

如果你还想拖进去np.matmul,基本上和broadcasting一样:

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])

使用 np.einsum,如果你熟悉它的字符串表示法,它可能看起来比其他的更整洁 -

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)

这篇关于多个外积的 Numpy 运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆