In the previous exercise you implemented a vanilla RNN and applied it to image captioning. In this notebook you will implement the LSTM update rule and use it for image captioning.
If you read recent papers, you'll see that many people use a variant on the vanilla RNN called Long-Short Term Memory (LSTM) RNNs. Vanilla RNNs can be tough to train on long sequences due to vanishing and exploding gradients caused by repeated matrix multiplication. LSTMs solve this problem by replacing the simple update rule of the vanilla RNN with a gating mechanism as follows.
Similar to the vanilla RNN, at each timestep we receive an input π₯π‘ββπ· and the previous hidden state βπ‘β1ββπ»; the LSTM also maintains an π»-dimensional cell state, so we also receive the previous cell state ππ‘β1ββπ». The learnable parameters of the LSTM are an input-to-hidden matrix ππ₯ββ4π»Γπ·, a hidden-to-hidden matrix πβββ4π»Γπ» and a bias vector πββ4π».
At each timestep we first compute an activation vector πββ4π» as π=ππ₯π₯π‘+πββπ‘β1+π. We then divide this into four vectors ππ,ππ,ππ,ππββπ» where ππ consists of the first π» elements of π, ππ is the next π» elements of π, etc. We then compute the input gate πββπ», forget gate πββπ», output gate πββπ» and block input πββπ» as
π=π(ππ)π=π(ππ)π=π(ππ)π=tanh(ππ)
where π is the sigmoid function and tanh is the hyperbolic tangent, both applied elementwise.
Finally we compute the next cell state ππ‘ and next hidden state βπ‘ as
ππ‘=πβππ‘β1+πβπβπ‘=πβtanh(ππ‘)
where β is the elementwise product of vectors.
In the rest of the notebook we will implement the LSTM update rule and apply it to the image captioning task.