【问题标题】:TensorFlow: How can I reuse Adam optimizer variables?TensorFlow:如何重用 Adam 优化器变量?
【发布时间】:2017-05-02 19:11:28
【问题描述】:

最近升级了我的 TensorFlow 版本后,我遇到了这个我无法解决的错误:

Traceback (most recent call last):
  File "cross_train.py", line 177, in <module>
    train_network(use_gpu=True)
  File "cross_train.py", line 46, in train_network
    with tf.control_dependencies([s_opt.apply_gradients(s_grads), s_increment_step]):

...

ValueError: Variable image-conv1-layer/weights/Adam/ already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:

  File "cross_train.py", line 34, in train_network
    with tf.control_dependencies([e_opt.apply_gradients(e_grads), e_increment_step]):
  File "cross_train.py", line 177, in <module>
    train_network(use_gpu=True)

我的模型架构是 3 个不同的卷积神经网络分支:M、E、S。在训练中,我尝试交替步骤,通过 M 和 E(嵌入的点积距离)传播样本并使用 Adam 进行更新;然后通过 M&S 传播样本并使用 Adam 进行更新;并重复。所以基本上 M 是固定的(每一步都更新),但 E 和 S 分支交替更新。

因此,我创建了两个 AdamOptimizer 实例(e_opt 和 s_opt),但我收到错误消息,因为当我尝试更新 S 分支时权重变量 M-conv1/weights/Adam/ 已经存在。

在我更新我的 TensorFlow 版本之前,这并没有发生在我身上。我知道如何在TensorFlow中设置变量的重用,例如:

with tf.variable_scope(name, values=[input_to_layer]) as scope:
    try:
        weights = tf.get_variable("weights", [height, width, input_to_layer.get_shape()[3], channels], initializer=tf.truncated_normal_initializer(stddev=0.1, dtype=tf.float32))
        bias = tf.get_variable("bias", [channels], initializer=tf.constant_initializer(0.0, dtype=tf.float32))
    except ValueError:
        scope.reuse_variables()
        weights = tf.get_variable("weights", [height, width, input_to_layer.get_shape()[3], channels], initializer=tf.truncated_normal_initializer(stddev=0.1, dtype=tf.float32))
        bias = tf.get_variable("bias", [channels], initializer=tf.constant_initializer(0.0, dtype=tf.float32))

但我不确定我是否可以为亚当做同样的事情。有任何想法吗?非常感谢您的帮助。

【问题讨论】:

  • 您是否为优化操作设置了名称? optimizer = tf.train.AdamOptimizer(learning_rate=0.0001, name='first_optimizer').minimize(loss)

标签: python tensorflow conv-neural-network


【解决方案1】:

原来我不需要实例化两个不同的 Adam 优化器。我刚刚创建了一个实例,没有名称冲突或尝试共享变量的问题。无论更新哪个网络分支,我都使用相同的优化器:

    e_grads = opt.compute_gradients(e_loss)
with tf.control_dependencies([opt.apply_gradients(e_grads), e_increment_step]):
    e_train = tf.no_op(name='english_train') 

还有……

    s_grads = opt.compute_gradients(s_loss)
with tf.control_dependencies([opt.apply_gradients(s_grads), s_increment_step]):
    s_train = tf.no_op(name='spanish_train')

有趣的是,旧版本的 Tensorflow 使用两个 Adam 实例没有问题,即使 M 分支名称冲突...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-02
    • 2016-02-20
    • 2017-05-23
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    相关资源
    最近更新 更多