Evasion Attacks against Deployed AI
local graph
Chapter 7 — Evasion Attacks against Deployed AI
Section titled “Chapter 7 — Evasion Attacks against Deployed AI”We looked at adversarial attacks targeting model development and its dependencies in the previous three chapters. In the ever-evolving landscape of AI and ML, adversaries will not always have access to the model development process. As we delve deeper into the intricacies of adversarial AI, our journey brings us to a new frontier—the realm of evasion attacks staged against deployed models. Evason attacks entail sophisticated techniques that adversaries can employ to deceive, manipulate, and ultimately compromise the integrity of ML models. This chapter covers evasion attacks and how to defend against them with hands-on examples. We will use the Adversarial Robustness Toolbox (ART) and TextAttack to assess and enhance model resilience against evasion attacks.
By the end of this chapter, you will have a deeper comprehension of evasion attacks and practical experience in implementing and defending against them, setting a solid foundation for building more secure AI systems.
The chapter covers the following topics:
- Fundamentals of evasion attacks
- Perturbations and image evasion attack techniques
- Adversarial patches for evasion attacks in the physical domain
- Evasion attacks in NLP and text misclassification
- Universal evasion attacks and evasion attack transferability in black-box settings
- Defending against evasion attacks
Let’s start with gaining a general understanding of evasion attacks.
Fundamentals of evasion attacks
Section titled “Fundamentals of evasion attacks”Evasion attacks in adversarial AI are sophisticated techniques designed to mislead Machine Learning (ML) models deliberately. They occur during the inference stage, which is when a trained model is used to make predictions. Adversaries craft these attacks by introducing subtle, often imperceptible, perturbations to the input data, aiming to cause the model to err. They do that by targeting the deployed model and the inference API, for instance, the ImRecS app we used in previous chapters.
Typically found in image classification, an evasion attack might involve adding noise to an image that is invisible to the human eye but causes an AI model to misclassify the image. For example, what is clearly an image of a panda to a human observer might be classified as a gibbon by the AI after applying adversarial noise. These perturbations are often optimized by algorithms designed to probe the model’s weaknesses, exploiting gradients (in gradient-based models) or other avenues to find the least noticeable changes that will lead to misclassification.
The evolution of evasion attacks has kept pace with advances in ML, becoming more sophisticated as models become more complex. The initial forays into adversarial attacks on ML models involved simple manipulations that have since given way to more complex algorithms capable of fooling basic classifiers and state-of-the-art deep learning networks. These attacks exploit the inherent limitations of learning algorithms, such as overfitting the training data and the inability to extrapolate the learned patterns to slightly modified inputs that haven’t been encountered before.
The success of these attacks is measured by the attacker’s ability to cause misclassification without detection, which is aided by an understanding of the model’s decision boundaries and the data it processes. Without access to the training process or the model itself, reconnaissance approaches become critical to staging successful evasion attacks.
Before we delve into understanding evasion techniques, let us explore the significance and impact of evasion attacks.
Importance of understanding evasion attacks
Section titled “Importance of understanding evasion attacks”Understanding evasion attacks is paramount for several reasons. First and foremost, deploying ML models in critical systems—ranging from finance and healthcare to autonomous vehicles and security—means that the stakes of adversarial attacks are higher than ever. In these applications, a successful evasion attack could lead to significant financial loss, endanger human life, or compromise sensitive data. By understanding the mechanics of these attacks, we can devise more robust models that can withstand adversarial conditions.
Moreover, the ML models’ inability to handle adversarial examples raises questions about their reliability and trustworthiness. To adopt these technologies, industries and end users must be assured of their resilience against such vulnerabilities. This requires a comprehensive study of how evasion attacks are constructed and how they can be detected or prevented.
The study of evasion attacks also extends beyond immediate practical implications; it touches on the theoretical foundations of ML and AI. The susceptibility of ML models to such attacks reveals the limitations of current algorithms and provides a fertile ground for research into more robust learning paradigms. It challenges researchers and practitioners to rethink model architectures, loss functions, and even the data processing pipelines to enhance security against these adversarial exploits.
Finally, as ML becomes more pervasive, the regulatory landscape is beginning to shift. Governments and international bodies are increasingly concerned with AI’s ethical implications and potential harms. Understanding evasion attacks is critical for policymakers to establish guidelines and regulations that ensure the safe deployment of AI technologies.
In conclusion, the study of evasion attacks is a critical component of adversarial AI research. It demands a cross-disciplinary approach encompassing technical, ethical, and regulatory perspectives to build intelligent, secure, and trustworthy systems. The potential impact of evasion attacks on AI applications underscores the urgency of this endeavor and mandates a proactive and informed response from the AI community.
The impact of evasion attacks will become more apparent in the following few sections as we discuss typical evasion techniques and the role of perturbations.
But how do attackers stage evasion attacks, especially black-box attacks on deployed AI APIs? The first step is to collect as much information as possible about the target model using reconnaissance techniques.
Let’s take a look at the reconnaissance techniques an attacker can use.
Reconnaissance techniques for evasion attacks
Section titled “Reconnaissance techniques for evasion attacks”Before attackers can craft and deploy evasion attacks against an AI system effectively, they must gather as much information as possible about the target model. This phase, known as reconnaissance, is critical in understanding the model’s potential vulnerabilities and the most effective strategies for exploitation. MITRE ATLAS provides a survey of reconnaissance techniques with some use cases at https://atlas.mitre.org/tactics/AML.TA0002/.
Here we will delve into the most common avenues through which attackers can gather this intelligence.
Model cards, published papers, and blogs
Section titled “Model cards, published papers, and blogs”For published models on hubs such as Hugging Face, model cards will be the starting point and the attacker will have access to the model to dissect. For proprietary models, the first step in reconnaissance often involves scouring academic literature and industry blogs for details on the target AI system’s architecture and training. Many organizations pride themselves on transparency and contribution to the AI community by publishing their findings and methodologies.
Attackers can exploit this information by identifying model architectures and training techniques with known vulnerabilities, giving them a blueprint for crafting attacks. For instance, if a company reveals that their image recognition system is based on a particular CNN architecture, an attacker can refer to literature identifying weaknesses in that specific model type.
Social engineering
Section titled “Social engineering”Attackers may use social engineering to trick insiders into revealing information about the AI system. Through carefully crafted phishing emails or social media interactions, they could solicit information about the datasets used for training, the type of ML model employed, or details about the feature sets that influence the model’s decisions.
Online probing
Section titled “Online probing”If the model is deployed as an API or an online service, attackers can engage in online probing. They can infer the model’s behavior by carefully crafting input data and observing the model’s responses. For example, attackers can use the outputs from the API to estimate the confidence level of certain classifications and then iteratively modify their inputs to find the decision boundary.
Note
Gray-box attacks, where the attacker has some information, such as documentation, will be easier than black-box attacks, where attackers will have to experiment with the requests and understand how the model works. The success will rely on additional information from other forms of reconnaissance, the verbosity of error messages leaking syntax information, or web and mobile frontends where the attacker can reverse-engineer and trace how the inference API is used.
Even if the inference API is not publicly exposed, attackers can try to understand a model in other, more indirect ways. For instance, if a company uses ML to filter spam emails, an attacker could send emails containing slight variations to see which ones are classified as spam and which are not, effectively mapping the contours of the model’s decision-making process.
More advanced techniques can include the use of reinforcement learning, which, because of the reward-based dynamic adaptation, can be very effective in query optimization. In the paper Robustness with Query-efficient Adversarial Attack using Reinforcement Learning by Sarkar et al., presented at CVPRW 2023, the researchers demonstrate how effective reinforcement learning can be in adversarial attacks, especially in image classification. You can find the full paper at https://openaccess.thecvf.com/content/CVPR2023W/AML/papers/Sarkar_Robustness_With_Query-Efficient_Adversarial_Attack_Using_Reinforcement_Learning_CVPRW_2023_paper.pdf.
Open source model repositories
Section titled “Open source model repositories”Repositories such as GitHub, Model Zoo, and Hugging Face host a plethora of ML models where attackers can find models similar to their target and conduct dry runs to refine their evasion techniques. For example, an attacker might use a pre-trained model from TensorFlow Hub that resembles the target model and experiment with different evasion strategies to see which one is most effective without directly probing the target system.
Transfer learning
Section titled “Transfer learning”Understanding that many AI systems are built upon pre-trained models using transfer learning, attackers can exploit the vulnerabilities inherent in the base models. If the base model is publicly available, attackers can experiment locally to create effective adversarial examples. Then, they use the transferability properties of adversarial payloads to apply these attacks to the target model, which is likely to be affected similarly. Attackers can also make intelligent guesses by the type of application. Pre-trained models such as ResNet50 and Google’s InceptionV3 are a popular choice for image recognition, whereas BERT and OpenAI’s GPT-2 are popular for Natural Language Processing (NLP) and language models.
Use of shadow models
Section titled “Use of shadow models”In more advanced scenarios, the attackers will use a more sophisticated approach technique to create shadow models —replicas of the target model created to approximate its behavior without having direct access to the model itself. Attackers will combine findings from all other techniques to construct a close-enough shadow model. This may include training these models on datasets that are similar or, in some cases, identical to the data used by the target system (obtained through reverse engineering, publicly available datasets, or data breaches). Attackers can use shadow models with sophisticated gradient-based algorithms or other techniques to generate and test their adversarial examples in a sandbox environment. This approach allows for an iterative process of refining attacks without risking detection by the target system’s security measures.
Note
Attackers may also use extraction attacks, a special type of probing, to extract model weights and parameters that can aid in model cloning. Extraction attacks are considered privacy adversarial attacks on their own, and we discuss them in more detail in Chapter 8.
In all these scenarios, attackers effectively map the landscape before setting their plans into motion. They are the digital equivalent of cartographers, charting the terrain before an invasion. This preparatory step often makes evasion attacks possible and potentially successful, especially when combined with advanced techniques such as adversarial ML.
Understanding the reconnaissance phase is critical for defenders as well. By recognizing how attackers could gather information about their systems, ML practitioners can obscure sensitive details, harden their systems against probing with API rate limiting, and implement monitoring to detect when such reconnaissance activities occur.
Once the attacker has collected enough information, they will start experimenting using some well-known evasion attack techniques. We will explore these techniques in detail so that we can gain a solid understanding of how attackers stage evasion attacks.
Perturbations and image evasion attack techniques
Section titled “Perturbations and image evasion attack techniques”Perturbations are essential to deceiving ML models in evasion attacks. Perturbations are crafted modifications that cause a model to make incorrect predictions when applied to input data. Perturbations are crafted using advanced calculations to make them as imperceptible as possible, and this can make them highly effective in escaping the attention of humans or even AI systems.
This subtle manipulation of data is central to evasion tactics, aiming to either confound the model entirely (untargeted attacks) or misguide it to a specific, erroneous outcome (targeted attacks). The sophistication of these techniques lies in their ability to alter the data imperceptibly to human observers while leading the AI astray—a trait that underscores their potential danger and the necessity for robust defenses.
Generating perturbations relies on the precise calculation of adversarial AI using optimization techniques that involve gradient descent with respect to normal input and is not dissimilar to the use of gradient descent in neural networks, as we discussed in Chapter 1. Perturbations are calculated with precision by fine-tuning norms, which are important parameters to create adversarial samples that meet the evasion and undetectability criteria. Norms are mathematical measures to quantify the following:
- The size of perturbation, in other words, the features to alter (L1 norm)
- Its closeness – or Euclidean distance – to the original sample (L2 norm)
- The maximum change to any feature in the data (infinity norm, or L∞)
By fine-tuning these norms, we craft changes that are subtle enough to remain undetected by the human eye and significant enough to mislead the model.
Different algorithms and techniques have been developed to perform this task, and each brings its unique approach and complexity. The effect of these techniques may differ depending on the type of the network (e.g., CNN or RNN) and its complexity and attackers will have to experiment with them
In the next few sections, we will delve into the best-known techniques, including the Fast Gradient Sign Method (FGSM), the Basic Iterative Method (BIM), the Projected Gradient Descent (PGD), the Carlini and Wagner (C&W) attack, and the Jacobian-based Saliency Map Attack (JSMA).
These methods vary in intent and suitability, from FGSM’s broad and rapid approach to PGD’s careful, multi-step optimization and JSMA’s precise targeting. The C&W attack, in particular, is noted for its effectiveness against models equipped with defensive strategies. This is not an exhaustive list of techniques but represents a good sample of the approaches an attacker may use to stage an evasion attack.
By understanding these techniques, we also understand the spectrum of challenges we may encounter when defending against evasion attacks.
We will use our ImRecS sample to describe evasion attacks using a couple of attack scenarios.
Evasion attack scenarios
Section titled “Evasion attack scenarios”ImRecS has decided to move away from their own CIFAR-10 CNN and adopt a pretrained ResNet50. This is to allow handling images of higher resolution and future flexibility.
The CTO of ImRecS has blogged about the transition as a sign of their team adopting better technologies. This is picked by a group of adversaries that has been planning to evade ImRecS’s notice.
The adversaries will aim to find perturbations in two attack scenarios:
- Untargeted evasion: The attackers can see a fast and easy way to evade the detection of planes
- Targeted evasion: The attackers are seeking a more sophisticated evasion so that planes are misclassified to birds, to avoid raising suspicion
The attackers experiment with three different images (plane1.jpg, plane2.jpg, and plane3.jpg), shown in the following figure, classified by ResNet50 as 404 (airliner), 908 (wing), and 404 (``airliner), respectively:

Figure 7.1 – Test images for evasion attacks
We will start with the simplest one, FGSM.
One-step perturbation with FGSM
Section titled “One-step perturbation with FGSM”FGSM is a foundational technique in adversarial ML. It is a white-box attack, meaning the attacker has access to the model architecture and weights. FGSM works by using the gradients of the neural network to create an adversarial example.
It does it in the opposite direction of the usual gradient descent of a neural network. It perturbs an image by adjusting each pixel in the direction that increases the loss with respect to the target label. For an input image, FGSM adds or subtracts a small error to each pixel in the direction of the gradient, increasing the classification loss.
FGSM is quick and efficient, making it accessible to entry-level attackers but also suitable for testing model robustness against adversarial examples in scenarios where computational resources or time are limited.
This provides a unique opportunity for attackers to utilize ResNet50 and stage evasion attacks against ImRecS’s prediction API.
Attack example
Section titled “Attack example”Assume that you are the attacker and have decided to use ART to try out the FGSM attack using Keras with the TensorFlow backend. Once you have created and tested perturbations locally, you will try them against the ImRecS service.
You can create your own adversarial FSGM lab by following these steps.
First, ensure you have the necessary packages installed:
pip install tensorflow keras artNow, let’s implement FGSM with the following code in a Jupyter notebook. The code illustrates how to do a simple untargeted attack (i.e., any incorrect classification) and demonstrates the basic workflow ART uses to stage evasion attacks with various techniques.
The workflow for any evasion attack in ART is similar:
- We load the target or shadow models in black-box attacks. In this case, we know the target uses ResNet and will use a copy directly using the built-in
from tensorflow.keras.applications.resnet_v2 import ResNet50V2# Load a pre-trained ResNet50 model trained on ImageNetmodel = ResNet50V2(weights='imagenet')
- Create an ART classifier wrapper for
from art.estimators.classification import KerasClassifier# create an classifier from the model and constrain input ranges to range for image values i.e 0..255# use_logits=false to denote a model using probabilities for its output and is the default value. You can specify True if the target model outputs raw logits.classifier = KerasClassifier(model=model, clip_values=(0, 255), use_logits=False)
- Use an ART attack object –
FastGradientMethodin our case – and create perturbations. The object will apply the technique and its math transparently, shielding you from complicated details. The following code shows you how that is done for an untargeted attack:The code will usefrom art.attacks.evasion import FastGradientMethod# Craft adversarial examples using FGSMdef fgsm_attack(model, sample, epsilon = 0.01):fgsm = FastGradientMethod(estimator=classifier, eps=epsilon)# Generate the adversarial examplex_adv = fgsm.generate(x=sample)adv_img = show_adversarial_images(sample,x_adv)return x_adv, adv_imgFastGradientMethodto create an FSGM attack with the estimator and a configurableepsilonvalue to return an adversarial image. Theepsilonvalue determines the magnitude of the perturbation; it needs to be small enough to keep the modifications imperceptible, but this will not always be possible. We can display the original image, the perturbation, and the adversarial image using a helper function:Note thedef show_adversarial_images(sample, x_adv):# Calculate the perturbationperturbation = x_adv - sample# Scaling perturbation for visualizationperturbation_display = perturbation / (2 * np.max(np.abs(perturbation))) + 0.5perturbation_img = keras_image.array_to_img(perturbation_display[0])original_img = keras_image.array_to_img(sample[0])adv_img = keras_image.array_to_img(x_adv[0])# Show images side by sideshow_images([original_img, perturbation_img, adv_img], ['Original Image', 'Perturbation', 'Adversarial Image'])print('prediction for original image: \n',predict(sample))print('prediction for adversarial image: \n',predict(x_adv))return adv_imgpredictmethod is a utility function in the notebook to call the model’spredictfunction and format the response. - Test against the target model and fine-tune the parameters until you get it right. You most likely will. In our case, we will use a preloaded
plane1 = load_preprocess_show('../images/plane1.png')_,_ = fgsm_attack(model,plane1)
The following screenshot shows the results of our FSGM attack, which successfully misclassifies an airliner as a warplane with the minimum of effort by adding an imperceptible perturbation to the original image:

