K-Means
Run K-Means clustering in JavaScript and TypeScript with @kanaries/ml. Includes k-means++ restarts, sample weights, inertia, serialization, and live demo.
View as MarkdownAlgorithm overview
K-Means is an unsupervised partitioning algorithm that groups numeric observations into n_clusters compact clusters by minimizing within-cluster squared Euclidean distance (inertia). Each iteration alternates between assigning every sample to its nearest centroid and recomputing each centroid as the (optionally weighted) mean of its assigned points until the relative inertia improvement drops below tol or max_iter iterations complete.
K-Means is a strong first choice when:
- You can estimate or sweep a small range of cluster counts (
k = 2..10) using elbow curves or silhouette scores. - Clusters are roughly convex, spherical, and comparable in scale.
- You need fast, interpretable customer segmentation, product grouping, or vector quantization in production.
JavaScript implementation
@kanaries/ml provides Clusters.KMeans in pure TypeScript for browsers and Node.js. It supports the canonical options-object constructor (KMeansProps) with k-means++ initialization, n_init restarts (keeping the lowest-inertia run), deterministic random_state seeding, optional per-sample weights, and full JSON persistence via toJSON() / loadModel().
Unlike server-only Python pipelines, running Clusters.KMeans directly in the browser lets users adjust k, inspect centroids, and segment CSV uploads instantaneously without uploading private data. For very large embedding tables (10,000+ vectors), see Clusters.EMeans or run fitting inside a Web Worker.
Interactive K-Means playground
Choose a dataset and cluster count, then play or step through the assignment and centroid-update loop. Click the plot to add observations; the animation is checked against a real Clusters.KMeans fit in your browser.
Lloyd iterations: assignments and moving centroids
Inertia across iterations
Implementation check
The animation records transparent Lloyd assignment/update steps. A real @kanaries/ml KMeans model is also fit with the identical initial centers. Final centroid difference: 0.000e+0; library inertia: 22.727.
The moons preset demonstrates a limitation: centroid-based Voronoi regions cannot follow arbitrary curved clusters.
Fit K-Means in JavaScript or Python
import { Clusters } from '@kanaries/ml';
const model = new Clusters.KMeans(
3, // number of clusters
1e-4, // convergence tolerance
undefined,
100, // maximum iterations
42, // random seed
10 // k-means++ restarts
);
const labels = model.fitPredict(X);
console.log(model.getCentroids());
console.log(model.getInertia());Quick start
import { Clusters } from '@kanaries/ml';
const X = [
[0, 0],
[0.5, 0],
[0.5, 1],
[1, 1],
[8, 8],
[8.5, 8.2],
];
const kmeans = new Clusters.KMeans({
n_clusters: 2,
tol: 1e-4,
n_init: 10,
random_state: 42,
});
const labels = kmeans.fitPredict(X);
console.log({ labels, centroids: kmeans.getCentroids(), inertia: kmeans.getInertia() });K-Means Clustering (KMeans) in Python vs JavaScript / TypeScript
If you searched for "K-Means Clustering (KMeans) in JavaScript" or "K-Means Clustering (KMeans) in TypeScript", this section maps the familiar scikit-learn call to the equivalent @kanaries/ml usage for browser and Node.js runtimes.
from sklearn.cluster import KMeans
X = [[0, 0], [0.2, 0.1], [4, 4], [4.1, 4.2]]
model = KMeans(n_clusters=2, tol=1e-4, n_init=10, random_state=42)
labels = model.fit_predict(X)
centers = model.cluster_centers_
inertia = model.inertia_import { Clusters } from '@kanaries/ml';
const X = [[0, 0], [0.2, 0.1], [4, 4], [4.1, 4.2]];
const model = new Clusters.KMeans({
n_clusters: 2,
tol: 1e-4,
n_init: 10,
random_state: 42,
});
const labels = model.fitPredict(X);
const centers = model.getCentroids();
const inertia = model.getInertia();Detailed API reference
new Clusters.KMeans(props?)
(Legacy positional calls new Clusters.KMeans(n_clusters, tol, initCenters, max_iter, random_state, n_init) remain supported for backward compatibility, but prefer the options object.)
| Parameter | Type | Default | Description |
|---|---|---|---|
n_clusters | number | 2 | Number of clusters (k) to form. |
tol | number | 1e-4 | Relative tolerance on weighted inertia change to declare convergence. |
initCenters | number[][] | undefined | Optional explicit starting centroids ([n_clusters][nFeatures]). When supplied, n_init is forced to 1. |
max_iter | number | 30 | Maximum Lloyd iterations per restart. |
random_state | number | undefined | Seed for reproducible k-means++ centroid initialization. |
n_init | number | 10 | Number of independent k-means++ restarts; the run with the lowest weighted inertia is kept. |
Methods
| Method | Signature | Description |
|---|---|---|
fitPredict | (sampleX: number[][], sampleWeights?: number[]) => number[] | Fits centroids on sampleX (optionally weighted) and returns integer cluster labels 0..n_clusters-1. |
getCentroids | () => number[][] | null | Returns the fitted centroid coordinates (or null before fitting). |
getInertia | () => number | Returns the sum of squared weighted distances of samples to their closest centroid. |
getParams / setParams / toJSON | Inherited from ClusterBase | Full estimator contract & JSON serialization via loadModel(). |
Practical guidance & pitfalls
- Always standardize feature scales: Because K-Means relies on squared Euclidean distance, a feature measured in thousands (
revenue) will drown out a feature in[0, 1](churn_rate). Scale columns first withStandardScaler. - Choosing
k: Sweepkacross candidate values and inspect bothgetInertia()(elbow curve) andMetrics.silhouetteScore. - Non-spherical or noisy clusters: If clusters have arbitrary shapes or outliers, try
Clusters.DBSCAN,Clusters.HDBSCAN, orMixture.GaussianMixture. - Related pages: E-Means, Customer Segmentation CSV Guide, K-Means Playground, Clustering Overview.
Clustering
Explore clustering algorithms in JavaScript and TypeScript with @kanaries/ml, including K-Means, DBSCAN, HDBSCAN, Mean Shift, OPTICS, and clustering utilities.
E-Means Clustering
Cluster dense vectors in browser or Node.js with TypeScript E-Means in @kanaries/ml. Covers moving-average updates, rare clusters, and measured benchmarks.