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_orig = f.read()

In [3]:
reviews[:2000]


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

In [5]:
all_text[:2000]


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 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 [6]:
words[:100]


Out[6]:
['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 [7]:
import pickle
with open('../embeddings/word_embeddings.pkl', 'rb') as f:
    [vocab_to_int, embed_mat] = pickle.load(f)

In [8]:
embed_mat.shape


Out[8]:
(63641, 200)

In [9]:
bak = embed_mat[vocab_to_int['the'],:]

In [10]:
# Reorganize so that 0 can be the empty string.
embed_mat = np.concatenate((np.random.uniform(-1,1, (1,embed_mat.shape[1])),
                            embed_mat),
                           axis=0)



vocab_to_int = {k:v+1 for k,v in vocab_to_int.items()}

# embed_mat = embed_mat.copy()
# embed_mat.resize((embed_mat.shape[0]+1, embed_mat.shape[1]))
# embed_mat[-1,:] = embed_mat[0]
# embed_mat[0,:] = np.random.uniform(-1,1, (1,embed_mat.shape[1]))
# embed_mat.shape

In [11]:
vocab_to_int[''] = 0

In [12]:
assert(all(bak == embed_mat[vocab_to_int['the'],:]))

In [13]:
[k  for k,v in vocab_to_int.items() if v == 0]


Out[13]:
['']

In [14]:
embed_mat[vocab_to_int['stupid'],:]


Out[14]:
array([ 0.35697988,  0.1069046 ,  0.08238979, -0.00406986, -0.34720451,
       -0.77245474,  0.0808581 ,  0.49796218,  0.75016075,  0.07728519,
       -0.20827438,  0.38448888,  1.06788683,  0.83007568, -0.14582813,
        0.10820879,  0.4354361 , -0.06962948,  0.15013321, -0.24022944,
        0.51627201, -0.60149592, -0.48031864, -0.72488469, -0.02249308,
       -0.55005729, -0.40508327,  0.28334558, -0.10564353, -0.57459408,
        0.98043782,  0.14127359, -0.38759598, -0.02978262,  0.05406132,
        0.15871142,  0.69640952, -0.45155627, -0.13053691, -0.03086282,
       -0.32121602, -0.48382735,  0.16200632, -0.518565  ,  0.64365619,
       -0.24515107,  0.08551664, -0.53729045, -0.05288922,  0.33088401,
       -0.43984249, -0.40983635, -0.07039884, -0.04871373,  0.11257239,
       -0.20059106,  0.04986364,  0.7179212 ,  0.15679736,  0.42004651,
       -0.44161612,  0.29631335, -0.97390938,  0.23395972,  0.24074256,
       -0.45422056,  0.28060582, -0.17274907,  0.202913  , -0.70445651,
        0.08296651, -0.19971102, -0.20850761, -0.15931307,  0.24542986,
       -0.19555482,  0.65150326,  0.45571849, -0.80041206, -0.47911659,
       -0.60118043,  0.13611387,  0.52189785,  0.5831458 , -0.58627421,
        0.34075618,  0.06335662,  0.1288231 ,  0.22164184,  0.19596221,
        0.67848098,  0.09224103, -0.69386923,  0.58741403, -0.11836304,
       -0.33354563, -0.03038691,  0.33967263,  0.57766819, -0.17281742,
       -0.08231562,  0.13292058,  0.03230377, -0.71446282,  0.58813763,
        0.03187338, -0.24733698,  0.51105767, -0.44474944,  0.68396103,
        0.39127731, -0.13501169, -0.14051975,  0.1149906 , -0.81139165,
        0.42426777, -0.8137036 , -0.50563151,  0.05021006, -0.23224594,
       -0.0548373 , -0.17424335, -0.22003345,  0.70832747, -0.35698283,
        0.33907086,  0.49071813, -0.02342475, -0.24458125, -0.33864141,
        0.35244423,  0.16485272, -0.09101822, -0.0645677 ,  0.11732717,
        0.28215784, -0.21858871,  0.30952406, -0.20476204, -0.44197416,
       -0.11917711, -0.31815934, -0.01323729,  0.44033828, -0.72054112,
        0.07993569,  0.40662196,  0.13030107,  0.03254975,  0.0171403 ,
       -0.2088306 ,  0.53539294,  0.11975062,  0.57075435,  0.26117641,
       -0.0608898 , -0.26190588,  0.7102865 , -0.6699481 , -0.82266599,
        0.36200973, -0.44768903,  0.21385254, -0.60753149, -0.31191006,
        0.3310256 , -0.37905335,  0.13917191,  0.18705218,  0.22216362,
        0.29397151, -0.01335618,  0.19063088, -0.05634491,  0.03575912,
       -0.03168556, -0.54383653, -0.5089767 , -0.21046624,  0.81422889,
        0.64798337,  0.73423797,  0.8625893 ,  0.36075363, -0.34806883,
        0.18633921,  0.10010779, -0.28176621, -0.16703437,  0.35460892,
        0.08453263,  0.14628245,  0.05149674,  0.10497274,  0.78489035,
        0.3806071 , -0.58502221, -0.35085252, -0.02280574, -0.86601943])

In [15]:
non_words = set(['','.','\n'])
extra_words = set([w for w in set(words) if w not in vocab_to_int and w not in non_words])

new_vocab = [(word, index) for index,word in enumerate(extra_words, len(vocab_to_int))]

embed_mat = np.concatenate(
    (embed_mat,
     np.random.uniform(-1,1, (len(extra_words), embed_mat.shape[1]))),
    axis=0)

print("added {} extra words".format(len(extra_words)))

vocab_to_int.update(new_vocab)
del extra_words
del new_vocab


added 37807 extra words

In [16]:
37807/63641


Out[16]:
0.5940667179962603

In [17]:
reviews_ints = [[vocab_to_int[word] for word in review.split(' ') if word not in non_words] for review in reviews]
# Create your dictionary that maps vocab words to integers here vocab_to_int = {word: index for index,word in enumerate(set(words),1)} vocab_to_int[''] = 0 # Convert the reviews to integers, same shape as reviews list, but with integers non_words = set(['','.','\n']) reviews_ints = [[vocab_to_int[word] for word in review.split(' ') if word not in non_words] for review in reviews]

In [18]:
set([word for word in set(words) if word not in vocab_to_int])


Out[18]:
set()

In [19]:
len(vocab_to_int)


Out[19]:
101449

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 [20]:
# Convert labels to 1s and 0s for 'positive' and 'negative'
labels = np.array([(0 if l == 'negative' else 1) for l in labels_orig.split('\n')])

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


In [21]:
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 [22]:
x = [1,2,3]
x[:10]


Out[22]:
[1, 2, 3]

In [23]:
# Filter out that review with 0 length
new_values = [(review_ints[:200], label) for review_ints,label
              in zip(reviews_ints, labels)
              if len(review_ints) > 0]
reviews_ints, labels = zip(*new_values)

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 [24]:
seq_len = 200
features = np.array([([0] * (seq_len-len(review))) + review for review in reviews_ints])
labels = np.array(labels)

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


In [25]:
review = reviews_ints[0]

In [26]:
len(review)


Out[26]:
140

In [27]:
features[:10,:]


Out[27]:
array([[    0,     0,     0, ...,    27,  6006,   155],
       [    0,     0,     0, ...,    32,   400,  3126],
       [21756,    29, 74378, ...,  6286,    24,     6],
       ..., 
       [    0,     0,     0, ...,    11,   110,  5768],
       [    0,     0,     0, ...,    44,   505,   110],
       [   62,    72,    18, ..., 11464,    14,   105]])

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

split_tv = int(features.shape[0] * split_frac)
split_vt = int(round(features.shape[0] * (1-split_frac) / 2)) + split_tv
train_x = features[:split_tv,:]
train_y =   labels[:split_vt  ]

val_x = features[split_tv:split_vt,:]
val_y =   labels[split_tv:split_vt]

test_x = features[split_vt:,:]
test_y =   labels[split_vt:  ]

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.
  • learning_rate: Learning rate

In [53]:
#run_number = 7
if 'run_number' in locals():
    run_number += 1
else:
    run_number = 1
run_number


Out[53]:
2

In [54]:
lstm_size = 512
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 [55]:
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, shape=(None,seq_len), name='inputs')
    labels_ = tf.placeholder(tf.int32, shape=(None,1), name='labels')
    keep_prob = tf.placeholder(tf.float32, name='keep_prob')

