python - Tensorflow 基础知识 - 计算累积移动平均值

标签 python tensorflow

我刚刚开始使用 Tensorflow,想知道下面的代码是否是计算累积滚动平均值的正确方法

import tensorflow as tf
import numpy as np

x = tf.Variable(0, name = "x")
x_pld = tf.placeholder(tf.int32)
update_x = tf.assign(x, x_pld)

curr_avg = tf.Variable(tf.constant(0.), name="curr_avg")
avg_pld = tf.placeholder("float")
update_avg = tf.assign(curr_avg, avg_pld)

# Initalize 
init_op = tf.initialize_all_variables()

with tf.Session() as session:
    session.run(init_op)

    for i in range(5):  
        temp_avg = session.run(curr_avg)
        session.run(update_x, feed_dict={x_pld: np.random.randint(1000)})
        new_x = session.run(x)
        print(new_x) 
        session.run(update_avg, feed_dict={avg_pld: ((temp_avg * (i)) + new_x)/(i+1)})

    print(session.run(curr_avg))

最佳答案

import numpy as np
import tensorflow as tf

# Set Variables
# only need single placeholder because only feeding in one value to graph
next_val = tf.placeholder(shape=(), dtype=tf.float32) 
cumulative = tf.Variable(0, dtype=tf.float32)
divisor = tf.Variable(0, dtype=tf.float32)

#Calculations
cumulative = cumulative.assign_add(next_val)
divisor = divisor.assign_add(1)
avg = tf.div(cumulative, divisor)

with tf.Session() as session:
    tf.initialize_all_variables().run() # run initialization of variables in graph

    for i in range(5):
        new_val = np.random.randint(1000)
        # run graph ops once, and return the result of avg
        curr_avg = session.run([avg], feed_dict={next_val: new_val})

        print "next value added: {}".format(new_val) # allows you to verify output
        print "rolling average: {}".format(curr_avg)

关于python - Tensorflow 基础知识 - 计算累积移动平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37487848/

相关文章:

python - 在表格 View 单元格内添加多列

machine-learning - Tensorflow - 图形是如何执行的?

android - Keras深度学习模型到android

python - 在 Python 中识别列表中的重复值

tensorflow - 多输入深度学习模型中两个输入的平均值

python - 将大数据加载到 TensorFlow 2.0 中,而不将其加载到 RAM 上

docker - Tensorflow/Docker对开发有用吗,还是仅用于演示/测试?

python - 如何对没有属性的 div 内的节点进行 XPath 处理

python - 识别方程中的变量

python - 如何在 Google Colab 交互式中制作 matplotlib 图