【问题标题】:gradients with respect to a repeating function关于重复函数的梯度
【发布时间】:2018-02-12 06:28:47
【问题描述】:

我在计算重复调用的转换函数的梯度时遇到问题。

相对于动作计算的梯度是 None 即使损失取决于通过重复转换调用生成的最大值之和选择的选定动作。如果我们将损失函数的值更改为 v 的总和而不是 a,那么我们会收到过渡的梯度。

当我们的损失是根据 a 上的总和计算时,为什么没有为过渡计算梯度?

下面是一段示例代码,您可以在其中复制问题。

import tensorflow as tf
import numpy as np

ACTION_DIM = 1

# random input
x = tf.Variable(np.random.rand(1, 5))  # [b branches, state_dim]

depth = 3
b = 4
v_list, a_list = [], []  # value and action store
# make value estimates 3 steps into the future by predicting intermediate states
for i in range(depth):
    reuse = True if i > 0 else False
    x = tf.tile(x, [b, 1])  # copy the state to be used for b different actions
    mu = tf.layers.dense(x, ACTION_DIM, name='mu', reuse=reuse)
    action_distribution = tf.distributions.Normal(loc=mu, scale=tf.ones_like(mu))
    a = tf.reshape(action_distribution.sample(1), [-1, ACTION_DIM])
    x_a = tf.concat([x, a], axis=1)  # concatenate action and state
    x = tf.layers.dense(x_a, x.shape[-1], name='transition', reuse=reuse)  # next state s'
    v = tf.layers.dense(x, 1, name='value', reuse=reuse)  # value of s'
    v_list.append(tf.reshape(v, [-1, b ** i]))
    a_list.append(tf.reshape(a, [-1, b ** i]))

# backup our sum of max values along trajectory
sum_v = [None]*depth
sum_v[-1] = v_list[-1]
for i in reversed(range(depth)):
    max_v_i = tf.reduce_max(v_list[i], axis=1)
    if i > 0:
        sum_v[i-1] = tf.reduce_max(v_list[i-1], axis=1) + max_v_i

max_idx = tf.reshape(tf.argmax(sum_v[0]), [-1, 1])
v = tf.gather_nd(v_list[0], max_idx)
a = tf.gather_nd(a_list[0], max_idx)
loss = -tf.reduce_sum(a)
opt = tf.train.AdamOptimizer()
grads = opt.compute_gradients(loss)

【问题讨论】:

    标签: python tensorflow deep-learning reinforcement-learning


    【解决方案1】:

    我相信问题源于您在定义col_idx 时调用arg_maxArg_max 是一个位置参数,因此没有渐变。这是有道理的,因为最大值在列表中的位置不会随着最大值的变化而变化。

    我也不相信对tf.contrib.distributions.Normal 的调用会对其输入变量产生导数,但这仅仅是因为它在contrib 中。如果修复 arg_max 后问题仍然存在,也许您可​​以尝试使用默认的 tensorflow。

    【讨论】:

    • argmax 梯度将仅通过最大输入路径“引导”梯度。为了进一步参考,这里进行了很好的讨论:reddit.com/r/MachineLearning/comments/4e2get/…
    • 你引用的解释很好,但我不同意你的观点。我相信他们是说max 操作通过最大输入路径引导梯度,但argmax 操作没有。这就是我们所期望的,因为张量的最大值的导数随着最大值的变化而线性变化。最大值的位置没有,因此不应定义渐变。
    • 你是对的。抱歉,我的速度不够快,无法完全掌握您的第一篇文章,感谢您抽出宝贵时间来解决问题。
    猜你喜欢
    • 2017-12-11
    • 1970-01-01
    • 2022-01-24
    • 2011-10-28
    • 1970-01-01
    • 2020-05-12
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多