【问题标题】:optimizer.applyGradient doesnt work in tensorflowoptimizer.apply Gradient 在张量流中不起作用
【发布时间】:2017-03-14 03:42:02
【问题描述】:

我正在尝试更改 tensorflow 中的渐变,然后尝试使用 applyGradient() 函数进行更新。这是我的代码,它不起作用

cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y, y_))
optimizer = tf.train.AdamOptimizer(LEARNING_RATE)
        for j in range(n_rounds):
            sample = np.random.randint(row, size=int(batch_size))
            batch_xs = temp[sample][:]
            batch_ys = output[sample][:]
            vars_with_grads = sess.run(optimizer.compute_gradients(cross_entropy), feed_dict={x: batch_xs, y_: batch_ys})
            noiseAddedGradient = []
            print(vars_with_grads)
            for var in vars_with_grads:
                gaussianNoise = [np.random.normal(MEAN_FOR_AUTOENCODER, SCALE_FOR_AUTOENCODER, var[0].shape) for i in range(int(batch_size))]
                totalGaussianNoise = [sum(x) for x in zip(*gaussianNoise)]
                averageGaussianNoise = [x1 / float(batch_size) for x1 in totalGaussianNoise]
                averageGaussianNoiseList = np.array(averageGaussianNoise).flatten().reshape(var[0].shape)
                noiseAddedGradient.append((tf.Variable(np.add(var[0], averageGaussianNoiseList), dtype=np.float32), var[1]))
            appliedGradient = sess.run(optimizer.apply_gradients(noiseAddedGradient))

返回错误函数:

Traceback (most recent call last):
  File "/home/Downloads/objectPerturbation.py", line 214, in <module>
    appliedGradient = sess.run(optimizer.apply_gradients(noiseAddedGradient))
  File "/home/anaconda2/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 384, in apply_gradients
    p = _get_processor(v)
  File "/home/anaconda2/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 98, in _get_processor
    if v.op.type == "ReadVariableOp":
AttributeError: 'numpy.ndarray' object has no attribute 'op'

你能帮帮我吗?

【问题讨论】:

  • 您正在向训练循环中的图表添加操作。你不想那样做。原因见stackoverflow.com/questions/36230559/…
  • 您能解释一下原因吗?我只想为渐变添加噪点。它可能会慢一些,但现在对我来说并不重要。
  • 重要的不是你做什么,而是你怎么做。 TF是先建立图,然后在不改变图的情况下循环运行图。您不应该在循环中调用 tf.Variable 或 optimizer.compute_gradients(cross_entropy) 或 optimizer.apply_gradients(noiseAddedGradient),因为它们在每次迭代中都会向计算图中添加一些内容。相反,您想在训练循环之外创建它们,然后在训练循环中运行它们。不要为每个 python 值创建一个变量,而是使用 feed dicts 将 python 值输入 TF。
  • 实际上,如果您在分布式环境中做某事并且必须将渐变发送到其他机器,那么将其放在图表中是不合适的。也可以按照建议的方式进行测试。

标签: python-2.7 optimization tensorflow gradient


【解决方案1】:

尝试像这样改变它。应该在图中计算梯度。

cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y, y_))
optimizer = tf.train.AdamOptimizer(LEARNING_RATE)
grads = optimizer.compute_gradients(cross_entropy)
grad_placeholder = [(tf.placeholder("float", shape=grad[1].get_shape()), grad[1] for grad in grads]
apply_placeholder_op = opt.apply_gradients(grad_placeholder)

#added in case you don't do this
sess.run(tf.initialize_all_variables())

    for j in range(n_rounds):
        sample = np.random.randint(row, size=int(batch_size))
        batch_xs = temp[sample][:]
        batch_ys = output[sample][:]
        vars_with_grads = sess.run(grads, feed_dict={x: batch_xs, y_: batch_ys})
        #Add gaussian noise to gradients
        feed_dict = {}
        for i in range(len(grad_placeholder)):
            feed_dict[grad_placeholder[i][0]] = add_gaussian_noise_fn(grad_vals[i])
        sess.run(apply_placeholder_op, feed_dict=feed_dict)

#separate function to make it more general to do whatever you want with grads
def add_gaussian_noise_fn(x):
  return x + np.random.normal(size=x.shape)

想法与上一篇文章类似: Efficiently grab gradients from TensorFlow?

【讨论】:

  • 和以前一样的错误?你也可以试试 sess.run(grads[0])
  • 是的,和以前一样的错误。我只想添加噪音,但我做不到。
  • 我想我最初误读了错误。我会尝试用不同的版本更新我的答案。现在的主要问题是您在计算图之外创建一个 tf.Variable 。之后您应该只做纯 numpy,然后将其添加回图表。
  • 如果您对更新后的答案仍有任何问题,请告诉我。
猜你喜欢
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-20
  • 1970-01-01
  • 2017-10-14
  • 1970-01-01
  • 2021-06-29
相关资源
最近更新 更多