In [56]:
n_words


Out[56]:
101449

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 [57]:
import os
os.makedirs('./logs/{}/val'.format(run_number), exist_ok=True)

In [58]:
word_order = {v:k for k,v in vocab_to_int.items()}
embedding_metadata_file = './logs/{}/val/metadata.tsv'.format(run_number)
with open(embedding_metadata_file, 'w') as f:
    for i in range(len(word_order)):
        f.write(word_order[i]+'\n')

In [59]:
projector_config = tf.contrib.tensorboard.plugins.projector.ProjectorConfig()
embedding_config = projector_config.embeddings.add()

In [60]:
embed_mat.dtype


Out[60]:
dtype('float64')

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

    with graph.as_default():
        with tf.name_scope('embedding'):
            embedding = tf.Variable(
                tf.random_uniform((n_words,embed_size),
                                  -1,1), name="word_embedding")
            embedding_config.tensor_name = embedding.name
            embedding_config.metadata_path = embedding_metadata_file
            embed = tf.nn.embedding_lookup(embedding, inputs_)
            tf.summary.histogram('embedding', embedding)
            
else:
    embed_size = embed_mat.shape[1] 

    with graph.as_default():
        with tf.name_scope('embedding'):
            embedding = tf.Variable(embed_mat, name="word_embedding", dtype=tf.float32)
            
            embedding_config.tensor_name = embedding.name
            embedding_config.metadata_path = embedding_metadata_file

            embed = tf.nn.embedding_lookup(embedding, inputs_)
            tf.summary.histogram('embedding', embedding)


