In this tutorial, We build text classification models in Keras that use attention mechanism to provide insight into how classification decisions are being made.

1.Prepare Dataset

We’ll use the IMDB dataset that contains the text of 50,000 movie reviews from the Internet Movie Database. The IMDB dataset comes packaged with Keras. It has already been preprocessed such that the sequences of words have been converted to sequences of integers, where each integer represents a specific word in a dictionary.

Keras provide function pad_sequences takes care padding sequences. We only have to give it the max_len argument which will determine the length of the output arrays. If sentences are shorter than this length, they will be padded and if they are longer, they will be trimmed.

2.Create Attention Layer

You can use the final encoded state of a recurrent neural network for prediction. This could lose some useful information encoded in the previous steps of the sequence. In order to keep that information, you can use an average of the encoded states outputted by the RNN. But all of the encoded states of the RNN are equally valuable. Thus, we are using a weighted sum of these encoded states to make our prediction.

We compute these attention weights simply by building a small fully connected neural network on top of each encoded state. This network will have a single unit final layer which will correspond to the attention weight we will assign.

Keras Text Classification using Attention Mechanism

Attention function is very simple, it’s just dense layers back to back softmax. so basically a three-layer neural network density.

3.Embed Layer

Neural networks are the composition of operators from linear algebra and non-linear activation functions. In order to perform these computations on our input sentences, we must first embed them as a vector of numbers. There are two main approaches to perform this embedding pre-trained embeddings like Word2Vec or GloVe or randomly initializing. 

In this tutorial, we will be using a random initialization. To perform this embedding we use the embedding function from the layers package.The parameters of this matrix will then be trained with the rest of the graph.

4.Bi-directional RNN

We will use a bi-directional RNN. This is simply the concatentation of two RNNs, one which processes the sequence from left to right (the “forward” RNN) and one which process from right to left (the “backward” RNN). By using both directions, we get a stronger encoding as each word can be encoded using the context of its neighbors on boths sides rather than just a single side. 

Our model uses a bi-directional RNN, we first concatenate the hidden states from each RNN before computing the attention weights and applying the weighted sum.

The last layer is densely connected with a single output node. Using the sigmoid activation function, this value is a float between 0 and 1, representing a probability, or confidence level.

5.Compile Model

A model needs a loss function and an optimizer for training. Our model is a binary classification problem and the model outputs a probability. We’ll use the binary_crossentropy loss function.

6.Train Model

Train the model for 10 epochs in mini-batches of 200 samples. This is 10 iterations over all samples in the x_train and y_train tensors. While training, monitor the model’s loss and accuracy on the 20% samples from the validation set.

7.Evaluate Model

Let’s see how the model performs. Two values will be returned. Loss and accuracy.