Interpreting NLP Transformers
local graph
Chapter 8 — Interpreting NLP Transformers
Section titled “Chapter 8 — Interpreting NLP Transformers”In the last chapter, we learned about applying explanation methods to a specific type of deep learning model architecture, convolutional neural networks. In this chapter, we will provide some tools to do the same with the transformer model architecture. Transformer models are becoming increasingly popular, and their most common use case is Natural Language Processing (NLP). We broached the subject of NLP in Chapter 5, Local Model-Agnostic Interpretation Methods. In this chapter, we will do so too but with transformer-specific methods and tools. First, we will discuss how to visualize attention mechanisms, followed by interpreting integrated gradient attributions, and lastly, exploring the Swiss Army knife that is the Learning Interpretability Tool (LIT).
These are the main topics we will cover:
- Visualizing attention with BertViz
- Interpreting token attributions with integrated gradients
- LIME, counterfactuals, and other possibilities with the LIT
Technical requirements
Section titled “Technical requirements”This chapter’s example uses the mldatasets, pandas, numpy , torch, transformers , bertviz, captum, and lit-nlp libraries. Instructions on how to install all these libraries are in the Preface.
The code for this chapter is located here: https://packt.link/Yzf2L
The mission
Section titled “The mission”You are a data scientist working for a yet-to-launch startup in New York City. This startup aims to establish itself as the go-to place to find the best, newest, and most exciting culinary destinations in the city!
The aim is to move beyond the typical structured data about restaurants and delve deep into the vast array of textual data available online, from social media sites to directory websites. The startup believes that while ratings might provide a simplistic quantification of experiences, reviews contain richer details and can offer multidimensional insights into what makes a restaurant special.
Reviews express detailed sentiments that capture diverse user experiences, unlike ratings, which provide a singular, non-comparative perspective. By harnessing the granularity present in reviews, the startup can tailor its recommendations to cater to various audience segments with greater precision.
Your team has been discussing how to leverage sentiment analysis on reviews to determine how to best look for the feelings that exemplify the experience users look for in the recommender system. Binary sentiment analysis (positive/negative) does not offer the nuances required to distinguish between usual and unique experiences, or those catering to specific groups such as travelers, families, or couples. Also, the startup founders believe that the dining experience is multifaceted. An experience that might be seen as “positive” could range from “comforting and nostalgic” to “thrilling and adventurous.” Distinguishing these nuances will empower the recommender system to be more personalized and effective.
Your manager encountered a sentiment classification model that has 27 categories trained with a dataset called GoEmotions, published by Google. GoEmotions offers a more detailed classification of sentiments, capturing the richness of human emotions more effectively than binary classification models. However, the lead strategist decided there were too many classifications and decided to group them into a different emotion taxonomy called Ekman (see Figure 8.1):

Figure 8.1: The Taxonomy of Emotions
Ekman’s taxonomy of emotions is a classification system developed by psychologist Paul Ekman, which identifies six basic emotions that he believed to be universally experienced in all human cultures. These six emotions are joy, sadness, fear, anger, disgust, and surprise. Ekman suggested that these are fundamental emotions that are hard-wired into our brains and expressed in the same way by people all around the world, regardless of their culture. These emotions can be identified through specific facial expressions, and understanding them can help in fields like psychology, communication, and sociology. Ekman’s taxonomy offers a more concise set of emotion categories while still preserving the nuances. This makes the interpretation more manageable and actionable for the development team and other stakeholders. However, we’ve had to keep neutral, which cannot be classified into any Ekman category.
Now, the next step is to interpret the GoEmotions Ekman classifier model with the Tripadvisor review dataset to understand what the model learned and uncover patterns that could be useful to the development of the recommender system. It’s an open-ended task. The general goal is to understand the patterns the model has identified in the reviews and how these correlate with Ekman’s categories. However, this path could lead to many findings or a dead-end. Leadership stressed that data scientists, like yourself, would have to use their judgment to find opportunities in data exploration and model interpretation.
By uncovering these patterns, the startup can fine-tune its algorithm to look for reviews that resonate with these emotions. The insights can also guide restaurant partnerships, marketing strategies, and feature enhancements to the platform.
The approach
Section titled “The approach”You have decided to take a three-prong approach:
- You will look under the hood of the transformer model to visualize attention weights with BertViz to find relevant patterns in those mechanisms.
- Then, you’ll produce saliency maps where attributions are color-coded for each token in reviews of interest, using the integrated gradients method.
- Lastly, you’ll examine counterfactuals with the LIT.
You hope that you can deliver some actionable insights to the leadership team with these steps.
The preparations
Section titled “The preparations”You will find the code for this example here: https://github.com/PacktPublishing/Interpretable-Machine-Learning-with-Python-2E/tree/master/08/ReviewSentiment.ipynb
Loading the libraries
Section titled “Loading the libraries”To run this example, you need to install the following libraries:
mldatasetsto load the datasetpandasandnumpyto manipulate ittorch(PyTorch) andtransformersto load and configure the modelbertviz,captum, andlit-nlpto generate and visualize the model interpretations
You should load all of them first:
import mathimport os, random, re, gcimport warningswarnings.filterwarnings("ignore")import mldatasetsimport numpy as npimport pandas as pdimport torchfrom transformers import AutoTokenizer,\ AutoModelForSequenceClassification, pipelinefrom bertviz import head_view, model_viewfrom captum.attr import LayerIntegratedGradients,\ TokenReferenceBase, visualizationfrom lit_nlp import notebookfrom lit_nlp.api import dataset as lit_datasetfrom lit_nlp.api import model as lit_modelfrom lit_nlp.api import types as lit_typesNext, we work on data understanding and preparations.
Understanding and preparing the data
Section titled “Understanding and preparing the data”We load the data like this into a DataFrame we call reviews_df:
reviews_df = mldatasets.load("nyc-reviews", prepare=True)There should be over 380,000 records and 12 columns. We can verify this is the case with info():
reviews_df.info()The output checks out. There are no missing values. However, there are only three numeric features, one date, and all the rest are object data types because they are mostly text. Given that this chapter focuses on NLP, this shouldn’t come as a surprise. Let’s examine the data dictionary to understand what we will use from this DataFrame.
The data dictionary
Section titled “The data dictionary”These are the 12 columns in the DataFrame, most of which are there for reference:
review_id: ID – a unique identifier for the review (only for reference)author_id: ID – a unique identifier for the author (only for reference)restaurant_name: text – the name of the restaurant (only for reference)url_restaurant: URL – Uniform Resource Identifier to locate the web page where the restaurant review is located (only for reference)review_date: date – the date when the review was made (only for reference)review_title: text – the title the author wrote for the reviewreview_preview: text – the preview generated for the reviewreview_full: text – the full review written by the authorrating: ordinal – a rating given by the author to the establishment (a 1–5 rating scale)positive_sentiment: binary – whether the review has a positive sentiment according to a binary sentiment model (positive/negative)label: categorical – the predicted emotion by the GoEmotions classifier (according to the Ekman seven-class classification: joy, neutral, sadness, disgust, fear, anger, and surprise)score: continuous – the predicted probability that the review belongs to the predicted class
It’s a multi-class model, so it predicted scores for each class. However, we only stored the score of the most probable class (label). Therefore, the last two columns represent the output of the model. As for the input, let’s examine the first three rows to illustrate it:
reviews_df[[“review_title”,“review_full”,“label”,“score”]].head(3)
The preceding snippet will generate the output in Figure 8.2:

Figure 8.2: The first three reviews of the dataset
It’s the first two columns in Figure 8.2, review_title and review_full, that represent the input for the model. It does so as a single piece of text, so when we discuss the review, we are referring to a string that concatenates both with a colon and space, separating them like this: Disappointing: Food was mediocre at best. The lamb chops are an image they feature on the websites opening page.
But these are not the only columns that could matter in an analysis. We could, of course, analyze reviews by author, restaurant, date, and so on, and even connect restaurants to specific coordinates on a map to understand how sentiment varies geographically. This is all very interesting. However, we won’t go into any detail here because although it might be relevant to the general mission of sentiment analysis, it will divert from the technical topic of this chapter, which is interpreting transformer models.
Nonetheless, we will explore some features that are highly correlated with the model outcomes, which are the rating provided by the author and the outcome of the binary sentiment analysis model (positive_sentiment). You would definitely expect these to match because reviews are generally consistent with the ratings — that is, a positive review will have a higher rating than a negative one. Likewise, some emotions are more positive than negative.
To understand these correlations a bit better, let’s aggregate the reviews to get an average rating and positive_sentiment for each emotion like this:
sum_cols_l = ["score","positive_sentiment","rating"]summary_df = reviews_df.groupby("label")[sum_cols_l].agg( {"score":["count","mean"], "positive_sentiment":"mean", "rating":"mean"})summary_df.columns = ["count", "avg. score", "% positive", "avg. rating"]summary_df.sort_values(by="avg. rating", ascending=False).style.format( { "count":"{:,}", "avg. score":"{:.1%}", "% positive":"{:.1%}" , "avg. rating":"{:.2f}" }).bar(subset=["avg. score", "% positive", "avg. rating"],\ color="#4EF", width=60)The above code will produce the output in Figure 8.3:

Figure 8.3: A summary table of the emotions predicted for the review dataset
As you can appreciate in Figure 8.3, the majority of the 380,000 reviews are placed in the joy label or class. Joy is a positive emotion, so it makes sense that our binary sentiment classifier classified over 90% of them as positive and that the average rating for joyous reviews is nearly 4.5. The DataFrame is sorted by the average rating because it’s not a product of a model (which could be wrong), so it can perhaps give us the clearest indication of what predicted emotions the end users perceive to be the most positive. And as you go down in the list, you have positive emotions first, followed by neutral, and then the negative ones. Please note that the percentage of reviews that was deemed to be positive by the binary classifier is somewhat consistent with the same order provided by the average rating.
On the other hand, the average score for each label tells us how confident the predictions are on average that it belongs to said label. Joy, sadness, and surprise are the most confident. Since the multi-class predictions are seven numbers that add up to 1, an average score of 56.6% for anger is an indication that many predictions in which anger is the most probable emotion will have other emotions with a sizable probability – perhaps even emotions that may seem incompatible. We will put a pin on this because it would be interesting to explore this later.
Another fascinating interpretation you can make of Figure 8.3 is that a large proportion of surprise is negative, despite it being supposedly perceived to be a positive emotion. Also, with an average rating lower than 4, there are probably quite a few negative ratings weighing them down. We won’t explore the data in this chapter, but indeed, there are plenty of negative reviews that embody a sentiment of surprise. In light of this finding and for the sake of adapting to the mission, let’s say you presented this to your bosses, and they decided it made sense to focus on surprise because market research shows that people love to find and be surprised by “hidden gems.” Therefore, it’s critical that a recommendation engine can help unearth any restaurants that are positively surprising, while suppressing any that are consistently negatively surprising.
Loading the model
Section titled “Loading the model”Later on, we will be randomly selecting from our dataset, so in order to do that consistently, it’s best to set a random seed. It’s always good practice to initialize the seed in all the pertinent libraries, even though in this case it won’t make a difference for PyTorch inference operations:
rand = 42os.environ["PYTHONHASHSEED"]=str(rand)random.seed(rand)np.random.seed(rand)torch.manual_seed(rand)Next, let’s define a device variable because if you have a CUDA-enabled GPU, model inference will perform quicker. Then, we will load the tokenizer (goemotions_tok) and model (goemotions_mdl) from Hugging Face using the from_pretrained function. Lastly, we will move all the weights and biases to your device with the model.to(device) function and set the model to evaluation mode with model.eval():
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")goemotions_mdl_path = "monologg/bert-base-cased-goemotions-ekman"goemotions_tok = AutoTokenizer.from_pretrained(goemotions_mdl_path)goemotions_mdl = AutoModelForSequenceClassification.from_pretrained( goemotions_mdl_path, output_attentions=True)goemotions_mdl.to(device)goemotions_mdl.eval()Once the model is loaded, we always inspect its architecture with print(goemotions_mdl). However, architecturally, in broad terms, what may matter most when interpreting transformer models is how many layers and attention heads they have. We can inspect that easily with the following snippet:
num_layers = goemotions_mdl.config.num_hidden_layersnum_attention_heads = goemotions_mdl.config.num_attention_headsprint(f"The model has {num_layers} layers.")print(f"Each layer has {num_attention_heads} attention heads.")It should say that there are 12 layers and 12 attention heads. In the next section, we will dive into understanding how the attention mechanism works, and how to visualize the layers and heads with BertViz.
Visualizing attention with BertViz
Section titled “Visualizing attention with BertViz”What is attention? Let’s imagine you’re reading a book and come across a sentence that mentions a character you’ve read about earlier, but you’ve forgotten some details about them. Instead of going back and reading everything from the start, you’d likely skim through previous pages, focusing specifically on on the parts that talk about this character. Your mind gives “attention” to the relevant information while filtering out the less relevant parts.
The attention mechanism in models like transformers works in a similar way. When processing information, it doesn’t treat all pieces of data equally. Instead, it “pays attention” to the most relevant parts, giving them more importance in the context of the current task. This ability to selectively focus on specific parts helps the model understand complex patterns and relationships in the data.
Transformers are made up of two main components: the encoder and the decoder. Each component leverages attention mechanisms, but they do so differently:
Encoder: The encoder’s job is to understand the input data. It does this by using an attention mechanism to figure out how each part of the input (like a word in a sentence) relates to all other parts. This allows the encoder to create a rich representation of the input that captures the relationships and context within it. It’s like reading a sentence and understanding what each word means in the context of that sentence.
Decoder: Once the encoder has created this representation, the decoder uses it to produce the output. The decoder also uses an attention mechanism, but it uses it in two ways. First, it pays attention to the encoder’s representation to understand what the input was. Second, it pays attention to its own previous outputs to make sure the current output is consistent with what it has produced so far. It’s like writing a sentence that makes sense based on what you read and what you’ve already written.
However, not all transformer models have both components. In essence, the use case determines which parts of the transformer are needed:
Encoder models (like BERT): These models only use the encoder component of the transformer. They are typically used for tasks that involve understanding the input data, like sentiment analysis (determining whether a text is positive or negative), named entity recognition (identifying people, organizations, and locations in text), or other classification tasks. This is because the encoder’s job is to create a representation of the input data that captures the relationships and context within it.
Decoder models (like GPT, LLaMa, etc.): These are used for tasks that involve generating new data, like text generation. The decoder part of the transformer ensures the generated output is consistent with what has been produced so far.
Encoder-decoder models (like FLAN): These are used for tasks that involve transforming one piece of data into another, like translation. The encoder understands the input, and the decoder generates the output.
Now that we have covered attention models, let’s dive into BERT.
BERT, which stands for Bidirectional Encoder Representations from Transformers, is a type of transformer model developed by Google. It’s used to understand and analyze text data in a wide variety of languages. BERT is a transformer model that reads text bidirectionally to understand the context of words better. It only uses the encoder part of the transformer because its job is to understand text, not generate it. This makes BERT very effective for a wide range of tasks that involve understanding text.
So, our BERT transformer model has 12 layers and 12 attention heads. But what do these do, and how do they work?
BERT layers: The 12 hidden layers are BERT layers, and these are a stack of other layers that make up this encoder transformer. Much like with convolutional layers in a CNN, like the one we examined in Chapter 7, Visualizing Convolutional Neural Networks, BERT layers represent layers of abstraction. As the input data progresses through layers, the model learns increasingly abstract representations of the data. In the context of text, the lower layers might capture basic syntactic information, like the role of a word in a sentence. As you move up through the layers, they tend to capture higher-level semantics, such as overall sentence meaning or themes. The number of layers, called the depth of the model, often correlates with its ability to understand context and represent complex relationships. However, more layers also require more computational resources and might be more prone to overfitting if not enough data is available.
Attention head: The self-attention mechanism is the heart of any transformer model. The attention head has several self-attention mechanisms working in parallel. Inside the multi-head self-attention mechanism, there are multiple independent attention heads working in parallel. Each attention head learns to focus on different parts of the input data (like different relationships between tokens, which are usually the words). Having multiple attention heads allows the model to capture various types of relationships simultaneously. For example, one head might focus on the relationship between adjectives and nouns, while another might capture verb-subject relationships. After each head computes its own attention-weighted value representation, the outputs from all heads are concatenated and linearly transformed to produce the final value representation for the next layer.
Let’s use some real reviews to examine the inner workings of the GoEmotions model. To that end, we will take four sample reviews and print out their details using the following code. While we are at it, we will save the sample reviews in a dictionary (sample_reviews_dict) so we can reference them later:
surprise_sample_reviews_l = [174067, 284154, 480395, 47659]line_pattern = r"(?<=[.!?])\s+"sample_reviews_dict = {}for i, review_idx in enumerate(surprise_sample_reviews_l): review_s = reviews_df.loc[review_idx, :] sentiment = "Positive" if review_s["positive_sentiment"]\ else "Negative" review_lines_l = re.split( line_pattern, review_s["review_full"], maxsplit=1 ) review_txt = "\r\n\t\t".join(review_lines_l) print(f"{review_s["restaurant_name"]}") print(f"\tSentiment:\t\t{sentiment}") print(f"\tRating:\t\t\t{review_s["rating"]}") print(f"\tGoEmotions Label:\t{review_s["label"]}") print(f"\tGoEmotions Score:\t{review_s["score"]:.1%}") print(f"\tTitle:\t{review_s["review_title"]}") print(f"\tReview:\t {review_txt}") sample_reviews_dict[i] = review_lines_lThe preceding snippet should output the text in Figure 8.4:

Figure 8.4: A few sample surprise reviews in the dataset As you can see in Figure 8.4, the commonality between all the review samples is surprise, both negative and positive.
Next, we will leverage BertViz, which, despite the name, can visualize attention for encoder-only transformer models (like BERT and all variants), decoder-only transformers (like GPT and all variants), and encoder-decoder transformers (like T5). It’s very flexible, but it’s important to note that it’s an interactive tool, so the print screens represented by the figures in this section won’t do it justice.
Next, we will create a function that, with the tokenizer, model, and a tuple of sentences, can create two different kinds of BertViz visualizations:
def view_attention(tokenizer, model, sentences, view="model"): sentence_a, sentence_b = sentences # Encode sentences with tokenizer inputs = tokenizer.encode_plus( sentence_a, sentence_b, return_tensors="pt" ) # Extract components from inputs input_ids = inputs["input_ids"] token_type_ids = inputs["token_type_ids"] # Get attention weights from model given the inputs attention = model(input_ids, token_type_ids=token_type_ids)[-1] # Get 2nd sentence start and tokens sentence_b_start = token_type_ids[0].tolist().index(1) input_id_list = input_ids[0].tolist() tokens = tokenizer.convert_ids_to_tokens(input_id_list) # BertViz visualizers if view=="head": head_view(attention, tokens, sentence_b_start) elif view=="model": model_view(attention, tokens, sentence_b_start)To visualize attention, we will need to take a pair of input sentences and encode them with our tokenizer (inputs). Then, we extract the token IDs for these inputs (input_ids) and values, which indicate what sentence each token belongs to (token_type_ids) – in other words, 0 for the first sentence and 1 for the second sentence. We then pass the inputs (input_ids and token_type_ids) to the model and extract the attention weights. Finally, there are two BertViz visualizers, head_view and model_view, and for them to work, all we need is the attention weights produced by our inputs, the token IDs converted to tokens, and the position for when the second sentence begins (sentence_b_start).
Next, we will visualize attention throughout the model with the model view.
Plotting all attention with the model view
The following snippet will produce a model view for the sentences in the 1st sample review:
view_attention( goemotions_tok, goemotions_mdl, sample_reviews_dict[0], view="model")The preceding lines of code create a large plot, like the one portrayed in Figure 8.5:

Figure 8.5: The model view for the 1st sample review for 2nd Avenue Deli Figure 8.5 is a 12 x 12 grid with every attention head in the BERT model. We can click on any attention head to see both sentences in the BERT input, with lines drawn between them to represent the attention weights from one token (left) to another (right). We can select “Sentence A -> Sentence A”, “Sentence A -> Sentence B,” and every combination in between to view only a subset of all the attention weights. Lines for weights closest to one appear as very opaque, while weights close to zero show as transparent to the point of not being visible at all.
At a glance, we can tell that some attention heads have more lines, thicker lines, or lines that seem to go more in one direction than another. We can click on individual attention heads to examine them individually – for instance:
Layer 1 Head 11 is mostly attention, moving forward from one token to the following token in the same sentence. This is a very common pattern and makes complete logical sense because we read English left to right and understand it mostly in that order, although there are, of course, other patterns that are undoubtedly in the attention heads. We also see evidence of another common pattern, which is one or several tokens with attention weights toward the [CLS] token. The [CLS] token is a special token that is prepended to every input sequence when using BERT-like models for classification tasks. It’s often used to get the aggregate representation of the entire sequence for classification. This means that for this particular attention head, the token serves a purpose in the classification decision. This can be especially insightful when trying to understand which words in a sequence the model deems critical for classification decisions. When attention goes from a separator token [SEP] to the classification token [CLS], it could be seen as the model recognizing the end of a context or sentence and reflecting its semantic conclusion, to perhaps influence the classification decision.
Layer 9 Head seems to perform a more complicated task, which is to relate words to “great” and “surprised,” even across sentences. This is another common pattern where connecting words predict a word.
Take note of patterns in the attention heads, and notice a few others, like attention moving backward in a sentence, or connecting synonyms. Then, change the zero in sample_reviews_dict[0] to one, two, or three to see if the attention heads show the same pattern. The samples are quite different, but if the attention heads are not doing the same thing, chances are they are doing something remarkably similar. However, for the bigger picture, it’s probably best to squint your eyes and see what kind of patterns are evident across different layers.
Next, we will make this task easier with the head view.
Diving into layer attention with the head view
We can start by choosing the first sample with the following code:
view_attention( goemotions_tok, goemotions_mdl, sample_reviews_dict[0], view="head")We can select any of the 12 layers (0–11). Line transparency means the same thing it did with the model view. However, the difference is we can isolate individual token attention weights by clicking on them, so when we select any token on the left, we’ll see lines connect with tokens on the right. Also, color-coded boxes will appear on the right, representing how much attention weight is in each of the 12 attention heads.
And if we happen to select any token on the right, we’ll get all the attention that is directed to it from the left tokens. In Figure 8.6, we can see examples of how several of the sample sentences would appear:

