Frame · dsa / ai-algorithms / 08-k-means-embedding-clustering.jsJavaScript
K-Means Clustering of Embeddings
Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.
Same file as in the repo · ~20s timeout
From file header (JSDoc)
K-Means Clustering of Embeddings
Problem: Cluster embedding vectors into k groups (for topic discovery,
deduplication or building an IVF index). Implement Lloyd's algorithm:
1. Initialise centroids deterministically with the first k points.
2. Assign every point to its nearest centroid (squared Euclidean distance,
ties go to the lower centroid index).
3. Move each centroid to the mean of its points (an empty cluster keeps its
previous centroid).
Repeat until no assignment changes or `maxIter` is reached. Return
`{ centroids, labels, iterations, inertia }` where inertia is the sum of
squared distances of points to their centroid.
Constraints:
- 1 <= k <= points.length <= 10^5, dimension d <= 4096
Example:
points = [[0,0],[10,10],[0,1],[10,11]], k = 2
-> labels [0, 1, 0, 1], centroids [[0, 0.5], [10, 10.5]]
Approach: Alternate assignment and update steps; each step is O(n * k * d).
The objective never increases, so it converges. Total O(iter * n * k * d)
time, O(k * d + n) extra space. Production code uses k-means++ seeding.
@param {number[][]} points
@param {number} k
@param {number} [maxIter]
@returns {{ centroids: number[][], labels: number[], iterations: number, inertia: number }}