/home/ACCELEWARE/scott.quiring/.conda/envs/dlr7/lib/python3.6/site-packages/ipykernel_launcher.py:22: DeprecationWarning: PyUnicode_AsEncodedObject() is deprecated; use PyUnicode_AsEncodedString() to encode from str to bytes or PyCodec_Encode() for generic encoding
/home/ACCELEWARE/scott.quiring/.conda/envs/dlr7/lib/python3.6/site-packages/ipykernel_launcher.py:23: DeprecationWarning: PyUnicode_AsEncodedObject() is deprecated; use PyUnicode_AsEncodedString() to encode from str to bytes or PyCodec_Encode() for generic encoding

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 [62]:
with graph.as_default():
    with tf.name_scope('LSTM'):
        # 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 [63]:
with graph.as_default():
    with tf.name_scope('LSTM'):
        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 [64]:
with graph.as_default():
    with tf.name_scope('Prediction'):
        predictions = tf.contrib.layers.fully_connected(outputs[:, -1], 1, activation_fn=tf.sigmoid)

    with tf.name_scope('Loss'):
        cost = tf.losses.mean_squared_error(labels_, predictions)
        tf.summary.scalar('cost', cost)
    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 [65]:
with graph.as_default():
    with tf.name_scope('Accuracy'):
        correct_pred = tf.equal(tf.cast(tf.round(predictions), tf.int32), labels_)
        accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
        tf.summary.scalar('accuracy',accuracy)

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 [66]:
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 [ ]:


In [67]:
train_y.mean()


Out[67]:
0.5

In [68]:
epochs = 20

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

