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 [322]:
import numpy as np
import tensorflow as tf

In [323]:
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 [324]:
reviews[:2000]


Out[324]:
'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 satire is much closer to reality than is  teachers  . the scramble to survive financially  the insightful students who can see right through their pathetic teachers  pomp  the pettiness of the whole situation  all remind me of the schools i knew and their students . when i saw the episode in which a student repeatedly tried to burn down the school  i immediately recalled . . . . . . . . . at . . . . . . . . . . high . a classic line inspector i  m here to sack one of your teachers . student welcome to bromwell high . i expect that many adults of my age think that bromwell high is far fetched . what a pity that it isn  t   \nstory of a man who has unnatural feelings for a pig . starts out with a opening scene that is a terrific example of absurd comedy . a formal orchestra audience is turned into an insane  violent mob by the crazy chantings of it  s singers . unfortunately it stays absurd the whole time with no general narrative eventually making it just too off putting . even those from the era should be turned off . the cryptic dialogue would make shakespeare seem easy to a third grader . on a technical level it  s better than you might think with some good cinematography by future great vilmos zsigmond . future stars sally kirkland and frederic forrest can be seen briefly .  \nhomelessness  or houselessness as george carlin stated  has been an issue for years but never a plan to help those on the street that were once considered human who did everything from going to school  work  or vote for the matter . most people think of the homeless as just a lost cause while worrying about things such as racism  the war on iraq  pressuring kids to succeed  technology  the elections  inflation  or worrying if they  ll be next to end up on the streets .  br    br   but what if y'

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 [325]:
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()

In [326]:
all_text[:2000]


Out[326]:
'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 satire is much closer to reality than is  teachers   the scramble to survive financially  the insightful students who can see right through their pathetic teachers  pomp  the pettiness of the whole situation  all remind me of the schools i knew and their students  when i saw the episode in which a student repeatedly tried to burn down the school  i immediately recalled          at           high  a classic line inspector i  m here to sack one of your teachers  student welcome to bromwell high  i expect that many adults of my age think that bromwell high is far fetched  what a pity that it isn  t    story of a man who has unnatural feelings for a pig  starts out with a opening scene that is a terrific example of absurd comedy  a formal orchestra audience is turned into an insane  violent mob by the crazy chantings of it  s singers  unfortunately it stays absurd the whole time with no general narrative eventually making it just too off putting  even those from the era should be turned off  the cryptic dialogue would make shakespeare seem easy to a third grader  on a technical level it  s better than you might think with some good cinematography by future great vilmos zsigmond  future stars sally kirkland and frederic forrest can be seen briefly    homelessness  or houselessness as george carlin stated  has been an issue for years but never a plan to help those on the street that were once considered human who did everything from going to school  work  or vote for the matter  most people think of the homeless as just a lost cause while worrying about things such as racism  the war on iraq  pressuring kids to succeed  technology  the elections  inflation  or worrying if they  ll be next to end up on the streets   br    br   but what if you were given a bet to live on the st'

In [327]:
words[:100]


Out[327]:
['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',
 'satire',
 'is',
 'much',
 'closer',
 'to',
 'reality',
 'than',
 'is',
 'teachers',
 'the',
 'scramble',
 'to',
 'survive',
 'financially',
 'the',
 'insightful',
 'students',
 'who',
 'can',
 'see',
 'right',
 'through',
 'their',
 'pathetic',
 'teachers',
 'pomp',
 'the',
 'pettiness',
 'of',
 'the',
 'whole',
 'situation',
 'all',
 'remind',
 'me',
 'of',
 'the',
 'schools',
 'i',
 'knew',
 'and',
 'their',
 'students',
 'when',
 'i',
 'saw',
 'the',
 'episode',
 'in',
 'which',
 'a',
 'student',
 'repeatedly',
 'tried',
 'to',
 'burn',
 'down',
 'the',
 'school',
 'i',
 'immediately',
 'recalled',
 'at',
 'high']

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 [328]:
# Create your dictionary that maps vocab words to integers here
vocab_to_int = {word: index + 1 for index, word in enumerate(set(words))}

# Convert the reviews to integers, same shape as reviews list, but with integers
#print(reviews[:1])
#print(len(reviews))

reviews_ints = list()
for review in reviews:
    single_review_ints = list()
    for word in review.split():
        single_review_ints.append(vocab_to_int[word])
    reviews_ints.append(single_review_ints)
