我有两个矩阵与某些维度的矩阵乘法numpy工作,但在tensorflow中不起作用的情况。矩阵乘法tensorflow与numpy的区别
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和20,30到10乘以(30,40)?似乎TF matmul缺少广播,可能值得提交功能请求。你可以通过执行'y = tf.Variable(tf.truncated_normal([30,40],name ='w')+ tf.zeros((10,30,40)))''触发广播。相关问题(可能由于错误而关闭) - https://github.com/tensorflow/tensorflow/issues/216 –
matmul在这里与'np.einsum('ijk,kl-> ijl',x,y) ' – Kuba