gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:12:46 26 4
gpt4 key购买 nike

我刚开始使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com