再进入正题前,我们先介绍一下checkpoint(ckpt)和pb的区别和联系

model 保存方法 结果文件 加载
ckpt tf.train.Saver()

主要的4个文件

checkpoint                  

model.ckpt.data-xxx  

model.ckpt.index     

model.ckpt.meta        

tf.train.Saver() saver.restore() 

pb
SerializeToString()函数序列化
pb文件 见下文

pb模型文件具有语言独立性,可独立运行,封闭的序列化格式,支持其他语言解析,而且模型的变量都是固定的,模型的大小减小,一个模型文件也便于之后的使用。

tf生成pb文件

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

with tf.Session(graph=tf.Graph()) as sess:
    # 定义输入变量名
    x = tf.placeholder(tf.int32, name='x')
    y = tf.placeholder(tf.int32, name='y')
    b = tf.Variable(1, name='b')
    xy = tf.multiply(x, y)
    # 输出,需要加上变量名
    output = tf.add(xy, b, name='output')

    sess.run(tf.global_variables_initializer())

    # convert_variables_to_constants 需要指定output_node_names
    constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph_def, ['output'])

    print(sess.run(output, feed_dict={x: 2, y: 5}))

    # 写入序列化的pb文件
    with tf.gfile.FastGFile('model.pb', mode='wb') as f:
        f.write(constant_graph.SerializeToString())

tf加载pb文件

from tensorflow.python.platform import gfile

sess = tf.Session()
with gfile.FastGFile('model.pb', 'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    sess.graph.as_default()
    tf.import_graph_def(graph_def, name='')  # 导入计算图

# 需要有一个初始化的过程
sess.run(tf.global_variables_initializer())

# 输入
input_x = sess.graph.get_tensor_by_name('x:0')
input_y = sess.graph.get_tensor_by_name('y:0')

op = sess.graph.get_tensor_by_name('output:0')

res = sess.run(op, feed_dict={input_x: 5, input_y: 5})
print(res)

tips:应用到自己的程序中记得在输出添加变量名(如:output = tf.add(xy, b, name='output')),加载时获取输入输出变量名,将值传给输入变量,sess.run()即可

Logo

新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