张量'embedding_input'具有无效的形状'[None,None]'

时间:2019-01-17 15:17:47

标签: python tensorflow keras deep-learning tensorflow-lite

我正在尝试创建一个tensorflow lite文本多类分类模型。我主要从这里复制代码:https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/keras/basic_text_classification.ipynb

在tensorflow中一切似乎都工作正常,但是当我尝试将save h5模型转换为 Tensorflow Lite 时,出现此错误:

ValueError: None is only supported in the 1st dimension. Tensor 'embedding_input' has invalid shape '[None, None]'.

这是我的代码的样子:

vocab_size = 15000 # of words in dictionary

model = keras.Sequential()
model.add(keras.layers.Embedding(vocab_size, 16))
model.add(keras.layers.GlobalAveragePooling1D())
model.add(keras.layers.Dense(16, activation=tf.nn.relu))
model.add(keras.layers.Dense(7, activation=tf.nn.sigmoid))

model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

history = model.fit(...)
keras.models.save_model(model, graphFile)

converter = tf.contrib.lite.TFLiteConverter.from_keras_model_file(graphFile)
tflite_model = converter.convert()
open("converted.tflite", "wb").write(tflite_model)

我猜问题出在嵌入层?我该怎么解决?

1 个答案:

答案 0 :(得分:1)

转换需要知道输入张量的形状。只有第一个尺寸(批次)是未知的(None)。在某些情况下,Keras不会注释已知的张量形状。您可以通过传递input_shapes可选参数来指定输入形状:

converter = tf.contrib.lite.TFLiteConverter.from_keras_model_file(
    graphFile,
    input_shapes={'embedding_input': [1, vocab_size]}
)

另请参阅类似的问题:Tensorflow - h5 model to tflite conversion error