Adversarial Robustness
local graph
Chapter 13 — Adversarial Robustness
Section titled “Chapter 13 — Adversarial Robustness”Machine learning interpretation has many concerns, ranging from knowledge discovery to high-stakes ones with tangible ethical implications, like the fairness issues examined in the last two chapters. In this chapter, we will direct our attention to concerns involving reliability, safety, and security.
As we realized using the contrastive explanation method in Chapter 7, Visualizing Convolutional Neural Networks, we can easily trick an image classifier into making embarrassingly false predictions. This ability can have serious ramifications. For instance, a perpetrator can place a black sticker on a yield sign, and while most drivers would still recognize this as a yield sign, a self-driving car may no longer recognize it and, as a result, crash. A bank robber could wear a cooling suit designed to trick the bank vault’s thermal imaging system, and while any human would notice it, the imaging system would fail to do so.
The risk is not limited to sophisticated image classifiers. Other models can be tricked! The counterfactual examples produced in Chapter 6*, Anchors and Counterfactual Explanations,* are like adversarial examples except with the goal of deception. An attacker could leverage any misclassification example, straddling the decision boundary adversarially. For instance, a spammer could realize that adjusting some email attributes increases the likelihood of circumventing spam filters.
Complex models are more vulnerable to adversarial attacks. So why would we trust them?! We can certainly make them more foolproof, and that’s what adversarial robustness entails. An adversary can purposely thwart a model in many ways, but we will focus on evasion attacks and briefly explain other forms of attacks. Then we will explain two defense methods: spatial smoothing preprocessing and adversarial training. Lastly, we will demonstrate one robustness evaluation method.
These are the main topics we will cover:
- Learning about evasion attacks
- Defending against targeted attacks with preprocessing
- Shielding against any evasion attack through adversarial training of a robust classifier
Technical requirements
Section titled “Technical requirements”This chapter’s example uses the mldatasets, numpy, sklearn, tensorflow, keras, adversarial-robustness-toolbox, matplotlib, and seaborn 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/1MNrL
The mission
Section titled “The mission”The privately contracted security services industry market worldwide is valued at over USD 250 billion and is growing at around 5% annually. However, it faces many challenges, such as shortages of adequately trained guards and specialized security experts in many jurisdictions, and a whole host of unexpected security threats. These threats include widespread coordinated cybersecurity attacks, massive riots, social upheaval, and, last but not least, health risks brought on by pandemics. Indeed, 2020 tested the industry with a wave of ransomware, misinformation attacks, protests, and COVID-19 to boot.
In the wake of this, one of the largest hospital networks in the United States asked their contracted security company to monitor the correct use of masks by both visitors and personnel throughout the hospitals. The security company has struggled with this request because it diverts security personnel from tackling other threats, such as intruders, combative patients, and belligerent visitors. It has video surveillance in every hallway, operating room, waiting room, and hospital entrance. It’s impossible to have eyes on every camera feed every time, so the security company thought they could assist guards with deep learning models.
These models already alert unusual activities, such as running in the hallways and brandishing weapons anywhere on the premises. They have proposed to the hospital network that they would like to add a new model that detects masks’ correct usage. Before COVID-19, there were policies in place for mandatory mask usage in certain areas of each hospital, and during COVID-19, it was required everywhere. The hospital administrators would like to turn on and off this monitoring feature, depending on pandemic risk levels moving forward. They realize that personnel get fatigued and forget to put masks back on, or they partially slip off at times. Many visitors are also hostile toward using masks and may wear one when entering the hospital but take it off when no guard is around. This isn’t always intentional, so they wouldn’t want to dispatch guards on every alert, unlike other threats. Instead, they’d rather use awareness and a little bit of shame to modify behavior and only intervene with repeat offenders:

