【问题标题】:Tensorflow hub.load Model to TFLiteTensorflow hub.load 模型到 TFLite
【发布时间】:2020-05-04 15:32:35
【问题描述】:

我正在尝试将加载了 hub.load 的模型转换为 TFLite。 有问题的模型是universal-sentence-encoder (4),位于https://tfhub.dev/google/universal-sentence-encoder/4 我尝试在 Python 中使用 Tensorflow 版本 2.1.0 和 2.2.0

import tensorflow as tf
import tensorflow_hub as hub

model = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
converter = tf.lite.TFLiteConverter.from_keras_model(model )
converter.experimental_new_converter = True // tried with and without
tflite_model = converter.convert()

我收到以下错误:

    converter = tf.lite.TFLiteConverter.from_keras_model(model)
  File "...\lib\site-packages\tensorflow_core\lite\python\lite.py", line 394, in from_keras_model
    if not isinstance(model.call, _def_function.Function):
AttributeError: '_UserObject' object has no attribute 'call'

据我了解 hub.load 返回一个 keras SavedModel,所以不应该立即转换?

【问题讨论】:

    标签: python tensorflow keras tensorflow-lite


    【解决方案1】:

    尝试使用hub.KerasLayer 将模型加载到tf.keras.Model,然后使用.from_keras_model 将其转换为ŧflite

    没有“keras SavedModel”这样的东西。有SavedModel,即.pb 文件+assets 文件夹+variables 文件夹。它就像一种文件格式,一种存储模型的方式。它与内存中的tf.keras.Models 无关。 hub.load 不返回 tf.keras.Model,而是“最通用的东西”,您可以保存为 SavedModel 文件格式,即 _UserObject。这是因为您可以以SavedModels 文件格式保存除tf.keras.Modelss 之外的其他内容。

    我知道这不是您的问题,但如果您确实想在加载后找回您的tf.keras.Model,您可以使用tf.keras.save_model 保存它。然后它会在使用tf.saved_model.load 加载后以tf.keras.Model 的形式返回(所以它不再是最通用的东西)。

    编辑:

    只需代码:

    import tensorflow as tf
    import tensorflow_hub as hub 
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.InputLayer(dtype=tf.string, input_shape=()))
    model.add(hub.KerasLayer("https://tfhub.dev/google/universal-sentence-encoder/4"))
    converter = tf.lite.TFLiteConverter.from_keras_model(model)
    tflite_model = converter.convert()
    

    哪个有效(它开始转换),但你得到一个:

    2020-05-05 10:48:44.927433: I tensorflow/lite/toco/import_tensorflow.cc:659] Converting unsupported operation: StatefulPartitionedCall
    

    所以这代码将保存在SavedModel格式的模型转换为tflite,但是你得到一个google-universal-sentence-encoder特定的错误。不知道如何解决这个问题。

    【讨论】:

    • 我不认为这是问题所在,我尝试了 tf.saved_model.save(model, filepath) 然后 model = tf.saved_model.load(filepath),但错误仍然存​​在。我尝试使用 KerasLayer,但它一直给我输入大小的错误
    • 谢谢,现在更清楚如何使用 KerasLayer。我试过了,它给了我同样的错误,如果你添加 converter.experimental_new_converter = True 我发现还有其他人有同样的问题github.com/tensorflow/tensorflow/issues/34396
    猜你喜欢
    • 2020-07-13
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 2020-09-10
    • 2020-12-03
    • 1970-01-01
    • 2020-10-14
    相关资源
    最近更新 更多