Summer School Deep Learning Session 4

11 minute read

Recurrant Neural Networks

Recurrent Neural Networks (RNN’s) are very effective for Natural Language Processing and other sequence tasks because they have “memory”. They can read inputs (such as words) one at a time, and remember some information/context through the hidden layer activations that get passed from one time-step to the next. This allows a uni-directional RNN to take information from the past to process later inputs. A bidirection RNN can take context from both the past and the future.

The session notebook can be found here

Notation:

  • Superscript denotes an object associated with the layer.
    • Example: is the layer activation. and are the layer parameters.
  • Superscript denotes an object associated with the example.
    • Example: is the training example input.
  • Superscript denotes an object at the time-step.
    • Example: is the input x at the time-step. is the input at the timestep of example .
  • Lowerscript denotes the entry of a vector.
    • Example: denotes the entry of the activations in layer .

Forward propagation for the basic Recurrent Neural Network

The basic RNN that you will implement has the structure below. In this example, .

neuron

This is a Basic RNN model

Here’s how you can implement an RNN:

Code Instructions:

  1. Implement the calculations needed for one time-step of the RNN.
  2. Implement a loop over time-steps in order to process all the inputs, one at a time.

Let’s go!

RNN cell

A Recurrent neural network can be seen as the repetition of a single cell. You are first going to implement the computations for a single time-step. The following figure describes the operations for a single time-step of an RNN cell.

neuron This is a basic RNN cell. Takes as input (current input) and (previous hidden state containing information from the past), and outputs which is given to the next RNN cell and also used to predict

Code Instructions:

  1. Compute the hidden state with tanh activation: .
  2. Using your new hidden state , compute the prediction . We provided you a function: softmax.
  3. Store in cache
  4. Return , and cache

We will vectorize over examples. Thus, will have dimension , and will have dimension .

RNN forward pass

RNN as the repetition of the cell you’ve just built. If your input sequence of data is carried over 10 time steps, then you will copy the RNN cell 10 times. Each cell tak es as input the hidden state from the previous cell () and the current time-step’s input data (). It outputs a hidden state () and a prediction () for this time-step.

neuron A basic RNN is shown above. The input sequence is carried over time steps. The network outputs .

Code Instructions:

  1. Create a vector of zeros () that will store all the hidden states computed by the RNN.
  2. Initialize the “next” hidden state as (initial hidden state).
  3. Start looping over each time step, your incremental index is :
    • Update the “next” hidden state and the cache by running rnn_cell_forward
    • Store the “next” hidden state in ( position)
    • Store the prediction in y
    • Add the cache to the list of caches
  4. Return , and caches

Basic RNN backward pass

We will start by computing the backward pass for the basic RNN-cell.

neuron

This is a RNN-cell’s backward pass. Just like in a fully-connected neural network, the derivative of the cost function backpropagates through the RNN by following the chain-rule from calculus. The chain-rule is also used to calculate to update the parameters .

Deriving the one step backward functions:

To compute the rnn_cell_backward you need to compute the following equations. It is a good exercise to derive them by hand.

The derivative of is .

Similarly for , the derivative of is .

The final two equations also follow same rule and are derived using the derivative. Note that the arrangement is done in a way to get the same dimensions to match.

Backward pass through the RNN

Computing the gradients of the cost with respect to at every time-step is useful because it is what helps the gradient backpropagate to the previous RNN-cell. To do so, you need to iterate through all the time steps starting at the end, and at each step, you increment the overall , , and you store .

Instructions:

Implement the rnn_backward function. Initialize the return variables with zeros first and then loop through all the time steps while calling the rnn_cell_backward at each time timestep, update the other variables accordingly.

In the next part, you will build a more complex LSTM model, which is better at addressing vanishing gradients. The LSTM will be better able to remember a piece of information and keep it saved for many timesteps.

Long Short-Term Memory (LSTM) network

This following figure shows the operations of an LSTM-cell.

neuron

This is a LSTM-cell. This tracks and updates a “cell state” or memory variable at every time-step, which can be different from .

Similar to the RNN example above, you will start by understanding the LSTM cell for a single time-step. Then you can iteratively call it from inside a for-loop to have it process an input with time-steps.

About the gates

- Forget gate

For the sake of this illustration, lets assume we are reading words in a piece of text, and want use an LSTM to keep track of grammatical structures, such as whether the subject is singular or plural. If the subject changes from a singular word to a plural word, we need to find a way to get rid of our previously stored memory value of the singular/plural state. In an LSTM, the forget gate lets us do this:

Here, are weights that govern the forget gate’s behavior. We concatenate and multiply by . The equation above results in a vector with values between 0 and 1. This forget gate vector will be multiplied element-wise by the previous cell state . So if one of the values of is 0 (or close to 0) then it means that the LSTM should remove that piece of information (e.g. the singular subject) in the corresponding component of . If one of the values is 1, then it will keep the information.

- Update gate

Once we forget that the subject being discussed is singular, we need to find a way to update it to reflect that the new subject is now plural. Here is the formulat for the update gate:

Similar to the forget gate, here is again a vector of values between 0 and 1. This will be multiplied element-wise with , in order to compute .

- Updating the cell

To update the new subject we need to create a new vector of numbers that we can add to our previous cell state. The equation we use is:

Finally, the new cell state is:

- Output gate

To decide which outputs we will use, we will use the following two formulas:

Where in equation 5 you decide what to output using a sigmoid function and in equation 6 you multiply that by the of the previous state.

LSTM cell