Figure 13.1: Radar speed signs like this one help curb speeding
Awareness is a very effective method with radar speed signs (see Figure 13.1), which make roads safer by only making drivers aware that they are driving too fast. Likewise, having a screen at the end of heavily trafficked hallways showing snapshots of those who have recently either mistakenly or purposely not complied with mandatory mask usage potentially creates some embarrassment for offenders. The system will log repeat offenders so that security guards can look for them and either make them comply or ask them to vacate the premises.
There’s some concern with visitors trying to trick the model into evading compliance, so the security company has hired you to ensure that the model is robust in the face of this kind of adversarial attack. Security officers have noticed some low-tech trickery before, such as people momentarily covering their faces with their hands or a part of their sweater when they realize cameras monitor them. Also, in one disturbing incident, a visitor dimmed the lights and sprayed some gel on a camera, and in another, an individual painted their mouth. However, there are concerns about higher-tech attacks, such as jamming the camera’s wireless signal or shining high-powered lasers directly into cameras. Devices that perform these attacks are increasingly easier to obtain and could impact other surveillance functions on a larger scale, like preventing theft. The security company hopes this robustness exercise can inform their efforts to improve every surveillance system and model.
Eventually, the security company would like to produce its own dataset with face images from the hospitals they monitor. Meanwhile, synthetically masked faces from external sources are the best they can do to productionize a model in the short term. To this end, you have been provided a large dataset of synthetically correctly and incorrectly masked faces and their unmasked counterparts. The two datasets were combined into a single one, and the original dimensions of 1,024 × 1,024 were reduced to the thumbnail size of 124 × 124. Also, for efficiency’s sake, 21,000 images were sampled from roughly 210,000 in these datasets.
The approach
Section titled “The approach”You’ve decided to take a four-fold approach:
- Exploring several possible evasion attacks to understand how vulnerable the model is to them and how credible they are as threats
- Using a preprocessing method to protect a model against these attacks
- Leveraging adversarial retraining to produce a robust classifier that is intrinsically less prone to many of these attacks
- Evaluating robustness with state-of-the-art methods to assure hospital administrators that the model is adversarially robust
Let’s get started!
The preparations
Section titled “The preparations”You will find the code for this example here: https://github.com/PacktPublishing/Interpretable-Machine-Learning-with-Python-2E/tree/main/13/Masks.ipynb
Loading the libraries
Section titled “Loading the libraries”To run this example, you need to install the following libraries:
mldatasetsto load the datasetnumpyandsklearn(scikit-learn) to manipulate ittensorflowto fit the modelsmatplotlibandseabornto visualize the interpretations
You should load all of them first:
import mathimport osimport warningswarnings.filterwarnings("ignore")import mldatasetsimport numpy as npfrom sklearn import preprocessingimport tensorflow as tffrom tensorflow.keras.utils import get_fileimport matplotlib.pyplot as pltimport seaborn as snsfrom sklearn import metricsfrom art.estimators.classification import KerasClassifierfrom art.attacks.evasion import FastGradientMethod,\ ProjectedGradientDescent, BasicIterativeMethodfrom art.attacks.evasion import CarliniLInfMethodfrom art.attacks.evasion import AdversarialPatchNumpyfrom art.defences.preprocessor import SpatialSmoothingfrom art.defences.trainer import AdversarialTrainerfrom tqdm.notebook import tqdmLet’s check that TensorFlow has loaded the right version with print(tf.__version__). The version should be 2.0 and above.
We should also disable eager execution and verify that it worked with the following command:
tf.compat.v1.disable_eager_execution()print('Eager execution enabled:', tf.executing_eagerly())The output should say that it’s False.
In TensorFlow, turning eager execution mode on means that it doesn’t require a computational graph or a session. It’s the default for TensorFlow 2.x and later but not in prior versions, so you need to disable it to avoid incompatibilities with code that was optimized for prior versions of TensorFlow.
Understanding and preparing the data
Section titled “Understanding and preparing the data”We will load the data into four NumPy arrays, corresponding to the training/test datasets. While we are at it, we will divide X face images by 255 because, that way, they will be of values between zero and one, which is better for deep learning models. We call this feature scaling. We will need to record the min_ and max_ for the training data because we will need these later:
X_train, X_test, y_train, y_test = mldatasets.load( "maskedface-net_thumbs_sampled", prepare=True)X_train, X_test = X_train / 255.0, X_test / 255.0min_ = X_train.min()max_ = X_train.max()It’s always important to verify our data when we load it to make sure it didn’t get corrupted:
print('X_train dim:\t%s' % (X_train.shape,))print('X_test dim:\t%s' % (X_test.shape,))print('y_train dim:\t%s' % (y_train.shape,))print('y_test dim:\t%s' % (y_test.shape,))print('X_train min:\t%s' % (min_))print('X_train max:\t%s' % (max_))print('y_train labels:\t%s' % (np.unique(y_train)))The preceding snippet will produce the following output, which tells us that the images have dimensions of 128 × 128 pixels and three channels (color). There are 16,800 training images and 4,200 test images. The labels only have a 1 in the second value, which indicates that they are not one-hot encoded. Indeed, by printing the unique values (np.unique(y_train)), we can tell that labels are represented as text: Correct for correctly masked, Incorrect for incorrectly masked, and None for no mask:
X_train dim: (16800, 128, 128, 3)
X_test dim: (4200, 128, 128, 3)
y_train dim: (16800, 1)
y_test dim: (4200, 1)
X_train min: 0.0 X_train max: 1.0 y_train labels: [‘Correct’ ‘Incorrect’ ‘None’]
Therefore, a preprocessing step we will need to perform is to One-Hot Encode (OHE) 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 into the training data (y_train). We can also extract the categories from the encoder into a list (labels_l) to verify that it has all three:
ohe = preprocessing.OneHotEncoder(sparse=False)ohe.fit(y_train)labels_l = ohe.categories_[0].tolist()print(labels_l)For reproducibility’s sake, always initialize your random seeds like this:
rand = 9os.environ['PYTHONHASHSEED'] = str(rand)tf.random.set_seed(rand)np.random.seed(rand)Making machine learning truly reproducible means also making it deterministic, which means that training with the same data will produce a model with the same parameters. Determinism is very difficult with deep learning and is often session-, platform-, and architecture-dependent. If you use an NVIDIA GPU, you can install a library called framework-reproducibility.
Many of the adversarial attack, defense, and evaluation methods we will study in this chapter are very resource-intensive, so if we used the entire test dataset with them, they could likely take many hours on a single method! For efficiency, it is strongly suggested to use samples of the test dataset. Therefore, we will create a medium 200-image sample (X_test_mdsample, y_test_mdsample) and a small 20-image sample (X_test_smsample, y_test_smsample) using np.random.choice:
sampl_md_idxs = np.random.choice(X_test.shape[0], 200, replace=False)X_test_mdsample = X_test[sampl_md_idxs]y_test_mdsample = y_test[sampl_md_idxs]sampl_sm_idxs = np.random.choice(X_test.shape[0], 20, replace=False)X_test_smsample = X_test[sampl_sm_idxs]y_test_smsample = y_test[sampl_sm_idxs]We have two sample sizes because some methods could take too long with a larger sample size. Now, let’s take a peek at what images are in our datasets. In the preceding code, we have taken a medium and small sample of our test dataset. We will place each image of our small sample in a 4 × 5 grid with the class label above it, with the following code:
plt.subplots(figsize=(15,12))for s in range(20): plt.subplot(4, 5, s+1) plt.title(y_test_smsample[s][0], fontsize=12) plt.imshow(X_test_smsample[s], interpolation='spline16') plt.axis('off')plt.show()The preceding code plots the grid of images in Figure 13.2:

Figure 13.2: A small test dataset sample of masked and unmasked faces
Figure 13.2 depicts a variety of correctly and incorrectly masked and unmasked faces of all ages, genders, and ethnicities. Despite the variety, one thing to note about this dataset is that it only has light blue surgical masks represented, and images are mostly at a front-facing angle. Ideally, we would generate an even larger dataset with all colors and types of masks and augment it further with random rotations, shears, and brightness adjustments, either before or during training. These augmentations would make for a much more robust model. Nevertheless, we must differentiate between this general type of robustness and adversarial robustness.
Loading the CNN base model
Section titled “Loading the CNN base model”You don’t have to train the CNN base model, but the code to do so is provided nonetheless in the GitHub repository. The pretrained model has also been stored there. We can quickly load the model and output its summary like this:
model_path = get_file('CNN_Base_MaskedFace_Net.hdf5',\ 'https://github.com/PacktPublishing/Interpretable-Machine- \ Learning-with-Python/blob/master/models/ \ CNN_Base_MaskedFace_Net.hdf5?raw=true')base_model = tf.keras.models.load_model(model_path)base_model.summary()The preceding snippet outputs the following summary:
Model: “CNN_Base_MaskedFaceNet_Model”
Layer (type) Output Shape Param #
Section titled “Layer (type) Output Shape Param #”conv2d_1 (Conv2D) (None, 126, 126, 16) 448 _________________________________________________________________ maxpool2d_1 (MaxPooling2D) (None, 63, 63, 16) 0
conv2d_2 (Conv2D) (None, 61, 61, 32) 4640
maxpool2d_2 (MaxPooling2D) (None, 30, 30, 32) 0
conv2d_3 (Conv2D) (None, 28, 28, 64) 18496
maxpool2d_3 (MaxPooling2D) (None, 14, 14, 64) 0
conv2d_4 (Conv2D) (None, 12, 12, 128) 73856
maxpool2d_4 (MaxPooling2D) (None, 6, 6, 128) 0
flatten_6 (Flatten) (None, 4608) 0
dense_1 (Dense) (None, 768) 3539712
dropout_6 (Dropout) (None, 768) 0
dense_2 (Dense) (None, 3) 2307
Section titled “dense_2 (Dense) (None, 3) 2307”Total params: 3,639,459 Trainable params: 3,639,459 Non-trainable params: 0
The summary has pretty much everything we need to know about the model. It has four convolutional layers (Conv2D), each followed by a max pool layer (MaxPooling2D). It then has a Flatten layer and a fully connected layer (Dense). Then, there’s more Dropout before the second Dense layer. Naturally, three neurons are in this final layer, corresponding to each class.
Assessing the CNN base classifier
Section titled “Assessing the CNN base classifier”We can evaluate the model using the test dataset with the evaluate_multiclass_mdl function. The arguments include the model (base_model), our test data (X_test), and the corresponding labels (y_test), as well as the class names (labels_l) and the encoder (ohe). Lastly, we don’t need to plot the ROC curves since, given the high accuracy, they won’t be very informative (plot_roc=False). This function returns the predicted labels and probabilities, which we can store as variables for later use:
y_test_pred, y_test_prob = mldatasets.evaluate_multiclass_mdl( base_model, X_test, y_test, labels_l, ohe, plot_conf_matrix=True, predopts={"verbose":1})The preceding code generates Figure 13.3, with a confusion matrix and performance metrics for each class:

Figure 13.3: The confusion matrix and predictive performance metrics for the base classifier, evaluated on the test dataset
Even though the confusion matrix in Figure 13.3 seems to suggest a perfect classification, pay attention to the circled areas. We can tell the model had some issues with misclassifying incorrectly masked faces once we see the recall (99.5%) breakdown.
Now, we can start attacking this model to assess how robust it actually is!
Learning about evasion attacks
Section titled “Learning about evasion attacks”There are six broad categories of adversarial attacks:
- Evasion: designing an input that can cause a model to make an incorrect prediction, especially when it wouldn’t fool a human observer. It can either be targeted or untargeted, depending on the attacker’s intention to fool the model into misclassifying a specific class (targeted) or, rather, misclassifying any class (untargeted). The attack methods can be white-box if the attacker has full access to the model and its training dataset, or black-box with only inference access. Gray-box sits in the middle. Black-box is always model-agnostic, whereas white and gray-box methods might be.
- Poisoning: injecting faulty training data or parameters into a model can come in many forms, depending on the attacker’s capabilities and access. For instance, for systems with user-generated data, the attacker may be capable of adding faulty data or labels. If they have more access, perhaps they can modify large amounts of data. They can also adjust the learning algorithm, hyperparameters, or data augmentation schemes. Like evasion, poisoning can also be targeted and untargeted.
- Inference: extracting the training dataset through model inference. Inference attacks also come in many forms and can be used for espionage (privacy attacks) through membership inference, which confirms if one example (for instance, a specific person) was in the training dataset. Attribute inference ascertains if an example category (for instance, an ethnicity) was represented in the training data. Input inference (also known as model inversion) has attack methods to extract a training dataset from a model rather than guessing and confirming. These have broad privacy and regulatory implications, especially in medical and legal applications.
- Trojaning: this implants malicious functionality activated with a trigger during inference but requires retraining the model.
- Backdooring: similar to trojans but a backdoor remains, even when a model is retrained from scratch.
- Reprogramming: remote sabotaging of a model during training by sneaking in examples that are specifically designed to produce specific outputs. For instance, if you provide enough examples labeled as tiger shark where four small black squares are always in the same place, the model will learn that that is a tiger shark, regardless of what it is, thus intentionally forcing the model to overfit.
The first three are the most studied forms of adversarial attacks. Attacks can be further subcategorized once we split them by stage and goal (see Figure 13.4). The stage is when the attack is perpetrated because it can impact the model training or its inference, and the goal is what the attacker hopes to gain from it. This chapter will only deal with evasion sabotage attacks because we expect hospital visitors, patients, and personnel to occasionally sabotage the production model:

Figure 13.4: Table of adversarial attack category methods by stage and goal
Even though we use white-box methods to attack, defend, and evaluate a model’s robustness, we don’t expect attackers to have this level of access. We will only use white-box methods because we have full access to the model. In other circumstances, such as a bank surveillance system with a thermal imaging system and a corresponding model to detect perpetrators, we could expect professional attackers to use black-box methods to find vulnerabilities! So, as defenders of this system, we would be wise to try the very same attack methods.
The library we will use for adversarial robustness is called the Adversarial Robustness Toolbox (ART), and it’s supported by the LF AI & Data Foundation – the same folks that support other open-source projects such as AIX360 and AIF360, explored in Chapter 11*, Bias Mitigation and Causal Inference Methods*. ART requires that attacked models are abstracted in an estimator or classifier, even if it’s a black-box one. We will use KerasClassifier for most of this chapter except for the last section, in which we will use TensorFlowV2Classifier. Initializing an ART classifier is simple. You must specify the model, and sometimes there are other required attributes. For KerasClassifier, all remaining attributes are optional, but it is recommended you use clip_values to specify the range of the features. Many attacks are input permutations, so knowing what input values are allowed or feasible is essential:
base_classifier = KerasClassifier( model=base_model, clip_values=(min_, max_))y_test_mdsample_prob = np.max( y_test_prob[sampl_md_idxs], axis=1)y_test_smsample_prob = np.max( y_test_prob[sampl_sm_idxs], axis=1)In the preceding code, we also prepare two arrays with probabilities for the predicted class of the medium and small samples. It is entirely optional, but these assist in placing the predicted probability next to the predicted label when plotting some examples.
Fast gradient sign method attack
Section titled “Fast gradient sign method attack”One of the most popular attack methods is the Fast Gradient Sign Method (FSGM or FGM). As the name implies, it leverages a deep learning model’s gradient to find adversarial examples. It performs small perturbations on the pixels of the input image, either additions or subtractions. Which one to use depends on the gradient’s sign, which indicates what direction would increase or decrease the loss according to the pixel’s intensity.
As with all ART attack methods, you first initialize it by providing the ART estimator or classifier. FastGradientMethod also requires an attack step size eps, which will condition the attack strength. Incidentally, eps stands for epsilon (
), which represents error margins or infinitesimal approximation errors. A small step size will cause pixel intensity changes to be less visible, but it will also misclassify fewer examples. A larger step size will cause more examples to be misclassified with more visible changes:
attack_fgsm = FastGradientMethod(base_classifier, eps=0.1)After initializing, the next step is to generate the adversarial examples. The only required attribute is original examples (X_test_mdsample). Please note that FSGM can be targeted, so there’s an optional targeted attribute in the initialization, but you would also need to provide corresponding labels in the generation. This attack is untargeted because the attacker’s intent is to sabotage the model:
X_test_fgsm = attack_fgsm.generate(X_test_mdsample)Generating the adversarial examples with FSGM is quick, unlike other methods, hence the “Fast”!
Now, we will do two things in one swoop. First, evaluate the adversarial examples (X_test_fgsm) against our base classifier’s model (base_classifier.model) with evaluate_multiclass_mdl. Then we can employ compare_image_predictions to plot a grid of images, contrasting the randomly selected adversarial examples (X_test_fgsm) against the original ones (X_test_mdsample) and their corresponding predicted labels (y_test_fgsm_pred, y_test_mdsample) and probabilities (y_test_fgsm_prob, y_test_mdsample_prob). We customize the titles and limit the grid to four examples (num_samples). By default, compare_image_predictions only compares misclassifications but an optional attribute, use_misclass, can be set to False to compare correct classifications:
y_test_fgsm_pred, y_test_fgsm_prob =
mldatasets.evaluate_multiclass_mdl(
base_classifier.model, X_test_fgsm, y_test_mdsample,
labels_l, ohe, plot_conf_matrix=False, plot_roc=False
)y_test_fgsm_prob = np.max(y_test_fgsm_prob, axis=1)mldatasets.compare_image_predictions( X_test_fgsm, X_test_mdsample, y_test_fgsm_pred,\y_test_mdsample.flatten(), y_test_fgsm_prob,\y_test_mdsample_prob, title_mod_prefix="Attacked:",\ title_difference_prefix="FSGM Attack Average Perturbation:",\ num_samples=4)The preceding code outputs a table first, which shows that the model has only 44% accuracy with FSGM-attacked examples! And even though it wasn’t a targeted attack, it was most effective toward correctly masked faces. So hypothetically, if perpetrators managed to cause this level of signal distortion or interference, they would severely undermine the security companies’ ability to monitor mask compliance.
The code also outputs Figure 13.5, which shows some misclassifications caused by the FSGM attack. The attack pretty much evenly distributed noise throughout the images. It also shows that the image was only modified by a mean absolute error of 0.092, and since pixel values range between 0 and 1, this means 9.2%. If you were to calibrate attacks so that they are less detectable but still impactful, you must note that an eps of 0.1 causes a 9.2% mean absolute perturbation, which reduces accuracy to 44%:

Figure 13.5: Plot comparing FSGM-attacked versus the original images for the base classifier
Speaking of less detectable attacks, we will now learn about Carlini and Wagner attacks.
Carlini and Wagner infinity norm attack
Section titled “Carlini and Wagner infinity norm attack”In 2017, Carlini and Wagner (C&W) employed three norm-based distance metrics:
,
, and
, measuring the difference between the original and adversarial example. In other papers, these metrics had already been discussed, including the FSGM one. The innovation introduced by C&W was how these metrics were leveraged, using a gradient descent-based optimization algorithm designed to approximate a loss function minima. Specifically, to avoid getting stuck at a local minimum, they use multiple starting points in the gradient descent. And so that the process “yields a valid image,” it evaluates three methods to box-constrain the optimization problem. In this case, we want to find an adversarial example where the distances between that example and the original image are minimal, while also remaining realistic.
All three C&W attacks (
,
, and
) use the Adam optimizer to quickly converge. Their main difference is the distance metric, of which
is arguably the best one. It’s defined as follows:
And because it’s the maximum distance to any coordinate, you make sure that the adversarial example is not just “on average” minimally different but also not too different anywhere in the feature space. That’s what would make an attack less detectable!
Initializing C&W infinity norm attacks and generating adversarial examples with them is similar to FSGM. To initialize CarliniLInfMethod, we define optionally a batch_size (the default is 128). Then, to generate an untargeted adversarial attack, the same applies as with FSGM. Only X is needed when untargeted, and y when targeted:
attack_cw = CarliniLInfMethod( base_classifier, batch_size=40)X_test_cw = attack_cw.generate(X_test_mdsample)We will now evaluate the C&W adversarial examples (X_test_cw) just as we did with FSGM. It’s exactly the same code, only with fsgm replaced with cw and different titles in compare_image_predictions. Just as with FSGM, the following code will yield a classification report and grid of images (Figure 13.6):
y_test_cw_pred, y_test_cw_prob =\
mldatasets.evaluate_multiclass_mdl( base_classifier.model, X_test_cw, y_test_mdsample, labels_l,\ ohe, plot_conf_matrix=False, plot_roc=False )y_test_cw_prob = np.max(y_test_cw_prob, axis=1)mldatasets.compare_image_predictions( X_test_cw,\X_test_mdsample, y_test_cw_pred,\y_test_mdsample.flatten(), y_test_cw_prob,\y_test_mdsample_prob, title_mod_prefix="Attacked:",\ title_difference_prefix="C&W Inf Attack Average Perturbation",\ num_samples=4)As outputted by the preceding code, the C&W adversarial examples have a 92% accuracy with our base model. The drop is sufficient to render the model useless for its intended purpose. If the attacker disturbed a camera’s signal just enough, they could achieve the same results. And, as you can tell by Figure 13.6, the perturbation of 0.3% is tiny compared to FSGM, but it was sufficient to misclassify 8%, including the four in the grid that seem apparent to the naked eye:

Figure 13.6: Plot comparing C&W infinity norm-attacked versus the original images for the base classifier
Sometimes it doesn’t matter if an attack goes undetected or not. The point of it is to make a statement, and that’s what adversarial patches can do.
Targeted adversarial patch attack
Section titled “Targeted adversarial patch attack”Adversarial Patches (APs) are a robust, universal, and targeted method. You generate a patch you can either superimpose on an image, or print and physically place in a scene to trick a classifier into ignoring everything else in the scene. It is designed to work under a wide variety of conditions and transformations. Unlike other adversarial example generation approaches, there’s no intention of camouflaging the attack because, essentially, you replace a detectable portion of the scene with the patch. The method works by leveraging a variant of Expectation Over Transformation (EOT), which trains images over transformations of a given patch on different locations of an image. What it learns is the patch that fools the classifier the most, given the training examples.
This method requires more parameters and steps than FSGM and C&W. For starters, we will use AdversarialPatchNumpy, which is the variant that works with any neural network image or video classifier. There’s also one for TensorFlow v2, but our base classifier is a KerasClassifier. The first argument is the classifier (base_classifier), and the other ones we will define are optional but highly recommended. The scaling ranges scale_min and scale_max are particularly important because they define how big can patches be in relation to the images – in this case, we want to test no smaller than 40% and no larger than 70%. Besides that, it makes sense to define a target class (target). In this case, we want the patch to target the “Correct” class. For the learning_rate and max iterations (max_iter), we use the defaults but note that these can be tuned to improve patch adversarial effectiveness:
attack_ap = AdversarialPatchNumpy( base_classifier, scale_min=0.4, scale_max=0.7,\ learning_rate=5., max_iter=500,\ batch_size=40, target=0)We don’t want the patch generation algorithm to waste time testing patches everywhere in images, so we can direct this effort by using a Boolean mask. This mask tells it where it can center the patch. To make the mask, we start by creating an array of zeros, 128 × 128. Then we place ones in the rectangular area between pixels 80–93 and 45–84, which loosely corresponds to cover the center of the mouth area in most of the images. Lastly, we expand the array’s dimensions so that it’s (1, W, H) and convert it to a Boolean. Then we can proceed to generate patches using the small-size test dataset samples and the mask:
placement_mask = np.zeros((128,128))placement_mask[80:93,45:83] = 1placement_mask = np.expand_dims(placement_mask, axis=0).astype(bool)patch, patch_mask = attack_ap.generate( x=X_test_smsample, y=ohe.transform(y_test_smsample), mask=placement_mask)We can now plot the patch with the following snippet:
plt.imshow(patch * patch_mask)The preceding code produced the image in Figure 13.7. As expected, it has plenty of the shades of blue found in masks. It also has bright red and yellow hues, mostly missing from training examples, which confuse the classifier:

Figure 13.7: AP generated image to misclassify as correctly masked
Unlike other methods, generate didn’t produce adversarial examples but a single patch, which is an image we can then place on top of images to create adversarial examples. This task is performed with apply_patch, which takes the original examples X_test_smsample and a scale; we will use 55%. It is also recommended to use a mask that will make sure the patch is applied where it makes more sense – in this case, in the area around the mouth:
X_test_ap = attack_ap.apply_patch( X_test_smsample, scale=0.55, mask=placement_mask)Now it’s time to evaluate our attack and examine some misclassifications. We will do exactly as before and reuse the code that produced Figure 13.5 and Figure 13.7, except we replace the variables so that they have ap and a corresponding title:
y_test_ap_pred, y_test_ap_prob =\
mldatasets.evaluate_multiclass_mdl( base_classifier.model, X_test_ap, y_test_smsample, labels_l, ohe, plot_conf_matrix=False, plot_roc=False )y_test_ap_prob = np.max(y_test_ap_prob, axis=1)mldatasets.compare_image_predictions( X_test_ap, X_test_smsample, y_test_ap_pred,\ y_test_smsample.flatten(), y_test_ap_prob, y_test_smsample_prob, title_mod_prefix="Attacked:",\ title_difference_prefix="AP Attack Average Perturbation:", num_samples=4)The preceding code yields the accuracy result of our attack at 65%, which is quite good considering how few examples it was trained on. AP needs more data than other methods. Targeted attacks, in general, need more examples to understand how to best target one class. The preceding code also produced the grid of images in Figure 13.8, which demonstrates how, hypothetically, if people walked around holding a cardboard patch in front of their face, they could easily fool the model:

Figure 13.8: Plot comparing AP-attacked versus original images for base classifier
So far, we have studied three attack methods but haven’t yet tackled how to defend against these attacks. We will explore a couple of solutions next.
Defending against targeted attacks with preprocessing
Section titled “Defending against targeted attacks with preprocessing”There are five broad categories of adversarial defenses:
- Preprocessing: changing the model’s inputs so that they are harder to attack.
- Training: training a new robust model that is designed to overcome attacks.
- Detection: detecting attacks. For instance, you can train a model to detect adversarial examples.
- Transformer: modifying model architecture and training so that it’s more robust – this may include techniques such as distillation, input filters, neuron pruning, and unlearning.
- Postprocessing: changing model outputs to overcome production inference or model extraction attacks.
Only the first four defenses work with evasion attacks, and in this chapter, we will only cover the first two: preprocessing and adversarial training. FGSM and C&W can be defended easily with either of these, but an AP is tougher to defend against, so it might require a stronger detection or transformer method.
Before we defend, we must create a targeted attack. We will employ Projected Gradient Descent (PGD), which is a strong attack very similar in output to FSGM – that is, it produces noisy images. We won’t explain PGD in detail here but what is important to note is, like FSGM, it is regarded as a first-order adversary because it leverages first-order information about a network (due to gradient descent). Also, experiments prove that robustness against PGD ensures robustness against any first-order adversary. Specifically, PGD is a strong attack, so it makes for conclusive benchmarks.
To create a targeted attack against the correctly masked class, it’s best that we only select examples that aren’t correctly masked (x_test_notmasked) and their corresponding labels (y_test_notmasked) and predicted probabilities (y_test_notmasked_prob). Then, we want to create an array with the class (Correct) that we want to generate adversarial examples for (y_test_masked):
not_masked_idxs = np.where(y_test_smsample != 'Correct')[0]X_test_notmasked = X_test_smsample[not_masked_idxs]y_test_notmasked = y_test_smsample[not_masked_idxs]y_test_notmasked_prob = y_test_smsample_prob[not_masked_idxs]y_test_masked = np.array( ['Correct'] * X_test_notmasked.shape[0]).reshape(-1,1)We initialize ProjectedGradientDescent as we did with FSGM, except we will set the maximum perturbation (eps), attack step size (eps_step), maximum iterations (max_iter), and targeted=True. Precisely because it is targeted, we will set both X and y:
attack_pgd = ProjectedGradientDescent( base_classifier, eps=0.3, eps_step=0.01,\ max_iter=40, targeted=True)X_test_pgd = attack_pgd.generate( X_test_notmasked, y=ohe.transform(y_test_masked))Now let’s evaluate the PGD attack as we did before, but this time, let’s plot the confusion matrix (plot_conf_matrix=True):
y_test_pgd_pred, y_test_pgd_prob =\
mldatasets.evaluate_multiclass_mdl( base_classifier.model, X_test_pgd, y_test_notmasked,\ labels_l, ohe, plot_conf_matrix=True, plot_roc=False )y_test_pgd_prob = np.max(y_test_pgd_prob, axis=1)The preceding snippet produces the confusion matrix in Figure 13.9. The PGD attack was so effective that it produced an accuracy of 0%, making all unmasked and incorrectly masked examples appear to be masked:

