@kanaries/ml
API Reference/Clustering

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 Markdown

Algorithm 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.

Iteration0 / 2
Inertia (SSE)57.84
Library delta0.0e+0

Lloyd iterations: assignments and moving centroids

Feature 1Feature 2
Cluster 1Cluster 2Cluster 3

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.

Python
scikit-learn
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_
JavaScript / TypeScript
@kanaries/ml
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.)

ParameterTypeDefaultDescription
n_clustersnumber2Number of clusters (k) to form.
tolnumber1e-4Relative tolerance on weighted inertia change to declare convergence.
initCentersnumber[][]undefinedOptional explicit starting centroids ([n_clusters][nFeatures]). When supplied, n_init is forced to 1.
max_iternumber30Maximum Lloyd iterations per restart.
random_statenumberundefinedSeed for reproducible k-means++ centroid initialization.
n_initnumber10Number of independent k-means++ restarts; the run with the lowest weighted inertia is kept.

Methods

MethodSignatureDescription
fitPredict(sampleX: number[][], sampleWeights?: number[]) => number[]Fits centroids on sampleX (optionally weighted) and returns integer cluster labels 0..n_clusters-1.
getCentroids() => number[][] | nullReturns the fitted centroid coordinates (or null before fitting).
getInertia() => numberReturns the sum of squared weighted distances of samples to their closest centroid.
getParams / setParams / toJSONInherited from ClusterBaseFull estimator contract & JSON serialization via loadModel().

Practical guidance & pitfalls