@kanaries/ml
API Reference/Clustering

K-Means

Learn what K-Means clustering does, when to use it, and how to run K-Means in JavaScript or TypeScript with @kanaries/ml for browser and Node.js applications.

View as Markdown

Algorithm overview

K-Means is an unsupervised clustering algorithm that groups samples into k clusters by assigning each point to the nearest centroid and then repeatedly updating those centroids. It is widely used for segmentation, coarse pattern discovery, and exploratory analysis when labels are not available.

K-Means is a good fit when:

  • you can estimate a reasonable cluster count ahead of time
  • your clusters are roughly compact and distance-based
  • you want a fast baseline for customer, product, or behavior segmentation

It is usually one of the first clustering algorithms to try because it is simple, fast, and easy to explain.

JavaScript implementation

@kanaries/ml lets you run K-Means directly in JavaScript, which is useful for dashboards, segmentation tools, and in-product analytics where clustering needs to happen close to the user interaction. You can cluster points in the browser for exploratory work or in Node.js for server-side batch processing without leaving the JS stack.

This is especially valuable when frontend engineers want scikit-learn-like clustering behavior but need the implementation to live alongside React, Next.js, or other TypeScript-based application code.

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 transparent 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

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, random_state=0, n_init='auto')
labels = model.fit_predict(X)
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(2);
const labels = model.fitPredict(X);

Quick JavaScript example

import { Clusters } from '@kanaries/ml';

const X = [
    [0, 0],
    [0.5, 0],
    [0.5, 1],
    [1, 1],
];

const sampleWeights = [3, 1, 1, 3];
const initCenters = [[0, 0], [1, 1]];

const kmeans = new Clusters.KMeans(2, 0.05, initCenters);
const labels = kmeans.fitPredict(X, sampleWeights);
console.log(labels);

Detailed API reference

constructor (n_clusters: number = 2, opt_ratio: number = 0.05, initCenters?: number[][], max_iter: number = 30)
props nametypedefault value
n_clustersnumber2
opt_rationumber0.05
initCentersnumber[][]undefined
max_iternumber30

Methods

  • fitPredict(trainX: number[][], sampleWeights?: number[]): number[]

Usage notes

  • Normalize numeric features before clustering so distance behaves more predictably.
  • Try several values of k and compare cluster quality with both domain knowledge and quantitative metrics.
  • For interactive browser apps, run larger clustering jobs off the main thread.