Manuscript Offprint
arXiv:2611.07257Evolutionary Adaptive Neighborhood Learning: A Genetic Algorithm for Instance-Dependent k Optimization in Nearest Neighbor Classification
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Abstract
The number of neighbours is the central hyper-parameter of the -nearest neighbour (-NN) classifier, and it is almost always chosen globally, by cross-validation or, increasingly, by evolutionary search. Yet the bias-variance trade-off that governs is local: dense, noise-free regions favour small neighbourhoods, whereas sparse or label-noisy regions favour large ones. Because the global- search space is one-dimensional, replacing exhaustive search by a genetic algorithm (GA) cannot improve on it. We therefore change the object being optimised. We propose EANK (Evolutionary Adaptive Neighborhood ), which evolves a low-dimensional policy mapping a description of the local neighbourhood of a point (density, label entropy at two scales, vote margin, concentration, relative density) to an instance-dependent number of neighbours . A real-coded elitist GA maximises the leave-one-out accuracy of the induced adaptive rule, penalised by a neighbourhood-smoothness term. A pre-computed vote table reduces each fitness evaluation to look-ups. We prove that (i) a seeded EANK never does worse than the best global on its training criterion, (ii) the GA converges almost surely to the essential supremum of the fitness, (iii) the learned neighbourhood size is Lipschitz in the meta-features, and (iv) the policy class has a growth function polynomial in the sample size with exponent . This yields a uniform generalisation bound that does not depend on , which per-instance encodings do not enjoy. On a controlled benchmark with spatially heterogeneous structure, EANK recovers small neighbourhoods in the fine-grained region and large ones in the noisy region, and it improves accuracy over the best global at every noise level. In a nested, -fold evaluation on twelve public datasets, EANK obtains the best average rank among six -NN variants. Its accuracy is statistically indistinguishable from the tuned global- baselines, and it is significantly better than the default . We document the gap between in-sample and out-of-sample gains, and we identify it as the main obstacle for adaptive-neighbourhood methods.
Keywords: -nearest neighbours; adaptive neighbourhood; genetic algorithms; hyper-parameter optimisation; leave-one-out; generalisation bounds.
1 Introduction
The -nearest neighbour rule [5, 14, 29] remains one of the most widely used non-parametric classifiers. It is simple and universally consistent when and [12, 30], and its predictions are easy to interpret. Its behaviour, however, depends strongly on the neighbourhood
*Corresponding author. E-mail: isaac_touza@outlook.fr.
size . A small gives a low-bias, high-variance rule that is sensitive to label noise. A large smooths the decision boundary but erases fine structure and minority regions.
In practice is selected once for the whole input space, by grid search with cross-validation, by leave-one-out (LOO) error, or by a metaheuristic. A recent line of applied work uses genetic algorithms (GAs) to tune , often jointly with feature selection or distance weights [17, 20, 24, 25]. Further studies examine how the choice of interacts with feature selection and class imbalance [6]. When is the only quantity being optimised, the search space is one-dimensional and small. Exhaustive LOO search costs essentially the same as a single -NN pass, because all predictions of a point can be read from one sorted neighbour list. Exhaustive search therefore finds the exact optimum of the global- criterion, and it is an upper bound for any other optimiser of that criterion: a GA, random search [2] or Bayesian optimisation. Replacing grid search by a GA cannot, by construction, improve on it.
The statistical theory of nearest neighbours, by contrast, says that the right amount of smoothing is local. Convergence rates depend on the local density and the local margin [4], -NN adapts to the local intrinsic dimension [19], and recent adaptive rules choose the neighbourhood point by point [1]. This suggests changing the object being optimised: we look for a function rather than an integer.
Approach. We parameterise this function as a policy . Here is a small vector of meta-features that describe the neighbourhood of in the training set (scale, label entropy, vote margin, concentration, relative density), and with . The induced rule classifies by majority vote among its nearest neighbours. The objective is piecewise constant and non-differentiable in , and it has many plateaus, so we optimise it with a real-coded elitist GA. The fitness is the LOO accuracy of the adaptive rule minus a smoothness penalty on between neighbouring points.
-
Algorithm. EANK combines interpretable meta-features, a smooth monotone policy and an elitist GA with simulated binary crossover [7, 8], annealed Gaussian mutation and seeding with constant policies. A pre-computed LOO vote table makes a fitness evaluation cost , so a full evolution takes about a tenth of a second on the datasets considered (Sections 4 and 4.5).
-
Theory. We prove that the seeded GA dominates the best global on its training criterion, that the GA converges almost surely, and that the learned neighbourhood size is stable. Through a Sauer-Shelah argument we also obtain a uniform generalisation bound for the policy class whose complexity term depends on and , not on . The bound separates the policy approach from per-instance encodings (Section 5).
-
Evidence. We report a controlled synthetic study and a nested -fold benchmark on twelve public datasets against five -NN baselines, including a classical GA over and a two-stage local- method. We add ablations and corrected statistical tests (Section 6). We report negative and null results alongside positive ones.
2 Related work
Choosing a global . Classical recommendations range from to LOO or -fold cross-validation. The LOO error of -NN admits distribution-free performance bounds [11, 12], and Ghosh [15] studied the optimal choice of from a Bayesian viewpoint. Distance weighting [13] and optimally weighted schemes [27] soften the dependence on without removing it.
Locally adaptive neighbourhoods. Wettschereck and Dietterich [34] proposed locally adaptive nearest neighbour algorithms that store, for each training point, the values of that classify it correctly and reuse them for nearby queries. Hastie and Tibshirani [16] adapted the metric locally (DANN). Wang et al. [33] chose the neighbourhood size from a statistical confidence criterion. Zhang et al. [35] learned an optimal for every training sample by sparse reconstruction and then fitted a decision tree (kTree) to predict for test points. Mullick et al. [21] learned point-specific with a neural network, with a class-dependent weighting for imbalanced data. On the theory side, Balsubramani et al. [1] gave an adaptive rule with point-wise guarantees that grows the neighbourhood until a statistical bias test is passed, and Chaudhuri and Dasgupta [4], Kpotufe [19] showed that the optimal smoothing is governed by local quantities. These methods either learn targets point by point, which risks overfitting the LOO labels, or use a hand-designed stopping test. EANK sits between the two: a hand-designed, interpretable representation of the neighbourhood, and a learned map from that representation to , fitted directly on the end-to-end adaptive LOO accuracy.
Evolutionary optimisation of k-NN. GAs were combined with k-NN early on to learn feature weights [17], and later for joint feature selection and extraction [25]. More recent applied studies use GAs to tune and select features on medical data [24], or to optimise variables, metrics and weighting schemes in forest inventory [20]. To our knowledge, these approaches all treat as a single global gene. The genome of EANK instead encodes a decision rule for . For the theory we rely on the classical convergence analysis of elitist GAs [26] and on Vapnik–Chervonenkis theory [12, 28, 31].
3 Problem formulation
Let be an i.i.d. sample from a distribution on . For a query , let be the training points sorted by increasing Euclidean distance to . For training points, the query itself is excluded (LOO). Let denote their labels. For the k-NN prediction is
with ties broken towards the class of the closer neighbours (Section 4.3).
Definition 1 (Adaptive neighbourhood rule). A neighbourhood policy is a map . The associated rule is . Global k-NN is the special case .
The ideal policy minimises the risk . We learn by minimising a regularised empirical criterion
where uses and is the set of nearest training neighbours of . The penalty discourages abrupt changes of neighbourhood size between nearby points. Without it, the optimiser could fit idiosyncratic LOO outcomes. Equivalently, we maximise the fitness .
Two parameterisations of are possible. A direct encoding stores one per training point and needs a separate rule to extend it to new points, as in Wettschereck and Dietterich [34], Zhang et al. [35]. Its dimension grows with and, as discussed in Section 5, it has no sample-size-free capacity control. EANK uses a policy encoding with parameters, introduced next.
4 The EANK method
4.1 Neighbourhood meta-features
For every point (training points in LOO mode), we compute from its sorted neighbour list the following meta-features, with a local scale (default 10) and a wider scale (default 30). Here is the distance to the -th neighbour and is the number of neighbours of class among the first .
-
: , an inverse local density.
-
: , the normalised label entropy among neighbours.
-
: , the vote margin between the two leading classes.
-
: , whether the 1-NN agrees with the -NN majority.
-
: , which is very negative when an almost-duplicate neighbour exists.
-
: , an outlierness score relative to the neighbours' own scale.
-
: the label entropy among neighbours, a second, coarser scale.
The features are standardised with means and deviations computed on the training fold. They are cheap by-products of the neighbour search that -NN performs anyway. None of them uses the label of the query, so test-time meta-features are computed exactly like training-time ones.
4.2 Policy
Given and ,
where . The policy is monotone in a single linear score, which keeps it interpretable: the sign of says whether meta-feature calls for larger or smaller neighbourhoods. The constant policies recover every global . Parameters live in the box (, ).
4.3 Vote table and fitness evaluation
The cost of evaluating is dominated by computing the LOO predictions for arbitrary vectors . We pre-compute once the cumulative vote tensor . A secondary tie-breaking score favours closer neighbours. Since (the -th harmonic number), the combined score never lets override a full vote. The prediction and correctness tables
Algorithm 1: EANK: Evolutionary Adaptive Neighborhood
Input: training set , , scales , smoothness , GA settings
Output: policy parameters
1 Compute LOO neighbour lists of all up to rank ; 2 Build the vote tensor , the tie-break tensor , and the tables ; 3 Compute and standardise the meta-features ; 4 ; 5 Initialise the population with the constant policies for and a fixed grid of , the rest uniform in ; 6 for do 7 10 11 return best genome found; 12 Prediction for a query : find its neighbours, compute , set , return .
are stored in memory. Then costs . The global- LOO curve is the column mean , so the best global comes for free.
4.4 Genetic algorithm
Algorithm 1 summarises the method. We use a population of real-coded genomes, binary tournament selection of size 3, simulated binary crossover (SBX) [7, 8] with probability 0.9 and index , and Gaussian mutation. Each gene mutates with probability (), with at least one gene per offspring, and the step size is relative to the box width (, ). Offspring are reflected into . Replacement is elitist (2 elites), and evolution stops after generations or 25 generations without improvement. The initial population is seeded with the constant policies encoding and . The remaining genomes are drawn uniformly in .
4.5 Computational complexity
Proposition 1 (Cost). With brute-force neighbour search in , EANK training costs time and memory. Prediction costs per query, the same order as k-NN with .
Proof. The neighbour search costs , plus to sort the retained neighbours. Building the cumulative sums and the argmax over classes costs ; only (size ) and (size ) are kept. A fitness evaluation computes scores in , looks up entries of , and sums absolute differences. The GA performs at most evaluations. Prediction needs one neighbour query, the cumulative votes and one inner product.
5 Theoretical analysis
All proofs are given in Section A.
5.1 Dominance over global k and stability
Proposition 2 (Seeded dominance). Assume and ; this holds for whenever . Then for every there is with , and the output of seeded EANK satisfies
The guarantee concerns the training criterion. Whether the improvement carries over to unseen data is the question of generalisation, treated below and measured in Section 6.4.
Proposition 3 (Lipschitz neighbourhoods). For all and , . In particular, on the change in is at most .
Points with similar neighbourhood descriptions therefore receive similar neighbourhood sizes. The penalty adds a data-dependent version of this property on the training graph.
5.2 Convergence of the genetic search
F takes finitely many values, because ranges over a finite set. However, a maximiser of F may sit on a set of Lebesgue measure zero, for example a single boundary point. The meaningful target for a stochastic search on a continuous genome is the essential supremum
Theorem 4 (Almost-sure convergence). Run the GA of Algorithm 1 without the stagnation stop . Let be the best fitness in the population at generation . Then is non-decreasing and there is , which depends only on , , , and , such that . Consequently for all large enough, almost surely.
Corollary 5. . Hence even an unseeded EANK reaches the best global-k LOO accuracy almost surely. Seeding achieves this at generation 0.
This is the elitist analogue, for a continuous genome, of the result of Rudolph [26]: canonical GAs without elitism do not converge to the optimum, while elitist ones do.
5.3 Capacity of the policy class and generalisation
Fix the training sample . Then and the map are fixed functions, and the adaptive rule is indexed by only.
Lemma 6 (Growth function). For any points , the number of distinct vectors realised as ranges over is at most
Theorem 7 (Uniform generalisation of adaptive policies). Let be an i.i.d. sample from , independent of , and let be the error of on . With probability at least over , simultaneously for all ,
Remark 1 (Policy versus per-instance encodings). The bound holds uniformly in . It therefore covers any selected by any procedure, including a GA run on itself, at a price of order that does not depend on the number of training points or on the number of fitness evaluations. A direct encoding has no such guarantee: up to assignments can be realised on the training points, so selecting among them on the same sample can overfit arbitrarily. This motivates the policy design of EANK.
Remark 2 (LOO fitness). EANK uses the LOO accuracy on rather than an independent , in order to use all the data. Theorem 7 then does not apply verbatim, because the meta-features and the candidates depend on the same sample. Theorem 6 still bounds the effective number of distinct candidates by a polynomial of degree , which limits the optimism of LOO selection. We quantify this optimism empirically in Section 6.4. A validation-based variant, to which Theorem 7 applies exactly, is a direct extension.
6 Experiments
6.1 Setup
Datasets. We use twelve public classification datasets (Table 1). Iris, Wine, Breast cancer and Digits come from scikit-learn [23]; the other eight come from the UCI repository [18]. Constant features are removed, and all features are standardised using training-fold statistics.
Methods. All methods share the same neighbour search, tie-breaking rule and , so differences come only from the choice of . (1) (): the common default. (2) : global by exhaustive LOO search, which is the exact optimum of the global- criterion and therefore an upper bound for grid, random, Bayesian or evolutionary search over . (3) : distance-weighted voting [13] with chosen by exhaustive LOO. (4) : a classical GA over the single integer (population 10, 20 generations), representative of [20, 24]. (5) LocalK: a two-stage local- method in the spirit of Wettschereck and Dietterich [34], Zhang et al. [35]. Each training point gets the LOO-correct closest to , and a query uses the median of the values of its 5 nearest training points. (6) EANK with , , , and the GA settings of Section 4. These defaults were fixed before the benchmark was run and were not tuned per dataset.
Protocol. We use repeated stratified 5-fold cross-validation, i.e. 25 train/test splits per dataset and 300 in total. All model selection (choice of , evolution of , standardisation) happens inside the training fold. The test fold is used only for scoring, so the procedure is nested with respect to every tuned quantity [3, 32]. We report accuracy, macro-F1, balanced accuracy and wall-clock times. Across datasets we use the Friedman test with the Nemenyi critical difference, and Wilcoxon signed-rank tests with Holm correction [9, 10]. Within a dataset we use the corrected resampled -test of Nadeau and Bengio [22], which accounts for the overlap between training sets.
6.2 Controlled study: spatially heterogeneous neighbourhoods
We first test the hypothesis that motivates EANK: an adaptive neighbourhood helps when the optimal amount of smoothing varies across the input space. The synthetic distribution has two regions of equal mass. The left region is a noiseless checkerboard on , a fine structure that calls for small . The right region is a linear boundary on whose labels are flipped with probability , a smooth structure with noisy labels that calls for large . We train on points and test on 4000 independent points, with 10 replications per noise level.
Figures 1 and 2 and table 2 confirm the hypothesis. Without label noise, both the global and the adaptive rules pick small neighbourhoods. As grows, the global optimum moves to
Table 1: Datasets: number of instances , features (after removing constant ones), classes , and imbalance ratio (largest / smallest class).
| Dataset | Imb. ratio | |||
|---|---|---|---|---|
| Iris | 150 | 4 | 3 | 1.0 |
| Wine | 178 | 13 | 3 | 1.5 |
| Breast cancer | 569 | 30 | 2 | 1.7 |
| Digits | 1797 | 61 | 10 | 1.1 |
| Sonar | 208 | 60 | 2 | 1.1 |
| Ionosphere | 351 | 33 | 2 | 1.8 |
| Pima | 768 | 8 | 2 | 1.9 |
| Glass | 214 | 9 | 6 | 8.4 |
| Seeds | 210 | 7 | 3 | 1.0 |
| Banknote | 1372 | 4 | 2 | 1.2 |
| Haberman | 306 | 3 | 2 | 2.8 |
| Ecoli | 336 | 7 | 8 | 71.5 |
(a) training sample,

Figure 1: Synthetic heterogeneous benchmark (). (a) Training sample: noiseless checkerboard on the left, linear boundary with 30% label noise on the right. (b) Neighbourhood size chosen by the learned EANK policy over the input space. The policy selects small neighbourhoods in the fine-grained checkerboard and large ones in the noisy smooth region. The best single global value found by exhaustive LOO search is a compromise between the two.
, a compromise that over-smooths the checkerboard. EANK instead keeps a small in the left region and, for , uses a neighbourhood three to nine times larger on the right. EANK is the most accurate method at every noise level. The gain over the best global ranges from 0.2 to 0.8 points and is significant at . The two-stage LocalK baseline does not improve on the global rule here: per-point LOO targets are too noisy to transfer.
Table 2: Synthetic benchmark: test accuracy (%), mean over 10 replications) as a function of the label-noise rate in the smooth region. : two-sided Wilcoxon signed-rank test, EANK vs. kNN-LOO. Last two columns: global selected by kNN-LOO, and median used by EANK in the left / right regions.
| kNN-LOO | LocalK | EANK | (global) | EANK (L / R) | ||
|---|---|---|---|---|---|---|
| 0.0 | 95.18 | 95.17 | 95.42 | 0.055 | 4.4 | 1.4 / 1.5 |
| 0.1 | 89.81 | 89.85 | 90.49 | 0.004 | 9.5 | 4.3 / 20.0 |
| 0.2 | 84.04 | 84.05 | 84.76 | 0.016 | 16.0 | 8.8 / 23.8 |
| 0.3 | 78.73 | 78.39 | 79.33 | 0.084 | 18.6 | 6.2 / 32.8 |
| 0.4 | 73.05 | 72.92 | 73.84 | 0.010 | 14.9 | 2.6 / 22.9 |


Figure 2: Synthetic benchmark. Left: test-accuracy gain over the best global (kNN-LOO) versus noise rate (mean s.d. over 10 paired replications). Right: median neighbourhood size in each region.
Table 3: Test accuracy (%), mean s.d. over 25 nested splits). Bold: best per row. An arrow on EANK would mark a significant difference with kNN-LOO (corrected resampled -test, ); none was observed. Mean rank: average Friedman rank over the 12 datasets (lower is better).
| Dataset | kNN () | kNN-LOO | wkNN-LOO | GA-k | LocalK | EANK |
|---|---|---|---|---|---|---|
| Iris | ||||||
| Wine | ||||||
| Breast cancer | ||||||
| Digits | ||||||
| Sonar | ||||||
| Ionosphere | ||||||
| Pima | ||||||
| Glass | ||||||
| Seeds | ||||||
| Banknote | ||||||
| Haberman | ||||||
| Ecoli | ||||||
| Mean acc. | 86.64 | 87.94 | 87.91 | 87.94 | 88.04 | 87.95 |
| Mean rank | 5.00 | 3.54 | 3.42 | 2.88 | 3.42 | 2.75 |
6.3 Benchmark results
Table 3 reports test accuracy. EANK obtains the best average rank (2.75), followed by GA-k (2.88), wkNN-LOO and LocalK (3.42), kNN-LOO (3.54) and the default (5.00). The Friedman test rejects equality of the six methods (). The Nemenyi critical difference is 2.18, so only the gap between EANK and (2.25) is significant. Table 4 gives the pairwise picture. EANK wins on 11 of 12 datasets against (Holm-adjusted ). Against the tuned baselines it wins on 6 to 8 datasets and loses on 4 to 5, and none of these
Table 4: Pairwise comparison of EANK with each baseline over the 12 datasets (mean accuracy): wins/ties/losses, Wilcoxon signed-rank p-value, Holm-adjusted p-value, and number of datasets on which EANK is significantly better/worse according to the corrected resampled t-test.
| Baseline | W/T/L | p | p_{Holm} | sig. better/worse |
|---|---|---|---|---|
| kNN (k=5) | 11/0/1 | 0.001 | 0.005 | 0/0 |
| kNN-LOO | 8/0/4 | 0.569 | 1.000 | 0/0 |
| wkNN-LOO | 6/1/5 | 0.820 | 1.000 | 0/0 |
| GA-k | 6/1/5 | 0.820 | 1.000 | 0/0 |
| LocalK | 7/0/5 | 0.850 | 1.000 | 0/0 |
Table 5: Other metrics, averaged over the 12 datasets (ranks: lower is better), and mean wall-clock time per training fold on one CPU core.
| kNN (k=5) | kNN-LOO | wkNN-LOO | GA-k | LocalK | EANK | |
|---|---|---|---|---|---|---|
| Macro-F1 (mean) | 82.94 | 84.25 | 84.44 | 84.24 | 84.45 | 84.14 |
| Macro-F1 (rank) | 4.92 | 3.71 | 2.88 | 3.08 | 3.50 | 2.92 |
| Balanced acc. (mean) | 83.05 | 84.30 | 84.38 | 84.28 | 84.47 | 84.08 |
| Balanced acc. (rank) | 5.00 | 3.67 | 2.92 | 2.96 | 3.38 | 3.08 |
| Fit time (ms) | 3.2 | 9.1 | 8.1 | 10.2 | 7.8 | 113.8 |
| Predict time (ms) | 1.4 | 2.6 | 2.8 | 2.6 | 2.8 | 3.6 |



