Exploring the TF-Hub CORD-19 Swivel Embeddings

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

The CORD-19 Swivel text embedding module from TF-Hub (https://tfhub.dev/tensorflow/cord-19/swivel-128d/3) was built to support researchers analyzing natural languages text related to COVID-19. These embeddings were trained on the titles, authors, abstracts, body texts, and reference titles of articles in the CORD-19 dataset.

In this colab we will:

  • Analyze semantically similar words in the embedding space
  • Train a classifier on the SciCite dataset using the CORD-19 embeddings

Setup

import functools
import itertools
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd

import tensorflow as tf

import tensorflow_datasets as tfds
import tensorflow_hub as hub

from tqdm import trange

Analyze the embeddings

Let's start off by analyzing the embedding by calculating and plotting a correlation matrix between different terms. If the embedding learned to successfully capture the meaning of different words, the embedding vectors of semantically similar words should be close together. Let's take a look at some COVID-19 related terms.

# Use the inner product between two embedding vectors as the similarity measure
def plot_correlation(labels, features):
  corr = np.inner(features, features)
  corr /= np.max(corr)
  sns.heatmap(corr, xticklabels=labels, yticklabels=labels)

# Generate embeddings for some terms
queries = [
  # Related viruses
  'coronavirus', 'SARS', 'MERS',
  # Regions
  'Italy', 'Spain', 'Europe',
  # Symptoms
  'cough', 'fever', 'throat'
]

module = hub.load('https://tfhub.dev/tensorflow/cord-19/swivel-128d/3')
embeddings = module(queries)

plot_correlation(queries, embeddings)

png

We can see that the embedding successfully captured the meaning of the different terms. Each word is similar to the other words of its cluster (i.e. "coronavirus" highly correlates with "SARS" and "MERS"), while they are different from terms of other clusters (i.e. the similarity between "SARS" and "Spain" is close to 0).

Now let's see how we can use these embeddings to solve a specific task.

SciCite: Citation Intent Classification

This section shows how one can use the embedding for downstream tasks such as text classification. We'll use the SciCite dataset from TensorFlow Datasets to classify citation intents in academic papers. Given a sentence with a citation from an academic paper, classify whether the main intent of the citation is as background information, use of methods, or comparing results.

builder = tfds.builder(name='scicite')
builder.download_and_prepare()
train_data, validation_data, test_data = builder.as_dataset(
    split=('train', 'validation', 'test'),
    as_supervised=True)

NUM_EXAMPLES =   10

TEXT_FEATURE_NAME = builder.info.supervised_keys[0]
LABEL_NAME = builder.info.supervised_keys[1]

def label2str(numeric_label):
  m = builder.info.features[LABEL_NAME].names
  return m[numeric_label]

data = next(iter(train_data.batch(NUM_EXAMPLES)))


pd.DataFrame({
    TEXT_FEATURE_NAME: [ex.numpy().decode('utf8') for ex in data[0]],
    LABEL_NAME: [label2str(x) for x in data[1]]
})

Training a citaton intent classifier

We'll train a classifier on the SciCite dataset using Keras. Let's build a model which use the CORD-19 embeddings with a classification layer on top.



EMBEDDING = 'https://tfhub.dev/tensorflow/cord-19/swivel-128d/3'  
TRAINABLE_MODULE = False  

hub_layer = hub.KerasLayer(EMBEDDING, input_shape=[], 
                           dtype=tf.string, trainable=TRAINABLE_MODULE)

model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(3))
model.summary()
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
WARNING:tensorflow:Layer dense is casting an input tensor from dtype float64 to the layer's dtype of float32, which is new behavior in TensorFlow 2.  The layer has dtype float32 because it's dtype defaults to floatx.

If you intended to run this layer in float32, you can safely ignore this warning. If in doubt, this warning is likely only an issue if you are porting a TensorFlow 1.X model to TensorFlow 2.

To change all layers to have dtype float64 by default, call `tf.keras.backend.set_floatx('float64')`. To change just this layer, pass dtype='float64' to the layer constructor. If you are the author of this layer, you can disable autocasting by passing autocast=False to the base Layer constructor.


