将TensorFlow Hub的Faster RCNN模型转为TF Lite失败求助
问题:TensorFlow Hub Faster-RCNN模型转TF Lite失败及解决方案
我尝试将TensorFlow Hub上的faster_rcnn/openimages_v4/inception_resnet_v2模型转换为TF Lite格式,但未成功。该模型基于openimages_v4训练,我对此格外关注,想知道是否有人成功实现过转换?
附上我使用的代码:
import tensorflow as tf import tensorflow_hub as hub # 从TensorFlow Hub下载谷歌目标检测Faster-RCNN模型 module_handle = "https://tfhub.dev/google/faster_rcnn/openimages_v4/inception_resnet_v2/1" model = hub.load(module_handle) # TensorFlow模型转TF Lite模型 converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert() # 保存模型 with open('model.tflite', 'wb') as f: f.write(tflite_model)
报错信息:
错误:'AutoTrackable' 对象没有属性 'call'
问题原因
hub.load()返回的是AutoTrackable类型对象,并非标准Keras模型,因此无法直接用from_keras_model()方法转换。
解决方法
需要基于模型的推断签名函数创建TF Lite转换器,具体修改后的代码如下:
import tensorflow as tf import tensorflow_hub as hub # 加载模型 module_handle = "https://tfhub.dev/google/faster_rcnn/openimages_v4/inception_resnet_v2/1" model = hub.load(module_handle) # 获取模型的默认推断签名函数 infer_func = model.signatures['default'] # 初始化TF Lite转换器 converter = tf.lite.TFLiteConverter.from_concrete_functions([infer_func]) # 启用TensorFlow特有算子支持,避免转换时算子缺失报错 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() # 保存转换后的模型 with open('faster_rcnn_openimages_v4.tflite', 'wb') as f: f.write(tflite_model)
补充说明
- 该模型包含TensorFlow专属操作,必须启用
SELECT_TF_OPS并允许自定义操作,否则会出现算子不兼容错误; - 转换完成后,可使用TF Lite解释器加载模型,传入符合要求的输入张量完成推断测试。
内容的提问来源于stack exchange,提问作者nelson mundaca
相关产品推荐
相关产品推荐

