Skip to main content
 首页 » 编程设计

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

2024年10月24日38EasonJim

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