In this tutorial, we’re gonna to build a recurrent neural network that’s able to classify reviews. This can be used to improve online conversation and today we’re going to focus build something that can classify positive or negative review. If you spent any time online in comment sections or on social websites you’ve probably run into this kind of classification. In this tutorial, we’ll use Attention Mechanism for focus down on the words that are the most useful for classification.

Dataset


We’ll use the IMDB dataset that contains the text of 50,000 movie reviews from the Internet Movie Database. These are split into 25,000 reviews for training and 25,000 reviews for testing. The training and testing sets are balanced, they contain an equal number of positive and negative reviews.

The IMDB dataset comes packaged with TensorFlow. 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.
The following code downloads the IMDB dataset to your machine or uses a cached copy if you’ve already downloaded it:

The argument num_words=20000 keeps the top 20,000 most frequently occurring words in the training data. The rare words are discarded to keep the size of the data manageable.

Prepare Input Dataset


Since the movie reviews must be the same length, we will use the pad_sequences function to standardize the lengths:

Build Model


The framework we’re gonna use is the Embed, Encode, Attend and Predict framework this was introduced by Matthew Honnibal. It’s just a way of encapsulating some of the most common techniques in natural language into usable blocks, blocks they play well with each other.

Embed will be how do you transform words into vectors. In order to do deep learning, you need to transform words into numbers that you can do computations on.

Original numbers you get from embedding might not be the most useful. Encoding turns them into more useful numbers and that’s a neural network that does that. Not all of the numbers from encoding are going to be equally useful. So attention lets you focus down on the numbers that are the most useful. Finally, the network will predict whatever it predicts.

1. Use Pre-Trained Word Embeddings.

Anytime you do deep learning exercises with the natural language you’re going to generate some embeddings and this embedding be useful in other problems. Some very useful embeddings that were created were something like Word2Vec by google or Glove by Stanford. In this tutorial, we’ll use glove embedding.

2.Encode: Bidirectional RNN

When you’re using regular RNN you only learn the dependencies of each word in one direction each word can learn from the words before it not the words after it and sometimes in your use cases it’s useful to have the whole context in both directions of a word. So there’s a simple trick for doing this you just use two RNN one that goes forward and one that goes backward and this two RNN will give you a context in both directions and so you obtain two output vectors.

tensorflow bidirectional lstm

You have two vectors, you can just glue these two vectors together by concatenation and you’ll get have one vector aging and you can use this for prediction.

3.Attention

If you stopped before attention you still have a classifier and it should still work but it’s only using the output from the last cell and you’re feeding that into your predictor but there’s still information in other cells and  for long sentences this information might get lost by the time it gets to the last cell so you’d like to somehow keep this information.

. TensorFlow Text Classification using Attention Mechanism

You have the outputs of all the cell you can do something simple like just take the straight average these vectors and feed that to your predictor. But it’s also true that not all of this information will be equally important so you might want to use a weighted average so you want some weights tells you which words are the most important and which words are less important and the question is how are you going to come up with these weights you can try and learn them from scratch but that’s not so good you probably want some information about each of the words in computing these weights.

Train a little neural network a very very small neural network from the output of the cell whose whole job it is to vote on how important that word is. So this little neuron network gets its vote. It gives you a little alpha here which tells you how important the cell is then you do the weighted sum and then you feed that into your predictor and that’s how you do attention.

Attention is just how big these weights are that’s how much attention pay to each of the words and in this structure this mini neuron network.

Normalize your attention mechanism.
That’s the last important trick and it’s just a technical trick these are first when (a1,h1)they come out of the neural network can be anything they can be negative they can be positive they can be small.so again we’re gonna use softmax and this will just turn them into a number between 0 & 1 that add up to one. That’ll make for a nice weighted average.

Attention function is very simple, it’s just dense layers back to back and then a little bit of reshaping and softmax. so basically a two-layer neural network density.

4.Prediction

The final step the predicting step is of again just one usually a very small dense layer that has output two because we have two classes positive or negative. Then the prediction is just which of these two classes is bigger. Which of these two numbers is bigger which is what the argmax does. Then to compute the loss and train the network we’re gonna use the softmax cross entropy.

Train the Model


Next, let’s create an Estimator a TensorFlow class for performing high-level model training, evaluation, and inference for our model.

The model_fn argument specifies the model function to use for training, evaluation, and prediction.

Train the Model

Now we’re ready to train our model, which we can do by calling train() on the classifier.

Evaluate the Model

Once training is complete, we want to evaluate our model to determine its accuracy on the test set. We call the evaluate method, which evaluates the metrics.