{'fraction_non_alphanumeric': 0.03084673245462701, 'fraction_numerical': 0.008453522876268028, 'mean_word_length': 4.783875473957294, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
A Perturbation Resistant Transformation and Classification System for Deep Neural Networks

Deep convolutional neural networks accurately classify a diverse range of natural images, but may be easily deceived when designed, imperceptible perturbations are embedded in the images. In this paper, we design a multi-pronged training, input transformation, and image ensemble system that is attack agnostic and not easily estimated. Our system incorporates two novel features. The first is a transformation layer that computes feature level polynomial kernels from class-level training data samples and iteratively updates input image copies at inference time based on their feature kernel differences to create an ensemble of transformed inputs. The second is a classification system that incorporates the prediction of the undefended network with a hard vote on the ensemble of filtered images. Our evaluations on the CIFAR10 dataset show our system improves the robustness of an undefended network against a variety of bounded and unbounded white-box attacks under different distance metrics, while sacrificing little accuracy on clean images. Against adaptive full-knowledge attackers creating end-to-end attacks, our system successfully augments the existing robustness of adversarially trained networks, for which our methods are most effectively applied.


Introduction
Modern neural networks provide state-of-the-art classification performance in many applications such as image recognition and language processing. As such, neural networks are seeing tremendous application growth in every day tasks and thus their safety and security have never been more paramount to human society.
Despite their increasing sophistication and diminishing error rates, original work by Szegedy et al. [1] demonstrated that small manipulations to images, called adversarial examples, can easily fool neural networks. In a whitebox adversarial setting, a malicious actor exploits a knowledge of a neural network's parameters and defenses to intelligently create these examples that are then misclassified by the network. Previous efforts to combat these perturbations rely on several strategies to formulate algorithms or network architectures that are more resistant to adversarial attacks. The two main camps of defenses either manipulate network learning procedures at training time (adversarial training) [2,3,4,5,6,7,8,9] or apply transformations to inputs that counter adversarial perturbations before presenting them to the network for classification or detection [10,11,12,13,14,15,16,17].
In response to the previously mentioned defenses, many white-box attack techniques have been developed that have minimized their effectiveness or bypassed them altogether; particularly against the latter camp of defense techniques [18,19,20,21].
In this paper, we present a novel system whose elements span the work of both camps. We adversarially train a neural network and then encapsulate it with custom preprocessing and classification layers. The core element of our preprocessing technique borrows ideas from neural style transfer [22]: we copy the input once for each possible label and impart the feature level polynomial kernel statistics of sampled training set images from each class onto the copies. Our classification layer treats the transformed copies as a hard vote committee for classification. However, by default, the system assumes that the classification on the original input is correct and only changes its decision if a minimum quorum of the committee agrees on a new label.
We evaluate our defense both statically and adaptively against a ResNet18 [23] classifying the CIFAR10 [24] dataset.
Our system does share similarities to previous defense strategies that have vulnerabilities; namely in the preprocessing and ensembling effects, but we also differ in one fundamental way. Previous ensembles of preprocessing defenses have been rendered ineffective [20] by adaptive attackers, but to our knowledge these defenses incorporated processing filters that attempted to 'clean' contaminated examples and maintain (or simplify) their salient features in the pixel space. In contrast, our polynomial kernel optimization strategy splays the input image towards all other labels at the feature level. Coupled with our classification system, the full-knowledge attacker has the burden of convincing a critical mass of these seemingly opposing transformations to coalesce around a single incorrect label with a single perturbation set or otherwise the perturbed image passes through the baseline adversarially trained network (the default classification unless the committee overrules it).
We make the following contributions in this paper: • We construct a novel defense system that shows increased robustness against a diverse set of attacks of varying type, imperceptibility, and strength.
• We demonstrate how imparting feature level polynomial kernels from training set sample images to new examples can correctly reclassify weak adversaries and form an ensemble of diversely transformed images.
• We form a robust classification system that adapts the final prediction based on both the original input and transformed input copies.

Preliminary Notations
A convolutional neural network classifier is considered as a function f (x; θ) that maps an input image x ∈ [0, 1] CxW xH to a vector y ∈ R K given θ, a set of network weights and biases. Element y k of y = {y 1 , y 2 , ...y K } represents the probability x belongs to class k such that K k=1 y k = 1 and K is the number of possible distinct labels that can be individually assigned to x. A final predicted label, y p , is assigned to x by the network using the classification function Y = arg max k (y). If the ground-truth label of x, y t , is equal to y p , then the network has correctly classified x.
Given a training set T , a classifier f (x; θ) trained on T, and evaluated on a batch of images X = {x 1 , x 2 , ...x B }, an illicit actor may gain unhindered access to θ and compute a set of perturbations ∆ = {δ 1 , δ 2 , ...δ B } to define a set of adversarial inputs, x adv,b = x b + δ b , b = 1...B. The goal of each adversary is to trick the network into a misclassification Y (f (x adv,b ; θ)) = y t | x b and more generally the actor maximizes E [1(Y (f (x adv ; θ)) = y t | x )].

Problem Statement
In this work, we propose and evaluate defense mechanisms that minimize the effect of adversarial attacks. Formally, 1. Given a trained neural network f (x; θ) and set of potentially perturbed images in a white-box adversarial setting, we must present a defense that minimizes E [1(Y (f (x adv ; θ)) = y t | x )].

Threat Model
The threat model determines under what conditions we claim the defense mechanism to be secure [21,25]. We attempt to evaluate performance in a white-box adversarial setting with the following assumptions that are specific to our defense: 1. The attacker knows the neural network's training set, T , and the network's weights and biases, θ.
2. The attacker is aware of the defense mechanism's algorithmic steps, hyperparameter settings, and feature level loss calculations.
Before we present our system we briefly review existing attack methods and previously proposed defenses.

Review
First we present attack methods and then the defenses working to mitigate the attacks.

Fast Gradient Sign Method (FGSM)
Goodfellow et al. [26] proposed the Fast Gradient Sign Method as an efficient approach to generate adversarial examples based on the gradient of the classification loss function with respect to the image. An image x is perturbed to obtain an adversarial image x adv as follows: where α is an L ∞ -bounded step size, y t is the ground-true label of x, L is a classification loss function such as crossentropy loss, and θ is the set of neural network parameters. FGSM calculates the adversarial example in a single step by taking the sign of the gradient and moving a fixed distance to stay within an L ∞ -norm boundary around x.

Basic Iterative Method (BIM)
The Basic Iterative Method (BIM) [27] is an iterative version of FGSM using smaller incremental step sizes and clipping pixel values after each update as necessary. The basic update step to the input is, where Clip projects the image to a maximum L ∞ -bound set by .

Projected Gradient Descent (PGD)
Madry et al. [2] generate adversarial examples from a generalized version of BIM that projects to different L p -bounds. They have also shown that networks trained using adversarial examples generated by their methods are resilient against adversarial attacks.

DeepFool
Dezfooli et al. [28] convert the local non-linear problem of finding an adversarial example to that of an affine problem by linearizing the decision boundary between classes and projecting the input image towards a classification boundary in an iterative manner until misclassification occurs. This process extends to the multinomial classification problem by approximating the non-linear boundaries of multiple classes surrounding x as a polyhedron and finding the minimum distance to its surface.

Carlini-Wagner
Carlini et al. [18] formulate an optimization problem that minimizes the L p -norm distance between the clean and adversarial image, subject to the constraint that the adversarial image is misclassified by the neural network. They move the misclassification constraint into the objective function to form the non-convex problem: where f (x adv ) is a function that signals when the adversary is found and c is a hyperparameter that controls the relative objective weights of minimizing distance and finding the adversary. The authors propose several different functions for f and show general trends for selecting c. We make special note that a confidence parameter, κ, may be prescribed to the increase the confidence of misclassification at the expense of higher distortion. Carlini-Wagner (CW) attacks are strong and unbounded attacks that seek imperceptibility and are employed in our evaluations.

Backward Pass Differentiable Approximation and Expectation Over Transformation
Although not technically new attacks, backward pass differentiable approximation (BPDA) and expectation over transformation (EOT) [21,29] allow existing attacks to handle defense systems that apply non-differentiable or randomized techniques. Athalye et al. point out that these defenses effectively corrupt available gradient information through shattering (making gradients unavailable at the input due to a non-differentiable operation), stochasticity (applying randomness such that a single calculation of gradients is not representative), and explosion/vanishment (artificial overflow or underflow of gradient values). From a high level, by sampling transformations in the forward pass (EOT) and approximating non-differentiable operations as the identity function in the backward pass (BPDA), gradient based attacks can still find approximate gradients at the input and over many iterations still find a successful perturbation set.

Decision-Based Attack
In situations where gradient information is not reliable, a decision-based attack, like the Boundary Attack proposed by Brendel et al. [30], relies only on the forward pass prediction of the network. The Boundary Attack finds an initial perturbation distribution that is adversarial to the network and then progressively draws new perturbations that both maintain misclassification and reduce the vector norm distance to the original image.

Review of previously proposed defenses 2.2.1 Adversarial Training
Conceptually, the adversarial training approach forces the network to learn more robust decision boundaries at training time via exposure to training examples generated using one or more adversarial attack methods or modifications to the learning process.
Madry et. al [2] increased network robustness by perturbing training examples up to a fixed L p -bound using PGD at each epoch and letting the network learn from the adversarial distribution. As an extension of [2], Ding et. al [3] proposed in Max-Margin training (MMA) that the L p -bound placed on adversarially generated examples need not be fixed and in fact could be optimized on a per example basis to optimize the average decision boundary margin. Zhang et. al [6] included a regularization term in their training loss that searches for an adversarial example in an -neighborhood that maximally changes the output of the network compared to the clean example before updating the network parameters, thus encouraging decision boundaries to move maximally away from the data.
Further advancement in adversarial training focused on crafting adversarial examples based on not only classification loss, but also on the inter-example feature relationships between clean and generated examples. In [7], a PGD adversarial distribution is selected based on maximizing an optimal transport distance from the clean example distribution at the feature map level resulting in adversarial examples that are diverse and distant from clean examples during training.

Image Transformation and Reconstruction
A different defensive strategy is to apply voluntary transformations to inputs or network behaviors at inference time in the hope that these effects cannot be easily approximated by the attacker. Examples of image transformation include random resizing and padding [14], JPEG compression [11], and image quilting [15].
A related defensive strategy involves attempting to eliminate adversarial perturbations through various means [11,13,10,12]. The basis for this strategy relies on the observation that clean and adversarial images, despite often visually similar in pixel space, come from different manifolds in feature space and that any mapping which bridges these two distributions could reduce adversarial corruptions in an image.
In the next section, we present the polynomial kernel matrix, which we use to transform the feature maps of denoised input images.

Polynomial Kernels for Image Transformation
A convolutional neural network, f (x; θ), can be viewed as a composition of functions: where F S is the softmax activation function, F f c is a sequence of fully connected layers, and F 1 ...F L are convolutional layers, that perform the feature extraction function of the network. Each F l , l ∈ {1...L}, is itself a composition of functions, transforming the output of the convolutional layers before it, such that h is a non-linear mapping and Conv(·) is a convolutional operation. Let the set V l = {v 1 , v 2 , ...v C } represent the C feature maps of dimension HxW at layer l. Given any pair of feature maps within the same layer, v i and v j , we define a polynomial kernel function, where e ≥ 0 and integer d ≥ 1 are chosen parameters and ·, · is the inner product. Treating input maps v i and v j as having dimension N = H × W , the kernel function κ(·, ·) has the property that there exists a mapping Given a set of feature vectors V in a convolutional layer, the elements of a kernel matrix G ∈ S CxC + for that layer are computed by, The kernel matrix is a positive semi-definite matrix unique to each layer. Note that for e = 0 and d = 1, the kernel matrix is identical to the Gram matrix.
Specifically for polynomial kernels, the mapping φ(v i ) transforms the input feature map into a higher dimensional vector whose components are formed by all monomial combinations of the input vector components up to total order d. For example, if N = 2, m = 1, and d = 3, then φ(v i ) : R 2 → R 10 maps the components of v i = [v i1 , v i2 ] to a vector that includes all monomial terms from the set {a r,s v r i1 v s i2 | r, s = 0...3, r + s ≤ 3, a r,s ∈ R}. The next section details our defense system construction and the conceptual ideas behind our design choices.

Proposed Training and Defense Methods
As shown in Fig. 1, we describe a training phase (left column) and defense methodology (right column) to produce a perturbation resistant deep neural network. All of the steps contained in the following section can be found in Fig. 1.

Training Phase
Train neural network on clean and smoothed data. Since our defense system applies a traditional image smoothing operation such as a median filter to the image, we wish for the network to be able to recognize the smoothed versions of the original image. Therefore, for each image t ∈ T , we generate a corresponding smoothed image t R to obtain a set T R and then use all examples in {T } ∪ {T R } to train the network.

Inference Phase
Receive new input x. Classify x with f (x; θ) and store result y p |x.
Apply smoothing operation to x to create x R . Apply the same smoothing operation to x that was used to generate set {T R } in the training phase.
From the correctly classified, denoised training data set {T R,c }, draw one sample image corresponding to each class to create a sample set {s 1 ...s K }. Compute and store the polynomial kernel matrices for each sample image. The  Figure 1: Schematic of proposed training and defense processes.
K stored polynomial kernel matrix sets from {s 1 ...s K } will act as target kernel matrices towards which our smoothed x R will be transformed. Create K copies of x R . Each x R copy's polynomial kernels will be transformed independently towards one of the K sets of polynomial kernels stored from {s 1 ...s K } in the next step.

Iteratively impart polynomial kernel values of s
The following discussion is based on the flowchart in Fig. 2. Conceptually similar to but substantially different from neural style transfer [22], the polynomial kernel module computes losses in one or more layers of the network comparing the kernel matrix values of the k th copy of x R to the k th sampled image s k (from class k). The MSE loss for a single layer is: We compute MSE losses at chosen network feature extraction layers and backpropagate their summed loss to the input, updating x R,k using a gradient descent algorithm. After every pixel update, we apply both an L 1 [31] and L ∞ distance constraint to the current updated input, limiting the vector distance between x R,k and its final transformed version x RT,k . The values of these constraints are hyperparameters obtained from validation study. We begin the iteration process by randomly perturbing the target x R within the chosen L ∞ ball.
We iterate on the loss-backpropagate-constraint loop for a chosen number of iterations, recalculating the layer losses, pixel gradients, and vector norm projections independently for each iteration. We emphasize that this transfer procedure is completed for each x R,k corresponding to a different polynomial kernel set generated from s k . The end result is that we output K differently transformed versions of the input, x RT,1 ...x RT,K , to the next step. Having transformed all K copies of x R , we run inference on each transformed copy through the network and store each label prediction in a set, {y p |x RT,1 ...y p |x RT,K }. From this set of predictions, we create a subset H keeping only the predictions that are different than the stored, original prediction on x. We then apply a simple hard vote type rule to the remaining predictions: if the most common predicted label, mode(H), of the predictions that changed due to transformation has a count greater than or equal to a threshold hyperparameter c 3 , we change our final prediction to this most common label. Otherwise, we keep the original network prediction on x.

From an Attacker's Perspective
As shown in Fig. 3, the attacker can choose to attack the network directly (option A) or simulate the full defense system (option B) by implementing the defense algorithm on the forward pass, using gradient approximations on the backward pass, and increasing their sample sizes to better estimate the polynomial kernel transformations that the defender will use at inference time. These two different choices would result in one of two different adversarial images, x adv,A or x adv,B , being fed to the defense system. The defense system initializes by making a prediction on the adversarial image through the 'bare' network, thus storing either f (x adv,A ; θ) or f (x adv,B ; θ). Note how x adv,B was not designed to attack the bare network f (θ) without the defense transformations. Adversarial image x adv,B could still transfer to f (θ), but we posit that it cannot be more likely to succeed than if the attack algorithm had just attacked f (θ) directly, i.e. crafted x adv,A in the first place. The ideal scenario B outcome for the attacker is that a multitude (greater than threshold parameter c 3 ) of the polynomial kernel transforms move x adv,B to the same incorrect label; otherwise the network effectively drops its own defense and resorts to f (x adv,B ; θ), for which we have already stated x adv,B was not designed.

The Polynomial Kernel Transforms
Recall our defense system takes K (number of classes) copies of the smoothed input x R and iteratively imparts the polynomial kernel values of K sampled images from the clean training set (one sample from each class). In the toy example of Fig. 4, a CIFAR10 'dog' is initially correctly classified as class 5, but incorrectly classified to class 3 'cat' when the ResNet18 network is directly attacked (BIM-scenario A). We draw a sample of images from a few classes and also include the original clean image, then apply 25 iterations of kernel transformation from the samples to the adversarial example using feature maps from each residual block in ResNet18 (early and deep layers). Several transformations are successful in restoring the correct classification and some are not.
Our results suggest several important conclusions. First, if the kernel matrix information of the original image is imparted on a perturbed version of itself, the network recovers the correct classification. Second, transformations derived from a sample class k can recover the correct classification of images from other classes k = k as can be seen from the boat sample reclassifying the dog. Third, we track the average polynomial kernel loss 9 at iteration 0 for the deepest residual block in ResNet18 as a (%) share of the total loss across all layers and recognize the original image 'sample' has the highest loss share compared to other samples; likewise, the early layers have relatively low kernel loss. This effect implies that adversarial attacks' imperceptible pixel manipulations create correspondingly small changes in early layer kernel matrices, but larger changes in the deeper layers, which are closer to classification. Lastly, not all transformations result in correct classifications. An important consideration not shown in this particular example, is sometimes we receive random classifications k / ∈ {k, k }. Our interpretation of the toy experiment is pictured on the far right of Fig. 4, a clean example x (black) is perturbed across the decision boundary to a misclassified x adv . Several transformation directions are shown altering x adv to x RT,k depending on the sample's class. Some transformations cross back over the decision boundary and are correctly classified, some remain misclassified, and others end up in random other classes. Let the tuple (k , k ) represent the decision boundary between class k and k . We believe and have found that if the adversary is close to the boundary of the correct class or 'weak', then (k, k ) presents as a larger cross-sectional target to the kernel transforms as compared to others in {(k , k), (k , k ), (k , k )}. Therefore, if any reclassification is to occur, a propensity exists for a correct classification over a random classification. What about clean examples, will they be mistakenly reclassified? Particularly in the case of adversarially trained networks, the clean data is pushed away from the boundary, so the risk of any reclassification is lowered compared to a weak adversary pushed just over the boundary. Further, we perform validation studies to choose a voting threshold parameter c 3 that allows for a few random reclassifications of clean examples without the defense changing its prediction due to the voting committee.
How do these ideas interact with the attack scenario of Fig. 3? The polynomial kernel transforms are not attempting to cleanse adversarial perturbations, rather they are independent feature transformations to all possible classes. The scenario B attacker, to achieve the ideal scenario, must coalesce these different transformations with a single perturbation set or risk that the designed adversary is transferred back to the bare network as a weaker adversary than if it had just targeted the bare network originally.

Evaluation networks and datasets
To evaluate our defense system, we applied our techniques to a basic Resnet18 neural network [23] and tested it against a variety of attacks on the CIFAR10 dataset [24] in the Pytorch environment [32] with 1 GPU. CIFAR10 examples consist of 50,000 training and 10,000 test 32x32 3-channel color images of various natural objects ranging from airplanes to dogs. We trained the network in two different ways. In the first 'Std' training, the network was trained for 100 epochs using standard cross-entropy loss and in the second 'Adv' training, the network was adversarially trained for 100 epochs using the free adversarial training method (m=5) [33] and TRADES loss [6] with λ = 1.

Generation of Adversarial Examples
We used the FoolBox [35,36] library to create a set of L ∞ -bounded (BIM) and unbounded attacks (CW-L2, Deep-Fool) generated against 1000 randomly selected CIFAR10 test set images (drawn separately from the validation study points). The Carlini-Wagner attacks optimized the L2 distance metric and executed 15 binary search steps beginning with c = 0.01. For scenario B adaptive attacks, we used BPDA across the kernel transforms and Pytorch subgradients across the median filter. To handle the ensemble function, we modified the logit output similar to [20]. If Z k is the output logit vector of sample s k , then our adaptive attack model outputs

CIFAR10 Evaluation
Our results in Table 2 show several important trends. We applied our defense system, although intended for an adversarially trained network, to a standard trained network for completeness. Those results show that while the system correctly classifies static scenario A adversarial examples quite frequently, particularly the weaker L 2 adversaries (DeepFool, CW κ = 0), the system is completely bypassed in scenario B by stronger attacks.
In the case of an adversarially trained network under an adaptive BIM = 8/255 attack (scenario B), the defense system maintains a minimum accuracy of 40.4% compared to the baseline network accuracy of 38.6% when we use polynomial kernel transforms from layers 1-5. It does not maintain this accuracy and in fact is reduced from the baseline when we use kernel matrices from only early layers in the network (0-2). This difference in performance suggests that our system must impart information from the deeper feature extraction layers, which contain more classspecific features.
We notice a bifurcation in trend between the weaker (DeepFool, CW κ = 0) and stronger (CW κ = 5) attacks between scenarios A and B, where the system improves accuracy against weaker attacks, but lowers accuracy against stronger attacks. As stated before, we believe the system is better suited for weaker attacks and thus in this case, these attacks close to the decision boundary are failing to find a consensus incorrect label in the ensemble and transferring the perturbed image back to the bare network for classification. The system is not as adept at handling stronger attacks and presumably the attacks can take advantage of our transformations by applying small perturbations in the image space that are favorably magnified by our transforms, so we see the opposite trend against CW κ = 5 attacks. Increasing κ has also been shown to increase the transferability of an attack [18] and would more likely cause our bare network to misclassify even if a voting threshold is not reached. Appropriately, if we were to increase κ further, the system would collapse, but at increasing risk to the attacker that perturbations becomes visually perceptible. Lastly, using a higher order polynomial kernel (d=2) did not provide a benefit in performance and in most cases hurt the system. Results in %. Layers column indicates chosen feature extraction layers to impart kernel transforms.

Conclusion
In this paper, we developed an adversarial defense system that improves the robustness of a neural network against a diverse array of white-box attacks. Our GPU resources limited our generated attacks to a small number of iterations compared to previous works [18], but on a comparative basis our defense maintained increases in robust accuracy against adaptive attacks under certain hyperparameter settings.