Skip to main content
 首页 » 编程设计

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

2024年12月31日8wuhuacong

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

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

ValueError: None 仅在第一维中受支持。张量“embedding_input”的形状“[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) 

我猜问题出在嵌入层上?我该怎么做才能修复它?

请您参考如下方法:

转换需要知道输入张量的形状。只有第一个维度(批处理)可以是未知的(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