TensorFlow加载模型后获取全部张量名称的方法

Felix
Felix
发布时间:2026-10-13 | 2人浏览过
原创

本文介绍在TensorFlow中加载预训练模型(如Inception_v3)后,如何提取图中所有节点的张量名称。通过遍历tf.get_default_graph().as_graph_def().node,可获取完整节点列表。支持直接打印输出或写入TXT文件保存,便于后续分析模型结构。

TensorFlow获取模型张量名称的实现方法

核心实现逻辑如下所示:


[tensor.name for tensor in tf.get_default_graph().as_graph_def().node]

具体示例代码展示了如何加载Inception_v3模型,并提取该模型中所有节点的名称列表。


# -*- coding: utf-8 -*-
 
import tensorflow as tf
import os
 
model_dir = 'C:/Inception_v3'
model_name = 'output_graph.pb'
 
# 读取并创建一个图graph来存放训练好的 Inception_v3模型(函数)
def create_graph():
 with tf.gfile.FastGFile(os.path.join(
   model_dir, model_name), 'rb') as f:
  # 使用tf.GraphDef()定义一个空的Graph
  graph_def = tf.GraphDef()
  graph_def.ParseFromString(f.read())
  # Imports the graph from graph_def into the current default Graph.
  tf.import_graph_def(graph_def, name='')
 
# 创建graph
create_graph()
 
tensor_name_list = [tensor.name for tensor in tf.get_default_graph().as_graph_def().node]
for tensor_name in tensor_name_list:
 print(tensor_name,'\n')

程序运行后的输出结果如下:


mixed_8/tower/conv_1/batchnorm/moving_variance 

mixed_8/tower/conv_1/batchnorm 

r_1/mixed/conv_1/batchnorm 

.

.

.

mixed_10/tower_1/mixed/conv_1/CheckNumerics 

mixed_10/tower_1/mixed/conv_1/control_dependency 

mixed_10/tower_1/mixed/conv_1 

pool_3 

pool_3/_reshape/shape 

pool_3/_reshape 

input/BottleneckInputPlaceholder 
.
.
.
.
final_training_ops/weights/final_weights 

final_training_ops/weights/final_weights/read 

final_training_ops/biases/final_biases 

final_training_ops/biases/final_biases/read 

final_training_ops/Wx_plus_b/MatMul 

final_training_ops/Wx_plus_b/add 

final_result

由于输出内容较为冗长,此处仅展示部分结果,其余部分已省略。

若不希望直接在控制台打印输出,也可将结果保存至TXT文件以便查阅。

将张量名称写入TXT文件的代码如下:


tensor_name_list = [tensor.name for tensor in tf.get_default_graph().as_graph_def().node]
 
txt_path = './txt/节点名称'
full_path = txt_path+ '.txt'
 
for tensor_name in tensor_name_list:
 name = tensor_name + '\n'
 file = open(full_path,'a+')
file.write(name)
file.close()

以上即为TensorFlow中获取加载模型全部张量名称的完整实现方案,供读者参考使用。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表