代码之家  ›  专栏  ›  技术社区  ›  I. A Ziang Yan

为什么不能将赋值操作作为参数添加到tensorflow中的控件相关性中?

  •  0
  • I. A Ziang Yan  · 技术社区  · 7 年前

    我有一个简单的模型。但是我需要在执行更新之前修改一个变量。因此,我有以下几点:

    l = tf.Variable(tf.constant(0.01), trainable=False, name="l")
    baseline = tf.Variable(tf.constant(0.0), dtype=tf.float32, name="baseline")
    
    # Actor optimizer
    # Note that our target is: e^{-L} where L is the loss on the validation dataset. 
    # So we pass to the target mae_loss in the code below
    def optimize_actor(scores_a, scores_v, target):
        with tf.name_scope('Actor_Optimizer'):
            update_moving_loss = tf.assign(baseline, l * baseline + (1 - l) * target, name="update_baseline")
            dec_l = l.assign_add(0.001)
    
            update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
            with tf.control_dependencies([update_ops, update_moving_loss, dec_l]):
                loss_a = scores_a * tf.exp(target - baseline)
                loss_v = scores_v * tf.exp(target - baseline)
                actor_a_optimizer = tf.train.AdamOptimizer(0.0001).minimize(loss_a)
                actor_v_optimizer = tf.train.AdamOptimizer(0.0001).minimize(loss_v)
        return actor_a_optimizer, actor_v_optimizer
    

    因此,在运行上述脚本时,我出现以下错误:

    Can not convert a list into a Tensor or Operation.
    

    导致此问题的原因是 update_moving_loss dec_l 。当我删除它们时,代码运行良好。

    请注意,我使用的是tensorflow 1.7

    非常感谢您的帮助!!!

    1 回复  |  直到 7 年前
        1
  •  1
  •   mikkola    7 年前

    我无法重现您的问题,但我猜问题在于使用 tf.get_collection 。如 documentation ,它将返回 列表 集合中的值。让我们称之为列表 L 使事情简洁明了。

    然后您可以这样做:

    L = tf.get_collection(tf.GraphKeys.UPDATE_OPS)    
    with tf.control_dependencies([L, tensor1, tensor2]):
             ...
    

    这里的论点是另一个列表,包含三个元素:你的列表 L 和两个张量。这就是问题所在:第一个元素是一个列表,因此您可以看到

    Can not convert a list into a Tensor or Operation.
    

    你可以通过以下方式解决这个问题: 追加 而不是制作另一个包含列表的列表:

    L = tf.get_collection(tf.GraphKeys.UPDATE_OPS)    
    with tf.control_dependencies( L + [tensor1, tensor2]):
             ...
    

    这个 + 运算符将新的列表元素添加到原始列表中 L