Tensorflow:ValueError:输入大小(输入深度)必须可通过形状推断访问,但看到值无 [英] Tensorflow: ValueError: Input size (depth of inputs) must be accessible via shape inference, but saw value None
问题描述
示例代码如下:
class Model:
def __init__(self, config):
inputs = self.get_inputs()
outputs, _ = tf.nn.dynamic_rnn(
cell=tf.contrib.rnn.BasicLSTMCell(config.hidden_dim, state_is_tuple=True),
inputs=inputs,
dtype=tf.float32)
def get_inputs(self):
# do something to archive the inputs,
# which are not just the word embeddings,
# rather, they are the outputs of another
# model. The shape is (batch_size, ?, hidden_dim),
# ? means the maxlength for each batch depends
# on the data.
然而,当我训练我的模型时,我得到了这个错误:
However, when I trained my model, I got this error:
Tensorflow:ValueError:输入大小(输入深度)必须可通过形状推断访问,但看到值无.
我认为是变量 maxlength 导致了问题.我需要为我的模型编写自己的 LSTM 还是有办法解决这个问题?
I assume it's the variable maxlength that causes the problem. Do I need to write my own LSTM for my model or is there a way to fix this?
推荐答案
inputs
的最后一个维度必须在编译图形时已经知道.您可以通过打印其静态形状来检查这一点:
The last dimension of inputs
has to be known already when compiling the graph. You can check this by printing its static shape:
print(inputs.get_shape())
您可能看到的是最后一个维度是 ?
意味着 TensorFlow 无法推断它.你说输入的形状总是[batch_size, ?, hidden_dim]
.但是,TensorFlow 不一定能够推断 hidden_dim
.TensorFlow 用于推断不同操作的输出形状的智能水平因 TensorFlow 版本而异.
What you probably see is that the last dimension is ?
meaning that TensorFlow was unable to infer it. You said that the shape of the inputs is always [batch_size, ?, hidden_dim]
. However, TensorFlow is not necessarily able to infer hidden_dim
. The level of intelligence that TensorFlow has for infering the output shape of different operations varies between TensorFlow versions.
您可以通过明确告知 TensorFlow 输入的维度来解决问题.在调用 tf.nn.dynamic_rnn()
之前,使用 inputs.set_shape(shape)
设置输入的形状.它的工作原理类似于 inputs = tf.reshape(inputs, shape)
,但它只设置静态形状.如果shape
的某些维度是None
,它们将不会被改变:
You can fix the problem by explicitly telling the dimensionality of the inputs to TensorFlow. Before calling tf.nn.dynamic_rnn()
, set the shape of the inputs usinginputs.set_shape(shape)
. It works like inputs = tf.reshape(inputs, shape)
, but it only sets the static shape. If some dimensions of shape
are None
, they won't be altered:
inputs.set_shape([None, None, hidden_dim])
这篇关于Tensorflow:ValueError:输入大小(输入深度)必须可通过形状推断访问,但看到值无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!