Missed TensorFlow Dev Summit? Check out the video playlist. Watch recordings

Text classification with an RNN

View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook

This text classification tutorial trains a recurrent neural network on the IMDB large movie review dataset for sentiment analysis.

Setup

!pip install -q tf-nightly
import tensorflow_datasets as tfds
import tensorflow as tf
ERROR: tensorflow 2.1.0 has requirement gast==0.2.2, but you'll have gast 0.3.3 which is incompatible.

Import matplotlib and create a helper function to plot graphs:

import matplotlib.pyplot as plt

def plot_graphs(history, metric):
  plt.plot(history.history[metric])
  plt.plot(history.history['val_'+metric], '')
  plt.xlabel("Epochs")
  plt.ylabel(metric)
  plt.legend([metric, 'val_'+metric])
  plt.show()

Setup input pipeline

The IMDB large movie review dataset is a binary classification dataset—all the reviews have either a positive or negative sentiment.

Download the dataset using TFDS.

dataset, info = tfds.load('imdb_reviews/subwords8k', with_info=True,
                          as_supervised=True)
train_examples, test_examples = dataset['train'], dataset['test']

The dataset info includes the encoder (a tfds.features.text.SubwordTextEncoder).

encoder = info.features['text'].encoder
print('Vocabulary size: {}'.format(encoder.vocab_size))
Vocabulary size: 8185

This text encoder will reversibly encode any string, falling back to byte-encoding if necessary.

sample_string = 'Hello TensorFlow.'

encoded_string = encoder.encode(sample_string)
print('Encoded string is {}'.format(encoded_string))

original_string = encoder.decode(encoded_string)
print('The original string: "{}"'.format(original_string))
Encoded string is [4025, 222, 6307, 2327, 4043, 2120, 7975]
The original string: "Hello TensorFlow."

assert original_string == sample_string
for index in encoded_string:
  print('{} ----> {}'.format(index, encoder.decode([index])))
4025 ----> Hell
222 ----> o 
6307 ----> Ten
2327 ----> sor
4043 ----> Fl
2120 ----> ow
7975 ----> .

Prepare the data for training

Next create batches of these encoded strings. Use the padded_batch method to zero-pad the sequences to the length of the longest string in the batch:

BUFFER_SIZE = 10000
BATCH_SIZE = 64
train_dataset = (train_examples
                 .shuffle(BUFFER_SIZE)
                 .padded_batch(BATCH_SIZE, padded_shapes=([None],[])))

test_dataset = (test_examples
                .padded_batch(BATCH_SIZE,  padded_shapes=([None],[])))
train_dataset = (train_examples
                 .shuffle(BUFFER_SIZE)
                 .padded_batch(BATCH_SIZE))

test_dataset = (test_examples
                .padded_batch(BATCH_SIZE))

Create the model

Build a tf.keras.Sequential model and start with an embedding layer. An embedding layer stores one vector per word. When called, it converts the sequences of word indices to sequences of vectors. These vectors are trainable. After training (on enough data), words with similar meanings often have similar vectors.

This index-lookup is much more efficient than the equivalent operation of passing a one-hot encoded vector through a tf.keras.layers.Dense layer.

A recurrent neural network (RNN) processes sequence input by iterating through the elements. RNNs pass the outputs from one timestep to their input—and then to the next.

The tf.keras.layers.Bidirectional wrapper can also be used with an RNN layer. This propagates the input forward and backwards through the RNN layer and then concatenates the output. This helps the RNN to learn long range dependencies.

model = tf.keras.Sequential([
    tf.keras.layers.Embedding(encoder.vocab_size, 64),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(1)
])

Compile the Keras model to configure the training process:

model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
              optimizer=tf.keras.optimizers.Adam(1e-4),
              metrics=['accuracy'])

Train the model

history = model.fit(train_dataset, epochs=10,
                    validation_data=test_dataset, 
                    validation_steps=30)
Epoch 1/10
391/391 [==============================] - 40s 103ms/step - loss: 0.6406 - accuracy: 0.5610 - val_loss: 0.4282 - val_accuracy: 0.8078
Epoch 2/10
391/391 [==============================] - 41s 104ms/step - loss: 0.3428 - accuracy: 0.8578 - val_loss: 0.3380 - val_accuracy: 0.8510
Epoch 3/10
391/391 [==============================] - 41s 104ms/step - loss: 0.2560 - accuracy: 0.9014 - val_loss: 0.3209 - val_accuracy: 0.8646
Epoch 4/10
391/391 [==============================] - 41s 104ms/step - loss: 0.2138 - accuracy: 0.9211 - val_loss: 0.3430 - val_accuracy: 0.8714
Epoch 5/10
391/391 [==============================] - 41s 105ms/step - loss: 0.1869 - accuracy: 0.9330 - val_loss: 0.3498 - val_accuracy: 0.8677
Epoch 6/10
391/391 [==============================] - 40s 103ms/step - loss: 0.1736 - accuracy: 0.9378 - val_loss: 0.3690 - val_accuracy: 0.8682
Epoch 7/10
391/391 [==============================] - 40s 103ms/step - loss: 0.1502 - accuracy: 0.9495 - val_loss: 0.3648 - val_accuracy: 0.8573
Epoch 8/10
391/391 [==============================] - 40s 103ms/step - loss: 0.1397 - accuracy: 0.9531 - val_loss: 0.4227 - val_accuracy: 0.8547
Epoch 9/10
391/391 [==============================] - 40s 103ms/step - loss: 0.1259 - accuracy: 0.9581 - val_loss: 0.4375 - val_accuracy: 0.8562
Epoch 10/10
391/391 [==============================] - 40s 103ms/step - loss: 0.1249 - accuracy: 0.9601 - val_loss: 0.4373 - val_accuracy: 0.8547

