问题描述
我有一个大小为(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)
由于文档状态:
Theano具有 batched_dot 类似的功能,因此会是
Theano has similar functionaly of batched_dot so it would be
C = theano.tensor.batched_dot(A, B)
这篇关于numpy和theano中的3D矩阵乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!