Kmeans
   HOME

TheInfoList



OR:

''k''-means clustering is a method of
vector quantization Vector quantization (VQ) is a classical quantization technique from signal processing that allows the modeling of probability density functions by the distribution of prototype vectors. Developed in the early 1980s by Robert M. Gray, it was ori ...
, originally from
signal processing Signal processing is an electrical engineering subfield that focuses on analyzing, modifying and synthesizing ''signals'', such as audio signal processing, sound, image processing, images, Scalar potential, potential fields, Seismic tomograph ...
, that aims to partition ''n'' observations into ''k'' clusters in which each observation belongs to the
cluster may refer to: Science and technology Astronomy * Cluster (spacecraft), constellation of four European Space Agency spacecraft * Cluster II (spacecraft), a European Space Agency mission to study the magnetosphere * Asteroid cluster, a small ...
with the nearest
mean A mean is a quantity representing the "center" of a collection of numbers and is intermediate to the extreme values of the set of numbers. There are several kinds of means (or "measures of central tendency") in mathematics, especially in statist ...
(cluster centers or cluster
centroid In mathematics and physics, the centroid, also known as geometric center or center of figure, of a plane figure or solid figure is the arithmetic mean position of all the points in the figure. The same definition extends to any object in n-d ...
), serving as a prototype of the cluster. This results in a partitioning of the data space into
Voronoi cell In mathematics, a Voronoi diagram is a partition of a plane into regions close to each of a given set of objects. It can be classified also as a tessellation. In the simplest case, these objects are just finitely many points in the plane (calle ...
s. ''k''-means clustering minimizes within-cluster variances ( squared Euclidean distances), but not regular Euclidean distances, which would be the more difficult Weber problem: the mean optimizes squared errors, whereas only the
geometric median In geometry, the geometric median of a discrete point set in a Euclidean space is the point minimizing the sum of distances to the sample points. This generalizes the median, which has the property of minimizing the sum of distances or absolute ...
minimizes Euclidean distances. For instance, better Euclidean solutions can be found using ''k''-medians and ''k''-medoids. The problem is computationally difficult (
NP-hard In computational complexity theory, a computational problem ''H'' is called NP-hard if, for every problem ''L'' which can be solved in non-deterministic polynomial-time, there is a polynomial-time reduction from ''L'' to ''H''. That is, assumi ...
); however, efficient
heuristic algorithm A heuristic or heuristic technique (''problem solving'', '' mental shortcut'', ''rule of thumb'') is any approach to problem solving that employs a pragmatic method that is not fully optimized, perfected, or rationalized, but is nevertheless ...
s converge quickly to a
local optimum In mathematical analysis, the maximum and minimum of a function are, respectively, the greatest and least value taken by the function. Known generically as extremum, they may be defined either within a given range (the ''local'' or ''relative' ...
. These are usually similar to the
expectation–maximization algorithm In statistics, an expectation–maximization (EM) algorithm is an iterative method to find (local) maximum likelihood or maximum a posteriori (MAP) estimates of parameters in statistical models, where the model depends on unobserved latent varia ...
for
mixtures In chemistry, a mixture is a material made up of two or more different chemical substances which can be separated by physical method. It is an impure substance made up of 2 or more elements or compounds mechanically mixed together in any proporti ...
of
Gaussian distribution In probability theory and statistics, a normal distribution or Gaussian distribution is a type of continuous probability distribution for a real number, real-valued random variable. The general form of its probability density function is f(x ...
s via an iterative refinement approach employed by both ''k-means'' and ''Gaussian mixture modeling''. They both use cluster centers to model the data; however, ''k''-means clustering tends to find clusters of comparable spatial extent, while the Gaussian mixture model allows clusters to have different shapes. The unsupervised ''k''-means algorithm has a loose relationship to the ''k''-nearest neighbor classifier, a popular supervised
machine learning Machine learning (ML) is a field of study in artificial intelligence concerned with the development and study of Computational statistics, statistical algorithms that can learn from data and generalise to unseen data, and thus perform Task ( ...
technique for classification that is often confused with ''k''-means due to the name. Applying the 1-nearest neighbor classifier to the cluster centers obtained by ''k''-means classifies new data into the existing clusters. This is known as nearest centroid classifier or
Rocchio algorithm The Rocchio algorithm is based on a method of relevance feedback found in information retrieval systems which stemmed from the SMART Information Retrieval System developed between 1960 and 1964. Like many other retrieval systems, the Rocchio algor ...
.


Description

Given a set of observations , where each observation is a d-dimensional real vector, ''k''-means clustering aims to partition the ''n'' observations into () sets so as to minimize the within-cluster sum of squares (WCSS) (i.e.
variance In probability theory and statistics, variance is the expected value of the squared deviation from the mean of a random variable. The standard deviation (SD) is obtained as the square root of the variance. Variance is a measure of dispersion ...
). Formally, the objective is to find: \mathop\operatorname_\mathbf \sum_^ \sum_ \left\, \mathbf x - \boldsymbol\mu_i \right\, ^2 = \mathop\operatorname_\mathbf \sum_^k , S_i, \operatorname S_i where ''μi'' is the mean (also called centroid) of points in S_i, i.e. \boldsymbol = \frac\sum_ \mathbf x, , S_i, is the size of S_i, and \, \cdot\, is the usual ''L''2 norm . This is equivalent to minimizing the pairwise squared deviations of points in the same cluster: \mathop\operatorname_\mathbf \sum_^ \, \frac \, \sum_ \left\, \mathbf - \mathbf \right\, ^2 The equivalence can be deduced from identity , S_i, \sum_ \left\, \mathbf x - \boldsymbol\mu_i \right\, ^2 = \frac \sum_\left\, \mathbf x - \mathbf y\right\, ^2. Since the total variance is constant, this is equivalent to maximizing the sum of squared deviations between points in ''different'' clusters (between-cluster sum of squares, BCSS). This deterministic relationship is also related to the
law of total variance The law of total variance is a fundamental result in probability theory that expresses the variance of a random variable in terms of its conditional variances and conditional means given another random variable . Informally, it states that the o ...
in probability theory.


History

The term "''k''-means" was first used by James MacQueen in 1967, though the idea goes back to
Hugo Steinhaus Hugo Dyonizy Steinhaus ( , ; 14 January 1887 – 25 February 1972) was a Polish mathematician and educator. Steinhaus obtained his PhD under David Hilbert at Göttingen University in 1911 and later became a professor at the Jan Kazimierz Univers ...
in 1956. The standard algorithm was first proposed by Stuart Lloyd of
Bell Labs Nokia Bell Labs, commonly referred to as ''Bell Labs'', is an American industrial research and development company owned by Finnish technology company Nokia. With headquarters located in Murray Hill, New Jersey, Murray Hill, New Jersey, the compa ...
in 1957 as a technique for
pulse-code modulation Pulse-code modulation (PCM) is a method used to digitally represent analog signals. It is the standard form of digital audio in computers, compact discs, digital telephony and other digital audio applications. In a PCM stream, the amplitud ...
, although it was not published as a journal article until 1982. Published in journal much later: In 1965, Edward W. Forgy published essentially the same method, which is why it is sometimes referred to as the Lloyd–Forgy algorithm.


Algorithms


Standard algorithm (naive ''k''-means)

The most common algorithm uses an iterative refinement technique. Due to its ubiquity, it is often called "the ''k''-means algorithm"; it is also referred to as
Lloyd's algorithm In electrical engineering and computer science, Lloyd's algorithm, also known as Voronoi iteration or relaxation, is an algorithm named after Stuart P. Lloyd for finding evenly spaced sets of points in subsets of Euclidean spaces and partitions of ...
, particularly in the computer science community. It is sometimes also referred to as "naïve ''k''-means", because there exist much faster alternatives. Given an initial set of means (see below), the algorithm proceeds by alternating between two steps: # Assignment step: Assign each observation to the cluster with the nearest mean: that with the least squared
Euclidean distance In mathematics, the Euclidean distance between two points in Euclidean space is the length of the line segment between them. It can be calculated from the Cartesian coordinates of the points using the Pythagorean theorem, and therefore is o ...
. (Mathematically, this means partitioning the observations according to the
Voronoi diagram In mathematics, a Voronoi diagram is a partition of a plane into regions close to each of a given set of objects. It can be classified also as a tessellation. In the simplest case, these objects are just finitely many points in the plane (calle ...
generated by the means.) S_i^ = \left \, where each x_p is assigned to exactly one S^, even if it could be assigned to two or more of them. # Update step: Recalculate means (
centroid In mathematics and physics, the centroid, also known as geometric center or center of figure, of a plane figure or solid figure is the arithmetic mean position of all the points in the figure. The same definition extends to any object in n-d ...
s) for observations assigned to each cluster. m^_i = \frac \sum_ x_j The objective function in ''k''-means is the WCSS (within cluster sum of squares). After each iteration, the WCSS decreases and so we have a nonnegative monotonically decreasing sequence. This guarantees that the ''k''-means always converges, but not necessarily to the global optimum. The algorithm has converged when the assignments no longer change or equivalently, when the WCSS has become stable. The algorithm is not guaranteed to find the optimum. The algorithm is often presented as assigning objects to the nearest cluster by distance. Using a different distance function other than (squared) Euclidean distance may prevent the algorithm from converging. Various modifications of ''k''-means such as spherical ''k''-means and ''k''-medoids have been proposed to allow using other distance measures. ;Pseudocode The below pseudocode outlines the implementation of the standard ''k''-means clustering algorithm. Initialization of centroids, distance metric between points and centroids, and the calculation of new centroids are design choices and will vary with different implementations. In this example pseudocode, argmin is used to find the index of the minimum value. def k_means_cluster(k, points): # Initialization: choose k centroids (Forgy, Random Partition, etc.) centroids = 1, c2, ..., ck # Initialize clusters list clusters = for _ in range(k)] # Loop until convergence converged = false while not converged: # Clear previous clusters clusters = for _ in range(k)] # Assign each point to the "closest" centroid for point in points: distances_to_each_centroid = istance(point, centroid) for centroid in centroids cluster_assignment = argmin(distances_to_each_centroid) clusters luster_assignmentappend(point) # Calculate new centroids # (the standard implementation uses the mean of all points in a # cluster to determine the new centroid) new_centroids = alculate_centroid(cluster) for cluster in clusters converged = (new_centroids

centroids) centroids = new_centroids if converged: return clusters


Initialization methods

Commonly used initialization methods are Forgy and Random Partition. The Forgy method randomly chooses ''k'' observations from the dataset and uses these as the initial means. The Random Partition method first randomly assigns a cluster to each observation and then proceeds to the update step, thus computing the initial mean to be the centroid of the cluster's randomly assigned points. The Forgy method tends to spread the initial means out, while Random Partition places all of them close to the center of the data set. According to Hamerly et al., the Random Partition method is generally preferable for algorithms such as the ''k''-harmonic means and fuzzy ''k''-means. For expectation maximization and standard ''k''-means algorithms, the Forgy method of initialization is preferable. A comprehensive study by Celebi et al., however, found that popular initialization methods such as Forgy, Random Partition, and Maximin often perform poorly, whereas Bradley and Fayyad's approach performs "consistently" in "the best group" and ''k''-means++ performs "generally well". File:K Means Example Step 1.svg, 1. ''k'' initial "means" (in this case ''k''=3) are randomly generated within the data domain (shown in color). File:K Means Example Step 2.svg, 2. ''k'' clusters are created by associating every observation with the nearest mean. The partitions here represent the
Voronoi diagram In mathematics, a Voronoi diagram is a partition of a plane into regions close to each of a given set of objects. It can be classified also as a tessellation. In the simplest case, these objects are just finitely many points in the plane (calle ...
generated by the means. File:K Means Example Step 3.svg, 3. The
centroid In mathematics and physics, the centroid, also known as geometric center or center of figure, of a plane figure or solid figure is the arithmetic mean position of all the points in the figure. The same definition extends to any object in n-d ...
of each of the ''k'' clusters becomes the new mean. File:K Means Example Step 4.svg, 4. Steps 2 and 3 are repeated until convergence has been reached.
The algorithm does not guarantee convergence to the global optimum. The result may depend on the initial clusters. As the algorithm is usually fast, it is common to run it multiple times with different starting conditions. However, worst-case performance can be slow: in particular certain point sets, even in two dimensions, converge in exponential time, that is . These point sets do not seem to arise in practice: this is corroborated by the fact that the smoothed running time of ''k''-means is polynomial. The "assignment" step is referred to as the "expectation step", while the "update step" is a maximization step, making this algorithm a variant of the ''generalized''
expectation–maximization algorithm In statistics, an expectation–maximization (EM) algorithm is an iterative method to find (local) maximum likelihood or maximum a posteriori (MAP) estimates of parameters in statistical models, where the model depends on unobserved latent varia ...
.


Complexity

Finding the optimal solution to the ''k''-means clustering problem for observations in ''d'' dimensions is: *
NP-hard In computational complexity theory, a computational problem ''H'' is called NP-hard if, for every problem ''L'' which can be solved in non-deterministic polynomial-time, there is a polynomial-time reduction from ''L'' to ''H''. That is, assumi ...
in general
Euclidean space Euclidean space is the fundamental space of geometry, intended to represent physical space. Originally, in Euclid's ''Elements'', it was the three-dimensional space of Euclidean geometry, but in modern mathematics there are ''Euclidean spaces ...
(of ''d'' dimensions) even for two clusters, *
NP-hard In computational complexity theory, a computational problem ''H'' is called NP-hard if, for every problem ''L'' which can be solved in non-deterministic polynomial-time, there is a polynomial-time reduction from ''L'' to ''H''. That is, assumi ...
for a general number of clusters ''k'' even in the plane, * if ''k'' and ''d'' (the dimension) are fixed, the problem can be exactly solved in time O(n^), where ''n'' is the number of entities to be clustered. Thus, a variety of
heuristic algorithm A heuristic or heuristic technique (''problem solving'', '' mental shortcut'', ''rule of thumb'') is any approach to problem solving that employs a pragmatic method that is not fully optimized, perfected, or rationalized, but is nevertheless ...
s such as Lloyd's algorithm given above are generally used. The running time of Lloyd's algorithm (and most variants) is O(n k d i), where: * ''n'' is the number of ''d''-dimensional vectors (to be clustered) * ''k'' the number of clusters * ''i'' the number of iterations needed until convergence. On data that does have a clustering structure, the number of iterations until convergence is often small, and results only improve slightly after the first dozen iterations. Lloyd's algorithm is therefore often considered to be of "linear" complexity in practice, although it is in the
worst case In computer science, best, worst, and average cases of a given algorithm express what the resource usage is ''at least'', ''at most'' and ''on average'', respectively. Usually the resource being considered is running time, i.e. time complexity, b ...
superpolynomial when performed until convergence. * In the worst-case, Lloyd's algorithm needs i = 2^ iterations, so that the worst-case complexity of Lloyd's algorithm is superpolynomial. * Lloyd's ''k''-means algorithm has polynomial smoothed running time. It is shown that for arbitrary set of ''n'' points in ,1d, if each point is independently perturbed by a normal distribution with mean and variance \sigma^2, then the expected running time of -means algorithm is bounded by O( n^ k^ d^8 \log^4(n) / \sigma^6 ), which is a polynomial in , , and 1/\sigma. * Better bounds are proven for simple cases. For example, it is shown that the running time of ''k''-means algorithm is bounded by O(dn^4M^2) for points in an
integer lattice In mathematics, the -dimensional integer lattice (or cubic lattice), denoted , is the lattice (group), lattice in the Euclidean space whose lattice points are tuple, -tuples of integers. The two-dimensional integer lattice is also called the s ...
\^d. Lloyd's algorithm is the standard approach for this problem. However, it spends a lot of processing time computing the distances between each of the ''k'' cluster centers and the ''n'' data points. Since points usually stay in the same clusters after a few iterations, much of this work is unnecessary, making the naïve implementation very inefficient. Some implementations use caching and the triangle inequality in order to create bounds and accelerate Lloyd's algorithm.


Optimal number of clusters

Finding the optimal number of clusters (''k'') for ''k''-means clustering is a crucial step to ensure that the clustering results are meaningful and useful. Several techniques are available to determine a suitable number of clusters. Here are some of commonly used methods: * Elbow method (clustering): This method involves plotting the explained variation as a function of the number of clusters, and picking the elbow of the curve as the number of clusters to use. However, the notion of an "elbow" is not well-defined and this is known to be unreliable. * Silhouette (clustering): Silhouette analysis measures the quality of clustering and provides an insight into the separation distance between the resulting clusters. A higher silhouette score indicates that the object is well matched to its own cluster and poorly matched to neighboring clusters. * Gap statistic: The Gap Statistic compares the total within intra-cluster variation for different values of k with their expected values under null reference distribution of the data. The optimal k is the value that yields the largest gap statistic. * Davies–Bouldin index: The Davies-Bouldin index is a measure of the how much separation there is between clusters. Lower values of the Davies-Bouldin index indicate a model with better separation. * Calinski-Harabasz index: This Index evaluates clusters based on their compactness and separation. The index is calculated using the ratio of between-cluster variance to within-cluster variance, with higher values indicate better-defined clusters. *
Rand index The Rand index or Rand measure (named after William M. Rand) in statistics, and in particular in data clustering, is a measure of the similarity between two data clusterings. A form of the Rand index may be defined that is adjusted for the chance ...
: It calculates the proportion of agreement between the two clusters, considering both the pairs of elements that are correctly assigned to the same or different clusters. Higher values indicate greater similarity and better clustering quality. To provide a more accurate measure, the Adjusted Rand Index (ARI), introduced by Hubert and Arabie in 1985, corrects the Rand Index by adjusting for the expected similarity of all pairings due to chance.


Variations

* Jenks natural breaks optimization: ''k''-means applied to univariate data * ''k''-medians clustering uses the median in each dimension instead of the mean, and this way minimizes L_1 norm (
Taxicab geometry Taxicab geometry or Manhattan geometry is geometry where the familiar Euclidean distance is ignored, and the distance between two points is instead defined to be the sum of the absolute differences of their respective Cartesian coordinates, a dis ...
). * ''k''-medoids (also: Partitioning Around Medoids, PAM) uses the medoid instead of the mean, and this way minimizes the sum of distances for ''arbitrary'' distance functions. * Fuzzy C-Means Clustering is a soft version of ''k''-means, where each data point has a fuzzy degree of belonging to each cluster. * Gaussian mixture models trained with
expectation–maximization algorithm In statistics, an expectation–maximization (EM) algorithm is an iterative method to find (local) maximum likelihood or maximum a posteriori (MAP) estimates of parameters in statistical models, where the model depends on unobserved latent varia ...
(EM algorithm) maintains probabilistic assignments to clusters, instead of deterministic assignments, and multivariate Gaussian distributions instead of means. * ''k''-means++ chooses initial centers in a way that gives a provable upper bound on the WCSS objective. * The filtering algorithm uses ''k''-d trees to speed up each ''k''-means step. * Some methods attempt to speed up each ''k''-means step using the
triangle inequality In mathematics, the triangle inequality states that for any triangle, the sum of the lengths of any two sides must be greater than or equal to the length of the remaining side. This statement permits the inclusion of Degeneracy (mathematics)#T ...
. * Escape local optima by swapping points between clusters. * The Spherical ''k''-means clustering algorithm is suitable for textual data. * Hierarchical variants such as Bisecting ''k''-means, X-means clustering and G-means clustering repeatedly split clusters to build a hierarchy, and can also try to automatically determine the optimal number of clusters in a dataset. * Internal cluster evaluation measures such as cluster silhouette can be helpful at determining the number of clusters. * Minkowski weighted ''k''-means automatically calculates cluster specific feature weights, supporting the intuitive idea that a feature may have different degrees of relevance at different features. These weights can also be used to re-scale a given data set, increasing the likelihood of a cluster validity index to be optimized at the expected number of clusters. * Mini-batch ''k''-means: ''k''-means variation using "mini batch" samples for data sets that do not fit into memory. * Otsu's method


Hartigan–Wong method

Hartigan and Wong's method provides a variation of ''k''-means algorithm which progresses towards a local minimum of the minimum sum-of-squares problem with different solution updates. The method is a local search that iteratively attempts to relocate a sample into a different cluster as long as this process improves the objective function. When no sample can be relocated into a different cluster with an improvement of the objective, the method stops (in a local minimum). In a similar way as the classical ''k''-means, the approach remains a heuristic since it does not necessarily guarantee that the final solution is globally optimum. Let \varphi(S_j) be the individual cost of S_j defined by \sum_ (x - \mu_j)^2, with \mu_j the center of the cluster. ;Assignment step: Hartigan and Wong's method starts by partitioning the points into random clusters \_. ;Update step: Next it determines the n,m \in \ and x \in S_n for which the following function reaches a maximum \Delta(m,n,x) = \varphi(S_n) + \varphi(S_m) - \varphi(S_n \setminus \ ) - \varphi(S_m \cup \ ). For the x,n,m that reach this maximum, x moves from the cluster S_n to the cluster S_m. ;Termination: The algorithm terminates once \Delta(m,n,x) is less than zero for all x,n,m. Different move acceptance strategies can be used. In a ''first-improvement'' strategy, any improving relocation can be applied, whereas in a ''best-improvement'' strategy, all possible relocations are iteratively tested and only the best is applied at each iteration. The former approach favors speed, whether the latter approach generally favors solution quality at the expense of additional computational time. The function \Delta used to calculate the result of a relocation can also be efficiently evaluated by using equality \Delta(x,n,m) = \frac \cdot \lVert \mu_n - x \rVert^2 - \frac \cdot \lVert \mu_m - x \rVert^2.


Global optimization and meta-heuristics

The classical ''k''-means algorithm and its variations are known to only converge to local minima of the minimum-sum-of-squares clustering problem defined as \mathop\operatorname_\mathbf \sum_^ \sum_ \left\, \mathbf x - \boldsymbol\mu_i \right\, ^2 . Many studies have attempted to improve the convergence behavior of the algorithm and maximize the chances of attaining the global optimum (or at least, local minima of better quality). Initialization and restart techniques discussed in the previous sections are one alternative to find better solutions. More recently, global optimization algorithms based on
branch-and-bound Branch and bound (BB, B&B, or BnB) is a method for solving optimization problems by breaking them down into smaller sub-problems and using a bounding function to eliminate sub-problems that cannot contain the optimal solution. It is an algorithm ...
and
semidefinite programming Semidefinite programming (SDP) is a subfield of mathematical programming concerned with the optimization of a linear objective function (a user-specified function that the user wants to minimize or maximize) over the intersection of the cone of po ...
have produced ‘’provenly optimal’’ solutions for datasets with up to 4,177 entities and 20,531 features. As expected, due to the
NP-hardness In computational complexity theory, a computational problem ''H'' is called NP-hard if, for every problem ''L'' which can be solved in non-deterministic polynomial-time, there is a polynomial-time reduction from ''L'' to ''H''. That is, assumi ...
of the subjacent optimization problem, the computational time of optimal algorithms for ''k''-means quickly increases beyond this size. Optimal solutions for small- and medium-scale still remain valuable as a benchmark tool, to evaluate the quality of other heuristics. To find high-quality local minima within a controlled computational time but without optimality guarantees, other works have explored
metaheuristics In computer science and mathematical optimization, a metaheuristic is a higher-level procedure or heuristic designed to find, generate, tune, or select a heuristic (partial search algorithm) that may provide a sufficiently good solution to an opt ...
and other
global optimization Global optimization is a branch of operations research, applied mathematics, and numerical analysis that attempts to find the global minimum or maximum of a function or a set of functions on a given set. It is usually described as a minimization ...
techniques, e.g., based on incremental approaches and convex optimization, random swaps (i.e., iterated local search),
variable neighborhood search Variable neighborhood search (VNS), proposed by Mladenović & Hansen in 1997, is a metaheuristic method for solving a set of combinatorial optimization and global optimization problems. It explores distant neighborhoods of the current incumbent so ...
and
genetic algorithm In computer science and operations research, a genetic algorithm (GA) is a metaheuristic inspired by the process of natural selection that belongs to the larger class of evolutionary algorithms (EA). Genetic algorithms are commonly used to g ...
s. It is indeed known that finding better local minima of the minimum sum-of-squares clustering problem can make the difference between failure and success to recover cluster structures in feature spaces of high dimension.


Discussion

Three key features of ''k''-means that make it efficient are often regarded as its biggest drawbacks: *
Euclidean distance In mathematics, the Euclidean distance between two points in Euclidean space is the length of the line segment between them. It can be calculated from the Cartesian coordinates of the points using the Pythagorean theorem, and therefore is o ...
is used as a
metric Metric or metrical may refer to: Measuring * Metric system, an internationally adopted decimal system of measurement * An adjective indicating relation to measurement in general, or a noun describing a specific type of measurement Mathematics ...
and
variance In probability theory and statistics, variance is the expected value of the squared deviation from the mean of a random variable. The standard deviation (SD) is obtained as the square root of the variance. Variance is a measure of dispersion ...
is used as a measure of cluster scatter. * The number of clusters ''k'' is an input parameter: an inappropriate choice of ''k'' may yield poor results. That is why, when performing ''k''-means, it is important to run diagnostic checks for determining the number of clusters in the data set. * Convergence to a local minimum may produce counterintuitive ("wrong") results (see example in Fig.). A key limitation of ''k''-means is its cluster model. The concept is based on spherical clusters that are separable so that the mean converges towards the cluster center. The clusters are expected to be of similar size, so that the assignment to the nearest cluster center is the correct assignment. When for example applying ''k''-means with a value of k=3 onto the well-known
Iris flower data set The ''Iris'' flower data set or Fisher's ''Iris'' data set is a Multivariate statistics, multivariate data set used and made famous by the British statistician and biologist Ronald Fisher in his 1936 paper ''The use of multiple measurements in ta ...
, the result often fails to separate the three Iris species contained in the data set. With k=2, the two visible clusters (one containing two species) will be discovered, whereas with k=3 one of the two clusters will be split into two even parts. In fact, k = 2 is more appropriate for this data set, despite the data set's containing 3 ''classes''. As with any other clustering algorithm, the ''k''-means result makes assumptions that the data satisfy certain criteria. It works well on some data sets, and fails on others. The result of ''k''-means can be seen as the Voronoi cells of the cluster means. Since data is split halfway between cluster means, this can lead to suboptimal splits as can be seen in the "mouse" example. The Gaussian models used by the
expectation–maximization algorithm In statistics, an expectation–maximization (EM) algorithm is an iterative method to find (local) maximum likelihood or maximum a posteriori (MAP) estimates of parameters in statistical models, where the model depends on unobserved latent varia ...
(arguably a generalization of ''k''-means) are more flexible by having both variances and covariances. The EM result is thus able to accommodate clusters of variable size much better than ''k''-means as well as correlated clusters (not in this example). In counterpart, EM requires the optimization of a larger number of free parameters and poses some methodological issues due to vanishing clusters or badly-conditioned covariance matrices. ''k''-means is closely related to nonparametric
Bayesian modeling Bayesian inference ( or ) is a method of statistical inference in which Bayes' theorem is used to calculate a probability of a hypothesis, given prior evidence, and update it as more information becomes available. Fundamentally, Bayesian inferen ...
.


Applications

''k''-means clustering is rather easy to apply to even large data sets, particularly when using heuristics such as
Lloyd's algorithm In electrical engineering and computer science, Lloyd's algorithm, also known as Voronoi iteration or relaxation, is an algorithm named after Stuart P. Lloyd for finding evenly spaced sets of points in subsets of Euclidean spaces and partitions of ...
. It has been successfully used in
market segmentation In marketing, market segmentation or customer segmentation is the process of dividing a consumer or business market into meaningful sub-groups of current or potential customers (or consumers) known as ''segments''. Its purpose is to identify pr ...
,
computer vision Computer vision tasks include methods for image sensor, acquiring, Image processing, processing, Image analysis, analyzing, and understanding digital images, and extraction of high-dimensional data from the real world in order to produce numerical ...
, and
astronomy Astronomy is a natural science that studies celestial objects and the phenomena that occur in the cosmos. It uses mathematics, physics, and chemistry in order to explain their origin and their overall evolution. Objects of interest includ ...
among many other domains. It often is used as a preprocessing step for other algorithms, for example to find a starting configuration.


Vector quantization

Vector quantization Vector quantization (VQ) is a classical quantization technique from signal processing that allows the modeling of probability density functions by the distribution of prototype vectors. Developed in the early 1980s by Robert M. Gray, it was ori ...
, a technique commonly used in signal processing and computer graphics, involves reducing the
color palette In color theory, a color scheme is a combination of 2 or more colors used in aesthetic or practical design. Aesthetic color schemes are used to create style and appeal. Colors that create a color harmony, harmonious feeling when viewed togethe ...
of an image to a fixed number of colors, known as ''k''. One popular method for achieving
vector quantization Vector quantization (VQ) is a classical quantization technique from signal processing that allows the modeling of probability density functions by the distribution of prototype vectors. Developed in the early 1980s by Robert M. Gray, it was ori ...
is through ''k''-means clustering. In this process, ''k''-means is applied to the color space of an image to partition it into k clusters, with each cluster representing a distinct color in the image. This technique is particularly useful in image segmentation tasks, where it helps identify and group similar colors together. Example: In the field of
computer graphics Computer graphics deals with generating images and art with the aid of computers. Computer graphics is a core technology in digital photography, film, video games, digital art, cell phone and computer displays, and many specialized applications. ...
, ''k''-means clustering is often employed for
color quantization In computer graphics, color quantization or color image quantization is quantization applied to color spaces; it is a process that reduces the number of distinct colors used in an image, usually with the intention that the new image should be as ...
in image compression. By reducing the number of colors used to represent an image, file sizes can be significantly reduced without significant loss of visual quality. For instance, consider an image with millions of colors. By applying ''k''-means clustering with ''k'' set to a smaller number, the image can be represented using a more limited
color palette In color theory, a color scheme is a combination of 2 or more colors used in aesthetic or practical design. Aesthetic color schemes are used to create style and appeal. Colors that create a color harmony, harmonious feeling when viewed togethe ...
, resulting in a compressed version that consumes less storage space and bandwidth. Other uses of vector quantization include non-random sampling, as ''k''-means can easily be used to choose ''k'' different but prototypical objects from a large data set for further analysis.


Cluster analysis

Cluster analysis Cluster analysis or clustering is the data analyzing technique in which task of grouping a set of objects in such a way that objects in the same group (called a cluster) are more Similarity measure, similar (in some specific sense defined by the ...
, a fundamental task in data mining and
machine learning Machine learning (ML) is a field of study in artificial intelligence concerned with the development and study of Computational statistics, statistical algorithms that can learn from data and generalise to unseen data, and thus perform Task ( ...
, involves grouping a set of data points into clusters based on their similarity. ''k''-means clustering is a popular algorithm used for partitioning data into k clusters, where each cluster is represented by its centroid. However, the pure ''k''-means algorithm is not very flexible, and as such is of limited use (except for when vector quantization as above is actually the desired use case). In particular, the parameter ''k'' is known to be hard to choose (as discussed above) when not given by external constraints. Another limitation is that it cannot be used with arbitrary distance functions or on non-numerical data. For these use cases, many other algorithms are superior. Example: In marketing, ''k''-means clustering is frequently employed for
market segmentation In marketing, market segmentation or customer segmentation is the process of dividing a consumer or business market into meaningful sub-groups of current or potential customers (or consumers) known as ''segments''. Its purpose is to identify pr ...
, where customers with similar characteristics or behaviors are grouped together. For instance, a retail company may use ''k''-means clustering to segment its customer base into distinct groups based on factors such as purchasing behavior, demographics, and geographic location. These customer segments can then be targeted with tailored marketing strategies and product offerings to maximize sales and customer satisfaction.


Feature learning

''k''-means clustering has been used as a
feature learning In machine learning (ML), feature learning or representation learning is a set of techniques that allow a system to automatically discover the representations needed for feature detection or classification from raw data. This replaces manual fea ...
(or dictionary learning) step, in either ( semi-)
supervised learning In machine learning, supervised learning (SL) is a paradigm where a Statistical model, model is trained using input objects (e.g. a vector of predictor variables) and desired output values (also known as a ''supervisory signal''), which are often ...
or
unsupervised learning Unsupervised learning is a framework in machine learning where, in contrast to supervised learning, algorithms learn patterns exclusively from unlabeled data. Other frameworks in the spectrum of supervisions include weak- or semi-supervision, wh ...
. The basic approach is first to train a ''k''-means clustering representation, using the input training data (which need not be labelled). Then, to project any input datum into the new feature space, an "encoding" function, such as the thresholded matrix-product of the datum with the centroid locations, computes the distance from the datum to each centroid, or simply an indicator function for the nearest centroid, or some smooth transformation of the distance. Alternatively, transforming the sample-cluster distance through a Gaussian RBF, obtains the hidden layer of a
radial basis function network In the field of mathematical modeling, a radial basis function network is an artificial neural network that uses radial basis functions as activation functions. The output of the network is a linear combination of radial basis functions of the in ...
. This use of ''k''-means has been successfully combined with simple,
linear classifier In machine learning, a linear classifier makes a classification decision for each object based on a linear combination of its features. Such classifiers work well for practical problems such as document classification, and more generally for prob ...
s for semi-supervised learning in NLP (specifically for
named-entity recognition Named-entity recognition (NER) (also known as (named) entity identification, entity chunking, and entity extraction) is a subtask of information extraction that seeks to locate and classify named entities mentioned in unstructured text into pr ...
) and in
computer vision Computer vision tasks include methods for image sensor, acquiring, Image processing, processing, Image analysis, analyzing, and understanding digital images, and extraction of high-dimensional data from the real world in order to produce numerical ...
. On an object recognition task, it was found to exhibit comparable performance with more sophisticated feature learning approaches such as
autoencoder An autoencoder is a type of artificial neural network used to learn efficient codings of unlabeled data (unsupervised learning). An autoencoder learns two functions: an encoding function that transforms the input data, and a decoding function ...
s and
restricted Boltzmann machine A restricted Boltzmann machine (RBM) (also called a restricted Sherrington–Kirkpatrick model with external field or restricted stochastic Ising–Lenz–Little model) is a generative stochastic artificial neural network that can learn a prob ...
s. However, it generally requires more data, for equivalent performance, because each data point only contributes to one "feature". Example: In
natural language processing Natural language processing (NLP) is a subfield of computer science and especially artificial intelligence. It is primarily concerned with providing computers with the ability to process data encoded in natural language and is thus closely related ...
(NLP), ''k''-means clustering has been integrated with simple linear classifiers for semi-supervised learning tasks such as
named-entity recognition Named-entity recognition (NER) (also known as (named) entity identification, entity chunking, and entity extraction) is a subtask of information extraction that seeks to locate and classify named entities mentioned in unstructured text into pr ...
(NER). By first clustering unlabeled text data using ''k''-means, meaningful features can be extracted to improve the performance of NER models. For instance, ''k''-means clustering can be applied to identify clusters of words or phrases that frequently co-occur in the input text, which can then be used as features for training the NER model. This approach has been shown to achieve comparable performance with more complex
feature learning In machine learning (ML), feature learning or representation learning is a set of techniques that allow a system to automatically discover the representations needed for feature detection or classification from raw data. This replaces manual fea ...
techniques such as
autoencoder An autoencoder is a type of artificial neural network used to learn efficient codings of unlabeled data (unsupervised learning). An autoencoder learns two functions: an encoding function that transforms the input data, and a decoding function ...
s and restricted
Boltzmann machine A Boltzmann machine (also called Sherrington–Kirkpatrick model with external field or stochastic Ising model), named after Ludwig Boltzmann, is a spin glass, spin-glass model with an external field, i.e., a Spin glass#Sherrington–Kirkpatrick m ...
s, albeit with a greater requirement for labeled data.


Recent Developments

Recent advancements in the application of ''k''-means clustering include improvements in initialization techniques, such as the use of ''k''-means++ initialization to select initial cluster centroids in a more effective manner. Additionally, researchers have explored the integration of ''k''-means clustering with deep learning methods, such as
convolutional neural network A convolutional neural network (CNN) is a type of feedforward neural network that learns features via filter (or kernel) optimization. This type of deep learning network has been applied to process and make predictions from many different ty ...
s (CNNs) and
recurrent neural network Recurrent neural networks (RNNs) are a class of artificial neural networks designed for processing sequential data, such as text, speech, and time series, where the order of elements is important. Unlike feedforward neural networks, which proces ...
s (RNNs), to enhance the performance of various tasks in
computer vision Computer vision tasks include methods for image sensor, acquiring, Image processing, processing, Image analysis, analyzing, and understanding digital images, and extraction of high-dimensional data from the real world in order to produce numerical ...
,
natural language processing Natural language processing (NLP) is a subfield of computer science and especially artificial intelligence. It is primarily concerned with providing computers with the ability to process data encoded in natural language and is thus closely related ...
, and other domains.


Relation to other algorithms


Gaussian mixture model

The slow "standard algorithm" for ''k''-means clustering, and its associated
expectation–maximization algorithm In statistics, an expectation–maximization (EM) algorithm is an iterative method to find (local) maximum likelihood or maximum a posteriori (MAP) estimates of parameters in statistical models, where the model depends on unobserved latent varia ...
, is a special case of a Gaussian mixture model, specifically, the limiting case when fixing all covariances to be diagonal, equal and have infinitesimal small variance. Instead of small variances, a hard cluster assignment can also be used to show another equivalence of ''k''-means clustering to a special case of "hard" Gaussian mixture modelling. This does not mean that it is efficient to use Gaussian mixture modelling to compute ''k''-means, but just that there is a theoretical relationship, and that Gaussian mixture modelling can be interpreted as a generalization of ''k''-means; on the contrary, it has been suggested to use ''k''-means clustering to find starting points for Gaussian mixture modelling on difficult data.


''k''-SVD

Another generalization of the ''k''-means algorithm is the ''k''-SVD algorithm, which estimates data points as a sparse linear combination of "codebook vectors". ''k''-means corresponds to the special case of using a single codebook vector, with a weight of 1.


Principal component analysis

The relaxed solution of -means clustering, specified by the cluster indicators, is given by principal component analysis (PCA). The intuition is that ''k''-means describe spherically shaped (ball-like) clusters. If the data has 2 clusters, the line connecting the two centroids is the best 1-dimensional projection direction, which is also the first PCA direction. Cutting the line at the center of mass separates the clusters (this is the continuous relaxation of the discrete cluster indicator). If the data have three clusters, the 2-dimensional plane spanned by three cluster centroids is the best 2-D projection. This plane is also defined by the first two PCA dimensions. Well-separated clusters are effectively modelled by ball-shaped clusters and thus discovered by ''k''-means. Non-ball-shaped clusters are hard to separate when they are close. For example, two half-moon shaped clusters intertwined in space do not separate well when projected onto PCA subspace. ''k''-means should not be expected to do well on this data. It is straightforward to produce counterexamples to the statement that the cluster centroid subspace is spanned by the principal directions.


Mean shift clustering

Basic mean shift clustering algorithms maintain a set of data points the same size as the input data set. Initially, this set is copied from the input set. All points are then iteratively moved towards the mean of the points surrounding them. By contrast, ''k''-means restricts the set of clusters to ''k'' clusters, usually much less than the number of points in the input data set, using the mean of all points in the prior cluster that are closer to that point than any other for the centroid (e.g. within the Voronoi partition of each updating point). A mean shift algorithm that is similar then to ''k''-means, called ''likelihood mean shift'', replaces the set of points undergoing replacement by the mean of all points in the input set that are within a given distance of the changing set. An advantage of mean shift clustering over ''k''-means is the detection of an arbitrary number of clusters in the data set, as there is not a parameter determining the number of clusters. Mean shift can be much slower than ''k''-means, and still requires selection of a bandwidth parameter.


Independent component analysis

Under sparsity assumptions and when input data is pre-processed with the
whitening transformation A whitening transformation or sphering transformation is a linear transformation that transforms a vector of random variables with a known covariance matrix into a set of new variables whose covariance is the identity matrix, meaning that they ar ...
, ''k''-means produces the solution to the linear independent component analysis (ICA) task. This aids in explaining the successful application of ''k''-means to
feature learning In machine learning (ML), feature learning or representation learning is a set of techniques that allow a system to automatically discover the representations needed for feature detection or classification from raw data. This replaces manual fea ...
.


Bilateral filtering

''k''-means implicitly assumes that the ordering of the input data set does not matter. The bilateral filter is similar to ''k''-means and mean shift in that it maintains a set of data points that are iteratively replaced by means. However, the bilateral filter restricts the calculation of the (kernel weighted) mean to include only points that are close in the ordering of the input data. This makes it applicable to problems such as image denoising, where the spatial arrangement of pixels in an image is of critical importance.


Similar problems

The set of squared error minimizing cluster functions also includes the ''k''-medoids algorithm, an approach which forces the center point of each cluster to be one of the actual points, i.e., it uses medoids in place of
centroid In mathematics and physics, the centroid, also known as geometric center or center of figure, of a plane figure or solid figure is the arithmetic mean position of all the points in the figure. The same definition extends to any object in n-d ...
s.


Software implementations

Different implementations of the algorithm exhibit performance differences, with the fastest on a test data set finishing in 10 seconds, the slowest taking 25,988 seconds (~7 hours). The differences can be attributed to implementation quality, language and compiler differences, different termination criteria and precision levels, and the use of indexes for acceleration.


Free Software/Open Source

The following implementations are available under Free/Open Source Software licenses, with publicly available source code. *
Accord.NET Accord.NET is a framework for scientific computing in .NET. The source code of the project is available under the terms of the Gnu Lesser Public License, version 2.1. The framework comprises a set of libraries that are available in source code a ...
contains C# implementations for ''k''-means, ''k''-means++ and ''k''-modes. *
ALGLIB ALGLIB is a cross-platform open source numerical analysis and data processing library. It can be used from several programming languages ( C++, C#, VB.NET, Python, Delphi, Java). ALGLIB started in 1999 and has a long history of steady developm ...
contains parallelized C++ and C# implementations for ''k''-means and ''k''-means++. * AOSP contains a Java implementation for ''k''-means. *
CrimeStat CrimeStat is a crime mapping software program. CrimeStat is Windows-based program that conducts spatial and statistical analysis and is designed to interface with a geographic information system (GIS). The program is developed by Ned Levine & Assoc ...
implements two spatial ''k''-means algorithms, one of which allows the user to define the starting locations. *
ELKI ELKI (''Environment for Developing KDD-Applications Supported by Index-Structures'') is a data mining (KDD, knowledge discovery in databases) software framework developed for use in research and teaching. It was originally created by the databa ...
contains ''k''-means (with Lloyd and MacQueen iteration, along with different initializations such as ''k''-means++ initialization) and various more advanced clustering algorithms. * Smile contains ''k''-means and various more other algorithms and results visualization (for java, kotlin and scala). * Julia contains a ''k''-means implementation in the JuliaStats Clustering package. *
KNIME KNIME (), the Konstanz Information Miner, is a data analytics, reporting and integrating platform. KNIME integrates various components for machine learning and data mining through its modular data pipelining "Building Blocks of Analytics" con ...
contains nodes for ''k''-means and ''k''-medoids. *
Mahout A mahout is an elephant rider, trainer, or keeper. Mahouts were used since antiquity for both civilian and military use. Traditionally, mahouts came from ethnic groups with generations of elephant keeping experience, with a mahout retainin ...
contains a
MapReduce MapReduce is a programming model and an associated implementation for processing and generating big data sets with a parallel and distributed algorithm on a cluster. A MapReduce program is composed of a ''map'' procedure, which performs filte ...
based ''k''-means. *
mlpack mlpack is a free, open-source and header-only software library for machine learning and artificial intelligence written in C++, built on top of the Armadillo library and thensmallennumerical optimization library. mlpack has an emphasis on scal ...
contains a C++ implementation of ''k''-means. *
Octave In music, an octave (: eighth) or perfect octave (sometimes called the diapason) is an interval between two notes, one having twice the frequency of vibration of the other. The octave relationship is a natural phenomenon that has been referr ...
contains ''k''-means. *
OpenCV OpenCV (Open Source Computer Vision Library) is a Library (computing), library of programming functions mainly for Real-time computing, real-time computer vision. Originally developed by Intel, it was later supported by Willow Garage, then Itseez ...
contains a ''k''-means implementation. * Orange includes a component for ''k''-means clustering with automatic selection of ''k'' and cluster silhouette scoring. * PSPP contains ''k''-means, The QUICK CLUSTER command performs ''k''-means clustering on the dataset. * R contains three ''k''-means variations. *
SciPy SciPy (pronounced "sigh pie") is a free and open-source Python library used for scientific computing and technical computing. SciPy contains modules for optimization, linear algebra, integration, interpolation, special functions, fast Fourier ...
and
scikit-learn scikit-learn (formerly scikits.learn and also known as sklearn) is a free and open-source machine learning library for the Python programming language. It features various classification, regression and clustering algorithms including support ...
contain multiple ''k''-means implementations. * Spark MLlib implements a distributed ''k''-means algorithm. *
Torch A torch is a stick with combustible material at one end which can be used as a light source or to set something on fire. Torches have been used throughout history and are still used in processions, symbolic and religious events, and in juggl ...
contains an ''unsup'' package that provides ''k''-means clustering. *
Weka The weka, also known as the Māori hen or woodhen (''Gallirallus australis'') is a flightless bird species of the rail family. It is endemic to New Zealand. Some authorities consider it as the only extant member of the genus '' Gallirallus''. ...
contains ''k''-means and ''x''-means.


Proprietary

The following implementations are available under
proprietary {{Short pages monitor