[Solved] Tensorflow: 使用Adam优化器时,可能出现的错误 Adam权重不存在 weights/Adam/ does not exist

在修改WGAN代码为WGAN-GP时,遇到Adam优化器错误:权重不存在。通过调整tf.get_variable_scope().reuse_variables()位置,从variable scope外移至内,成功解决错误。分享详细解决过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注: 本文是作者的自我总结,主要作为个人总结记录, 欢迎大家批评,交流. https://zhouxiaowei1120.github.io/#blogs

Tensorflow 中使用Adam优化器可能出现的错误

问题: Adam 权重不存在 weights/Adam/ does not exist

昨天在把WGAN的代码修改为WGAN-GP的代码时发现,原本正常使用的Adam优化器,突然报出如下错误:

ValueError: Variable d_h0_conv/w/Adam/ does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=None in VarScope?

找了很多的解决办法,发现不奏效. 最后在github的一个网页中找到了一个解决办法,结果一试,解决了问题. 在此谢过作者, 并附上作者链接: DCGAN-tensorflow

解决过程
错误的代码:
if reuse:
        tf.get_variable_scope().reuse_variables()
with tf.name_scope('Decoder'):
    with tf.variable_scope('Decoder'):
        with tf.variable_scope('conv1'):
            x = _conv_layer(x, [3, 3, 1, 64],[64],layername='conv1_1')
            x = _conv_layer(x, [3, 3, 64, 64],[64],layername='conv1_2')
            d_x_block1 = _pool_layer(x, layer_name='block1_pool', kernel_size=(1, 2, 2, 1), strides_size=(1, 2, 2, 1))
后面的代码省略....
正确的代码:
with tf.name_scope('Decoder'):
   with tf.variable_scope('Decoder'):
       if reuse:
           tf.get_variable_scope().reuse_variables() #主要问题是reuse variables这行代码的位置不同
       with tf.variable_scope('conv1'):
           x = _conv_layer(x, [3, 3, 1, 64],[64],layername='conv1_1')
           x = _conv_layer(x, [3, 3, 64, 64],[64],layername='conv1_2')
           d_x_block1 = _pool_layer(x, layer_name='block1_pool', kernel_size=(1, 2, 2, 1), strides_size=(1, 2, 2, 1))
后面的代码省略...

可以看出,主要的差别就是权重共享(Variables Share)对应的代码,其出现的位置不同.
至于为什么放在variable scope之内, 代码就不会报错, 个人认为get_variable_scope().reuse_variables() 这行代码, 在variable scope之内和之外时, 获取的scope范围不同, 所以权重共享的作用范围也不同.
个人猜测, get_variable_scope().reuse_variables() 在 variable scope 之外执行时, 权重共享不包含Adam优化器的Adam权重. 而放在variable scope之内执行时, 权重共享就可以了. 当然这都是我个人猜测的结果, 欢迎大家批评指正, 交流分享. 我发现原因之后,再来更新.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值