numpy和theano中的3D矩阵乘法 [英] 3D Matrix multiplication in numpy and theano

查看:123
本文介绍了numpy和theano中的3D矩阵乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大小为(5,7,3)的矩阵A和一个大小为(5,3,8)的矩阵B.我想将它们乘以C = A.B,而C的大小为(5,7,8).

I have a matrix A with size (5,7,3) and a matrix B with size (5,3,8). I want to multiply them C = A.B, and the size of C is (5,7,8).

这意味着矩阵A中一个大小为(7,3)的2D子矩阵将分别与矩阵B中一个大小为(3,8)的2D子矩阵相乘.所以我必须乘以5倍.

It means that one 2D submatrix with size (7,3) in matrix A will be multiplied with one 2D submatrix with size (3,8) in matrix B respectively. So I have to multiply 5 times.

最简单的方法是使用循环和numpy:

The simplest way is using a loop and numpy:

for u in range(5):
    C[u] = numpy.dot(A[u],B[u])

有没有不用循环就可以做到这一点的方法? Theano中有没有等效的方法可以在不使用扫描的情况下执行此操作?

Is there any way to do this without using a loop? Is there any equivalent method in Theano to do this without using scan?

推荐答案

可以简单地在numpy中使用np.einsum来完成.

Can be done pretty simply with np.einsum in numpy.

C = numpy.einsum('ijk,ikl->ijl', A, B)

它也可以简单地是:

C = numpy.matmul(A,B)

由于文档状态:

如果任何一个参数为N-D,N> 2,则将其视为位于最后两个索引中并相应广播的一组矩阵

If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly

Theano具有 batched_dot 类似的功能,因此会是

Theano has similar functionaly of batched_dot so it would be

C = theano.tensor.batched_dot(A, B)

这篇关于numpy和theano中的3D矩阵乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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