Tensorflow(三)--持久化模型(1)

"""
#存储
import tensorflow as tf
#重构计算图,注意计算图和变量取值分开看,计算图是结构而值是计算图中变量具体的取值
a=tf.Variable(tf.constant(1),name="v1")  #在checkpoint文件中的名字为v1
b=tf.Variable(tf.constant(1),name="v2")

saver=tf.train.Saver()
result=a+b
ini_op=tf.initialize_all_variables()
with tf.Session() as sess:
    sess.run(ini_op)
    saver.save(sess,"/model/model.ckpt")
"""
"""
#同名字恢复
import tensorflow as tf
m=tf.Variable(tf.constant(1),name="v1")  #name参数与存储的名字一样
n=tf.Variable(tf.constant(1),name="v2")

saver=tf.train.Saver([m,n])   #取与m,n变量name对应存储的变量值,也可以传入[m]表示只取m
result=m+n
with tf.Session() as sess:
    saver.restore(sess,"/model/model.ckpt")  #运行成功说明在checkpoint记录的是变量name
"""
"""
#重命名实现
import tensorflow as tf
a=tf.Variable(tf.constant(1),name="model_1")  #name参数与存储的名字不一样
b=tf.Variable(tf.constant(1),name="model_2")

saver=tf.train.Saver({"v1":a,"v2":b})   #传入字典,如果参数为空,那么tensroflow默认传入key值为上诉的变量对象组成的列表
result=a+b
with tf.Session() as sess:
    saver.restore(sess,"/model/model.ckpt")
"""
"""
#上诉的重命名变量可以很方便的应用到前向传播中,我们可以读取训练好的
#模型的影子变量传入前向传播函数里得到预测值,下面创建保存滑动平均模型的样例
import tensorflow as tf
v=tf.Variable(0,name='v',dtype=tf.float32)

mean_class=tf.train.ExponentialMovingAverage(0.99)
mean_op=mean_class.apply(tf.all_variables())

saver=tf.train.Saver()
with tf.Session() as sess:
    tf.initialize_all_variables().run()
    sess.run(tf.assign(v,10))
    sess.run(mean_op)
    saver.save(sess,"D:/model/model.ckpt")
"""
#恢复滑动平均模型
import tensorflow as tf
v=tf.Variable(0,dtype=tf.float32,name="v")

mean_class=tf.train.ExponentialMovingAverage(0.99)
saver=tf.train.Saver(mean_class.variables_to_restore()) #默认所有可训练变量和有影子变量的变量
#If an ExponentialMovingAverage object is created and the apply() method is
#called on a list of variables, these variables will be added to the
#GraphKeys.MOVING_AVERAGE_VARIABLES collection.
with tf.Session() as sess:
    saver.restore(sess,"D:/model/model.ckpt")
    print(sess.run(v))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值