Text Classification with TF Hub

Use a pretrained model from TF Hub to classify text

This tutorial classifies movie reviews as positive or negative using the text of the review. This is an example of binary—or two-class—classification, an important and widely applicable kind of machine learning problem.

The tutorial demonstrates the basic application of transfer learning with TensorFlow Hub and Keras.

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

This notebook uses keras, a high-level API to build and train models in TensorFlow, and TensorFlow hub, a library for loading trained models from TFHub in a single line of code. For a more advanced text classification tutorial using Keras, see the MLCC Text Classification Guide.


Download the IMDB dataset

The IMDB dataset is available on imdb reviews or on TensorFlow datasets. The following code downloads the IMDB dataset to your machine:

if (dir.exists("aclImdb/"))
  unlink("aclImdb/", recursive = TRUE)
url <- "https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz"
dataset <- get_file(
  untar = TRUE,
  cache_dir = '.',
  cache_subdir = ''
unlink("aclImdb/train/unsup/", recursive = TRUE)

We can then create a TensorFlow dataset from the directory structure using the text_dataset_from_directory() function:

batch_size <- 512
seed <- 42

train_data <- text_dataset_from_directory(
  batch_size = batch_size,
  validation_split = 0.2,
  subset = 'training',
  seed = seed
validation_data <- text_dataset_from_directory(
  batch_size = batch_size,
  validation_split = 0.2,
  subset = 'validation',
  seed = seed
test_data <- text_dataset_from_directory(
  batch_size = batch_size

Explore the data

Let’s take a moment to understand the format of the data. Each example is a sentence representing the movie review and a corresponding label. The sentence is not preprocessed in any way. The label is an integer value of either 0 or 1, where 0 is a negative review, and 1 is a positive review.

Let’s print first 10 examples.

batch <- train_data %>%
  reticulate::as_iterator() %>%

tf.Tensor(b'Upon seeing this film once again it appeared infinitely superior to me this time than the previous times I have viewed it. The acting is stunningly wonderful. The characters are very clearly drawn. Brad Pitt is simply superb as the errant son who rebels. The other actors and actresses are equally fine in every respect. Robert Redford creates a wonderful period piece from the days of speakeasies of the 1920s. The scenery is incredibly beautiful of the mountains and streams of western Montana. All in all, this is one of the finest films made in the 1990s.<br /><br />You must see this movie!<br /><br />', shape=(), dtype=string)

Let’s also print the first 10 labels.

tf.Tensor([1 0 1 0 0 0 1 1 0 0], shape=(10), dtype=int32)

Build the model

The neural network is created by stacking layers—this requires three main architectural decisions:

  • How to represent the text?
  • How many layers to use in the model?
  • How many hidden units to use for each layer?

In this example, the input data consists of sentences. The labels to predict are either 0 or 1.

One way to represent the text is to convert sentences into embeddings vectors. Use a pre-trained text embedding as the first layer, which will have three advantages:

  • You don’t have to worry about text preprocessing,
  • Benefit from transfer learning,
  • the embedding has a fixed size, so it’s simpler to process.

For this example you use a pre-trained text embedding model from TensorFlow Hub called google/nnlm-en-dim50/2.

There are many other pre-trained text embeddings from TFHub that can be used in this tutorial:

And many more! Find more text embedding models on TFHub.

Let’s first create a Keras layer that uses a TensorFlow Hub model to embed the sentences, and try it out on a couple of input examples. Note that no matter the length of the input text, the output shape of the embeddings is: (num_examples, embedding_dimension).

embedding <- "https://tfhub.dev/google/nnlm-en-dim50/2"
hub_layer <- tfhub::layer_hub(handle = embedding, trainable = TRUE)
[[ 0.25639075  0.3877134   0.11458008  0.46377152 -0.27114582 -0.23548658
  -0.05462555  0.05912564 -0.5467191   0.3111871  -0.1600283  -0.07053421
  -0.24705383  0.09001824 -0.04209795 -0.338748   -0.24183151 -0.32309988
   0.10837323 -0.63822275  0.07474954 -0.47535446  0.40693286  0.31290904
  -0.15077834  0.16694836 -0.6367395   0.18927397  0.44574213 -0.24568915
  -0.46415132  0.25134537  0.14228602 -0.4408587  -0.26528108  0.09904836
   0.18815233 -0.05307331  0.2677936  -0.60579234 -0.27559575  0.05044953
  -0.48596272  0.21479744 -0.17461552 -0.64222157 -0.31650636 -0.33656725
  -0.09484115 -0.07192937]
 [ 1.2899796   0.32863247 -0.00310844  0.8232223  -0.40982845 -0.5109542
   0.08370162 -0.13269287 -1.1700541   0.55316675 -0.05031178  0.14853314
  -0.15995869  0.26997143 -0.3404822  -0.49329752 -0.25939593  0.03390278
   0.25013074 -1.417716    0.19143656 -0.2392007   1.2250862   0.41607675
  -0.66565406  0.42407426 -1.2803619   0.47229245  0.53426725 -0.84027433
  -0.7578848   0.44375423  0.57404596 -0.5191065  -0.67364585  0.6255407
   0.54375225  0.22559978  0.17738008 -1.0557281   0.03807904  0.44274876
  -0.45797464  0.17220229 -0.2047742  -0.3091375  -0.7907681  -0.723012
   0.00783113 -0.0088165 ]], shape=(2, 50), dtype=float32)

Let’s now build the full model:

model <- keras_model_sequential() %>%
  hub_layer() %>%
  layer_dense(16, activation = 'relu') %>%

Model: <no summary available, model was not built>

The layers are stacked sequentially to build the classifier:

  1. The first layer is a TensorFlow Hub layer. This layer uses a pre-trained Saved Model to map a sentence into its embedding vector. The pre-trained text embedding model that you are using (google/nnlm-en-dim50/2) splits the sentence into tokens, embeds each token and then combines the embedding. The resulting dimensions are: (num_examples, embedding_dimension). For this NNLM model, the embedding_dimension is 50.
  2. This fixed-length output vector is piped through a fully-connected (Dense) layer with 16 hidden units.
  3. The last layer is densely connected with a single output node.

Let’s compile the model.

Loss function and optimizer

A model needs a loss function and an optimizer for training. Since this is a binary classification problem and the model outputs logits (a single-unit layer with a linear activation), you’ll use the binary_crossentropy loss function.

This isn’t the only choice for a loss function, you could, for instance, choose mean_squared_error. But, generally, binary_crossentropy is better for dealing with probabilities—it measures the “distance” between probability distributions, or in our case, between the ground-truth distribution and the predictions.

Later, when you are exploring regression problems (say, to predict the price of a house), you’ll see how to use another loss function called mean squared error.

Now, configure the model to use an optimizer and a loss function:

model %>% compile(
  optimizer = 'adam',
  loss = loss_binary_crossentropy(from_logits = TRUE),
  metrics = 'accuracy'

Train the model

Train the model for 10 epochs in mini-batches of 512 samples. This is 10 iterations over all samples in the x_train and y_train tensors. While training, monitor the model’s loss and accuracy on the 10,000 samples from the validation set:

history <- model %>% fit(
  epochs = 10,
  validation_data = validation_data,
  verbose <- 1

Evaluate the model

And let’s see how the model performs. Two values will be returned. Loss (a number which represents our error, lower values are better), and accuracy.

results <- model %>% evaluate(test_data, verbose = 2)
     loss  accuracy 
0.3458011 0.8584400 

This fairly naive approach achieves an accuracy of about 87%. With more advanced approaches, the model should get closer to 95%.

Further reading