Skip to content
ImagineWorld

Visualizing Convolutional Neural Networks

node_idnode-book_interpretable-machine-learning-with-python-second-edition_chapter-07-visualizing-convolutional-neural-networks
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleVisualizing Convolutional Neural Networks
pillar_membershipJ — architecture_design_craft
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 7 — Visualizing Convolutional Neural Networks

Section titled “Chapter 7 — Visualizing Convolutional Neural Networks”

Up to this point, we have only dealt with tabular data and, briefly, text data, in Chapter 5, Local Model-Agnostic Interpretation Methods. This chapter will exclusively explore interpretation methods that work with images and, in particular, with the Convolutional Neural Network (CNN) models that train image classifiers. Typically, deep learning models are regarded as the epitome of black box models. However, one of the benefits of a CNN is how easily it lends itself to visualization, so we can not only visualize outcomes but also every step of the learning process with activations. The possibility of interpreting these steps is rare among so-called black box models. Once we have grasped how CNNs learn, we will study how to use state-of-the-art gradient-based attribution methods, such as saliency maps and Grad-CAM to debug class attribution. Lastly, we will extend our attribution debugging know-how with perturbation-based attribution methods such as occlusion sensitivity and KernelSHAP.

These are the main topics we are going to cover:

  • Assessing the CNN classifier with traditional interpretation methods
  • Visualizing the learning process with an activation-based method
  • Evaluating misclassifications with gradient-based attribution methods
  • Understanding classifications with perturbation-based attribution methods

This chapter’s example uses the mldatasets, pandas, numpy, sklearn, tqdm, torch, torchvision, pytorch-lightning, efficientnet-pytorch, torchinfo, matplotlib, seaborn, and captum libraries. Instructions on how to install all of these libraries are in the Preface.

The code for this chapter is located here: https://packt.link/qzUvD.

Over two billion tons of waste is produced annually globally, and it’s expected to grow to over 3.5 billion tons by 2050. The alarming rise in global waste production and the need for effective waste management systems have become increasingly critical in recent years. Over half of all household trash in high-income countries is recyclable, with 20% in lower-income countries and rising. Currently, most waste ends up in landfills or incinerated, contributing to environmental pollution and climate change. This is avoidable, considering that, globally, a significant portion of all recyclable materials is not recycled.

Assuming recyclable waste is collected, it can still be hard and costly to sort it. Previously, waste classification technologies included:

  • Separating materials by size with rotating cylindrical screens with holes (“trommel screens”)
  • Separating ferrous and non-ferrous metals with magnetic forces and magnetic fields (“eddy current separators”)
  • Separating by weight with air
  • Separating by density with water (“sink-float separation”)
  • Manual sorting performed by humans

Implementing all of these techniques effectively can be challenging, even for a large, wealthy, urban municipality. To tackle this challenge, smart recycling systems have emerged, leveraging computer vision and AI to classify waste efficiently and accurately.

The development of smart recycling systems can be traced back to the early 2010s when researchers and innovators started exploring the potential of computer vision and AI to improve waste management processes. They first developed basic image recognition algorithms, utilizing features such as color, shape, and texture to identify waste materials. These systems were primarily used in research settings with limited commercial applications. As machine learning and AI became more advanced, smart recycling systems underwent significant improvements. CNNs and other deep learning techniques enabled these systems to learn from vast amounts of data and improve their waste classification accuracy. Additionally, the integration of AI-driven robotics allowed for automated sorting and handling of waste materials, increasing efficiency in recycling plants.

Costs are significantly lower than a decade ago for cameras, robots, and even chips that run deep learning models in low-latency, high-volume scenarios, making state-of-the-art smart recycling systems accessible to even smaller and poorer municipal waste management departments. One of these municipalities in Brazil is looking to revamp their 20-year-old recycling plant made up of a patchwork of machines with a collective sorting accuracy of only 70%. Human sorting can only partially compensate for the difference, leading to inevitable pollution and contamination issues. The Brazilian municipality want to replace the current system with a single conveyor belt that sorts waste efficiently from 12 different categories into bins with a series of robots.

They purchased the conveyor belt, industrial robots, and cameras. Then, they paid an AI consultancy company to develop a model to classify the recyclables. Still, they wanted models of different sizes because they weren’t sure how quickly these would run on the hardware they had.

As requested, the consultancy returned with models of various sizes between 4 and 64 million parameters. The largest model (b7) is over six times slower than the smallest one (b0). Still, the largest model has a significantly higher validation F1 score at 96% (F1 val), as opposed to approximately 90% for the smallest one:

![Chart, line chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_01.png)

Figure 7.1: F1 scores for models delivered by the AI consultancy company

The municipal leadership was delighted with the results but also surprised because the consultants asked for no domain knowledge or data to train the models, which made them very skeptical. They asked their recycling plant workers to test the models with a batch of recyclables. They got a 25% misclassification rate with that one batch.

To seek a second opinion and an honest evaluation of the model, the municipality has approached another AI consultancy firm – yours!

The first order of business was to assemble a test dataset that was more realistic of the edge cases that the recycling plant workers found among the misclassifications. Your colleague obtained F1 scores with the test dataset between 62% and 66% (F1 test). Next, they have asked you to understand what’s causing those misclassifications.

No single interpretation method is perfect, and even the best scenario can only tell you one part of the story. Therefore, you have decided to, first, assess the model’s predictive performance using traditional interpretation methods, including the following:

  • ROC curves and ROC-AUC
  • Confusion matrices and some metrics derived from them, such as accuracy, precision, recall, and F1

Then, you’ll examine the model using an activation-based method:

  • Intermediate activation

This is followed by evaluating decisions with three gradient-based methods:

  • Saliency maps
  • Grad-CAM
  • Integrated gradients

And a backpropagation-based method:

  • DeepLIFT

This is followed by three perturbation-based methods:

  • Occlusion sensitivity
  • Feature ablation
  • Shapley value sampling

I hope that you understand why the model is not performing as it should and how to fix it by the end of this process. You can also leverage the many plots and visualizations you will produce to communicate this story to the municipality’s executives.

You will find most of the code for this example here: https://github.com/PacktPublishing/Interpretable-Machine-Learning-with-Python-2E/blob/main/07/GarbageClassifier.ipynb

To run this example, you need to install the following libraries:

  • torchvision to load the dataset
  • mldatasets, pandas, numpy, and sklearn (scikit-learn) to manipulate the dataset
  • torch, pytorch-lightning, efficientnet-pytorch, and torchinfo to predict with the models and show info about the models
  • matplotlib, seaborn, cv2, tqdm, and captum to make and visualize the interpretations

You should load all of them first:

import math
import os, gc
import random
import mldatasets
import numpy as np
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
import torchvision
import torch
import pytorch_lightning as pl
import efficientnet_pytorch
from torchinfo import summary
import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable
from matplotlib.colors import LinearSegmentedColormap
import seaborn as sns
import cv2
from tqdm.notebook import tqdm
from captum import attr

Next, we will load and prepare the data.

