BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Supervised models1 of 18 in topic

119. 通过最近邻的多数投票进行点分类

EasySupervised models
提问于MetaNetflixOpenAI

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 可以实现这一点);当投票平局时,最小的标签胜出。

Worked example

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 被广泛用于推荐系统并作为基准模型。
主题
Supervised models
公司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)

来自公开面试报告和指南。与这些公司无隶属关系或背书关系。

相似题目
  • 运行一个 epoch 的感知器学习规则Easy
  • 按最近类质心分类Easy
  • 计算单次分裂的信息增益Easy
  • 使用距离加权 k 最近邻投票进行分类Easy
所有 Supervised models 道题目
反馈
119 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def knn_predict(X_train, y_train, X_test, k):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 3 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS