---
title: kNN Proximity-Based Defense (KPB) Overview
url: https://www.emergentmind.com/topics/knn-proximity-based-defense-kpb
type: topic
---

# kNN Proximity-Based Defense (KPB) Overview

kNN Proximity-Based Defense (KPB) is a thresholded \(k\)-nearest-neighbor pre-processing defense introduced as one of four defenses against Beta Poisoning, a heuristic data poisoning attack designed to avoid expensive bilevel optimization and to make training data linearly nonseparable. KPB is tailored to a specific geometric artifact of Beta Poisoning: poisoning samples tend to lie very close to one another, forming a dense local cluster, and they are centered near the mean of the target class while being labelled as the non-target class. For each sample in a suspicious training set, KPB computes the average distance to its nearest neighbors and flags the sample as poisoned when that average falls below a threshold \(\tau\). In that sense, KPB is a high-density detector specialized to structured poisoning rather than a generic outlier detector [2508.01276].

## 1. Attack geometry and motivation

Beta Poisoning operates on a target class \(y_t\) by constructing poisoning samples \(x_p\) that maximize the class-conditional likelihood \(P(x_p \mid y_t)\) under a kernel density estimator, typically Gaussian KDE, while remaining within box constraints:
\[
\arg\max_{x_p} \; P(x_p \mid y_t)
\quad \text{s.t.} \quad
\mathbf{x}_{lb} \preceq x_p \preceq \mathbf{x}_{ub}.
\]
The poisoning sample is parameterized as a linear combination of target-class prototypes,
\[
x_p = \psi(\boldsymbol{\beta}, \mathcal{S}) = \sum_{x_i \in \mathcal{S}} \beta_i x_i,
\]
where \(\mathcal{S} = \{x_1,\dots,x_k\}\) are prototypes from class \(y_t\) and \(\boldsymbol{\beta}\) is optimized by gradient ascent on the KDE likelihood. The stated objective is to make the training data linearly nonseparable, which is especially damaging to linear models [2508.01276].

The defense rationale follows directly from two empirical properties of Beta-poisoned points. First, poisoning samples have **close proximity**: many lie very close to each other and form a dense local cluster. Second, they are **centered near the target-class mean** of \(y_t\), while being labelled as the non-target class \(y_{nt}\). Generic outlier detection is described as not ideal because it looks for isolated points, whereas Beta Poisoning produces structured, high-density anomalies. KPB therefore targets the first property directly: anomalously short distances to nearest neighbors.

This geometry yields the central intuition of KPB. Clean data are spread across the support of the class distributions, so the average distance to their nearest neighbors is moderate. Beta-poisoned points, by contrast, are clustered in a tight region and are close to one another in feature space, so each poisoning point has many very close neighbors, largely other poisoning points. KPB exploits this contrast by treating unusually high local density as the defining anomaly.

## 2. Formal definition and decision rule

KPB is defined on a suspicious dataset
\[
\mathcal{D}_{sp} = \{(x_1,y_1),\dots,(x_n,y_n)\},
\]
where some \(x_i\) are clean and others are poisoning samples generated by Beta Poisoning. Its output is a flagged subset
\[
\mathcal{D}_{fl} \subseteq \mathcal{D}_{sp},
\]
interpreted as the set of samples detected as poisoned. The defense uses a distance function \(\text{dist}(x_i,x_j)\); the paper does not lock in a specific metric, but in practice this is typically Euclidean,
\[
\text{dist}(x_i,x_j)=\|x_i-x_j\|_2.
\]
Its two parameters are the distance threshold \(\tau>0\) and the neighbor fraction \(\eta \in (0,1]\), which defines the number of neighbors as
\[
\text{num} = |\mathcal{D}_{sp}| \times \eta.
\]
In implementation, this quantity is rounded to an integer [2508.01276].

For each sample \((x_i,y_i)\in\mathcal{D}_{sp}\), KPB first identifies its \(\text{num}\) nearest neighbors:
\[
\text{nbrs}(x_i)=\text{Identify\_Neighbors}(x_i,\mathcal{D}_{sp},\text{num}).
\]
It then computes the average distance from \(x_i\) to these neighbors:
\[
\text{avg\_dist}(x_i)=\frac{1}{\text{num}}
\sum_{(x_j,y_j)\in \text{nbrs}(x_i)} \text{dist}(x_i,x_j).
\]
The flagging criterion is
\[
(x_i,y_i)\text{ is flagged as poisoned} \iff \text{avg\_dist}(x_i) < \tau.
\]
Equivalently,
\[
\mathcal{D}_{fl}=
\left\{
(x_i,y_i)\in\mathcal{D}_{sp}\mid \text{avg\_dist}(x_i)<\tau
\right\}.
\]

