# NLP: Seq2Seq ## 過去回 [第1回:NLP Outline](https://hackmd.io/uD2hEISAShqVHD6IRtceUw) [第2回:Word2Vec](https://hackmd.io/T2QJsuwsROSQluklguDOow) [第3回:Doc2Vec](https://hackmd.io/LIT2hp_jQ56Dvn-imOVemg) ## 元論文 https://papers.nips.cc/paper/2014/file/a14ac55a4f27472c5d894ec1c3c743d2-Paper.pdf ## 要点 * **文字列を入力し文字列を出力するモデル** * **ニューラル機械翻訳(NMT)の先駆け** * **RNN(LSTM等)を使ったEncoder - Decoderモデル** ## RNN RNN(Recurrent Neural Network) 再帰構造を持ったニューラルネットワーク。 1 node の場合 ![](https://i.imgur.com/q85hxfm.png) $$ z_{t}=W_{in}\times x_{t}+W_{hh}\times z_{t-1} \\ y_{t}=W_{out}\times z_{t} $$ 例えば、次の値を入力したとき、出力がどうなるかというと。 $$ t=0 : x = a_0 \\ t=1 : x = a_1 \\ t=2 : x = a_2 $$ $t=0$における、$z_{-1}$の値は0とすると $$ t=0 : z_{0} = W_{in}\times a_0 + W_{hh}\times 0\\ t=1 : z_{1} = W_{in}\times a_1 + W_{hh}\times z_{0} \\ =W_{in}\times a_1 + W_{hh}\times W_{in}\times a_0\\ t=2 : z_{2} = W_{in}\times a_2 + W_{hh}\times z_{1}\\ =W_{in}\times a_2 + W_{hh}\times (W_{in}\times a_1 + W_{hh}\times W_{in}\times a_0) $$ $t=2$のときは、$t=0$や$t=1$の$x_0$や$x_1$を使って計算する 2 node の場合 ![](https://i.imgur.com/oirSkbd.png) 例えば、次の値を入力したとき、出力がどうなるかというと。 $$ t=0 : x1 = a_0, x2 = b_0 \\ t=1 : x1 = a_1, x2 = b_1 \\ t=2 : x1 = a_2, x2 = b_2 \\ $$ $z_1, z_2$の初期値は$0$とする。$z_{1t}, z_{2t}$の値について $$ t=0 : z_{10}=W_{in11}\times a_0+W_{in21}\times b_0+W_{hh11}\times 0+W_{hh21}\times 0\\ t=0 : z_{20}=W_{in22}\times b_0+W_{in12}\times a_0+W_{hh22}\times 0+W_{hh12}\times 0\\ t=1 : z_{11}=W_{in11}\times a_1+W_{in21}\times b_1+W_{hh11}\times z_{10}+W_{hh21}\times z_{20}\\ t=1 : z_{21}=W_{in22}\times b_1+W_{in12}\times a_1+W_{hh22}\times z_{20}+W_{hh12}\times z_{10}\\ t=2 : z_{12}=W_{in11}\times a_2+W_{in21}\times b_2+W_{hh11}\times z_{11}+W_{hh21}\times z_{21}\\ t=2 : z_{22}=W_{in22}\times b_2+W_{in12}\times a_2+W_{hh22}\times z_{21}+W_{hh12}\times z_{11} $$ N node の場合 ![](https://i.imgur.com/AwtgV50.png) ## Seq2Seq RNNを使ったEncoder-Decoderモデル。 文字列を入力し、文字列を出力する。 [参考](https://d2l.ai/chapter_recurrent-modern/seq2seq.html) ### Encoder - Decoder 全体像 ![](https://i.imgur.com/PhmNOyK.png) ![](https://i.imgur.com/Dw66KJG.gif) 「This is a dog」→「これは犬です」の翻訳を学習する場合を考える ### RNN Encoder ![](https://i.imgur.com/tiJJt3z.png) これを順番にRNNに入れていく。 [EOS]はEnd-Of-the-Sequence の意味。 $t=0$のとき ![](https://i.imgur.com/6gsVVnV.png) $t=1$のとき ![](https://i.imgur.com/Li9YJow.png) $t=4$のとき ![](https://i.imgur.com/ej8HQSy.png) この $h_4$ は ==Context Vector==と呼ばれ、文章をEncodeしたベクトルになっている。 ### RNN Decoder Decoder側の処理。図は、学習時の時の絵 [BOS]はBegin-Of-the-Sequence の意味。 $t=0$のとき ![](https://i.imgur.com/WvWbOpF.png) $t=1$のとき ![](https://i.imgur.com/aa3liOS.png) $t=4$のとき ![](https://i.imgur.com/Y7XQsDp.png) それぞれで計算したlossを $$ loss=\sum_i^4loss_i $$ として、学習を進めていく。 ### Prediction predict する際は、例えば$t=1$の予測は$t=0$の出力$Y_0$ベクトルを、Decoder側のInputに使う。 ![](https://i.imgur.com/pEbAhYT.png) ### Seq2Seq の弱点 文章が長くなると、最初の単語の情報が失われてしまう。これは、RNNの欠点である。LSTMは長期記憶が可能なような設計思想であるが、この問題が原理的に解決したわけではない。