代码改变世界

ValueError: 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:

2019-04-20 16:50  zYaMei  阅读(7181)  评论(0编辑  收藏  举报

问题

  ValueError: 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:

原因

  调用了两次RNN网络,在第二次调用的时候报了上面这个错误。主要是因为第二次的变量名和第一次的变量名一样,导致了变量命名相同的冲突。在Tensorflow中有两种方法生成变量variable,tf.get_variable()tf.Variable()。在tf.name_scope()的框架下使用这两种方法,使用tf.Variable(),尽管name一样,但为了不重复变量名,Tensorflow输出的变量名并不一样,所以本质上是不一样的变量;使用tf.get_variable()定义的变量虽然不会被tf.name_scope()中的名字影响,但在未指定共享变量时,如果重名了会报错。要实现变量共享,可以使用tf.variable_scope(reuse=tf.AUTO_REUSE)创建具有相同名称的作用域。

1 # 出错代码
2 with tf.name_scope("fw_side"):
3 
4 # 改成
5 with tf.name_scope("fw_side"), tf.variable_scope("fw_side", reuse=tf.AUTO_REUSE):

改了之后,在第二次调用RNN时就不会报错了。

详情了解:https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/5-12-scope/