Figure 3: GA convergence on four datasets: fitness gain over the best global k (LOO, points), mean and 10–90% band over 25 folds. The dashed line marks the seeded starting point (Theorem 2).
differences is significant, neither across datasets nor within any single dataset. The largest gains over kNN-LOO occur on Ionosphere (+0.92 points), Pima (+0.62), Seeds (+0.57) and Glass (+0.47). The largest losses occur on Haberman (-1.31), Iris (-0.53) and Wine (-0.46).
On macro-F1 and balanced accuracy (Table 5), EANK ranks second, just behind distance-weighted kNN-LOO. The fitness optimises plain accuracy, so this is consistent with the objective rather than evidence of an imbalance-specific benefit. Training takes about 0.11 s per fold, against 0.01 s for exhaustive global search. Prediction is only about 40% slower than k-NN, because the meta-features reuse the neighbour list of the query.
6.4 In-sample versus out-of-sample gains
Theorem 2 guarantees that EANK improves the LOO criterion over the best global k. On average the improvement is +1.52 points (up to +5.05 on Glass). The test-set improvement over kNN-LOO, however, averages only +0.01 points. The correlation between the two across datasets is 0.37: datasets where the policy finds more in-sample structure (Glass, Ionosphere, Sonar) tend to be those where EANK helps most, but most of the LOO gain is selection optimism. This is the empirical face of the LOO caveat after Theorem 7. Even a policy with eight parameters can fit chance fluctuations of the LOO correctness table on samples of a few hundred points. The smoothness penalty mitigates this optimism but does not remove it (Section 6.5).

