tf的ExponentialMovingAverage滑动平均实现

# -*- coding: utf-8 -*-
"""
Created on Fri Jan 11 22:34:48 2019

@author: ZZL
"""
import tensorflow as tf
w = tf.Variable([1.,1.])
ema = tf.train.ExponentialMovingAverage(0.9)
update = tf.assign_add(w, [2.,2.])

with tf.control_dependencies([update]):
    #返回一个op,这个op用来更新moving_average,i.e. shadow value
    ema_op = ema.apply([w])#这句和下面那句不能调换顺序
# 以 w 当作 key, 获取 shadow value 的值
ema_val = ema.average(w)  #参数可以是list,有点蛋疼

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    for i in range(3):
        sess.run(ema_op)
        print(sess.run(ema_val))
    print(sess.run(tf.get_collection(tf.GraphKeys.UPDATE_OPS)))
    print(sess.run(tf.moving_average_variables()))  # 返回的是 滑动平均变量- w的更新后的值 [array([7., 7.], dtype=float32)]
    print(sess.run(w))
# 创建一个时间序列 1 2 3 4
#输出:
#1.2      =0.9*1 + 0.1*(1+2)
#1.58     =0.9*1.2+0.1*(1+2+2) = 1.08+0.1*5= 1.58
#2.122    =

 

你可能感兴趣的:(Tensorflow)