TensorFlow 2.0中运行冻结图的方法及Session属性报错问题咨询
当然可以在TensorFlow 2.0里运行冻结图啦!你碰到的AttributeError是因为TF2默认开启了即时执行(Eager Execution),tf.Session是TF1.x的核心API,在TF2的默认环境下已经被移除了。下面给你两种靠谱的解决办法:
方法一:使用TF1.x兼容模块
如果你想沿用类似TF1.x的会话模式,可以借助tf.compat.v1模块来兼容旧代码,步骤如下:
- 先加载你的冻结图文件
- 禁用即时执行(或者直接使用兼容版的Session)
- 用兼容会话运行推理
示例代码:
import tensorflow as tf # 禁用TF2的即时执行,让兼容API正常工作 tf.compat.v1.disable_eager_execution() def load_frozen_graph(pb_file_path): """加载冻结的.pb图文件""" graph = tf.Graph() with graph.as_default(): graph_def = tf.compat.v1.GraphDef() with tf.io.gfile.GFile(pb_file_path, 'rb') as fid: serialized_graph = fid.read() graph_def.ParseFromString(serialized_graph) tf.import_graph_def(graph_def, name='') return graph # 替换成你的冻结图路径 frozen_graph = load_frozen_graph("your_frozen_model.pb") # 使用兼容版Session运行推理 with tf.compat.v1.Session(graph=frozen_graph) as sess: # 这里要替换成你冻结图中实际的输入、输出张量名称 # 可以通过打印图中所有操作来确认:print([op.name for op in frozen_graph.get_operations()]) input_tensor = frozen_graph.get_tensor_by_name("input:0") output_tensor = frozen_graph.get_tensor_by_name("output:0") # 执行推理 output_data = sess.run(output_tensor, feed_dict={input_tensor: test_images})
方法二:用TF2原生的即时执行模式运行
如果你想完全适配TF2的风格,不需要依赖Session,可以直接在即时执行模式下加载并运行冻结图:
import tensorflow as tf def load_frozen_graph(pb_file_path): """加载冻结图并返回输入、输出张量""" graph_def = tf.compat.v1.GraphDef() with tf.io.gfile.GFile(pb_file_path, 'rb') as fid: serialized_graph = fid.read() graph_def.ParseFromString(serialized_graph) # return_elements参数传入你需要的输入、输出张量名称 input_tensor, output_tensor = tf.import_graph_def( graph_def, return_elements=["input:0", "output:0"] ) return input_tensor, output_tensor # 加载张量 input_tensor, output_tensor = load_frozen_graph("your_frozen_model.pb") # 直接在Eager模式下运行推理,无需Session output_data = output_tensor.numpy(feed_dict={input_tensor: test_images}) # 如果需要多次执行推理,建议包装成tf.function提升性能 @tf.function def run_inference(input_data): return output_tensor output_data = run_inference(test_images).numpy()
小提示:如果不确定冻结图里的输入输出张量名称,可以通过print([op.name for op in frozen_graph.get_operations()])(方法一中)或者查看导出冻结图时的日志来确认,通常张量名称是操作名加上:0后缀。
内容的提问来源于stack exchange,提问作者kumar desappan
相关产品推荐
相关产品推荐