Algorithmically, the procedure is direct. Initialize \(\mathcal{D}_{fl}\gets \emptyset\), set \(\text{num}\gets |\mathcal{D}_{sp}|\times \eta\), iterate through all samples, compute nearest neighbors, accumulate total distance, divide by \(\text{num}\), and add the sample to \(\mathcal{D}_{fl}\) whenever the resulting average is below \(\tau\). The cleaned dataset is then
\[
\mathcal{D}_{clean}=\mathcal{D}_{sp}\setminus \mathcal{D}_{fl},
\]
and the experimental protocol retrains the model \(f_\theta\) on \(\mathcal{D}_{clean}\).

Two characteristics distinguish KPB from the other defenses in the same study. It is conceptually simpler than Clustering-Based Defense (CBD), which requires k-means clustering and the elbow method, and unlike Mean Distance Threshold (MDT) it does not require computing class means. The paper also states that KPB does not require knowledge of which class is target or non-target; it uses only local proximity in feature space.

## 3. Hyperparameters, implementation, and complexity

The recommended implementation begins with feature normalization consistent with classifier training, such as per-pixel normalization for images. If dimensionality is very high, PCA or another embedding may optionally be applied for computational or numerical reasons, although KPB itself does not require dimensionality reduction. Neighbor search is performed over the entire suspicious dataset \(\mathcal{D}_{sp}\), commonly excluding the query point itself from its neighbor set. Exact search by brute force, k-d trees, or ball trees is suggested for moderate \(n\) and modest dimensionality, while approximate kNN libraries such as FAISS, Annoy, and FLANN are suggested for large datasets or high dimension [2508.01276].

The paper’s default setting is
\[
\eta = 0.1,
\]
so that
\[
k = \text{num} = \lfloor \eta n \rfloor \approx 0.1n.
\]
The stated rationale is that this scales with dataset size and avoids manually tuning \(k\) in absolute terms. The paper does not provide a sensitivity analysis over \(\eta\); it fixes \(\eta=0.1\) and focuses on \(\tau\). It also notes the trade-off that too small \(\eta\) yields tiny neighborhoods and a noisy estimate, whereas too large \(\eta\) washes out the local density signal.

Threshold selection is presented as the central tuning problem. On MNIST and CIFAR-10, the best-performing values are reported in the range
\[
\tau \in [3,5],
\]
under the paper’s normalization and feature scale. For very small \(\tau\), both precision and recall drop sharply because the threshold becomes too strict and true poisons are missed. For large \(\tau\), recall remains high but precision drops because legitimate points in moderately dense regions begin to be flagged. The practical guideline is that \(\tau\) “should be neither too large nor too small,” and the paper explicitly characterizes the optimal \(\tau\) as dataset-dependent.

When labeled poisoned points are unavailable, the suggested procedure is to compute \(\text{avg\_dist}(x_i)\) for all points, inspect the empirical distribution, and choose \(\tau\) near the lower tail where an unusually dense cluster is expected, for example by using a small percentile cut-off such as \(1\%\) to \(5\%\), possibly adjusted with validation.

The computational bottleneck is neighbor search. A naïve implementation requires \(O(n^2 d)\) distance computations and \(O(n^2)\) neighbor selection overall, while space complexity is \(O(nd)\) for storing the dataset and \(O(k)\) extra space if points are processed sequentially. This suggests that KPB is naturally suited to pre-processing settings, where the cost is paid once per dataset rather than per query.

## 4. Empirical performance and comparison within the Beta Poisoning study

The evaluation treats defense as a binary classifier at the sample level and reports accuracy, precision, recall, and F1. Experiments are reported on MNIST, CIFAR-10, and preliminarily on CIFAR-100, all at a 20% poison rate. On MNIST and CIFAR-10, KPB achieves perfect scores under optimized \(\tau\); on CIFAR-100 it remains near-perfect but not flawless, with precision preserved at \(1.0\) and recall reduced to \(0.966\). The tuning plots show a characteristic regime change: precision and recall are close to zero at very small \(\tau\), both reach \(1.0\) in the mid-range, and at large \(\tau\) precision falls while recall stays near \(1.0\), indicating increasing false positives [2508.01276].

| Dataset | Accuracy / F1 / Precision / Recall | Notes |
|---|---|---|
| MNIST | \(1.0 / 1.0 / 1.0 / 1.0\) | Optimized \(\tau\) |
| CIFAR-10 | \(1.0 / 1.0 / 1.0 / 1.0\) | Optimized \(\tau\) |
| CIFAR-100 | \(0.994 / 0.983 / 1.0 / 0.966\) | Preliminary experiment |