Figure 8.6: The head view for samples 1, 2, and 4 In Figure 8.6, see how we can drill down on patterns just as we did with model view. For instance, we can examine different patterns of attention, from related words that are next to each other (“great sandwich” and “albeit quite expensive”) to those that have a relationship only in the context of the sentence (“sandwich” and “expensive”), or even across sentences (“bad” and “ignored,” “chef,” and “menu”).
By doing this, we can realize that visualizing attention heads is not just for curiosity’s sake but can also help us understand how a model connects the dots between words, thus accomplishing a downstream task like classification. Perhaps this can help us understand what to do next, whether it’s to fine-tune the model further with underrepresented words and situations, or prepare the data differently to stop the model from getting confused by a particular word or set of words. However, given the complexity of attention heads finding model issues, this can be like looking for a needle in a haystack. We only started with layers and attention heads in this chapter because it provides an intuitive way of understanding how transformers encode relationships between tokens.
A better way to start would be with attributions. An attribution method is a method that will compute how much a part of an input contributed to a model’s prediction for that input. In the case of images in Chapter 7, Visualizing Convolutional Neural Networks, the part of the input we compute attributions for is pixels. For text, the equivalent would be tokens, which in this case are made up of (mostly) words, so next, we will generate token attributions.
Interpreting token attributions with integrated gradients
Integrated gradients is a popular method, and in Chapter 7, we explained and leveraged it to produce attributions for each pixel in an image. The method has the same steps:
Choose a baseline input: The baseline represents no information. For images, it is usually a solid black image. For text, this could be a sentence with all words replaced by a placeholder like [PAD] or just an empty sentence.
Gradually change this baseline input into your actual input sentence (e.g., the review), step by step. At each step, you change a little bit of the baseline toward the actual input.
Compute output changes: For each step, calculate how much the model’s prediction changes.
Sum up all these changes for each word in the sentence. This gives you a score for each word, indicating how much it contributed to the model’s final prediction.
However, before we can use integrated gradients, it’s best that we define a transformer pipeline that tokenizes the input and performs inference on the model in one step:
goemotions = pipeline( model=goemotions_mdl, tokenizer=goemotions_tok, task="text-classification", function_to_apply="softmax", device=device, top_k=None)You can test the goemotions pipeline like this:
goemotions(["this restaurant was unexpectedly disgusting!", "this restaurant was shockingly amazing!"])It should output the following list of lists of dictionaries:
[[{"label": "disgust", "score": 0.961812436580658}, {"label": "surprise", "score": 0.022211072966456413}, {"label": "sadness", "score": 0.004870257806032896}, {"label": "anger", "score": 0.0034139526542276144}, {"label": "joy", "score": 0.003016095608472824}, {"label": "fear", "score": 0.0027414397336542606}, {"label": "neutral", "score": 0.0019347501220181584}], [{"label": "joy", "score": 0.6631762385368347}, {"label": "surprise", "score": 0.3326122760772705}, {"label": "neutral", "score": 0.001732577453367412}, {"label": "anger", "score": 0.0011324150254949927}, {"label": "sadness", "score": 0.0010195496724918485}, {"label": "fear", "score": 0.00021178492170292884}, {"label": "disgust", "score": 0.00011514205834828317}]]As you can see, in the first list, there are two predictions (one for each text), and each prediction has a list with seven dictionaries, with one that has the score for each class. Since the dictionaries are sorted from the highest score to the lowest, you can tell that the first restaurant review was mostly predicted as disgust and the second as joy at 66%, but there was also a sizable amount of surprise.
Next, we will create a function that can take any DataFrame row with our review and our transformer, and generate and output attributions for every prediction with over 10% probability:
def visualize_ig_review(interpret_s:pd.Series, pline:pipeline, max_prob_thresh:float=0.1, max_classes=np.PINF, concat_title=True, summary_df=None) -> pd.DataFrame: print(f"{interpret_s.name}: {interpret_s['restaurant_name']}") # Init some variables if concat_title: text = interpret_s["review_title"] + ":" + interpret_s["review_full"] else: text = interpret_s["review_full"] true_label = "Positive" if interpret_s["positive_sentiment"]\ else "Negative" rating = interpret_s["rating"] # Get predictions prediction = pline(text)[0] prediction_df = pd.DataFrame(prediction) if summary_df is not None: prediction_df["label_avg_rating"] = prediction_df.label.\ replace(summary_df["avg. rating"].to_dict()) prediction_df = prediction_df.sort_values("label_avg_rating",\ ascending=False).reset_index(drop=True) # Process predictions prediction_tuples = [(p["label"], p["score"]) for p in prediction] sorted_prediction_tuples = sorted(prediction_tuples,\ key=lambda x: x[1], reverse=True) pred_class, pred_prob = sorted_prediction_tuples[0] # Initialize Integrated Gradients forward_func = lambda inputs, position=0: pline.model( inputs, attention_mask=torch.ones_like(inputs) )[position] layer = getattr(pline.model, "bert").embeddings lig = LayerIntegratedGradients(forward_func, layer) # Prepare tokens and baseline device = torch.device("cuda:0" if torch.cuda.is_available()\ else "cpu") inputs = torch.tensor(pline.tokenizer.encode(text,\ add_special_tokens=False), device = device).unsqueeze(0) tokens = pline.tokenizer.convert_ids_to_tokens( inputs.detach().numpy()[0] ) sequence_len = inputs.shape[1] baseline = torch.tensor( [pline.tokenizer.cls_token_id]\ + [pline.tokenizer.pad_token_id] * (sequence_len - 2)\ + [pline.tokenizer.sep_token_id],\ device=device ).unsqueeze(0) # Iterate over every prediction vis_record_l = [] for i, (attr_class, attr_score) in\ enumerate(sorted_prediction_tuples): if (attr_score > max_prob_thresh) and (i < max_classes): # Sets the target class target = pline.model.config.label2id[attr_class] # Get attributions with torch.no_grad(): attributes, delta = lig.attribute( inputs=inputs, baselines=baseline, target=target, return_convergence_delta = True ) # Post-processing attributions attr = attributes.sum(dim=2).squeeze(0) attr = attr / torch.norm(attr) attr = attr.cpu().detach().numpy() # Generate & Append Visualization Data Record vis_record = visualization.VisualizationDataRecord( word_attributions=attr, pred_prob=pred_prob, pred_class=pred_class, true_class=f"{true_label} ({rating})", attr_class=attr_class, attr_score=attr_score, raw_input_ids=tokens, convergence_score=delta ) vis_record_l.append(vis_record) # Display list of visualization data records _ = visualization.visualize_text(vis_record_l) return prediction_dfIt may seem complicated by the amount of code, but there are plenty of steps that are relatively straightforward when explained individually. We will start with model inference and work our way down:
Get predictions: This is a very straightforward step. It just feeds the text into the pipeline (pline). It takes only the first item returned ([0]) because it only anticipates one prediction being inputted and, thus, returned by the pipeline. The next few lines show what the model does if the function receives a sample_df, which it only really needs to sort the predictions in the order of the best rating on average.
Process predictions: Here, the code makes sure predictions are sorted and in tuples for easier iteration in the for loop that follows later.
Initialize integrated gradients: A forward function is defined, which takes inputs and returns the model’s output for a given position, as well as a layer for which the attributions will be calculated, which in this case is the embedding layer. Then, an instance of LayerIntegratedGradients (lig) is initialized with the forward function and the specified layer.
Prepare tokens and baseline: First, the text is tokenized and converted into a tensor, which is then moved to the specified device. Then, the token IDs are converted back to tokens for potential visualization or analysis. A baseline is created for the integrated gradients method. It consists of [CLS][ token at the start, ]{custom-style=“P - Code”}[SEP][ token at the end, and ]{custom-style=“P - Code”}[PAD][ tokens in the middle matching the length of the input ]{custom-style=“P - Code”}text.
Iterate over every prediction: Here’s the for loop that iterates over every prediction as long as the probability is over 10%, as defined by max_prob_threshold. Within the for loop, we:
Set the target class: Integrated gradients is a directed attribution method, so we need to know what target class to generate attributions for; therefore, we need the ID that was used internally by the model for the predicted class. 2. Get the attributions: Using the very same Captum attribute method we used in Chapter 7, we generate the IG attributions for the tokenized version of our text (inputs), the baselines, the target, and decide whether to return a delta (a measure of approximation error) of the IG method (return_convergence_delta). 3. Post-process the attributions: the attributions returned by the IG method are of the shape (num_inputs, sequence_length, embedding_dim), where embedding_dim=768 for this model, sequence_length corresponds to the number of tokens in the input, and num_inputs=1 because we only perform one attribution at a time. So each token’s embedding has an attribution score, but what we need is one attribution per token. Therefore, these scores are summed across the embedding dimension to get a single attribution value for each token in the sequence. Then, the attributions are normalized, ensuring that the attributions have a magnitude between 0 and 1 and are in a comparable scale. Finally, the attributions are detached from the computation graph, moved to the CPU, and converted to a numpy array for further processing or visualization. 4. Generate and append the Visualization Data Record: Captum has a method called VisualizationDataRecord, which creates a record of each attribution for visualization purposes, so what we do in this step is create these records with the attributions, deltas, tokens, and metadata related to the prediction. It then appends this data record to a list.
Display the list of Visualization Data Records: leverage visualize_text to display the list of records.
Now, let’s create some samples to perform integrated gradient attributions on:
neg_surprise_df = reviews_df[ (reviews_df["label"]=="surprise") & (reviews_df["score"]>0.9) & (reviews_df["positive_sentiment"]==0) & (reviews_df["rating"]<3)] #43neg_surprise_samp_df = neg_surprise_df.sample( n=10, random_state=rand)In the above snippet, we take all surprise reviews with a probability over 90%, but to ensure that they are negative, we will select a negative sentiment and a rating below three. Then, we will take a random sample of 10 reviews from these.
Next, we will iterate across every review in this list and generate some visualizations. A few others are shown in the screenshot in Figure 8.7:
for i in range(10): sample_to_interpret = neg_surprise_samp_df.iloc[i] _ = visualize_ig_review( sample_to_interpret, goemotions, concat_title=True, summary_df=summary_df)The preceding snippet of code will produce the visualizations in Figure 8.7:

