Text drift detection on IMDB movie reviews

Method

We detect drift on text data using both the Maximum Mean Discrepancy and Kolmogorov-Smirnov (K-S) detectors. In this example notebook we will focus on detecting covariate shift $\Delta p(x)$ as detecting predicted label distribution drift does not differ from other modalities (check K-S and MMD drift on CIFAR-10).

It becomes however a little bit more involved when we want to pick up input data drift $\Delta p(x)$. When we deal with tabular or image data, we can either directly apply the two sample hypothesis test on the input or do the test after a preprocessing step with for instance a randomly initialized encoder as proposed in Failing Loudly: An Empirical Study of Methods for Detecting Dataset Shift (they call it an Untrained AutoEncoder or UAE). It is not as straightforward when dealing with text, both in string or tokenized format as they don't directly represent the semantics of the input.

As a result, we extract (contextual) embeddings for the text and detect drift on those. This procedure has a significant impact on the type of drift we detect. Strictly speaking we are not detecting $\Delta p(x)$ anymore since the whole training procedure (objective function, training data etc) for the (pre)trained embeddings has an impact on the embeddings we extract.

The library contains functionality to leverage pre-trained embeddings from HuggingFace's transformer package but also allows you to easily use your own embeddings of choice. Both options are illustrated with examples in this notebook.

Note

As is done in this example, it is recommended to pass text data to detectors as a list of strings (List[str]). This allows for seamless integration with HuggingFace's transformers library.

One exception to the above is when custom embeddings are used. Here, it is important to ensure that the data is passed to the custom embedding model in a compatible format. In the final example, a preprocess_batch_fn is defined in order to convert list's to the np.ndarray's expected by the custom TensorFlow embedding.

Backend

The method works with both the PyTorch and TensorFlow frameworks for the statistical tests and preprocessing steps. Alibi Detect does however not install PyTorch for you. Check the PyTorch docs how to do this.

Dataset

Binary sentiment classification dataset containing $25,000$ movie reviews for training and $25,000$ for testing. Install the nlp library to fetch the dataset:

!pip install nlp
import nlp
import numpy as np
import os
import tensorflow as tf
from transformers import AutoTokenizer
from alibi_detect.cd import KSDrift, MMDDrift
from alibi_detect.saving import save_detector, load_detector

Load tokenizer

Load data

Let's take a look at respectively a negative and positive review:

We split the original test set in a reference dataset and a dataset which should not be rejected under the H0 of the statistical test. We also create imbalanced datasets and inject selected words in the reference set.

Reference, H0 and imbalanced data:

Inject words in reference data:

Preprocessing

First we need to specify the type of embedding we want to extract from the BERT model. We can extract embeddings from the ...

  • pooler_output: Last layer hidden-state of the first token of the sequence (classification token; CLS) further processed by a Linear layer and a Tanh activation function. The Linear layer weights are trained from the next sentence prediction (classification) objective during pre-training. Note: this output is usually not a good summary of the semantic content of the input, you’re often better with averaging or pooling the sequence of hidden-states for the whole input sequence.

  • last_hidden_state: Sequence of hidden states at the output of the last layer of the model, averaged over the tokens.

  • hidden_state: Hidden states of the model at the output of each layer, averaged over the tokens.

  • hidden_state_cls: See hidden_state but use the CLS token output.

If hidden_state or hidden_state_cls is used as embedding type, you also need to pass the layer numbers used to extract the embedding from. As an example we extract embeddings from the last 8 hidden states.

Let's check what an embedding looks like:

So the BERT model's embedding space used by the drift detector consists of a $768$-dimensional vector for each instance. We will therefore first apply a dimensionality reduction step with an Untrained AutoEncoder (UAE) before conducting the statistical hypothesis test. We use the embedding model as the input for the UAE which then projects the embedding on a lower dimensional space.

Let's test this again:

K-S detector

Initialize

We proceed to initialize the drift detector. From here on the detector works the same as for other modalities such as images. Please check the images example or the K-S detector documentation for more information about each of the possible parameters.

Detect drift

Let’s first check if drift occurs on a similar sample from the training set as the reference data.

Detect drift on imbalanced and perturbed datasets:

MMD TensorFlow detector

Initialize

Again check the images example or the MMD detector documentation for more information about each of the possible parameters.

Detect drift

H0:

Imbalanced data:

Perturbed data:

MMD PyTorch detector

Initialize

We can run the same detector with PyTorch backend for both the preprocessing step and MMD implementation:

Detect drift

H0:

Imbalanced data:

Perturbed data:

Train embeddings from scratch

So far we used pre-trained embeddings from a BERT model. We can however also use embeddings from a model trained from scratch. First we define and train a simple classification model consisting of an embedding and LSTM layer in TensorFlow.

Load data and train model

Load and tokenize data:

Let's check out an instance:

Define and train a simple model:

Extract the embedding layer from the trained model and combine with UAE preprocessing step:

Again, create reference, H0 and perturbed datasets. Also test against the Reuters news topic classification dataset.

Initialize detector and detect drift

H0:

Perturbed data:

The detector is not as sensitive as the Transformer-based K-S drift detector. The embeddings trained from scratch only trained on a small dataset and a simple model with cross-entropy loss function for 2 epochs. The pre-trained BERT model on the other hand captures semantics of the data better.

Sample from the Reuters dataset:

Last updated

Was this helpful?