137. 运行一次 k-means 迭代
k-means 交替执行两个步骤:将每个点分配给其最近的质心,然后将每个质心移动到其所属点的均值位置。
编写 kmeans_step(X, centroids) 函数,执行一次完整的迭代并返回 (labels, new_centroids)。labels 是一个 int 列表。如果出现距离相等的情况,分配给索引较小的质心。如果某个质心没有分配到任何点,则保持其原位。
def kmeans_step(X, centroids)示例 1
输入: kmeans_step([[0.0], [1.0], [9.0], [10.0]], [[0.0], [5.0]])
输出: ([0, 0, 1, 1], [[0.5], [9.5]])
示例 2
输入: kmeans_step(np.array([[0.0, 0.0], [0.0, 1.0], [10.0, 10.0], [10.0, 11.0], [11.0, 10.0]]), [[0, 0], [10, 10]])[0]
输出: [0, 0, 1, 1, 1]
示例 3
输入: kmeans_step(np.array([[0.0, 0.0], [0.0, 1.0], [10.0, 10.0], [10.0, 11.0], [11.0, 10.0]]), [[0, 0], [10, 10]])[1]
输出: [[0.0, 0.5], [10.333333, 10.333333]]
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
One iteration is two separate steps: assign every point to its closest centroid, then recompute each centroid as the mean of its assigned points.
提示 2
Compute squared distances between every point and every centroid with broadcasting, take np.argmin over centroids for labels, then loop over centroids and average the points with that label.
提示 3
Distances come from X[:, None, :] - C[None, :, :] summed over the last axis, argmin already picks the lowest index on ties, and start from C.copy() so empty clusters keep their old position.
常见错误
- 有 Bug 的版本会将其移动到原点。
理解思路
k-means 通过重复两个步骤将点围绕中心进行分组。首先,每个点加入其最近的质心。其次,每个质心移动到加入它的点的平均值位置。可以将其想象为商店移动到其常客的中心位置。对于选择最近质心而言,平方距离就足够了,因为平方根不会改变顺序。Worked example, 1D: X = [0, 1, 9, 10], centroids [0, 5]。点 0 离质心 0 最近。点 1 距离质心 0 为 1,距离质心 1 为 4,因此分配给质心 0。点 9 和 10 分配给质心 1。新质心:mean(0, 1) = 0.5 和 mean(9, 10) = 9.5。Labels [0, 0, 1, 1]。恰好处于中点的点分配给索引较小的质心。如果一个质心没有分配到任何点,它就没有均值,因此应保持原位,而不是将其移动到零。
通过平方距离的 argmin 进行分配,然后 centroid = 其成员的 mean。k-means 被用于对 embedding 进行聚类并构建向量索引分区。
公司7
- Amazon a candidate reported this question Amazon AI Research Scientist interview experience (February 2025)
- Anthropic the topic appears in interview reports Coding Exercises & ML System Design: Real AI Interview Questions (landedjobs)
- ByteDance a candidate reported this question ByteDance Machine Learning Engineer Interview Process
- Google the topic appears in interview reports Google Interview Prep (Deep-ML)
- Meta a candidate reported this question Meta Research Engineer Interview Guide (Dataford)
- Microsoft a candidate reported this question Microsoft Senior Applied Scientist (L63) Interview Experience
- OpenAI a candidate reported this question OpenAI interview questions, page 54 (Screna)
来自公开面试报告和指南。与这些公司无隶属关系或背书关系。