You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow Hub下载的saved_model.pb无法正常加载及调用如何解决?

正确使用TensorFlow Hub SavedModel格式模型的流程

1. 理解模型加载后的结构

用tf.saved_model.load()加载的是SavedModel对象,它包含对应不同使用场景的签名函数,无法直接像Keras模型那样调用predict(),必须先获取对应的推理签名函数。

2. 查看模型的可用签名

加载模型后,执行以下代码查看所有可用签名:

import tensorflow as tf

my_model = tf.saved_model.load("extraction_path")
print(list(my_model.signatures.keys()))

你下载的EfficientNet V2分类模型,默认会有serving_default签名,这是推理的入口。

3. 获取推理用的签名函数

提取默认的服务签名:

infer = my_model.signatures["serving_default"]

4. 预处理输入图像

该模型对输入有固定要求:

  • 输入张量形状为[batch_size, 480, 480, 3](匹配EfficientNet V2的输入尺寸)
  • 像素值保留[0,255]范围即可

示例预处理代码:

# 读取并处理单张图像
image_path = "your_image.jpg"
image = tf.io.read_file(image_path)
image = tf.image.decode_jpeg(image, channels=3)
image = tf.image.resize(image, (480, 480))
image = tf.expand_dims(image, 0)  # 添加batch维度

5. 执行推理

先确认签名函数的输入参数名,再传入输入执行推理:

# 查看输入参数信息
print(infer.structured_input_signature)
# 输出示例:(() , {'input_1': TensorSpec(shape=(None, 480, 480, 3), dtype=tf.float32, name='input_1')})

# 执行推理
predictions = infer(image)["predictions"]

6. 后处理推理结果

predictions是形状为[1, 1000]的张量(对应ImageNet 1k分类概率),可以解码为可读的类别标签:

from tensorflow.keras.applications.imagenet_utils import decode_predictions

# 获取Top3预测结果
decoded_results = decode_predictions(predictions.numpy(), top=3)[0]
for class_id, class_name, score in decoded_results:
    print(f"{class_name}: {score:.2f}")

可选:转换为Keras模型

如果偏好使用Keras的predict()方法,可尝试将SavedModel转换为Keras模型:

keras_model = tf.keras.Model(inputs=infer.inputs, outputs=infer.outputs)
# 现在可以直接调用predict
keras_predictions = keras_model.predict(image)

注意:部分TF Hub模型可能无法完美转换,若转换失败,建议使用签名函数方式。

内容的提问来源于stack exchange,提问作者AndreaF

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 21:13:10