Figure 7.2 – FSGM attack successfully misclassifying an airliner
Repeating the attacks for the two other images proves unsuccessful. Although the perturbation misclassifies the images, the misclassification is to airship, which is not useful for the attacker. The method produces more convincing misclassifications, but only if we increase epsilon dramatically, which makes the image visibly change.
Similarly, targeted attacks with FSGM fail. The targeted attack is almost identical to the previous one, except that we define the target label, one-hot-encode it, pass it to our attack object, and set the targeted parameter to True:
from art.attacks.evasion import FastGradientMethod# Craft adversarial examples using FGSM for targeted attacksdef fgsm_targeted_attack(sample, target_label=None, classifier=classifier, epsilon=0.01): target_one_hot = np.zeros((1, 1000)) target_one_hot[0, target_label] = 1 fgsm = FastGradientMethod(estimator=classifier, eps=epsilon, targeted=True, y=target_one_hot) # Generate the adversarial example x_adv = fgsm.generate(x=sample, y=target_class) adv_img = show_adversarial_images(sample, x_adv) return x_adv, adv_imgWe can now test it as follows:
_, _ = fgsm_targeted_attack(plane1, target_class=8)Here, 8 is the ImageNet label for a hen. We test it against a number of bird labels:
bird_labels = [8, 10, 11, 12, 13] # Imagenets Class IDs for Hen, Brambling, Goldfinch, Junco, Indigo buntingThe targeted attack is unsuccessful, with the first and third planes being classified correctly or misclassified as happened with the untargeted attack. The second image is misclassified in an untargeted way as shovel, alp, and, a few times, ptarmigan.
The FGSM method is an important concept to understand in the field of adversarial ML, as it showcases the vulnerability of neural networks to seemingly minor perturbations. It is, however, a relatively simple one-step technique. The following section will discuss more advanced multi-step techniques to generate perturbations.
Basic Iterative Method (BIM)
Section titled “Basic Iterative Method (BIM)”BIM is an enhancement over single-step adversarial attack methods such as FGSM. While FGSM makes a single large update to the input image, BIM applies multiple small updates, iteratively nudging the input image toward the adversarial target. This iterative nature often results in more effective and subtle perturbations.
Attack example
Section titled “Attack example”The BIM implementation in ART uses a PGD attack under the hood by setting the step size and number of iterations accordingly. However, PGD offers more flexibility and robustness compared to BIM. We will cover PGD later in this chapter. For now, here is an example of how you’d use BIM in ART:
from art.attacks.evasion import BasicIterativeMethoddef bmi_attack(sample, wrapper=classifier, epsilon=0.01, eps_step=0.001, max_iter=10, batch_size=32): bmi = BasicIterativeMethod(estimator=wrapper, eps=epsilon, eps_step=0.001, max_iter=10,batch_size=32) # Generate the adversarial example x_adv = bmi.generate(x=sample) adv_img = show_adversarial_images(sample,x_adv) return x_adv, adv_img_,_ = bmi_attack(plane1)The results are similar to FSGM but an attacker has the option to fine-tune the other parameters.
Note
We have covered BIM here for completeness. In attack scenarios, attackers will use PGD.
One of the challenges in adapting FSGM and BIM to complex real-world scenarios is that both treat all input data uniformly. In the next section, we will explore a different technique that focuses on changing the most important data points.
Jacobian-based Saliency Map Attack (JSMA)
Section titled “Jacobian-based Saliency Map Attack (JSMA)”While FGSM and BIM represent broad strokes in the adversarial landscape, JSMA is a fine brush that paints targeted and precise adversarial examples. Unlike FGSM, which perturbs all pixels uniformly, or BIM, which iteratively applies perturbations, JSMA computes a saliency map for a sample, which identifies data points whose modification would have the most significant impact on the output classification. The technique can be applied to images, text, and tabular data. For images, for instance, it changes a select few pixels with the most significant impact on the output. This calculation is based on the gradients of the output with respect to the input image and will maximally affect the class scores according to the Jacobian matrix of the model. This selective approach often results in minimal and less detectable modifications, making JSMA particularly suitable for targeted attacks. It is a computationally intensive technique because it involves calculating the forward derivative of the model to construct a saliency map, from which the most influential pixels are identified for modification.
Attack example
Section titled “Attack example”Implementing JSMA with ART is straightforward using the attack = SaliencyMapMethod (classifier=classifier, theta=0.1, gamma=0.1) statement. The classifier parameter is an ART wrapper to the target or shadow model. theta is the amount of perturbation introduced in each step, and gamma is the maximum fraction affected (e.g., pixels), expressed as a value between 0 and 1. You can also specify an optional batch size, which we have not used in our sample, and being an iterative method. This example looks similar to the previous one, except for the creation of the attack. We exploit this ART encapsulation by creating a general attack method and passing the attack-specific parameters. The generic method looks as follows:
def attack(sample, attack_class, wrapper=classifier, **kwargs): attack_instance = attack_class(wrapper, **kwargs) x_adv = attack_instance.generate(x=sample) adv_img = show_adversarial_images(sample, x_adv) return x_adv, adv_imgWe can then use it as follows, passing the sample and the attack type:
from art.attacks.evasion import SaliencyMapMethod_, _ = attack(plane1, SaliencyMapMethod, theta=0.1, gamma=1, batch_size=1)This helps reuse the code and focus on the attack-specific parameters rather than boilerplate code.
We can go a step further and create a single attack method to cater for our different attack methods, for both untargeted and targeted attacks, as shown in the following code:
import inspect# Unified attack function for both targeted and untargeted attacksdef has_targeted_parameter(attack_class): signature = inspect.signature(attack_class) return 'targeted' in signature.parametersdef attack(sample, attack_class,target_label=None, wrapper=classifier, **kwargs): if target_label is not None: target_one_hot = np.zeros((1, 1000)) target_one_hot[0, target_label] = 1 if has_targeted_parameter(attack_class): print(f"creating an instance)" attack_instance = attack_class(wrapper, targeted=True, **kwargs) prin else: attack_instance = attack_class(wrapper, **kwargs) x_adv = attack_instance.generate(x=sample, y=target_one_hot) else: attack_instance = attack_class(wrapper, **kwargs) x_adv = attack_instance.generate(x=sample) adv_img = show_adversarial_images(sample, x_adv) return x_adv, adv_imgThe code checks whether a target_label has been supplied and, if so, it instantiates the attack classes for a targeted attack; otherwise, it proceeds as before. The JSMA implementation has built-in support for targeted attacks and it does not require the targeted=True parameter, which when passed throws an error. We use inspect to bypass this limitation and provide a single implementation.
The attack takes time to complete but is successful on all three images in untargeted attacks and targeted attacks. In targeted attacks, it succeeds in the first three attacks but produces slightly different bird labels for the last two; planes are misclassified as house_finch and junco, instead of junco and indigo_bunting. But this is still a success for our attack scenario.
Note
Despite its computational demands, JSMA is a highly effective evasion technique. JSMA and FSGM have also been used against deep reinforcement learning models. You can find out more details in the research paper Adversarial Attacks and Defense in Deep Reinforcement Learning (DRL)-Based Traffic Signal Controllers by Ammar Haydari, Michael Zhang, and Chen-Nee Chuah, 2021, at https://par.nsf.gov/servlets/purl/10349108.
JSMA, like FGSM and BIM, relies predominately on gradients. In the next section, we will see a more sophisticated approach.
Carlini and Wagner (C&W) attack
Section titled “Carlini and Wagner (C&W) attack”The C&W attack is a sophisticated and powerful targeted adversarial technique that stands out due to its efficacy and the difficulty in defending against it. Unlike the earlier mentioned methods, such as FGSM, BIM, and JSMA, which predominantly rely on manipulating the gradients of the model to generate adversarial examples, the C&W attack takes a different route. It formulates the creation of adversarial examples as an optimization problem, aiming to find the smallest possible perturbation that can cause a misclassification to a specific target class while also striving to keep the perturbation imperceptible.
The C&W attack differs from FGSM and BIM in that it doesn’t solely depend on the gradient sign but optimizes for the smallest change needed to alter the classification. This results in a more subtle and often more effective perturbation. In contrast to JSMA, which selectively alters a small subset of features, the C&W attack considers the entire image, optimizing the perturbation across all pixels in a way that is tuned to the specific model’s loss landscape.
Attack example
Section titled “Attack example”To implement the C&W attack using ART, first ensure you have ART installed
Like the previous examples, ART encapsulates C&W as an evasion attack object, and we can reuse the generic implementation by supplying the appropriate parameters. Because we use different parameters than the defaults, we create a thin wrapper to avoid having to supply the parameter values all the time:
from art.attacks.evasion import CarliniL2Methoddef cw_attack(sample, wrapper=classifier, confidence=0.1, batch_size=1, learning_rate=0.01, max_iter=10): return attack(sample, CarliniL2Method, confidence=confidence, batch_size=batch_size, learning_rate=learning_rate, max_iter=max_iter)We can now call the attack as follows:
_,_ = cw_attack(plane1)Adjusting confidence affects how noticeable and robust the adversarial example is, with higher values increasing both the effect and detectability. learning_rate controls the speed and precision of the optimization, where a higher rate can lead to quicker but potentially less accurate results, and a lower rate improves fine-tuning at the cost of speed. Finally, max_iter sets the limit on iterations, with more iterations allowing for more detailed adjustments but taking longer, and fewer iterations speeding up the attack but possibly reducing its effectiveness. Balancing these parameters can take a lot of experimentation.
The C&W attack is a sophisticated attack method that is designed to bypass defenses using its optimization approach. It is interesting to inspect the quality of perturbations both targeted and across the image, as shown in the following figure:

Figure 7.3 – C&W-generated perturbation
However, the method is quite computationally intensive. It takes longer to run out of all of the attacks we have used so far, taking 30 minutes per attack on a powerful workstation (48-core CPU, 128 GB RAM, NVIDIA RTX-4090 GPU with 24 GB VRAM).
The following section will look at the PGD attack. This advanced attack method is less computationally intensive and can be used for both untargeted and targeted methods and has become a benchmark in evaluating adversarial robustness.
Projected Gradient Descent (PGD)
Section titled “Projected Gradient Descent (PGD)”PGD is one of the most popular and effective methods for generating adversarial examples. It is an iterative attack that is widely used due to its effectiveness against various ML models. Unlike one-step attacks such as FGSM, which apply a single large update to the input, PGD applies multiple smaller updates, refining the perturbation at each step. Compared to BIM, it offers more flexibility and robustness as it includes options for random initialization, different norms (e.g., L1, L2, and L∞), and adaptive step sizes, allowing for a broader range of attack strategies and more effective adversarial example generation.
This process allows PGD to find adversarial examples that are closer to the original input in the input space while still misleading the model. Compared to the JSMA and C&W attacks, PGD is faster and more flexible, although it may require more fine-tuning than JSMA to succeed, and unlike C&W, it may not find the minimum perturbation required to induce a misclassification.
Attack example
Section titled “Attack example”We can use our attack function to implement a PGD attack, passing the Projected GradientDescent class and relevant parameters.
Like in FSGM, the eps parameter determines the maximum perturbation allowed, influencing how noticeable and effective the adversarial changes are. eps_step controls the step size in each iteration, where smaller steps lead to more precise but slower adjustments. The max_iter parameter sets the number of iterations the attack runs, affecting the refinement and strength of the adversarial example; more iterations allow for thorough optimization, while fewer iterations quicken the process but may lessen the attack’s impact. The default options create visibly distorted images and as a result, we use different defaults. To avoid retyping the parameters, like with C&W, we create a thin wrapper as follows:
from art.attacks.evasion import ProjectedGradientDescentfor bird_label in bird_labels: for plane in planes: _,_ = attack(plane, ProjectedGradientDescent, target_label=bird_label, eps=0.03, eps_step=0.001, max_iter=10, batch_size=1)We can now reuse it in our attacks or model evaluations with one line:
pgd_attack(plane1)We have covered the basic types of evasion techniques and the approaches they follow. Using ART and the consolidated function we developed, it is straightforward to evaluate models for adversarial robustness against evasion attacks.
ART is constantly expanding its catalog of evasion attacks, incorporating attacks published in new research. For more information, see the ART documentation on evasion attacks at https://adversarial-robustness-toolbox.readthedocs.io/en/latest/modules/attacks/evasion.html.
Because of the encapsulation ART offers, you can extend the generic function used in this book to incorporate new evasion attacks relevant to your use cases.
Adversarial patches – bridging digital and physical evasion techniques
Section titled “Adversarial patches – bridging digital and physical evasion techniques”Adversarial patches represent a paradigm shift in the domain of adversarial AI. Unlike methods such as FGSM, BIM, C&W, or PGD, which typically introduce fine-tuned, often imperceptible perturbations, adversarial patches are localized alterations designed to be superimposed onto a segment of the input, such as part of an image.
Attack scenarios
Section titled “Attack scenarios”Traditional evasion techniques often require access to the model’s gradient information to craft perturbations that are spread across the input, making them inherently suited for digital attacks. Adversarial patches, conversely, do not need such detailed knowledge and can be crafted to be highly visible yet still effective, making them uniquely suited to physical-world applications.
For example, a physical adversarial patch could be placed on a road sign to mislead an autonomous vehicle’s vision system—a direct and tangible interaction with the AI. Alternatively, by creating a patch attached to a car, an attacker can bypass CCTV object detection. This type of attack leverages the physical attributes of the patch, such as shape, color, and pattern, to exploit the model’s vulnerabilities.
Adversarial patches can be used in the digital domain, too. In digital attacks, adversarial patches are inserted into digital images or video frames before being fed into the AI system, causing similar misclassifications as they would in the real world.
In our case, our attack scenario will try and use a patch to misclassify a car as an animal, evading CCTV object detection.
Attack example
Section titled “Attack example”We can generate an adversarial patch using ART. As always, first, ensure you have ART installed:
pip install adversarial-robustness-toolboxThen, we can proceed with the following code in a Jupyter notebook:
from art.attacks.evasion import AdversarialPatchimport tensorflow as tf... load a ResNet50v2 and wrap it in an ART classifier called wrapper as before# Create the adversarial patch attackap = AdversarialPatch(classifier=wrapper, rotation_max=22.5, scale_min=0.4, scale_max=scale_max,learning_rate=learning_rate,max_iter=500, batch_size=16,patch_shape=(224, 224, 3))# load sample image to attackimg = load_preprocess('../images/racing-car.jpg')# set the target to a tabby cattarget_class = 281 # 'tabby cat' class in ImageNety_one_hot = np.zeros(1000)y_one_hot[target_class] = 1.0y_target = np.expand_dims(y_one_hot, axis=0) # Shape (1, 1000)#generate the patchpatch, _ = ap.generate(x=img, y=y_target)The code demonstrates the creation of an adversarial patch using ART’s AdversarialPatch class, applying it to an input image, and then feeding the altered image into a pre-trained model to assess its impact. The attack is successful as it misclassifies the car as siamese_cat or fox_squirrel, which, although not a tabby cat, may meet the attack scenario objectives. Sometimes it misclassifies it as an airliner, but the classification depends on the position of the patch on the image. An attacker knowing where to place the patch would evade object recognition without raising suspicion when viewing predictions.
The next screenshot shows the two images side by side with the patch position causing a fox_squirrel misclassification:

Figure 7.4 – The fox_squirrel misclassification
You can find the full example in the Targeted Adversarial Patch notebook. It showcases the generation of the patch, its application at a specified scale and position, and the subsequent misclassification by the AI model.
NLP evasion attacks with BERT using TextAttack
Section titled “NLP evasion attacks with BERT using TextAttack”While initially the focus of evasion attacks was on image classification tasks, its underlying principles can be adapted for NLP use. TextAttack is a popular Python framework to generate adversarial text inputs. We will demonstrate its use to stage adversarial attacks in NLP for two attack scenarios: sentiment analysis and language inference.
Let’s start with sentiment analysis.
Attack scenario – sentiment analysis
Section titled “Attack scenario – sentiment analysis”In NLP, linear classifiers, such as logistic regression or linear support vector machines (SVMs), or language models such as BERT, are often used for tasks such as sentiment analysis or spam detection. These classifiers work by learning a decision boundary separating different feature space classes. Adversarial samples in NLP might involve changing words or phrases in a text snippet to change its classification from positive to negative sentiment or non-spam to spam, with the smallest change possible. This would allow, for instance, positive reviews to be misclassified as negative with barely detected changes. Our attack example will demonstrate this by attacking sentiment analysis on IMDb.
Attack example
Section titled “Attack example”We’ll use TextAttack with BERT to carry out an attack on the sentiment analysis process. BERT TextAttack is a Python framework designed explicitly for generating adversarial examples in NLP. It offers a variety of pre-built attack recipes, transformations, and goal functions tailored to text data, making it an ideal tool for testing and strengthening NLP models against evasion attacks.
The steps are documented in the Python code as comments. The attack will involve altering words in the input text to change the model’s classification.
First, ensure that you have the necessary packages installed. In addition to TextAttack, we will install transformers that we can access and use from Hugging Face:
pip install textattack transformersNow, we can proceed with the implementation using a pre-built attack, TextFoolerJin2019:
import transformersimport randomfrom textattack. models.wrappers import HuggingFaceModelWrapper, ModelWrapperfrom textattack.attack_recipes import TextFoolerJin2019from textattack.datasets import HuggingFaceDataset# Load the target pre-trained model for sentiment analysis and a tokenizermodel = transformers.AutoModelForSequenceClassification.from_pretrained("textattack/bert-base-uncased-imdb")tokenizer = transformers.AutoTokenizer.from_pretrained("textattack/bert-base-uncased-imdb")#tokenizer = AutoTokenizer('bert-base-uncased-snli')model_wrapper = HuggingFaceModelWrapper(model, tokenizer)# Choose the attack methodattack = TextFoolerJin2019.build(model_wrapper)# Test the attack with your own simple textinput_text = "I really enjoyed the new movie that came out last month."label = 1 #Positiveattack_result = attack.attack(input_text, label)print(attack_result)The code downloads and instantiates an IMDb-fine-tuned version of BERT from Hugging Face and the appropriate tokenizer. It then uses a TextAttack TextFoolerJin2019 attack recipe to implement the attack by perturbating the input text. The following are the results of this simple test, showing how by changing one word, we flip the classification from positive to negative:
1 (99%) --> 0 (97%)I really enjoyed the new movie that came out last month.I really rained the new movie that came out last month.This is a very simple example. The TextAttack - NLP Evasion Attacks on Bert notebook contains this example and tests on portions of the IMDb dataset.
We used TextAttack to demonstrate adversarial perturbations focusing on sentiment analysis and how such perturbations can lead to sentiment misclassification in language models. In the next section, we will see how they can also be used in more sophisticated attacks by attacking language inference.
Attack scenario – natural language inference
Section titled “Attack scenario – natural language inference”NLP models are particularly susceptible to word-level perturbations that maintain the semantic meaning of a text but alter its classification. For instance, a spam detection model might classify an email as non-spam, but by changing certain words or phrases, an attacker could cause it to be filtered incorrectly. TextAttack can automate the process of identifying and applying such perturbations to test the resilience of these models. This goes beyond simple spam classification of meaning in Natural Language Inference (NLI). We will use TextAttack and BERT with the Stanford Natural Language Inference (SNLI) dataset.
Attack example
Section titled “Attack example”The SLNI dataset is a collection of sentence pairs annotated with one of three labels: entailment, contradiction, or neutral. These labels represent the relationship between a premise and a hypothesis sentence:
- Entailment: The hypothesis is a true statement given the premise
- Contradiction: The hypothesis is a false statement given the premise
- Neutral: The truth of the hypothesis is undetermined given the premise
The SNLI-fine-tuned version of BERT supports this. We provide a pair of text sentences, and it returns with a classification from one of these:
0– contradiction1– neutral2– entailment
In our example, we will demonstrate how to use TextAttack and the same attack recipe to subtly change either the premise or the hypothesis and manipulate the inference.
The attack is like the previous one; we use a different model and tokenizer for SNLI:
# Load model and tokenizerslni_model = transformers.AutoModelForSequenceClassification.from_pretrained("textattack/bert-base-uncased-snli")slni_tokenizer = transformers.AutoTokenizer.from_pretrained("textattack/bert-base-uncased-snli")We can wrap the model and build the attack:
# Wrap the model with TextAttack's HuggingFaceModelWrapperslni_model_wrapper = HuggingFaceModelWrapper(slni_model, slni_tokenizer)# Build the attack objectslni_attack = TextFoolerJin2019.build(slni_model_wrapper)Here is a simple test attack we can run to flip a contradictory inference to entailment:
from collections import OrderedDictinput_text_pair = OrderedDict([ ("premise", "A man inspects the uniform of a figure in some East Asian country."), ("hypothesis", "The man is sleeping")])label = 0 # 0 - contradiction, 1 - neutral, 2 - entailmentattack_result = slni_attack.attack(input_text_pair, label)print(attack_result)The example successfully produces an entailment classification by rewording the hypothesis. Here is the output of the attack:
0 (100%) --> 2 (57%)Premise: A man inspects the uniform of a figure in some East Asian country.Hypothesis: The man is sleepingPremise: A man inspects the uniform of a figure in some East Asian country.Hypothesis: The comrade is dreamThis is a simple attack, and the sample notebook (TextAttack - NLP Evasion Attacks on Bert) contains the code and tests against a test portion of the SNLI dataset.
This concludes our exploration of NLP-based evasion attacks.
Universal Adversarial Perturbations (UAPs)
Section titled “Universal Adversarial Perturbations (UAPs)”UAPs pose a unique and significant threat to ML models. Unlike traditional adversarial examples crafted for a specific model, UAPs are input perturbations effective across a wide range of models. They exploit the shared vulnerabilities inherent in the feature space of different models, allowing attackers to create a single perturbation that can cause misclassification on any model trained to perform the same task.
Attack scenario
Section titled “Attack scenario”Consider the case where multiple image recognition systems, each with a different architecture (e.g., VGG19, ResNet50, and InceptionV3), are deployed in security-sensitive environments. An attacker creates a UAP that causes all three models to misclassify the input when added to any image. The perturbation is universal in that it does not target the idiosyncrasies of a single model but rather the commonalities in the decision boundaries of all models.
Attack example
Section titled “Attack example”The following Python code demonstrates staging a UAP using ART’s support for UAP. We will stage an attack using ResNet50 and apply it to multiple models (VGG19 and InceptionV3).
First, we need to install the necessary packages:
pip install adversarial-robustness-toolbox tensorflowWe also need to install ImageNet_Stubs, which contains 16 ImageNet images to use in our tests:
pip install git+https://github.com/nottombrown/imagenet_stubsWe can now import the required packages:
import numpy as npimport tensorflow as tffrom art.estimators.classification import TensorFlowV2Classifierfrom art.attacks.evasion import UniversalPerturbationimport imagenet_stubsFirst, we need to load the three models and wrap them in ART classifiers:
# Load pre-trained modelsresnet_model = tf.keras.applications.ResNet50(weights='imagenet')vgg_model = tf.keras.applications.VGG19(weights='imagenet')inception_model = tf.keras.applications.InceptionV3(weights='imagenet')# Wrap modelsclip_values = (0, 255)resnet_classifier = TensorFlowV2Classifier(model=resnet_model, nb_classes=1000, input_shape=(224, 224, 3),clip_values=clip_values)vgg_classifier = TensorFlowV2Classifier(model=vgg_model, nb_classes=1000, input_shape=(224, 224, 3), clip_values=clip_values)inception_classifier = TensorFlowV2Classifier(model=inception_model, nb_classes=1000, input_shape=(299, 299, 3),clip_values=clip_values)We load the 16 sample images and preprocess them:
from tensorflow.keras.preprocessing import imageimages_list = list()for image_path in imagenet_stubs.get_image_paths(): im = image.load_img(image_path, target_size=(224, 224)) im = image.img_to_array(im) im = im[::::-1].astype(np.float32) # RGB to BGR im = np.expand_dims(im, axis=0) images_list.append(im)images = np.vstack(images_list)We create a UAP attack, which we then use to create our adversarial images for our ImageNet samples:
# Create a UAP using ResNet50 that is model-agnosticattack = UniversalPerturbation(classifier=resnet_classifier, attacker="deepfool", max_iter=5)adversarial_images = attack.generate(x=images)We can test the adversarial images generated by ResNet50 against VGG19 and InceptionV3:
predictions_vgg = vgg_classifier.predict(adversarial_images)from tensorflow.image import resize# InceptionV3 uses a different format and we need to reshape the inputsadversarial_images_resized = np.array([resize(image, (299, 299)).numpy() for image in adversarial_images])predictions_inception = inception_classifier.predict(adversarial_images_resized)You can find the code and the results in the Universal Adversarial Perturbations notebook. The success rates are 100% for InceptionV3 but only 12.5% for VGG19. The results are only for the images and parameters we have used and can be improved by fine-tuning the attack.
This section has provided an overview of UAPs and their potential to cause widespread misclassification across different models. It has also highlighted the importance of universal adversarial training as a defense mechanism. You can find more in-depth information on UAPs and how they could affect self-driving cars in the following research paper: Resilience of Autonomous Vehicle Object Category Detection to Universal Adversarial Perturbations, by Mohammad Nayeem Teli and Seungwon Oh, 2021, at https://arxiv.org/abs/2107.04749.
The paper also has a repository with its code at https://github.com/seungwonoh5/Adversarial_Attacks_against_Object_Detection.
Black-box attacks with transferability
Section titled “Black-box attacks with transferability”So far, we have looked at white- and gray-box attacks where the attackers acquire a knowledge of the target model, including its architecture, sufficient to derive a shadow model.
An alternative approach is to utilize transfer learning for black-box attacks. Black-box attacks are particularly insidious, as they are executed without knowledge of the target model’s parameters, architecture, or training data. Instead, attackers typically have access only to the model’s inputs and outputs. The key to the success of black-box attacks lies in the concept of transferability, where adversarial examples crafted for one model (the surrogate) can also deceive another model (the target).
Attack scenario
Section titled “Attack scenario”The threat model for black-box attacks assumes that attackers have no internal knowledge of the target system. They cannot directly calculate gradients or other model specifics required for crafting adversarial examples. However, they can observe the model output for given inputs, which they use to train a surrogate model. Once the surrogate is trained, they craft adversarial examples against it and then apply these examples to the target model, exploiting the transferability of adversarial examples.
This transferability exploits the fact that different models can learn similar decision boundaries, particularly when they are trained on similar datasets or perform similar tasks. An adversarial example that causes a misclassification in the surrogate model also has a significant chance of causing a misclassification in the target model.
Attack example
Section titled “Attack example”We can perform a transferability attack using ART. Before starting, ensure you have ART installed:
pip install adversarial-robustness-toolboxNow, let’s proceed with the implementation in a Jupyter notebook:
#importsfrom art.estimators.classification import TensorFlowV2Classifierfrom art.attacks.evasion import FastGradientMethodimport tensorflow as tfimport numpy as np# Load pre-trained target and surrogate modelstarget_model = tf.keras.applications.MobileNetV2(weights='imagenet')surrogate_model = tf.keras.applications.ResNet50(weights='imagenet')# Wrap models with ART classifiersloss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=True)classifier_target = TensorFlowV2Classifier(model=target_model, nb_classes=1000, input_shape=(224, 224, 3), clip_values=(0, 255), loss_object=loss_object)classifier_surrogate = TensorFlowV2Classifier(model=surrogate_model, nb_classes=1000, input_shape=(224, 224, 3), clip_values=(0, 255),loss_object=loss_object)# Get an image and preprocess itimage = tf.keras.preprocessing.image.load_img('path_to_image.jpg', target_size=(224, 224))image = tf.keras.preprocessing.image.img_to_array(image)image = tf.keras.applications.mobilenet_v2.preprocess_input(image)image = np.expand_dims(image, axis=0)# Generate adversarial examples on the surrogate modelattack = FastGradientMethod(estimator=classifier_surrogate, eps=8, eps_step=2)adv_examples = attack.generate(x=image)# Apply adversarial examples on target modelpredictions = classifier_target.predict(adv_examples)# Decode predictionsdecoded_predictions = tf.keras.applications.mobilenet_v2.decode_predictions(predictions, top=5)In the preceding code, we instantiate two pre-trained models, ResNet50 and MobileNetV2, which serve as the surrogate and target models, respectively. The Fast Gradient Method (FGM), an attack algorithm, is employed to create adversarial examples against the surrogate ResNet50 model. These adversarial examples are then used to test the robustness of the MobileNetV2 model, thereby demonstrating the transferability of adversarial samples—a phenomenon where an attack developed for one model is effective against another. This property is particularly concerning in real-world scenarios where attackers might not have access to the internals of a target model but can still mount successful attacks by exploiting similar vulnerabilities across different models.
This section has provided a brief overview of black-box attacks and the concept of transferability, a core characteristic that allows adversarial examples to be effective across different models. It has also discussed defensive distillation as a potential mitigation strategy and a conceptual demonstration of its implementation using ART. The continuous evolution of adversarial and defense techniques requires ongoing vigilance and adaptation by ML practitioners.
Defending against evasion attacks
Section titled “Defending against evasion attacks”In the arms race between attackers crafting increasingly sophisticated evasion attacks and defenders bolstering the security of ML models, a multifaceted approach to defense is essential. This section will explore a suite of strategies designed to mitigate the risk and impact of evasion attacks.
Mitigation strategies overview
Section titled “Mitigation strategies overview”Defense strategies against evasion attacks can be broadly categorized into reactive and proactive measures. Reactive defenses respond to attacks as they happen, often employing real-time detection and mitigation techniques. On the other hand, proactive measures focus on hardening models against potential attacks even before they occur, such as during the training process or model design phase.
These strategies can also be layered, providing a defense-in-depth approach that secures models at multiple levels. For instance, input preprocessing can be combined with adversarial training to prevent and withstand adversarial examples. Furthermore, model hardening techniques can be implemented alongside certified defenses to not only improve resilience but also mathematically guarantee a certain level of robustness against adversarial manipulations.
Adversarial training
Section titled “Adversarial training”Adversarial training involves augmenting the training data with adversarial examples. By learning from these perturbed inputs, models can become more robust to similar attacks encountered during inference. The following code demonstrates how you can implement adversarial training:
from art.attacks.evasion import FastGradientMethodfrom art.estimators.classification import TensorFlowV2Classifier# Assuming 'model' is a TensorFlow/Keras model already defined and compiledclassifier = TensorFlowV2Classifier(model=model, clip_values=(0, 1), use_logits=False)# Generate adversarial training dataattack = FastGradientMethod(estimator=classifier, eps=0.1)x_train_adv = attack.generate(x=x_train)# Combine with original training datax_train_combined = np.concatenate((x_train, x_train_adv), axis=0)y_train_combined = np.concatenate((y_train, y_train), axis=0)# Train the model on the combined datasetclassifier.fit(x_train_combined, y_train_combined, batch_size=64, epochs=10)The Evasion Defenses – Adversarial Training notebook provides a full basic example. The code and example show adversarial training against FGM. You can also use TextAttack to generate adversarial samples to train NLP and text-based models.
Similarly, you can use ART to generate any other adversarial samples from the attacks you want to be robust against. You may, for instance, choose to create UAP samples and incorporate them into your adversarial training in each training epoch.
Alternatively, you may use the set of adversarial trainers ART offers, which automate training against a range of attacks and incorporate specialized trainers found in research.
Its AdversarialTrainer trains an ART classifier against its evasion attacks. We could use this, for instance, to perform adversarial training against adversarial patches:
from art.attacks.evasion import AdversarialPatchfrom art.estimators.classification import KerasClassifierfrom art.defences.trainer import AdversarialTrainer# Wrap the model(loaded frm an ART classifierwrapper = KerasClassifier(model=model, clip_values=(0, 255))# Define the adversarial patchpatch_attack = AdversarialPatch(classifier=wrapper, max_iter=50)# Create the Adversarial Trainertrainer = AdversarialTrainer(wrapper, attacks=patch_attack, ratio=1)# Train the model with adversarial examples generated on-the-flytrainer.fit(x_train, y_train, nb_epochs=5)The code wraps a model into a Keras classifier, which is used to create an evasion attack (in this case, AdversarialPatch) and is passed alongside the attack to the trainer. Note the ratio parameter, which by default is 0.5. This indicates how many samples should be replaced with adversarial ones. If you set 1, then all samples will be replaced. Be careful to choose the right ratio. For instance, by default, there will be two adversarial samples, and unless your training set has two samples too, the trainer.fit method will raise an exception.
The trainer is then trained as a Keras model using its fit(..) method. You can then use the new model and evaluate it. The sample notebook contains an example of how to evaluate the updated model against the targeted adversarial patch attack we examined earlier.
You can find an up-to-date list of adversarial trainers at https://adversarial-robustness-toolbox.readthedocs.io/en/latest/modules/defences/trainer.html.
Input preprocessing
Section titled “Input preprocessing”Input preprocessing defenses modify inputs before they are fed into the model, potentially neutralizing adversarial perturbations. This can include transformations such as image cropping, rotation, and scaling. The following example demonstrates the use of image rotation on model input:
from tensorflow.keras.preprocessing.image import ImageDataGeneratorsamples=[...array of processed images..]# Data augmentation generatordatagen = ImageDataGenerator( rotation_range=15, # Random rotations in the range (degrees, 0 to 180) horizontal_flip=True, # Randomly flip inputs horizontally # ... include any other augmentations ...)samples_rotated = np.array([datagen.random_transform(img) for img in samples])We could also include other transformations, such as image compression, to further disrupt perturbations:
from art.defences.preprocessor import JpegCompression, FeatureSqueezing# Initialize JPEG Compression with a specific quality factor jpeg_compression = JpegCompression(clip_values=(0, 1), quality=75, apply_predict=True)# Apply defenses to input dataSamples_compressed = jpeg_compression (samples)[0]Feature squeezing is another popular data preprocessing technique that reduces the search space available to an adversary by squeezing out unnecessary input features. An example would be reducing the color bit depth in images, which makes the model less sensitive to small perturbations.
You can easily implement feature squeezing manually. However, ART offers feature squeezing as part of its preprocessing defenses and you can use it in the same way as we used JpegCompression and combine them in the same preprocessing pipeline:
from art.defences.preprocessor import FeatureSqueezing# Initialize preprocessing defensesbit_depth = 3 # Number of bits to keep in each color channelfeature_squeezing = FeatureSqueezing(clip_values=(0, 1), bit_depth=bit_depth)# Apply Feature Squeezing to the datasetsamples_squeezed, _ = feature_squeezing(samples)You can find examples of these preprocessing techniques in the Evasion Defenses - Data Preprocessing notebook.
In addition, ART offers a range of other data preprocessors, including spatial smoothing, which applies filters to reduce noise and perturbations; total variance minimization, which smooths images by reducing the total variation between pixels; and Gaussian augmentation, which randomly adds Gaussian noise to training data to increase model resilience. Additionally, pixel deflection deflects pixels randomly to disrupt adversarial perturbations, and thermometer encoding transforms inputs into a more robust thermometric scale, while more advanced preprocessors include MP3 and video compression and inverse GANs.
This is a growing list; you can find more about the latest data preprocessing defenses of ART at https://adversarial-robustness-toolbox.readthedocs.io/en/latest/modules/defences/preprocessor.html.
Model hardening techniques
Section titled “Model hardening techniques”Model hardening encompasses techniques that strengthen the model itself against adversarial attacks. This can include architectural changes, modifying the training process, or incorporating additional components such as defensive distillation or feature squeezing.
Defensive distillation uses a teacher model to produce softened labels, which are then used to train a student model:
# Assuming 'teacher_model' is a trained Keras model eg ResNet50v2temperature = 10 # High temperature softens the output distribution# Create softened labels using the teacher modelsoftened_labels = tf.nn.softmax(teacher_model.predict(x_train) / temperature)# Train the student model with softened labelsstudent_model = build_model() # build_model is a function to create a new instance of the modelstudent_model.compile(optimizer='adam', loss='categorical_crossentropy')student_model.fit(x_train, softened_labels, epochs=5)Feature squeezing, part of data preprocessing defenses, is also a model hardening technique. Other model hardening techniques include gradient masking and robust loss functions.
Gradient masking focuses on making the gradient information used during the training of neural networks less useful for attackers, thereby hindering their ability to create effective adversarial examples. This technique involves modifying the model or training process to obscure the gradients that attackers exploit. Here is an example implementation to use and train or fine-tune a model:
# Gradient Masking functiondef train_with_gradient_masking(model, x_train, y_train, epochs=10, noise_level=0.1): for epoch in range(epochs): print('Epoch:', epoch + 1) for i in range(0, len(x_train), batch_size): x_batch = x_train[i:i+batch_size] y_batch = y_train[i:i+batch_size] with tf.GradientTape() as tape: # Add random noise to the inputs to mask gradients noise = tf.random.normal(shape=tf.shape(x_batch), mean=0.0, stddev=noise_level, dtype=tf.float32) noisy_x_batch = x_batch + noise noisy_x_batch = tf.clip_by_value(noisy_x_batch, 0, 1) # Ensure pixel values are valid preds = model(noisy_x_batch, training=True) loss = loss_fn(y_batch, preds) gradients = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables))x_train, y_train = load_your_dataset() # Substitute with actual data loadingloss_fn = tf.keras.losses.CategoricalCrossentropy() # Example loss functionoptimizer = tf.keras.optimizers.Adam() # Example optimizerbatch_size = 32The train_with_gradient_masking function iterates through training epochs, applying random Gaussian noise to batches of input data to obscure gradient information during backpropagation. This noise addition aims to protect against gradient-based adversarial attacks by making it harder for attackers to accurately calculate the gradients necessary to modify the inputs in a way that fools the model.
This approach can help reduce the effectiveness of gradient-based adversarial attacks but must be implemented cautiously as attackers can adapt to such defenses by adapting black-box testing and sidestepping gradient masking.
Robust loss functions can harden a model against adversarial examples by minimizing the model’s sensitivity to small perturbations in the input data. This can be an effective defense against C&W attacks, which are an optimization-based approach and can bypass many traditional defenses
A side-effect of robustness is that if it is too strong, it will reject valid data in addition to preventing attacks. Experimenting and finding the right balance is key.
Here’s how to implement such a defense:
def robust_loss_function(y_true, y_pred): # Standard categorical cross-entropy loss cce_loss = tf.keras.losses.categorical_crossentropy(y_true, y_pred) # Adversarial regularization term (for demonstration, using L2 norm of predictions) adv_reg = tf.reduce_mean(tf.square(y_pred)) # Combine both terms total_loss = cce_loss + 0.01 * adv_reg # Adjust the weight of the regularization term as needed return total_loss# Retrain or fine-tune the model with the robust loss functionmodel.compile(optimizer='adam', loss=robust_loss_function, metrics=['accuracy'])# Example training call using the robust loss functionmodel.fit(x_train, y_train, epochs=5)# Evaluate the robustness of the retrained modelpredictions_robust = model.predict(x_test_adv)accuracy_robust = np.sum(np.argmax(predictions_robust, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)print("Accuracy on adversarial examples with robust model: {}%".format(accuracy_robust * 100))This is a simple generic sample of a robust loss function. For real-life scenarios, the actual implementation of a robust loss function would depend on the specific characteristics of the model and the types of adversarial perturbations it faces, and it includes functions.
Model ensembles
Section titled “Model ensembles”Defending against PGD and other iterative attacks is challenging, but one effective strategy is using model ensembles. An ensemble can increase the robustness of the system since an adversarial example that fools one model may not fool another. Here is a brief example of setting up an ensemble of models for CIFAR-10:
from tensorflow.keras.models import Modelfrom tensorflow.keras.layers import Average# Assume we have loaded several trained modelsmodels = [load_model('model_1.h5'), load_model('model_2.h5'), load_model('model_3.h5')]# Create a model ensembleoutputs = [model.outputs[0] for model in models]average_layer = Average()(outputs)ensemble_model = Model(inputs=models[0].inputs, outputs=average_layer)# Evaluate the ensemble on the adversarial exampleensemble_predictions = ensemble_model.predict(adv_image)print('Ensemble predictions on adversarial example:', np.argmax(ensemble_predictions, axis=1))InNote
Using an ensemble can improve resilience, as it diversifies the decision-making process and makes it harder for a single adversarial example to exploit the weaknesses of all models simultaneously. In our experiments, it appears to be a reliable defense. However, it’s important to note that ensembles can still be vulnerable to more sophisticated attacks that specifically target ensembles, and they also come with increased computational costs.
Certified defenses
Section titled “Certified defenses”Certified defenses offer a provable guarantee of robustness within a certain bound of the input space. These approaches use mathematical methods to ensure that the model’s prediction will remain consistent for any input within a defined neighborhood.
An example of a certified defense is randomized smoothing, which uses noise to create a provably robust classifier.
We can implement randomized smoothing by taking advantage of the GaussianAugmentation offered by ART:
from art.defences.preprocessor import GaussianAugmentation# Initialize the randomized smoothing defensegaussian_augmentation = GaussianAugmentation(sigma=1.0, augmentation=False)# Apply randomized smoothing to create a smoothed classifierx_train_smoothed, _ = gaussian_augmentation(x_train)# Train the model on the smoothed datamodel.fit(x_train_smoothed, y_train, epochs=5)Using randomized smoothing, we can make theoretical guarantees about the robustness of the classifier to adversarial examples within a certain noise level.
You will need to experiment with the level and type of noise to achieve robustness without adversely affecting the model’s abilities. This will typically be your own empirical testing and cross-validation across different subsets of data.
This section has explored a comprehensive set of strategies for defending against evasion attacks, ranging from adversarial training and input preprocessing to model hardening and certified defenses. Each technique contributes to a defense strategy, reinforcing the model’s resilience from different angles and providing a robust foundation against adversarial threats.
Note
These are advanced techniques and the examples, including the sample notebooks, aim to help show you how they work. Designing and implementing adversarial defenses will require evaluation, experimentation, and further refinement, with experienced data scientists and AI engineers working together.
Summary
Section titled “Summary”In this chapter, we covered evasion attacks against deployed models aiming to degrade the model’s integrity. We covered targeted and untargeted attacks, white- and black-box approaches, and reconnaissance techniques aiding evasion attacks.
We discussed various approaches to creating adversarial payloads for evasion attacks, such as perturbations and patches in the digital and physical worlds. We delved into image and textual inputs and discussed mitigations such as input preprocessing, adversarial training, model hardening techniques, and certified defenses.
We mentioned model extraction attacks, which attackers can use to help them stage evasion attacks. Model extraction is part of attacks targeting the privacy of the model. In the next chapter, we will cover these attacks in more detail.