TensorFlow 指数移动平均线

标签 tensorflow moving-average

我不知道如何让 tf.train.ExponentialMovingAverage 工作。以下是在简单的 y_ = x * w 方程中查找 w 的简单代码。 m 是移动平均线。为什么代码对 m 返回 None?如何让它返回移动平均值?

import numpy as np
import tensorflow as tf

w = tf.Variable(0, dtype=tf.float32)
ema = tf.train.ExponentialMovingAverage(decay=0.9)
m = ema.apply([w])

x = tf.placeholder(tf.float32, [None])
y = tf.placeholder(tf.float32, [None])
y_ = tf.multiply(x, w)

with tf.control_dependencies([m]):
    loss = tf.reduce_sum(tf.square(tf.subtract(y, y_)))
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
    train = optimizer.minimize(loss)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(20):
        _, w_, m_ = sess.run([train, w, m], feed_dict={x: [1], y: [10]})
        print(w_, ',', m_)

输出为:

0.02 , None
0.03996 , None
0.0598801 , None
0.0797603 , None
0.0996008 , None
0.119402 , None
0.139163 , None
0.158884 , None
0.178567 , None
0.19821 , None
0.217813 , None
0.237378 , None
0.256903 , None
0.276389 , None
0.295836 , None
0.315244 , None
0.334614 , None
0.353945 , None
0.373237 , None
0.39249 , None

最佳答案

这是因为 m (python) 变量不保存操作的结果,而是保存操作本身。请参阅文档:

Returns:
  An Operation that updates the moving averages.

要访问平均值,您需要在图表中创建一个新元素:

av = ema.average(w)

然后:

_, w_, av_ = sess.run([train, w, av], feed_dict={x: [1], y: [10]})
print(w_, ',', av_)

将打印

[0.020000001, 0.0]
[0.039960001, 0.0020000006]
[0.059880082, 0.0057960013]
[0.07976032, 0.01120441]
[0.099600799, 0.018060002]
<小时/>

完整代码

import tensorflow as tf

w = tf.Variable(0, dtype=tf.float32)
ema = tf.train.ExponentialMovingAverage(decay=0.9)
m = ema.apply([w])
av = ema.average(w)

x = tf.placeholder(tf.float32, [None])
y = tf.placeholder(tf.float32, [None])
y_ = tf.multiply(x, w)

with tf.control_dependencies([m]):
    loss = tf.reduce_sum(tf.square(tf.subtract(y, y_)))
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
    train = optimizer.minimize(loss)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(20):
        _, w_, av_ = sess.run([train, w, av], feed_dict={x: [1], y: [10]})
        print(w_, ',', av_)

关于TensorFlow 指数移动平均线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45206910/

相关文章:

python - 计算移动平均线

database - 在 Open Office 中需要一个累积移动平均线的公式

tensorflow - Keras - 自定义损失函数 - 倒角距离

python-3.x - tensorflow 1.8 与 python 3.6 在 windows64

不完整时间序列数据的运行平均值

python - 有效地采用稀疏数据的移动平均值并在python中过滤高于阈值

video - 自动选择视频的缩略图

python - Tensorflow basic_rnn_seq2seq TypeError : Expected int32, 取而代之的是 'float' 类型的 -0.1

python - 从 Cleverhans 攻击模型生成对抗数据

python - 在 python 中按定义的间隔按 id/group 移动平均值