【发布时间】:2017-06-30 19:42:07
【问题描述】:
我有一个案例,两个具有特定维度的矩阵的矩阵乘法在 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)))
这按预期工作并打印:
np shapes: (10, 20, 30) x (30, 40) = (10, 20, 40)
但是在 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)
结果
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].
为什么这个操作会失败?
【问题讨论】:
-
numpy matmul 在这里做什么?广播第二个条目到 10,20,30 并通过 (30,40) 做 10 个 20,30 的 matmuls?似乎 TF matmul 缺少广播,可能值得提交功能请求。您可以通过
y = tf.Variable(tf.truncated_normal([30,40], name='w')+tf.zeros((10,30,40)))触发广播。相关问题(可能被错误关闭)--github.com/tensorflow/tensorflow/issues/216 -
matmul 这里的作用和
np.einsum('ijk,kl->ijl', x, y)一样
标签: python numpy matrix tensorflow