On the Robustness of Deep K-Nearest Neighbors

03/20/2019 ∙ by Chawin Sitawarin, et al. ∙ berkeley college 18

Despite a large amount of attention on adversarial examples, very few works have demonstrated an effective defense against this threat. We examine Deep k-Nearest Neighbor (DkNN), a proposed defense that combines k-Nearest Neighbor (kNN) and deep learning to improve the model's robustness to adversarial examples. It is challenging to evaluate the robustness of this scheme due to a lack of efficient algorithm for attacking kNN classifiers with large k and high-dimensional data. We propose a heuristic attack that allows us to use gradient descent to find adversarial examples for kNN classifiers, and then apply it to attack the DkNN defense as well. Results suggest that our attack is moderately stronger than any naive attack on kNN and significantly outperforms other attacks on DkNN.

READ FULL TEXT VIEW PDF
POST COMMENT

Comments

There are no comments yet.

Authors

page 1

page 6

This week in AI

Get the week's most popular data science and artificial intelligence research sent straight to your inbox every Saturday.

I Introduction

Deep learning has recently attained immense popularity from various fields and communities due to its superhuman performance on complicated tasks such as image classification [1, 2], playing complex games [3, 4, 5], controlling driverless vehicles [6, 7], and medical imaging [8]

. Nonetheless, many works have shown that neural networks and other machine learning classifiers are not robust in the face of adversaries (e.g. adversarial examples)

[9, 10, 11, 12, 13] as well as more common cases of distribution shifts [14, 15].

This phenomenon raises a call for more robust and more interpretable neural network models. Many defenses against adversarial examples have been proposed; however, most have been broken by adaptive adversaries [16, 17, 18]. Only a few defenses provide a significant improvement in robustness on toy datasets like MNIST and CIFAR-10 [19, 20]. One plausible approach to simultaneously combat adversaries and make neural networks more trustworthy is to build interpretable models [21, 22, 23] or to provide an explanation supporting the model’s output [24, 25, 26]. Deep k-Nearest Neighbors (DkNN), recently proposed by Papernot & McDaniel, showed promising results: their evaluation suggests it offers robustness against adversarial examples, interpretability, and other benefits [23].

Nonetheless, adversarial examples are surprisingly difficult to detect when that the adversary has full knowledge of the defense [17]. Among the works that have been beaten, many attempts to distinguish adversarial inputs by statistically inspecting their representation (or activation) from hidden layers of neural networks [27, 28, 29, 30]. This fact raises some concerns for the robustness of DkNN, which uses kNN on the intermediate representations produced by the neural network.

In this paper, we examine the robustness of DkNN against adversarial examples. We develop a new gradient-based attack on kNN and DkNN. While gradient descent has found great success in attacking neural networks, it is challenging to apply to kNN, as kNN is not differentiable. At a high level, our attack approximates the discrete nature of kNN with a soft threshold (e.g., a sigmoid), making the objective function differentiable. Then, we find a local optimum using gradient descent under an -norm constraint. With this attack, we find that DkNN is vulnerable to adversarial examples with a small perturbation in both and norms. With -norm of 0.2, our attack manages to reduce the accuracy of a DkNN on MNIST to only 17.44%. Some of the adversarial examples generated with our attack are shown in Fig. 1.

Fig. 1: Adversarial examples generated from the gradient-based attack on kNN and DkNN with - and -norm constraints. The numbers on top and bottom are predictions of DkNN on the clean and the adversarial samples respectively. For a few adversarial examples, the perturbation might change the human label: some of the adversarial 4’s have their top closed, so a human might consider them a 9, and one of the 3’s looks close to an 8.

The main contributions of this paper are as follows:

  1. We propose a gradient-based attack on kNN and DkNN.

  2. We evaluate our attack on kNN and DkNN, compare it to other naive approaches as well as the adaptive attack proposed by Papernot & McDaniel, show that our attack performs better than prior attacks, and show that it can find adversarial examples for kNN and DkNN on MNIST.

  3. We show that the credibility scores from DkNN models are not effective for detecting our attacks without a significant drop in accuracy on clean images.

