如何成功运行TensorFlow1模型库中的MobileDet预训练模型?
我之前折腾过MobileDet在TF1.x环境下的部署,刚好遇到过类似的问题,给你拆解下错误原因和可行的解决思路:
错误1:加载tflite_graph.pb时的FusedBatchNormV3属性不兼容
问题根源
你用的tflite_graph.pb大概率是用比TF1.15更高版本的TensorFlow(比如TF2.x或TF1.15之后的兼容版本)导出的,导致图中的FusedBatchNormV3节点带有TF1.15不支持的exponential_avg_factor属性——TF1.15的FusedBatchNormV3 Op定义里确实没有这个属性,所以导入时会触发兼容性报错。
解决办法
不要直接用预训练包里的tflite_graph.pb,而是用ckpt文件重新导出兼容TF1.15的推理图:
- 确保你用的TensorFlow Object Detection API版本和TF1.15匹配:建议下载2020年5月左右的models repo commit(也就是MobileDet预训练模型发布的时间点),避免版本不兼容。
- 找到对应的MobileDet pipeline配置文件(可以从预训练包或models repo的
samples/configs目录里找到ssdlite_mobiledet_cpu_320x320_coco.config)。 - 运行API自带的
export_inference_graph.py脚本导出推理图:python export_inference_graph.py \ --input_type image_tensor \ --pipeline_config_path ./ssdlite_mobiledet_cpu_320x320_coco.config \ --trained_checkpoint_prefix ./tf_ckpts/ssdlite_mobiledet_cpu_320x320_coco_2020_05_19/model.ckpt-400000 \ --output_directory ./mobiledet_inference_graph - 用导出目录里的
frozen_inference_graph.pb来加载,这应该能完美兼容TF1.15。
错误2:加载ckpt时的LegacyParallelInterleaveDatasetV2 Op未注册
问题根源
这个Op属于tf.data模块,你的TF1.15环境里没有注册这个Op,大概率是因为模型训练时用了更高版本的TF(比如TF1.15之后的版本或TF2.x),或者你没有提前导入依赖模块导致Op没有被懒加载。
解决办法
- 加载ckpt前,先确保相关模块已经导入,触发Op的注册。比如在代码开头加入:
import tensorflow as tf # 导入Object Detection API模块,触发自定义Op和tf.data相关Op的注册 from object_detection.utils import label_map_util - 同样建议用匹配版本的Object Detection API来加载模型,避免训练和推理环境的Op定义不一致。
整体验证步骤
- 确认TF版本是1.15,安装对应版本的Object Detection API(protobuf版本建议用3.8.0,避免版本冲突)。
- 用上述方法重新导出
frozen_inference_graph.pb。 - 用以下代码测试加载和推理:
import os import tensorflow as tf import numpy as np from PIL import Image MODEL_DIR = './mobiledet_inference_graph/' MODEL_PATH = os.path.join(MODEL_DIR, 'frozen_inference_graph.pb') # 加载模型 detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(MODEL_PATH, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') # 准备测试图片 image_path = 'test_image.jpg' image = Image.open(image_path) image_np = np.array(image) image_np_expanded = np.expand_dims(image_np, axis=0) # 运行推理 with tf.Session(graph=detection_graph) as sess: image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0') detection_scores = detection_graph.get_tensor_by_name('detection_scores:0') detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') (boxes, scores, classes, num) = sess.run( [detection_boxes, detection_scores, detection_classes, num_detections], feed_dict={image_tensor: image_np_expanded}) print(f"检测到{int(num[0])}个目标")
我之前用这套流程在TF1.15环境下成功运行过MobileDet模型,应该能解决你的问题。
内容的提问来源于stack exchange,提问作者Shane Zhao
相关产品推荐
相关产品推荐