Figure 13.9: Confusion matrix for PGD attacked examples evaluated against the base classifier
Next, let’s run compare_image_prediction to see some random misclassifications:
mldatasets.compare_image_predictions( X_test_pgd, X_test_notmasked, y_test_pgd_pred,\y_test_notmasked.flatten(), y_test_pgd_prob,\y_test_smsample_prob, title_mod_prefix="Attacked:",\ num_samples=4, title_difference_prefix="PGD Attack Average Perturbation:")The preceding code plots the grid of images in Figure 13.10. The mean absolute perturbation is the highest we’ve seen so far at 14.7%, and all unmasked faces in the grid are classified as correctly masked:

Figure 13.10: Plot comparing PGD-attacked versus original images for the base classifier
The accuracy cannot get worse, and the images are grainy beyond repair. So how can we combat noise? If you recall, we have dealt with this problem before. In Chapter 7, Visualizing Convolutional Neural Networks, SmoothGrad improved saliency maps by averaging the gradients. It’s a different application but the same principle – just as with a human, a noisy saliency map is more challenging to interpret than a smooth one, and a grainy image is much more challenging for a model to interpret than a smooth one.
Spatial smoothing is just a fancy way of saying blur! However, what’s novel about it being introduced as an adversarial defense method is that the proposed implementation (SpatialSmoothing) calls for using the median and not the mean in a sliding window. The window_size is configurable, and it is recommended to adjust it where it is most useful as a defense. Once the defense has been initialized, you plug in the adversarial examples (X_test_pgd). It will output spatially smoothed adversarial examples (X_test_pgd_ss):
defence_ss = SpatialSmoothing(window_size=11)X_test_pgd_ss, _ = defence_ss(X_test_pgd)Now we can take the blurred adversarial examples produced and evaluate them as we did before – first, with evaluate_multiclass_mdl to get predicted labels (y_test_pgd_ss_pred) and probabilities (y_test_pgd_ss_prob) and the output of some predictive performance metrics. With compare_image_predictions to plot a grid of images, let’s use use_misclass=False to compare properly classified images – in other words, the adversarial examples that were defended successfully:
y_test_pgd_ss_pred, y_test_pgd_ss_prob =\
mldatasets.evaluate_multiclass_mdl( base_classifier.model, X_test_pgd_ss,\ y_test_notmasked, labels_l, ohe,\ plot_conf_matrix=False, plot_roc=False )y_test_pgd_ss_prob = np.max(y_test_pgd_ss_prob, axis=1)mldatasets.compare_image_predictions( X_test_pgd_ss, X_test_notmasked, y_test_pgd_ss_pred,\y_test_notmasked.flatten(), y_test_pgd_ss_prob,\y_test_notmasked_prob, use_misclass=False,\ title_mod_prefix="Attacked+Defended:", num_samples=4,\ title_difference_prefix="PGD Attack & Defended Average:")The preceding code yields an accuracy of 54%, which is much better than 0% before the spatial smoothing defense. It also produces Figure 13.11, which demonstrates how blur effectively thwarted the PGD attack. It even halved the mean absolute perturbation!

