Sentiment Analysis with an RNN

In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate since we can include information about the sequence of words. Here we'll use a dataset of movie reviews, accompanied by labels.

The architecture for this network is shown below.

Here, we'll pass in words to an embedding layer. We need an embedding layer because we have tens of thousands of words, so we'll need a more efficient representation for our input data than one-hot encoded vectors. You should have seen this before from the word2vec lesson. You can actually train up an embedding with word2vec and use it here. But it's good enough to just have an embedding layer and let the network learn the embedding table on it's own.

From the embedding layer, the new representations will be passed to LSTM cells. These will add recurrent connections to the network so we can include information about the sequence of words in the data. Finally, the LSTM cells will go to a sigmoid output layer here. We're using the sigmoid because we're trying to predict if this text has positive or negative sentiment. The output layer will just be a single unit then, with a sigmoid activation function.

We don't care about the sigmoid outputs except for the very last one, we can ignore the rest. We'll calculate the cost from the output of the last step and the training label.


In [1]:
import numpy as np
import tensorflow as tf

In [2]:
with open('../sentiment-network/reviews.txt', 'r') as f:
    reviews = f.read()
with open('../sentiment-network/labels.txt', 'r') as f:
    labels = f.read()

In [3]:
reviews[:200]


Out[3]:
'bromwell high is a cartoon comedy . it ran at the same time as some other programs about school life  such as  teachers  . my   years in the teaching profession lead me to believe that bromwell high  '

Data preprocessing

The first step when building a neural network model is getting your data into the proper form to feed into the network. Since we're using embedding layers, we'll need to encode each word with an integer. We'll also want to clean it up a bit.

You can see an example of the reviews data above. We'll want to get rid of those periods. Also, you might notice that the reviews are delimited with newlines \n. To deal with those, I'm going to split the text into each review using \n as the delimiter. Then I can combined all the reviews back together into one big string.

First, let's remove all punctuation. Then get all the text without the newlines and split it into individual words.


In [4]:
from string import punctuation
all_text = ''.join([c for c in reviews if c not in punctuation])
reviews = all_text.split('\n')

all_text = ' '.join(reviews)
words = all_text.split()
print('Reviews Length: {}, Words Length: {}'.format(np.shape(reviews), len(words)))


Reviews Length: (25001,), Words Length: 6020196

In [5]:
all_text[:200]


Out[5]:
'bromwell high is a cartoon comedy  it ran at the same time as some other programs about school life  such as  teachers   my   years in the teaching profession lead me to believe that bromwell high  s '

In [6]:
words[:10]


Out[6]:
['bromwell', 'high', 'is', 'a', 'cartoon', 'comedy', 'it', 'ran', 'at', 'the']

Encoding the words

The embedding lookup requires that we pass in integers to our network. The easiest way to do this is to create dictionaries that map the words in the vocabulary to integers. Then we can convert each of our reviews into integers so they can be passed into the network.

Exercise: Now you're going to encode the words with integers. Build a dictionary that maps words to integers. Later we're going to pad our input vectors with zeros, so make sure the integers start at 1, not 0. Also, convert the reviews to integers and store the reviews in a new list called reviews_ints.


In [7]:
# Create your dictionary that maps vocab words to integers here
vocab_to_int = dict()
for word in words:
    vocab_to_int[word] = vocab_to_int.get(word, 1) + 1
# Convert the reviews to integers, same shape as reviews list, but with integers
reviews_ints = []
for review in reviews: 
    reviews_ints.append([vocab_to_int[word] for word in review.split()])

Encoding the labels

Our labels are "positive" or "negative". To use these labels in our network, we need to convert them to 0 and 1.

Exercise: Convert labels from positive and negative to 1 and 0, respectively.


In [8]:
# Convert labels to 1s and 0s for 'positive' and 'negative'
raw_labels = labels.split('\n')
num_labels = np.zeros((1, len(raw_labels)))
for i in range(1, len(raw_labels)):
    if raw_labels[i] == 'positive':
        num_labels[:, i] = 1
print(np.shape(num_labels))


(1, 25001)

If you built labels correctly, you should see the next output.


In [9]:
from collections import Counter
review_lens = Counter([len(x) for x in reviews_ints])
print("Zero-length reviews: {}".format(review_lens[0]))
print("Maximum review length: {}".format(max(review_lens)))


Zero-length reviews: 1
Maximum review length: 2514

