# 最近邻算法

最近邻算法通过在一个选定的距离度量下找到与查询最接近的已存储数据点，并基于这些点构造结果来回答查询：分类中通过多数投票给出类别标签，回归中给出近邻响应的平均值。<sup>[1](https://doi.org/10.1109/tit.1967.1053964)</sup><sup> • </sup><sup>[2](https://scikit-learn.org/stable/modules/neighbors.html)</sup><sup> • </sup><sup>[3](https://www.stat.cmu.edu/~cshalizi/dm/20/lectures/03/lecture-03.html)</sup> 该算法族基于实例且是惰性的：拟合只存储数据，几乎所有计算都在查询到来时发生。<sup>[4](https://www.ibm.com/think/topics/knn)</sup> 它带有很强的保证：随着数据增长，其误差保持在可达最佳误差的两倍以内。<sup>[1](https://doi.org/10.1109/tit.1967.1053964)</sup>

| 关键事实 | 值 |
|---|---|
| 分类输出 | k个最近训练点中的多数标签<sup>[2](https://scikit-learn.org/stable/modules/neighbors.html)</sup> |
| 回归输出 | k个最近邻上的响应平均值<sup>[3](https://www.stat.cmu.edu/~cshalizi/dm/20/lectures/03/lecture-03.html)</sup> |
| 1-NN误差界 | 当n → ∞时，至多为贝叶斯误差的两倍<sup>[1](https://doi.org/10.1109/tit.1967.1053964)</sup> |
| 一致性 | 若k → ∞且k/n → 0，则k-NN误差收敛到贝叶斯误差<sup>[5](https://cseweb.ucsd.edu/~elkan/151/nearestn.pdf)</sup> |
| 暴力查询成本 | 每次查询\( O(nd) \)时间；总体\( O(np) \)内存<sup>[5](https://cseweb.ucsd.edu/~elkan/151/nearestn.pdf)</sup><sup> • </sup><sup>[6](https://www.stat.cmu.edu/~cshalizi/dm/22/lectures/11/lecture-11.pdf)</sup> |
| 高维失效 | 距离集中现象在低至10–15维时就会出现<sup>[7](https://home.cse.ust.hk/~raywong/comp5331/References/WhenIsNearestNeighborMeaningful.pdf)</sup> |
| 现代搜索默认 | 基于图的近似搜索因精度与效率的权衡而被广泛使用<sup>[8](https://arxiv.org/abs/2101.12631)</sup> |

## 工作原理

1-NN规则给查询赋予单个最近存储点的标签；k-NN取k个最近点中的多数标签，而k-NN回归对它们的响应值取平均。<sup>[2](https://scikit-learn.org/stable/modules/neighbors.html)</sup><sup> • </sup><sup>[3](https://www.stat.cmu.edu/~cshalizi/dm/20/lectures/03/lecture-03.html)</sup> 使用欧几里得度量时，p个特征中样本\( x_i \)与\( x_l \)之间的距离为\( d(x_i, x_l) = \sqrt{\sum_{j=1}^{p}(x_{ij} - x_{lj})^2} \)。<sup>[9](http://www.scholarpedia.org/article/K-nearest_neighbor)</sup> 闵可夫斯基族将其推广：\( p = 1 \)给出[曼哈顿距离](https://www.edgepedia.org/zh/manhattan-distance)，\( p = 2 \)给出[欧几里得距离](https://www.edgepedia.org/zh/euclidean-distance)，<sup>[10](https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html)</sup> 汉明距离覆盖布尔或字符串向量，<sup>[4](https://www.ibm.com/think/topics/knn)</sup> 马哈拉诺比斯距离考虑特征协方差，尽管要高效地实现它要困难得多。<sup>[11](https://sebastianraschka.com/pdf/lecture-notes/stat479fs19/02-knn__notes.pdf)</sup> 对于实值向量，在高维中\( p < 2 \)的p范数可能有益。<sup>[5](https://cseweb.ucsd.edu/~elkan/151/nearestn.pdf)</sup> 度量也可以学习：大间隔最近邻为k-NN分类学习一个伪度量，这与现在所称的三元组损失有关，<sup>[12](https://doi.org/10.5555/1577069.1577078)</sup><sup> • </sup><sup>[13](https://www.cs.cornell.edu/courses/cs3780/2026sp/lectures/lecturenote02_kNN.html)</sup> 而邻域成分分析最大化一个随机的留一法k-NN得分。<sup>[2](https://scikit-learn.org/stable/modules/neighbors.html)</sup> 距离加权变体给近邻分配与其距离倒数成比例的权重；较大的k抑制噪声，但使分类边界不那么清晰。<sup>[2](https://scikit-learn.org/stable/modules/neighbors.html)</sup>

理论锚点是科夫–哈特界（Cover–Hart bound）：在M类情形下，最近邻误差R满足\( R^* \le R \le R^*(2 - M \cdot R^*/(M-1)) \)，其中\( R^* \)是贝叶斯误差，而对于适当光滑的底层分布，这些界是可能的最紧界。<sup>[1](https://doi.org/10.1109/tit.1967.1053964)</sup> 任何其他基于无限数据集的决策规则相对于1-NN最多只能把误差削减一半。<sup>[1](https://doi.org/10.1109/tit.1967.1053964)</sup> 若k → ∞且k/n → 0，则当n → ∞时k-NN误差收敛到贝叶斯误差。<sup>[5](https://cseweb.ucsd.edu/~elkan/151/nearestn.pdf)</sup> [查尔斯·斯通](https://www.edgepedia.org/zh/charles-j-stone)（Charles Stone）在1977年完全一般地证明了这一结果，取消了对奇异分布的排除。<sup>[14](https://doi.org/10.1214/aos/1176343886)</sup><sup> • </sup><sup>[15](https://garfield.library.upenn.edu/classics1982/A1982NF37700001.pdf)</sup>

## 如何实施

实践者存储训练集，选择度量和k，计算查询到每个存储点的距离，选出k个最近点（或半径r内的所有点），然后投票、取平均或返回近邻。k通常选为奇数以避免平局，<sup>[9](http://www.scholarpedia.org/article/K-nearest_neighbor)</sup> 并通过v折交叉验证选择，即重复数据划分并对预测误差取平均。<sup>[6](https://www.stat.cmu.edu/~cshalizi/dm/22/lectures/11/lecture-11.pdf)</sup> 较小的k带来低偏差和高方差；较大的k带来高偏差和较低方差。<sup>[4](https://www.ibm.com/think/topics/knn)</sup>

朴素预测对每个测试样本花费\( O(nd) \)，而线性分类器（如感知机）为\( O(d) \)。<sup>[5](https://cseweb.ucsd.edu/~elkan/151/nearestn.pdf)</sup> 对N个D维样本，暴力计算所有对之间的距离规模为\( O[D \cdot N^{2}] \)，而基于树的结构将其降至\( O[D \cdot N \log N] \)或更好。<sup>[2](https://scikit-learn.org/stable/modules/neighbors.html)</sup> 对于小数据集（N约低于30），暴力法可能比树更高效。<sup>[2](https://scikit-learn.org/stable/modules/neighbors.html)</sup> 在低至10维时，线性扫描就可能胜过索引，因此高维评估应包含线性扫描比较作为合理性检查。<sup>[7](https://home.cse.ust.hk/~raywong/comp5331/References/WhenIsNearestNeighborMeaningful.pdf)</sup>

## 起源

科夫（Cover）和哈特（Hart）于1967年在《IEEE信息论汇刊》（IEEE Transactions on Information Theory）上发表了《最近邻模式分类》（Nearest Neighbor Pattern Classification）。<sup>[1](https://doi.org/10.1109/tit.1967.1053964)</sup> 更早的一个相关进展是洛夫茨加登（Loftsgaarden）和奎森伯里（Quesenberry）1965年的k最近邻密度估计，它早于科夫和哈特的分类论文。<sup>[16](https://doi.org/10.1214/aoms/1177700079)</sup><sup> • </sup><sup>[17](https://luc.devroye.org/Biau+Devroye-LecturesontheNearestNeighborMethod-2015.pdf)</sup> 作为一个搜索问题，最近邻最初被提出，<sup>[18](https://www.theoryofcomputing.org/articles/v008a014/v008a014.pdf)</sup> 并被称为邮局问题。<sup>[19](https://www.mdpi.com/1424-8220/23/2/629)</sup> 后续有若干改进：哈特1968年的压缩最近邻规则，<sup>[20](https://doi.org/10.1109/tit.1968.1054155)</sup> 盖茨（Gates）1972年的约简最近邻规则，<sup>[21](https://doi.org/10.1109/tit.1972.1054809)</sup> 以及福永（Fukunaga）和纳伦德拉（Narendra）1975年计算k最近邻的分支定界算法。<sup>[22](https://doi.org/10.1109/t-c.1975.224297)</sup>

## 变体

半径近邻用固定半径r内的所有点而不是固定数量进行分类，这适合非均匀采样的数据，但在高维中效果较差。<sup>[2](https://scikit-learn.org/stable/modules/neighbors.html)</sup> k-NN密度估计与核估计对偶：它固定近邻数k并测量到第k个最近点的距离，而核估计固定带宽。<sup>[17](https://luc.devroye.org/Biau+Devroye-LecturesontheNearestNeighborMethod-2015.pdf)</sup> 压缩和编辑会缩减存储集：哈特的压缩最近邻规则保留一个与完整数据集一致的子集，<sup>[20](https://doi.org/10.1109/tit.1968.1054155)</sup> 而盖茨的约简规则迭代这一思想。<sup>[21](https://doi.org/10.1109/tit.1972.1054809)</sup>

就搜索本身而言，经典的k-d树在低维（\( D < 20 \)）下很快，但随着D增大而变得低效；球树嵌套超球面，在高维中可胜过k-d树，查询时间约为\( O[D \log N] \)。<sup>[2](https://scikit-learn.org/stable/modules/neighbors.html)</sup> [近似最近邻搜索](https://www.edgepedia.org/zh/approximate-nearest-neighbor-search)（ANNS）算法分为四大类：基于哈希、基于树、基于量化和基于图。<sup>[8](https://arxiv.org/abs/2101.12631)</sup> [局部敏感哈希](https://www.edgepedia.org/zh/locality-sensitive-hashing)由因迪克（Indyk）和莫特瓦尼（Motwani）于1998年提出，它对点进行哈希，使相近对象碰撞的概率远高于相距较远的对象；在c近似问题中，算法可以报告到查询点的距离不超过真实最近点到查询点距离的c倍的任意点。<sup>[18](https://www.theoryofcomputing.org/articles/v008a014/v008a014.pdf)</sup> HNSW构建一个每个顶点近邻数有界的分层图，允许对数级搜索扩展，代价是更高的内存使用；Vamana增加一个参数α，控制哪些候选加入近邻集。<sup>[8](https://arxiv.org/abs/2101.12631)</sup> [乘积量化](https://www.edgepedia.org/zh/product-quantization)由热古（Jégou）、杜兹（Douze）和施密德（Schmid）于2010年报告，它压缩向量以用于基于量化的搜索。<sup>[23](https://doi.org/10.1109/tpami.2010.57)</sup>

## 应用

在现代近似搜索格局中，基于图的算法因精度与效率的权衡而被广泛使用，并被微软（Microsoft）、阿里巴巴（Alibaba）和雅虎（Yahoo）采用。<sup>[8](https://arxiv.org/abs/2101.12631)</sup> 在工业规模（约1亿到10亿以上向量）下，基于图的DiskANN是当前默认选择：它使用SSD作为主存储、仅在RAM中保留压缩索引，对十亿规模数据集执行ANN搜索，并在同等召回率下每个节点索引的向量数为HNSW或FAISS IVF的5–10倍；而IVF式聚类索引主要在内存受限或经过过滤的较小规模工作负载中受到青睐。<sup>[24](https://eliasjaasaari.com/pdf/neurips2024.pdf)</sup>

## 局限与替代方案

在广泛条件下，随着维数增加，到最近数据点的距离趋近于到最远点的距离，经验结果表明这种集中现象在低至10–15维时就可能出现。<sup>[7](https://home.cse.ust.hk/~raywong/comp5331/References/WhenIsNearestNeighborMeaningful.pdf)</sup> 样本需求呈指数增长：对于均匀采样数据，包含k个近邻的区域的边长约为\( \ell \approx (k/n)^{1/d} \)，而要求\( \ell = 0.1 \)需要\( n = k \cdot 10^{d} \)个样本。<sup>[13](https://www.cs.cornell.edu/courses/cs3780/2026sp/lectures/lecturenote02_kNN.html)</sup> 对于大约\( d \ge 20 \)的维数，尚不知道有任何数据结构在实践中可用于精确搜索，<sup>[5](https://cseweb.ucsd.edu/~elkan/151/nearestn.pdf)</sup> 而寻找真正最近邻通常无法比线性扫描高效得多，或者需要使用随d呈指数增长的空间。<sup>[25](https://www.sciencedirect.com/science/article/pii/S0306437921000569)</sup> 这些极限情形结果通常不会出现在真实世界数据集中，后者往往位于低维子空间或流形上，k-NN在这些地方仍然有效。<sup>[25](https://www.sciencedirect.com/science/article/pii/S0306437921000569)</sup><sup> • </sup><sup>[13](https://www.cs.cornell.edu/courses/cs3780/2026sp/lectures/lecturenote02_kNN.html)</sup> 该方法还对无关特征敏感，超过最优数量的额外特征可能增加分类误差。<sup>[4](https://www.ibm.com/think/topics/knn)</sup> 与替代方案相比，最明显的差异是成本：线性分类器在\( O(d) \)时间内回答查询，而k-NN为\( O(nd) \)。<sup>[5](https://cseweb.ucsd.edu/~elkan/151/nearestn.pdf)</sup>

## References

1. [T. Cover, P. Hart (1967). Nearest neighbor pattern classification. IEEE Transactions on Information Theory.](https://doi.org/10.1109/tit.1967.1053964)
2. [1.6. Nearest Neighbors, scikit-learn documentation](https://scikit-learn.org/stable/modules/neighbors.html)
3. [k-Nearest Neighbors (CMU 36-290 lecture notes, Cosma Shalizi)](https://www.stat.cmu.edu/~cshalizi/dm/20/lectures/03/lecture-03.html)
4. [What is the k-nearest neighbors algorithm? | IBM](https://www.ibm.com/think/topics/knn)
5. [Nearest neighbor methods course notes (Charles Elkan, UCSD)](https://cseweb.ucsd.edu/~elkan/151/nearestn.pdf)
6. [k-Nearest Neighbors (CMU lecture notes, 2022 version)](https://www.stat.cmu.edu/~cshalizi/dm/22/lectures/11/lecture-11.pdf)
7. [When Is 'Nearest Neighbor' Meaningful? (Beyer, Goldstein, Ramakrishnan, Shaft, ICDT 1999)](https://home.cse.ust.hk/~raywong/comp5331/References/WhenIsNearestNeighborMeaningful.pdf)
8. [A Comprehensive Survey and Experimental Comparison of Graph-Based Approximate Nearest Neighbor Search](https://arxiv.org/abs/2101.12631)
9. [K-nearest neighbor, Scholarpedia](http://www.scholarpedia.org/article/K-nearest_neighbor)
10. [KNeighborsClassifier, scikit-learn API documentation](https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html)
11. [STAT 479: Machine Learning, Nearest Neighbor Methods (Sebastian Raschka)](https://sebastianraschka.com/pdf/lecture-notes/stat479fs19/02-knn__notes.pdf)
12. [Kilian Q. Weinberger, Lawrence K. Saul (2009). Distance Metric Learning for Large Margin Nearest Neighbor Classification. Journal of Machine Learning Research.](https://doi.org/10.5555/1577069.1577078)
13. [k-nearest neighbors / Curse of Dimensionality (Cornell CS3780, 2026sp)](https://www.cs.cornell.edu/courses/cs3780/2026sp/lectures/lecturenote02_kNN.html)
14. [Charles J. Stone (1977). Consistent Nonparametric Regression. The Annals of Statistics.](https://doi.org/10.1214/aos/1176343886)
15. [Citation Classic commentary by Thomas M. Cover (1982) on Cover & Hart 1967](https://garfield.library.upenn.edu/classics1982/A1982NF37700001.pdf)
16. [D. O. Loftsgaarden, C. P. Quesenberry (1965). A Nonparametric Estimate of a Multivariate Density Function. The Annals of Mathematical Statistics.](https://doi.org/10.1214/aoms/1177700079)
17. [Lectures on the Nearest Neighbor Method (Biau & Devroye, Springer, 2015)](https://luc.devroye.org/Biau+Devroye-LecturesontheNearestNeighborMethod-2015.pdf)
18. [Approximate Nearest Neighbor: Towards Removing the Curse of Dimensionality (Andoni & Indyk, Theory of Computing)](https://www.theoryofcomputing.org/articles/v008a014/v008a014.pdf)
19. [Survey on Exact kNN Queries over High-Dimensional Data Space (Sensors, MDPI)](https://www.mdpi.com/1424-8220/23/2/629)
20. [P. Hart (1968). The condensed nearest neighbor rule (Corresp.). IEEE Transactions on Information Theory.](https://doi.org/10.1109/tit.1968.1054155)
21. [G. Gates (1972). The reduced nearest neighbor rule (Corresp.). IEEE Transactions on Information Theory.](https://doi.org/10.1109/tit.1972.1054809)
22. [K. Fukunaga, P.M. Narendra (1975). A Branch and Bound Algorithm for Computing k-Nearest Neighbors. IEEE Transactions on Computers.](https://doi.org/10.1109/t-c.1975.224297)
23. [H Jégou, M Douze, C Schmid (2010). Product Quantization for Nearest Neighbor Search. IEEE Transactions on Pattern Analysis and Machine Intelligence.](https://doi.org/10.1109/tpami.2010.57)
24. [LoRANN: Low-Rank Matrix Factorization for Approximate Nearest Neighbor Search (NeurIPS 2024, author PDF)](https://eliasjaasaari.com/pdf/neurips2024.pdf)
25. [The role of local dimensionality measures in benchmarking nearest neighbor search (Information Systems)](https://www.sciencedirect.com/science/article/pii/S0306437921000569)

---
*Initially written Sep 29, 2026 · Edited: Oct 15, 2026; Oct 21, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 人工智能与数据 › Machine learning and neural computation › Machine learning methods › Supervised, unsupervised, and semi-supervised learning › Classification algorithms

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/nearest-neighbor-algorithm

English original: https://www.edgepedia.org/nearest-neighbor-algorithm
