张量流基础计算累积移动平均值

2024-05-23 17:21:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚从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))

Tags: runnameimportnewsessiontfasnp
1条回答
网友
1楼 · 发布于 2024-05-23 17:21:49
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)

相关问题 更多 >