关于循环调用Variable RNN的reuse问题
问题:Variable already exists
问题描述:Variable rnn/basic_lstm_cell/kernel already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope? Originally defined at:
原因
数据格式如下:需要对不同ID的数据分别进行神经网络的预测,for循环下每个ID都调用一次搭建的RNN模型,这种情况下就出现了reuse的问题。
解决
-
如果只需要计算一次RNN模型,那么常见的解决的解决方法是在rnn_cell上使用 with tf.variable_scope即可,reuse = ‘None’ ,‘True’, ‘tf.AUTO_REUSE’
需要注意的是如果有两个cell且名称一致的话, 第一个的cell 上面一定写上resuse = ’None’或’tf.AUTO_REUSE’ ,第二个之后要写’True’ 。 -
或者,你可以直接给两个cell其不同的名字。
with tf.variable_scope('lstm',reuse=tf.AUTO_REUSE):
rnn_cell = tf.contrib.rnn.BasicLSTMCell(num_units=128)
#####有两个cell,起不同的名字 或者 设置reuse #######
with tf.variable_scope('lstm',reuse=None):
rnn_cell = tf.contrib.rnn.BasicLSTMCell(num_units=128)
with tf.variable_scope('lstm',reuse=True):
rnn_cell = tf.contrib.rnn.BasicLSTMCell(num_units=128)
- 我遇到的是需要不断的调用计算,所以设置reuse就没有效果了。因为如果设置为’True’ ,则违背了第一个cell不同为True的原则,如果设置为另外两个,又违背了之后要令cell为True的原则,所以只能用改名的方法了。代码示例如下:
###for对user_id的循环下##
flage =str(user_id)
####在网络中传递 flage ,使每次调用cell都有不同的名字,这个问题就解决了。
def model_loss(flage,ac_fn, keep_prob, input_, label_):
with tf.variable_scope(flage,reuse=tf.AUTO_REUSE):
rnn_cell = tf.contrib.rnn.BasicLSTMCell(num_units=128)
outputs, (h_c, h_n) = tf.nn.dynamic_rnn(
rnn_cell, # cell you have chosen
input_, # input
initial_state=None, # the initial hidden state
dtype=tf.float32, # must given if set initial_state = None
time_major=False, # False: (batch, time step, input); True: (time step, batch, input)
)
train_features, train_targets, val_features, val_targets, test_features, leaky_relu)
这是一个小问题,但是当时没想明白,对tensorflow的reuse设置也不了解,所以还是记录一下。另外,如果以上方法还没解决这个问题,可以考虑重启python核,另外 tf.reset_default_graph() 放在程序开始也是常见的操作。