Skip to content

Clustering, density estimation, and anomaly detection · Partition clustering · UCL001 · Algorithm

K-means

Partition numerical observations into KK compact groups represented by means. It is a useful baseline for segmentation and vector quantization when squared Euclidean geometry matches the scientific question.

Runs in CodeSplash Component demo, not a trained model CodeSplash's run and the reference's record

In CodeSplash

A CodeSplash method runs this entry in Python and R. Set it up from the method's page.

Do it in CodeSplash Run it on your own data, in Python or R.

Availability
Runs in CodeSplash
Code example
Component demo, not a trained model
Who ran it
CodeSplash's run and the reference's record
CodeSplash's run
Verified in Python and R through discover.kmeans. The reference's example ran in Python and R here, and they agree.
The reference's record
Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

Partition numerical observations into KK compact groups represented by means. It is a useful baseline for segmentation and vector quantization when squared Euclidean geometry matches the scientific question.

Question / hypotheses

Which partition best represents the chosen distance-based notion of within-group similarity? This entry defines an estimation or optimization objective, not an intrinsic null/alternative hypothesis test.

Architecture / computational structure

Assignment table and a K-by-d centroid matrix; nearest-center passes alternate with arithmetic means.

Assumptions

Compact, similarly dispersed clusters suit the objective; normality is unnecessary for the algorithm. Outliers have quadratic influence, and unequal density or curved shapes can produce misleading divisions. Empty clusters require a defined recovery rule.

Formula / computational definition

Minimize J=∑i∥xi−μzi∥22J=\sum_i\|x_i-\mu_{z_i}\|_2^2, where xix_i is observation ii, ziz_i its assignment, and μk\mu_k cluster kk's centroid. Lloyd iteration alternates nearest-centroid assignment and mean updates; convergence is to a local optimum.

Parameters and notation

Learned or fitted quantities: Centroid coordinates and observation labels. User-set hyperparameters/design choices: Choose KK, initialization, restart count, convergence tolerance, and feature scaling. Tune these against the stated objective and stability/validation criteria; do not select settings on the final evaluation set.

Fitting, fine-tuning, and adaptation

Neural fine-tuning is not applicable. Refit after changing the metric or scaling. Where the objective permits, warm-start from previous representatives, then compare against independent restarts; assign new cases using the same stored representation and distance.

How to use and calibrate

Compare objective values across restarts at fixed KK; use stability and domain usefulness when selecting KK. Inertia always decreases as KK increases. A silhouette score favors its own distance geometry and is not proof of genuine populations.

Example application

Segment standardized laboratory measurements into compact operating regimes. Define the reference population, measurement units, and success criterion before fitting; investigate whether discovered groups or alerts reflect the intended phenomenon.

Interpretation / pitfalls

Watch out

The reported result is conditional on the representation and objective. A stable partition can reflect nuisance structure such as batch, collection site, or missingness. Confirm the interpretation in original variables and an independent sample.

Python and R code examples

sklearn.cluster.KMeans(n_clusters=K, n_init=20, random_state=7); stats::kmeans(X, centers=K, nstart=20). Store the training scaler before assigning new observations.

Component: Squared-distance partition objective. Python: executed successfully; R: not executed (Rscript unavailable). These small fixtures establish the arithmetic operation, not full-method accuracy or reproduction of paper results.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Component demo, not a trained model — Squared-distance partition objective. · needs numpy

import numpy as np
X=np.array([[0.,0.],[1.,0.],[5.,5.]])
C=np.array([[.5,0.],[5.,5.]])
D=((X[:,None,:]-C[None,:,:])**2).sum(2)
result=D.min(1).sum()
print(result)
R

Component demo, not a trained model — Squared-distance partition objective.

X=rbind(c(0,0),c(1,0),c(5,5)); C=rbind(c(.5,0),c(5,5))
D=sapply(1:nrow(C),function(k) rowSums(sweep(X,2,C[k,])^2))
result=sum(apply(D,1,min))
print(result)

Sources

From the CodeSplash reference, entry UCL001.