【发布时间】:2020-07-04 16:43:01
【问题描述】:
我正在尝试将我的 tensorflow 模型 (2.0) 转换为 tensorflow lite 格式。我的模型有两个输入层如下:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import load_model
from tensorflow.keras.layers import Lambda, Input, add, Dot, multiply, dot
from tensorflow.keras.backend import dot, transpose, expand_dims
from tensorflow.keras.models import Model
r1 = Input(shape=[None, 1, 512], name='flatbuffer_data') # I want to take a variable amount of
# 512 float embeddings from my flatbuffer, if the flatbuffer has 4, embeddings then it would
# be inferred as shape=[4, 1, 512], if it has a 100 embeddings, then it is [100, 1, 512].
r2 = Input(shape=[1, 512], name='query_embedding')
#Example code
minus_r1 = Lambda(lambda x: -x, name='invert_value')(r1)
subtracted = add([r2, minus_r1], name='embeddings_diff')
out1 = tf.argsort(subtracted)
out2 = tf.sort(subtracted)
model = Model([r1, r2], [out1, out2])
然后我在图层上进行一些张量运算并按如下方式保存模型(没有训练,因此没有可训练的参数,只有一些我想移植到 android 的线性代数运算)
model.save('combined_model.h5')
我得到了我的 tensorflow .h5 模型,因此当我尝试将其转换为 tensorflow lite 时,我收到以下错误:
import tensorflow as tf
model = tf.keras.models.load_model('combined_model.h5')
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
#Error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/aspiring1/.virtualenvs/faiss/lib/python3.6/site-packages/tensorflow_core/lite/python/lite.py", line 446, in convert
"invalid shape '{1}'.".format(_get_tensor_name(tensor), shape_list))
ValueError: None is only supported in the 1st dimension. Tensor 'flatbuffer_data' has invalid shape '[None, None, 1, 512]'.
我知道我们在 tensorflow 1.x 中使用 tensorflow 占位符进行动态和静态形状推断。 tensorflow 2.x 中是否有类似物?另外,我也很欣赏 tensorflow 1.x 中的解决方案。
我读过的一些答案和博客可能会有所帮助: Tensorflow: how to save/restore a model?
Understand dynamic and static shape in tensorflow
Understanding tensorflow shapes
使用上面的第一个链接,我还尝试创建一个 tensorflow 1.x 图表并尝试使用 saved model 格式保存它,但我没有得到想要的结果。
你可以在这里找到我的代码:tensorflow 1.x gist code
【问题讨论】:
标签: python tensorflow keras tensorflow-lite tf.keras