[英]ValueError: Shape must be rank 2 but is rank 3 for 'MatMul'
I have the following TensorFlow code: 我有以下TensorFlow代码:
layer_1 = tf.add(tf.matmul(tf.cast(x, tf.float32), weights['h1']), biases['b1'])
But is throwing the following error: 但是抛出以下错误:
ValueError: Shape must be rank 2 but is rank 3 for 'MatMul' (op: 'MatMul') with input shapes: [?,5741,20000], [20000,128].
It says that x
has the shape of (?,5741,20000). 它说
x
的形状为(?,5741,20000)。 How could I transform the shape of x
to (5741, 20000)? 我怎样才能将
x
的形状转换为(5741,20000)?
Thank you in advance! 先感谢您!
I would suggest to work with tensors dot product instead of simple matrix multiplication in order to keep the batch size. 我建议使用张量点积而不是简单矩阵乘法,以保持批量大小。 This is answer is more general than @mrry
这个答案比@mrry更通用
layer_1 = tf.add(tf.tensordot(tf.cast(x, tf.float32), weights['h1'], [[2], [0]]), biases['b1'])
It looks like you are trying to matrix multiply 'x' with 'weights'. 看起来你正试图将'x'与'权重'进行矩阵乘法运算。 x has a shape of [5741, 20000] for one example, but when you feed examples in batches x will have a shape of [?, 5741, 20000].
对于一个示例,x的形状为[5741,20000],但是当您批量提供示例时,x将具有[?,5741,20000]的形状。 Similarly, weights should also have a shape of [?, 20000, 128].
同样,权重也应该具有[?,20000,128]的形状。 But, from the error, it looks like your weights are still [20000, 128] which tells me that you have some problem in your code which is not transforming the weights variable to shape [?, 20000, 128].
但是,从错误中看,你的权重看起来仍然是[20000,128],这告诉我你的代码中有一些问题没有将权重变量转换为形状[?,20000,128]。 When you can figure this out, the error should go away.
当你能想到这一点时,错误就会消失。 The result of matrix multiplication should have a shape of [?, 5741, 128]
矩阵乘法的结果应该是[?,5741,128]的形状
假设x
的动态形状x
是(1, 5741, 20000)
可以将其形状变换到(5741, 20000)
使用tf.squeeze()
如下:
x = tf.squeeze(x, axis=[0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.