Okay, a couple issues here. We seem to have one review with zero length. And, the maximum review length is way too many steps for our RNN. Let's truncate to 200 steps. For reviews shorter than 200, we'll pad with 0s. For reviews longer than 200, we can truncate them to the first 200 characters.

Exercise: First, remove the review with zero length from the reviews_ints list.


In [13]:
# Filter out that review with 0 length
reviews_ints = [x for x in reviews_ints if len(x) > 0]
print(len(reviews_ints), np.shape(reviews_ints))


25000 (25000,)

Exercise: Now, create an array features that contains the data we'll pass to the network. The data should come from review_ints, since we want to feed integers to the network. Each row should be 200 elements long. For reviews shorter than 200 words, left pad with 0s. That is, if the review is ['best', 'movie', 'ever'], [117, 18, 128] as integers, the row will look like [0, 0, 0, ..., 0, 117, 18, 128]. For reviews longer than 200, use on the first 200 words as the feature vector.

This isn't trivial and there are a bunch of ways to do this. But, if you're going to be building your own deep learning networks, you're going to have to get used to preparing your data.


In [17]:
seq_len = 200
features = np.zeros((len(reviews_ints), seq_len), dtype=int)
for i, v in enumerate(reviews_ints):
    features[i, -len(v):] = np.array(v)[:seq_len]

If you build features correctly, it should look like that cell output below.


In [18]:
features[:10,:100]


Out[18]:
array([[     0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      9,   2162, 107329, 163010,
           546,   3247,  96353,    239,  23514, 336714,   4054,  12725,
         46934,  15748,   9164,     67,  17375,   1660,   6629,   5135,
         46934,     78,  12504,   4518,  93969, 336714,     83,     66,
          1311,  10774, 135721,   2506,  73246,      9,   2162,  65362,
           262, 107329,   9764,    207],
       [     0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,  11989, 145865,
        163010,   5977,  21434,  16791,     47,    396,  44344, 163010,
           103,   1221,  17114,  44126],
       [     8,  18005,      2,  46934,    865,     13,    133,  16791,
          9290,  21561,    288,  44344,   4518,  42604,   6486, 163010,
           422, 135721,   1897,   4698,  34201, 336714,    700,  73246,
         10784,   2330,    485,   1597,  21434,   6297,   2326,  20499,
          4103, 135721,   1660,   4374,  18005,    223,  44344, 336714,
          1128,   8784,   9286,   7299, 145865, 336714,    141,  46934,
         17772, 163010,   1553,    536,   5318,     42,  17375,   3689,
          5135,  46934,    154, 336714,   2052,  34201,     86,      6,
          1844, 135721,    151,    246, 336714,     11,     12,  18005,
            42,  16804,  22907,   2894,  26958,   1718, 135721,   5651,
         13292,  34201, 336714,    270, 101873, 101873,  42604,  16160,
         16804,  34231,  10784,   1849, 163010,    245, 135721,   1553,
         34201, 336714,    270,  44344],
       [    94,   1221,  46934, 163010,    136,   4313,     40,    323,
        107329,     86,  13292,  44126,     94,     70,   5135,     24,
        135721,    588,     84,    162,     95,   1069,    469,  21434,
        107329,    358,   7971, 163010,    814, 145865,      6,  65362,
        135721,  29375,    129,  93969,     28, 145865,  96353,   6611,
           156, 135721, 336714,    565,  46934, 163010,     97,   9159,
         34201,    251, 107329,     95,   1139,    175,     51,      3,
         18422,   1357, 336714,     40,      2,   2193,   6031,  46934,
           102,  42604,    320,    640, 336714,    323, 107329,     62,
            10,  22547, 336714,    603,    301,      8,    952,      7,
         29375,   6907,     24,  65362,     18,     16,     12,    201,
          1334,      9,  21434,    140, 336714,     59,    570,  17114,
         44126,    180,    196,  22907],
       [     0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,   1197,   6334,   6494,  22547,     14,    289,
           118,   6414,    668,      9,    849,  87624,  27732,   5998,
          6680, 164108,   6454,   5213,  93969,    329,     45,  29431,
          1963, 135721,   1031, 336714,     62,  34201,   1646, 107329,
        163010,   1830,  46934,  15144,  46934,   2950,  93969,     47,
            25, 336714,   3510,  34201,     36, 107329,   9159,    672,
          7639,   6611,    124, 145865],
       [     0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,  76001,  40156,
           122,   5078,  87624,   1494,  34082,   2382,  12504,     98,
         34201,  23514,   9062,    139,  34201, 336714,   4041, 145865,
        336714,    623,   1220,  76001,     83,     75, 135721,   1059,
        145865,    491,  14183,  14224,     76, 336714,   2494,  44126,
         18422,    623,   5977,  12652, 336714,    857,   5213,   1674,
           972,  46934,   6611,    360],
       [     0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,  76001, 107329,    893, 336714,
          8784,    237,  40156,     24, 336714,    170,     78,   2687,
          8278,    157,  96353,   5941,  30627,   3377, 163010,    759,
           965, 145865,      8,    585],
       [     0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,    772,
          2224,  87624,   6168,  76001, 107329,   1517, 135721,  26958,
         21561,   1290,  40156,  42604,    433,  22907,   5042,  27732,
           183,  17114,    284,  23514, 336714,    174,  20618,   9286,
          7924,    203,  11386,    110,  17114, 164108,  30627,   6975,
          2538, 336714,   5384,    343, 164108,     22,   1386,  48209,
          2072,  76001,  11989, 107329,   7834,    418, 135721,   6975,
        336714,    117, 145865, 163010],
       [     0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,      0,
             0,      0,      0,      0,      0,      0,      0,  76001,
        107329,  30627, 336714,    779,    120,    170,  40156,  96353,
         48209,   9764,   2002,    177,   9920,   8784, 145865,  29375,
          7667, 164108,   4240,  11291],
       [ 14183,  87624,  48209,   6438,  12504,    764,   1101,  10774,
          1776, 135721, 336714,    829, 135721,  11479,     42,  96353,
         48209,  26790, 145865,   6676,   7667,  87624,   2237,  44126,
         12504,    764,  42604,  76001,  48209, 336714,  11919,  26790,
         10860,    196,  17114, 145865,   2908,   8120,  87624,  11291,
          6486,   6680,     42,   1777,  17772,    580, 164108,  87624,
          7924,  27732,    383,  17114, 336714,   1804, 145865,  12504,
          6629,   3267,  96353,  16160, 163010,    270,     27, 164108,
           241,   1812,   1538, 145865,  65362,     56, 164108,    159,
            79,    241,    405, 107329,  26790, 145865,  12504,   1233,
           677,  42604,     42, 107329,  22547,   2978, 336714,   2733,
          1538, 145865,   1040, 145865,  29375,   1008,  93969, 336714,
            19,   1602, 145865,     18]])

