tensorflow 常用代码片段

本文介绍了如何使用TensorFlow加载.pb文件,包括load_graph函数、分析图的输入输出节点以及如何简化模型,删除训练节点的过程。

tensorflow 常用代码片段

  • 加载pb文件
    def load_graph(frozen_graph_filename):
    with tf.io.gfile.GFile(frozen_graph_filename, “rb”) as f:
    graph_def = tf.compat.v1.GraphDef()
    graph_def.ParseFromString(f.read())
    with tf.Graph().as_default() as graph:
    tf.import_graph_def(graph_def)
    return graph

  • 写graph_def 到文件

with tf.gfile.Gfile('simplified.pb', 'wb') as fid:
    fid.write(graph_def.SerializeToString())
  • 获取图的输入输出节点名字
def analyze_inputs_outputs(graph):
    ops = graph.get_operations()
    outputs_set = set(ops)
    inputs = []
    for op in ops:
        if len(op.inputs) == 0 and op.type != 'Const':
            inputs.append(op)
        else:
            for input_tensor in op.inputs:
                if input_tensor.op in outputs_set:
                    outputs_set.remove(input_tensor.op)
    outputs = list(outputs_set)
    return (inputs, outputs)
  • 简化模型,删除训练节点
graph_def = tf.graph_util.convert_variables_to_constants(sess, graph_def, [out_name])
graph_def = tf.graph_util.remove_training_nodes(graph_def)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值