with tf.Session(graph=graph) as sess:
    sess.run(tf.global_variables_initializer())
    train_writer = tf.summary.FileWriter('./logs/{}/train'.format(run_number), sess.graph)
    val_writer = tf.summary.FileWriter('./logs/{}/val'.format(run_number))
    tf.contrib.tensorboard.plugins.projector.visualize_embeddings(val_writer, embedding_config)
    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}
            summary, loss, state, _ = sess.run([merged, cost, final_state, optimizer],
                                               feed_dict=feed)
            train_writer.add_summary(summary, iteration)
            
            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}
                    summary, batch_acc, val_state = sess.run([merged, accuracy, final_state],
                                                             feed_dict=feed)
                    val_acc.append(batch_acc)
                    val_writer.add_summary(summary, iteration)
                    saver.save(sess, './logs/{}/model.ckpt'.format(run_number), iteration)
                print("Val acc: {:.3f}".format(np.mean(val_acc)))
            iteration +=1
    saver.save(sess, "checkpoints/sentiment.ckpt")


Epoch: 0/20 Iteration: 5 Train loss: 0.239
Epoch: 0/20 Iteration: 10 Train loss: 0.242
Epoch: 0/20 Iteration: 15 Train loss: 0.238
Epoch: 0/20 Iteration: 20 Train loss: 0.261
Epoch: 0/20 Iteration: 25 Train loss: 0.239
Val acc: 0.616
Epoch: 0/20 Iteration: 30 Train loss: 0.242
Epoch: 0/20 Iteration: 35 Train loss: 0.232
Epoch: 0/20 Iteration: 40 Train loss: 0.237
Epoch: 1/20 Iteration: 45 Train loss: 0.169
Epoch: 1/20 Iteration: 50 Train loss: 0.196
Val acc: 0.674
Epoch: 1/20 Iteration: 55 Train loss: 0.153
Epoch: 1/20 Iteration: 60 Train loss: 0.486
Epoch: 1/20 Iteration: 65 Train loss: 0.495
Epoch: 1/20 Iteration: 70 Train loss: 0.284
Epoch: 1/20 Iteration: 75 Train loss: 0.268
Val acc: 0.506
Epoch: 1/20 Iteration: 80 Train loss: 0.272
Epoch: 2/20 Iteration: 85 Train loss: 0.267
Epoch: 2/20 Iteration: 90 Train loss: 0.249
Epoch: 2/20 Iteration: 95 Train loss: 0.253
Epoch: 2/20 Iteration: 100 Train loss: 0.240
Val acc: 0.600
Epoch: 2/20 Iteration: 105 Train loss: 0.232
Epoch: 2/20 Iteration: 110 Train loss: 0.227
Epoch: 2/20 Iteration: 115 Train loss: 0.478
Epoch: 2/20 Iteration: 120 Train loss: 0.319
Epoch: 3/20 Iteration: 125 Train loss: 0.311
Val acc: 0.643
Epoch: 3/20 Iteration: 130 Train loss: 0.362
Epoch: 3/20 Iteration: 135 Train loss: 0.243
Epoch: 3/20 Iteration: 140 Train loss: 0.256
Epoch: 3/20 Iteration: 145 Train loss: 0.242
Epoch: 3/20 Iteration: 150 Train loss: 0.253
Val acc: 0.546
Epoch: 3/20 Iteration: 155 Train loss: 0.243
Epoch: 3/20 Iteration: 160 Train loss: 0.235
Epoch: 4/20 Iteration: 165 Train loss: 0.229
Epoch: 4/20 Iteration: 170 Train loss: 0.221
Epoch: 4/20 Iteration: 175 Train loss: 0.232
Val acc: 0.591
Epoch: 4/20 Iteration: 180 Train loss: 0.209
Epoch: 4/20 Iteration: 185 Train loss: 0.219
Epoch: 4/20 Iteration: 190 Train loss: 0.215
Epoch: 4/20 Iteration: 195 Train loss: 0.197
Epoch: 4/20 Iteration: 200 Train loss: 0.204
Val acc: 0.545
Epoch: 5/20 Iteration: 205 Train loss: 0.214
Epoch: 5/20 Iteration: 210 Train loss: 0.203
Epoch: 5/20 Iteration: 215 Train loss: 0.205
Epoch: 5/20 Iteration: 220 Train loss: 0.188
Epoch: 5/20 Iteration: 225 Train loss: 0.221
Val acc: 0.722
Epoch: 5/20 Iteration: 230 Train loss: 0.198
Epoch: 5/20 Iteration: 235 Train loss: 0.172
Epoch: 5/20 Iteration: 240 Train loss: 0.191
Epoch: 6/20 Iteration: 245 Train loss: 0.360
Epoch: 6/20 Iteration: 250 Train loss: 0.222
Val acc: 0.594
Epoch: 6/20 Iteration: 255 Train loss: 0.207
Epoch: 6/20 Iteration: 260 Train loss: 0.196
Epoch: 6/20 Iteration: 265 Train loss: 0.190
Epoch: 6/20 Iteration: 270 Train loss: 0.235
Epoch: 6/20 Iteration: 275 Train loss: 0.200
Val acc: 0.651
Epoch: 6/20 Iteration: 280 Train loss: 0.246
Epoch: 7/20 Iteration: 285 Train loss: 0.170
Epoch: 7/20 Iteration: 290 Train loss: 0.160
Epoch: 7/20 Iteration: 295 Train loss: 0.177
Epoch: 7/20 Iteration: 300 Train loss: 0.185
Val acc: 0.670
Epoch: 7/20 Iteration: 305 Train loss: 0.180
Epoch: 7/20 Iteration: 310 Train loss: 0.145
Epoch: 7/20 Iteration: 315 Train loss: 0.103
Epoch: 7/20 Iteration: 320 Train loss: 0.148
Epoch: 8/20 Iteration: 325 Train loss: 0.091
Val acc: 0.654
Epoch: 8/20 Iteration: 330 Train loss: 0.227
Epoch: 8/20 Iteration: 335 Train loss: 0.142
Epoch: 8/20 Iteration: 340 Train loss: 0.132
Epoch: 8/20 Iteration: 345 Train loss: 0.238
Epoch: 8/20 Iteration: 350 Train loss: 0.186
Val acc: 0.618
Epoch: 8/20 Iteration: 355 Train loss: 0.162
Epoch: 8/20 Iteration: 360 Train loss: 0.191
Epoch: 9/20 Iteration: 365 Train loss: 0.130
Epoch: 9/20 Iteration: 370 Train loss: 0.125
Epoch: 9/20 Iteration: 375 Train loss: 0.113
Val acc: 0.771
Epoch: 9/20 Iteration: 380 Train loss: 0.108
Epoch: 9/20 Iteration: 385 Train loss: 0.128
Epoch: 9/20 Iteration: 390 Train loss: 0.111
Epoch: 9/20 Iteration: 395 Train loss: 0.080
Epoch: 9/20 Iteration: 400 Train loss: 0.085
Val acc: 0.726
Epoch: 10/20 Iteration: 405 Train loss: 0.060
Epoch: 10/20 Iteration: 410 Train loss: 0.099
Epoch: 10/20 Iteration: 415 Train loss: 0.134
Epoch: 10/20 Iteration: 420 Train loss: 0.136
Epoch: 10/20 Iteration: 425 Train loss: 0.095
Val acc: 0.724
Epoch: 10/20 Iteration: 430 Train loss: 0.073
Epoch: 10/20 Iteration: 435 Train loss: 0.075
Epoch: 10/20 Iteration: 440 Train loss: 0.076
Epoch: 11/20 Iteration: 445 Train loss: 0.061
Epoch: 11/20 Iteration: 450 Train loss: 0.059
Val acc: 0.792
Epoch: 11/20 Iteration: 455 Train loss: 0.071
Epoch: 11/20 Iteration: 460 Train loss: 0.062
Epoch: 11/20 Iteration: 465 Train loss: 0.055
Epoch: 11/20 Iteration: 470 Train loss: 0.063
Epoch: 11/20 Iteration: 475 Train loss: 0.059
Val acc: 0.818
Epoch: 11/20 Iteration: 480 Train loss: 0.068
Epoch: 12/20 Iteration: 485 Train loss: 0.048
Epoch: 12/20 Iteration: 490 Train loss: 0.054
Epoch: 12/20 Iteration: 495 Train loss: 0.051
Epoch: 12/20 Iteration: 500 Train loss: 0.051
Val acc: 0.826
Epoch: 12/20 Iteration: 505 Train loss: 0.043
Epoch: 12/20 Iteration: 510 Train loss: 0.066
Epoch: 12/20 Iteration: 515 Train loss: 0.085
Epoch: 12/20 Iteration: 520 Train loss: 0.107
Epoch: 13/20 Iteration: 525 Train loss: 0.053
Val acc: 0.726
Epoch: 13/20 Iteration: 530 Train loss: 0.040
Epoch: 13/20 Iteration: 535 Train loss: 0.058
Epoch: 13/20 Iteration: 540 Train loss: 0.052
Epoch: 13/20 Iteration: 545 Train loss: 0.043
Epoch: 13/20 Iteration: 550 Train loss: 0.028
Val acc: 0.843
Epoch: 13/20 Iteration: 555 Train loss: 0.025
Epoch: 13/20 Iteration: 560 Train loss: 0.020
Epoch: 14/20 Iteration: 565 Train loss: 0.021
Epoch: 14/20 Iteration: 570 Train loss: 0.037
Epoch: 14/20 Iteration: 575 Train loss: 0.046
Val acc: 0.773
Epoch: 14/20 Iteration: 580 Train loss: 0.024
Epoch: 14/20 Iteration: 585 Train loss: 0.020
Epoch: 14/20 Iteration: 590 Train loss: 0.034
Epoch: 14/20 Iteration: 595 Train loss: 0.035
Epoch: 14/20 Iteration: 600 Train loss: 0.016
Val acc: 0.778
Epoch: 15/20 Iteration: 605 Train loss: 0.018
Epoch: 15/20 Iteration: 610 Train loss: 0.036
Epoch: 15/20 Iteration: 615 Train loss: 0.048
Epoch: 15/20 Iteration: 620 Train loss: 0.020
Epoch: 15/20 Iteration: 625 Train loss: 0.021
Val acc: 0.828
Epoch: 15/20 Iteration: 630 Train loss: 0.057
Epoch: 15/20 Iteration: 635 Train loss: 0.036
Epoch: 15/20 Iteration: 640 Train loss: 0.024
Epoch: 16/20 Iteration: 645 Train loss: 0.032
Epoch: 16/20 Iteration: 650 Train loss: 0.050
Val acc: 0.822
Epoch: 16/20 Iteration: 655 Train loss: 0.043
Epoch: 16/20 Iteration: 660 Train loss: 0.023
Epoch: 16/20 Iteration: 665 Train loss: 0.056
Epoch: 16/20 Iteration: 670 Train loss: 0.030
Epoch: 16/20 Iteration: 675 Train loss: 0.022
Val acc: 0.829
Epoch: 16/20 Iteration: 680 Train loss: 0.109
Epoch: 17/20 Iteration: 685 Train loss: 0.018
Epoch: 17/20 Iteration: 690 Train loss: 0.047
Epoch: 17/20 Iteration: 695 Train loss: 0.045
Epoch: 17/20 Iteration: 700 Train loss: 0.018
Val acc: 0.837
Epoch: 17/20 Iteration: 705 Train loss: 0.016
Epoch: 17/20 Iteration: 710 Train loss: 0.012
Epoch: 17/20 Iteration: 715 Train loss: 0.009
Epoch: 17/20 Iteration: 720 Train loss: 0.008
Epoch: 18/20 Iteration: 725 Train loss: 0.001
Val acc: 0.874
Epoch: 18/20 Iteration: 730 Train loss: 0.006
Epoch: 18/20 Iteration: 735 Train loss: 0.005
Epoch: 18/20 Iteration: 740 Train loss: 0.005
Epoch: 18/20 Iteration: 745 Train loss: 0.003
Epoch: 18/20 Iteration: 750 Train loss: 0.004
Val acc: 0.868
Epoch: 18/20 Iteration: 755 Train loss: 0.001
Epoch: 18/20 Iteration: 760 Train loss: 0.002
Epoch: 19/20 Iteration: 765 Train loss: 0.003
Epoch: 19/20 Iteration: 770 Train loss: 0.004
Epoch: 19/20 Iteration: 775 Train loss: 0.005
Val acc: 0.868
Epoch: 19/20 Iteration: 780 Train loss: 0.003
Epoch: 19/20 Iteration: 785 Train loss: 0.004
Epoch: 19/20 Iteration: 790 Train loss: 0.005
Epoch: 19/20 Iteration: 795 Train loss: 0.000
Epoch: 19/20 Iteration: 800 Train loss: 0.000
Val acc: 0.870

