简体   繁体   English

如何制作2D和3D矩阵的点积(分别针对每个维进行计算)

[英]How to make dot.product of 2D and 3D matrices (taking it for each dimension separately)

I need to calculate dot product of two matrices. 我需要计算两个矩阵的点积。 Probably tensordot would do the job, however I am struggling to figure out exact solution. tensordot可能会胜任,但是我正在努力寻找确切的解决方案。

The simple option 简单的选择

res = np.dot(x, fullkernel[:, :-1].transpose())

works fine, where x is of shape (9999,), fullkernel of shape (980,10000), and res is of shape (1, 980). 工作正常,其中x的形状为(9999,),全内核的形状为(980,10000),res的形状为(1,980)。

Now I need to do similar thing with 2 dimensions. 现在我需要在2维上做类似的事情。 Thus my x now has shape (9999, 2), fullkernel (2, 980, 10000). 因此,我的x现在具有形状(9999,2),全内核(2,980,10000)。

Literally I want my result "res" to be of 2 dimensions, where each one is dot.product of one column of x and one dimension of fullkernel. 从字面上看,我希望我的结果“ res”是2维的,其中每一个是x的一列和全维的1维的dot.product。

You can do that like this: 您可以这样做:

res = np.einsum('ki,ijk->ij', x, fullkernel[:, :, :-1])
print(res.shape)
# (2, 980)

If you want to have the additional singleton dimension in the middle just do: 如果要在中间添加其他单例尺寸,请执行以下操作:

res = np.expand_dims(res, 1)

An equivalent solution with @ / np.matmul would be: @ / np.matmul的等效解决方案是:

res = np.expand_dims(x.T, 1) @ np.moveaxis(fullkernel[:, :, :-1], 2, 1)
print(res.shape)
# (2, 1, 980)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM