广播np.dot vs tf.matmul以进行张量矩阵乘法(形状必须为2级,但为3级错误) [英] Broadcasting np.dot vs tf.matmul for tensor-matrix multiplication (Shape must be rank 2 but is rank 3 error)
问题描述
假设我有以下张量:
X = np.zeros((3,201, 340))
Y = np.zeros((340, 28))
使用numpy成功制作X,Y的点积,并产生形状为(3,201,28)的张量.
但是使用tensorflow时出现以下错误:Shape must be rank 2 but is rank 3 error ...
Making a dot product of X, Y is successful with numpy, and yields a tensor of shape (3, 201, 28).
However with tensorflow I get the following error: Shape must be rank 2 but is rank 3 error ...
最小代码示例:
X = np.zeros((3,201, 340))
Y = np.zeros((340, 28))
print(np.dot(X,Y).shape) # successful (3, 201, 28)
tf.matmul(X, Y) # errornous
有人知道如何通过张量流实现相同的结果吗?
Any idea how to achieve the same result with tensorflow?
推荐答案
由于您正在使用tensors
,因此(出于性能考虑)在其中使用tensordot
比使用np.dot
更好. NumPy允许它(numpy.dot)通过降低性能在tensors
上工作,而tensorflow
似乎根本不允许它.
Since, you are working with tensors
, it would be better (for performance) to use tensordot
there than np.dot
. NumPy allows it (numpy.dot) to work on tensors
through lowered performance and it seems tensorflow
simply doesn't allow it.
因此,对于NumPy,我们将使用 np.tensordot
-
So, for NumPy, we would use np.tensordot
-
np.tensordot(X, Y, axes=((2,),(0,)))
对于tensorflow
,将使用 tf.tensordot
-
For tensorflow
, it would be with tf.tensordot
-
tf.tensordot(X, Y, axes=((2,),(0,)))
这篇关于广播np.dot vs tf.matmul以进行张量矩阵乘法(形状必须为2级,但为3级错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!