Figure 8.7: IG visualizations for negative surprises As we can see in Figure 8.7, the surprise prediction is attributed to words like “shocked,” “realized,” and “mystery” and phrases like “not sure how.” These all make sense because they indicate that something is unknown. Naturally, there are also a few cases where the word “surprise” or “surprised” is all it takes to get a surprise prediction. However, sometimes it’s not that simple. In the last one, it’s not one word that appears to indicate surprise but many words, saying to the effect that something doesn’t add up. More specifically, these visitors from London were very surprised that a deli in New York City was so expensive. Please note that the color coding for “Negative” and “Positive” doesn’t mean that a word is negative or positive but, rather, it’s weighting against (negatively) or in favor (positively) of the attribution label.
Next, we are going to repeat code similar to what we ran to generate IG explanations for a sample of surprise negative reviews, but this time for positive reviews. To ensure that they are positive, we will use ratings above 4. This time, we will make sure to remove any reviews with the word “surprise” from the samples just to make things interesting:
pos_surprise_df = reviews_df[ (reviews_df["label"]=="surprise") & (reviews_df["score"]>0.97) & (reviews_df["positive_sentiment"]==1) & (reviews_df["rating"]>4)]pos_surprise_samp_df = pos_surprise_df[ ~pos_surprise_df["review_full"].str.contains("surprise")]for i in range(10): sample_to_interpret = pos_surprise_samp_df.iloc[i] _ = visualize_ig_review( sample_to_interpret, goemotions,\ concat_title=False, summary_df=summary_df)The preceding code will produce the visualizations in Figure 8.8.

Figure 8.8. IG visualizations for positive surprises
Figure 8.8 shows how the words “perplexed” and “unbelievable,” as well as the phrase “couldn’t believe how” indicate surprise. There are also a few cases of tokens weighing negatively against the surprise prediction. For instance, for the last restaurant, having “something for everyone” doesn’t make it very surprising. Also, you’ll note the Japanese restaurant in the middle is predicted to embody both surprise and joy emotions. It’s interesting how some words correlate with one emotion but not so much with another, and sometimes they indicate the opposite, like the “hard” in “it’s very hard to find a place” indicating surprise but not joy.
Finding reviews with mixed sentiments like the Japanese restaurant might hold some answers to why some reviews are hard to classify entirely with one sentiment. So, now, we will produce some positive and negative mixed review samples. We can easily do so by making sure that the score for the predicted label is never over 50%:
pos_mixed_samp_df = reviews_df[ (~reviews_df["label"].isin(["neutral","joy"])) & (reviews_df["score"] < 0.5) & (reviews_df["positive_sentiment"]==1) & (reviews_df["rating"]< 5)].sample(n=10, random_state=rand)neg_mixed_samp_df = reviews_df[ (~reviews_df["label"].isin(["neutral","joy"])) & (reviews_df["score"] < 0.5) & (reviews_df["positive_sentiment"]==0) & (reviews_df["rating"]>2)].sample(n=10, random_state=rand)We can generate positive mixed sentiment reviews with the following snippet. Note that this time, we use a method called mldatasets.plot_polar, which plots a polar line chart for the predictions with plotly. You’ll need both plotly and kaleido to make this work:
for i in range(10): sample_to_interpret = pos_mixed_samp_df.iloc[i] prediction_df = visualize_ig_review( sample_to_interpret,\ goemotions, concat_title=False,\ summary_df=summary_df ) rest_name = sample_to_interpret["restaurant_name"] mldatasets.plot_polar( prediction_df, "score", "label", name=rest_name)The preceding code will produce the IG visualization and polar line plot in Figure 8.9:

Figure 8.9: IG visualizations for mixed sentiment reviews Figure 8.9 portrays how this review for a sandwich shop appears to have joy, fear, and neutral emotions. The words “terrific” and “friendly” connect with joy, but they don’t with neutral. However, strangely, the word “terrific” also correlates with fear. Perhaps it has to do with the WordPiece tokenization performed on the word. Note that “terrific” appears as three subword tokens, te, ##rri, and ##fic. This probably happened because the original corpus used to train the model (the Reddit comments) didn’t have enough frequency for “terrific” to include it as a standalone word, but these subwords did. The downside to this technique is that it’s possible that the “te” and “rri” tokens are used often for words like “terrifying,” and “fic” in other scary words like “horrific” and “mortific.” On the other hand, “fic” appears in “magnificent” and “beneficial.” So what happens is that despite the contextual embeddings, the subword tokens can cause some ambiguities.
We can now run the same code as before but for neg_mixed_samp_df, to examine other examples and make our own conclusions. Next, we can expand our XAI NLP-specific toolset with the LIT.
LIME, counterfactuals, and other possibilities with the LIT The LIT is an open-source platform developed by the People+AI Research (PAIR) initiative to visualize and understand NLP models. PAIR developed the What-If Tool featured in Chapter 6, Anchors and Counterfactual Explanations.
LIT provides an interactive and visual interface to delve deep into NLP model behavior. With LIT, users can:
Identify types of examples where a model underperforms.
Determine reasons behind specific model predictions.
Test the model’s consistency under textual variations, like style, verb tense, or pronoun gender.
LIT offers various built-in capabilities, including salience maps, attention visualization, metrics calculations, and counterfactual generation. However, it also supports customization, allowing the addition of specialized interpretability techniques, visualizations, and more.
Although LIT’s primary focus is textual language data, it also supports models that operate on image and tabular data. It’s compatible with a range of machine learning frameworks, including TensorFlow and PyTorch. The tool can run both as a standalone server and within notebook environments like Colab, Jupyter, and Google Cloud Vertex AI notebooks.
In order to work with any custom dataset, LIT provides a Dataset subclass to create a LIT-compatible dataset loader. You must include an init, which loads the dataset, and a spec function, which specifies the data types returned in the dataset, while the lit_nlp.api.types provide a way to ensure that LIT recognizes each feature in your dataset. In this case, we provide the review (TextSegment), the label (CategoryLabel) with the seven labels, and two additional categories, which can be used for slicing and binning:
class GEDataset(lit_dataset.Dataset): GE_LABELS = ["anger", "disgust", "fear", "joy",\ "neutral", "sadness", "surprise"] def __init__(self, df: pd.DataFrame): self._examples = [{ "review": row["review_title"] + ":" + row["review_full"], "label": row["label"], "rating": row["rating"], "positive": row["positive_sentiment"] } for _, row in df.iterrows()] def spec(self): return { "review": lit_types.TextSegment(), "label": lit_types.CategoryLabel(vocab=self.GE_LABELS), "rating": lit_types.CategoryLabel(), "positive": lit_types.CategoryLabel() }To make LIT flexible to accommodate any model, there is a Model subclass to make a LIT-compatible model loader. It also needs the init function to initialize the model, as well as a predict_minibatch function to predict with it. To this end, we also need to create specs for both the inputs (input_spec) and outputs (output_spec) of the predict function. In this case, we enter a review (of type TextSegment) and return probabilities of type MulticlassPreds. Remember that the output of the model is not always consistent, since each prediction is arranged from the highest to the lowest score. Note that in order to make the output of predict_minibatch comply with the MulticlassPreds, we have to arrange the probabilities as a list corresponding to the labels (GE_LABELS), in the same order provided to vocab:
class GEModel(lit_model.Model): GE_LABELS = ["anger", "disgust", "fear", "joy",\ "neutral", "sadness", "surprise"] def __init__(self, model, tokenizer, **kw): self._model = pipeline( model=model, tokenizer=tokenizer, task="text-classification", function_to_apply="softmax", device=device, top_k=None ) def input_spec(self): return { "review": lit_types.TextSegment() } def output_spec(self): return { "probas": lit_types.MulticlassPreds(vocab=self.GE_LABELS,\ parent="label") } def predict_minibatch(self, inputs): examples = [d["review"] for d in inputs] with torch.no_grad(): preds = self._model(examples) preds = [{p["label"]:p["score"] for p in pred_dicts}\ for pred_dicts in preds] preds = [dict(sorted(pred_dict.items())) for pred_dict in preds] preds = [{"probas": list(pred_dict.values())} for pred_dict in preds] return predsOK, so now we have the two classes we need for LIT to function. The GoEmotions model initializer (GEModel) takes the model (goemotions_mdl) and tokenizer (goemotions_tok). We put these in a dictionary because LIT can take more than one model and more than one dataset to compare them. For the dataset, to make it load quickly, we will use 100 samples (samples100_df), made up of the four 10-sample DataFrames we have created so far, plus 60 additional random samples from the entire reviews dataset. Then, we just input our 100-sample DataFrame into the GoEmotions dataset initializer (GEDataset) and place it into our datasets dictionary as NYCRestaurants. Lastly, we create the widget (notebook.LitWidget) by inputting our model and datasets dictionaries and render it. Please note that if you want to run this outside of a notebook environment, you can use the Server command to have it run on a LIT server:
models = {"GoEmotion":GEModel(goemotions_mdl, goemotions_tok)}samples100_df = pd.concat( [ neg_surprise_samp_df, pos_surprise_samp_df, neg_mixed_samp_df, pos_mixed_samp_df, reviews_df.sample(n=60, random_state=rand) ])datasets = {"NYCRestaurants":GEDataset(samples100_df)}widget = notebook.LitWidget(models, datasets)widget.render(height=600)litserver = lit_nlp.dev_server.Server(models, datasets, port=4321)
Section titled “litserver = lit_nlp.dev_server.Server(models, datasets, port=4321)”litserver.serve()
Section titled “litserver.serve()”The above snippet will produce the interface in Figure 8.10:

Figure 8.10: Notebook view with the Predictions tab open As you can appreciate in Figure 8.10, LIT has:
A top bar with a dropdown to select the model and dataset (but you can’t here because there’s only one of each) and three different views (simple, default, and notebook). notebook is selected by default.
A selection bar to select datapoints and see which ones are pinned.
A tab bar with three tabs (Predictions, Explanations, and Analysis). By default, Predictions is selected, and this tab has Data Table to the left, where you can select and pin individual datapoints, and the Classification Results pane to the right.
Even though the notebook view has much more going on than the simple view, it lacks many features available in the default view. From now on, we will examine the default view depicted in Figure 8.11:

Figure 8.11: The default view with the Predictions tab open As you can see in Figure 8.11, the default view has two permanent panes, with the Data Table and Datapoint Editor in the top pane and the tabs in the bottom pane. It’s not a great layout for a small notebook cell, but it can let you easily pin, select, and edit datapoints while also performing tasks on them in the tabs below. Note also that there are more than three tabs. We will briefly explain each one:
Predictions: This lets you see classification results for selected and pinned datapoints. Note that it denotes the predicted label with a “P” and the ground truth with a “T.” However, since we didn’t train the model with this dataset, the label provided is no different than the one predicted, but this can prove very useful for examining misclassifications. To the right of the Classification Results, we have Scalars, which allows us to compare scores for the pinned and selected datapoints with all others in the dataset.
Explanations: Here, we can use a number of explanation/attribution methods on our datapoints, such as LIME and integrated gradients.
Salience Clustering: We perform attributions on many datapoints and cluster the results to understand how tokens are clustered. We won’t go into details here, given that we only are using a dataset of 100.
Metrics: Had we been using a training dataset with ground truth labels, this tab would be very useful because it can slice and bin performance metrics in many ways.
Counterfactuals: Much like with Chapter 6, the concept of counterfactuals is the same here, which is working out what feature (a token in this case) you can change in such a way that you modify the model outcome (the predicted label). There are several counterfactual finding methods provided.
So, we will work our way down this list, excluding Salience Clustering and Predictions (which we already explained in Figure 8.11), so next, we will take a look at Explanations, as shown in Figure 8.12:

Figure 8.12: LIME explanation compared between pinned and selected reviews in the Explanations tab Figure 8.12 shows how LIME explanations vary between the pinned and selected datapoint. LIME was previously covered in Chapter 5, Local Model-Agnostic Interpretation Methods, and in the context of NLP no less. It’s the same here. Incidentally, although there are at least four methods available, including integrated gradients, only LIME will work with this model. The reason for this is that LIME is a model-agnostic permutation-based method that doesn’t need to access any of the intrinsic parameters of the model, but the rest of the methods aren’t model-agnostic. And if you recall, our GEModel doesn’t expose any of the intrinsic parameters. If we wanted to leverage gradient-based methods like IG within LIT, we would need to not use the pipeline and then specify the input and output in such a way that token embeddings are exposed. There are some examples on the LIT website that can help you accomplish this.
Next, we will take a look at the Metrics tab, as seen in Figure 8.13:

Figure 8.13: Confusion Matrix in the Metrics tab In Figure 8.13, in the Metrics panel, there usually would be informative metrics for the entire dataset, the selection you have made, and any additional facets you may define. However, if you expand the tab, you’ll always see 100% accuracy for this dataset because there’s no ground truth. Perhaps the Confusion Matrix panel to the right is more informative in this case because we can see a cross tab between labels and rating, or labels and positive, since we defined both rating and positive as CategoryLabels. Please note that, technically, it’s not a confusion matrix because it doesn’t compare a predicted sentiment label against the corresponding true label, but you can see how much agreement there is between the predicted label and the rating.
Finally, let’s examine the Counterfactuals tab, depicted in Figure 8.14:

Figure 8.14: Generating ablation flip counterfactuals in the Counterfactuals tab The Counterfactuals tab in Figure 8.14 provides several methods to change the input in such a way that the predicted label is modified. Not all methods will work with GEModel, given how some counterfactual methods are model-agnostic and others require intrinsic parameters. Here, we use ablation flip, a model-agnostic method, to ablate (remove) tokens from the inputs. Ablation flip simply tries dropping tokens from the input to figure out which one changes the prediction. As you can see, the first one removed “Not” from “review,” and the second removed “impressed.”
With counterfactuals, you can test that the subword tokens in te ##rri ##fic (as depicted in Figure 8.9) indeed cause ambiguity when they are added and ablated in many different contexts. For instance, you can remove one token at a time from te ##rri ##fic from a review that is deemed to have a neutral or negative sentiment by the model, seeing if the prediction changes in a positive direction. You can also replace all three tokens with a synonym like “magnificent.”
Mission accomplished
It was pretty evident from the summary table (Figure 8.3), and confirmed with the integrated gradients and, to some degree, the attention visualization exercise, that many of the Ekman emotions are hard to discern from the reviews, with fear, disgust, anger, and sadness producing many mixed sentiment reviews. And these hard ones are all negative emotions.
Also, many emotions in both the GoEmotions and Ekman taxonomy don’t matter as much in the context of a recommendation engine, so it makes sense to consider consolidating some of the negative emotions and, given the ambiguity with the surprise category being sometimes positive and sometimes negative, splitting them to include curiosity and confusion.
Another important finding was that, given the many consistent patterns you found, surprise is not as hard to classify and yet a critical emotion to predict. However, there are good surprises and bad surprises. And given the right training data, a model can likely differentiate both with high precision. We can ensure that tokenization never separates words that convey emotions for the training corpus.
Summary
After reading this chapter, you should understand how to leverage BertViz to visualize transformer models, layers, and attention heads, and how to use Captum’s attribution methods, more specifically integrated gradients, and the Visualization Data Record to see what tokens are responsible for a predicted label. Finally, you should have a solid grasp of how to get started with the LIT. In the next chapter, we will look at interpreting multi-variate time-series models.
Further reading
Vig, J., 2019, A Multiscale Visualization of Attention in the Transformer Model. ArXiv: https://arxiv.org/abs/1906.05714 Kokhlikyan, N., Miglani, V., Martin, M., Wang, E., Alsallakh, B., Reynolds, J., Melnikov, A., Kliushkina, N., Araya, C., Yan, S., & Reblitz-Richardson, O., 2020, Captum: A unified and generic model interpretability library for PyTorch. ArXiv: https://arxiv.org/abs/2009.07896 Tenney, I., Wexler, J., Bastings, J., Bolukbasi, T., Coenen, A., Gehrmann, S., Jiang, E., Pushkarna, M., Radebaugh, C., Reif, E., & Yuan, A., 2020, The Language Interpretability Tool: Extensible, Interactive Visualizations and Analysis for NLP Models. Conference on Empirical Methods in Natural Language Processing: https://arxiv.org/abs/2008.05122