【TensorFlow】模型持久化tf.train.Saver—下(九)

tf.train.Saver类也支持在保存和加载时给变量重命名,声明Saver类对象的时候使用一个字典dict重命名变量即可,{“已保存的变量的名称name”: 重命名变量名},saver = tf.train.Saver({“v1”:u1, “v2”: u2})即原来名称name为v1的变量现在加载到变量u1(名称name为other-v1)中。

import tensorflow as tf  

# 声明的变量名称name与已保存的模型中的变量名称name不一致  
u1 = tf.Variable(tf.constant(1.0, shape=[1]), name="other-v1")  
u2 = tf.Variable(tf.constant(2.0, shape=[1]), name="other-v2")  
result = u1 + u2  

# 若直接生命Saver类对象,会报错变量找不到  
# 使用一个字典dict重命名变量即可,{"已保存的变量的名称name": 重命名变量名}  
# 原来名称name为v1的变量现在加载到变量u1(名称name为other-v1)中  
saver = tf.train.Saver({"v1": u1, "v2": u2})  

with tf.Session() as sess:  
    saver.restore(sess, "./Model/model.ckpt")  
    print(sess.run(result)) # [ 3.] 

tf.train.Saver类支持在保存和加载时给变量重命名目的之一就是方便使用变量的滑动平均值,滑动平均值可以让神经网络模型更robust稳健。如果在加载模型时直接将影子变量映射到变量自身,则在使用训练好的模型时就不需要再调用函数来获取变量的滑动平均值了。载入时,声明Saver类对象时通过一个字典将滑动平均值直接加载到新的变量中;saver = tf.train.Saver({“v/ExponentialMovingAverage”: v});
通过tf.train.ExponentialMovingAverage的variables_to_restore()函数获取变量重命名字典。

import tensorflow as tf  

v = tf.Variable(0, dtype=tf.float32, name="v")  
for variables in tf.global_variables():  
    print(variables.name) # v:0  

ema = tf.train.ExponentialMovingAverage(0.99)  
maintain_averages_op = ema.apply(tf.global_variables())  
for variables in tf.global_variables():  
    print(variables.name) # v:0  
                          # v/ExponentialMovingAverage:0  

saver = tf.train.Saver()  

with tf.Session() as sess:  
    sess.run(tf.global_variables_initializer())  
    sess.run(tf.assign(v, 10))  
    sess.run(maintain_averages_op)  
    saver.save(sess, "Model/model_ema.ckpt")  
    print(sess.run([v, ema.average(v)])) # [10.0, 0.099999905]  

以下代码给出了如何通过变量重命名直接读取变量的滑动平均值。从下面的代码读取的变量V的值实际上是上面代码中变量V的滑动平均值。通过这个方法可以使用完全一样的代码来计算滑动平均值的前向传播的结果。

import tensorflow as tf  

v = tf.Variable(0, dtype=tf.float32, name="v")  
# 注意此处的变量名称name一定要与已保存的变量名称一致  
ema = tf.train.ExponentialMovingAverage(0.99)  
print(ema.variables_to_restore())  
# {'v/ExponentialMovingAverage': <tf.Variable 'v:0' shape=() dtype=float32_ref>}  
# 此处的v取自上面变量v的名称name="v"  

saver = tf.train.Saver(ema.variables_to_restore())  

with tf.Session() as sess:  
    saver.restore(sess, "./Model/model_ema.ckpt")  
    print(sess.run(v)) # 0.0999999  

通过convert_variables_to_constants函数将计算图中的变量及其取值通过常量的方式保存于一个文件中

# Part8: 通过convert_variables_to_constants函数将计算图中的变量及其取值通过常量的方式保存于一个文件中  

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

v1 = tf.Variable(tf.constant(1.0, shape=[1]), name="v1")  
v2 = tf.Variable(tf.constant(2.0, shape=[1]), name="v2")  
result = v1 + v2  

with tf.Session() as sess:  
    sess.run(tf.global_variables_initializer())  
    # 导出当前计算图的GraphDef部分,即从输入层到输出层的计算过程部分  
    graph_def = tf.get_default_graph().as_graph_def()
    #['add']参数给出了需要保存的节点名称。add节点是上述定义的两个变量相加的操作
    #值得注意的是这里给出的是计算节点的名称,所以没有后面的:0。  
    output_graph_def = graph_util.convert_variables_to_constants(sess,  
                                                        graph_def, ['add'])  
    #将导出的模型存入文件
    with tf.gfile.GFile("Model/combined_model.pb", 'wb') as f:  
        f.write(output_graph_def.SerializeToString())  

当只需要得到计算图中某个节点的取值时,这里的方法就比较简单了,并且使用这个方法很好的完成迁移学习。

import tensorflow as tf  
from tensorflow.python.platform import gfile  

with tf.Session() as sess:  
    model_filename = "Model/combined_model.pb"  
    with gfile.FastGFile(model_filename, 'rb') as f:  
        graph_def = tf.GraphDef()  
        graph_def.ParseFromString(f.read())  

    result = tf.import_graph_def(graph_def, return_elements=["add:0"])  
    print(sess.run(result)) # [array([ 3.], dtype=float32)]  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值