Training, Validation, Test

With our data in nice shape, we'll split it into training, validation, and test sets.

Exercise: Create the training, validation, and test sets here. You'll need to create sets for the features and the labels, train_x and train_y for example. Define a split fraction, split_frac as the fraction of data to keep in the training set. Usually this is set to 0.8 or 0.9. The rest of the data will be split in half to create the validation and testing data.


In [37]:
split_frac = 0.8
l_f = int(len(features)*0.8)

train_x, val_x = features[:l_f], features[l_f:] 
train_y, val_y = labels[:l_f], labels[l_f:]

t_split = int(len(val_x)*0.5)
val_x, test_x = val_x[:t_split], val_x[t_split:]
val_y, test_y = val_y[:t_split], val_y[t_split:]

print("\t\t\tFeature Shapes:")
print("Train set: \t\t{}".format(train_x.shape), 
      "\nValidation set: \t{}".format(val_x.shape),
      "\nTest set: \t\t{}".format(test_x.shape))


			Feature Shapes:
Train set: 		(20000, 200) 
Validation set: 	(2500, 200) 
Test set: 		(2500, 200)

With train, validation, and text fractions of 0.8, 0.1, 0.1, the final shapes should look like:

                    Feature Shapes:
Train set:       (20000, 200) 
Validation set:     (2500, 200) 
Test set:         (2500, 200)

Build the graph

Here, we'll build the graph. First up, defining the hyperparameters.

  • lstm_size: Number of units in the hidden layers in the LSTM cells. Usually larger is better performance wise. Common values are 128, 256, 512, etc.
  • lstm_layers: Number of LSTM layers in the network. I'd start with 1, then add more if I'm underfitting.
  • batch_size: The number of reviews to feed the network in one training pass. Typically this should be set as high as you can go without running out of memory. Tensorflow is great at matmul however it is better to do multiply a small amount of large matrices than multiply a large amount of small matrices
  • learning_rate: Learning rate

In [22]:
lstm_size = 256
lstm_layers = 1
batch_size = 500
learning_rate = 0.001

For the network itself, we'll be passing in our 200 element long review vectors. Each batch will be batch_size vectors. We'll also be using dropout on the LSTM layer, so we'll make a placeholder for the keep probability.

Exercise: Create the inputs_, labels_, and drop out keep_prob placeholders using tf.placeholder. labels_ needs to be two-dimensional to work with some functions later. Since keep_prob is a scalar (a 0-dimensional tensor), you shouldn't provide a size to tf.placeholder.


In [26]:
n_words = len(vocab_to_int)

# Create the graph object
graph = tf.Graph()
# Add nodes to the graph
with graph.as_default():
    inputs_ = tf.placeholder(tf.int32, [None, None], name= 'inputs')
    labels_ = tf.placeholder(tf.int32, [None, None], name= 'labels')
    keep_prob = tf.placeholder(tf.float32, name= 'keep_prob')

Embedding

Now we'll add an embedding layer. We need to do this because there are 74000 words in our vocabulary. It is massively inefficient to one-hot encode our classes here. You should remember dealing with this problem from the word2vec lesson. Instead of one-hot encoding, we can have an embedding layer and use that layer as a lookup table. You could train an embedding layer using word2vec, then load it here. But, it's fine to just make a new layer and let the network learn the weights.

Exercise: Create the embedding lookup matrix as a tf.Variable. Use that embedding matrix to get the embedded vectors to pass to the LSTM cell with tf.nn.embedding_lookup. This function takes the embedding matrix and an input tensor, such as the review vectors. Then, it'll return another tensor with the embedded vectors. So, if the embedding layer has 200 units, the function will return a tensor with size [batch_size, 200].


In [27]:
# Size of the embedding vectors (number of units in the embedding layer)
embed_size = 300 

with graph.as_default():
    embedding = tf.Variable(tf.random_uniform([n_words, embed_size], -1, 1))
    embed = tf.nn.embedding_lookup(embedding, inputs_)

LSTM cell

Next, we'll create our LSTM cells to use in the recurrent network (TensorFlow documentation). Here we are just defining what the cells look like. This isn't actually building the graph, just defining the type of cells we want in our graph.

To create a basic LSTM cell for the graph, you'll want to use tf.contrib.rnn.BasicLSTMCell. Looking at the function documentation:

tf.contrib.rnn.BasicLSTMCell(num_units, forget_bias=1.0, input_size=None, state_is_tuple=True, activation=<function tanh at 0x109f1ef28>)

you can see it takes a parameter called num_units, the number of units in the cell, called lstm_size in this code. So then, you can write something like

lstm = tf.contrib.rnn.BasicLSTMCell(num_units)

to create an LSTM cell with num_units. Next, you can add dropout to the cell with tf.contrib.rnn.DropoutWrapper. This just wraps the cell in another cell, but with dropout added to the inputs and/or outputs. It's a really convenient way to make your network better with almost no effort! So you'd do something like

drop = tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=keep_prob)

Most of the time, your network will have better performance with more layers. That's sort of the magic of deep learning, adding more layers allows the network to learn really complex relationships. Again, there is a simple way to create multiple layers of LSTM cells with tf.contrib.rnn.MultiRNNCell:

cell = tf.contrib.rnn.MultiRNNCell([drop] * lstm_layers)

Here, [drop] * lstm_layers creates a list of cells (drop) that is lstm_layers long. The MultiRNNCell wrapper builds this into multiple layers of RNN cells, one for each cell in the list.

So the final cell you're using in the network is actually multiple (or just one) LSTM cells with dropout. But it all works the same from an achitectural viewpoint, just a more complicated graph in the cell.

Exercise: Below, use tf.contrib.rnn.BasicLSTMCell to create an LSTM cell. Then, add drop out to it with tf.contrib.rnn.DropoutWrapper. Finally, create multiple LSTM layers with tf.contrib.rnn.MultiRNNCell.

Here is a tutorial on building RNNs that will help you out.


In [29]:
with graph.as_default():
    # Your basic LSTM cell
    lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size)
    
    # Add dropout to the cell
    drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)
    
    # Stack up multiple LSTM layers, for deep learning
    cell = tf.contrib.rnn.MultiRNNCell([drop] * lstm_layers)
    
    # Getting an initial state of all zeros
    initial_state = cell.zero_state(batch_size, tf.float32)

RNN forward pass

Now we need to actually run the data through the RNN nodes. You can use tf.nn.dynamic_rnn to do this. You'd pass in the RNN cell you created (our multiple layered LSTM cell for instance), and the inputs to the network.