Ii Background and Related Work

Ii-a Adversarial Examples

Adversarial examples are a type of an evasion attack against machine learning models at test time. While the robustness of machine learning classifiers in adversarial settings has been studied for a long time [31, 32], the term “adversarial examples” was recently introduced as an attack on deep neural networks by adding very small perturbation to a legitimate sample [10, 11]. Previous works propose algorithms for finding such perturbation under a norm-ball threat model which can be generalized as solving the following optimization problem:

(1)

where

is some loss function associated with the correct prediction of a clean sample

by the target neural network. The constraint is used to keep the perturbation small or imperceptible to humans. Our attack also uses the norm-ball constraint and an optimization problem of a similar form.

Ii-B Robustness of k-Nearest Neighbors

The kNN classifier is a popular non-parametric classifier that predicts the label of an input by finding its nearest neighbors in some distance metric such as Euclidean or cosine distance and taking a majority vote from the labels of the neighbors. Wang et al. recently studied the robustness of kNN in an adversarial setting, providing a theoretic bound on the required value of such that robustness of kNN can approach that of the Bayes Optimal classifier [33]. Since the required value of is too large in practice, they also propose a robust 1-NN by selectively removing some of the training samples. We did not experiment with this defense as it is limited to a 1-NN algorithm with two classes.

Ii-C Deep k-Nearest Neighbors

DkNN, proposed by Papernot & McDaniel, is a scheme that can be applied to any deep learning model, offering interpretability and robustness through a nearest neighbor search in each of the deep representation layers. Using inductive conformal prediction, the model computes, in addition to a prediction, confidence and credibility scores, which measure the model’s assessment of how likely its prediction is to be correct. The goal is that adversarial examples will have low credibility and can thus be easily detected. The credibility is computed by counting the number of neighbors from classes other than the majority; this score is compared to scores seen when classifying samples from a held-out calibration set. Papernot & McDaniel evaluate DkNN with an adaptive adversary which is found to be quite unsuccessful. We examine the robustness of DkNN with the stronger attack we propose.

We note that the DkNN proposed by Papernot & McDaniel uses cosine distance, which is equivalent to Euclidean distance given that all samples are normalized to have a unit norm. For the rest of the paper, we tend to omit the normalization for simplicity and less clutter in equations. The implementation and the evaluation, however, use cosine distance as instructed in the original paper.

Iii Threat Model

We assume the white-box threat model for attacks on both kNN and DkNN. More precisely, the adversary is assumed to have access to the training set and all parameters of the DkNN neural network. Since a kNN classifier is non-parametric, the training set is, in some sense, equivalent to the weights of parametric models. We also assume that the adversary knows all hyperparameters, namely

, the distance metric used (Euclidean or cosine distance), and additionally the calibration set for DkNN. Though this knowledge is less crucial to the adversary, it allows the adversary to accurately evaluate his/her attack during the optimization resulting in a more effective attack.

For consistent comparisons with previous literature, the adversarial examples must be contained within a norm-ball ( and ) centered at given test samples. We recognize that the -norm constraint may not be representative of human perception nor applicable in many real-world cases.

Iv Attack on k-Nearest Neighbors

Iv-a Notation

We follow notation from Papernot & McDaniel as much as possible. Let denote a target sample or a clean sample that the adversary uses as a starting point to generate an adversarial example, and its ground-truth label. We denote the perturbed version of as . The training set for both kNN and DkNN is with samples of dimension . The classifier’s prediction for a sample is .

Iv-B Mean Attack

We first introduce a simple, intuitive attack to serve as a baseline. Let be a clean sample, its ground-truth class, and be a target class. The attack, which we call the mean attack, works by moving in the direction towards the mean of all samples in the training set with class . Concretely, we first search for the class such that the mean of training samples with that class is closest to in Euclidean distance. Let denote the corresponding mean. We then use binary search to find the smallest such that is misclassified by the kNN.

