将Tensorflow hub.load模型转换为TFLite

将Tensorflow hub.load模型转换为TFLite,tensorflow,keras,tensorflow-lite,Tensorflow,Keras,Tensorflow Lite,我正在尝试将加载了hub.load的模型转换为TFLite。 所讨论的模型是通用句子编码器(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.TFLiteConverte

我正在尝试将加载了hub.load的模型转换为TFLite。 所讨论的模型是通用句子编码器(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保存的模型,因此不应该立即转换?

尝试使用
hub.KerasLayer
将您的模型加载到
tf.keras.model
中,然后使用
.From\u keras\u model
将其转换为

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

我知道这不是你的问题,但如果你确实想在加载后将
tf.keras.Model
取回,你可以使用
tf.keras.save\u Model
来保存它。使用
tf.saved\u 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通用句子编码器
特定错误。不知道如何解决这个难题

我认为这不是问题所在,我尝试了tf.saved_model.save(model,filepath),然后model=tf.saved_model.load(filepath),但错误仍然存在。我试着使用KerasLayer,但它一直给我输入大小的错误,现在更清楚如何使用KerasLayer。我试过了,它给了我同样的错误,如果添加转换器,错误就会改变。experimental_new_converter=True我发现还有其他人也有同样的问题