矩阵乘法张量流与numpy的差异

Kub*_*uba 6 python numpy matrix tensorflow

我有一个案例,其中两个具有一定维度的矩阵的矩阵乘法在numpy中工作,但在tensorflow中不起作用.

x = np.ndarray(shape=(10,20,30), dtype = float)
y = np.ndarray(shape=(30,40), dtype = float)
z = np.matmul(x,y)
print("np shapes: %s x %s = %s" % (np.shape(x), np.shape(y), np.shape(z)))
Run Code Online (Sandbox Code Playgroud)

这按预期工作并打印:

np shapes: (10, 20, 30) x (30, 40) = (10, 20, 40)
Run Code Online (Sandbox Code Playgroud)

但是在tensorflow中,当我尝试将占位符和与上面的numpy数组相同形状的变量相乘时,我得到一个错误

x = tf.placeholder(tf.float32, shape=(10,20,30))
y = tf.Variable(tf.truncated_normal([30,40], name='w'))
print("tf shapes: %s x %s" % (x.get_shape(), y.get_shape()))
tf.matmul(x,y)
Run Code Online (Sandbox Code Playgroud)

结果是

tf shapes: (10, 20, 30) x (30, 40)
InvalidArgumentError: 
Shape must be rank 2 but is rank 3 for 'MatMul_12' 
(op: 'MatMul') with input shapes: [10,20,30], [30,40].
Run Code Online (Sandbox Code Playgroud)

为什么这个操作失败了?

Dmi*_*kiy 2

不知道为什么tf.matmul不支持这种乘法(可能核心开发人员之一可以提供有意义的答案)。

但如果您只想以这种方式乘以张量,请查看tf.einsum函数。它可以使用任意阶的张量进行操作。