查看TensorFlow的pb模型文件的ops和tensor并使用TensorBoard可视化

加载pb模型文件,并输出定义
model = 'model.pb'
with tf.Session() as sess:
    with open(model, 'rb') as model_file:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        print(graph_def)

采用上述的方式可以在新的会话中重新加载本地的模型文件(pb),然后二进制解析后,输出可以看到结果。但是如果网络层结构十分复杂,那么这种显示方式就会比较难以阅读。

加载pb模型文件,并使用Tensorboard可视化
import tensorflow as tf
from tensorflow.python.platform import gfile

model = '1.pb'
graph = tf.get_default_graph()
graph_def = graph.as_graph_def()
graph_def.ParseFromString(gfile.FastGFile(model, 'rb').read())
tf.import_graph_def(graph_def, name='graph')
summaryWriter = tf.summary.FileWriter('log/', graph)

然后会在你的log文件夹下面生成文件。在终端中执行

tensorboard --logdir DIR --host IP --port PORT

一般情况下,不设置host和port,就会在localhost:6006启动。DIR是路径(不加引号)。
上面的例子:

tensorboard --logdir log

然后在浏览器中访问localhost:6006就可以可视化你的网络结构了。

打印pb模型文件中的tensor名字及shape
# coding:utf-8
import tensorflow as tf
from tensorflow.python.platform import gfile

tf.reset_default_graph()  # 重置计算图
output_graph_path = '1.pb'
with tf.Session() as sess:
    tf.global_variables_initializer().run()
    output_graph_def = tf.GraphDef()
    # 获得默认的图
    graph = tf.get_default_graph()
    with gfile.FastGFile(output_graph_path, 'rb') as f:
        output_graph_def.ParseFromString(f.read())
        _ = tf.import_graph_def(output_graph_def, name="")
        # 得到当前图有几个操作节点
        print("%d ops in the final graph." % len(output_graph_def.node))

        tensor_name = [tensor.name for tensor in output_graph_def.node]
        print(tensor_name)
        print('---------------------------')
        # 在log_graph文件夹下生产日志文件,可以在tensorboard中可视化模型
        # summaryWriter = tf.summary.FileWriter('log_graph/', graph)

        for op in graph.get_operations():
            # print出tensor的name和值
            print(op.name, op.values())

猜你喜欢

转载自blog.csdn.net/qq_36653505/article/details/86526310