Figure 4: Distribution of the neighbourhood sizes assigned by EANK to training points, pooled over folds. Dashed: median global chosen by kNN-LOO.
Table 6: Ablations over the 12 datasets: mean test accuracy (%), mean rank among the six variants, mean LOO fitness gain over the best global (points), mean within-fold standard deviation of test-time , mean number of fitness evaluations, and mean training time (ms).
| Variant | Acc. | Rank | LOO gain | s.d.(k) | #eval | Time |
|---|---|---|---|---|---|---|
| EANK | 87.95 | 2.25 | +1.52 | 5.24 | 2092 | 114 |
| EANK () | 87.64 | 4.46 | +1.84 | 12.56 | 1829 | 68 |
| EANK (random search) | 87.81 | 3.42 | +0.36 | 4.21 | 1297 | 59 |
| EANK (no seeding) | 87.68 | 3.79 | +1.53 | 7.18 | 2410 | 131 |
| EANK (density feats) | 87.71 | 3.88 | +1.14 | 4.44 | 2051 | 111 |
| EANK (label feats) | 87.91 | 3.21 | +0.98 | 3.02 | 1901 | 101 |
6.5 Ablation study
Table 6 isolates each design choice.
-
Smoothness (). Removing increases the LOO gain (+1.84 vs. +1.52) and more than doubles the variability of (12.6 vs. 5.2), while lowering test accuracy and giving the worst rank. This is the overfitting mechanism of Section 6.4, and the regulariser counters it.
-
Search (random search with the same budget). Random search finds only a quarter of the GA's LOO improvement (+0.36). It nevertheless reaches a similar test accuracy: the GA's extra in-sample progress is partly optimism.
-
Seeding. Without constant-policy seeds the GA still exceeds the global optimum in-sample (Theorem 5), but it converges more slowly and generalises slightly worse.
-
Meta-features. Label-based features (entropy, margin, agreement) carry most of the useful signal. Density features alone are weaker, and the full set is best, although the differences between feature sets are small.
6.6 What do the learned policies say?
In 21% of the folds, the GA returns the seeded constant policy unchanged, i.e. it finds no adaptive policy better than the best global . This happens in 60% of the folds on Banknote, where all methods exceed 99.8% accuracy, and never on Glass, Ionosphere or Sonar. EANK therefore falls back to the global rule when there is nothing to adapt to. Among non-constant policies, the coefficient of concentration is positive in 78% of the folds: points with an almost-duplicate nearest neighbour get small neighbourhoods. The coefficient of nn_agree is negative in 71%: when the 1-NN disagrees with the local majority, a larger vote is used. Both patterns match the