This attack is very simple to carry out and applicable to any classifier. While it is a natural choice for attacking a kNN with Euclidean distance, the attack may perform less well for cosine distance or other distance measures. As our experiments show, the mean attack also produces perturbations that make the resulting adversarial example look, to humans, more like samples from the target class, and thus makes the attack more noticeable. Nonetheless, this attack can be regarded as a simple baseline for measuring the robustness of nearest-neighbor classifiers.

Iv-C Naive Attack

Fig. 2: (a) naive attack for : The target sample (light blue circle) is moved towards each of the samples from a different class (red triangles). The one that requires the smallest -distance to change the prediction is the optimal adversarial example (pink circle). (b) naive attack for : In the first step, a set of 3 samples from the different class closest to are located with a greedy algorithm. The second step involves moving towards a mean of the samples in and stops when the prediction changes.

Next, we introduce a second baseline attack that improves slightly on the mean attack. When , a simple algorithm can find the optimal adversarial example in time. For each training sample of a class other than , the algorithm moves the target sample in a straight line towards until (i.e., setting , we find the smallest such that ). This produces candidate adversarial examples, and the algorithm outputs the one that is closest to . Fig. 2(a) illustrates this algorithm.

This strategy finds the optimal adversarial example when , but when , it is not clear how to find the optimal adversarial example efficiently. Repeating the previous strategy on all sets of training samples does not guarantee an optimal solution and is inefficient, as its complexity grows exponentially with . Instead, we propose a computationally cheaper attack that greedily chooses only one set of samples to move towards, as summarized in Fig. 2(b). There are multiple possible heuristics to choose this set. One simple option would be to find the nearest neighbors of whose labels all match but are different from . We instead use a slightly more complex variant: (1) find the nearest neighbor from any class other than , say class , (2) add this sample to an empty set , and (3) out of all samples with class , iteratively find the nearest sample to the mean of and add it to . The final step is repeated until . Finally, we move towards the mean of until the classifier’s prediction differs from .

Iv-D Gradient-Based Attack

Here we introduce our main attack on kNN. On a high-level, it uses a heuristic initialization to choose a set of samples that are close to the target sample . Then, a gradient-based optimization is used to move closer to the ones with the target class and further from the ones with the original class .

We will discuss the choices for the heuristic initialization towards the end of this section. For now, the algorithm can be formulated as the following optimization problem.

(2)

where is the perturbation, is the adversarial example, are the training samples selected earlier, and if the label of is , otherwise . The first constraint constrains the norm of the perturbation, and the second constraint ensures that the adversarial example lies in a valid input range, which here we assume to be for pixel values.

However, Eq. 2 may not achieve what we desire since it treats all equally and does not take into account that for kNN, only the nearest neighbors contribute to the prediction, while the other training samples are entirely irrelevant. Moreover, the distance to these neighbors does not matter as long as they are the closest. In other words, the distance to each of these neighbors is irrelevant so long as it is under a certain threshold (where is the distance to the -th nearest neighbor). This means that a sample gets a vote if ; otherwise, it gets zero vote. The optimization above does not take this into account.

We show how to adjust the optimization to model this aspect of kNN classifiers. The function that maps to 0 or 1 according to whether

gets a vote is not a continuous function and it has zero gradient where it is differentiable, so it poses challenges for gradient-based optimization. To circumvent this problem, we approximate the threshold with a sigmoid function,

where is a hyperparameter that controls “steepness” (or an inverse of temperature) of the sigmoid. As , the sigmoid exactly represents the Heaviside step function, i.e., a hard threshold. This lets us adjust Eq. 2 to incorporate the considerations above, as follows:

(3)

Ideally, should be recomputed at every optimization step, but this requires finding nearest neighbors at each step, which is computationally expensive. Instead, we fix the value of by taking the average distance, over all training samples, from each sample to its -th nearest neighbor.

