注: 本文是作者的自我总结,主要作为个人总结记录, 欢迎大家批评,交流. 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之内执行时, 权重共享就可以了. 当然这都是我个人猜测的结果, 欢迎大家批评指正, 交流分享. 我发现原因之后,再来更新.