#print(reviews_ints[:1])

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 [329]:
# Convert labels to 1s and 0s for 'positive' and 'negative'
# Needs np.array to work (doesn't work as plain list)
labels = np.array([1 if label == 'positive' else 0 for label in labels.split()])
print(labels[:5])
print(len(labels))


[1 0 1 0 1]
25000

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


In [330]:
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 [331]:
# Filter out that review with 0 length
print(len(reviews_ints))
reviews_ints.remove([])
print(len(reviews_ints))

# Remove from labels?! Labels is already #25000 (it is 25001 is we split on '\n')


25001
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 [332]:
seq_len = 200
features = list()

for index, review_ints in enumerate(reviews_ints):
    review_length = len(review_ints)
    if review_length < 200:
        padding = [0] * (seq_len - review_length)
        padding.extend(review_ints)
        features.append([])
        features[-1].extend(padding)
    else:
        features.append([])
        features[-1].extend(review_ints[:200])

features = np.asarray(features)

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


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


Out[333]:
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, 26651, 11855, 66202,
        66143, 70486,  9692, 57326, 17615, 31835, 60020, 38741, 39035,
        37486, 37330, 48076, 38065, 34104, 18613,  8552, 53832, 37486,
        48043, 44275, 53239,  9636, 60020, 42557, 44059, 33885, 30747,
        72043, 39461, 20673, 26651, 11855,  9537, 57483, 66202, 53013,
        24905],
       [    0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0, 47439, 12377, 66143, 15799,
        41607, 67019, 36326, 37682, 22496, 66143, 18708, 69284, 70981,
        72233],
       [69774, 45449,  6954, 37486, 55177, 44754, 47301, 67019, 14872,
        56243, 20259, 22496, 53239, 20736, 66361, 66143, 68166, 72043,
        54920, 56430, 56433, 60020, 24563, 20673, 16465, 34827,  4355,
        48310, 41607, 34455, 63008, 69787, 60376, 72043, 18613, 39499,
        45449, 10657, 22496, 60020, 42383, 39509, 45305, 70864, 12377,
        60020, 51106, 37486, 58696, 66143, 34213, 56869, 73814,   215,
        34104, 14149, 53832, 37486, 40457, 60020, 39823, 56433, 62859,
         7459, 44921, 72043, 35982,  3861, 60020, 32781, 10532, 45449,
          215, 39020,  7589,   810, 66683, 20338, 72043, 59590, 15717,
        56433, 60020, 49983, 29968, 29968, 20736, 46329, 39020, 49548,
        16465, 66068, 66143, 32905, 72043, 57856, 56433, 60020, 49983,
        22496],
       [59412, 69284, 37486, 66143, 10777, 34698, 27922, 18235, 66202,
         5593, 15717, 72233, 46939, 47347, 53832, 61257, 72043, 53206,
           55, 70449, 19748, 60791, 48733, 41607, 66202, 28360, 37991,
        66143, 25969, 12377, 63513,  9537, 72043, 47606, 24337,  9636,
        70358, 12377, 57326, 12220, 69809, 72043, 60020, 30078, 37486,
        66143, 52068, 37792, 56433, 36115, 66202, 19748, 47567, 72033,
        24056, 64143, 40215, 53935, 60020, 27922, 58616, 68290, 23364,
        37486, 64643, 20736, 63972, 22753, 60020, 18235, 66202,  9598,
        17011, 70688, 60020, 15969, 56376, 50470, 11339, 56360, 47606,
        70127, 40017,  9537,   835,  2640, 70167, 26661, 40351, 12192,
        41607,  2039, 60020,  9983,  3129, 70981, 72233, 41166, 26493,
         7589],
       [    0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0, 15501, 73050, 57546, 70688,
        40573, 42944, 69437, 43551, 47568, 73325, 11262, 70152, 12533,
        38046, 59832, 23534, 16568, 66854,  9636, 37487,  3790, 14620,
          251, 72043, 33704, 60020, 61858, 56433, 19288, 66202, 66143,
        69891, 37486, 11551, 37486, 46485,  9636, 12104, 45757, 60020,
        54278, 56433, 35251, 66202, 37792, 23166, 42712, 12220, 68059,
        12377],
       [    0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
        21427, 18616, 10577, 43872, 70152, 54720,  1239, 11479, 44275,
        52511, 56433, 31835, 41523, 33736, 56433, 60020, 62395, 12377,
        60020, 52637, 41713, 21427, 43132, 73110, 72043, 71749, 12377,
        61857, 40594, 57484,  4645, 60020, 71192, 72233, 40215, 52637,
        15799, 13600, 60020, 65226, 66854, 10962, 44212, 37486, 12220,
         9499],
       [    0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0, 21427, 66202, 13144, 60020, 39509,
        30735, 18616, 55046, 60020, 71710,  6678,   403, 37808, 51803,
        57326, 62594, 48494, 15444, 66143, 37963, 66642, 12377, 69774,
        26356],
       [    0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0, 68246, 17693, 70152, 11615, 21427, 66202, 53929,
        72043, 66683, 56243, 27095, 18616, 20736, 26903,  7589, 46411,
        12533, 19589, 70981, 55389, 31835, 60020, 53594, 12607, 45305,
        43493, 23855, 19452, 54406, 70981, 23534, 48494, 61174, 49418,
        60020, 11730,  4184, 23534, 15351, 58810, 19732, 51703, 21427,
        47439, 66202, 32900, 43772, 72043, 61174, 60020, 55712, 12377,
        66143],
       [    0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0,     0,     0,
            0,     0,     0,     0,     0,     0,     0, 21427, 66202,
        48494, 60020, 48762, 46413, 71710, 18616, 57326, 19732, 53013,
        18878, 49499, 61544, 39509, 12377, 47606, 64311, 23534, 11666,
        34161],
       [40594, 70152, 19732, 25692, 44275,  8027, 48323, 30747, 37713,
        72043, 60020, 45832, 72043, 20140, 73398, 57326, 19732, 58499,
        12377, 68198, 64311, 70152, 70404, 72233, 44275,  8027, 20736,
        21427, 19732, 60020, 30592, 58499, 65072, 40708, 70981, 12377,
         5046,  9012, 70152, 34161, 66361, 59832, 73398, 33899, 58696,
        48935, 23534, 70152, 43493, 12533, 10771, 70981, 60020, 15871,
        12377, 44275,  8552, 11137, 57326, 46329, 66143, 49462, 26461,
        23534, 43032, 32342,  5986, 12377,  9537, 64437, 23534, 26597,
        51564, 50501, 52683, 66202, 58499, 12377, 44275, 35289, 66544,
        20736, 73398, 66202, 70688, 19556, 60020, 56538,  5986, 12377,
        29829, 12377, 47606, 21827,  9636, 60020, 62385, 33743, 12377,
         2338]])

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 [334]:
split_frac = 0.8