Instructions:

  1. Concatenate and in a single matrix:
  2. Compute all the formulas 1-6. You can use sigmoid() and np.tanh().
  3. Compute the prediction . You can use softmax()

Forward pass for LSTM

Now that you have implemented one step of an LSTM, you can now iterate this over this using a for-loop to process a sequence of inputs.

neuron

The above image shows a LSTM over multiple time-steps.

Exercise: Implement lstm_forward() to run an LSTM over time-steps.

Note: is initialized with zeros.

The forward passes for the basic RNN and the LSTM. When using a deep learning framework, implementing the forward pass is sufficient to build systems that achieve great performance. Now we will see how to do backpropagation in LSTM and RNNS

LSTM backward pass

One Step backward

The LSTM backward pass is slighltly more complicated than the forward one. We have provided you with all the equations for the LSTM backward pass below. (If you enjoy calculus exercises feel free to try deriving these from scratch yourself.)

Gate derivatives

Parameter derivatives

To calculate you just need to sum across the horizontal (axis= 1) axis on respectively. Note that you should have the keep_dims = True option.

Finally, you will compute the derivative with respect to the previous hidden state, previous memory state, and input.

Here, the weights for equations 13 are the first n_a, (i.e. etc…)

where the weights for equation 15 are from n_a to the end, (i.e. etc…)

Backward pass through the LSTM RNN

This part is very similar to the rnn_backward function you implemented above. You will first create variables of the same dimension as your return variables. You will then iterate over all the time steps starting from the end and call the one step function you implemented for LSTM at each iteration. You will then update the parameters by summing them individually. Finally return a dictionary with the new gradients.

Instructions: Implement the lstm_backward function. Create a for loop starting from and going backward. For each step call lstm_cell_backward and update the your old gradients by adding the new gradients to them. Note that dxt is not updated but is stored.

Activity Recognition

Here’s a Github Gist to an activity recognition code using LSTM’s : link.

Sequence to Sequence Models - a general overview

Many times, we might have to convert one sequence to another. Really? Where?

We do this in machine translation. For this purpose we use models known as sequence to sequence models. (seq2seq)

If we take a high-level view, a seq2seq model has encoder, decoder and intermediate step as its main components: alt text

A basic sequence-to-sequence model consists of two recurrent neural networks (RNNs): an encoder that processes the input and a decoder that generates the output. This basic architecture is depicted below. alt text

Each box in the picture above represents a cell of the RNN, most commonly a GRU cell or an LSTM cell. Encoder and decoder can share weights or, as is more common, use a different set of parameters.

In the basic model depicted above, every input has to be encoded into a fixed-size state vector, as that is the only thing passed to the decoder. To allow the decoder more direct access to the input, an attention mechanism was introduced. We’ll look into details of the attention mechanism in the next part.

Encoder

Our input sequence is how are you. Each word from the input sequence is associated to a vector w∈Rd (via a lookup table). In our case, we have 3 words, thus our input will be transformed into . Then, we simply run an LSTM over this sequence of vectors and store the last hidden state outputed by the LSTM: this will be our encoder representation e. Let’s write the hidden states (and thus ). alt text

Decoder

Now that we have a vector e that captures the meaning of the input sequence, we’ll use it to generate the target sequence word by word. Feed to another LSTM cell: as hidden state and a special start of sentence vector as input. The LSTM computes the next hidden state . Then, we apply some function so that is a vector of the same size as the vocabulary.

\begin{equation} h_0 = LSTM ( e , w_{s o s} ) \end{equation} \begin{equation} s_0 = g ( h_0 ) \end{equation} \begin{equation} p_0 = softmax ( s_0 ) \end{equation} \begin{equation} i_0 = argmax ( p_0 )$$ \end{equation}

Then, apply a softmax to to normalize it into a vector of probabilities . Now, each entry of will measure how likely is each word in the vocabulary. Let’s say that the word “comment” has the highest probability (and thus corresponds to the index of “comment”). Get a corresponding vector and repeat the procedure: the LSTM will take as hidden state and as input and will output a probability vector over the second word, etc.

\begin{equation} h_1 = LSTM ( h_0 , w_{i_0} ) \end{equation} \begin{equation} s_1 = g ( h_1 ) \end{equation} \begin{equation} p_1 = softmax ( s_1 ) \end{equation} \begin{equation} i _1 = argmax ( p_1 ) \end{equation}

The decoding stops when the predicted word is a special end of sentence token.

alt text

Attention !!!

alt text

Seq2Seq with Attention

The previous model has been refined over the past few years and greatly benefited from what is known as attention. Attention is a mechanism that forces the model to learn to focus (= to attend) on specific parts of the input sequence when decoding, instead of relying only on the hidden vector of the decoder’s LSTM. One way of performing attention is as follows. We slightly modify the reccurrence formula that we defined above by adding a new vector to the input of the LSTM \begin{equation} h_t = LSTM ( h_{t − 1} , [ w_{i_{t − 1 }}, c_t ] ) \end{equation} \begin{equation} s_t = g ( h_t ) \end{equation} \begin{equation} p_t = softmax ( s_t ) \end{equation} \begin{equation} i_t = argmax ( p_t ) \end{equation}

The vector c_t is the attention (or context) vector. We compute a new context vector at each decoding step. First, with a function , compute a score for each hidden state of the encoder. Then, normalize the sequence of using a softmax and compute c t as the weighted average of the .

for all

The choice of the function varies

One of the main usage of a sequence to sequence model is in Neural Machine Translation

Check out the Session note book for the code on how to do this

Leave a Comment