tensorflow - 将 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 支持链接到额外的操作。
解决方案
试试这个来转换模型。
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()
推荐阅读
- android - 共享(Activity/NavGraph-scoped)ViewModel 和 Fragment ViewModel 之间的通信
- node.js - 在 Node.js 应用程序中使用 GraphQL 从 Microsoft SQL Server 查询数据
- excel - 如何使用 VBA 从 powerpoint 中删除一个形状
- python - 'path/wsgi.py apache ubuntu 对 fopen() 的 mod_wsgi 调用失败
- reactjs - npm start 突然停止在 react 应用程序上工作
- json - 如何在 QTextEdit 中传递 JSON 对象
- amadeus - 自助服务 API 错误响应有多种格式
- accessibility - 直播视频播放器
- powerbi - 在 Power BI 中按降序对月份名称进行长期排序
- google-chrome - 更新后无法在 Chrome 中登录 Blazor WASM