首页 > 解决方案 > 将 Keras 模型转换为 TensorFlow lite - 如何避免不支持的操作?

问题描述

我有使用该TimeDistributed层的基于 MobileNetV2 的模型。我想将该模型转换为 TensorFlow Lite 模型以便在智能手机上运行它,但是存在未定义的操作。

这是代码:

import tensorflow as tf

IMAGE_SHAPE = (224, 224, 3)

mobilenet_model = tf.keras.applications.MobileNetV2(input_shape=IMAGE_SHAPE,
                                               include_top=False,
                                               pooling='avg',
                                               weights='imagenet')

inputs = tf.keras.Input(shape=(5,) + IMAGE_SHAPE)
x = tf.keras.applications.mobilenet_v2.preprocess_input(inputs)
outputs = tf.keras.layers.TimeDistributed(mobilenet_model)(x)
model = tf.keras.Model(inputs, outputs)
model.compile()
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tfmodel = converter.convert() # fails

这是错误消息:

error: failed while converting: 'main': 
Some ops are not supported by the native TFLite runtime, you can enable TF kernels fallback using TF Select. See instructions: https://www.tensorflow.org/lite/guide/ops_select 
TF Select ops: Mul
Details:
    tf.Mul(tensor<?x5x224x224x3xf32>, tensor<f32>) -> (tensor<?x5x224x224x3xf32>)

该错误是由输入预处理和 TimeDistributed 层之间的交互引起的。如果我禁用输入预处理,则转换成功,但显然如果不重新训练,网络将无法正常工作。也可以转换具有预处理但没有 TimeDistributed 层的模型。是否可以将预处理移至其他位置以避免此错误?

此外,添加选择操作有助于成功转换它,但我不确定如何在运行时启用它们。我正在使用 Mediapipe 框架来构建一个 Android 应用程序。而且我不认为 Mediapipe 支持链接到额外的操作。

标签: tensorflowkerastensorflow-lite

解决方案


试试这个来转换模型。

converter = TFLiteConverter.from_saved_model(model_dir)
converter.experimental_new_converter = False
converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]
converter.allow_custom_ops=True
tflite_model = converter.convert()

推荐阅读