test_loss, test_acc = model.evaluate(test_dataset)

print('Test Loss: {}'.format(test_loss))
print('Test Accuracy: {}'.format(test_acc))
391/391 [==============================] - 15s 40ms/step - loss: 0.4355 - accuracy: 0.8561
Test Loss: 0.4355419874191284
Test Accuracy: 0.8561199903488159

The above model does not mask the padding applied to the sequences. This can lead to skew if trained on padded sequences and test on un-padded sequences. Ideally you would use masking to avoid this, but as you can see below it only have a small effect on the output.

If the prediction is >= 0.5, it is positive else it is negative.

def pad_to_size(vec, size):
  zeros = [0] * (size - len(vec))
  vec.extend(zeros)
  return vec
def sample_predict(sample_pred_text, pad):
  encoded_sample_pred_text = encoder.encode(sample_pred_text)

  if pad:
    encoded_sample_pred_text = pad_to_size(encoded_sample_pred_text, 64)
  encoded_sample_pred_text = tf.cast(encoded_sample_pred_text, tf.float32)
  predictions = model.predict(tf.expand_dims(encoded_sample_pred_text, 0))

  return (predictions)
# predict on a sample text without padding.

sample_pred_text = ('The movie was cool. The animation and the graphics '
                    'were out of this world. I would recommend this movie.')
predictions = sample_predict(sample_pred_text, pad=False)
print(predictions)
[[0.24708563]]

# predict on a sample text with padding

sample_pred_text = ('The movie was cool. The animation and the graphics '
                    'were out of this world. I would recommend this movie.')
predictions = sample_predict(sample_pred_text, pad=True)
print(predictions)
[[-0.32349688]]

plot_graphs(history, 'accuracy')

png

plot_graphs(history, 'loss')

png

Stack two or more LSTM layers

Keras recurrent layers have two available modes that are controlled by the return_sequences constructor argument:

  • Return either the full sequences of successive outputs for each timestep (a 3D tensor of shape (batch_size, timesteps, output_features)).
  • Return only the last output for each input sequence (a 2D tensor of shape (batch_size, output_features)).
model = tf.keras.Sequential([
    tf.keras.layers.Embedding(encoder.vocab_size, 64),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64,  return_sequences=True)),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dropout(0.5),
    tf.keras.layers.Dense(1)
])
model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
              optimizer=tf.keras.optimizers.Adam(1e-4),
              metrics=['accuracy'])
history = model.fit(train_dataset, epochs=10,
                    validation_data=test_dataset,
                    validation_steps=30)
Epoch 1/10
391/391 [==============================] - 73s 188ms/step - loss: 0.6533 - accuracy: 0.5583 - val_loss: 0.5066 - val_accuracy: 0.7781
Epoch 2/10
391/391 [==============================] - 74s 189ms/step - loss: 0.4130 - accuracy: 0.8283 - val_loss: 0.3866 - val_accuracy: 0.8344
Epoch 3/10
391/391 [==============================] - 74s 190ms/step - loss: 0.2935 - accuracy: 0.8892 - val_loss: 0.3406 - val_accuracy: 0.8604
Epoch 4/10
391/391 [==============================] - 75s 193ms/step - loss: 0.2360 - accuracy: 0.9168 - val_loss: 0.3579 - val_accuracy: 0.8625
Epoch 5/10
391/391 [==============================] - 75s 192ms/step - loss: 0.2028 - accuracy: 0.9318 - val_loss: 0.3645 - val_accuracy: 0.8568
Epoch 6/10
391/391 [==============================] - 76s 193ms/step - loss: 0.1811 - accuracy: 0.9412 - val_loss: 0.3920 - val_accuracy: 0.8604
Epoch 7/10
391/391 [==============================] - 75s 192ms/step - loss: 0.1547 - accuracy: 0.9529 - val_loss: 0.4203 - val_accuracy: 0.8583
Epoch 8/10
391/391 [==============================] - 75s 191ms/step - loss: 0.1333 - accuracy: 0.9617 - val_loss: 0.4406 - val_accuracy: 0.8536
Epoch 9/10
391/391 [==============================] - 75s 192ms/step - loss: 0.1136 - accuracy: 0.9699 - val_loss: 0.4735 - val_accuracy: 0.8422
Epoch 10/10
391/391 [==============================] - 75s 192ms/step - loss: 0.0988 - accuracy: 0.9755 - val_loss: 0.5162 - val_accuracy: 0.8536

test_loss, test_acc = model.evaluate(test_dataset)

print('Test Loss: {}'.format(test_loss))
print('Test Accuracy: {}'.format(test_acc))
391/391 [==============================] - 29s 74ms/step - loss: 0.4999 - accuracy: 0.8492
Test Loss: 0.4999251365661621
Test Accuracy: 0.8492000102996826

# predict on a sample text without padding.

sample_pred_text = ('The movie was not good. The animation and the graphics '
                    'were terrible. I would not recommend this movie.')
predictions = sample_predict(sample_pred_text, pad=False)
print(predictions)
[[-2.537749]]

# predict on a sample text with padding

sample_pred_text = ('The movie was not good. The animation and the graphics '
                    'were terrible. I would not recommend this movie.')
predictions = sample_predict(sample_pred_text, pad=True)
print(predictions)
[[-2.4626944]]

plot_graphs(history, 'accuracy')

png

plot_graphs(history, 'loss')

png

Check out other existing recurrent layers such as GRU layers.

If you're interestied in building custom RNNs, see the Keras RNN Guide.