outputs, final_state = tf.nn.dynamic_rnn(cell, inputs, initial_state=initial_state)

Above I created an initial state, initial_state, to pass to the RNN. This is the cell state that is passed between the hidden layers in successive time steps. tf.nn.dynamic_rnn takes care of most of the work for us. We pass in our cell and the input to the cell, then it does the unrolling and everything else for us. It returns outputs for each time step and the final_state of the hidden layer.

Exercise: Use tf.nn.dynamic_rnn to add the forward pass through the RNN. Remember that we're actually passing in vectors from the embedding layer, embed.


In [30]:
with graph.as_default():
    outputs, final_state = tf.nn.dynamic_rnn(cell, embed, initial_state=initial_state)

Output

We only care about the final output, we'll be using that as our sentiment prediction. So we need to grab the last output with outputs[:, -1], the calculate the cost from that and labels_.


In [31]:
with graph.as_default():
    predictions = tf.contrib.layers.fully_connected(outputs[:, -1], 1, activation_fn=tf.sigmoid)
    cost = tf.losses.mean_squared_error(labels_, predictions)
    
    optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)

Validation accuracy

Here we can add a few nodes to calculate the accuracy which we'll use in the validation pass.


In [32]:
with graph.as_default():
    correct_pred = tf.equal(tf.cast(tf.round(predictions), tf.int32), labels_)
    accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

Batching

This is a simple function for returning batches from our data. First it removes data such that we only have full batches. Then it iterates through the x and y arrays and returns slices out of those arrays with size [batch_size].


In [33]:
def get_batches(x, y, batch_size=100):
    
    n_batches = len(x)//batch_size
    x, y = x[:n_batches*batch_size], y[:n_batches*batch_size]
    for ii in range(0, len(x), batch_size):
        yield x[ii:ii+batch_size], y[ii:ii+batch_size]

Training

Below is the typical training code. If you want to do this yourself, feel free to delete all this code and implement it yourself. Before you run this, make sure the checkpoints directory exists.


In [38]:
epochs = 10

with graph.as_default():
    saver = tf.train.Saver()

with tf.Session(graph=graph) as sess:
    sess.run(tf.global_variables_initializer())
    iteration = 1
    for e in range(epochs):
        state = sess.run(initial_state)
        
        for ii, (x, y) in enumerate(get_batches(train_x, train_y, batch_size), 1):
            feed = {inputs_: x,
                    labels_: y[:, None],
                    keep_prob: 0.5,
                    initial_state: state}
            loss, state, _ = sess.run([cost, final_state, optimizer], feed_dict=feed)
            
            if iteration%5==0:
                print("Epoch: {}/{}".format(e, epochs),
                      "Iteration: {}".format(iteration),
                      "Train loss: {:.3f}".format(loss))

            if iteration%25==0:
                val_acc = []
                val_state = sess.run(cell.zero_state(batch_size, tf.float32))
                for x, y in get_batches(val_x, val_y, batch_size):
                    feed = {inputs_: x,
                            labels_: y[:, None],
                            keep_prob: 1,
                            initial_state: val_state}
                    batch_acc, val_state = sess.run([accuracy, final_state], feed_dict=feed)
                    val_acc.append(batch_acc)
                print("Val acc: {:.3f}".format(np.mean(val_acc)))
            iteration +=1
    saver.save(sess, "checkpoints/sentiment.ckpt")


-----------------------------------------------------------------------
TypeError                             Traceback (most recent call last)
<ipython-input-38-da10d9fe9550> in <module>()
     12         for ii, (x, y) in enumerate(get_batches(train_x, train_y, batch_size), 1):
     13             feed = {inputs_: x,
---> 14                     labels_: y[:, None],
     15                     keep_prob: 0.5,
     16                     initial_state: state}

TypeError: string indices must be integers

Testing


In [ ]:
test_acc = []
with tf.Session(graph=graph) as sess:
    saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))
    test_state = sess.run(cell.zero_state(batch_size, tf.float32))
    for ii, (x, y) in enumerate(get_batches(test_x, test_y, batch_size), 1):
        feed = {inputs_: x,
                labels_: y[:, None],
                keep_prob: 1,
                initial_state: test_state}
        batch_acc, test_state = sess.run([accuracy, final_state], feed_dict=feed)
        test_acc.append(batch_acc)
    print("Test accuracy: {:.3f}".format(np.mean(test_acc)))