如果我不在 sess.run(train_step) 中再次提供 feed_dict,您发布的方法似乎会失败。我不知道为什么需要 feed_dict,但有可能再次运行所有累加器,并重复最后一个示例。在我的情况下,这是我必须做的:
self.session.run(zero_ops)
for i in range(0, mini_batch):
self.session.run(accum_ops, feed_dict={self.ph_X: imgs_feed[np.newaxis, i, :, :, :], self.ph_Y: flow_labels[np.newaxis, i, :, :, :], self.keep_prob: self.dropout})
self.session.run(norm_acums, feed_dict={self.ph_X: imgs_feed[np.newaxis, i, :, :, :], self.ph_Y: flow_labels[np.newaxis, i, :, :, :], self.keep_prob: self.dropout})
self.session.run(train_op, feed_dict={self.ph_X: imgs_feed[np.newaxis, i, :, :, :], self.ph_Y: flow_labels[np.newaxis, i, :, :, :], self.keep_prob: self.dropout})
为了标准化梯度,我知道这只是将累积的梯度除以批量大小,所以我只添加一个新的操作
norm_accums = [accum_op/float(batchsize) for accum_op in accum_ops]
有人遇到过同样的 feed_dict 问题吗?
*更新
正如我所怀疑的那样,它使用批处理中的最后一个示例再次运行所有图。
这个小代码测试一下
import numpy as np
import tensorflow as tf
ph = tf.placeholder(dtype=tf.float32, shape=[])
var_accum = tf.get_variable("acum", shape=[],
initializer=tf.zeros_initializer())
acum = tf.assign_add(var_accum, ph)
divide = acum/5.0
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(5):
sess.run(acum, feed_dict={ph: 2.0})
c = sess.run([divide], feed_dict={ph: 2.0})
#10/5 = 2
print(c)
#but it gives 2.4, that is 12/5, so sums one more time
我想出了如何解决这个问题。所以,张量流有条件操作。我放
一个分支中的累积和另一个分支中的归一化和更新的最后累积。我的代码是一团糟,但是为了快速检查我说我让一个使用示例的小代码。
import numpy as np
import tensorflow as tf
ph = tf.placeholder(dtype=tf.float32, shape=[])
#placeholder for conditional braching in the graph
condph = tf.placeholder(dtype=tf.bool, shape=[])
var_accum = tf.get_variable("acum", shape=[], initializer=tf.zeros_initializer())
accum_op = tf.assign_add(var_accum, ph)
#function when condition of condph is True
def truefn():
return accum_op
#function when condtion of condph is False
def falsefn():
div = accum_op/5.0
return div
#return the conditional operation
cond = tf.cond(condph, truefn, falsefn)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(4):
#run only accumulation
sess.run(cond, feed_dict={ph: 2.0, condph: True})
#run acumulation and divition
c = sess.run(cond, feed_dict={ph: 2.0, condph: False})
print(c)
#now gives 2
*重要提示:忘记一切都不起作用。优化器放弃了失败。