Skip to main content
 首页 » 编程设计

python之TensorFlow:如何重用 Adam 优化器变量

2024年10月01日34oomusou

最近升级我的 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)但是我得到了错误,因为权重变量 M-conv1/weights/Adam/ 当我尝试更新 S 分支时已经存在。

在我更新我的 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)) 

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

请您参考如下方法:

原来我不需要实例化两个不同的 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,即使 M 分支名称发生冲突,使用两个 Adam 实例也没有问题......