featuresLen = len(features)

split_idx = int(featuresLen * split_frac)
print(split_idx)
test_idx = int(featuresLen * (split_frac + (1 - split_frac) / 2))
print(test_idx)

print(len(features))
print(len(labels))

print(features.shape)
print(labels.shape)

train_x, val_x = features[:split_idx], features[split_idx : test_idx]
train_y, val_y = labels[:split_idx], labels[split_idx : test_idx]

test_x = features[test_idx:]
test_y = labels[test_idx:]

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))


20000
22500
25000
25000
(25000, 200)
(25000,)
			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.
  • learning_rate: Learning rate

In [335]:
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 [336]:
#n_words = len(vocab)
# +1 because we have the padding word (index 0)
n_words = len(set(words)) + 1

print(n_words)
#Fix added in newer commit by udacity
#n_words = len(vocab_to_int)

# Create the graph object
graph = tf.Graph()
# Add nodes to the graph
with graph.as_default():
    # batch_size x review_length (one_hot encoding review)
    inputs_ = tf.placeholder(tf.int32, [None, seq_len], name='inputs')
    labels_ = tf.placeholder(tf.int32, [None, 1], name='labels')
    keep_prob = tf.placeholder(tf.float32, name='keep_prob')


74073

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 300 units, the function will return a tensor with size [batch_size, 300].