Choosing the initial samples. There is no single correct way to initialize the set of samples. We empirically found that choosing all of them from the same class , and choosing the training samples of that class that are closest to , works reasonably well. We choose by computing the distance from to the mean of all samples of class , for each , and taking the class that minimizes this distance. Other heuristics might well perform better; we did not attempt to explore alternatives in depth, as this simple heuristic sufficed in our experiments. The choice of the attack parameter affects the attack success rate. A larger means we consider more training samples which make the kNN more likely to be fooled, but it is also more expensive to compute and may produce larger distortion. In principle, one could recompute the set of samples periodically as the optimization progresses, but for our experiments, we select them only once in the beginning.

For , we use a change of variable as introduced by Carlini & Wagner [34] to provide pixel-wise box constraints that simultaneously satisfy both of the optimization constraints in Eq. 3. More precisely, the -th pixel of the adversarial example is written as where and are the upper and the lower bound of that pixel respectively. becomes the variable that we optimize over, but for simplicity, we omit it from Eq. 3. In the case of , this change of variables enforces the second constraint. The first constraint is relaxed and added to the objective function as a penalty term:

(4)
such that

To find an appropriate value for , we use a binary search for five steps. If the attack succeeds, is increased; otherwise, is decreased.

V Attack on Deep k-Nearest Neighbors

V-a Notation

Let denote DkNN’s prediction for a sample . The prediction of the -layer neural network part of the DkNN is denoted as , and the output from the -th layer as where . The calibration set is used to calculate the empirical -value as well as the credibility and confidence.

V-B Mean Attack

The mean attack for DkNN is exactly the same as for kNN without any modification as the attack does not depend on the choice of classifiers.

V-C Baseline Attack

We use the adaptive attack evaluated by Papernot & McDaniel as a baseline. Given a target sample , we try to minimize the distance between its representation at the first layer and that of a guide sample , a sample from a different class whose representation is closest to . For the -norm constraint, the attack can be written as:

(5)
such that

The optimization is solved with L-BFGS-B optimizer as suggested in Sabour et al. [35]. For completeness, we will also evaluate the attack with a constraint, using the same relaxation as Eq. 4.

V-D Gradient-Based Attack

The baseline attack relies on an assumption that if is close to , then will also be close to for , resulting in both and having a similar set of neighbors for all of the layers as well as the final prediction. However, while this assumption makes intuitive sense, it can be excessively strict for generating adversarial examples. The adversary only needs a large fraction of the neighbors of to be of class . By extending the gradient-based attack on kNN, we formulate an analogous optimization problem for attacking DkNN as follows:

(6)

The samples are chosen similarly to the attack on kNN. In the interest of space, we omit the formulation for the constraint as it is also analogous to Eq. 4.

Vi Experimental Setup

We reimplement DkNN from Papernot & McDaniel with the same hyperparameters, including the network architecture and the value of . We evaluate our attacks on the MNIST dataset [36] as past research suggests that finding adversarial examples on other tasks is even easier. 60,000 samples are used as the training samples for kNN, DkNN, as well as the neural network part of DkNN. 750 samples (75 from each digit) are held out as the calibration set, leaving 9,250 test samples for evaluating the accuracy and the robustness of the classifiers against the attacks. Similarly to Papernot & McDaniel, for a quick nearest neighbor search on DkNN, we use a locality-sensitive hash (LSH) from the FALCONN Python library, which is based off cross-polytope LSH by Andoni et al. [37]. kNN uses an exact neighbor search without any approximation. The kNN and the DkNN have an accuracy of 95.74% and 98.83% on the clean test set, respectively. The neural network alone has an accuracy of 99.24%.

All of the attacks are evaluated under both - and -norm constraints, except for the naive attack on kNN and the mean attacks. For simplicity, we only evaluate untargeted attacks. Both the mean and the naive attacks use only five binary search steps. For the other attacks, we use 400 iterations of gradient updates and five steps of binary search on the -penalty constant. The Adam optimizer is used in the gradient-based attack, and to save computation time, we only check for the termination condition (i.e., whether is misclassified) three times at iterations 320, 360, and 400, instead of at every step.

