我认为您保存的模型是 keras model 而不是 'SavedModel. So, you need to usefrom_keras_model`,如下所示。
我尝试使用简单模型来模拟问题,并成功重现了您的问题。检查下面的代码。
!pip install tf-nightly
import tensorflow as tf
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test)
训练模型后,我猜你保存如下
model.save('my_model.h5',save_format='h5')
然后尝试将模型转换为 tflite 模型(以下是您的代码)
# Converting a SavedModel to a TensorFlow Lite model.
saved_model_dir = '/content/my_model.h5' #r"C:\Users\Munib\New folder"
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
tflite_model = converter.convert()
使用上面的代码,我得到了以下错误(看起来和你面临的错误一样)
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-4-a9a46a590f90> in <module>()
1 # Converting a SavedModel to a TensorFlow Lite model.
2 saved_model_dir = '/content/my_model.h5' #r"C:\Users\Munib\New folder"
----> 3 converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
4 tflite_model = converter.convert()
4 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/saved_model/loader_impl.py in parse_saved_model(export_dir)
111 (export_dir,
112 constants.SAVED_MODEL_FILENAME_PBTXT,
--> 113 constants.SAVED_MODEL_FILENAME_PB))
114
115
OSError: SavedModel file does not exist at: /content/my_model.h5/{saved_model.pbtxt|saved_model.pb}
这是更新后的代码
# Converting a SavedModel to a TensorFlow Lite model.
saved_model_dir = '/content/my_model.h5' #r"C:\Users\Munib\New folder"
loaded_model = tf.keras.models.load_model(saved_model_dir)
converter = tf.lite.TFLiteConverter.from_keras_model(loaded_model)# .from_saved_model(saved_model_dir)
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)
完整代码是here。