tensorflow框架.ckpt .pb模型节点tensor_name打印及ckpt模型转.pb模型

转换模型首先要知道的是从哪个节点输出,如果没有源代码是很难清楚节点信息。

获取ckpt模型的节点名称

import os
from tensorflow.python import pywrap_tensorflow

checkpoint_path = os.path.join('./ade20k', "model.ckpt-27150")
reader = pywrap_tensorflow.NewCheckpointReader(checkpoint_path)
var_to_shape_map = reader.get_variable_to_shape_map()
for key in var_to_shape_map:
    print("tensor_name: ", key)
    # print(reader.get_tensor(key)) #相应的值

获取pb模型的节点名称

import tensorflow as tf
import os

model_dir = './'
model_name = 'model.pb'

def create_graph():
    with tf.gfile.FastGFile(os.path.join(
            model_dir, model_name), 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        tf.import_graph_def(graph_def, name='')
        
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')

ckpt转换为pb模型

from tensorflow.python.tools import inspect_checkpoint as chkp
import tensorflow as tf

saver = tf.train.import_meta_graph("./ade20k/model.ckpt-27150.meta", clear_devices=True)

#【敲黑板!】这里就是填写输出节点名称惹
output_nodes = ["xxx"] 

with tf.Session(graph=tf.get_default_graph()) as sess:
    input_graph_def = sess.graph.as_graph_def()
    saver.restore(sess, "./ade20k/model.ckpt-27150")
    output_graph_def = tf.graph_util.convert_variables_to_constants(sess,
                                                                    input_graph_def,
                                                                    output_nodes)
    with open("frozen_model.pb", "wb") as f:
        f.write(output_graph_def.SerializeToString())

[new version] ckpt to pb

import tensorflow as tf
from tensorflow.python.framework import graph_util

checkpoint = "model.ckpt-xxx"
graph_file = "xxx.pb"


def return_ops(candidate):
    ops = []
    if isinstance(candidate, (list, tuple)):
        for x in candidate:
            ops += return_ops(x)
    else:
        ops.append(candidate.op)

    return ops


def dump_graph():
    with tf.Graph().as_default():
        inputs = setup_input(dtype=tf.float32,
                             shape=[None, 224, 224, 3],
                             name='graph_input')

        outputs = model_inference(inputs, 1000)

        model_info = gen_info(inputs, outputs)
        print(model_info)

        saver = tf.train.Saver(tf.global_variables())
        dest_node = return_ops(outputs)

        with tf.Session() as sess:
            saver.restore(sess, checkpoint)
            cur_graphdef = sess.graph.as_graph_def()
            output_graphdef = graph_util.convert_variables_to_constants(
                sess, cur_graphdef, [n.name for n in dest_node])

            with tf.gfile.GFile(graph_file, 'wb') as gf:
                gf.write(output_graphdef.SerializeToString())

            with open(graph_file + '.info', 'w') as info_f:
                info_f.write(model_info)


def setup_input(dtype, shape, name=None):
    p_node = tf.Placeholder(dtype=dtype, shape=shape, name=name)
    return p_node


def gen_info(inp, o):
    info_text = '[input tensor]: {0}\n[input shape]: {1}\n'.format(
        inp.name, inp.get_shape())
    print("outp", o)
    info_text += '[output tensor]: {0}\n[output shape]: {1}\n'.format(
        o.name, o.get_shape())

    return info_text


def model_inference(images, num_classes):
    with tf.variable_scope('xxx'):
        logits = tf.xxx
    return logits


if __name__ == "__main__":
    dump_graph()
    print('dump finish!')

  • 5
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 34
    评论
评论 34
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值