变量的滑动平均值模型

保存滑动平均值的模型

example:

import tensorflow as tf
 v = tf.Variable(0, dtype = tf.float32, name = "v")
#没有申明滑动平均模型时只有一个变量v
for variables in tf.all_variables():
    pirnt(variable.name)
    #输出v:0

ema = tf.train.ExponentialMovingAverage(0.99)
maintain_average_op = ema.apply(tf.all_variables())

#申明滑动平均模型之后,Tensorflow 会自动生成一个影子变量"v/ExponentialMoving Average

for variables in tf.all_variable():
    print(variables.name)
    #output: v:0, v/ExponentialMoving: 0

saver = tf.train.Saver()
with tf.Session() as sess:
    init_op = tf.initialize_all_variables()
    sess.run(init_op)

    sess.run(tf.assgin(v, 10))
    sess.run(maintain_average_op)
    saver.save(sess, "/path/to/model/model.ckpt")
    #v:o, v/ExeponentialMovingAverage:0,都将保存
    print(sess.run([v, ema.average(v)])
    #输出:[10.0, 0.099999905]

通过变量重新命名直接读取变量的滑动平均值

v = tf.Variable(0, dtype = tf.float32, name = 'v')
#通过变量重命名 将原来的变量v的ExeponentialMovingAverage 赋值给v
saver = tf.train.Saver({"v/ExeponentialMovingAverage": v})
with tf.Session() as sess:
    saver.restore(sess, "/path/to/model/model.ckpt")
    print("sess.run(v)")
    #输出 0.099999905, 为原来模型中变量v的滑动平均值

为了方便加载时候的重命名, ema.variables_to_restore() 生成tf.train.Saver类所需要的变量重命名字典。

即把saver = tf.train.Saver({“v/ExeponentialMovingAverage”: v})
替换成saver = tf.train.Saver(ema.variables_to_restore())

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值