Figure 13.11: Plot comparing spatially smoothed PGD-attacked images versus the original images for the base classifier
Next, we will try another defense method in our toolbox: adversarial training!
Shielding against any evasion attack by adversarial training of a robust classifier
Section titled “Shielding against any evasion attack by adversarial training of a robust classifier”In Chapter 7, Visualizing Convolutional Neural Networks, we identified a garbage image classifier that would likely perform poorly in the intended environment of a municipal recycling plant. The abysmal performance on out-of-sample data was due to the classifier being trained on a large variety of publicly available images that don’t match the expected conditions, or the characteristics of materials that are processed by a recycling plant. The chapter’s conclusion called for training a network with images that represent their intended environment to make for a more robust model.
For model robustness, training data variety is critical, but only if it represents the intended environment. In statistical terms, it’s a question of using samples for training that accurately depict the population so that a model learns to classify them correctly. For adversarial robustness, the same principles apply. If you augment data to include plausible examples of adversarial attacks, the model will learn to classify them. That’s what adversarial training is in a nutshell.
Machine learning researchers in the adversarial robustness field suggest this form of defense is very effective against any kind of evasion attack, essentially shielding it. That being said, it’s not impervious. Its effectiveness is contingent on using the right kind of adversarial examples in training, the optimal hyperparameters, and so forth. There are some guidelines outlined by researchers, such as increasing the number of neurons in the hidden layers and using PGD or BIM to produce adversarial examples for the training. BIM stands for Basic Iterative Method. It’s like FSGM but not fast because it iterates to approximate the best adversarial example within a
-neighborhood for the original image. The eps attribute bounds this neighborhood.
Training a robust model can be very resource-intensive. It is not required because we can download one already trained for us, but it’s important to understand how to perform this with ART. We will explain these steps to give the option of completing the model training with ART. Otherwise, just skip the steps and download the trained model. The robust_model is very much like the base_model except we use equal-sized filters in the four convolutional (Conv2D) layers. We do this to decrease complexity to counter the complexity we add by quadrupling the neurons in the first hidden (Dense) layer, as suggested by the machine learning researchers:
robust_model = tf.keras.models.Sequential([ tf.keras.layers.InputLayer(input_shape=X_train.shape[1:]), tf.keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu'), tf.keras.layers.MaxPooling2D(pool_size=(2, 2)), tf.keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu'), tf.keras.layers.MaxPooling2D(pool_size=(2, 2)), tf.keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu'), tf.keras.layers.MaxPooling2D(pool_size=(2, 2)), tf.keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu'), tf.keras.layers.MaxPooling2D(pool_size=(2, 2)), tf.keras.layers.Flatten(), tf.keras.layers.Dense(3072, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(3, activation='softmax')], name='CNN_Robust_MaskedFaceNet_Model')robust_model.compile( optimizer=tf.keras.optimizers.Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])robust_model.summary()The summary() in the preceding code outputs the following. You can see that trainable parameters total around 3.6 million – similar to the base model:
Model: “CNN_Robust_MaskedFaceNet_Model”
Layer (type) Output Shape Param #
Section titled “Layer (type) Output Shape Param #”conv2d_1 (Conv2D) (None, 126, 126, 32) 896
maxpool2d_1 (MaxPooling2D) (None, 63, 63, 32) 0
conv2d_2 (Conv2D) (None, 61, 61, 32) 9248
maxpool2d_2 (MaxPooling2D) (None, 30, 30, 32) 0
conv2d_3 (Conv2D) (None, 28, 28, 32) 9248
maxpool2d_3 (MaxPooling2D) (None, 14, 14, 32) 0
conv2d_4 (Conv2D) (None, 12, 12, 32) 9248
maxpool2d_4 (MaxPooling2D) (None, 6, 6, 32) 0
flatten (Flatten) (None, 1152) 0
dense_1 (Dense) (None, 3072) 3542016
dropout (Dropout) (None, 3072) 0
dense_2 (Dense) (None, 3) 9219
Section titled “dense_2 (Dense) (None, 3) 9219”Total params: 3,579,875 Trainable params: 3,579,875 Non-trainable params: 0
Next, we can adversarially train the model by first initializing a new KerasClassifier with the robust_model. Then, we initialize a BasicIterativeMethod attack on this classifier. Lastly, we initialize AdversarialTrainer with the robust_classifier and the BIM attack and fit it. Please note that we saved the BIM attack into a variable called attacks because this could be a list of ART attacks instead of a single one. Also, note that AdversarialTrainer has an attribute called ratio. This attribute determines what percentage of the training examples are adversarial examples. This percentage dramatically impacts the effectiveness of adversarial attacks. If it’s too low, it might not perform well with adversarial examples, and if it’s too high, it might perform less effectively with non-adversarial examples. If we run the trainer, it will likely take many hours to complete, so don’t get alarmed:
robust_classifier = KerasClassifier( model=robust_model, clip_values=(min_, max_))attacks = BasicIterativeMethod( robust_classifier, eps=0.3, eps_step=0.01, max_iter=20)trainer = AdversarialTrainer( robust_classifier, attacks, ratio=0.5)trainer.fit( X_train, ohe.transform(y_train), nb_epochs=30, batch_size=128)If you didn’t train the robust_classifier, you can download a pretrained robust_model and initialize the robust_classifier with it like this:
model_path = get_file( 'CNN_Robust_MaskedFace_Net.hdf5', 'https://github.com/PacktPublishing/Interpretable-Machine- \ Learning-with-Python/blob/master/models/ \ CNN_Robust_MaskedFace_Net.hdf5?raw=true')robust_model = tf.keras.models.load_model(model_path)robust_classifier = KerasClassifier( model=robust_model, clip_values=(min_, max_))Now, let’s evaluate the robust_classifier against the original test dataset using evaluate_multiclass_mdl. We set plot_conf_matrix=True to see the confusion matrix:
y_test_robust_pred, y_test_robust_prob =\
mldatasets.evaluate_multiclass_mdl( robust_classifier.model, X_test, y_test, labels_l, ohe,\ plot_conf_matrix=True, predopts={"verbose":1})The preceding code outputs the confusion matrix and performance metrics in Figure 13.12. It’s 1.8% less accurate than the base classifier. Most of the misclassifications are with correctly masked faces getting classified as incorrectly masked. There’s certainly a trade-off when choosing a 50% adversarial example ratio, or perhaps we can tune the hyperparameters or the model architecture to improve this:

Figure 13.12: Robust classifier confusion metrics and performance metrics
Let’s see how the robust model fares against adversarial attacks. Let’s use FastGradientMethod again, but this time, replace base_classifier with robust_classifier:
attack_fgsm_robust = FastGradientMethod( robust_classifier, eps=0.1)X_test_fgsm_robust = attack_fgsm_robust.generate(X_test_mdsample)Next, we can employ evaluate_multiclass_mdl and compare_image_predictions to measure and observe the effectiveness of our attack, but this time against the robust_classifier:
y_test_fgsm_robust_pred, y_test_fgsm_robust_prob =\
mldatasets.evaluate_multiclass_mdl( robust_classifier.model, X_test_fgsm_robust,\ y_test_mdsample, labels_l, ohe,\ plot_conf_matrix=False, plot_roc=False )y_test_fgsm_robust_prob = np.max( y_test_fgsm_robust_prob, axis=1)mldatasets.compare_image_predictions( X_test_fgsm_robust, X_test_mdsample, y_test_fgsm_robust_pred, num_samples=4,\y_test_mdsample.flatten(), y_test_fgsm_robust_prob,\y_test_mdsample_prob, title_mod_prefix="Attacked:",\ title_difference_prefix="FSGM Attack Average Perturbation:")The preceding snippet outputs some performance metrics, which evidenced a 95.5% accuracy. If you compare how an equally strengthened FSGM attack fared against the base_classifier, it yielded a 44% accuracy. That was quite an improvement! The preceding code also produces the image grid in Figure 13.13. You can tell how the FSGM attack against the robust model makes less grainy and more patchy images. On average, they are less perturbed than they were against the base model because so few of them were successful, but those that were significantly degraded. It appears as if the FSGM reduced their color depth from millions of possible colors (24+ bits) to 256 (8-bit) or 16 (4-bit) colors. Of course, an evasion attack can’t actually do that, but what happened was that the FSGM algorithm converged at the same shades of blue, brown, red, and orange that could fool the classifier! Other shades remain unaltered:

Figure 13.13: Plot comparing FSGM-attacked versus the original images for the robust classifier
So far, we have evaluated the robustness of models but only against one attack strength, without factoring in possible defenses, thus evaluating its robustness. In the next section, we will study a method that does this.
Evaluating adversarial robustness
Section titled “Evaluating adversarial robustness”It’s necessary to test your systems in any engineering endeavor to see how vulnerable they are to attacks or accidental failures. However, security is a domain where you must stress-test your solutions to ascertain what level of attacks are needed to make your system break down beyond an acceptable threshold. Furthermore, figuring out what level of defense is needed to curtail an attack is useful information too.
Comparing model robustness with attack strength
Section titled “Comparing model robustness with attack strength”We now have two classifiers we can compare against an equally strengthened attack, and we try different attack strengths to see how they fare across all of them. We will use FSGM because it’s fast, but you could use any method!
The first attack strength we can assess is no attack strength. In other words, what is the classification accuracy against the test dataset with no attack? We already had stored the predicted labels for both the base (y_test_pred) and robust (y_test_robust_pred) models, so this is easy to obtain with scikit-learn’s accuracy_score metric:
accuracy_base_0 = metrics.accuracy_score( y_test, y_test_pred)accuracy_robust_0 = metrics.accuracy_score( y_test, y_test_robust_pred)We can now iterate across a range of attack strengths (eps_range) between 0.01 and 0.9. Using linspace, we can generate 9 values between 0.01 and 0.09 and 9 values between 0.1 and 0.9, and concatenate them into a single array. We will test attacks for these 18 eps values by for-looping through all of them, attacking each model, and retrieving the post-attack accuracies with evaluate. The respective accuracies are appended to two lists (accuracy_base, accuracy_robust). And after the for loop, we prepend 0 to the eps_range to account for the accuracies prior to any attacks:
eps_range = np.concatenate( (np.linspace(0.01, 0.09, 9), np.linspace(0.1, 0.9, 9)), axis=0).tolist()accuracy_base = [accuracy_base_0]accuracy_robust = [accuracy_robust_0]for eps in tqdm(eps_range, desc='EPS'): attack_fgsm.set_params(**{'eps': eps}) X_test_fgsm_base_i =attack_fgsm.generate(X_test_mdsample) _, accuracy_base_i =\ base_classifier.model.evaluate( X_test_fgsm_base_i, ohe.transform(y_test_mdsample) ) attack_fgsm_robust.set_params(**{'eps': eps}) X_test_fgsm_robust_i=attack_fgsm_robust.generate( X_test_mdsample ) _, accuracy_robust_i =\ robust_classifier.model.evaluate( X_test_fgsm_robust_i, ohe.transform(y_test_mdsample) ) accuracy_base.append(accuracy_base_i) accuracy_robust.append(accuracy_robust_i)eps_range = [0] + eps_rangeNow, we can plot the accuracies for both classifiers across all attack strengths with the following code:
fig, ax = plt.subplots(figsize=(14,7))
ax.plot( np.array(eps_range), np.array(accuracy_base),\'b–', label='Base classifier')
ax.plot( np.array(eps_range), np.array(accuracy_robust),\'r–', label='Robust classifier')legend = ax.legend(loc='upper center')plt.xlabel('Attack strength (eps)')plt.ylabel('Accuracy')The preceding code generates Figure 13.14, which demonstrates that the robust model performs better between attack strengths of 0.02 and 0.3 but then does consistently about 10% worse:

Figure 13.14: Accuracy measured for the robust and base classifiers at different FSGM attack strengths
One thing that Figure 13.14 fails to account for is defenses. For example, if hospital cameras were constantly jammed or tampered with, the security company would be remiss not to defend their models. The easiest way to do so for this kind of attack is with some sort of smoothing.
Adversarial training also produces an empirically robust classifier that you cannot guarantee will work under certain pre-defined circumstances, which is why there’s a need for certifiable defenses.
Mission accomplished
Section titled “Mission accomplished”The mission was to perform some adversarial robustness tests on their face mask model to determine if hospital visitors and staff can evade mandatory mask compliance. The base model performed very poorly on many evasion attacks, from the most aggressive to the most subtle.
You also looked at possible defenses to these attacks, such as spatial smoothing and adversarial retraining. And then, you explored ways to evaluate the robustness of your proposed defenses. You can now provide an end-to-end framework to defend against this kind of attack. That being said, what you did was only a proof of concept.
Now, you can propose training a certifiably robust model against the attacks the hospitals expect to encounter the most. But first, you need the ingredients for a generally robust model. To this end, you will need to take all 210,000 images in the original dataset, make many variations on mask colors and types with them, and augment them even further with reasonable brightness, shear, and rotation transformations. Lastly, the robust model needs to be trained with several kinds of attacks, including several kinds of APs. These are important because they mimic the most common compliance evasion behavior of concealing faces with body parts or clothing items.
Summary
Section titled “Summary”After reading this chapter, you should understand how attacks can be perpetrated on machine learning models and evasion attacks in particular. You should know how to perform FSGM, BIM, PGD, C&W, and AP attacks, as well as how to defend against them with spatial smoothing and adversarial training. Last but not least, you know how to evaluate adversarial robustness.
The next chapter is the last one, and it outlines some ideas on what’s next for machine learning interpretation.
Dataset sources
Section titled “Dataset sources”- Adnane Cabani, Karim Hammoudi, Halim Benhabiles, and Mahmoud Melkemi, 2020, MaskedFace-Net - A dataset of correctly/incorrectly masked face images in the context of COVID-19, Smart Health, ISSN 2352–6483, Elsevier: https://doi.org/10.1016/j.smhl.2020.100144 (Creative Commons BY-NC-SA 4.0 license by NVIDIA Corporation)
- Karras, T., Laine, S., and Aila, T., 2019, A Style-Based Generator Architecture for Generative Adversarial Networks. 2019 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), 4396–4405: https://arxiv.org/abs/1812.04948 (Creative Commons BY-NC-SA 4.0 license by NVIDIA Corporation)
Further reading
Section titled “Further reading”- Polyakov, A., 2019, Aug 6, How to attack Machine Learning (Evasion, Poisoning, Inference, Trojans, Backdoors) [blog post]: https://towardsdatascience.com/how-to-attack-machine-learning-evasion-poisoning-inference-trojans-backdoors-a7cb5832595c
- Carlini, N., & Wagner, D., 2017, Towards Evaluating the Robustness of Neural Networks. 2017 IEEE Symposium on Security and Privacy (SP), 39–57: https://arxiv.org/abs/1608.04644
- Brown, T., Mané, D., Roy, A., Abadi, M., and Gilmer, J., 2017, Adversarial Patch. ArXiv: https://arxiv.org/abs/1712.09665