In [337]:
# 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 [338]:
with graph.as_default():
    # Your basic LSTM cell
    # input_size is deprecated (automatically detected?!). The input is the embed, so batch_size x embed_size
    # Every LSTM get a single word (length is embed_size because we use embedding instead of one-hot vector)
    # When we use batch_size > 1, every LSTM get all the nth-word of all the batches
    #lstm = tf.contrib.rnn.BasicLSTMCell(num_units=lstm_size, input_size=(batch_size, embed_size))
    lstm = tf.contrib.rnn.BasicLSTMCell(num_units=lstm_size)
    
    # Add dropout to the cell
    drop = tf.contrib.rnn.DropoutWrapper(cell=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)

# Initial state shape: batch_size x lstm_size.
print(initial_state)


(LSTMStateTuple(c=<tf.Tensor 'zeros:0' shape=(500, 256) dtype=float32>, h=<tf.Tensor 'zeros_1:0' shape=(500, 256) dtype=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 [339]:
# IMHO:
# Embed gets "inputs" placeholder as input which has shape batch_size x review_length
# tf.nn.dynamic_rnn creates #review_length LSTM in parallel
with graph.as_default():
    outputs, final_state = tf.nn.dynamic_rnn(cell=cell, inputs=embed, initial_state=initial_state)

# Outputs shape is batch_size x review_length (max_time) x lstm_size.
# It includes all the LSTMs (#review_length here).
# Each LSTM output is lstm_size, but we have to consider also the batch_size.
print("outputs shape: " + str(outputs.shape))
# Last LSTM state. Final state shape is batch_size x lstm_size
print("final state shape: " + str(final_state))


outputs shape: (500, 200, 256)
final state shape: (LSTMStateTuple(c=<tf.Tensor 'rnn/while/Exit_2:0' shape=(500, 256) dtype=float32>, h=<tf.Tensor 'rnn/while/Exit_3:0' shape=(500, 256) dtype=float32>),)

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 [340]:
print(len(set(words)))
with graph.as_default():
    # outputs shape is batch_size x review_length x lstm_size,
    # we pick the last LSTM output (batch_size x lstm_size)
    print(outputs.shape)
    print(outputs[:, -1].shape)
    # Squash all single LSTM output values (#lstm_size) to single output and apply sigmoid.
    predictions = tf.contrib.layers.fully_connected(outputs[:, -1], 1, activation_fn=tf.sigmoid)
    # Predictions shape is batch_size x 1, so labels is 2D shape=(batch_size,)
    print(predictions.shape)
    cost = tf.losses.mean_squared_error(labels_, predictions)
    
    optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)


74072
(500, 200, 256)
(500, 256)
(500, 1)

Validation accuracy

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


In [341]:
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 [342]:
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 [343]:
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")


Epoch: 0/10 Iteration: 5 Train loss: 0.244
Epoch: 0/10 Iteration: 10 Train loss: 0.238
Epoch: 0/10 Iteration: 15 Train loss: 0.214
Epoch: 0/10 Iteration: 20 Train loss: 0.203
Epoch: 0/10 Iteration: 25 Train loss: 0.179
Val acc: 0.732
Epoch: 0/10 Iteration: 30 Train loss: 0.177
Epoch: 0/10 Iteration: 35 Train loss: 0.159
Epoch: 0/10 Iteration: 40 Train loss: 0.203
Epoch: 1/10 Iteration: 45 Train loss: 0.143
Epoch: 1/10 Iteration: 50 Train loss: 0.208
Val acc: 0.720
Epoch: 1/10 Iteration: 55 Train loss: 0.232
Epoch: 1/10 Iteration: 60 Train loss: 0.194
Epoch: 1/10 Iteration: 65 Train loss: 0.177
Epoch: 1/10 Iteration: 70 Train loss: 0.155
Epoch: 1/10 Iteration: 75 Train loss: 0.131
Val acc: 0.770
Epoch: 1/10 Iteration: 80 Train loss: 0.155
Epoch: 2/10 Iteration: 85 Train loss: 0.117
Epoch: 2/10 Iteration: 90 Train loss: 0.167
Epoch: 2/10 Iteration: 95 Train loss: 0.129
Epoch: 2/10 Iteration: 100 Train loss: 0.112
Val acc: 0.810
Epoch: 2/10 Iteration: 105 Train loss: 0.121
Epoch: 2/10 Iteration: 110 Train loss: 0.117
Epoch: 2/10 Iteration: 115 Train loss: 0.096
Epoch: 2/10 Iteration: 120 Train loss: 0.092
Epoch: 3/10 Iteration: 125 Train loss: 0.091
Val acc: 0.824
Epoch: 3/10 Iteration: 130 Train loss: 0.089
Epoch: 3/10 Iteration: 135 Train loss: 0.078
Epoch: 3/10 Iteration: 140 Train loss: 0.077
Epoch: 3/10 Iteration: 145 Train loss: 0.094
Epoch: 3/10 Iteration: 150 Train loss: 0.106
Val acc: 0.789
Epoch: 3/10 Iteration: 155 Train loss: 0.096
Epoch: 3/10 Iteration: 160 Train loss: 0.096
Epoch: 4/10 Iteration: 165 Train loss: 0.067
Epoch: 4/10 Iteration: 170 Train loss: 0.060
Epoch: 4/10 Iteration: 175 Train loss: 0.046
Val acc: 0.785
Epoch: 4/10 Iteration: 180 Train loss: 0.048
Epoch: 4/10 Iteration: 185 Train loss: 0.065
Epoch: 4/10 Iteration: 190 Train loss: 0.144
Epoch: 4/10 Iteration: 195 Train loss: 0.070
Epoch: 4/10 Iteration: 200 Train loss: 0.141
Val acc: 0.639
Epoch: 5/10 Iteration: 205 Train loss: 0.109
Epoch: 5/10 Iteration: 210 Train loss: 0.136
Epoch: 5/10 Iteration: 215 Train loss: 0.171
Epoch: 5/10 Iteration: 220 Train loss: 0.122
Epoch: 5/10 Iteration: 225 Train loss: 0.071
Val acc: 0.809
Epoch: 5/10 Iteration: 230 Train loss: 0.117
Epoch: 5/10 Iteration: 235 Train loss: 0.088
Epoch: 5/10 Iteration: 240 Train loss: 0.097
Epoch: 6/10 Iteration: 245 Train loss: 0.106
Epoch: 6/10 Iteration: 250 Train loss: 0.131
Val acc: 0.793
Epoch: 6/10 Iteration: 255 Train loss: 0.092
Epoch: 6/10 Iteration: 260 Train loss: 0.119
Epoch: 6/10 Iteration: 265 Train loss: 0.090
Epoch: 6/10 Iteration: 270 Train loss: 0.150
Epoch: 6/10 Iteration: 275 Train loss: 0.114
Val acc: 0.804
Epoch: 6/10 Iteration: 280 Train loss: 0.099
Epoch: 7/10 Iteration: 285 Train loss: 0.057
Epoch: 7/10 Iteration: 290 Train loss: 0.105
Epoch: 7/10 Iteration: 295 Train loss: 0.051
Epoch: 7/10 Iteration: 300 Train loss: 0.061
Val acc: 0.803
Epoch: 7/10 Iteration: 305 Train loss: 0.027
Epoch: 7/10 Iteration: 310 Train loss: 0.046
Epoch: 7/10 Iteration: 315 Train loss: 0.021
Epoch: 7/10 Iteration: 320 Train loss: 0.019
Epoch: 8/10 Iteration: 325 Train loss: 0.095
Val acc: 0.840
Epoch: 8/10 Iteration: 330 Train loss: 0.059
Epoch: 8/10 Iteration: 335 Train loss: 0.047
Epoch: 8/10 Iteration: 340 Train loss: 0.047
Epoch: 8/10 Iteration: 345 Train loss: 0.047
Epoch: 8/10 Iteration: 350 Train loss: 0.045
Val acc: 0.653
Epoch: 8/10 Iteration: 355 Train loss: 0.029
Epoch: 8/10 Iteration: 360 Train loss: 0.354
Epoch: 9/10 Iteration: 365 Train loss: 0.215
Epoch: 9/10 Iteration: 370 Train loss: 0.221
Epoch: 9/10 Iteration: 375 Train loss: 0.211
Val acc: 0.588
Epoch: 9/10 Iteration: 380 Train loss: 0.213
Epoch: 9/10 Iteration: 385 Train loss: 0.197
Epoch: 9/10 Iteration: 390 Train loss: 0.197
Epoch: 9/10 Iteration: 395 Train loss: 0.169
Epoch: 9/10 Iteration: 400 Train loss: 0.168
Val acc: 0.697

Testing


In [344]:
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)))


Test accuracy: 0.714