简体   繁体   English

将 3D 矩阵与 2D 矩阵相乘,返回与 2D 矩阵具有相同维度的矩阵

[英]Multiply a 3D matrix with a 2D matrix, return a matrix with the same dimensions as the 2D one

In Numpy, say I have a matrix A of dimensions ixjxk, and a matrix B of dimensions kx i.在 Numpy 中,假设我有一个尺寸为 ixjxk 的矩阵 A,和一个尺寸为 kx i 的矩阵 B。 How do I get back a product with dimensions kxi without using a loop?如何在不使用循环的情况下取回尺寸为 kxi 的产品?
For example:例如:

 Let         A = [[[1 2],
                   [3 4]],
                  [[5 6],
                   [7 8]]]

             B = [[a b],
                  [c d]]

I would like to get:我想得到:

             C = [[a+2c  5b+6d],
                  [3a+4c 7b+8d]]

My current solution is我目前的解决方案是

np.diagonal(np.dot(A, B), axis1=0, axis2=2)

However, the problem is I'm working with a large data set ( A and B have huge dimensions) so np.dot(A, B) would lead to MemoryError .但是,问题是我正在处理一个大数据集( AB有很大的尺寸),所以np.dot(A, B)会导致MemoryError Therefore I want to figure out a better way to solve this without computing the dot product.因此,我想找出一种更好的方法来解决这个问题,而无需计算点积。

I have looked into functions like einsum and tensordot but I didn't find what I need (or maybe I missed something).我已经研究过像einsumtensordot这样的函数,但我没有找到我需要的东西(或者我可能错过了一些东西)。 I would appreciate if someone could help me out.如果有人可以帮助我,我将不胜感激。 Thank you!谢谢!

You can do this by analyzing the input and output dimensions.您可以通过分析输入和 output 维度来做到这一点。

A.shape -> i, j, k
B.shape -> k, i

Your example is not very good, but if you look carefully at what you're asking the output to be, the shape of B must match the first and last dimensions of A .你的例子不是很好,但如果你仔细看看你要求 output 是什么, B的形状必须与A的第一个和最后一个尺寸相匹配。

The sum reduction is happening along the last axis of A and the first axis of B :总和减少发生在A的最后一个轴和B的第一个轴上:

np.einsum('ijk,ki->ji', A, B)

einsum can be intimidating, but doing this sort of analysis can save you a lot of the frustration caused by trial and error. einsum可能令人生畏,但进行此类分析可以为您节省大量因反复试验而导致的挫败感。

Looking at your output, C[:,0] is看着你的 output, C[:,0]

A[0] @ B[0].T

and similarly, C[:,1] is A[1] @ B[1].T .同样, C[:,1]A[1] @ B[1].T

With that in mind, the np.einsum formula is:考虑到这一点, np.einsum公式为:

C = np.einsum('ijk,ik->ji', A,B)

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

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