Warning:tensorflow:Layer dense is casting an input tensor from dtype float64 to the layer's dtype of float32, which is new behavior in TensorFlow 2.  The layer has dtype float32 because it's dtype defaults to floatx.

If you intended to run this layer in float32, you can safely ignore this warning. If in doubt, this warning is likely only an issue if you are porting a TensorFlow 1.X model to TensorFlow 2.

To change all layers to have dtype float64 by default, call `tf.keras.backend.set_floatx('float64')`. To change just this layer, pass dtype='float64' to the layer constructor. If you are the author of this layer, you can disable autocasting by passing autocast=False to the base Layer constructor.


Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 128)               17301632  
_________________________________________________________________
dense (Dense)                (None, 3)                 387       
=================================================================
Total params: 17,302,019
Trainable params: 387
Non-trainable params: 17,301,632
_________________________________________________________________

Train and evaluate the model

Let's train and evaluate the model to see the performance on the SciCite task

EPOCHS =   35
BATCH_SIZE = 32

history = model.fit(train_data.shuffle(10000).batch(BATCH_SIZE),
                    epochs=EPOCHS,
                    validation_data=validation_data.batch(BATCH_SIZE),
                    verbose=1)
Epoch 1/35
257/257 [==============================] - 2s 9ms/step - loss: 0.8679 - accuracy: 0.6003 - val_loss: 0.7595 - val_accuracy: 0.6954
Epoch 2/35
257/257 [==============================] - 2s 6ms/step - loss: 0.6797 - accuracy: 0.7291 - val_loss: 0.6633 - val_accuracy: 0.7314
Epoch 3/35
257/257 [==============================] - 2s 6ms/step - loss: 0.6120 - accuracy: 0.7618 - val_loss: 0.6206 - val_accuracy: 0.7566
Epoch 4/35
257/257 [==============================] - 2s 7ms/step - loss: 0.5808 - accuracy: 0.7758 - val_loss: 0.5975 - val_accuracy: 0.7576
Epoch 5/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5627 - accuracy: 0.7807 - val_loss: 0.5849 - val_accuracy: 0.7566
Epoch 6/35
257/257 [==============================] - 2s 7ms/step - loss: 0.5497 - accuracy: 0.7833 - val_loss: 0.5755 - val_accuracy: 0.7598
Epoch 7/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5430 - accuracy: 0.7866 - val_loss: 0.5709 - val_accuracy: 0.7653
Epoch 8/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5355 - accuracy: 0.7902 - val_loss: 0.5653 - val_accuracy: 0.7675
Epoch 9/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5302 - accuracy: 0.7914 - val_loss: 0.5630 - val_accuracy: 0.7740
Epoch 10/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5259 - accuracy: 0.7917 - val_loss: 0.5589 - val_accuracy: 0.7718
Epoch 11/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5254 - accuracy: 0.7948 - val_loss: 0.5584 - val_accuracy: 0.7740
Epoch 12/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5219 - accuracy: 0.7936 - val_loss: 0.5546 - val_accuracy: 0.7740
Epoch 13/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5176 - accuracy: 0.7956 - val_loss: 0.5552 - val_accuracy: 0.7740
Epoch 14/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5154 - accuracy: 0.7957 - val_loss: 0.5510 - val_accuracy: 0.7773
Epoch 15/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5141 - accuracy: 0.7967 - val_loss: 0.5533 - val_accuracy: 0.7784
Epoch 16/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5152 - accuracy: 0.7990 - val_loss: 0.5514 - val_accuracy: 0.7740
Epoch 17/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5097 - accuracy: 0.7988 - val_loss: 0.5512 - val_accuracy: 0.7806
Epoch 18/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5141 - accuracy: 0.7975 - val_loss: 0.5522 - val_accuracy: 0.7773
Epoch 19/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5086 - accuracy: 0.7967 - val_loss: 0.5504 - val_accuracy: 0.7784
Epoch 20/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5087 - accuracy: 0.7988 - val_loss: 0.5466 - val_accuracy: 0.7795
Epoch 21/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5064 - accuracy: 0.7994 - val_loss: 0.5470 - val_accuracy: 0.7795
Epoch 22/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5066 - accuracy: 0.7995 - val_loss: 0.5486 - val_accuracy: 0.7795
Epoch 23/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5071 - accuracy: 0.8000 - val_loss: 0.5475 - val_accuracy: 0.7817
Epoch 24/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5046 - accuracy: 0.7991 - val_loss: 0.5452 - val_accuracy: 0.7817
Epoch 25/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5025 - accuracy: 0.7995 - val_loss: 0.5454 - val_accuracy: 0.7849
Epoch 26/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5031 - accuracy: 0.7999 - val_loss: 0.5449 - val_accuracy: 0.7817
Epoch 27/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5029 - accuracy: 0.8021 - val_loss: 0.5466 - val_accuracy: 0.7860
Epoch 28/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5005 - accuracy: 0.8006 - val_loss: 0.5467 - val_accuracy: 0.7828
Epoch 29/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5017 - accuracy: 0.8003 - val_loss: 0.5447 - val_accuracy: 0.7860
Epoch 30/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5003 - accuracy: 0.8013 - val_loss: 0.5459 - val_accuracy: 0.7817
Epoch 31/35
257/257 [==============================] - 2s 6ms/step - loss: 0.4991 - accuracy: 0.8021 - val_loss: 0.5469 - val_accuracy: 0.7882
Epoch 32/35
257/257 [==============================] - 2s 6ms/step - loss: 0.4998 - accuracy: 0.8022 - val_loss: 0.5453 - val_accuracy: 0.7860
Epoch 33/35
257/257 [==============================] - 2s 6ms/step - loss: 0.4980 - accuracy: 0.8008 - val_loss: 0.5452 - val_accuracy: 0.7860
Epoch 34/35
257/257 [==============================] - 2s 6ms/step - loss: 0.5005 - accuracy: 0.8033 - val_loss: 0.5468 - val_accuracy: 0.7871
Epoch 35/35
257/257 [==============================] - 2s 6ms/step - loss: 0.4984 - accuracy: 0.8022 - val_loss: 0.5446 - val_accuracy: 0.7882