These results imply different operating profiles across datasets. On MNIST and CIFAR-10, KPB fully recovers a clean training set in the reported setting: all poisoning samples are detected and no clean samples are falsely flagged. On CIFAR-100, the outcome is more conservative: all flagged points are actually poisoned, but a small fraction of poisoning samples remain undetected. This suggests that increasing data complexity makes the density-based separation harder to exploit perfectly, while leaving the basic mechanism intact.

Within the same study, KPB is compared to Neighborhood Class Comparison (NCC), Clustering-Based Defense (CBD), and Mean Distance Threshold (MDT). Under optimized parameters, MDT also achieves perfect \(1.0\) scores on MNIST and CIFAR-10; CBD is perfect on MNIST and very high but slightly non-perfect on CIFAR-10, with accuracy \(\approx 0.992\), F1 \(\approx 0.976\), precision \(\approx 0.952\), and recall \(1.0\); NCC shows lower precision and overall accuracy because of many false positives. KPB therefore matches the best-performing method in the paper while using only local proximity and no class-mean information.

## 5. Position within the broader nearest-neighbor defense literature

KPB belongs to a broader family of nearest-neighbor defenses, but its role within that family is unusually specific. In the Beta Poisoning setting it is a training-set sanitization mechanism based on high local density. By contrast, other nearest-neighbor defenses use proximity in representation space at test time, certification by vote margins, or semantic retrieval over a trusted database. A representation-space defense classifies a test input by kNN over intermediate activations and, in a 1-NN plus Lipschitz-network variant, derives a certified lower bound
\[
\|r\|_2 \ge \frac{\gamma(x)}{2L}
\]
on the perturbation required to change the decision. A certified poisoning defense for kNN and rNN uses the vote margin
\[
e^*(\mathbf{x})=
\Big\lceil \frac{s_a(\mathbf{x})-s_b(\mathbf{x})+\mathbb{I}(a>b)}{2}\Big\rceil -1
\]
to guarantee prediction stability under bounded poisoning. In 3D point cloud classification, KNN-Defense performs nearest-neighbor search in feature space and aggregates neighbors’ softmax outputs instead of reconstructing geometry. For clean-label data poisoning on CIFAR-10, a Deep k-NN defense filters training examples whose labels disagree with the plurality label among their deep-feature neighbors, detecting over \(99\%\) of poisoned examples in both feature collision and convex polytope attacks. ASK-Def goes further by training DkNN with a soft kNN loss that directly regularizes proximity relations under adversarial perturbations [1906.09525, 2012.03765, 2506.06906, 1909.13374, 2106.14300].

This comparison clarifies what is distinctive about KPB in the strict sense of the Beta Poisoning literature. It is not a classifier replacement, not a certification mechanism, and not an embedding-learning objective. It is a specialized pre-processing detector that assumes poisoning samples form an anomalously dense local cluster. A plausible implication is that KPB should be viewed less as a generic property of kNN and more as a geometry-matched countermeasure against one particular poisoning construction.

## 6. Limitations, controversy, and open directions

The principal limitation stated for KPB is dependence on attack structure. The defense leverages specific traits of Beta Poisoning, especially the dense cluster produced by linearly combined prototypes. If an attacker uses a poisoning method that does not create such clusters, KPB could be less effective. The paper does not examine KPB against other poisoning attacks and explicitly leaves that for future work. It also identifies dataset dependence of \(\tau\), the difficulty of perfect separation on more complex data such as CIFAR-100, the \(O(n^2)\) cost of naïve kNN search, and the prospect of adaptive attacks specifically optimized to evade the proposed defenses, for example by spreading poisoning samples more diffusely [2508.01276].

Broader nearest-neighbor research sharpens these caveats. Attack papers on deep kNN and other kNN-based models show that non-differentiability is not itself a defense: gradient-based attacks can produce stronger results than earlier methods and can make several kNN-based defenses appear less robust than standard adversarial training under proper evaluation. Theory further shows that nearest-neighbor robustness depends critically on the value of \(k\): constant \(k\) can be asymptotically non-robust wherever \(\eta(x)\in(0,1)\), whereas robustness approaches that of the Bayes Optimal classifier for fast-growing \(k\). Geometric work on \(k\)-NN poisoning also indicates that strong poisoning attacks are highly local and act by inducing local majority changes in small regions. This suggests that KPB’s present form is best understood as one effective point in a larger design space whose general problem is still open: how to convert local proximity structure into defenses that remain robust under adaptive, geometry-aware poisoning strategies [2003.06559, 1903.08333, 1706.03922, 2306.12377].

Source: https://www.emergentmind.com/topics/knn-proximity-based-defense-kpb