We made minimal effort to select hyperparameters. We fix the steepness of the sigmoid at 4, and for DkNN, we arbitrarily choose the initial samples to be the training samples with class whose first-layer representation is closest to that of . For the -norm attacks, is simply chosen to be 0 with the constant being 1. This choice of penalty generally allows the optimization to find adversarial examples most of the time but may result in unnecessarily large perturbations. To set a more strict constraint, one could set to a desired threshold and to a very large number.

Vii Results

Vii-a k-Nearest Neighbors

Attacks Accuracy Mean Distortion in
Clean Samples 0.9574 -
Mean Attack 0.0589 8.611
Naive Attack 0.7834 8.599
Gradient Attack () 0.0989 6.565
Gradient Attack () 0.8514 5.282
TABLE I: Evaluation of all the attacks on kNN.

Table I displays the accuracy and mean distortion of the successful adversarial examples for kNN. As expected, the mean attack is very good at finding adversarial examples but the perturbation is large and the adversarial examples sometimes introduce anomalies that may be noticeable to humans. Surprisingly, the naive attack performs much more poorly compared to the mean attack, indicating that the heuristic used to choose the set of target samples can significantly affect the attack success rate. The gradient-based attack with the -norm performs well and is on par with the mean attack while having considerably smaller mean distortion. On the other hand, the gradient attack with -norm of 0.2 is mostly unsuccessful. We speculate this might be because is too small and the -norm is an ineffective choice of norm as kNN relies on Euclidean distance in the pixel space for prediction.

Vii-B Deep k-Nearest Neighbors

Attacks Accuracy Mean Dist. Mean Cred.
Clean Samples 0.9883 - 0.6642
Mean Attack 0.1313 4.408 0.0172
Baseline Attack () 0.1602 3.459 0.0185
Baseline Attack () 0.8891 2.660 0.0807
Baseline Attack (fixed ) 0.5004 3.435 0.1385
Gradient Attack () 0.0000 2.164 0.0482
Gradient Attack () 0.1744 3.476 0.1037
Gradient Attack (fixed ) 0.0059 3.375 0.3758
TABLE II: Evaluation of all the attacks on DkNN.

Table II compares the accuracy, mean distortion, and mean credibility of the successful adversarial examples for DkNN between the three attacks. Our novel gradient-based attack outperforms the baseline as well as the mean attack by a significant margin. With an -norm constraint of 0.2, the gradient attack reduces the classifier’s accuracy much further compared to the baseline. With an -norm constraint, our gradient attack also performs better with smaller perturbation. Although the mean attack reduces the accuracy even lower than the gradient attack with -norm of 0.2, it has lower mean credibility and the perturbation is also considerably larger and more visible to humans.

Unlike an constraint, which is strictly enforced by the change of variables trick, an constraint is written as a penalty term with only a tunable weighting constant. To compare the baseline and the gradient attacks under a similar -norm, we arbitrarily set to be the mean -norm of the gradient attack (3.476) and the constant to be just high enough that the optimization still finds successful attacks with a minimal violation on the constraint . We report the results for both attacks in Table II on the “fixed ” rows. The gradient attack, when given a large budget, can increase the credibility significantly and reduce the accuracy to almost zero (0.6%). In contrast, the baseline attack can only find adversarial examples for about 50% of the samples under the same constraint.

Fig. 3: Each column shows five nearest neighbors for each of the four deep representation spaces of DkNN. From left to right, the inputs are a randomly chosen legitimate sample, its and baseline attacks, and its and gradient attacks. For the -norm constraint, is 0.2. The legitimate sample is correctly predicted by the DkNN, and all of the attacks succeed in changing the prediction from a six to a five, except for the baseline attack.

