TensorFlowでBRNNなんかを実装しようとした際に出る"Matrix already exists, disallowed"


背景

TensorFlowを勉強がてらRNNを改造してBRNNの実装を試みた際、

ValueError: Variable RNN/BasicLSTMCell/Linear/Matrix already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:

というエラーが出て苦労したのでその時のメモ。

状況としては元々のRNNの実装で

lstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)

としてあった所に逆方向からの伝搬部分を付け加えて、

lstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)
blstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)#ココ追加

としたことで上述のエラーが発生した。

原因と解決策

色々調べたところどうやら双方のcellが"BiRNN_FW/RNN/BasicLSTMCell/Linear/Matrix" を使おうとすることでname collisionが起きるらしい。
そこで上記のコードを

with tf.variable_scope('forward',reuse=True):
    self.lstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)   
with tf.variable_scope('backward',reuse=True):
    self.blstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)

とすることで解決できるらしい。メモメモ

参考
Got error when initialize bidirectional rnn with LSTM cell

Jupyterで…

上記の作業をずっとJupyterで行っていたのですが、Shift + Enterでの起動やいったん「■」ボタン押して停止してから再び実行してもずっと"Matrix already exist"のエラーでっぱなしでした。
仕方ないので一度Shutdownしてから起動することでようやくエラーが消えて実行できました。