from matplotlib import pyplot as plt
def display_training_curves(training, validation, title, subplot):
  if subplot%10==1: # set up the subplots on the first call
    plt.subplots(figsize=(10,10), facecolor='#F0F0F0')
    plt.tight_layout()
  ax = plt.subplot(subplot)
  ax.set_facecolor('#F8F8F8')
  ax.plot(training)
  ax.plot(validation)
  ax.set_title('model '+ title)
  ax.set_ylabel(title)
  ax.set_xlabel('epoch')
  ax.legend(['train', 'valid.'])
display_training_curves(history.history['accuracy'], history.history['val_accuracy'], 'accuracy', 211)
display_training_curves(history.history['loss'], history.history['val_loss'], 'loss', 212)

png

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.batch(512), verbose=2)

for name, value in zip(model.metrics_names, results):
  print('%s: %.3f' % (name, value))
loss: 0.533
accuracy: 0.788

We can see that the loss quickly decreases while especially the accuracy rapidly increases. Let's plot some examples to check how the prediction relates to the true labels:

prediction_dataset = next(iter(test_data.batch(20)))

prediction_texts = [ex.numpy().decode('utf8') for ex in prediction_dataset[0]]
prediction_labels = [label2str(x) for x in prediction_dataset[1]]

predictions = [label2str(x) for x in model.predict_classes(prediction_texts)]


pd.DataFrame({
    TEXT_FEATURE_NAME: prediction_texts,
    LABEL_NAME: prediction_labels,
    'prediction': predictions
})

We can see that for this random sample, the model predicts the correct label most of the times, indicating that it can embed scientific sentences pretty well.

What's next?

Now that you've gotten to know a bit more about the CORD-19 Swivel embeddings from TF-Hub, we encourage you to participate in the CORD-19 Kaggle competition to contribute to gaining scientific insights from COVID-19 related academic texts.