In [69]:
train_writer.flush()
val_writer.flush()

In [ ]:

Testing


In [70]:
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.863

Test accuracy: 0.748
Test accuracy: 0.784


In [71]:
print(features.shape)


(25000, 200)

In [82]:
def TestSomeText(text):
    text = text.lower()
    delete = ['.','!',',','"',"'",'\n']
    for d in delete:
        text = text.replace(d," ")
    text_ints = [vocab_to_int[word] for word in text.split(' ') if word in vocab_to_int]
    print(len(text_ints))
    text_ints = text_ints[:seq_len]
    #print(text_ints)
    #text_features = np.zeros((batch_size,seq_len))
    text_features = np.array([([0] * (seq_len-len(text_ints))) + text_ints] * batch_size)
    #print(text_features)
    #print(text_features.shape)
    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 i in range(1):
            feed = {inputs_: text_features,
                    labels_: [[0]]*batch_size,
                    keep_prob: 1,
                    initial_state: test_state}
            pred, mycost, test_state = sess.run([predictions, accuracy, final_state], feed_dict=feed)
    return pred[0,0]

In [73]:
TestSomeText("highly underrated movie")
#pred[0,0]


Out[73]:
0.90843976

In [74]:
TestSomeText('overrated movie')


Out[74]:
0.11279746

In [83]:
TestSomeText("""I ve been looking forward to a viking film or TV series for many years
and when my wishes were finally granted, I was very worried that this production
was going to be total crap. After viewing the first two episodes I do not worry
about that anymore. Thank you, Odin
As a person of some historical knowledge of the viking era, I can point out numerous
flaws - but they don't ruin the story for me, so I will let them slip. Historical
accounts about those days are, after all, not entirely reliable.
Happy to see Travis Fimmel in a role that totally suits him. A physical and intense
character, with that spice of humor that is the viking trademark from the sagas.
Gabriel Byrne plays a stern leader, that made me think of him in "Prince of Jutland",
and Clive Standen seems like he's going to surprise us.
Been pondering the Game of Thrones comparison, since I love that show too, but in my
opinion Vikings has its own thing going on. Way fewer lead characters to begin with,
and also a more straight forward approach. Plenty of room for more series with this
high class!
Can I wish for more than the planned nine episodes, PLEASE!!!""")


236
Out[83]:
0.28223041

In [96]:
TestSomeText("""vikings""")


1
Out[96]:
0.16672063

In [76]:
delete = ['.','!',',','"',"'",'\n']
for d in delete:
    text = text.replace(d," ")


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-76-28435776e4a8> in <module>()
      1 delete = ['.','!',',','"',"'",'\n']
      2 for d in delete:
----> 3     text = text.replace(d," ")

NameError: name 'text' is not defined

In [77]:
TestSomeText("""Pirates of the Caribbean has always been a franchise that makes no attempt for Oscar worthy material but in its own way is massively enjoyable.

Pirates of the Caribbean: Dead Men Tell No Tales certainly embraces the aspects of the original movie while also incorporating new plot lines that fit in well with plots from the original story. With the introduction of Henry and Karina there is a new love interest that is provided to the audience that rivals that of Will and Elizabeth Turner's.

Henry Turner is portrayed as an almost exact copy of his father except just a teensy bit worse at sword fighting while Karina differs from the usual women as she remains just as important, if not more, as Henry as she guides the course towards Posiedon's trident.

Jack Sparrow is entertaining as always with his usual drunk characteristics. For those of you who are tired of Sparrow acting this way Don't SEE THE MOVIE Jack sparrow isn't going to change because it doesn't make sense for his character to suddenly change.

All together the movie was expertly written and expertly performed by the entire cast even Kiera Knightely who didn't manage to get one word throughout the whole movie. I know as a major fan of the Pirates of the Caribbean I can't wait to see what happens for the future of the franchise.
""")


Out[77]:
0.93077099

In [ ]:
pred,mycost = TestSomeText(text)
pred[0,0]

