关于循环调用Variable RNN的reuse问题

关于循环调用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的问题。
tialhead

解决

  1. 如果只需要计算一次RNN模型,那么常见的解决的解决方法是在rnn_cell上使用 with tf.variable_scope即可,reuse = ‘None’ ,‘True’, ‘tf.AUTO_REUSE’
    需要注意的是如果有两个cell且名称一致的话, 第一个的cell 上面一定写上resuse = ’None’或’tf.AUTO_REUSE’ ,第二个之后要写’True’ 。

  2. 或者,你可以直接给两个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)       
  1. 我遇到的是需要不断的调用计算,所以设置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() 放在程序开始也是常见的操作。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值