如何加载并使用旧版TensorFlow导出的模型?
解决方法
方法1:使用SavedModel的签名函数直接推理
由于模型是通过tf.saved_model.save导出的,缺少Keras元数据,加载后需调用其签名函数完成预测:
- 加载模型:
import tensorflow as tf loaded_model = tf.saved_model.load("model/saved_model")
- 获取默认服务签名(若不确定可用
print(list(loaded_model.signatures.keys()))查看所有签名):
inference_fn = loaded_model.signatures["serving_default"]
- 准备符合模型输入要求的张量数据(需匹配原模型的预处理逻辑,比如图像缩放、归一化等),执行推理:
# 示例:假设输入为(1, 224, 224, 3)的预处理后图像张量 input_tensor = tf.random.normal((1, 224, 224, 3)) output = inference_fn(input_tensor) # 根据模型输出键名提取结果,如output["predictions"].numpy() print(output)
方法2:重构模型结构并加载权重(知晓原模型结构时)
如果清楚原模型的网络架构(比如你提到的MobileNetV2),可以重新构建模型,再通过checkpoint文件加载权重:
- 定义与原模型完全一致的网络结构:
from tensorflow.keras.applications import MobileNetV2 # 需匹配原模型的输入尺寸、分类类别数等参数 model = MobileNetV2(input_shape=(224,224,3), weights=None, classes=你的类别数量)
- 通过checkpoint加载权重:
checkpoint = tf.train.Checkpoint(model=model) # checkpoint路径为模型文件夹下checkpoint文件指向的具体权重文件,如"model/ckpt-50000" checkpoint.restore("model/ckpt-50000").assert_consumed()
- 此时模型具备
predict方法,可直接调用:
preds = model.predict(input_data)
方法3:若为TensorFlow Object Detection模型(含pipeline.config)
从文件结构(存在pipeline.config)判断,这大概率是TensorFlow Object Detection API训练的模型,需用对应API加载和推理:
- 加载模型:
import tensorflow as tf from object_detection.utils import label_map_util from object_detection.utils import visualization_utils as viz_utils detect_fn = tf.saved_model.load("model/saved_model")
- 加载标签映射文件(若存在)并预处理输入图像:
# 加载标签映射文件 category_index = label_map_util.create_category_index_from_labelmap("path/to/label_map.pbtxt", use_display_name=True) # 读取并预处理测试图像 image_np = tf.io.read_file("test_image.jpg") image_np = tf.image.decode_jpeg(image_np, channels=3) image_np = tf.expand_dims(image_np, 0)
- 执行检测并处理结果:
detections = detect_fn(image_np) # 可视化检测结果 viz_utils.visualize_boxes_and_labels_on_image_array( image_np[0].numpy(), detections['detection_boxes'][0].numpy(), detections['detection_classes'][0].numpy().astype(int), detections['detection_scores'][0].numpy(), category_index, use_normalized_coordinates=True, max_boxes_to_draw=200, min_score_thresh=.30, agnostic_mode=False)
内容的提问来源于stack exchange,提问作者jl303
相关产品推荐
相关产品推荐