In [78]:
TestSomeText("""If your child is a fan of the Wimpy Kid series, they'll no doubt enjoy this one, it's entertaining and lowbrow enough to also appease the moodiest of teens and grumpiest adults.""")


Out[78]:
0.69900268

In [79]:
TestSomeText("""At first I thought the film was going to be just a normal thriller but it turned out to be a thousand times better than I expected. The film is truly original and was so dark & sinister that gives the tensive mood also it is emotionally & psychologically thrilling, the whole movie is charged with pulse pounding suspense and seems like it's really happening. It's amazing that how they managed to make an 80 minute movie with just a guy in a phone booth but the full credit goes to Colin Farrell and Larry Cohen the writer not Joel Schumacher because he is a crappy director. Joel Schumacher's films are rubbish especially The Number 23, Phone Booth was shot in 10 days with a budget of $10 million so it wasn't a hard job to make it, that's why Joel doesn't get any credit but the cast & crew did a fantastic job. I also really liked the raspberry coloured shirt Colin was wearing and it was an excellent choice of clothing because the viewers are going to watch him throughout the whole film. When I first saw the movie I fell in love with it and I bought it on DVD the next day and I've seen it about 20 times and I'm still not fed up with it. Phone Booth is and always will be Colin Farrell's best film! Overall it is simply one of my favourite films and I even argued over my friend because he didn't like it.
""")


Out[79]:
0.19138487

In [ ]:
delete = ['.','!',',','"',"'",'\n']
for d in delete:
    text = text.replace(d," ")

In [ ]:
text

In [ ]:
pred,mycost = TestSomeText(text)
pred[0,0]

In [80]:
TestSomeText("""There are few quality movies or series about the Vikings, and this series is outstanding and well worth waiting for. Not only is Vikings a series that is a joy to watch, it is also a series that is easy to recommend. I personally feel that the creator and producers did a fine job of giving the viewer quality material. Now, there are a few inconsistencies with the series, most notably would be the idea that Vikings had very little knowledge of other European countries and were amazed by these people across the big waters. In reality Vikings engaged in somewhat normal commercial activities with other Anglo-Saxons, so the idea that Vikings were as amazed as they seemed when they realize that other people were out there is not that realistic. However, it is this small inconsistency that goes a long way in holding the premise together. I simply love the series and would recommend it to anyone wanting to watch a quality show.""")


Out[80]:
0.12850964

In [ ]:
delete = ['.','!',',','"',"'",'\n']
for d in delete:
    text = text.replace(d," ")

In [ ]:
pred,mycost = TestSomeText(text)
pred[0,0]

In [81]:
TestSomeText("""This movie didn't feel any different from the other anime movies out there. Sure, the sibling dynamics were good, as well as the family values, the childhood memories and older brother anxiety. The main idea was interesting, with the new baby seeming rather like a boss sent into the family to spy on the parents and solve a big problem for his company. You can't help but identify with the older kid, especially if you have younger siblings. But eventually, the action was a bit main stream. The action scenes were not original and kind of boring. Other than that, the story became a little complicated when you start to think about what's real and what's not. The narration was good and the animation was nice, with the cute babies and puppies. So, 4 out of 10.

""")


Out[81]:
0.021647727

In [ ]:
delete = ['.','!',',','"',"'",'\n']
for d in delete:
    text = text.replace(d," ")

In [ ]:
text

In [ ]:
pred,mycost = TestSomeText(text)
pred[0,0]

In [98]:
TestSomeText('seriously awesome movie')


3
Out[98]:
0.37036353

In [ ]: