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

如何加载Python2.7构建的未知架构TensorFlow saved_model.pb模型

解决Python2.7构建的TensorFlow SavedModel加载问题

先明确你之前两种方法的错误原因

  1. tf.keras.models.load_model报错:这个API仅适用于加载Keras导出的完整模型目录(目录下需包含saved_model.pb、variables文件夹及keras_metadata.pb),你的模型是TensorFlow原生SavedModel格式,且你直接传入了单个pb文件路径而非目录,因此触发错误。
  2. tf.saved_model.load报错:TF2.x版本的该函数不需要传入session参数,且tags不能设为None——旧版TF导出的SavedModel必须指定对应标签(如['serve']或['train']),参数错误导致了迭代报错。

可行加载方案

方案一:使用TensorFlow 1.x(推荐,匹配模型构建环境)

由于你的模型是Python2.7+TensorFlow 1.x构建的,用TF1.15(TF1.x最后一个支持Python2.7的版本)加载兼容性最佳:

import tensorflow as tf

# 初始化会话
sess = tf.Session()

# 先查看模型包含的标签(tags),避免猜标签出错
from tensorflow.core.protobuf import saved_model_pb2
from google.protobuf import text_format

with open('my_folder/saved_model.pb', 'rb') as f:
    saved_model = saved_model_pb2.SavedModel()
    saved_model.ParseFromString(f.read())
    tags = saved_model.meta_graphs[0].meta_info_def.tags
    print("模型标签:", tags)

# 用获取到的标签加载模型
tf.saved_model.loader.load(sess, tags, 'my_folder')

# 查看模型所有操作节点,定位输入输出张量
graph = sess.graph
for op in graph.get_operations():
    print(op.name)

# 示例:假设找到输入张量为"input:0",输出为"output:0",执行推理
input_tensor = graph.get_tensor_by_name('input:0')
output_tensor = graph.get_tensor_by_name('output:0')
# 替换your_input_data为你的输入数据
result = sess.run(output_tensor, feed_dict={input_tensor: your_input_data})

方案二:使用TensorFlow 2.x(需启用兼容模式)

如果必须用TF2.x,需开启TF1.x兼容模式:

import tensorflow as tf

# 禁用Eager Execution,启用TF1.x兼容模式
tf.compat.v1.disable_eager_execution()

# 先获取模型标签
from tensorflow.core.protobuf import saved_model_pb2
from google.protobuf import text_format

with open('my_folder/saved_model.pb', 'rb') as f:
    saved_model = saved_model_pb2.SavedModel()
    saved_model.ParseFromString(f.read())
    tags = saved_model.meta_graphs[0].meta_info_def.tags
    print("模型标签:", tags)

# 加载模型
sess = tf.compat.v1.Session()
tf.compat.v1.saved_model.loader.load(sess, tags, 'my_folder')

# 后续操作同方案一,定位并使用输入输出张量

额外注意事项

  • 确认my_folder目录结构完整:目录下必须包含saved_model.pb和variables文件夹,不能只复制单个pb文件。
  • 如果用Python3加载Python2.7构建的模型,可能遇到编码或序列化格式问题,优先推荐用Python2.7+TF1.15环境加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:45:45