Fig. 3 shows a clean sample and its adversarial versions generated by all of the attacks along with their five nearest neighbors at each of the four layers of representation. On the first column, all of the 20 neighbors of the clean sample have the correct class (a six). On the other hand, the majority of neighbors of the adversarial examples are of the incorrect class (a five) with an exception of the first layer whose neighbors generally still come from the correct class. The other common property of all the attacks is that almost every neighbor in the final layer has the adversarial class.

Note that the -attacks, both the baseline and the gradient-based attack, often perturb the sample in a semantically meaningful manner. Most are subtle, but some are quite prominent. For instance, the input of the third column from the left in Fig. 3 is perturbed by slightly removing the connected line that distinguishes between a five and a six, making the adversarial example appear somewhat ambiguous to humans. In contrast, the adversarial examples usually spread the perturbation over the entire image without changing its semantic meaning in a way that is noticeable to humans.

Fig. 4: (a) Accuracy and (b) mean credibility of DkNN under the baseline attack and our gradient-based attack at different -norm constraints.

For the -norm constraint, as we increase , the accuracy of DkNN drops further and hits zero at , as shown in Fig. 4(a), whereas increasing on the baseline attack reduces accuracy at a much slower rate.

Fig. 4(b) displays the mean credibility of successful adversarial examples generated from the baseline and the gradient attacks. As expected, as we increase , the mean credibility also increases for both attacks because the adversarial example can move closer to training samples from the target class. The gradient-based attack increases the mean credibility at a much faster rate than the baseline potentially because its objective function indirectly corresponds to the credibility as it takes into account training samples instead of one like the baseline. In the next section, we discuss the possibility of detecting adversarial examples by setting a threshold on the credibility score.

Viii Discussion

Viii-a Credibility Threshold

Fig. 5: Histogram of credibility of the clean test samples and the adversarial examples generated from the gradient-based attack with the -norm constraint of 0.2 and 0.3. The black dashed vertical line indicates credibility of 0.1.

Papernot & McDaniel argues that the credibility output by DkNN is a well-calibrated metric for detecting adversarial examples. In Fig. 5, we show the distribution of the credibility for the clean test set and for adversarial examples generated from the gradient-based attack with two different -norms. Most of the test samples (around 55%) have credibility between 0.9 and 1. On the other hand, the majority of the adversarial examples have credibility less than 0.1, suggesting that setting a threshold on credibility can potentially filter out most of the adversarial examples. However, doing so comes at a cost of lowering accuracy on legitimate samples. Choosing a credibility threshold of 0.1 reduces accuracy on the test set to 91.15%, which is already very low for MNIST, and with this threshold, 28% and 43% of the adversarial examples with -norm of 0.2 and 0.3 respectively still pass the threshold and would not be detected. It is also important to note that our attack is not designed to maximize the credibility. Rather, it is designed to find adversarial examples with minimal distortion. Simple parameter fine-tuning, e.g. a larger , more iterations, and a smaller , might all help increase the credibility.

Our experiments suggest that DkNN’s credibility may not be sufficient for eliminating adversarial examples, but it is still a more robust metric for detecting adversarial examples than a softmax score of typical neural networks. Unfortunately, thresholding the credibility hurts accuracy on legitimate examples significantly even for a simple task like MNIST. According to Papernot & McDaniel, the SVHN and GTSRB datasets both have a larger fraction of legitimate samples with low credibility than MNIST, making a credibility threshold even less attractive. Experiments with the ImageNet dataset, deeper networks, choosing which layers to use, and pruning DkNN for robustness are all interesting directions for future works.

Ix Conclusion

We propose two heuristic attacks and a gradient-based attack on kNN and use them to attack DkNN. We found that our gradient attack performs better than the baseline: it generates adversarial examples with a higher success rate but lower distortion on both and norms. Our work suggests that DkNN is vulnerable to adversarial examples in a white-box adversarial setting. Nonetheless, DkNN still holds promise as a direction for providing significant robustness against adversarial attacks as well as interpretability of deep neural networks.

X Acknowledgements

This work was supported by the Hewlett Foundation through the Center for Long-Term Cybersecurity and by generous gifts from Huawei and Google.

References