119. 通过最近邻的多数投票进行点分类
k-nearest neighbours 没有训练步骤。要为新点标记标签,请找到 k 个最近的训练点并取出现次数最多的标签。
编写 knn_predict(X_train, y_train, X_test, k)。使用 Euclidean distance。如果距离相等,则较小的训练索引胜出(使用 stable sort)。如果投票平局,则最小的标签胜出。返回一个 int 列表。
def knn_predict(X_train, y_train, X_test, k)示例 1
输入: X_train = [[0, 0], [0, 1], [1, 0], [5, 5], [5, 6], [6, 5]], y_train = [0, 0, 0, 1, 1, 1], X_test = [[0.2, 0.3], [5.5, 5.2]], k = 3
输出: [0, 1]
示例 2
输入: X_train = [[0, 0], [0, 1], [1, 0], [5, 5], [5, 6], [6, 5]], y_train = [0, 0, 0, 1, 1, 1], X_test = [[4, 4]], k = 1
输出: [1]
示例 3
输入: X_train = [[0], [2]], y_train = [1, 0], X_test = [[1]], k = 2
输出: [0]
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
There is nothing to train: for each test point you just rank all training points by distance and let the k closest ones vote.
提示 2
For each test point, compute Euclidean distances to every training row, take the k smallest with a stable argsort, count how often each label appears, and choose the label with the most votes.
提示 3
Use np.argsort(d, kind='stable')[:k] so equal distances keep the lower training index. For the vote, find the max count, then take min over the labels that have that count.
常见错误
- 有 bug 的版本按负距离排序,这会导致选出最远的点。
理解思路
k-nearest neighbours 没有训练过程。要为新点标记标签,你需要找到 k 个最近的训练点并进行投票,就像询问你的邻居哪家店最好一样。为了使结果可测试,我们设定了两个平局规则:当距离相等时,较小的训练索引优先(stable sort 可以实现这一点);当投票平局时,最小的标签胜出。
X_train = [[0], [1], [5]], y_train = [0, 0, 1], test point [4]。距离分别为 4, 3 和 1。当 k = 1 时,最近的是 index 2,标签为 1。当 k = 3 时,投票结果为 0, 0, 1,所以标签为 0。当 k = 2 时,最近的是 index 2 (label 1) 和 index 1 (label 0),投票为 1 比 1 平局,因此较小的标签 0 胜出。
按 Euclidean distance 升序排序,保留前 k 个,并使用最小标签作为平局处理规则。按负距离排序会选出最远的点,这是一个经典的 bug。kNN 被广泛用于推荐系统并作为基准模型。
公司3
- Meta a candidate reported this question Machine Learning interview questions, page 10 (KatKat)
- Netflix the topic appears in interview reports Netflix Machine Learning Engineer Interview Process
- OpenAI a candidate reported this question OpenAI Interview Process & Questions (2026) (TrueInterview)
来自公开面试报告和指南。与这些公司无隶属关系或背书关系。