The data used to train the model is publicly available at Kaggle (https://www.kaggle.com/datasets/mostafaabla/garbage-classification). It’s called “Garbage Classification” and is a compilation of several different online sources, including web scraping. It has already been split into training and test datasets and also comes with an additional smaller test dataset taken from Wikimedia Commons that your colleague used to test the models. These test images come in a slightly higher resolution too.

We download the data from a ZIP file like this:

dataset_file = "garbage_dataset_sample"
dataset_url = f"https://github.com/PacktPublishing/Interpretable-Machine-Learning-with-Python-2E/raw/main/datasets/{dataset_file}.zip"
torchvision.datasets.utils.download_url(dataset_url, ".")
torchvision.datasets.utils.extract_archive(f"{dataset_file}.zip",\
remove_finished=True)

It will also extract the ZIP file into four folders corresponding to the three datasets and the larger resolution test dataset. Please note that garbage_dataset_sample has only a fraction of the training and validation datasets. If you want to download the full datasets, then use dataset_file = "garbage_dataset". It won’t impact the size of the test dataset either way. Next, we can initialize the transformation and loading of the datasets like this:

X_train, norm_mean = (0.485, 0.456, 0.406)
norm_std = (0.229, 0.224, 0.225)
transform = torchvision.transforms.Compose(
[
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(norm_mean, norm_std),
]
)
train_data = torchvision.datasets.ImageFolder(
f"{dataset_file}/train", transform
)
val_data = torchvision.datasets.ImageFolder(
f"{dataset_file}/validation", transform
)
test_data = torchvision.datasets.ImageFolder(
f"{dataset_file}/test", transform
)
test_400_data = torchvision.datasets.ImageFolder(
f"{dataset_file}/test_400", transform
)

What the above code does is compose a series of standard transforms such as normalization and converting images to tensors. Then, it instantiates PyTorch datasets corresponding to each folder – that is, one for the training, validation, and test datasets, as well as the larger resolution test dataset (test_400_data). These datasets also include transforms. That way, each time an image is loaded from one of the datasets, it is automatically transformed. We can verify that the shapes of the datasets match our expectations with the following code:

print(f"# Training Samples: \t{len(train_data)}")
print(f"# Validation Samples: \t{len(val_data)}")
print(f"# Test Samples: \t{len(test_data)}")
print(f"Sample Dimension: \t{test_data[0][0].shape}")
print("="*50)
print(f"# Test 400 Samples: \t{len(test_400_data)}")
print(f"# 400 Sample Dimension:\t{test_400_data[0][0].shape}")

The preceding code outputs the number of images in each dataset and the dimensions of the images in the datasets. You can tell that there are over 3,700 training images, 900 validation images, and 120 test images of 3 x 224 x 224 dimensions. The first number corresponds to the channels (red, green, and blue) and the following two to the width and height in pixels, which is what the model uses for inference. The Test 400 dataset is the same as the Test dataset, the except images have a larger height and width. We won’t need the Test 400 dataset for inference, so it’s Okay that it doesn’t meet the model’s dimension requirements:

Sample Dimension: torch.Size([3, 224, 224])

==================================================

400 Sample Dimension: torch.Size([3, 400, 400])

Section titled “400 Sample Dimension: torch.Size([3, 400, 400])”

If you print(test_data[0]), you’ll notice that it will first output a tensor with the image and then a single integer, which we call a scalar. This integer is a number between 0 and 11, which corresponds to the labels used. For quick reference, these are the 12 labels:

labels_l = ['battery', 'biological', 'brown-glass', 'cardboard',\
'clothes', 'green-glass', 'metal', 'paper', 'plastic',\
'shoes', 'trash', 'white-glass']

Interpreting often involves taking single samples and extracting them from the dataset to later perform inference with the model. To that end, it’s important to get familiar with extracting any image from the dataset, say the very first sample from the test dataset:

tensor, label = test_400_data[0]
img = mldatasets.tensor_to_img(tensor, norm_std, norm_mean)
plt.figure(figsize=(5,5))
plt.title(labels_l[label], fontsize=16)
plt.imshow(img)
plt.show()

In the preceding snippet, we are taking the first sample (0) from the higher resolution version of the test dataset (test_400_data) and extracting the tensor and label portion from it. Then, we are using the convenience function tensor_to_img to convert the PyTorch tensor to a numpy array but also reversing the standardization that had been previously performed on the tensor. Then, we plot the image with matplotlib’s imshow and use the labels_l list to convert the label into a string, which we print in the title. The result can be seen in Figure 7.2:

![A picture containing diagram

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_02.png)

Figure 7.2: A test sample for a recyclable alkaline battery

Another preprocessing step we will need to perform is the One-Hot Encoding (OHE) of the y labels because we will need the OHE form to evaluate the model’s predictive performance. Once we initialize the OneHotEncoder, we will need to fit it to the test labels (y_test) in array format. But first, we will need to put the test labels into a list (y_test). We can do the same with the validation labels because these will also be useful for easy evaluation:

y_test = np.array([l for _, l in test_data])
y_val = np.array([l for _, l in val_data])
ohe = OneHotEncoder(sparse=False).\
fit(np.array(y_test).reshape(-1, 1))

Also, for the sake of reproducibility, always initialize your random seeds like this:

rand = 42
os.environ['PYTHONHASHSEED']=str(rand)
np.random.seed(rand)
random.seed(rand)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if device == 'cuda':
torch.cuda.manual_seed(rand)
else:
torch.manual_seed(rand)

It is acknowledged that determinism is very difficult with deep learning and is often session-, platform-, and architecture-dependent. If you are using an NVIDIA GPU, you can attempt to use PyTorch to avoid nondeterministic algorithms with the command torch.use_deterministic_algorithms(True). It’s not a guarantee, but it will throw an error when the operation that you are attempting can’t be accomplished deterministically. If it succeeds, it will be much slower. It’s only worth it if you need to make model outcomes identical – for instance, for scientific research or regulatory compliance. For further details about reproducibility and PyTorch, look here: https://pytorch.org/docs/stable/notes/randomness.html.

Now, let’s take a peek at what images are in our datasets. We know that the training and validation datasets are very similar, so we will start with the validation dataset. We can iterate every class in labels_l and randomly select a single one from the validation dataset with np.random.choice. We place each image on a 4 × 3 grid with the class label above it:

plt.subplots(figsize=(14,10))
for c, category in enumerate(labels_l):
plt.subplot(3, 4, c+1)
plt.title(labels_l[c], fontsize=12)
idx = np.random.choice(np.where(y_test==c)[0], 1)[0]
im = mldatasets.tensor_to_img(test_data[idx][0], norm_std,\
norm_mean)
plt.imshow(im, interpolation='spline16')
plt.axis("off")
plt.show()

The preceding code generates Figure 7.3. You can tell that there is significant pixelation around the edges of the items; some items appear much darker than others, and some of the pictures are from odd angles:

![Graphical user interface

Description automatically generated with medium confidence](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_03.png)

Figure 7.3: A random sample of the validation dataset

Let’s now do the same for the test dataset to compare it to the validation/training datasets. We can use the same code as before, except we replace y_val with y_test, and val_data with test_data. The resulting code generates Figure 7.4. You can tell that the test set has less pixelated and more consistently lit items, mostly from the top- and side-facing angles:

![A picture containing text, different, various

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_04.png)

Figure 7.4: A random sample of the test dataset

We won’t need to train a CNN in this chapter. Thankfully, it has been provided to us by the client.

The models trained by the other consultancy company are fine-tuned EfficientNet models. In other words, the AI consultancy company took a previously trained model with the EfficientNet architecture and trained it further with the garbage classification dataset. This technique is called transfer learning because it allows a model to utilize previously learned knowledge from a large dataset (in this case, a million images from the ImageNet database) and apply it to new tasks with smaller datasets. The advantage is it significantly reduces training time and computational resources while maintaining high performance because it has already learned to extract useful features from images, which can be a valuable starting point for a new task and only needs to adapt to the specific task at hand.

It makes sense that they chose EfficientNet. After all, EfficientNet is a family of CNNs introduced by Google AI researchers in 2019. The key innovation of EfficientNet is its compound scaling method, which enables the model to achieve higher accuracy and efficiency than other CNNs. In addition, it is based on the observation that different dimensions of the model, such as width, depth, and resolution, contribute to the overall performance in a balanced way. The EfficientNet architecture is built upon a baseline model called EfficientNet-B0. A compound scaling method is employed to create larger and more powerful versions of the baseline model, which simultaneously scales up the width, depth, and resolution of the network. This results in a series of models, EfficientNet-B1 to EfficientNet-B7, with increasing capacity and performance. The largest model, EfficientNet-B7, has achieved state-of-the-art performance on several benchmarks, such as ImageNet.

Before we can load the model, we must define the class for EfficientLite – a class that inherits from PyTorch Lightning’s pl.LightningModule. This class is designed to create a custom model based on the EfficientNet architecture, train it, and perform inference. We only need it for the latter, which is why we have also adapted it to include a predict() function – much like scikit-learn models do for the convenience of being able to use similar evaluation functions to would with these models:

class EfficientLite(pl.LightningModule):
def __init__(self, lr: float, num_class: int,\
pretrained="efficientnet-b0", *args, **kwargs):
super().__init__()
self.save_hyperparameters()
self.model = efficientnet_pytorch.EfficientNet.\
from_pretrained(pretrained)
in_features = self.model._fc.in_features
self.model._fc = torch.nn.Linear(in_features, num_class)
def forward(self, x):
return self.model(x)
def predict(self, dataset):
self.model.eval()
device = torch.device("cuda" if torch.cuda.is_available()\
else "cpu")
with torch.no_grad():
if isinstance(dataset, np.ndarray):
if len(dataset.shape) == 3:
dataset = np.expand_dims(dataset, axis=0)
dataset = [(x,0) for x in dataset]
loader = torch.utils.data.DataLoader(dataset,\
batch_size=32)
probs = None
for X_batch, _ in tqdm(loader):
X_batch = X_batch.to(device, dtype=torch.float32)
logits_batch = self.model(X_batch)
probs_batch = torch.nn.functional.softmax(logits_batch,\
dim=1).cpu().detach().numpy()
if probs is not None:
probs = np.concatenate((probs, probs_batch))
else:
probs = probs_batch
clear_gpu_cache()
return probs

You will notice that the class has three functions:

  • __init__: This is the constructor for the EfficientLite class. It initializes the model by loading a pretrained EfficientNet model using the efficientnet_pytorch.EfficientNet.from_pretrained() method. It then replaces the last fully connected layer (_fc) with a new torch.nn.Linear layer that has the same number of input features but a different number of output features equal to the number of classes (num_class).
  • forward: This method defines the forward pass of the model. It takes an input tensor x and passes it through the model, returning the output.
  • predict: This method takes a dataset and performs inference using the trained model. It first sets the model to evaluation mode (self.model.eval()). The input dataset is converted into a DataLoader object with a batch size of 32. The method iterates over the DataLoader, processing each batch of data and computing probabilities using the softmax function. The clear_gpu_cache() function is called after each iteration to release unused GPU memory. Finally, the method returns the computed probabilities as a numpy array.

If you are using a CUDA-enabled GPU, there’s a utility function called clear_gpu_cache(), which is run every time there’s a GPU-intensive operation. Depending on how powerful your GPU is, you may need to run it more often. Feel free to use another convenience function, print_gpu_mem_used(), to check how much GPU memory is utilized at any given moment or to print the entire summary with print(torch.cuda.memory_summary()). The next code downloads the pre-trained EfficientNet model, loads the model weights to EfficientLite, and prepares the model for inference. Lastly, it prints a summary:

model_weights_file = "garbage-finetuned-efficientnet-b4"
model_url = f"https://github.com/PacktPublishing/Interpretable-Machine-Learning-with-Python-2E/raw/main/models/{model_weights_file}.ckpt"
torchvision.datasets.utils.download_url(model_url, ".")
garbage_mdl = EfficientLite.load_from_checkpoint(
f"{model_weights_file}.ckpt"
)
garbage_mdl = garbage_mdl.to(device).eval()
print(summary(garbage_mdl))

The code is pretty straightforward but what’s important to note is that we are choosing the b4 model for this chapter, which is in between b0 and b7 in terms of size, speed, and accuracy. You can change the last digit according to your hardware’s abilities, but it might change some of the outcomes of this chapter’s code. The preceding snippet outputs the following summary:

=======================================================================Layer (type:depth-idx) Param # =======================================================================EfficientLite — ├─EfficientNet: 1-1 – │ └─Conv2dStaticSamePadding: 2-1 1,296 │ │ └─ZeroPad2d: 3-1 – │ └─BatchNorm2d: 2-2 96 │ └─ModuleList: 2-3 – │ │ └─MBConvBlock: 3-2 2,940 │ │ └─MBConvBlock: 3-3 1,206 │ │ └─MBConvBlock: 3-4 11,878 │ │ └─MBConvBlock: 3-5 18,120 │ │ └─MBConvBlock: 3-6 18,120 │ │ └─MBConvBlock: 3-7 18,120 │ │ └─MBConvBlock: 3-8 25,848 │ │ └─MBConvBlock: 3-9 57,246 │ │ └─MBConvBlock: 3-10 57,246 │ │ └─MBConvBlock: 3-11 57,246 │ │ └─MBConvBlock: 3-12 70,798 │ │ └─MBConvBlock: 3-13 197,820 │ │ └─MBConvBlock: 3-14 197,820 │ │ └─MBConvBlock: 3-15 197,820 │ │ └─MBConvBlock: 3-16 197,820 │ │ └─MBConvBlock: 3-17 197,820 │ │ └─MBConvBlock: 3-18 240,924 │ │ └─MBConvBlock: 3-19 413,160 │ │ └─MBConvBlock: 3-20 413,160 │ │ └─MBConvBlock: 3-21 413,160 │ │ └─MBConvBlock: 3-22 413,160 │ │ └─MBConvBlock: 3-23 413,160 │ │ └─MBConvBlock: 3-24 520,904 │ │ └─MBConvBlock: 3-25 1,159,332 │ │ └─MBConvBlock: 3-26 1,159,332 │ │ └─MBConvBlock: 3-27 1,159,332 │ │ └─MBConvBlock: 3-28 1,159,332 │ │ └─MBConvBlock: 3-29 1,159,332 │ │ └─MBConvBlock: 3-30 1,159,332 │ │ └─MBConvBlock: 3-31 1,159,332 │ │ └─MBConvBlock: 3-32 1,420,804 │ │ └─MBConvBlock: 3-33 3,049,200 │ └─Conv2dStaticSamePadding: 2-4 802,816 │ │ └─Identity: 3-34 – │ └─BatchNorm2d: 2-5 3,584 │ └─AdaptiveAvgPool2d: 2-6 – │ └─Dropout: 2-7 – │ └─Linear: 2-8 21,516 │ └─MemoryEfficientSwish: 2-9

Section titled “=======================================================================Layer (type:depth-idx) Param # =======================================================================EfficientLite — ├─EfficientNet: 1-1 – │ └─Conv2dStaticSamePadding: 2-1 1,296 │ │ └─ZeroPad2d: 3-1 – │ └─BatchNorm2d: 2-2 96 │ └─ModuleList: 2-3 – │ │ └─MBConvBlock: 3-2 2,940 │ │ └─MBConvBlock: 3-3 1,206 │ │ └─MBConvBlock: 3-4 11,878 │ │ └─MBConvBlock: 3-5 18,120 │ │ └─MBConvBlock: 3-6 18,120 │ │ └─MBConvBlock: 3-7 18,120 │ │ └─MBConvBlock: 3-8 25,848 │ │ └─MBConvBlock: 3-9 57,246 │ │ └─MBConvBlock: 3-10 57,246 │ │ └─MBConvBlock: 3-11 57,246 │ │ └─MBConvBlock: 3-12 70,798 │ │ └─MBConvBlock: 3-13 197,820 │ │ └─MBConvBlock: 3-14 197,820 │ │ └─MBConvBlock: 3-15 197,820 │ │ └─MBConvBlock: 3-16 197,820 │ │ └─MBConvBlock: 3-17 197,820 │ │ └─MBConvBlock: 3-18 240,924 │ │ └─MBConvBlock: 3-19 413,160 │ │ └─MBConvBlock: 3-20 413,160 │ │ └─MBConvBlock: 3-21 413,160 │ │ └─MBConvBlock: 3-22 413,160 │ │ └─MBConvBlock: 3-23 413,160 │ │ └─MBConvBlock: 3-24 520,904 │ │ └─MBConvBlock: 3-25 1,159,332 │ │ └─MBConvBlock: 3-26 1,159,332 │ │ └─MBConvBlock: 3-27 1,159,332 │ │ └─MBConvBlock: 3-28 1,159,332 │ │ └─MBConvBlock: 3-29 1,159,332 │ │ └─MBConvBlock: 3-30 1,159,332 │ │ └─MBConvBlock: 3-31 1,159,332 │ │ └─MBConvBlock: 3-32 1,420,804 │ │ └─MBConvBlock: 3-33 3,049,200 │ └─Conv2dStaticSamePadding: 2-4 802,816 │ │ └─Identity: 3-34 – │ └─BatchNorm2d: 2-5 3,584 │ └─AdaptiveAvgPool2d: 2-6 – │ └─Dropout: 2-7 – │ └─Linear: 2-8 21,516 │ └─MemoryEfficientSwish: 2-9”

Total params: 17,570,132 Trainable params: 17,570,132 Non-trainable params: 0 ======================================================================

It has pretty much everything we need to know about the model. It has two custom convolutional layers (Conv2dStaticSamePadding), each followed by a batch normalization layer (BatchNorm2d) and 32 MBConvBlock modules.

The network also has a memory-efficient implementation of the Swish activation function (MemoryEfficientSwish), which, like all activation functions, introduces non-linearity into the model. It’s smooth and non-monotonic, which helps it converge more quickly while learning more complex and nuanced patterns. It also has a global average pooling operation (AdaptiveAvgPool2d), which reduces the spatial dimensions of the feature maps. It then has a first Dropout layer for regularization, followed by a fully connected layer (Linear) that takes it from 1792 nodes to 12. Dropout prevents overfitting by making a fraction of the neurons inactive in each update cycle. If you want to see more details of how the output shape of each layer gets reduced between one layer and another, enter the input_size into the summary – like summary(garbage_mdl, input_size=(64, 3, 224, 224)) – because the network was designed with a batch size of 64 in mind. Don’t worry if none of these terms sound familiar to you. We will revisit them later.

Assessing the CNN classifier with traditional interpretation methods

Section titled “Assessing the CNN classifier with traditional interpretation methods”

We will first evaluate the model using the validation dataset with the evaluate_multiclass_mdl function. The arguments include the model (garbage_mdl), our validation data (val_data), as well as the class names (labels_l) and the encoder (ohe). Lastly, we won’t plot the ROC curves (plot_roc=False). This function returns the predicted labels and probabilities, which we can store in variables for later use:

y_val_pred, y_val_prob = mldatasets.evaluate_multiclass_mdl(
garbage_mdl, val_data,\
class_l=labels_l, ohe=ohe, plot_roc=False
)

The preceding code generates both Figure 7.5 with a confusion matrix and Figure 7.6 with performance metrics for each class:

![Graphical user interface, text, application, email

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_05.png)

Figure 7.5: The confusion matrix for the validation dataset

Even though the confusion matrix in Figure 7.5 seems to suggest a perfect classification, once you see the precision and recall breakdown in Figure 7.6, you can tell that the model had issues with metal, plastic, and white glass:

![A picture containing text, receipt

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_06.png)

Figure 7.6: The classification report for the validation dataset

You can expect a model to always reach 100% training accuracy if you train it for enough epochs using optimal hyperparameters. A near-perfect validation accuracy is harder to achieve, depending on how different these two are. We know that the validation dataset is simply a sample of images from the same collection, so it’s not particularly surprising that 94.7% was achieved.

Now, let’s repeat the same code snippet for the test dataset. This time, we want to see the ROC curves (plot_roc=True) but only the averages, and not on a class-by-class basis (plot_roc_class=False) because there are only four pictures per class. Given the small number of samples, we can display the numbers in the confusion matrix rather than percentages (pct_matrix=False):

y_test_pred, y_test_prob = mldatasets.evaluate_multiclass_mdl(
garbage_mdl, test_data,\
class_l=labels_l, ohe=ohe,\
plot_roc=True, plot_roc_class=False, pct_matrix=False
)

The preceding code snippet generated the ROC curve in Figure 7.7, the confusion matrix in Figure 7.8, and the classification report in Figure 7.9:

![Chart, line chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_07.png)

Figure 7.7: The ROC curve for the test dataset

The test ROC plot (Figure 7.7) shows the macro-average and micro-average ROC curves. The difference in both of these is in how they are calculated. Macro metrics are computed for each class independently and then averaged, treating each differently, whereas micro-averages factor in the contribution or representation of each class; generally, micro-averages are more reliable.

![Chart, scatter chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_08.png)

Figure 7.8: The confusion matrix for the test dataset

If we take a look at the confusion matrix in Figure 7.8, we can tell that only biological, green glass, and shoes are getting 10-out-of-10 classifications. However, a lot of items are being misclassified as biologicals and shoes. On the other hand, many items are more often than not misclassified, such as metal, paper, and plastic. Many of them are similar in shape or color, so you could understand how that would happen, but how does a piece of metal get confused with white glass, or paper with a battery?

![Table

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_09.png)

Figure 7.9: The predictive performance metrics for the test dataset

When classification models are discussed in a business setting, stakeholders are often only interested in one number: accuracy. It’s easy to let this drive the discussion, but there’s much more nuance to it. For instance, the disappointing test accuracy (68.3%) could mean many things. It could mean that six classes are getting perfect classification, and all others are not, or that 12 classes are getting only half misclassified. There are many possibilities of what could be going on.

In any case, when dealing with a multiclass classification problem, even an accuracy below 50% might not be as bad as it seems. Consider that the no information rate represents the accuracy that can be achieved by a naive model that always predicts the most frequent class in the dataset. It serves as a benchmark to ensure that the developed model is providing insights beyond this simplistic approach. And with 12 evenly split, the no information rate is likely to be around 8.33% (100%/12 classes), so 68% is still orders of magnitude higher than that. In fact, there is less of a leap to 100%! To a machine learning practitioner, this means that if we judge solely based on test accuracy results, the model is still learning something of value that can be improved upon.

In any case, the predictive performance metrics in Figure 7.9 for the test dataset are consistent with what we saw in the confusion matrix. Biological gets high recall but low precision and metal, paper, plastic, and trash are low for both.

Determining what misclassifications to focus on

Section titled “Determining what misclassifications to focus on”

We have already noticed some exciting misclassifications we can focus on:

  • Metal false positives: 16 out of the 120 samples in the test dataset were misclassified as metal. That’s 42% of all misclassifications! What is it about metal that renders it so easily confused with other garbage according to the model?
  • Plastic false negatives: 70% of all true plastic samples were misclassified. Thus, plastics had the lowest recall of any material besides trash. It’s easy to tell why trash would be so difficult to classify because it’s exceedingly diverse but not plastic.

We should also examine some true positives to contrast these misclassifications. Namely, batteries because they get many false positives as metals and plastic, and white glass because it gets false negatives as metals 30% of the time. Since there are so many metal false positives, we should narrow them down to just those that are for batteries.

To visualize the tasks ahead, we can create a DataFrame (preds_df) with the true labels (y_true) in one column and predicted labels in another (y_pred). And to understand how certain the models are of these predictions, we can create another DataFrame with the probabilities (probs_df). We can generate column totals for these probabilities to sort the columns according to which category the model is most certain about across all samples. Then, we can concatenate our predictions DataFrame with the first 12 columns from our probabilities DataFrame:

preds_df = pd.DataFrame({'y_true':[labels_l[o] for o in y_test],\
'y_pred':y_test_pred})
probs_df = pd.DataFrame(y_test_prob*100).round(1)
probs_df.loc['Total']= probs_df.sum().round(1)
probs_df.columns = labels_l
probs_df = probs_df.sort_values('Total', axis=1, ascending=False)
probs_df.drop(['Total'], axis=0, inplace=True)
probs_final_df = probs_df.iloc[:,0:12]
preds_probs_df = pd.concat([preds_df, probs_final_df], axis=1)

Let’s now output the DataFrame with color coding for the prediction instances we are interested in assessing. On one hand, we have the metal false positives and, on the other, the plastic false negatives. But we also have the true positives for battery and white glass. Lastly, we have bolded all probabilities over 50% and hidden all probabilities of 0% so that it’s easier to spot any predictions with high probabilities:

num_cols_l = list(preds_probs_df.columns[2:])
num_fmt_dict = dict(zip(num_cols_l, ["{:,.1f}%"]*len(num_cols_l)))
preds_probs_df[
(preds_probs_df.y_true!=preds_probs_df.y_pred)
| (preds_probs_df.y_true.isin(['battery', 'white-glass']))
].style.format(num_fmt_dict).apply(
lambda x: ['background: lightgreen' if (x[0] == x[1])\
else '' for i in x], axis=1
).apply(
lambda x: ['background: orange' if (x[0] != x[1] and\
x[1] == 'metal' and x[0] == 'battery')\
else '' for i in x], axis=1
).apply(
lambda x: ['background: yellow' if (x[0] != x[1] and\
x[0] == 'plastic')\
else '' for i in x], axis=1
).apply(
lambda x: ['font-weight: bold' if isinstance(i, float)\
and i >= 50\
else '' for i in x], axis=1
).apply(
lambda x: ['color:transparent' if i == 0.0\
else '' for i in x], axis=1)

The preceding code snippet produces Figure 7.10. We can tell by the highlights which are the metal false positives and the plastic false negatives, as well as which would be the true positives: #0-6 for battery, and #110-113 and #117-119 for white glass:

![Table

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_10.png)

Figure 7.10: Table with all 38 misclassifications in the test dataset, selected true positives, and their true and predicted labels, as well as their predicted probabilities

We can easily store the indexes for these instances in lists with the following code. That way, for future reference, we can iterate through these lists to assess individual predictions or subset arrays with them to perform interpretation tasks for the entire group. As you can tell, we have lists for all four groups:

plastic_FN_idxs = preds_df[
(preds_df['y_true'] !=preds_df['y_pred'])
& (preds_df['y_true'] == 'plastic')
].index.to_list()
metal_FP_idxs = preds_df[
(preds_df['y_true'] != preds_df['y_pred'])
& (preds_df['y_pred'] == 'metal')
& (preds_df['y_true'] == 'battery')
].index.to_list()
battery_TP_idxs = preds_df[
(preds_df['y_true'] ==preds_df['y_pred'])
& (preds_df['y_true'] == 'battery')
].index.to_list()
wglass_TP_idxs = preds_df[
(preds_df['y_true'] == preds_df['y_pred'])
& (preds_df['y_true'] == 'white-glass')
].index.to_list()

Now that we have all our data preprocessed, the model is fully loaded and lists the groups of predictions to debug. Now we can move forward. Let the interpretation begin!

Visualizing the learning process with activation-based methods

Section titled “Visualizing the learning process with activation-based methods”

Before we get into discussing activations, layers, filters, neurons, gradients, convolutions, kernels, and all the fantastic elements that make up a CNN, let’s first briefly revisit the mechanics of a CNN and one in particular.

The convolution layer is the essential building block of a CNN, which is a sequential neural network. It convolves the input with learnable filters, which are relatively small but are applied across the entire width, height, and depth at specific distances or strides. Each filter produces a two-dimensional activation map (also known as a feature map). It’s called an activation map because it denotes positions of activations in the images – in other words, where specific “features” are located. In this context, a feature is an abstract spatial representation that, downstream in the process, is reflected in the learned weights of fully connected (linear) layers. For instance, in the garbage CNN case, the first convolutional layer has 48 filters with a 3 × 3 kernel, a 2 × 2 stride, and static padding, which ensure that the output maps maintain the same size as the inputs. Filters are template matching because they end up activating areas of the activation map when certain patterns are found in the input image.

But before we get to our fully connected layers, we have to reduce the dimensions of our filters until they have a workable size. For instance, if we flattened the output of our first convolution (48 × 112 × 112), we would have over 602,000 features. I think we can all agree that that would be too much to feed into a fully connected layer. Even if we used enough neurons to handle this workload, we probably wouldn’t have captured enough spatial representations for the neural network to make sense of the images. For this reason, convolutional layers are often paired with pooling layers, which downsample the input – in other words, they reduce the dimensionality of the data. In this case, there’s an adaptive average pooling layer (AdaptiveAvgPool2d) that performs an average across all the channels as well as many pooling layers within the Mobile Inverted Bottleneck Convolution Blocks (MBConvBlock).

Incidentally, MBConvBlock, Conv2dStaticSamePadding, and BatchNorm2d are the building blocks of the EfficientNet architecture. These components work together to create a highly efficient and accurate convolutional neural network:

  • MBConvBlock: Mobile inverted bottleneck convolution blocks that form the core of the EfficientNet architecture. In traditional convolutional layers, filters are applied across all input channels simultaneously, resulting in a high number of computations, but MBConvBlocks divide the process into two steps: first, they apply depthwise convolutions that handle each input channel separately, and then use pointwise (1 x 1) convolutions to combine the information from different channels. For this reason, inside the MBConvBlock modules for B0, there are three convolutional layers: a depthwise convolution, a pointwise (1 x 1) convolution (called project convolution), and another pointwise (1 x 1) convolution (called expand convolution) in some blocks. However, the first block only contains two convolutional layers (depthwise and project convolutions) because it doesn’t have an expand convolution. For B4, the architecture is similar except more convolutions are stacked in each block and there are twice as many MBConvBlocks. Naturally, B7 has many more blocks and convolutional layers. For B4, there are a total of 158 convolutional operations between the 32 MBConvBlocks.
  • Conv2dStaticSamePadding: Unlike traditional convolutional layers (such as Conv2d), these don’t reduce the dimensions. It ensures the input and output feature maps have the same spatial dimensions.
  • BatchNorm2d: Batch normalization layers that help stabilize and accelerate training by normalizing the input features, which helps keep the distribution of the input features consistent during training.

Once the over 230 convolutional and pooling operations are performed, we are left with a flattened output of a more workable size: 1,792 features, which the fully connected layer converts into 12, which, leveraging softmax activation, outputs probabilities between 0 and 1 for each of the classes. In the garbage CNN, there is a dropout layer involved to help regularize the training. We can ignore this entirely because, for inference, they are ignored.

If this wasn’t entirely clear, don’t fret! The sections that follow will demonstrate visually through activations, gradients, and perturbations how the network probably learned or did not learn image representations.

For inference, the image goes through the network’s input and the prediction comes out through the output traversing every single layer. However, one of the advantages of having a sequential and layered architecture is that we can extract any layer’s output and not just the final layer. The intermediate activations are simply the outputs of any of the convolution or pooling layers. They are activation maps because, after an activation function has been applied, the brighter spots map to the image’s features. In this case, the model used ReLU on all convolutional layers, so that is what activates the spots. We are only interested in the convolutional layers’ intermediate activations because the pooling layers are simply downsampled versions of these ones. Why not see the higher-resolution version instead?

As the filters become smaller in width and height, the learned representations will be larger. In other words, the first convolutional layer may be about details such as texture, the following one about edges, and the last one about shapes. We must then flatten the convolutional layers’ output to feed it to the multilayer perceptron that takes over from then on.

What we will do now is extract activations for some of the convolutional layers. In B4, there are 158, so we can’t do all of them! To this end, we will obtain the first level of layers with model.children(), and iterate across them. We will append the two Conv2dStaticSamePadding layers from this top level into a conv_layers list. But we will also go deeper, appending the first convolutional layer for the first six MBConvBlock layers in the ModuleList layers. In the end, we should have eight convolutional layers – the six in the middle belonging to Mobile Inverted Bottleneck Convolution blocks:

conv_layers = []
model_children = list(garbage_mdl.model.children())
for model_child in model_children:
if (type(model_child) ==\
efficientnet_pytorch.utils.Conv2dStaticSamePadding):
conv_layers.append(model_child)
elif (type(model_child) == torch.nn.modules.container.ModuleList):
module_children = list(model_child.children())
module_convs = []
for module_child in module_children:
module_convs.append(list(module_child.children())[0])
conv_layers.extend(module_convs[:6])
print(conv_layers)

Before we iterate across all of them producing activation maps for each convolutional layer, let’s do it for a single filter and layer:

idx = battery_TP_idxs[0]
tensor = test_data[idx][0][None, :].to(device)
label = y_test[idx]
method = attr.LayerActivation(garbage_mdl, conv_layers[layer]
attribution = method.attribute(tensor).detach().cpu().numpy()
print(attribution.shape)

The preceding snippet extracts the tensor for the first battery true positive (battery_TP_idxs[0]). Then, it initializes the LayerActivation attribution method with the model (garbage_mdl) and the first convolutional layer (conv_layers[0]). Using the attribute function, it creates an attribution with this method. For the shape of the attribution, we should get (1, 48, 112, 112). The tensor was for a single image, so it makes sense that the first number is a one. The next number corresponds to the number of filters, followed by the width and height dimensions of each filter. Regardless of the kind of attribution, the numbers inside each attribution relate to how a pixel in the input is seen by the model. Interpretation varies according to the method. However, generally, it is interpreted that higher numbers mean more of an impact on the outcome, but attributions may also have negative numbers, which mean the opposite.

Let’s visualize the first filter, but before we do that, we must decide what colormap to use. A colormap will determine what colors to assign to different numbers as a gradient. For instance, the following colormap has white for 0 (#ffffff in hexadecimal), a medium gray for 0.25, and black (#000000 in hexadecimal) for 1 with a gradient between these colors:

cbinary_cmap = LinearSegmentedColormap.from_list('custom binary',
[(0, '#ffffff'),
(0.25, '#777777'),
(1, '#000000')])

You can also use any of the named colormaps from https://matplotlib.org/stable/tutorials/colors/colormaps.html, rather than using your own. Next, let’s plot the attribution for the first filter like this:

filter = 0
filter_attr = attribution[0,filter]
filter_attr = mldatasets.apply_cmap(filter_attr, cbinary_cmap, 'positive')
y_true = labels_l[label]
y_pred = y_test_pred[idx]
fig, ax = plt.subplots(1, 1, figsize=(8, 6))
fig.suptitle(f"Actual label: {y_true}, Predicted: {y_pred}", fontsize=16)
ax.set_title(
f"({method.get_name()} Attribution for Filter #{filter+1} for\
Convolutional Layer #{layer+1})",
fontsize=12
)
ax.imshow(filter_attr)
ax.grid(False)
fig.colorbar(
ScalarMappable(norm='linear', cmap=cbinary_cmap),
ax=ax,
orientation="vertical"
)
plt.show()

The code saves the first filter for the first image from the attribution to filter_attr and then leverages the apply_cmap utility function to convert the attribution array to a normalized colormap, which is then plotted with imshow. The rest of the code plots the title with the actual and predicted label for the image and a colorbar with the colormap. The snippet will output Figure 7.11:

![Diagram

Description automatically generated with low confidence](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_11.png)

Figure 7.11: Intermediate activation map for the first filter for the first convolutional layer for the first true positive battery sample

As you can tell in Figure 7.11, it seems like the intermediate activations for the first filter are finding the edges of the battery and the most prominent text.

Next, we will iterate across all computational layers and every battery and visualize attributions for each one. Now, some of these attribution operations can be computationally expensive, so it’s important to clear the GPU cache (clear_gpu_cache()) in between them:

for l, layer in enumerate(conv_layers):
layer = conv_layers[l]
method = attr.LayerActivation(garbage_mdl, layer)
for idx in battery_TP_idxs:
orig_img = mldatasets.tensor_to_img(test_400_data[idx][0],\
norm_std, norm_mean,\
to_numpy=True)
tensor = test_data[idx][0][None, :].to(device)
label = int(y_test[idx])
attribution = method.attribute(tensor).detach().cpu().numpy()
viz_img = mldatasets.create_attribution_grid(attribution,\
cmap='copper', cmap_norm='positive')
y_true = labels_l[label]
y_pred = y_test_pred[idx]
probs_s = probs_df.loc[idx]
name = method.get_name()
title = f'CNN Layer #{l+1} {name} Attributions for Sample #{idx}'
mldatasets.compare_img_pred_viz(orig_img, viz_img, y_true,\
y_pred, probs_s, title=title)
clear_gpu_cache()

The preceding snippet should look fairly familiar. Where it’s different is that it’s placing every attribution map for every filter in a grid (viz_img) with create_attribition_grid. It could just then display it with plt.imshow as before, but instead, we will leverage a utility function called compare_img_pred_viz to visualize the attribution(s) side by side with the original image (orig_img). It also takes the sample’s actual label (y_true) and predicted label (y_pred). Optionally, we can provide a pandas series with the probabilities for this prediction (probs_s) and a title. It generates 56 images in total, including Figures 7.12, 7.13, and 7.14.

As you can tell from Figure 7.12, the first convolutional layer seems to be picking up on the battery’s letters as well as its contours:

![Graphical user interface

Description automatically generated with low confidence](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_12.png)

Figure 7.12: Intermediate activations for the first convolutional layer for battery #4

However, Figure 7.13 shows how, by the fourth convolutional layer, the network understands a battery’s contours better:

![Graphical user interface

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_13.png)

Figure 7.13: Intermediate activations for the fourth convolutional layer for battery #4

The last convolutional layer in Figure 7.14 is impossible to interpret because there are 1,792 filters that are 7 pixels wide and high, but rest assured, there are some very high-level features encoded in those tiny maps:

![A picture containing text

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_14.png)

Figure 7.14: Intermediate activations for the last convolutional layer for battery #4

Extracting intermediate activations can provide you with some insight on a sample-by-sample basis. In other words, it’s a local model interpretation method. It’s by no means the only layerwise-attribution method. Captum has more than ten layer attribution methods: https://github.com/pytorch/captum#about-captum.

Evaluating misclassifications with gradient-based attribution methods

Section titled “Evaluating misclassifications with gradient-based attribution methods”

Gradient-based methods calculate attribution maps for each classification with both forward and background passes through the CNN. As the name suggests, these methods leverage the gradients in the backward pass to compute the attribution maps. All of these methods are local interpretation methods because they only derive a single interpretation per sample. Incidentally, attributions in this context mean that we are attributing the predicted labels to areas of an image. They are often called sensitivity maps in academic literature, too.

To get started, we will first need to create an array with all of our misclassification samples (X_misclass) from the test dataset (test_data) using the combined indexes for all of our misclassifications of interest (misclass_idxs). Since there aren’t that many misclassifications, we are loading a single batch of them (next):

misclass_idxs = metal_FP_idxs + plastic_FN_idxs[-4:]
misclass_data = torch.utils.data.Subset(test_data, misclass_idxs)
misclass_loader = torch.utils.data.DataLoader(misclass_data,\
batch_size = 32)
X_misclass, y_misclass = next(iter(misclass_loader))

X_misclass, y_misclass = X_misclass.to(device), y_misclass.to(device)

The next step is to create a utility function we can reuse to obtain the attribution maps for any method. Optionally, we can smooth the map with a method called NoiseTunnel (https://github.com/pytorch/captum#getting-started). We will cover this method in more detail later:

def get_attribution_maps(method, model, device,X,y=None,\
init_args={}, nt_type=None, nt_samples=10,\
stdevs=0.2, **kwargs):
attr_maps_size = tuple([0] + list(X.shape[1:]))
attr_maps = torch.empty(attr_maps_size).to(device)
attr_method = method(model, **init_args)
if nt_type is not None:
noise_tunnel = attr.NoiseTunnel(attr_method)
nt_attr_maps = torch.empty(attr_maps_size).to(device)
for i in tqdm(range(len(X))):
X_i = X[i].unsqueeze(0).requires_grad_()
model.zero_grad()
extra_args = {**kwargs}
if y is not None:
y_i = y[i].squeeze_()
extra_args.update({"target":y_i})
attr_map = attr_method.attribute(X_i, **extra_args)
attr_maps = torch.cat([attr_maps, attr_map])
if nt_type is not None:
model.zero_grad()
nt_attr_map = noise_tunnel.attribute(
X_i, nt_type=nt_type, nt_samples=nt_samples,\
stdevs=stdevs, nt_samples_batch_size=1, **extra_args)
nt_attr_maps = torch.cat([nt_attr_maps, nt_attr_map])
clear_gpu_cache()
if nt_type is not None:
return attr_maps, nt_attr_maps
return attr_maps

The preceding code can create attribution maps for any Captum method for a given model and device. To that end, it takes tensors for the images, X, and their corresponding labels, y. The labels are optional and only needed if the attribution method is targeted – most methods are. Most attribution methods (attr_method) are initialized with only the model, but some require some additional arguments (init_args). Where they tend to have the most arguments is when the attribution is generated with the attribute function, which is why we have the **kwargs collect additional arguments in the get_attribution_maps function and place them in this call.

One important thing to note is that, in this function, we iterate across all the samples in the X tensor and create the attribute maps for each one independently. This is often unnecessary because the attribute methods are all equipped to process a batch at once. However, there’s a risk the hardware can’t handle an entire batch, and at the time of this writing, very few methods come with an internal_batch_size argument, which can limit how many samples are processed at a time. What we are doing here is essentially equivalent to setting this number to 1 every single time in an effort to ensure that we don’t run into memory issues. However, if you have powerful hardware, you can rewrite the function to process the X and y tensors directly.

Next, we will perform our first gradient-based attribution method.

Saliency maps rely on the absolute value of gradients. The intuition is that it will find the pixels in the image that can be perturbed the least so that the output changes the most with these values. It doesn’t perform perturbations, so it doesn’t validate the hypothesis, and the use of absolute values prevents it from finding other evidence to the contrary.

This first saliency map method was groundbreaking at the time and has inspired a bunch of different methods. It’s typically nicknamed “vanilla” to distinguish it from other saliency maps.

Generating saliency maps for all of our misclassified samples is relatively simple with our get_attribution_maps function. All you need is the Captum attribution method (attr.Saliency), model (garbage_mdl), device, and the tensors for the misclassified samples (X_misclass and y_misclass):

saliency_maps = get_attribution_maps(attr.Saliency, garbage_mdl,\
device, X_misclass, y_misclass)

We can plot the output of one of these saliency maps, the fifth one, side by side with the sample image to provide context. Matplotlib can do this easily with a subplots grid. We will make a 1 × 3 grid and place the sample image in the first spot, its saliency heatmap in the second, and one overlayed over the other in the third. As we have done with previous attribution maps, we can use tensor_to_img to convert the images to numpy arrays while also applying a colormap to the attribution. It uses the jet colormap (cmap='jet') by default to make the salient areas appear more striking:

pos = 4
orig_img = mldatasets.tensor_to_img(X_misclass[pos], norm_std,\
norm_mean, to_numpy=True)
attr_map = mldatasets.tensor_to_img(
saliency_maps[pos], to_numpy=True,\
cmap_norm='positive'
)

fig, axs = plt.subplots(1, 3, figsize=(15,5))

axs[0].imshow(orig_img)

axs[0].grid(None)

axs[0].set_title(“Original Image”)

axs[1].imshow(attr_map)

axs[1].grid(None)

axs[1].set_title(“Saliency Heatmap”)

axs[2].imshow(np.mean(orig_img, axis=2), cmap=“gray”)

axs[2].imshow(attr_map, alpha=0.6)

axs[2].grid(None)

axs[2].set_title(“Saliency Overlayed”)

idx = misclass_idxs[pos]
y_true = labels_l[int(y_test[idx])]
y_pred = y_test_pred[idx]
plt.suptitle(f"Actual label: {y_true}, Predicted: {y_pred}")
plt.show()

The preceding code generates the plot in Figure 7.15:

![Chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_15.png)

Figure 7.15: Saliency maps for plastic misclassified as biological waste

The sample image in Figure 7.15 appears to be shredded plastic, but the prediction is for biological waste. The vanilla saliency map attributes that prediction mostly to the smoother duller areas of the plastic. It appears that the lack of specular highlights has thrown the model off, but typically, older broken pieces of plastic lose their shine.

Specular highlights are bright spots of light that appear on the surface of an object when it reflects light. They are often the direct reflections of a light source and are more pronounced on shiny or glossy surfaces, such as metal, glass, or water.

To discuss guided Grad-CAM, we first ought to discuss CAM, which stands for Class Activation Map. The way CAM works is that it removes all but the last fully connected layers, and it replaces the last MaxPooling layer with a Global Average Pooling (GAP) layer. A GAP layer calculates the average value of each feature map, reducing it to a single value per map, while a MaxPooling layer downsizes feature maps by selecting the maximum value from a set of values in a local region of the map. For instance, in this case:

  1. The last convolutional layer outputs a tensor that is 1792 × 7 × 7.
  2. GAP reduces dimensions by merely averaging the last two dimensions of this tensor, producing a 1792 × 1 × 1 tensor.
  3. It then feeds this to a fully connected layer with 12 neurons corresponding to each class.
  4. Once you retrain a CAM model and pass a sample image through the CAM model, it takes the weights from the last layer (a 1792 × 12 tensor) and extracts the values corresponding to the predicted class (a 1792 × 1 tensor).
  5. Then, you calculate the dot product of the last convolutional layer’s output (1792 × 7 × 7) with the weight tensor (1792 x 1).
  6. This weighted sum will end with a 1 × 7 × 7 tensor.
  7. With bilinear interpolation to stretch it out to 1 × 224 × 224, this becomes an upsampled class activation map. When you upsample data, you increase its dimensions.

The intuition behind CAM is that CNNs inherently retain spatial details in convolutional layers but they are, sadly, lost in fully connected layers. In fact, each filter in the last convolutional layer represents visual patterns at different spatial locations. Once weighted, they represent the most salient regions in the entire image. However, to apply CAM, you must radically modify a model and retrain it, and some models don’t lend themselves easily to this.

As the name suggests, Grad-CAM is a similar concept but lacks the modifying and retraining hassle, and uses gradients instead – specifically, those of the class score (prior to softmax) concerning the convolutional layer’s activation maps. GAP is performed on these gradients to obtain neuron importance weights. Then, we compute a weighted linear combination of activation maps with these weights, followed by a ReLU. The ReLU is very important because it ensures locating features that only positively influence the outcome. Like CAM, it is upsampled with bilinear interpolation to match the dimensions of the image.

Grad-CAM does have some shortcomings too, such as failing to identify multiple occurrences or the entirety of the object represented by the predicted class. Like CAM, the resolution of the activation maps may be limited by the final convolutional layer’s dimensions, hence the upsampling.

For these reasons, we are using guided Grad-CAM instead. Guided Grad-CAM is a combination of Grad-CAM and guided backpropagation. Guided backpropagation is another visualization method that computes the gradients of the target class with respect to the input image, but it modifies the backpropagation process to only propagate positive gradients for positive activations. This results in a higher-resolution, more detailed visualization. This is achieved by performing an element-wise multiplication of the Grad-CAM heatmap (upsampled to the input image resolution) with the guided backpropagation result. The output is a visualization that emphasizes the most relevant features in the image for the given class, with higher spatial detail than Grad-CAM alone.

Generating Grad-CAM attribution maps for all of our misclassified samples can be done with our get_attribution_maps function. All you need is the Captum attribution method (attr.GuidedGradCam), model (garbage_mdl), device, and the tensors for the misclassified samples (X_misclass and y_misclass), and, within the method initialization arguments, a layer for which Grad-CAM attributions are computed:

gradcam_maps = get_attribution_maps(
attr.GuidedGradCam, garbage_mdl, device, X_misclass,\
y_misclass, init_args={'layer':conv_layers[3]}
)

Notice that we aren’t using the last layer (which can be indexed with 7 or -1) but the fourth one (3). This is just to keep things interesting, but we can change it. Next, let’s plot the attributions just as we have before. Nearly the same code is used except saliency_maps is replaced by gradcam_maps. The output is depicted in Figure 7.16.

![Chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_16.png)

Figure 7.16: Guided Grad-CAM heatmaps for plastic misclassified as biological waste

As you can observe in Figure 7.16, similar smooth matte areas are highlighted as with the saliency attribution maps, that except guided Grad-CAM yields a few bright areas and edges.

Take all of this with a grain of salt. There is still a lot of ongoing debate in the CNN interpretation domain. And researchers are still coming up with new and better methods, and even techniques that are nearly perfect for most use cases still have flaws. Regarding CAM-like methods, there are many newer ones, such as Score-CAM, Ablation-CAM, and Eigen-CAM, which provide similar functionality but don’t rely on gradients, which can be unstable and, therefore, occasionally unreliable. We won’t discuss them here because, of course, they aren’t gradient-based! But it’s essential to note that it doesn’t hurt to try different methods to see what works for your use case.

Integrated gradients (IG), also known as path-integrated gradients, is a technique that is not exclusive to CNNs. You can apply it to any neural network architecture because it computes the gradients of the output with respect to the inputs averaged all along a path between a baseline and the actual input. It is agnostic to the presence of convolutional layers. However, it requires the definition of a baseline, which is supposed to convey a lack of signal, like a uniformly colored image. In practice, for CNNs in particular, this is what a zero baseline represents, which, for every pixel, would usually mean a completely black image. Also, although the name suggests the use of path integrals, integrals aren’t computed but approximated, with summation in sufficiently small intervals for a certain number of steps. For a CNN, this means it makes variations of the input image progressively darker or lighter until it becomes the baseline corresponding to the predefined number of steps. It then feeds these variations to the CNN, computes the gradients for each one, and averages them. The IG is the dot product of the image times the gradient averages.

Like Shapley values, IG is grounded in solid mathematical theory. In this case, it’s the fundamental theorem of calculus for line integrals. The mathematical proof of the IG method ensures that the attributions of all the features add up to the difference between the model’s prediction on the input data and its prediction on the baseline input. In addition to this property, which they call completeness, there is linearity preservation, symmetry preservation, and sensitivity. We won’t describe each of these properties here. However, it’s important to note that some interpretation methods satisfy notable mathematical properties, while others demonstrate their effectiveness in practical terms.

In addition to IG, we will also leverage NoiseTunnel to perform small random perturbations on the sample image – in other words, to add noise. It creates different noisy versions of the same sample image multiple times and then computes the attribution method for each. It then averages these attributions, potentially making the attribution maps much smoother, which is why this method is called SmoothGrad.

But wait, you may ask: Shouldn’t it be a perturbation-based method then?! We’ve already dealt with several perturbation-based methods before in this book, from SHAP to anchors, and something they have in common is that they perturb the input to measure the effect on the output. SmoothGrad doesn’t measure the impact on the outputs. It only helps yield a more robust attribution map because the mean attribution of perturbed inputs should make for more trustworthy attribution maps. We perform cross-validation to evaluate machine learning models for the same reason: the average metrics performed on different test datasets with slightly different distributions make for better metrics.

For IG, we will use very similar code as we did for Saliency, except we will add several arguments related to NoiseTunnel, such as the type of noise tunnel (nt_type='smoothgrad'), the sample variations to produce (nt_samples=20), and an amount of random noise to add to each one in standard deviations (stdevs=0.2). We will find that the more permuted samples to generate, the better, up to a point, and then it doesn’t have much effect. However, there is such a thing as too much noise, and if you use too little, there won’t be any effect:

ig_maps, smooth_ig_maps = get_attribution_maps(
attr.IntegratedGradients, garbage_mdl, device, X_misclass,\
y_misclass, nt_type='smoothgrad', nt_samples=20, stdevs=0.2

)

We can also optionally define the number of steps for the IG (n_steps). It’s set to 50 by default, and we can also modify the baselines, which is a tensor of zeros by default. As we’ve done with Grad-CAM, we can plot our first sample image side by side with the IG map, but this time, we will modify the code to plot the SmoothGrad integrated gradients (smooth_ig_maps) in the third position, like this:

nt_attr_map = mldatasets.tensor_to_img(
smooth_ig_maps[pos], to_numpy=True, cmap_norm='positive'
)

axs[2].imshow(nt_attr_map)

axs[2].grid(None)

axs[2].set_title(“SmoothGrad Integrated Gradients”)

The modified snippet outputs Figure 7.17:

![Chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_17.png)

Figure 7.17: Integrated gradient heatmaps for plastic misclassified as biological waste

The areas in the IG heatmap in Figure 7.17 coincide with many of the regions spotted by the saliency and guided Grad-CAM maps. However, there are more clusters of strong attributions in the bright yellow areas as well as in brownish shadowed areas, which is consistent with how some foods look when they are disposed of (like banana peels and rotten leafy greens). On the other hand, the bright orange and green areas aren’t.

As for the SmoothGrad IG heatmap, it is striking how different this map is compared to the non-smooth IG heatmap. This is not always the case; often, it’s just a smoother version. What likely happened was that the 0.2 noise distorted the attributions a bit too much, or that 20 perturbed samples weren’t enough. However, it’s tough to tell because it’s also possible that SmoothGrad more accurately depicts the real story.

We won’t do this now, but you can visually “tune” the stdevs and nt_samples parameters. You can try it with less noise and more samples, using a series of combinations, such as 0.1 and 80, and 0.15 and 40, trying to figure out whether you see a commonality between them. The one you go with is the one that most clearly depicts this consistent story. One of the shortcomings of SmoothGrad is having to define optimal parameters. Incidentally, IG also has the same issue with defining the baselines and number of steps (n_steps). The default baseline won’t work in cases where the input image is too large or small, so it must be changed, and the authors of the IG paper suggest that 20-300 steps will approximate the integral within 5%.

IG has its detractors, who have made similar methods that avoid using gradients, such as DeepLIFT. IG can be sensitive to zero-valued gradients and discontinuities with gradients, which can lead to misleading attributions. But these point to general disadvantages shared by all gradient-based methods. For this reason, we are introducing the Deep Learning Important FeaTures algorithm (DeepLIFT). It’s neither a gradient-based nor a perturbation-based method. It’s a backpropagation-based approach!

In this section, we will contrast it with IG. Like IG and Shapley values, DeepLIFT was designed for completeness, and as such, complies with remarkable mathematical properties. In addition to that, like IG, DeepLIFT can also be applied to various deep learning architectures, including CNNs and recurrent neural networks (RNNs), making it versatile for different use cases.

DeepLIFT works by decomposing the output prediction of the model into contributions from each input feature, using the concept of “difference-from-reference.” It backpropagates these contributions through the network layers to assign an importance score to each input feature.

More specifically, like IG, it uses a baseline that represents no specific information about any class. However, it then calculates the difference in the activations of each neuron between the input and the baseline, and it backpropagates these differences through the network, calculating each neuron’s contribution to the output prediction. Then we sum the contributions for each input feature to obtain its importance score (attribution).

It’s advantages over IG are as follows:

  • Reference-based: Unlike gradient-based methods such as IG, DeepLIFT explicitly compares the input to a reference input, making the attributions more interpretable and meaningful.
  • Non-linear interactions: DeepLIFT considers the non-linear interactions between neurons when computing attributions. It captures these interactions by considering the multipliers (the change in output due to the change in input) in each layer of the neural network.
  • Stability: DeepLIFT is more stable than gradient-based methods, as it is less sensitive to small changes in the input, providing more consistent attributions. So, using a SmoothGrad is unnecessary on DeepLIFT attributions although highly recommended for gradient-based methods.

Overall, DeepLIFT provides a more interpretable, stable, and comprehensive approach to attributions, making it a valuable tool for understanding and explaining deep learning models.

Next, we will create DeepLIFT attribution maps in a similar fashion as we have done the others:

deeplift_maps = get_attribution_maps(attr.DeepLift, garbage_mdl,\
device, X_misclass, y_misclass)

To plot an attribution map, nearly the same code as with Grad-CAM is used, except gradcam_maps is replaced by deeplift_maps. The output is depicted in Figure 7.18.

![Chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_18.png)

Figure 7.18: DeepLIFT heatmaps for plastic misclassified as biological waste

The attributions of Figure 7.18 are not as noisy as in IG. But they also seem to cluster around some dull yellows and dark areas in the shadows; it also points toward dull greens near the top-right corner.

Now, we will take everything that we have learned about gradient-based attribution methods and use it to understand the reasons for all the chosen misclassifications (the plastic false negatives and metal false positives). As we did with intermediate activation maps, we can leverage the compare_img_pred_viz function to place the higher-resolution sample image side by side with four attribution maps: saliency, Grad-CAM, SmoothGrad IG, and DeepLift. To this end, we first have to iterate all the misclassifications’ positions and indexes and extract all the maps. Note that we are using overlay_bg in the tensor_to_img function to produce a new image overlaying the original image with the heatmap for each. Lastly, we concatenate the four attribution outputs into a single image (viz_img). Just as we have done before, we extract the actual label (y_true), predicted label (y_pred), and pandas series with the probabilities (probs_s) to add some context to the plot we will produce. The for loop will produce six plots but, for brevity’s sake, we are only going to discuss three of them:

for pos, idx in enumerate(misclass_idxs):
orig_img = mldatasets.tensor_to_img(test_400_data[idx][0],\
norm_std, norm_mean, to_numpy=True)
bg_img = mldatasets.tensor_to_img(test_data[idx][0],\
norm_std, norm_mean, to_numpy=True)
map1 = mldatasets.tensor_to_img(
saliency_maps[pos], to_numpy=True,\
cmap_norm='positive', overlay_bg=bg_img
)
map2 = mldatasets.tensor_to_img(
smooth_ig_maps[pos],to_numpy=True,\
cmap_norm='positive', overlay_bg=bg_img
)
map3 = mldatasets.tensor_to_img(
gradcam_maps[pos], to_numpy=True,\
cmap_norm='positive', overlay_bg=bg_img
)
map4 = mldatasets.tensor_to_img(
deeplift_maps[pos], to_numpy=True,\
cmap_norm='positive', overlay_bg=bg_img
)
viz_img = cv2.vconcat([
cv2.hconcat([map1, map2]),
cv2.hconcat([map3, map4])
])
label = int(y_test[idx])
y_true = labels_l[label]
y_pred = y_test_pred[idx]
probs_s = probs_df.loc[idx]
title = 'Gradient-Based Attr for Misclassification Sample #{}'.\
format(idx)
mldatasets.compare_img_pred_viz(orig_img, viz_img, y_true,\
y_pred, probs_s, title=title)

The preceding code generates Figures 7.19 to 7.21. It’s important to note that in all generated plots, we can observe saliency attributions at the top left, SmoothGrad IG at the top right, guided Grad-CAM at the bottom left, and DeepLIFT at the bottom right:

![Graphical user interface

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_19.png)

Figure 7.19: Gradient-based attributions for battery as metal misclassification #8

In Figure 7.19, there’s a lack of consistency between all four attribution methods. The saliency attribution maps show that all the center parts of the batteries are seen as metal surfaces, in addition to the white parts of the cardboard container. On the other hand, SmoothGrad IG zeros in on the white cardboard and Grad-CAM on the blue cardboard almost exclusively. Lastly, DeepLIFT is much more sparse, only pointing to some parts of the white cardboard.

In Figure 7.20, the attributions are much more consistent than in Figure 7.19. Matte white areas are clearly confusing the model. This makes sense considering that the plastic in the training data was mostly single pieces of empty plastic containers – including white milk jugs. However, people do recycle toys, plastic tools like spatulas, and other plastic objects. Interestingly enough, although all attribution methods were salient around white and light-yellow surfaces, SmoothGrad IG also highlights some edges, like one of the ducks’ hats and another one’s collar:

![Graphical user interface, application

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_20.png)

Figure 7.20: Gradient-based attributions for plastic misclassification #86

To continue with the recycling toys theme, how do LEGO bricks get misclassified as batteries? See Figure 7.21 for an interpretation:

![Diagram

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_21.png)

Figure 7.21: Gradient-based attributions for plastic misclassification #89

Figure 7.21 shows how, among all the attribution methods, it’s mostly the yellow and green bricks (and to a lesser degree, light blue) that are to blame for the misclassification because these are popular colors among battery manufacturers, as attested by the training data. Also, the flat surface in between the studs got the most attributions since these resemble the contacts in batteries and, more specifically, 9-volt square batteries. As with the other examples, saliency was the most noisy method. However, this time, guided Grad-CAM was the least noisy. It was also more salient on the edges than on surfaces, unlike the others.

We will next try to discover what the model learned about batteries (in addition to white glass) through perturbation-based attribution methods performed on true positives.

Understanding classifications with perturbation-based attribution methods

Section titled “Understanding classifications with perturbation-based attribution methods”

Perturbation-based methods have already been covered to a great extent in this book so far. So many of the methods we have covered, including SHAP, LIME, anchors, and even permutation feature importance, employ perturbation-based strategies. The intuition behind them is that if you remove, alter, or mask features in your input data and then make predictions with them, you’ll be able to attribute the difference between the new predictions and the original predictions to the changes you made in the input. These strategies can be leveraged in both global and local interpretation methods.

We will now do the same as we did with the misclassification samples, but to the chosen true positives, and gather four of each class in a single tensor (X_correctcls):

correctcls_idxs = wglass_TP_idxs[:4] + battery_TP_idxs[:4]
correctcls_data = torch.utils.data.Subset(test_data, correctcls_idxs)
correctcls_loader = torch.utils.data.DataLoader(correctcls_data,\
batch_size = 32)
X_correctcls, y_correctcls = next(iter(correctcls_loader))
X_correctcls, y_correctcls = X_correctcls.to(device),\
y_correctcls.to(device)

One of the more complicated aspects of performing permutation methods on images is that there are not just a few dozen features but many thousands to permute. Picture this: 224 x 224 equals 50,176 pixels, and if we want to measure how a change in each pixel independently affects the outcome, we’ll need to make at least 20 permuted samples for each pixel. So, over a million! For this reason, several permutation methods accept masks to determine which blocks of pixels to permute at once. If we group them in blocks of 32 x 32 pixels, this means we’ll have only 49 blocks in total to permute. However, although it will speed up the attribution methods, we’ll miss out on the effects on smaller sets of pixels the larger the block.

We can use many methods to create masks, such as using a segmentation algorithm to break up the images into intuitive blocks based on surfaces and edges. Segmentation is done per image, so the number and placement of segments will vary on an image-to-image basis. There are many methods with scikit-learn’s image segmentation library (skimage.segmentation): https://scikit-image.org/docs/stable/api/skimage.segmentation.html. However, we are going to keep things simple and create one mask for all 224 x 224 images with the following code:

feature_mask = torch.zeros(3, 224, 224).int().to(device)
counter = 0
strides = 16
for row in range(0, 224, strides):
for col in range(0, 224, strides):
feature_mask[:, row:row+strides, col:col+strides] = counter
counter += 1

What the preceding code does is initialize a tensor of zeros the size of the model’s input. It’s easier to conceptualize this tensor as an empty image. Then it moves across strides that are 16 pixels wide and high, from the top-left corner of the image to the bottom right. As it moves across, it sets the values with consecutive numbers with the counter. What you end up with is a tensor with all values filled with numbers between 0 and 195, and, if you visualized it as an image, it would be a diagonal gradient from black at the top left to light gray at the bottom right. What’s important to note is that each block with the same value is treated as if it were the same pixel by the attribution method.

Before we move forward, let’s discuss baselines. In Captum attribution methods, as in other libraries for that matter, the default baseline is a tensor of zeros, which is usually equivalent to a black image when images are made up of floating-point numbers between 0 and 1. However, in our case, we are standardizing our input tensors so the model doesn’t see tensors with a minimum of 0 but a mean of 0! Therefore, for our garbage model, a tensor of zeros corresponds to a medium gray image, not a black image. For gradient-based methods, there’s nothing inherently wrong with a gray image baseline because there are likely a number of steps between it and the input image. However, perturbation-based methods can be particularly sensitive to having baselines that are too close to the input image because if you replace parts of the input image with the baseline, the model won’t tell the difference!

For our garbage model’s case, a black image is made up of tensors of -2.1179 because one of the transformations performed to standardize the input tensors was (x-0.485)/0.229, which happens to equal approximately -2.1179, when x=0. You can also calculate the tensors when x=1; it converts to 2.64 for a white image. That being said, there’s no harm in assuming that somewhere in our true positive samples, there’s at least one pixel that has the lowest value and another with the highest, so we will just use max() and min() to create both light and dark baselines:

baseline_light = float(X_correctcls.max().detach().cpu())
baseline_dark = float(X_correctcls.min().detach().cpu())

We will use only one baseline for all but one perturbation method but feel free to switch them around. Now, on to creating attribution maps for each method!

Feature ablation is a relatively simple method. What it does is occlude portions of the sample input image by replacing it with the baseline, which is, by default, zero. The goal is to understand the importance of each input feature (or feature group) in making a prediction by observing the effect of altering it.

Here’s how feature ablation works:

  1. Obtain the original prediction: First, the model’s prediction for the original input is obtained. This serves as a baseline for comparing the effect of perturbing the input features.
  2. Perturb the input feature: Next, for each input feature (or feature group as set by the feature mask), it is replaced with the baselines value. This creates an “ablated” version of the input.
  3. Obtain the prediction for the perturbed input: The model’s prediction is calculated for the ablated input.
  4. Compute the attribution: The difference in the model’s predictions between the original input and the ablated input is calculated. This difference is attributed to the altered feature, indicating its importance in the prediction.

Feature ablation is a simple and intuitive approach to understanding the importance of input features in a model’s prediction. However, it has some limitations. It assumes that features are independent and may not accurately capture the effects of interactions between features. Additionally, it can be computationally expensive for models with a large number of input features or complex input structures. Despite these limitations, feature ablation is a valuable tool for understanding and interpreting model behavior.

To generate the attribution maps, we will use the get_attribution_maps function as we have before, and enter the additional arguments for the feature_mask and baselines:

ablation_maps = get_attribution_maps(
attr.FeatureAblation,garbage_mdl,\
device,X_correctcls,y_correctcls,\
feature_mask=feature_mask,\
baselines=baseline_dark
)

To plot an example of the attribution map, you can copy the same code that we used for saliency, except saliency_maps is replaced by ablation_maps, and we are using the second image in the occlusion_maps array, like this:

pos = 2
orig_img = mldatasets.tensor_to_img(X_correctcls[pos], norm_std,\
norm_mean, to_numpy=True)
attr_map = mldatasets.tensor_to_img(occlusion_maps[pos],to_numpy=True,\
cmap_norm='positive')

The modified snippet outputs Figure 7.22:

![Graphical user interface

Description automatically generated with medium confidence](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_22.png)

Figure 7.22: Feature ablation maps for a white glass true positive from the test dataset

In Figure 7.22, the feature groups in the bottom of the bowl of the wine glass appear to be most important because their absence makes the biggest difference in the outcome, but other portions of the glass are also salient to a lesser degree, except the stem of the wine glass. It makes sense because a wine glass without a stem is still a glass-like container.

Next, we will discuss a similar method that will be able to show us attributions with greater detail.

Occlusion sensitivity is very similar to feature ablation because it also replaces portions of the image with a baseline. However, unlike feature ablation, it doesn’t use a feature mask to group pixels together. Instead, it groups contiguous features automatically with a sliding window and strides. In this process, it creates many overlapping regions. When this happens, it averages the output differences to compute the attribution for each pixel.

In this scenario, besides overlapping regions and their corresponding averages, occlusion sensitivity and feature ablation are identical. In fact, if we used both sliding windows and strides of 3 x 16 x 16, there wouldn’t be any overlapping areas and the feature grouping would be identical to those defined by our feature_mask made up of 16 x 16 blocks.

So, you may wonder, what’s the point of being familiar with both methods? The point is occlusion sensitivity is only suitable for use when a fixed grouping of contiguous features matter, like with images and perhaps other spatial data. And because of its use of strides, it can capture local dependencies and spatial relationships between features. However, although we used contiguous blocks of features, feature ablation doesn’t have to because the feature_mask can be arranged in whichever way it makes most sense for your inputs to be segmented. This small detail makes it very versatile to other data types. Therefore, feature ablation is a more general approach that can handle various input types and model architectures, while occlusion sensitivity is specifically tailored to image data and convolutional neural networks, with a focus on spatial relationships between features.

To generate the attribution maps for occlusion, we will do as before, and enter the additional arguments for the baselines, sliding_window_shapes, and strides:

occlusion_maps = get_attribution_maps(
attr.Occlusion, garbage_mdl,\
device,X_correctcls,y_correctcls,\
baselines=baseline_dark,\
sliding_window_shapes=(3,16,16),\
strides=(3,8,8)
)

Please note that we are creating ample overlapping regions by setting the strides to be only 8 pixels while the sliding windows are 16 pixels. To plot an attribution, you can copy the same code that we used for feature ablation, except ablation_maps is replaced by occlusion_maps. The output is depicted in Figure 7.23:

![Graphical user interface

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_23.png)

Figure 7.23: Occlusion sensitivity maps for a white glass true positive from the test dataset

With Figure 7.23, we can tell that occlusion’s attributions are eerily similar to the ablation’s attribution, except with more resolution. This resemblance shouldn’t be surprising considering how the feature mask of the former aligns with the sliding window of the latter.

Whether we use blocks of non-overlapping 16 x 16 pixels or overlapping 8 x 8, the impact of their absence is measured independently to create the attributions. Therefore, both ablation and occlusion methods aren’t equipped to measure interactions between non-contiguous feature groups. This can prove to be a problem when the absence of two non-contiguous feature groups is what causes a classification to change. For instance, can a wine glass without a stem or a base still be considered a wine glass? It can certainly be considered glass, one would hope, but perhaps the model has learned the wrong relationships.

Speaking of relationships, next, we will revisit an old friend: Shapley!

If you recall from Chapter 4, Global Model-Agnostic Interpretation Methods, Shapley has provided a method that is very good at measuring and attributing the impact of coalitions of features to the outcome. Shapley does this by permuting entire coalitions of features at a time rather than permuting one feature at a time, like the two previous methods. That way, it can tease out how more than one feature or feature group interacts with one another.

The code to create the attribution maps should be very familiar by now. This method uses the feature_mask and baselines but also the number of feature permutations tested (n_samples). This last attribute has a huge impact on the fidelity of the method. However, it can make it notoriously computationally expensive, so we are not going to run it with the default 25 samples per permutation. Instead, we will use 5 samples to make things more manageable. However, feel free to tweak it should your hardware be able to handle it:

svs_maps = get_attribution_maps(
attr.ShapleyValueSampling,garbage_mdl,\
device, X_correctcls, y_correctcls,\
baselines=baseline_dark,\
n_samples=5, feature_mask=feature_mask
)

To plot an attribution, you can copy the same snippet that we used for occlusion, except occlusion_maps is replaced by svs_maps. The output is shown in Figure 7.24:

Figure 7.24: Shapley value sampling maps for a white glass true positive from the test dataset

Figure 7.24 shows some consistent attributions, such as the most salient area being in the bottom-left corner of the wine glass bowl. Also, the base seems to be more important than the occlusion and ablation methods suggested.

However, the attributions are a lot more noisy than the previous ones. This is partially because we didn’t use a sufficient number of samples to cover all the combinations of features and interactions, and partially because of the messy nature of interactions. It makes sense that attributions for a single independent feature are concentrated in a few areas, such as the bowl of a wine glass. However, interactions can rely on several parts of the image, such as the base and the rim of the wine glass. They may become important only when they appear together. More interesting is the effect of a background. For instance, if you remove portions of the background, does the wine glass no longer look like a wine glass? Perhaps the background is more important than you think, especially when dealing with a translucent material.

Since we are on the topic of Shapley values, let’s try KernelSHAP from Chapter 4, Global Model-Agnostic Interpretation Methods. It leverages LIME to compute Shapley values more efficiently. The Captum implementation is similar to the SHAP one except it uses linear regression and not Lasso, and it computes the kernel differently. Also, for the LIME image explainer, it is best to use meaningful feature groups (called superpixels) rather than the contiguous blocks we have used in the feature mask. The same advice persists for KernelSHAP. However, we will keep this simple for this exercise, and also consistent for comparing with the other three permutation-based methods.

We will now create the attribution maps but, this time, we will do one with light baselines and another with dark ones. Because KernelSHAP is an approximation to Shapley sampling values and not as computationally expensive, we can set n_samples=300. However, this won’t necessarily guarantee high fidelity because it takes a high amount of samples in KernelSHAP to approximate what a relatively low amount of samples can do exhaustively with Shapley:

kshap_light_maps = get_attribution_maps(attr.KernelShap, garbage_mdl,\
device, X_correctcls, y_correctcls,\
baselines=baseline_light,\
n_samples=300,\
feature_mask=feature_mask)
kshap_dark_maps = get_attribution_maps(attr.KernelShap, garbage_mdl,\
device, X_correctcls, y_correctcls,\
baselines=baseline_dark,\
n_samples=300,\
feature_mask=feature_mask)

To plot an attribution, you can copy the same snippet that we used for Shapley, except svs_maps is replaced by kshap_light_maps, and we modify the code to plot the attributions with the dark baselines in the third position, like this:

axs[2].imshow(attr_dark_map)

axs[2].grid(None)

axs[2].set_title(“Kernel Shap Dark Baseline Heatmap”)

The preceding snippet outputs the plots in Figure 7.25:

![A picture containing graphical user interface

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_25.png)

Figure 7.25: KernelSHAP maps for a white glass true positive from the test dataset

The two attribution maps in Figure 7.25 are mostly not consistent with each other, but more importantly, not with the previous attributions. Sometimes, some methods have a harder time than others, or it takes some tweaking to get them to work how we expect them to.

Now, we will take everything that we have learned about perturbation-based attribution methods and use it to understand the reasons for all the chosen true positive classifications (for both white glass and batteries). As we did before, we can leverage the compare_img_pred_viz function to place the higher-resolution sample image side by side with the four attribution maps: feature ablation, occlusion sensitivity, Shapley, and KernelSHAP. First, we have to iterate all the classifications’ positions and indexes and extract all the maps. Note that we are using overlay_bg to produce a new image overlaying the original image with the heatmap for every attribution, as we did for the gradient-based section. Lastly, we concatenate the four attribution outputs into a single image (viz_img). Just as we have done before, we extract the actual label (y_true), predicted label (y_pred), and pandas series with the probabilities (probs_s) to add some context to the plot we will produce. The for loop will produce six plots, but we will only discuss two of them:

for pos, idx in enumerate(correctcls_idxs):
orig_img = mldatasets.tensor_to_img(test_400_data[idx][0],\
norm_std, norm_mean,\
to_numpy=True)
bg_img = mldatasets.tensor_to_img(test_data[idx][0],\
norm_std, norm_mean,\
to_numpy=True)
map1 = mldatasets.tensor_to_img(ablation_maps[pos],\
to_numpy=True,\
cmap_norm='positive',\
overlay_bg=bg_img)
map2 = mldatasets.tensor_to_img(svs_maps[pos], to_numpy=True,\
cmap_norm='positive',\
overlay_bg=bg_img)
map3 = mldatasets.tensor_to_img(occlusion_maps[pos],\
to_numpy=True,\
cmap_norm='positive',\
overlay_bg=bg_img)
map4 = mldatasets.tensor_to_img(kshap_dark_maps[pos],\
to_numpy=True,\
cmap_norm='positive',\
overlay_bg=bg_img)
viz_img = cv2.vconcat([
cv2.hconcat([map1, map2]),
cv2.hconcat([map3, map4])
])
label = int(y_test[idx])
y_true = labels_l[label]
y_pred = y_test_pred[idx]
probs_s = probs_df.loc[idx]
title = 'Pertubation-Based Attr for Correct classification #{}'.\
format(idx)
mldatasets.compare_img_pred_viz(orig_img, viz_img, y_true,\
y_pred, probs_s, title=title)

The preceding code snippet generates several explanations, including Figures 7.26 to 7.28. For your reference, ablation is in the top-left corner and occlusion is at the bottom left. Then, Shapley is at the top right and KernelSHAP is at the bottom right.

Overall, you can tell that ablation and occlusion are very consistent, while much less so with Shapley and KernelSHAP. However, what Shapley and KernelSHAP have in common is that the attributions are more spread out.

In Figure 7.26, all attribution methods have text highlighted, as well as, at least, the left contact of the battery. This is similar to Figure 7.28, where the text is abundantly highlighted as well as the top contact. This suggests that, for batteries, the model has learned that text and a contact matter. As for white glass, it is less clear. All the attribution methods in Figure 7.27 point to some of the edges of the broken vase, but not always the same edges (except for ablation and occlusion, which are consistent):

![Graphical user interface, application

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_26.png)

Figure 7.26: Perturbation-based attributions for battery classification #1

White glass is the hardest glass to classify of the three, and it’s not hard to tell why:

![Graphical user interface

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_27.png)

Figure 7.27: Perturbation-based attributions for white glass classification #113

As noted in Figure 7.27, and others in the test example, it’s hard for the model to distinguish white glass from the light backgrounds. It manages to classify it correctly with these examples. However, this doesn’t mean it will generalize well in other examples where glass is in shards and not as well-lit. As long as the attributions show significant influence from the background, it’s hard to trust that it can recognize glass for its specular highlights, texture, and edges alone.

![Graphical user interface

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_28.png)

Figure 7.28: Perturbation-based attributions for battery classification #2

For Figure 7.28, the background is also highlighted significantly in all attribution maps. But perhaps this is because the baseline was dark and so is the object in its entirety. If you replace an area just outside the edge of the battery with a black square, it makes sense that the model would be confused. For this reason, with permutation-based methods, it’s important to choose an appropriate baseline.

The mission was to provide an objective evaluation of the garbage classification model for the municipal recycling plant. The predictive performance on out-of-sample validation images was dismal! You could have stopped there, but then you would not have known how to make a better model.

However, the predictive performance evaluation was instrumental in deriving specific misclassifications, as well as correct classifications, to assess using other interpretation methods. To this end, you ran a comprehensive suite of interpretation methods, including activation, gradient, perturbation, and backpropagation-based methods. The consensus between all the methods was that the model was having the following issues:

  • Differentiating between the background and the objects
  • Understanding that different objects share similar color hues
  • Confounding lighting conditions, such as specular highlights as specific material characteristics, like with the wine glasses
  • An inability to separate unique features of each object, such as plastic studs in LEGO bricks from battery contacts
  • Being confused by objects with multiple materials, such as batteries contained in plastic and even cardboard packaging

To address these problems, the model needed to be trained with a more varied dataset – hopefully, one that reflects the real-world conditions of the recycling plant; for instance, the expected background (on a conveyor belt), different lighting conditions, and even objects partially occluded by hands, gloves, bags, and so on. Also, they ought to add a category for miscellaneous objects that are made up of multiple materials.

Once this dataset has been compiled, it is essential to leverage data augmentation to make the model even more robust to all sorts of variations: angle, brightness, contrast, saturation, and hue variants. And they won’t have to retrain the model from scratch! They can even fine-tune EfficientNet!

After reading this chapter, you should understand how to leverage traditional interpretation methods to more thoroughly assess predictive performance on a CNN classifier and visualize the learning process of CNNs with activation-based methods. You should also understand how to compare and contrast misclassifications and true positives with gradient-based and perturbation-based attribution methods. In the next chapter, we will study interpretation methods for NLP transformers.

  • Smilkov, D., Thorat, N., Kim, B., Viégas, F., and Wattenberg, M., 2017, SmoothGrad: Removing noise by adding noise. ArXiv, abs/1706.03825: https://arxiv.org/abs/1706.03825
  • Sundararajan, M., Taly, A., and Yan, Q., 2017, Axiomatic Attribution for Deep Networks. Proceedings of Machine Learning Research, pp. 3319–3328, International Convention Centre, Sydney, Australia: https://arxiv.org/abs/1703.01365
  • Zeiler, M.D., and Fergus, R., 2014, Visualizing and Understanding Convolutional Networks. In European conference on computer vision, pp. 818–833: https://arxiv.org/abs/1311.2901
  • Shrikumar, A., Greenside, P., and Kundaje, A., 2017, Learning Important Features Through Propagating Activation Differences: https://arxiv.org/abs/1704.02685Up to this point, we have only dealt with tabular data and, briefly, text data, in Chapter 5, Local Model-Agnostic Interpretation Methods. This chapter will exclusively explore interpretation methods that work with images and, in particular, with the Convolutional Neural Network (CNN) models that train image classifiers. Typically, deep learning models are regarded as the epitome of black box models. However, one of the benefits of a CNN is how easily it lends itself to visualization, so we can not only visualize outcomes but also every step of the learning process with activations. The possibility of interpreting these steps is rare among so-called black box models. Once we have grasped how CNNs learn, we will study how to use state-of-the-art gradient-based attribution methods, such as saliency maps and Grad-CAM to debug class attribution. Lastly, we will extend our attribution debugging know-how with perturbation-based attribution methods such as occlusion sensitivity and KernelSHAP.

These are the main topics we are going to cover:

  • Assessing the CNN classifier with traditional interpretation methods
  • Visualizing the learning process with an activation-based method
  • Evaluating misclassifications with gradient-based attribution methods
  • Understanding classifications with perturbation-based attribution methods

This chapter’s example uses the mldatasets, pandas, numpy, sklearn, tqdm, torch, torchvision, pytorch-lightning, efficientnet-pytorch, torchinfo, matplotlib, seaborn, and captum libraries. Instructions on how to install all of these libraries are in the Preface.

The code for this chapter is located here: https://packt.link/qzUvD.

Over two billion tons of waste is produced annually globally, and it’s expected to grow to over 3.5 billion tons by 2050. The alarming rise in global waste production and the need for effective waste management systems have become increasingly critical in recent years. Over half of all household trash in high-income countries is recyclable, with 20% in lower-income countries and rising. Currently, most waste ends up in landfills or incinerated, contributing to environmental pollution and climate change. This is avoidable, considering that, globally, a significant portion of all recyclable materials is not recycled.

Assuming recyclable waste is collected, it can still be hard and costly to sort it. Previously, waste classification technologies included:

  • Separating materials by size with rotating cylindrical screens with holes (“trommel screens”)
  • Separating ferrous and non-ferrous metals with magnetic forces and magnetic fields (“eddy current separators”)
  • Separating by weight with air
  • Separating by density with water (“sink-float separation”)
  • Manual sorting performed by humans

Implementing all of these techniques effectively can be challenging, even for a large, wealthy, urban municipality. To tackle this challenge, smart recycling systems have emerged, leveraging computer vision and AI to classify waste efficiently and accurately.

The development of smart recycling systems can be traced back to the early 2010s when researchers and innovators started exploring the potential of computer vision and AI to improve waste management processes. They first developed basic image recognition algorithms, utilizing features such as color, shape, and texture to identify waste materials. These systems were primarily used in research settings with limited commercial applications. As machine learning and AI became more advanced, smart recycling systems underwent significant improvements. CNNs and other deep learning techniques enabled these systems to learn from vast amounts of data and improve their waste classification accuracy. Additionally, the integration of AI-driven robotics allowed for automated sorting and handling of waste materials, increasing efficiency in recycling plants.

Costs are significantly lower than a decade ago for cameras, robots, and even chips that run deep learning models in low-latency, high-volume scenarios, making state-of-the-art smart recycling systems accessible to even smaller and poorer municipal waste management departments. One of these municipalities in Brazil is looking to revamp their 20-year-old recycling plant made up of a patchwork of machines with a collective sorting accuracy of only 70%. Human sorting can only partially compensate for the difference, leading to inevitable pollution and contamination issues. The Brazilian municipality want to replace the current system with a single conveyor belt that sorts waste efficiently from 12 different categories into bins with a series of robots.

They purchased the conveyor belt, industrial robots, and cameras. Then, they paid an AI consultancy company to develop a model to classify the recyclables. Still, they wanted models of different sizes because they weren’t sure how quickly these would run on the hardware they had.

As requested, the consultancy returned with models of various sizes between 4 and 64 million parameters. The largest model (b7) is over six times slower than the smallest one (b0). Still, the largest model has a significantly higher validation F1 score at 96% (F1 val), as opposed to approximately 90% for the smallest one:

![Chart, line chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_01.png)

Figure 7.1: F1 scores for models delivered by the AI consultancy company

The municipal leadership was delighted with the results but also surprised because the consultants asked for no domain knowledge or data to train the models, which made them very skeptical. They asked their recycling plant workers to test the models with a batch of recyclables. They got a 25% misclassification rate with that one batch.

To seek a second opinion and an honest evaluation of the model, the municipality has approached another AI consultancy firm – yours!

The first order of business was to assemble a test dataset that was more realistic of the edge cases that the recycling plant workers found among the misclassifications. Your colleague obtained F1 scores with the test dataset between 62% and 66% (F1 test). Next, they have asked you to understand what’s causing those misclassifications.

No single interpretation method is perfect, and even the best scenario can only tell you one part of the story. Therefore, you have decided to, first, assess the model’s predictive performance using traditional interpretation methods, including the following:

  • ROC curves and ROC-AUC
  • Confusion matrices and some metrics derived from them, such as accuracy, precision, recall, and F1

Then, you’ll examine the model using an activation-based method:

  • Intermediate activation

This is followed by evaluating decisions with three gradient-based methods:

  • Saliency maps
  • Grad-CAM
  • Integrated gradients

And a backpropagation-based method:

  • DeepLIFT

This is followed by three perturbation-based methods:

  • Occlusion sensitivity
  • Feature ablation
  • Shapley value sampling

I hope that you understand why the model is not performing as it should and how to fix it by the end of this process. You can also leverage the many plots and visualizations you will produce to communicate this story to the municipality’s executives.

You will find most of the code for this example here: https://github.com/PacktPublishing/Interpretable-Machine-Learning-with-Python-2E/blob/main/07/GarbageClassifier.ipynb

To run this example, you need to install the following libraries:

  • torchvision to load the dataset
  • mldatasets, pandas, numpy, and sklearn (scikit-learn) to manipulate the dataset
  • torch, pytorch-lightning, efficientnet-pytorch, and torchinfo to predict with the models and show info about the models
  • matplotlib, seaborn, cv2, tqdm, and captum to make and visualize the interpretations

You should load all of them first:

import math
import os, gc
import random
import mldatasets
import numpy as np
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
import torchvision
import torch
import pytorch_lightning as pl
import efficientnet_pytorch
from torchinfo import summary
import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable
from matplotlib.colors import LinearSegmentedColormap
import seaborn as sns
import cv2
from tqdm.notebook import tqdm
from captum import attr

Next, we will load and prepare the data.

The data used to train the model is publicly available at Kaggle (https://www.kaggle.com/datasets/mostafaabla/garbage-classification). It’s called “Garbage Classification” and is a compilation of several different online sources, including web scraping. It has already been split into training and test datasets and also comes with an additional smaller test dataset taken from Wikimedia Commons that your colleague used to test the models. These test images come in a slightly higher resolution too.

We download the data from a ZIP file like this:

dataset_file = "garbage_dataset_sample"
dataset_url = f"https://github.com/PacktPublishing/Interpretable-Machine-Learning-with-Python-2E/raw/main/datasets/{dataset_file}.zip"
torchvision.datasets.utils.download_url(dataset_url, ".")
torchvision.datasets.utils.extract_archive(f"{dataset_file}.zip",\
remove_finished=True)

It will also extract the ZIP file into four folders corresponding to the three datasets and the larger resolution test dataset. Please note that garbage_dataset_sample has only a fraction of the training and validation datasets. If you want to download the full datasets, then use dataset_file = "garbage_dataset". It won’t impact the size of the test dataset either way. Next, we can initialize the transformation and loading of the datasets like this:

X_train, norm_mean = (0.485, 0.456, 0.406)
norm_std = (0.229, 0.224, 0.225)
transform = torchvision.transforms.Compose(
[
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(norm_mean, norm_std),
]
)
train_data = torchvision.datasets.ImageFolder(
f"{dataset_file}/train", transform
)
val_data = torchvision.datasets.ImageFolder(
f"{dataset_file}/validation", transform
)
test_data = torchvision.datasets.ImageFolder(
f"{dataset_file}/test", transform
)
test_400_data = torchvision.datasets.ImageFolder(
f"{dataset_file}/test_400", transform
)

What the above code does is compose a series of standard transforms such as normalization and converting images to tensors. Then, it instantiates PyTorch datasets corresponding to each folder – that is, one for the training, validation, and test datasets, as well as the larger resolution test dataset (test_400_data). These datasets also include transforms. That way, each time an image is loaded from one of the datasets, it is automatically transformed. We can verify that the shapes of the datasets match our expectations with the following code:

print(f"# Training Samples: \t{len(train_data)}")
print(f"# Validation Samples: \t{len(val_data)}")
print(f"# Test Samples: \t{len(test_data)}")
print(f"Sample Dimension: \t{test_data[0][0].shape}")
print("="*50)
print(f"# Test 400 Samples: \t{len(test_400_data)}")
print(f"# 400 Sample Dimension:\t{test_400_data[0][0].shape}")

The preceding code outputs the number of images in each dataset and the dimensions of the images in the datasets. You can tell that there are over 3,700 training images, 900 validation images, and 120 test images of 3 x 224 x 224 dimensions. The first number corresponds to the channels (red, green, and blue) and the following two to the width and height in pixels, which is what the model uses for inference. The Test 400 dataset is the same as the Test dataset, the except images have a larger height and width. We won’t need the Test 400 dataset for inference, so it’s Okay that it doesn’t meet the model’s dimension requirements:

Sample Dimension: torch.Size([3, 224, 224])

==================================================

400 Sample Dimension: torch.Size([3, 400, 400])

Section titled “400 Sample Dimension: torch.Size([3, 400, 400])”

If you print(test_data[0]), you’ll notice that it will first output a tensor with the image and then a single integer, which we call a scalar. This integer is a number between 0 and 11, which corresponds to the labels used. For quick reference, these are the 12 labels:

labels_l = ['battery', 'biological', 'brown-glass', 'cardboard',\
'clothes', 'green-glass', 'metal', 'paper', 'plastic',\
'shoes', 'trash', 'white-glass']

Interpreting often involves taking single samples and extracting them from the dataset to later perform inference with the model. To that end, it’s important to get familiar with extracting any image from the dataset, say the very first sample from the test dataset:

tensor, label = test_400_data[0]
img = mldatasets.tensor_to_img(tensor, norm_std, norm_mean)
plt.figure(figsize=(5,5))
plt.title(labels_l[label], fontsize=16)
plt.imshow(img)
plt.show()

In the preceding snippet, we are taking the first sample (0) from the higher resolution version of the test dataset (test_400_data) and extracting the tensor and label portion from it. Then, we are using the convenience function tensor_to_img to convert the PyTorch tensor to a numpy array but also reversing the standardization that had been previously performed on the tensor. Then, we plot the image with matplotlib’s imshow and use the labels_l list to convert the label into a string, which we print in the title. The result can be seen in Figure 7.2:

![A picture containing diagram

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_02.png)

Figure 7.2: A test sample for a recyclable alkaline battery

Another preprocessing step we will need to perform is the One-Hot Encoding (OHE) of the y labels because we will need the OHE form to evaluate the model’s predictive performance. Once we initialize the OneHotEncoder, we will need to fit it to the test labels (y_test) in array format. But first, we will need to put the test labels into a list (y_test). We can do the same with the validation labels because these will also be useful for easy evaluation:

y_test = np.array([l for _, l in test_data])
y_val = np.array([l for _, l in val_data])
ohe = OneHotEncoder(sparse=False).\
fit(np.array(y_test).reshape(-1, 1))

Also, for the sake of reproducibility, always initialize your random seeds like this:

rand = 42
os.environ['PYTHONHASHSEED']=str(rand)
np.random.seed(rand)
random.seed(rand)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if device == 'cuda':
torch.cuda.manual_seed(rand)
else:
torch.manual_seed(rand)

It is acknowledged that determinism is very difficult with deep learning and is often session-, platform-, and architecture-dependent. If you are using an NVIDIA GPU, you can attempt to use PyTorch to avoid nondeterministic algorithms with the command torch.use_deterministic_algorithms(True). It’s not a guarantee, but it will throw an error when the operation that you are attempting can’t be accomplished deterministically. If it succeeds, it will be much slower. It’s only worth it if you need to make model outcomes identical – for instance, for scientific research or regulatory compliance. For further details about reproducibility and PyTorch, look here: https://pytorch.org/docs/stable/notes/randomness.html.

Now, let’s take a peek at what images are in our datasets. We know that the training and validation datasets are very similar, so we will start with the validation dataset. We can iterate every class in labels_l and randomly select a single one from the validation dataset with np.random.choice. We place each image on a 4 × 3 grid with the class label above it:

plt.subplots(figsize=(14,10))
for c, category in enumerate(labels_l):
plt.subplot(3, 4, c+1)
plt.title(labels_l[c], fontsize=12)
idx = np.random.choice(np.where(y_test==c)[0], 1)[0]
im = mldatasets.tensor_to_img(test_data[idx][0], norm_std,\
norm_mean)
plt.imshow(im, interpolation='spline16')
plt.axis("off")
plt.show()

The preceding code generates Figure 7.3. You can tell that there is significant pixelation around the edges of the items; some items appear much darker than others, and some of the pictures are from odd angles:

![Graphical user interface

Description automatically generated with medium confidence](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_03.png)

Figure 7.3: A random sample of the validation dataset

Let’s now do the same for the test dataset to compare it to the validation/training datasets. We can use the same code as before, except we replace y_val with y_test, and val_data with test_data. The resulting code generates Figure 7.4. You can tell that the test set has less pixelated and more consistently lit items, mostly from the top- and side-facing angles:

![A picture containing text, different, various

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_04.png)

Figure 7.4: A random sample of the test dataset

We won’t need to train a CNN in this chapter. Thankfully, it has been provided to us by the client.

The models trained by the other consultancy company are fine-tuned EfficientNet models. In other words, the AI consultancy company took a previously trained model with the EfficientNet architecture and trained it further with the garbage classification dataset. This technique is called transfer learning because it allows a model to utilize previously learned knowledge from a large dataset (in this case, a million images from the ImageNet database) and apply it to new tasks with smaller datasets. The advantage is it significantly reduces training time and computational resources while maintaining high performance because it has already learned to extract useful features from images, which can be a valuable starting point for a new task and only needs to adapt to the specific task at hand.

It makes sense that they chose EfficientNet. After all, EfficientNet is a family of CNNs introduced by Google AI researchers in 2019. The key innovation of EfficientNet is its compound scaling method, which enables the model to achieve higher accuracy and efficiency than other CNNs. In addition, it is based on the observation that different dimensions of the model, such as width, depth, and resolution, contribute to the overall performance in a balanced way. The EfficientNet architecture is built upon a baseline model called EfficientNet-B0. A compound scaling method is employed to create larger and more powerful versions of the baseline model, which simultaneously scales up the width, depth, and resolution of the network. This results in a series of models, EfficientNet-B1 to EfficientNet-B7, with increasing capacity and performance. The largest model, EfficientNet-B7, has achieved state-of-the-art performance on several benchmarks, such as ImageNet.

Before we can load the model, we must define the class for EfficientLite – a class that inherits from PyTorch Lightning’s pl.LightningModule. This class is designed to create a custom model based on the EfficientNet architecture, train it, and perform inference. We only need it for the latter, which is why we have also adapted it to include a predict() function – much like scikit-learn models do for the convenience of being able to use similar evaluation functions to would with these models:

class EfficientLite(pl.LightningModule):
def __init__(self, lr: float, num_class: int,\
pretrained="efficientnet-b0", *args, **kwargs):
super().__init__()
self.save_hyperparameters()
self.model = efficientnet_pytorch.EfficientNet.\
from_pretrained(pretrained)
in_features = self.model._fc.in_features
self.model._fc = torch.nn.Linear(in_features, num_class)
def forward(self, x):
return self.model(x)
def predict(self, dataset):
self.model.eval()
device = torch.device("cuda" if torch.cuda.is_available()\
else "cpu")
with torch.no_grad():
if isinstance(dataset, np.ndarray):
if len(dataset.shape) == 3:
dataset = np.expand_dims(dataset, axis=0)
dataset = [(x,0) for x in dataset]
loader = torch.utils.data.DataLoader(dataset,\
batch_size=32)
probs = None
for X_batch, _ in tqdm(loader):
X_batch = X_batch.to(device, dtype=torch.float32)
logits_batch = self.model(X_batch)
probs_batch = torch.nn.functional.softmax(logits_batch,\
dim=1).cpu().detach().numpy()
if probs is not None:
probs = np.concatenate((probs, probs_batch))
else:
probs = probs_batch
clear_gpu_cache()
return probs

You will notice that the class has three functions:

  • __init__: This is the constructor for the EfficientLite class. It initializes the model by loading a pretrained EfficientNet model using the efficientnet_pytorch.EfficientNet.from_pretrained() method. It then replaces the last fully connected layer (_fc) with a new torch.nn.Linear layer that has the same number of input features but a different number of output features equal to the number of classes (num_class).
  • forward: This method defines the forward pass of the model. It takes an input tensor x and passes it through the model, returning the output.
  • predict: This method takes a dataset and performs inference using the trained model. It first sets the model to evaluation mode (self.model.eval()). The input dataset is converted into a DataLoader object with a batch size of 32. The method iterates over the DataLoader, processing each batch of data and computing probabilities using the softmax function. The clear_gpu_cache() function is called after each iteration to release unused GPU memory. Finally, the method returns the computed probabilities as a numpy array.

If you are using a CUDA-enabled GPU, there’s a utility function called clear_gpu_cache(), which is run every time there’s a GPU-intensive operation. Depending on how powerful your GPU is, you may need to run it more often. Feel free to use another convenience function, print_gpu_mem_used(), to check how much GPU memory is utilized at any given moment or to print the entire summary with print(torch.cuda.memory_summary()). The next code downloads the pre-trained EfficientNet model, loads the model weights to EfficientLite, and prepares the model for inference. Lastly, it prints a summary:

model_weights_file = "garbage-finetuned-efficientnet-b4"
model_url = f"https://github.com/PacktPublishing/Interpretable-Machine-Learning-with-Python-2E/raw/main/models/{model_weights_file}.ckpt"
torchvision.datasets.utils.download_url(model_url, ".")
garbage_mdl = EfficientLite.load_from_checkpoint(
f"{model_weights_file}.ckpt"
)
garbage_mdl = garbage_mdl.to(device).eval()
print(summary(garbage_mdl))

The code is pretty straightforward but what’s important to note is that we are choosing the b4 model for this chapter, which is in between b0 and b7 in terms of size, speed, and accuracy. You can change the last digit according to your hardware’s abilities, but it might change some of the outcomes of this chapter’s code. The preceding snippet outputs the following summary:

=======================================================================Layer (type:depth-idx) Param # =======================================================================EfficientLite — ├─EfficientNet: 1-1 – │ └─Conv2dStaticSamePadding: 2-1 1,296 │ │ └─ZeroPad2d: 3-1 – │ └─BatchNorm2d: 2-2 96 │ └─ModuleList: 2-3 – │ │ └─MBConvBlock: 3-2 2,940 │ │ └─MBConvBlock: 3-3 1,206 │ │ └─MBConvBlock: 3-4 11,878 │ │ └─MBConvBlock: 3-5 18,120 │ │ └─MBConvBlock: 3-6 18,120 │ │ └─MBConvBlock: 3-7 18,120 │ │ └─MBConvBlock: 3-8 25,848 │ │ └─MBConvBlock: 3-9 57,246 │ │ └─MBConvBlock: 3-10 57,246 │ │ └─MBConvBlock: 3-11 57,246 │ │ └─MBConvBlock: 3-12 70,798 │ │ └─MBConvBlock: 3-13 197,820 │ │ └─MBConvBlock: 3-14 197,820 │ │ └─MBConvBlock: 3-15 197,820 │ │ └─MBConvBlock: 3-16 197,820 │ │ └─MBConvBlock: 3-17 197,820 │ │ └─MBConvBlock: 3-18 240,924 │ │ └─MBConvBlock: 3-19 413,160 │ │ └─MBConvBlock: 3-20 413,160 │ │ └─MBConvBlock: 3-21 413,160 │ │ └─MBConvBlock: 3-22 413,160 │ │ └─MBConvBlock: 3-23 413,160 │ │ └─MBConvBlock: 3-24 520,904 │ │ └─MBConvBlock: 3-25 1,159,332 │ │ └─MBConvBlock: 3-26 1,159,332 │ │ └─MBConvBlock: 3-27 1,159,332 │ │ └─MBConvBlock: 3-28 1,159,332 │ │ └─MBConvBlock: 3-29 1,159,332 │ │ └─MBConvBlock: 3-30 1,159,332 │ │ └─MBConvBlock: 3-31 1,159,332 │ │ └─MBConvBlock: 3-32 1,420,804 │ │ └─MBConvBlock: 3-33 3,049,200 │ └─Conv2dStaticSamePadding: 2-4 802,816 │ │ └─Identity: 3-34 – │ └─BatchNorm2d: 2-5 3,584 │ └─AdaptiveAvgPool2d: 2-6 – │ └─Dropout: 2-7 – │ └─Linear: 2-8 21,516 │ └─MemoryEfficientSwish: 2-9

Section titled “=======================================================================Layer (type:depth-idx) Param # =======================================================================EfficientLite — ├─EfficientNet: 1-1 – │ └─Conv2dStaticSamePadding: 2-1 1,296 │ │ └─ZeroPad2d: 3-1 – │ └─BatchNorm2d: 2-2 96 │ └─ModuleList: 2-3 – │ │ └─MBConvBlock: 3-2 2,940 │ │ └─MBConvBlock: 3-3 1,206 │ │ └─MBConvBlock: 3-4 11,878 │ │ └─MBConvBlock: 3-5 18,120 │ │ └─MBConvBlock: 3-6 18,120 │ │ └─MBConvBlock: 3-7 18,120 │ │ └─MBConvBlock: 3-8 25,848 │ │ └─MBConvBlock: 3-9 57,246 │ │ └─MBConvBlock: 3-10 57,246 │ │ └─MBConvBlock: 3-11 57,246 │ │ └─MBConvBlock: 3-12 70,798 │ │ └─MBConvBlock: 3-13 197,820 │ │ └─MBConvBlock: 3-14 197,820 │ │ └─MBConvBlock: 3-15 197,820 │ │ └─MBConvBlock: 3-16 197,820 │ │ └─MBConvBlock: 3-17 197,820 │ │ └─MBConvBlock: 3-18 240,924 │ │ └─MBConvBlock: 3-19 413,160 │ │ └─MBConvBlock: 3-20 413,160 │ │ └─MBConvBlock: 3-21 413,160 │ │ └─MBConvBlock: 3-22 413,160 │ │ └─MBConvBlock: 3-23 413,160 │ │ └─MBConvBlock: 3-24 520,904 │ │ └─MBConvBlock: 3-25 1,159,332 │ │ └─MBConvBlock: 3-26 1,159,332 │ │ └─MBConvBlock: 3-27 1,159,332 │ │ └─MBConvBlock: 3-28 1,159,332 │ │ └─MBConvBlock: 3-29 1,159,332 │ │ └─MBConvBlock: 3-30 1,159,332 │ │ └─MBConvBlock: 3-31 1,159,332 │ │ └─MBConvBlock: 3-32 1,420,804 │ │ └─MBConvBlock: 3-33 3,049,200 │ └─Conv2dStaticSamePadding: 2-4 802,816 │ │ └─Identity: 3-34 – │ └─BatchNorm2d: 2-5 3,584 │ └─AdaptiveAvgPool2d: 2-6 – │ └─Dropout: 2-7 – │ └─Linear: 2-8 21,516 │ └─MemoryEfficientSwish: 2-9”

Total params: 17,570,132 Trainable params: 17,570,132 Non-trainable params: 0 ======================================================================

It has pretty much everything we need to know about the model. It has two custom convolutional layers (Conv2dStaticSamePadding), each followed by a batch normalization layer (BatchNorm2d) and 32 MBConvBlock modules.

The network also has a memory-efficient implementation of the Swish activation function (MemoryEfficientSwish), which, like all activation functions, introduces non-linearity into the model. It’s smooth and non-monotonic, which helps it converge more quickly while learning more complex and nuanced patterns. It also has a global average pooling operation (AdaptiveAvgPool2d), which reduces the spatial dimensions of the feature maps. It then has a first Dropout layer for regularization, followed by a fully connected layer (Linear) that takes it from 1792 nodes to 12. Dropout prevents overfitting by making a fraction of the neurons inactive in each update cycle. If you want to see more details of how the output shape of each layer gets reduced between one layer and another, enter the input_size into the summary – like summary(garbage_mdl, input_size=(64, 3, 224, 224)) – because the network was designed with a batch size of 64 in mind. Don’t worry if none of these terms sound familiar to you. We will revisit them later.

Assessing the CNN classifier with traditional interpretation methods

Section titled “Assessing the CNN classifier with traditional interpretation methods”

We will first evaluate the model using the validation dataset with the evaluate_multiclass_mdl function. The arguments include the model (garbage_mdl), our validation data (val_data), as well as the class names (labels_l) and the encoder (ohe). Lastly, we won’t plot the ROC curves (plot_roc=False). This function returns the predicted labels and probabilities, which we can store in variables for later use:

y_val_pred, y_val_prob = mldatasets.evaluate_multiclass_mdl(
garbage_mdl, val_data,\
class_l=labels_l, ohe=ohe, plot_roc=False
)

The preceding code generates both Figure 7.5 with a confusion matrix and Figure 7.6 with performance metrics for each class:

![Graphical user interface, text, application, email

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_05.png)

Figure 7.5: The confusion matrix for the validation dataset

Even though the confusion matrix in Figure 7.5 seems to suggest a perfect classification, once you see the precision and recall breakdown in Figure 7.6, you can tell that the model had issues with metal, plastic, and white glass:

![A picture containing text, receipt

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_06.png)

Figure 7.6: The classification report for the validation dataset

You can expect a model to always reach 100% training accuracy if you train it for enough epochs using optimal hyperparameters. A near-perfect validation accuracy is harder to achieve, depending on how different these two are. We know that the validation dataset is simply a sample of images from the same collection, so it’s not particularly surprising that 94.7% was achieved.

Now, let’s repeat the same code snippet for the test dataset. This time, we want to see the ROC curves (plot_roc=True) but only the averages, and not on a class-by-class basis (plot_roc_class=False) because there are only four pictures per class. Given the small number of samples, we can display the numbers in the confusion matrix rather than percentages (pct_matrix=False):

y_test_pred, y_test_prob = mldatasets.evaluate_multiclass_mdl(
garbage_mdl, test_data,\
class_l=labels_l, ohe=ohe,\
plot_roc=True, plot_roc_class=False, pct_matrix=False
)

The preceding code snippet generated the ROC curve in Figure 7.7, the confusion matrix in Figure 7.8, and the classification report in Figure 7.9:

![Chart, line chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_07.png)

Figure 7.7: The ROC curve for the test dataset

The test ROC plot (Figure 7.7) shows the macro-average and micro-average ROC curves. The difference in both of these is in how they are calculated. Macro metrics are computed for each class independently and then averaged, treating each differently, whereas micro-averages factor in the contribution or representation of each class; generally, micro-averages are more reliable.

![Chart, scatter chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_08.png)

Figure 7.8: The confusion matrix for the test dataset

If we take a look at the confusion matrix in Figure 7.8, we can tell that only biological, green glass, and shoes are getting 10-out-of-10 classifications. However, a lot of items are being misclassified as biologicals and shoes. On the other hand, many items are more often than not misclassified, such as metal, paper, and plastic. Many of them are similar in shape or color, so you could understand how that would happen, but how does a piece of metal get confused with white glass, or paper with a battery?

![Table

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_09.png)

Figure 7.9: The predictive performance metrics for the test dataset

When classification models are discussed in a business setting, stakeholders are often only interested in one number: accuracy. It’s easy to let this drive the discussion, but there’s much more nuance to it. For instance, the disappointing test accuracy (68.3%) could mean many things. It could mean that six classes are getting perfect classification, and all others are not, or that 12 classes are getting only half misclassified. There are many possibilities of what could be going on.

In any case, when dealing with a multiclass classification problem, even an accuracy below 50% might not be as bad as it seems. Consider that the no information rate represents the accuracy that can be achieved by a naive model that always predicts the most frequent class in the dataset. It serves as a benchmark to ensure that the developed model is providing insights beyond this simplistic approach. And with 12 evenly split, the no information rate is likely to be around 8.33% (100%/12 classes), so 68% is still orders of magnitude higher than that. In fact, there is less of a leap to 100%! To a machine learning practitioner, this means that if we judge solely based on test accuracy results, the model is still learning something of value that can be improved upon.

In any case, the predictive performance metrics in Figure 7.9 for the test dataset are consistent with what we saw in the confusion matrix. Biological gets high recall but low precision and metal, paper, plastic, and trash are low for both.

Determining what misclassifications to focus on

Section titled “Determining what misclassifications to focus on”

We have already noticed some exciting misclassifications we can focus on:

  • Metal false positives: 16 out of the 120 samples in the test dataset were misclassified as metal. That’s 42% of all misclassifications! What is it about metal that renders it so easily confused with other garbage according to the model?
  • Plastic false negatives: 70% of all true plastic samples were misclassified. Thus, plastics had the lowest recall of any material besides trash. It’s easy to tell why trash would be so difficult to classify because it’s exceedingly diverse but not plastic.

We should also examine some true positives to contrast these misclassifications. Namely, batteries because they get many false positives as metals and plastic, and white glass because it gets false negatives as metals 30% of the time. Since there are so many metal false positives, we should narrow them down to just those that are for batteries.

To visualize the tasks ahead, we can create a DataFrame (preds_df) with the true labels (y_true) in one column and predicted labels in another (y_pred). And to understand how certain the models are of these predictions, we can create another DataFrame with the probabilities (probs_df). We can generate column totals for these probabilities to sort the columns according to which category the model is most certain about across all samples. Then, we can concatenate our predictions DataFrame with the first 12 columns from our probabilities DataFrame:

preds_df = pd.DataFrame({'y_true':[labels_l[o] for o in y_test],\
'y_pred':y_test_pred})
probs_df = pd.DataFrame(y_test_prob*100).round(1)
probs_df.loc['Total']= probs_df.sum().round(1)
probs_df.columns = labels_l
probs_df = probs_df.sort_values('Total', axis=1, ascending=False)
probs_df.drop(['Total'], axis=0, inplace=True)
probs_final_df = probs_df.iloc[:,0:12]
preds_probs_df = pd.concat([preds_df, probs_final_df], axis=1)

Let’s now output the DataFrame with color coding for the prediction instances we are interested in assessing. On one hand, we have the metal false positives and, on the other, the plastic false negatives. But we also have the true positives for battery and white glass. Lastly, we have bolded all probabilities over 50% and hidden all probabilities of 0% so that it’s easier to spot any predictions with high probabilities:

num_cols_l = list(preds_probs_df.columns[2:])
num_fmt_dict = dict(zip(num_cols_l, ["{:,.1f}%"]*len(num_cols_l)))
preds_probs_df[
(preds_probs_df.y_true!=preds_probs_df.y_pred)
| (preds_probs_df.y_true.isin(['battery', 'white-glass']))
].style.format(num_fmt_dict).apply(
lambda x: ['background: lightgreen' if (x[0] == x[1])\
else '' for i in x], axis=1
).apply(
lambda x: ['background: orange' if (x[0] != x[1] and\
x[1] == 'metal' and x[0] == 'battery')\
else '' for i in x], axis=1
).apply(
lambda x: ['background: yellow' if (x[0] != x[1] and\
x[0] == 'plastic')\
else '' for i in x], axis=1
).apply(
lambda x: ['font-weight: bold' if isinstance(i, float)\
and i >= 50\
else '' for i in x], axis=1
).apply(
lambda x: ['color:transparent' if i == 0.0\
else '' for i in x], axis=1)

The preceding code snippet produces Figure 7.10. We can tell by the highlights which are the metal false positives and the plastic false negatives, as well as which would be the true positives: #0-6 for battery, and #110-113 and #117-119 for white glass:

![Table

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_10.png)

Figure 7.10: Table with all 38 misclassifications in the test dataset, selected true positives, and their true and predicted labels, as well as their predicted probabilities

We can easily store the indexes for these instances in lists with the following code. That way, for future reference, we can iterate through these lists to assess individual predictions or subset arrays with them to perform interpretation tasks for the entire group. As you can tell, we have lists for all four groups:

plastic_FN_idxs = preds_df[
(preds_df['y_true'] !=preds_df['y_pred'])
& (preds_df['y_true'] == 'plastic')
].index.to_list()
metal_FP_idxs = preds_df[
(preds_df['y_true'] != preds_df['y_pred'])
& (preds_df['y_pred'] == 'metal')
& (preds_df['y_true'] == 'battery')
].index.to_list()
battery_TP_idxs = preds_df[
(preds_df['y_true'] ==preds_df['y_pred'])
& (preds_df['y_true'] == 'battery')
].index.to_list()
wglass_TP_idxs = preds_df[
(preds_df['y_true'] == preds_df['y_pred'])
& (preds_df['y_true'] == 'white-glass')
].index.to_list()

Now that we have all our data preprocessed, the model is fully loaded and lists the groups of predictions to debug. Now we can move forward. Let the interpretation begin!

Visualizing the learning process with activation-based methods

Section titled “Visualizing the learning process with activation-based methods”

Before we get into discussing activations, layers, filters, neurons, gradients, convolutions, kernels, and all the fantastic elements that make up a CNN, let’s first briefly revisit the mechanics of a CNN and one in particular.

The convolution layer is the essential building block of a CNN, which is a sequential neural network. It convolves the input with learnable filters, which are relatively small but are applied across the entire width, height, and depth at specific distances or strides. Each filter produces a two-dimensional activation map (also known as a feature map). It’s called an activation map because it denotes positions of activations in the images – in other words, where specific “features” are located. In this context, a feature is an abstract spatial representation that, downstream in the process, is reflected in the learned weights of fully connected (linear) layers. For instance, in the garbage CNN case, the first convolutional layer has 48 filters with a 3 × 3 kernel, a 2 × 2 stride, and static padding, which ensure that the output maps maintain the same size as the inputs. Filters are template matching because they end up activating areas of the activation map when certain patterns are found in the input image.

But before we get to our fully connected layers, we have to reduce the dimensions of our filters until they have a workable size. For instance, if we flattened the output of our first convolution (48 × 112 × 112), we would have over 602,000 features. I think we can all agree that that would be too much to feed into a fully connected layer. Even if we used enough neurons to handle this workload, we probably wouldn’t have captured enough spatial representations for the neural network to make sense of the images. For this reason, convolutional layers are often paired with pooling layers, which downsample the input – in other words, they reduce the dimensionality of the data. In this case, there’s an adaptive average pooling layer (AdaptiveAvgPool2d) that performs an average across all the channels as well as many pooling layers within the Mobile Inverted Bottleneck Convolution Blocks (MBConvBlock).

Incidentally, MBConvBlock, Conv2dStaticSamePadding, and BatchNorm2d are the building blocks of the EfficientNet architecture. These components work together to create a highly efficient and accurate convolutional neural network:

  • MBConvBlock: Mobile inverted bottleneck convolution blocks that form the core of the EfficientNet architecture. In traditional convolutional layers, filters are applied across all input channels simultaneously, resulting in a high number of computations, but MBConvBlocks divide the process into two steps: first, they apply depthwise convolutions that handle each input channel separately, and then use pointwise (1 x 1) convolutions to combine the information from different channels. For this reason, inside the MBConvBlock modules for B0, there are three convolutional layers: a depthwise convolution, a pointwise (1 x 1) convolution (called project convolution), and another pointwise (1 x 1) convolution (called expand convolution) in some blocks. However, the first block only contains two convolutional layers (depthwise and project convolutions) because it doesn’t have an expand convolution. For B4, the architecture is similar except more convolutions are stacked in each block and there are twice as many MBConvBlocks. Naturally, B7 has many more blocks and convolutional layers. For B4, there are a total of 158 convolutional operations between the 32 MBConvBlocks.
  • Conv2dStaticSamePadding: Unlike traditional convolutional layers (such as Conv2d), these don’t reduce the dimensions. It ensures the input and output feature maps have the same spatial dimensions.
  • BatchNorm2d: Batch normalization layers that help stabilize and accelerate training by normalizing the input features, which helps keep the distribution of the input features consistent during training.

Once the over 230 convolutional and pooling operations are performed, we are left with a flattened output of a more workable size: 1,792 features, which the fully connected layer converts into 12, which, leveraging softmax activation, outputs probabilities between 0 and 1 for each of the classes. In the garbage CNN, there is a dropout layer involved to help regularize the training. We can ignore this entirely because, for inference, they are ignored.

If this wasn’t entirely clear, don’t fret! The sections that follow will demonstrate visually through activations, gradients, and perturbations how the network probably learned or did not learn image representations.

For inference, the image goes through the network’s input and the prediction comes out through the output traversing every single layer. However, one of the advantages of having a sequential and layered architecture is that we can extract any layer’s output and not just the final layer. The intermediate activations are simply the outputs of any of the convolution or pooling layers. They are activation maps because, after an activation function has been applied, the brighter spots map to the image’s features. In this case, the model used ReLU on all convolutional layers, so that is what activates the spots. We are only interested in the convolutional layers’ intermediate activations because the pooling layers are simply downsampled versions of these ones. Why not see the higher-resolution version instead?

As the filters become smaller in width and height, the learned representations will be larger. In other words, the first convolutional layer may be about details such as texture, the following one about edges, and the last one about shapes. We must then flatten the convolutional layers’ output to feed it to the multilayer perceptron that takes over from then on.

What we will do now is extract activations for some of the convolutional layers. In B4, there are 158, so we can’t do all of them! To this end, we will obtain the first level of layers with model.children(), and iterate across them. We will append the two Conv2dStaticSamePadding layers from this top level into a conv_layers list. But we will also go deeper, appending the first convolutional layer for the first six MBConvBlock layers in the ModuleList layers. In the end, we should have eight convolutional layers – the six in the middle belonging to Mobile Inverted Bottleneck Convolution blocks:

conv_layers = []
model_children = list(garbage_mdl.model.children())
for model_child in model_children:
if (type(model_child) ==\
efficientnet_pytorch.utils.Conv2dStaticSamePadding):
conv_layers.append(model_child)
elif (type(model_child) == torch.nn.modules.container.ModuleList):
module_children = list(model_child.children())
module_convs = []
for module_child in module_children:
module_convs.append(list(module_child.children())[0])
conv_layers.extend(module_convs[:6])
print(conv_layers)

Before we iterate across all of them producing activation maps for each convolutional layer, let’s do it for a single filter and layer:

idx = battery_TP_idxs[0]
tensor = test_data[idx][0][None, :].to(device)
label = y_test[idx]
method = attr.LayerActivation(garbage_mdl, conv_layers[layer]
attribution = method.attribute(tensor).detach().cpu().numpy()
print(attribution.shape)

The preceding snippet extracts the tensor for the first battery true positive (battery_TP_idxs[0]). Then, it initializes the LayerActivation attribution method with the model (garbage_mdl) and the first convolutional layer (conv_layers[0]). Using the attribute function, it creates an attribution with this method. For the shape of the attribution, we should get (1, 48, 112, 112). The tensor was for a single image, so it makes sense that the first number is a one. The next number corresponds to the number of filters, followed by the width and height dimensions of each filter. Regardless of the kind of attribution, the numbers inside each attribution relate to how a pixel in the input is seen by the model. Interpretation varies according to the method. However, generally, it is interpreted that higher numbers mean more of an impact on the outcome, but attributions may also have negative numbers, which mean the opposite.

Let’s visualize the first filter, but before we do that, we must decide what colormap to use. A colormap will determine what colors to assign to different numbers as a gradient. For instance, the following colormap has white for 0 (#ffffff in hexadecimal), a medium gray for 0.25, and black (#000000 in hexadecimal) for 1 with a gradient between these colors:

cbinary_cmap = LinearSegmentedColormap.from_list('custom binary',
[(0, '#ffffff'),
(0.25, '#777777'),
(1, '#000000')])

You can also use any of the named colormaps from https://matplotlib.org/stable/tutorials/colors/colormaps.html, rather than using your own. Next, let’s plot the attribution for the first filter like this:

filter = 0
filter_attr = attribution[0,filter]
filter_attr = mldatasets.apply_cmap(filter_attr, cbinary_cmap, 'positive')
y_true = labels_l[label]
y_pred = y_test_pred[idx]
fig, ax = plt.subplots(1, 1, figsize=(8, 6))
fig.suptitle(f"Actual label: {y_true}, Predicted: {y_pred}", fontsize=16)
ax.set_title(
f"({method.get_name()} Attribution for Filter #{filter+1} for\
Convolutional Layer #{layer+1})",
fontsize=12
)
ax.imshow(filter_attr)
ax.grid(False)
fig.colorbar(
ScalarMappable(norm='linear', cmap=cbinary_cmap),
ax=ax,
orientation="vertical"
)
plt.show()

The code saves the first filter for the first image from the attribution to filter_attr and then leverages the apply_cmap utility function to convert the attribution array to a normalized colormap, which is then plotted with imshow. The rest of the code plots the title with the actual and predicted label for the image and a colorbar with the colormap. The snippet will output Figure 7.11:

![Diagram

Description automatically generated with low confidence](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_11.png)

Figure 7.11: Intermediate activation map for the first filter for the first convolutional layer for the first true positive battery sample

As you can tell in Figure 7.11, it seems like the intermediate activations for the first filter are finding the edges of the battery and the most prominent text.

Next, we will iterate across all computational layers and every battery and visualize attributions for each one. Now, some of these attribution operations can be computationally expensive, so it’s important to clear the GPU cache (clear_gpu_cache()) in between them:

for l, layer in enumerate(conv_layers):
layer = conv_layers[l]
method = attr.LayerActivation(garbage_mdl, layer)
for idx in battery_TP_idxs:
orig_img = mldatasets.tensor_to_img(test_400_data[idx][0],\
norm_std, norm_mean,\
to_numpy=True)
tensor = test_data[idx][0][None, :].to(device)
label = int(y_test[idx])
attribution = method.attribute(tensor).detach().cpu().numpy()
viz_img = mldatasets.create_attribution_grid(attribution,\
cmap='copper', cmap_norm='positive')
y_true = labels_l[label]
y_pred = y_test_pred[idx]
probs_s = probs_df.loc[idx]
name = method.get_name()
title = f'CNN Layer #{l+1} {name} Attributions for Sample #{idx}'
mldatasets.compare_img_pred_viz(orig_img, viz_img, y_true,\
y_pred, probs_s, title=title)
clear_gpu_cache()

The preceding snippet should look fairly familiar. Where it’s different is that it’s placing every attribution map for every filter in a grid (viz_img) with create_attribition_grid. It could just then display it with plt.imshow as before, but instead, we will leverage a utility function called compare_img_pred_viz to visualize the attribution(s) side by side with the original image (orig_img). It also takes the sample’s actual label (y_true) and predicted label (y_pred). Optionally, we can provide a pandas series with the probabilities for this prediction (probs_s) and a title. It generates 56 images in total, including Figures 7.12, 7.13, and 7.14.

As you can tell from Figure 7.12, the first convolutional layer seems to be picking up on the battery’s letters as well as its contours:

![Graphical user interface

Description automatically generated with low confidence](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_12.png)

Figure 7.12: Intermediate activations for the first convolutional layer for battery #4

However, Figure 7.13 shows how, by the fourth convolutional layer, the network understands a battery’s contours better:

![Graphical user interface

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_13.png)

Figure 7.13: Intermediate activations for the fourth convolutional layer for battery #4

The last convolutional layer in Figure 7.14 is impossible to interpret because there are 1,792 filters that are 7 pixels wide and high, but rest assured, there are some very high-level features encoded in those tiny maps:

![A picture containing text

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_14.png)

Figure 7.14: Intermediate activations for the last convolutional layer for battery #4

Extracting intermediate activations can provide you with some insight on a sample-by-sample basis. In other words, it’s a local model interpretation method. It’s by no means the only layerwise-attribution method. Captum has more than ten layer attribution methods: https://github.com/pytorch/captum#about-captum.

Evaluating misclassifications with gradient-based attribution methods

Section titled “Evaluating misclassifications with gradient-based attribution methods”

Gradient-based methods calculate attribution maps for each classification with both forward and background passes through the CNN. As the name suggests, these methods leverage the gradients in the backward pass to compute the attribution maps. All of these methods are local interpretation methods because they only derive a single interpretation per sample. Incidentally, attributions in this context mean that we are attributing the predicted labels to areas of an image. They are often called sensitivity maps in academic literature, too.

To get started, we will first need to create an array with all of our misclassification samples (X_misclass) from the test dataset (test_data) using the combined indexes for all of our misclassifications of interest (misclass_idxs). Since there aren’t that many misclassifications, we are loading a single batch of them (next):

misclass_idxs = metal_FP_idxs + plastic_FN_idxs[-4:]
misclass_data = torch.utils.data.Subset(test_data, misclass_idxs)
misclass_loader = torch.utils.data.DataLoader(misclass_data,\
batch_size = 32)
X_misclass, y_misclass = next(iter(misclass_loader))

X_misclass, y_misclass = X_misclass.to(device), y_misclass.to(device)

The next step is to create a utility function we can reuse to obtain the attribution maps for any method. Optionally, we can smooth the map with a method called NoiseTunnel (https://github.com/pytorch/captum#getting-started). We will cover this method in more detail later:

def get_attribution_maps(method, model, device,X,y=None,\
init_args={}, nt_type=None, nt_samples=10,\
stdevs=0.2, **kwargs):
attr_maps_size = tuple([0] + list(X.shape[1:]))
attr_maps = torch.empty(attr_maps_size).to(device)
attr_method = method(model, **init_args)
if nt_type is not None:
noise_tunnel = attr.NoiseTunnel(attr_method)
nt_attr_maps = torch.empty(attr_maps_size).to(device)
for i in tqdm(range(len(X))):
X_i = X[i].unsqueeze(0).requires_grad_()
model.zero_grad()
extra_args = {**kwargs}
if y is not None:
y_i = y[i].squeeze_()
extra_args.update({"target":y_i})
attr_map = attr_method.attribute(X_i, **extra_args)
attr_maps = torch.cat([attr_maps, attr_map])
if nt_type is not None:
model.zero_grad()
nt_attr_map = noise_tunnel.attribute(
X_i, nt_type=nt_type, nt_samples=nt_samples,\
stdevs=stdevs, nt_samples_batch_size=1, **extra_args)
nt_attr_maps = torch.cat([nt_attr_maps, nt_attr_map])
clear_gpu_cache()
if nt_type is not None:
return attr_maps, nt_attr_maps
return attr_maps

The preceding code can create attribution maps for any Captum method for a given model and device. To that end, it takes tensors for the images, X, and their corresponding labels, y. The labels are optional and only needed if the attribution method is targeted – most methods are. Most attribution methods (attr_method) are initialized with only the model, but some require some additional arguments (init_args). Where they tend to have the most arguments is when the attribution is generated with the attribute function, which is why we have the **kwargs collect additional arguments in the get_attribution_maps function and place them in this call.

One important thing to note is that, in this function, we iterate across all the samples in the X tensor and create the attribute maps for each one independently. This is often unnecessary because the attribute methods are all equipped to process a batch at once. However, there’s a risk the hardware can’t handle an entire batch, and at the time of this writing, very few methods come with an internal_batch_size argument, which can limit how many samples are processed at a time. What we are doing here is essentially equivalent to setting this number to 1 every single time in an effort to ensure that we don’t run into memory issues. However, if you have powerful hardware, you can rewrite the function to process the X and y tensors directly.

Next, we will perform our first gradient-based attribution method.

Saliency maps rely on the absolute value of gradients. The intuition is that it will find the pixels in the image that can be perturbed the least so that the output changes the most with these values. It doesn’t perform perturbations, so it doesn’t validate the hypothesis, and the use of absolute values prevents it from finding other evidence to the contrary.

This first saliency map method was groundbreaking at the time and has inspired a bunch of different methods. It’s typically nicknamed “vanilla” to distinguish it from other saliency maps.

Generating saliency maps for all of our misclassified samples is relatively simple with our get_attribution_maps function. All you need is the Captum attribution method (attr.Saliency), model (garbage_mdl), device, and the tensors for the misclassified samples (X_misclass and y_misclass):

saliency_maps = get_attribution_maps(attr.Saliency, garbage_mdl,\
device, X_misclass, y_misclass)

We can plot the output of one of these saliency maps, the fifth one, side by side with the sample image to provide context. Matplotlib can do this easily with a subplots grid. We will make a 1 × 3 grid and place the sample image in the first spot, its saliency heatmap in the second, and one overlayed over the other in the third. As we have done with previous attribution maps, we can use tensor_to_img to convert the images to numpy arrays while also applying a colormap to the attribution. It uses the jet colormap (cmap='jet') by default to make the salient areas appear more striking:

pos = 4
orig_img = mldatasets.tensor_to_img(X_misclass[pos], norm_std,\
norm_mean, to_numpy=True)
attr_map = mldatasets.tensor_to_img(
saliency_maps[pos], to_numpy=True,\
cmap_norm='positive'
)

fig, axs = plt.subplots(1, 3, figsize=(15,5))

axs[0].imshow(orig_img)

axs[0].grid(None)

axs[0].set_title(“Original Image”)

axs[1].imshow(attr_map)

axs[1].grid(None)

axs[1].set_title(“Saliency Heatmap”)

axs[2].imshow(np.mean(orig_img, axis=2), cmap=“gray”)

axs[2].imshow(attr_map, alpha=0.6)

axs[2].grid(None)

axs[2].set_title(“Saliency Overlayed”)

idx = misclass_idxs[pos]
y_true = labels_l[int(y_test[idx])]
y_pred = y_test_pred[idx]
plt.suptitle(f"Actual label: {y_true}, Predicted: {y_pred}")
plt.show()

The preceding code generates the plot in Figure 7.15:

![Chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_15.png)

Figure 7.15: Saliency maps for plastic misclassified as biological waste

The sample image in Figure 7.15 appears to be shredded plastic, but the prediction is for biological waste. The vanilla saliency map attributes that prediction mostly to the smoother duller areas of the plastic. It appears that the lack of specular highlights has thrown the model off, but typically, older broken pieces of plastic lose their shine.

Specular highlights are bright spots of light that appear on the surface of an object when it reflects light. They are often the direct reflections of a light source and are more pronounced on shiny or glossy surfaces, such as metal, glass, or water.

To discuss guided Grad-CAM, we first ought to discuss CAM, which stands for Class Activation Map. The way CAM works is that it removes all but the last fully connected layers, and it replaces the last MaxPooling layer with a Global Average Pooling (GAP) layer. A GAP layer calculates the average value of each feature map, reducing it to a single value per map, while a MaxPooling layer downsizes feature maps by selecting the maximum value from a set of values in a local region of the map. For instance, in this case:

  1. The last convolutional layer outputs a tensor that is 1792 × 7 × 7.
  2. GAP reduces dimensions by merely averaging the last two dimensions of this tensor, producing a 1792 × 1 × 1 tensor.
  3. It then feeds this to a fully connected layer with 12 neurons corresponding to each class.
  4. Once you retrain a CAM model and pass a sample image through the CAM model, it takes the weights from the last layer (a 1792 × 12 tensor) and extracts the values corresponding to the predicted class (a 1792 × 1 tensor).
  5. Then, you calculate the dot product of the last convolutional layer’s output (1792 × 7 × 7) with the weight tensor (1792 x 1).
  6. This weighted sum will end with a 1 × 7 × 7 tensor.
  7. With bilinear interpolation to stretch it out to 1 × 224 × 224, this becomes an upsampled class activation map. When you upsample data, you increase its dimensions.

The intuition behind CAM is that CNNs inherently retain spatial details in convolutional layers but they are, sadly, lost in fully connected layers. In fact, each filter in the last convolutional layer represents visual patterns at different spatial locations. Once weighted, they represent the most salient regions in the entire image. However, to apply CAM, you must radically modify a model and retrain it, and some models don’t lend themselves easily to this.

As the name suggests, Grad-CAM is a similar concept but lacks the modifying and retraining hassle, and uses gradients instead – specifically, those of the class score (prior to softmax) concerning the convolutional layer’s activation maps. GAP is performed on these gradients to obtain neuron importance weights. Then, we compute a weighted linear combination of activation maps with these weights, followed by a ReLU. The ReLU is very important because it ensures locating features that only positively influence the outcome. Like CAM, it is upsampled with bilinear interpolation to match the dimensions of the image.

Grad-CAM does have some shortcomings too, such as failing to identify multiple occurrences or the entirety of the object represented by the predicted class. Like CAM, the resolution of the activation maps may be limited by the final convolutional layer’s dimensions, hence the upsampling.

For these reasons, we are using guided Grad-CAM instead. Guided Grad-CAM is a combination of Grad-CAM and guided backpropagation. Guided backpropagation is another visualization method that computes the gradients of the target class with respect to the input image, but it modifies the backpropagation process to only propagate positive gradients for positive activations. This results in a higher-resolution, more detailed visualization. This is achieved by performing an element-wise multiplication of the Grad-CAM heatmap (upsampled to the input image resolution) with the guided backpropagation result. The output is a visualization that emphasizes the most relevant features in the image for the given class, with higher spatial detail than Grad-CAM alone.

Generating Grad-CAM attribution maps for all of our misclassified samples can be done with our get_attribution_maps function. All you need is the Captum attribution method (attr.GuidedGradCam), model (garbage_mdl), device, and the tensors for the misclassified samples (X_misclass and y_misclass), and, within the method initialization arguments, a layer for which Grad-CAM attributions are computed:

gradcam_maps = get_attribution_maps(
attr.GuidedGradCam, garbage_mdl, device, X_misclass,\
y_misclass, init_args={'layer':conv_layers[3]}
)

Notice that we aren’t using the last layer (which can be indexed with 7 or -1) but the fourth one (3). This is just to keep things interesting, but we can change it. Next, let’s plot the attributions just as we have before. Nearly the same code is used except saliency_maps is replaced by gradcam_maps. The output is depicted in Figure 7.16.

![Chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_16.png)

Figure 7.16: Guided Grad-CAM heatmaps for plastic misclassified as biological waste

As you can observe in Figure 7.16, similar smooth matte areas are highlighted as with the saliency attribution maps, that except guided Grad-CAM yields a few bright areas and edges.

Take all of this with a grain of salt. There is still a lot of ongoing debate in the CNN interpretation domain. And researchers are still coming up with new and better methods, and even techniques that are nearly perfect for most use cases still have flaws. Regarding CAM-like methods, there are many newer ones, such as Score-CAM, Ablation-CAM, and Eigen-CAM, which provide similar functionality but don’t rely on gradients, which can be unstable and, therefore, occasionally unreliable. We won’t discuss them here because, of course, they aren’t gradient-based! But it’s essential to note that it doesn’t hurt to try different methods to see what works for your use case.

Integrated gradients (IG), also known as path-integrated gradients, is a technique that is not exclusive to CNNs. You can apply it to any neural network architecture because it computes the gradients of the output with respect to the inputs averaged all along a path between a baseline and the actual input. It is agnostic to the presence of convolutional layers. However, it requires the definition of a baseline, which is supposed to convey a lack of signal, like a uniformly colored image. In practice, for CNNs in particular, this is what a zero baseline represents, which, for every pixel, would usually mean a completely black image. Also, although the name suggests the use of path integrals, integrals aren’t computed but approximated, with summation in sufficiently small intervals for a certain number of steps. For a CNN, this means it makes variations of the input image progressively darker or lighter until it becomes the baseline corresponding to the predefined number of steps. It then feeds these variations to the CNN, computes the gradients for each one, and averages them. The IG is the dot product of the image times the gradient averages.

Like Shapley values, IG is grounded in solid mathematical theory. In this case, it’s the fundamental theorem of calculus for line integrals. The mathematical proof of the IG method ensures that the attributions of all the features add up to the difference between the model’s prediction on the input data and its prediction on the baseline input. In addition to this property, which they call completeness, there is linearity preservation, symmetry preservation, and sensitivity. We won’t describe each of these properties here. However, it’s important to note that some interpretation methods satisfy notable mathematical properties, while others demonstrate their effectiveness in practical terms.

In addition to IG, we will also leverage NoiseTunnel to perform small random perturbations on the sample image – in other words, to add noise. It creates different noisy versions of the same sample image multiple times and then computes the attribution method for each. It then averages these attributions, potentially making the attribution maps much smoother, which is why this method is called SmoothGrad.

But wait, you may ask: Shouldn’t it be a perturbation-based method then?! We’ve already dealt with several perturbation-based methods before in this book, from SHAP to anchors, and something they have in common is that they perturb the input to measure the effect on the output. SmoothGrad doesn’t measure the impact on the outputs. It only helps yield a more robust attribution map because the mean attribution of perturbed inputs should make for more trustworthy attribution maps. We perform cross-validation to evaluate machine learning models for the same reason: the average metrics performed on different test datasets with slightly different distributions make for better metrics.

For IG, we will use very similar code as we did for Saliency, except we will add several arguments related to NoiseTunnel, such as the type of noise tunnel (nt_type='smoothgrad'), the sample variations to produce (nt_samples=20), and an amount of random noise to add to each one in standard deviations (stdevs=0.2). We will find that the more permuted samples to generate, the better, up to a point, and then it doesn’t have much effect. However, there is such a thing as too much noise, and if you use too little, there won’t be any effect:

ig_maps, smooth_ig_maps = get_attribution_maps(
attr.IntegratedGradients, garbage_mdl, device, X_misclass,\
y_misclass, nt_type='smoothgrad', nt_samples=20, stdevs=0.2

)

We can also optionally define the number of steps for the IG (n_steps). It’s set to 50 by default, and we can also modify the baselines, which is a tensor of zeros by default. As we’ve done with Grad-CAM, we can plot our first sample image side by side with the IG map, but this time, we will modify the code to plot the SmoothGrad integrated gradients (smooth_ig_maps) in the third position, like this:

nt_attr_map = mldatasets.tensor_to_img(
smooth_ig_maps[pos], to_numpy=True, cmap_norm='positive'
)

axs[2].imshow(nt_attr_map)

axs[2].grid(None)

axs[2].set_title(“SmoothGrad Integrated Gradients”)

The modified snippet outputs Figure 7.17:

![Chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_17.png)

Figure 7.17: Integrated gradient heatmaps for plastic misclassified as biological waste

The areas in the IG heatmap in Figure 7.17 coincide with many of the regions spotted by the saliency and guided Grad-CAM maps. However, there are more clusters of strong attributions in the bright yellow areas as well as in brownish shadowed areas, which is consistent with how some foods look when they are disposed of (like banana peels and rotten leafy greens). On the other hand, the bright orange and green areas aren’t.

As for the SmoothGrad IG heatmap, it is striking how different this map is compared to the non-smooth IG heatmap. This is not always the case; often, it’s just a smoother version. What likely happened was that the 0.2 noise distorted the attributions a bit too much, or that 20 perturbed samples weren’t enough. However, it’s tough to tell because it’s also possible that SmoothGrad more accurately depicts the real story.

We won’t do this now, but you can visually “tune” the stdevs and nt_samples parameters. You can try it with less noise and more samples, using a series of combinations, such as 0.1 and 80, and 0.15 and 40, trying to figure out whether you see a commonality between them. The one you go with is the one that most clearly depicts this consistent story. One of the shortcomings of SmoothGrad is having to define optimal parameters. Incidentally, IG also has the same issue with defining the baselines and number of steps (n_steps). The default baseline won’t work in cases where the input image is too large or small, so it must be changed, and the authors of the IG paper suggest that 20-300 steps will approximate the integral within 5%.

IG has its detractors, who have made similar methods that avoid using gradients, such as DeepLIFT. IG can be sensitive to zero-valued gradients and discontinuities with gradients, which can lead to misleading attributions. But these point to general disadvantages shared by all gradient-based methods. For this reason, we are introducing the Deep Learning Important FeaTures algorithm (DeepLIFT). It’s neither a gradient-based nor a perturbation-based method. It’s a backpropagation-based approach!

In this section, we will contrast it with IG. Like IG and Shapley values, DeepLIFT was designed for completeness, and as such, complies with remarkable mathematical properties. In addition to that, like IG, DeepLIFT can also be applied to various deep learning architectures, including CNNs and recurrent neural networks (RNNs), making it versatile for different use cases.

DeepLIFT works by decomposing the output prediction of the model into contributions from each input feature, using the concept of “difference-from-reference.” It backpropagates these contributions through the network layers to assign an importance score to each input feature.

More specifically, like IG, it uses a baseline that represents no specific information about any class. However, it then calculates the difference in the activations of each neuron between the input and the baseline, and it backpropagates these differences through the network, calculating each neuron’s contribution to the output prediction. Then we sum the contributions for each input feature to obtain its importance score (attribution).

It’s advantages over IG are as follows:

  • Reference-based: Unlike gradient-based methods such as IG, DeepLIFT explicitly compares the input to a reference input, making the attributions more interpretable and meaningful.
  • Non-linear interactions: DeepLIFT considers the non-linear interactions between neurons when computing attributions. It captures these interactions by considering the multipliers (the change in output due to the change in input) in each layer of the neural network.
  • Stability: DeepLIFT is more stable than gradient-based methods, as it is less sensitive to small changes in the input, providing more consistent attributions. So, using a SmoothGrad is unnecessary on DeepLIFT attributions although highly recommended for gradient-based methods.

Overall, DeepLIFT provides a more interpretable, stable, and comprehensive approach to attributions, making it a valuable tool for understanding and explaining deep learning models.

Next, we will create DeepLIFT attribution maps in a similar fashion as we have done the others:

deeplift_maps = get_attribution_maps(attr.DeepLift, garbage_mdl,\
device, X_misclass, y_misclass)

To plot an attribution map, nearly the same code as with Grad-CAM is used, except gradcam_maps is replaced by deeplift_maps. The output is depicted in Figure 7.18.

![Chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_18.png)

Figure 7.18: DeepLIFT heatmaps for plastic misclassified as biological waste

The attributions of Figure 7.18 are not as noisy as in IG. But they also seem to cluster around some dull yellows and dark areas in the shadows; it also points toward dull greens near the top-right corner.

Now, we will take everything that we have learned about gradient-based attribution methods and use it to understand the reasons for all the chosen misclassifications (the plastic false negatives and metal false positives). As we did with intermediate activation maps, we can leverage the compare_img_pred_viz function to place the higher-resolution sample image side by side with four attribution maps: saliency, Grad-CAM, SmoothGrad IG, and DeepLift. To this end, we first have to iterate all the misclassifications’ positions and indexes and extract all the maps. Note that we are using overlay_bg in the tensor_to_img function to produce a new image overlaying the original image with the heatmap for each. Lastly, we concatenate the four attribution outputs into a single image (viz_img). Just as we have done before, we extract the actual label (y_true), predicted label (y_pred), and pandas series with the probabilities (probs_s) to add some context to the plot we will produce. The for loop will produce six plots but, for brevity’s sake, we are only going to discuss three of them:

for pos, idx in enumerate(misclass_idxs):
orig_img = mldatasets.tensor_to_img(test_400_data[idx][0],\
norm_std, norm_mean, to_numpy=True)
bg_img = mldatasets.tensor_to_img(test_data[idx][0],\
norm_std, norm_mean, to_numpy=True)
map1 = mldatasets.tensor_to_img(
saliency_maps[pos], to_numpy=True,\
cmap_norm='positive', overlay_bg=bg_img
)
map2 = mldatasets.tensor_to_img(
smooth_ig_maps[pos],to_numpy=True,\
cmap_norm='positive', overlay_bg=bg_img
)
map3 = mldatasets.tensor_to_img(
gradcam_maps[pos], to_numpy=True,\
cmap_norm='positive', overlay_bg=bg_img
)
map4 = mldatasets.tensor_to_img(
deeplift_maps[pos], to_numpy=True,\
cmap_norm='positive', overlay_bg=bg_img
)
viz_img = cv2.vconcat([
cv2.hconcat([map1, map2]),
cv2.hconcat([map3, map4])
])
label = int(y_test[idx])
y_true = labels_l[label]
y_pred = y_test_pred[idx]
probs_s = probs_df.loc[idx]
title = 'Gradient-Based Attr for Misclassification Sample #{}'.\
format(idx)
mldatasets.compare_img_pred_viz(orig_img, viz_img, y_true,\
y_pred, probs_s, title=title)

The preceding code generates Figures 7.19 to 7.21. It’s important to note that in all generated plots, we can observe saliency attributions at the top left, SmoothGrad IG at the top right, guided Grad-CAM at the bottom left, and DeepLIFT at the bottom right:

![Graphical user interface

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_19.png)

Figure 7.19: Gradient-based attributions for battery as metal misclassification #8

In Figure 7.19, there’s a lack of consistency between all four attribution methods. The saliency attribution maps show that all the center parts of the batteries are seen as metal surfaces, in addition to the white parts of the cardboard container. On the other hand, SmoothGrad IG zeros in on the white cardboard and Grad-CAM on the blue cardboard almost exclusively. Lastly, DeepLIFT is much more sparse, only pointing to some parts of the white cardboard.

In Figure 7.20, the attributions are much more consistent than in Figure 7.19. Matte white areas are clearly confusing the model. This makes sense considering that the plastic in the training data was mostly single pieces of empty plastic containers – including white milk jugs. However, people do recycle toys, plastic tools like spatulas, and other plastic objects. Interestingly enough, although all attribution methods were salient around white and light-yellow surfaces, SmoothGrad IG also highlights some edges, like one of the ducks’ hats and another one’s collar:

![Graphical user interface, application

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_20.png)

Figure 7.20: Gradient-based attributions for plastic misclassification #86

To continue with the recycling toys theme, how do LEGO bricks get misclassified as batteries? See Figure 7.21 for an interpretation:

![Diagram

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_21.png)

Figure 7.21: Gradient-based attributions for plastic misclassification #89

Figure 7.21 shows how, among all the attribution methods, it’s mostly the yellow and green bricks (and to a lesser degree, light blue) that are to blame for the misclassification because these are popular colors among battery manufacturers, as attested by the training data. Also, the flat surface in between the studs got the most attributions since these resemble the contacts in batteries and, more specifically, 9-volt square batteries. As with the other examples, saliency was the most noisy method. However, this time, guided Grad-CAM was the least noisy. It was also more salient on the edges than on surfaces, unlike the others.

We will next try to discover what the model learned about batteries (in addition to white glass) through perturbation-based attribution methods performed on true positives.

Understanding classifications with perturbation-based attribution methods

Section titled “Understanding classifications with perturbation-based attribution methods”

Perturbation-based methods have already been covered to a great extent in this book so far. So many of the methods we have covered, including SHAP, LIME, anchors, and even permutation feature importance, employ perturbation-based strategies. The intuition behind them is that if you remove, alter, or mask features in your input data and then make predictions with them, you’ll be able to attribute the difference between the new predictions and the original predictions to the changes you made in the input. These strategies can be leveraged in both global and local interpretation methods.

We will now do the same as we did with the misclassification samples, but to the chosen true positives, and gather four of each class in a single tensor (X_correctcls):

correctcls_idxs = wglass_TP_idxs[:4] + battery_TP_idxs[:4]
correctcls_data = torch.utils.data.Subset(test_data, correctcls_idxs)
correctcls_loader = torch.utils.data.DataLoader(correctcls_data,\
batch_size = 32)
X_correctcls, y_correctcls = next(iter(correctcls_loader))
X_correctcls, y_correctcls = X_correctcls.to(device),\
y_correctcls.to(device)

One of the more complicated aspects of performing permutation methods on images is that there are not just a few dozen features but many thousands to permute. Picture this: 224 x 224 equals 50,176 pixels, and if we want to measure how a change in each pixel independently affects the outcome, we’ll need to make at least 20 permuted samples for each pixel. So, over a million! For this reason, several permutation methods accept masks to determine which blocks of pixels to permute at once. If we group them in blocks of 32 x 32 pixels, this means we’ll have only 49 blocks in total to permute. However, although it will speed up the attribution methods, we’ll miss out on the effects on smaller sets of pixels the larger the block.

We can use many methods to create masks, such as using a segmentation algorithm to break up the images into intuitive blocks based on surfaces and edges. Segmentation is done per image, so the number and placement of segments will vary on an image-to-image basis. There are many methods with scikit-learn’s image segmentation library (skimage.segmentation): https://scikit-image.org/docs/stable/api/skimage.segmentation.html. However, we are going to keep things simple and create one mask for all 224 x 224 images with the following code:

feature_mask = torch.zeros(3, 224, 224).int().to(device)
counter = 0
strides = 16
for row in range(0, 224, strides):
for col in range(0, 224, strides):
feature_mask[:, row:row+strides, col:col+strides] = counter
counter += 1

What the preceding code does is initialize a tensor of zeros the size of the model’s input. It’s easier to conceptualize this tensor as an empty image. Then it moves across strides that are 16 pixels wide and high, from the top-left corner of the image to the bottom right. As it moves across, it sets the values with consecutive numbers with the counter. What you end up with is a tensor with all values filled with numbers between 0 and 195, and, if you visualized it as an image, it would be a diagonal gradient from black at the top left to light gray at the bottom right. What’s important to note is that each block with the same value is treated as if it were the same pixel by the attribution method.

Before we move forward, let’s discuss baselines. In Captum attribution methods, as in other libraries for that matter, the default baseline is a tensor of zeros, which is usually equivalent to a black image when images are made up of floating-point numbers between 0 and 1. However, in our case, we are standardizing our input tensors so the model doesn’t see tensors with a minimum of 0 but a mean of 0! Therefore, for our garbage model, a tensor of zeros corresponds to a medium gray image, not a black image. For gradient-based methods, there’s nothing inherently wrong with a gray image baseline because there are likely a number of steps between it and the input image. However, perturbation-based methods can be particularly sensitive to having baselines that are too close to the input image because if you replace parts of the input image with the baseline, the model won’t tell the difference!

For our garbage model’s case, a black image is made up of tensors of -2.1179 because one of the transformations performed to standardize the input tensors was (x-0.485)/0.229, which happens to equal approximately -2.1179, when x=0. You can also calculate the tensors when x=1; it converts to 2.64 for a white image. That being said, there’s no harm in assuming that somewhere in our true positive samples, there’s at least one pixel that has the lowest value and another with the highest, so we will just use max() and min() to create both light and dark baselines:

baseline_light = float(X_correctcls.max().detach().cpu())
baseline_dark = float(X_correctcls.min().detach().cpu())

We will use only one baseline for all but one perturbation method but feel free to switch them around. Now, on to creating attribution maps for each method!

Feature ablation is a relatively simple method. What it does is occlude portions of the sample input image by replacing it with the baseline, which is, by default, zero. The goal is to understand the importance of each input feature (or feature group) in making a prediction by observing the effect of altering it.

Here’s how feature ablation works:

  1. Obtain the original prediction: First, the model’s prediction for the original input is obtained. This serves as a baseline for comparing the effect of perturbing the input features.
  2. Perturb the input feature: Next, for each input feature (or feature group as set by the feature mask), it is replaced with the baselines value. This creates an “ablated” version of the input.
  3. Obtain the prediction for the perturbed input: The model’s prediction is calculated for the ablated input.
  4. Compute the attribution: The difference in the model’s predictions between the original input and the ablated input is calculated. This difference is attributed to the altered feature, indicating its importance in the prediction.

Feature ablation is a simple and intuitive approach to understanding the importance of input features in a model’s prediction. However, it has some limitations. It assumes that features are independent and may not accurately capture the effects of interactions between features. Additionally, it can be computationally expensive for models with a large number of input features or complex input structures. Despite these limitations, feature ablation is a valuable tool for understanding and interpreting model behavior.

To generate the attribution maps, we will use the get_attribution_maps function as we have before, and enter the additional arguments for the feature_mask and baselines:

ablation_maps = get_attribution_maps(
attr.FeatureAblation,garbage_mdl,\
device,X_correctcls,y_correctcls,\
feature_mask=feature_mask,\
baselines=baseline_dark
)

To plot an example of the attribution map, you can copy the same code that we used for saliency, except saliency_maps is replaced by ablation_maps, and we are using the second image in the occlusion_maps array, like this:

pos = 2
orig_img = mldatasets.tensor_to_img(X_correctcls[pos], norm_std,\
norm_mean, to_numpy=True)
attr_map = mldatasets.tensor_to_img(occlusion_maps[pos],to_numpy=True,\
cmap_norm='positive')

The modified snippet outputs Figure 7.22:

![Graphical user interface

Description automatically generated with medium confidence](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_22.png)

Figure 7.22: Feature ablation maps for a white glass true positive from the test dataset

In Figure 7.22, the feature groups in the bottom of the bowl of the wine glass appear to be most important because their absence makes the biggest difference in the outcome, but other portions of the glass are also salient to a lesser degree, except the stem of the wine glass. It makes sense because a wine glass without a stem is still a glass-like container.

Next, we will discuss a similar method that will be able to show us attributions with greater detail.

Occlusion sensitivity is very similar to feature ablation because it also replaces portions of the image with a baseline. However, unlike feature ablation, it doesn’t use a feature mask to group pixels together. Instead, it groups contiguous features automatically with a sliding window and strides. In this process, it creates many overlapping regions. When this happens, it averages the output differences to compute the attribution for each pixel.

In this scenario, besides overlapping regions and their corresponding averages, occlusion sensitivity and feature ablation are identical. In fact, if we used both sliding windows and strides of 3 x 16 x 16, there wouldn’t be any overlapping areas and the feature grouping would be identical to those defined by our feature_mask made up of 16 x 16 blocks.

So, you may wonder, what’s the point of being familiar with both methods? The point is occlusion sensitivity is only suitable for use when a fixed grouping of contiguous features matter, like with images and perhaps other spatial data. And because of its use of strides, it can capture local dependencies and spatial relationships between features. However, although we used contiguous blocks of features, feature ablation doesn’t have to because the feature_mask can be arranged in whichever way it makes most sense for your inputs to be segmented. This small detail makes it very versatile to other data types. Therefore, feature ablation is a more general approach that can handle various input types and model architectures, while occlusion sensitivity is specifically tailored to image data and convolutional neural networks, with a focus on spatial relationships between features.

To generate the attribution maps for occlusion, we will do as before, and enter the additional arguments for the baselines, sliding_window_shapes, and strides:

occlusion_maps = get_attribution_maps(
attr.Occlusion, garbage_mdl,\
device,X_correctcls,y_correctcls,\
baselines=baseline_dark,\
sliding_window_shapes=(3,16,16),\
strides=(3,8,8)
)

Please note that we are creating ample overlapping regions by setting the strides to be only 8 pixels while the sliding windows are 16 pixels. To plot an attribution, you can copy the same code that we used for feature ablation, except ablation_maps is replaced by occlusion_maps. The output is depicted in Figure 7.23:

![Graphical user interface

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_23.png)

Figure 7.23: Occlusion sensitivity maps for a white glass true positive from the test dataset

With Figure 7.23, we can tell that occlusion’s attributions are eerily similar to the ablation’s attribution, except with more resolution. This resemblance shouldn’t be surprising considering how the feature mask of the former aligns with the sliding window of the latter.

Whether we use blocks of non-overlapping 16 x 16 pixels or overlapping 8 x 8, the impact of their absence is measured independently to create the attributions. Therefore, both ablation and occlusion methods aren’t equipped to measure interactions between non-contiguous feature groups. This can prove to be a problem when the absence of two non-contiguous feature groups is what causes a classification to change. For instance, can a wine glass without a stem or a base still be considered a wine glass? It can certainly be considered glass, one would hope, but perhaps the model has learned the wrong relationships.

Speaking of relationships, next, we will revisit an old friend: Shapley!

If you recall from Chapter 4, Global Model-Agnostic Interpretation Methods, Shapley has provided a method that is very good at measuring and attributing the impact of coalitions of features to the outcome. Shapley does this by permuting entire coalitions of features at a time rather than permuting one feature at a time, like the two previous methods. That way, it can tease out how more than one feature or feature group interacts with one another.

The code to create the attribution maps should be very familiar by now. This method uses the feature_mask and baselines but also the number of feature permutations tested (n_samples). This last attribute has a huge impact on the fidelity of the method. However, it can make it notoriously computationally expensive, so we are not going to run it with the default 25 samples per permutation. Instead, we will use 5 samples to make things more manageable. However, feel free to tweak it should your hardware be able to handle it:

svs_maps = get_attribution_maps(
attr.ShapleyValueSampling,garbage_mdl,\
device, X_correctcls, y_correctcls,\
baselines=baseline_dark,\
n_samples=5, feature_mask=feature_mask
)

To plot an attribution, you can copy the same snippet that we used for occlusion, except occlusion_maps is replaced by svs_maps. The output is shown in Figure 7.24:

Figure 7.24: Shapley value sampling maps for a white glass true positive from the test dataset

Figure 7.24 shows some consistent attributions, such as the most salient area being in the bottom-left corner of the wine glass bowl. Also, the base seems to be more important than the occlusion and ablation methods suggested.

However, the attributions are a lot more noisy than the previous ones. This is partially because we didn’t use a sufficient number of samples to cover all the combinations of features and interactions, and partially because of the messy nature of interactions. It makes sense that attributions for a single independent feature are concentrated in a few areas, such as the bowl of a wine glass. However, interactions can rely on several parts of the image, such as the base and the rim of the wine glass. They may become important only when they appear together. More interesting is the effect of a background. For instance, if you remove portions of the background, does the wine glass no longer look like a wine glass? Perhaps the background is more important than you think, especially when dealing with a translucent material.

Since we are on the topic of Shapley values, let’s try KernelSHAP from Chapter 4, Global Model-Agnostic Interpretation Methods. It leverages LIME to compute Shapley values more efficiently. The Captum implementation is similar to the SHAP one except it uses linear regression and not Lasso, and it computes the kernel differently. Also, for the LIME image explainer, it is best to use meaningful feature groups (called superpixels) rather than the contiguous blocks we have used in the feature mask. The same advice persists for KernelSHAP. However, we will keep this simple for this exercise, and also consistent for comparing with the other three permutation-based methods.

We will now create the attribution maps but, this time, we will do one with light baselines and another with dark ones. Because KernelSHAP is an approximation to Shapley sampling values and not as computationally expensive, we can set n_samples=300. However, this won’t necessarily guarantee high fidelity because it takes a high amount of samples in KernelSHAP to approximate what a relatively low amount of samples can do exhaustively with Shapley:

kshap_light_maps = get_attribution_maps(attr.KernelShap, garbage_mdl,\
device, X_correctcls, y_correctcls,\
baselines=baseline_light,\
n_samples=300,\
feature_mask=feature_mask)
kshap_dark_maps = get_attribution_maps(attr.KernelShap, garbage_mdl,\
device, X_correctcls, y_correctcls,\
baselines=baseline_dark,\
n_samples=300,\
feature_mask=feature_mask)

To plot an attribution, you can copy the same snippet that we used for Shapley, except svs_maps is replaced by kshap_light_maps, and we modify the code to plot the attributions with the dark baselines in the third position, like this:

axs[2].imshow(attr_dark_map)

axs[2].grid(None)

axs[2].set_title(“Kernel Shap Dark Baseline Heatmap”)

The preceding snippet outputs the plots in Figure 7.25:

![A picture containing graphical user interface

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_25.png)

Figure 7.25: KernelSHAP maps for a white glass true positive from the test dataset

The two attribution maps in Figure 7.25 are mostly not consistent with each other, but more importantly, not with the previous attributions. Sometimes, some methods have a harder time than others, or it takes some tweaking to get them to work how we expect them to.

Now, we will take everything that we have learned about perturbation-based attribution methods and use it to understand the reasons for all the chosen true positive classifications (for both white glass and batteries). As we did before, we can leverage the compare_img_pred_viz function to place the higher-resolution sample image side by side with the four attribution maps: feature ablation, occlusion sensitivity, Shapley, and KernelSHAP. First, we have to iterate all the classifications’ positions and indexes and extract all the maps. Note that we are using overlay_bg to produce a new image overlaying the original image with the heatmap for every attribution, as we did for the gradient-based section. Lastly, we concatenate the four attribution outputs into a single image (viz_img). Just as we have done before, we extract the actual label (y_true), predicted label (y_pred), and pandas series with the probabilities (probs_s) to add some context to the plot we will produce. The for loop will produce six plots, but we will only discuss two of them:

for pos, idx in enumerate(correctcls_idxs):
orig_img = mldatasets.tensor_to_img(test_400_data[idx][0],\
norm_std, norm_mean,\
to_numpy=True)
bg_img = mldatasets.tensor_to_img(test_data[idx][0],\
norm_std, norm_mean,\
to_numpy=True)
map1 = mldatasets.tensor_to_img(ablation_maps[pos],\
to_numpy=True,\
cmap_norm='positive',\
overlay_bg=bg_img)
map2 = mldatasets.tensor_to_img(svs_maps[pos], to_numpy=True,\
cmap_norm='positive',\
overlay_bg=bg_img)
map3 = mldatasets.tensor_to_img(occlusion_maps[pos],\
to_numpy=True,\
cmap_norm='positive',\
overlay_bg=bg_img)
map4 = mldatasets.tensor_to_img(kshap_dark_maps[pos],\
to_numpy=True,\
cmap_norm='positive',\
overlay_bg=bg_img)
viz_img = cv2.vconcat([
cv2.hconcat([map1, map2]),
cv2.hconcat([map3, map4])
])
label = int(y_test[idx])
y_true = labels_l[label]
y_pred = y_test_pred[idx]
probs_s = probs_df.loc[idx]
title = 'Pertubation-Based Attr for Correct classification #{}'.\
format(idx)
mldatasets.compare_img_pred_viz(orig_img, viz_img, y_true,\
y_pred, probs_s, title=title)

The preceding code snippet generates several explanations, including Figures 7.26 to 7.28. For your reference, ablation is in the top-left corner and occlusion is at the bottom left. Then, Shapley is at the top right and KernelSHAP is at the bottom right.

Overall, you can tell that ablation and occlusion are very consistent, while much less so with Shapley and KernelSHAP. However, what Shapley and KernelSHAP have in common is that the attributions are more spread out.

In Figure 7.26, all attribution methods have text highlighted, as well as, at least, the left contact of the battery. This is similar to Figure 7.28, where the text is abundantly highlighted as well as the top contact. This suggests that, for batteries, the model has learned that text and a contact matter. As for white glass, it is less clear. All the attribution methods in Figure 7.27 point to some of the edges of the broken vase, but not always the same edges (except for ablation and occlusion, which are consistent):

![Graphical user interface, application

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_26.png)

Figure 7.26: Perturbation-based attributions for battery classification #1

White glass is the hardest glass to classify of the three, and it’s not hard to tell why:

![Graphical user interface

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_27.png)

Figure 7.27: Perturbation-based attributions for white glass classification #113

As noted in Figure 7.27, and others in the test example, it’s hard for the model to distinguish white glass from the light backgrounds. It manages to classify it correctly with these examples. However, this doesn’t mean it will generalize well in other examples where glass is in shards and not as well-lit. As long as the attributions show significant influence from the background, it’s hard to trust that it can recognize glass for its specular highlights, texture, and edges alone.

![Graphical user interface

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_07_28.png)

Figure 7.28: Perturbation-based attributions for battery classification #2

For Figure 7.28, the background is also highlighted significantly in all attribution maps. But perhaps this is because the baseline was dark and so is the object in its entirety. If you replace an area just outside the edge of the battery with a black square, it makes sense that the model would be confused. For this reason, with permutation-based methods, it’s important to choose an appropriate baseline.

The mission was to provide an objective evaluation of the garbage classification model for the municipal recycling plant. The predictive performance on out-of-sample validation images was dismal! You could have stopped there, but then you would not have known how to make a better model.

However, the predictive performance evaluation was instrumental in deriving specific misclassifications, as well as correct classifications, to assess using other interpretation methods. To this end, you ran a comprehensive suite of interpretation methods, including activation, gradient, perturbation, and backpropagation-based methods. The consensus between all the methods was that the model was having the following issues:

  • Differentiating between the background and the objects
  • Understanding that different objects share similar color hues
  • Confounding lighting conditions, such as specular highlights as specific material characteristics, like with the wine glasses
  • An inability to separate unique features of each object, such as plastic studs in LEGO bricks from battery contacts
  • Being confused by objects with multiple materials, such as batteries contained in plastic and even cardboard packaging

To address these problems, the model needed to be trained with a more varied dataset – hopefully, one that reflects the real-world conditions of the recycling plant; for instance, the expected background (on a conveyor belt), different lighting conditions, and even objects partially occluded by hands, gloves, bags, and so on. Also, they ought to add a category for miscellaneous objects that are made up of multiple materials.

Once this dataset has been compiled, it is essential to leverage data augmentation to make the model even more robust to all sorts of variations: angle, brightness, contrast, saturation, and hue variants. And they won’t have to retrain the model from scratch! They can even fine-tune EfficientNet!

After reading this chapter, you should understand how to leverage traditional interpretation methods to more thoroughly assess predictive performance on a CNN classifier and visualize the learning process of CNNs with activation-based methods. You should also understand how to compare and contrast misclassifications and true positives with gradient-based and perturbation-based attribution methods. In the next chapter, we will study interpretation methods for NLP transformers.

  • Smilkov, D., Thorat, N., Kim, B., Viégas, F., and Wattenberg, M., 2017, SmoothGrad: Removing noise by adding noise. ArXiv, abs/1706.03825: https://arxiv.org/abs/1706.03825
  • Sundararajan, M., Taly, A., and Yan, Q., 2017, Axiomatic Attribution for Deep Networks. Proceedings of Machine Learning Research, pp. 3319–3328, International Convention Centre, Sydney, Australia: https://arxiv.org/abs/1703.01365
  • Zeiler, M.D., and Fergus, R., 2014, Visualizing and Understanding Convolutional Networks. In European conference on computer vision, pp. 818–833: https://arxiv.org/abs/1311.2901
  • Shrikumar, A., Greenside, P., and Kundaje, A., 2017, Learning Important Features Through Propagating Activation Differences: https://arxiv.org/abs/1704.02685