Figure 5: Mean policy weights per dataset (25 folds). Positive weights increase .
intuition behind adaptive . Other coefficients change sign across datasets (Figure 5), which reflects dataset-specific trade-offs.
7 Discussion and limitations
When does adaptive pay off? The synthetic study shows a clear and consistent benefit when the optimal smoothing genuinely varies across the input space. On the twelve standard benchmarks, which are small and mostly homogeneous, EANK is at least as good as tuned global on average and has the best mean rank. Its advantage is not statistically significant, however, and it loses on some datasets (Haberman, Iris, Wine). We regard this as an honest picture: much of the benefit reported for local- methods may depend on the evaluation protocol. Our protocol is fully nested, uses corrected tests, and gives the baselines the same tie-breaking rule and the exact global optimum.
Limitations. (i) The fitness is the LOO accuracy on the training set, which is optimistic (Section 6.4). Our generalisation guarantee is exact only for a held-out fitness. (ii) The policy is a monotone function of a linear score. Non-monotone dependencies, such as small at both very high and very low density, require a richer policy, for instance a small network, which increases in Theorem 7. (iii) The datasets are small to medium (); with brute-force search the neighbour computation dominates for large , and approximate search would be needed. (iv) We optimise accuracy; imbalance-aware or calibration-aware fitness functions are natural but untested here.
Future work. Promising directions are: held-out or cross-fitted fitness to close the in-sample/out-of-sample gap; multi-objective evolution that trades accuracy against smoothness and robustness, giving Pareto fronts of policies; class-aware meta-features for imbalanced data; and tracking distribution shift by re-evolving the policy online, warm-started from the previous population.
8 Conclusion
We argued that using a genetic algorithm to search for a single global cannot beat exhaustive search, and we proposed to evolve a neighbourhood policy instead. EANK learns an interpretable, low-dimensional map from local neighbourhood statistics to an instance-dependent . A pre-computed vote table makes each fitness evaluation cost . We showed that the method dominates the best global k on its training criterion, that the GA converges almost surely, and that its policy class admits a generalisation bound free of the sample size. Experiments show clear gains when the optimal neighbourhood is spatially heterogeneous, and performance on par with the best tuned baselines, with the best mean rank, on twelve standard datasets. They also identify the gap between in-sample and out-of-sample improvement as the main obstacle that future adaptive-neighbourhood methods must address.
Code and data availability. The Python implementation of EANK, the baselines and the scripts that reproduce every table and figure of this paper are available from the corresponding author upon request. All datasets used in this study are publicly available (Table 1).
References
[1] Akshay Balsubramani, Sanjoy Dasgupta, Yoav Freund, and Shay Moran. An adaptive nearest neighbor rule for classification. In Advances in Neural Information Processing Systems 32, 2019. doi: 10.48550/arXiv.1905.12717. URL https://cseweb.ucsd.edu/~dasgupta/papers/adaptive-nn.pdf.
[2] James Bergstra and Yoshua Bengio. Random search for hyper-parameter optimization. Journal of Machine Learning Research, 13:281–305, 2012. URL https://jmlr.org/papers/v13/bergstra12a.html.
[3] Gavin C. Cawley and Nicola L. C. Talbot. On over-fitting in model selection and subsequent selection bias in performance evaluation. Journal of Machine Learning Research, 11:2079–2107, 2010. URL https://www.jmlr.org/papers/v11/cawley10a.html.
[4] Kamalika Chaudhuri and Sanjoy Dasgupta. Rates of convergence for nearest neighbor classification. In Advances in Neural Information Processing Systems 27, 2014. doi:10.48550/arXiv.1407.0067. URL https://proceedings.neurips.cc/paper/2014/hash/2b764b803acec2d590f02b160f8a3700-Abstract.html.
[5] Thomas M. Cover and Peter E. Hart. Nearest neighbor pattern classification. IEEE Transactions on Information Theory, 13(1):21–27, 1967. doi: 10.1109/TIT.1967.1053964.
[6] Bryan A. Dawkins and Brett A. McKinney. Multivariate optimization of k for k-nearest-neighbor feature selection with dichotomous outcomes: Complex associations, class imbalance, and application to RNA-Seq in major depressive disorder. IEEE/ACM Transactions on Computational Biology and Bioinformatics, 22(1):39–51, 2025. doi: 10.1109/TCBBIO.2024.3494599.
[7] Kalyanmoy Deb and Ram Bhushan Agrawal. Simulated binary crossover for continuous search space. Complex Systems, 9(2):115–148, 1995. URL https://wpmedia.wolfram.com/uploads/sites/13/2018/02/09-2-2.pdf.
[8] Kalyanmoy Deb and Hans-Georg Beyer. Self-adaptive genetic algorithms with simulated binary crossover. Evolutionary Computation, 9(2):197–221, 2001. doi: 10.1162/106365601750190406.
[9] Janez Demšar. Statistical comparisons of classifiers over multiple data sets. Journal of Machine Learning Research, 7:1–30, 2006. URL https://www.jmlr.org/papers/v7/demsar06a.html.
[10] Joaquín Derrac, Salvador García, Daniel Molina, and Francisco Herrera. A practical tutorial on the use of nonparametric statistical tests as a methodology for comparing evolutionary and swarm intelligence algorithms. Swarm and Evolutionary Computation, 1(1):3–18, 2011. doi: 10.1016/j.swevo.2011.02.002.
[11] Luc Devroye and Terry J. Wagner. Distribution-free performance bounds for potential function rules. IEEE Transactions on Information Theory, 25(5):601–604, 1979. doi: 10.1109/TIT.1979.1056087.
[12] Luc Devroye, László Györfi, and Gábor Lugosi. A Probabilistic Theory of Pattern Recognition. Springer, New York, 1996. doi: 10.1007/978-1-4612-0711-5.
[13] Sahibsingh A. Dudani. The distance-weighted k-nearest-neighbor rule. IEEE Transactions on Systems, Man, and Cybernetics, SMC-6(4):325–327, 1976. doi: 10.1109/TSMC.1976.5408784.
[14] Evelyn Fix and Joseph L. Hodges. Discriminatory analysis. nonparametric discrimination: Consistency properties. Technical Report Project 21-49-004, Report 4, USAF School of Aviation Medicine, Randolph Field, Texas, 1951. URL https://apps.dtic.mil/sti/pdfs/ADA800276.pdf.
[15] Anil K. Ghosh. On optimum choice of k in nearest neighbor classification. Computational Statistics & Data Analysis, 50(11):3113–3123, 2006. doi: 10.1016/j.csda.2005.06.007.
[16] Trevor Hastie and Robert Tibshirani. Discriminant adaptive nearest neighbor classification. IEEE Transactions on Pattern Analysis and Machine Intelligence, 18(6):607–616, 1996. doi: 10.1109/34.506411.
[17] James D. Kelly, Jr. and Lawrence Davis. A hybrid genetic algorithm for classification. In Proceedings of the 12th International Joint Conference on Artificial Intelligence (IJCAI), pages 645–649, 1991. URL https://ijcai.org/proceedings/1991/94.
[18] Markelle Kelly, Rachel Longjohn, and Kolby Nottingham. The UCI machine learning repository, 2023. URL https://archive.ics.uci.edu.
[19] Samory Kpotufe. k-NN regression adapts to local intrinsic dimension. In Advances in Neural Information Processing Systems 24, pages 729–737, 2011. doi: 10.48550/arXiv.1110.4300. URL https://papers.nips.cc/paper/2011/file/05f971b5ec196b8c65b75d2ef8267331-Paper.pdf.
[20] Ronald E. McRoberts, Grant M. Domke, Qi Chen, Erik Næsset, and Terje Gobakken. Using genetic algorithms to optimize k-nearest neighbors configurations for use with airborne laser scanning data. Remote Sensing of Environment, 184:387–395, 2016. doi: 10.1016/j.rse.2016.07.007.
[21] Sankha Subhra Mullick, Shounak Datta, and Swagatam Das. Adaptive learning-based k-nearest neighbor classifiers with resilience to class imbalance. IEEE Transactions on Neural Networks and Learning Systems, 29(11):5713–5725, 2018. doi: 10.1109/TNNLS.2018.2812279.
[22] Claude Nadeau and Yoshua Bengio. Inference for the generalization error. Machine Learning, 52(3):239–281, 2003. doi: 10.1023/A:1024068626366.
[23] Fabian Pedregosa, Gaël Varoquaux, Alexandre Gramfort, Vincent Michel, Bertrand Thirion, Olivier Grisel, Mathieu Blondel, Peter Prettenhofer, Ron Weiss, Vincent Dubourg, Jake Vanderplas, Alexandre Passos, David Cournapeau, Matthieu Brucher, Matthieu Perrot, and Édouard Duchesnay. Scikit-learn: Machine learning in Python. Journal of Machine Learning Research, 12:2825–2830, 2011. doi: 10.48550/arXiv.1201.0490. URL https://www.jmlr.org/papers/v12/pedregosa11a.html.
[24] Rizki Tri Prasetio. Genetic algorithm to optimize k-nearest neighbor parameter for benchmarked medical datasets classification. JOIN (Jurnal Online Informatika), 5(2):153–160, 2020. doi: 10.15575/join.v5i2.656.
[25] Michael L. Raymer, William F. Punch, Erik D. Goodman, Leslie A. Kuhn, and Anil K. Jain. Dimensionality reduction using genetic algorithms. IEEE Transactions on Evolutionary Computation, 4(2):164–171, 2000. doi: 10.1109/4235.850656.
[26] Günter Rudolph. Convergence analysis of canonical genetic algorithms. IEEE Transactions on Neural Networks, 5(1):96–101, 1994. doi: 10.1109/72.265964.
[27] Richard J. Samworth. Optimal weighted nearest neighbour classifiers. The Annals of Statistics, 40(5):2733–2763, 2012. doi: 10.1214/12-AOS1049.
[28] Norbert Sauer. On the density of families of sets. Journal of Combinatorial Theory, Series A, 13(1):145–147, 1972. doi: 10.1016/0097-3165(72)90019-2.
[29] Bernard W. Silverman and M. Chris Jones. E. Fix and J. L. Hodges (1951): An important contribution to nonparametric discriminant analysis and density estimation (with a reprint of the original report). International Statistical Review, 57(3):233–247, 1989. doi: 10.2307/1403796.
[30] Charles J. Stone. Consistent nonparametric regression. The Annals of Statistics, 5(4): 595–620, 1977. doi: 10.1214/aos/1176343886.
[31] Vladimir N. Vapnik and Alexey Ya. Chervonenkis. On the uniform convergence of relative frequencies of events to their probabilities. Theory of Probability and Its Applications, 16(2): 264–280, 1971. doi: 10.1137/1116025.
[32] Sudhir Varma and Richard Simon. Bias in error estimation when using cross-validation for model selection. BMC Bioinformatics, 7:91, 2006. doi: 10.1186/1471-2105-7-91.
[33] Jigang Wang, Predrag Neskovic, and Leon N. Cooper. Neighborhood size selection in the k-nearest-neighbor rule using statistical confidence. Pattern Recognition, 39(3):417–423, 2006. doi: 10.1016/j.patcog.2005.08.009.
[34] Dietrich Wettschereck and Thomas G. Dietterich. Locally adaptive nearest neighbor algorithms. In Advances in Neural Information Processing Systems 6 (NIPS 1993), pages 184–191, 1994. URL https://papers.nips.cc/paper/1993/hash/2b3bf3eee2475e03885a110e9acaab61-Abstract.html.
[35] Shichao Zhang, Xuelong Li, Ming Zong, Xiaofeng Zhu, and Ruili Wang. Efficient kNN classification with different numbers of nearest neighbors. IEEE Transactions on Neural Networks and Learning Systems, 29(5):1774–1785, 2018. doi: 10.1109/TNNLS.2017.2673241.
A Proofs
Proof of Theorem 2. For , take and . Then exactly and , with for . For take : since , the rounding gives 0 and . For take : since , the rounding gives . Constant policies have , so . The initial population contains , and elitist replacement never removes the current best genome, so the best fitness never decreases. For , , and both conditions hold when .
Proof of Theorem 3. The logistic function is -Lipschitz. Hence , and Cauchy-Schwarz bounds the inner product by . Finally, for all reals . On , .
Proof of Theorem 4. Monotonicity. The two best parents enter the merged pool that is truncated to the P best, so the best fitness never decreases.
Hitting probability. Let , so by definition. Consider one offspring, whatever its parents and crossover result . With probability at least all genes are mutated: one gene is forced, and each of the other is mutated independently with probability . Conditional on this event, , where , holds the box widths, and is the coordinate-wise reflection into . Reflection maps each point back from at least the pre-image itself, so the density of at is at least the Gaussian density of at . Since ,
using . Therefore every offspring falls in with probability at least , independently of the past given the parents. Without hitting the best fitness stays below , and once is hit elitism keeps the best fitness at or above . Hence .
Almost-sure statement. Since , the Borel–Cantelli lemma shows that eventually, almost surely. (The best fitness may exceed if the search lands on a Lebesgue-null set of higher fitness, for example through seeds with and partial mutations that keep some genes unchanged; the theorem does not exclude this.)
Proof of Theorem 5. Let with an integer (the cases are treated as in Theorem 2, with in the interior of the half-line where the rounding is constant). The training meta-features are bounded, say . By continuity there is an open neighbourhood of on which for all . On , , , and . Since , the definition of gives the claim, and Theorem 4 applies to the unseeded GA.
Proof of Theorem 6. Let for . By (3), . The vector is therefore determined by the bits . These bits are the values of the homogeneous half-space indicator with normal at the points . Homogeneous half-spaces in have VC dimension , so by the Sauer-Shelah lemma [28] they realise at most bit patterns on these points. The last inequality is the standard bound for .
Proof of Theorem 7. Conditionally on , consider the error indicators , . On any points, the vector of these indicators is a function of , so the class realises at most patterns (Theorem 6). The Vapnik–Chervonenkis inequality [31], in the form of Devroye et al. [12, Thm. 12.5], gives
Setting the right-hand side to and using Theorem 6 yields the bound. The bound holds conditionally on every , hence also unconditionally.
Table 7: Default hyper-parameters of EANK (identical for all datasets).
| Symbol | Value | Symbol | Value |
|---|---|---|---|
| (max. neighbours) | 50 | (population) | 40 |
| (feature scales) | 10, 30 | (generations) | 60 (patience 25) |
| (smoothness) | 0.05, 5 | tournament size | 3 |
| (box) | 4, 6 | SBX | 0.9, 15 |
| elites | 2 | mutation | (annealed) |
B Hyper-parameters and implementation details
For every training fold, is capped at , and and at . The implementation uses NumPy and scikit-learn [23]. Neighbour lists are computed with NearestNeighbors, and the query point is removed explicitly from its own list, which handles duplicated points. The random seed of each split is . The code rounds with numpy.int (half to even), which differs from only on a Lebesgue-null set of parameters; the counting argument of Theorem 6 holds for either convention. The GA needs on average 2092 fitness evaluations (52 generations) per fold.