Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Clustering

KTH JupyterHub Open In Colab Binder

Introduction

Unsupervised machine learning learns patterns from data without predefined labels. Formally, the goal is to learn a function f(x)f(\mathbf{x}) from the dataset D={xi}D = \{\mathbf{x}_i\} by optimizing an objective function g(D,f)g(D, f), or simply to partition DD. The PCA chapter learned such a function, the projection onto the directions of largest variation. This chapter turns to clustering, which partitions the data into groups such that the data points within a group are similar to each other.

Clustering methods can be divided into hard clustering, in which each data point is assigned to exactly one cluster, and soft (fuzzy) clustering, in which a data point can belong to several clusters with different probabilities.

k-means clustering

One of the most common clustering algorithms is k-means, a hard clustering algorithm. It partitions the data points xp\mathbf{x}_p into kk clusters S1,…,SkS_1, \ldots, S_k with centers m1,…,mk\mathbf{m}_1, \ldots, \mathbf{m}_k, so that the within-cluster sum of squared Euclidean distances, also called the inertia,

J=∑i=1k∑xp∈Si∥xp−mi∥2,J = \sum_{i=1}^{k} \sum_{\mathbf{x}_p \in S_i} \lVert \mathbf{x}_p - \mathbf{m}_i \rVert^2,

is as small as possible.

Algorithm overview

Starting from kk initial centers, k-means alternates between two steps:

These steps are repeated until the cluster assignments no longer change. Neither step can increase JJ, so the algorithm always converges, but only to a local minimum of JJ that depends on the initial centers.

Illustrations of k-means

The figure below follows k-means through its first three iterations. The assignment steps are labelled E-steps and the recalculation steps M-steps, names that will make sense when we meet the EM algorithm below.

Notebook Cell
<Figure size 1200x1600 with 8 Axes>

The algorithm automatically assigns the points to clusters, and we can see that it closely matches what we would expect by visual inspection.

Voronoi cells and k-means clustering

The k-means clusters form Voronoi cells: each point in the cell of a cluster center is closer to that center than to any other center. The border between two neighbouring cells consists of the points at equal distance from both centers, which is a straight line (in more dimensions, a plane), so k-means always separates its clusters by linear boundaries. The script below draws the Voronoi cells of 7 randomly positioned cluster centers in two dimensions.

<Figure size 640x480 with 1 Axes>

Drawbacks of k-means

The k-means algorithm is simple and effective, but it has some drawbacks:

  1. Initialization sensitivity: The algorithm’s result can be highly dependent on the initial choice of cluster centers. Poor initialization may lead to suboptimal clustering, as k-means may converge to a local minimum of JJ. For example, using a different random seed can lead to different cluster assignments.

  2. Predefined number of clusters: k-means requires specifying the number of clusters beforehand. For example, if we set the number of clusters to three instead of five, the algorithm will still proceed, but the result may not be meaningful.

<Figure size 640x480 with 1 Axes>
  1. Linear cluster boundaries: The k-means algorithm assumes that clusters are spherical and separated by linear boundaries. It struggles with complex geometries. Consider the following dataset with two crescent-shaped clusters:

<Figure size 640x480 with 1 Axes>
  1. Differences in Euclidean size: k-means assumes that all clusters have fairly similar sizes, in terms of the Euclidean distance from their center to their border. Here is an example of three clusters arranged like the head and ears of Mickey Mouse, where k-means has a hard time placing the cluster borders correctly.

<Figure size 800x600 with 1 Axes>

Multivariate normal distribution

A multivariate normal distribution, also known as a multinormal distribution, is a generalization of the one-dimensional normal distribution to multiple dimensions.

Definition

A multivariate normal distribution is characterized by a vector of mean values (μ\boldsymbol{\mu}) and a covariance matrix (Σ\boldsymbol{\Sigma}). It describes the joint distribution of a set of random variables, each of which has a univariate normal distribution, but with the potential for covariance between them, allowing for dependencies. Mathematically, if X\mathbf{X} is a random vector (X1,X2,…,Xd)(X_1, X_2, \dots, X_d) following a multivariate normal distribution, its probability density function is given by:

N(x∣μ,Σ)=1(2π)d∣Σ∣exp⁡(−12(x−μ)TΣ−1(x−μ))\mathcal{N}(\mathbf{x} | \boldsymbol{\mu}, \boldsymbol{\Sigma}) = \frac{1}{\sqrt{(2\pi)^d |\boldsymbol{\Sigma}|}} \exp\left(-\frac{1}{2}(\mathbf{x} - \boldsymbol{\mu})^{\textsf{T}} \boldsymbol{\Sigma}^{-1} (\mathbf{x} - \boldsymbol{\mu})\right)

where:

The multivariate normal distribution is the building block of the Gaussian mixture models below.

Source
<Figure size 1200x600 with 3 Axes>

Gaussian mixture models (GMM)

Gaussian mixture models (GMMs) are a probabilistic, soft clustering method. They assume that the data were generated from a mixture of several multivariate normal distributions, one for each cluster, which makes them flexible enough to model clusters of different sizes, shapes and orientations.

Mathematical formulation

We model the data as generated from a mixture of KK components. Component kk is a multivariate normal distribution N(x∣μk,Σk)\mathcal{N}(\mathbf{x}|\boldsymbol{\mu}_k, \boldsymbol{\Sigma}_k) with its own mean μk\boldsymbol{\mu}_k and covariance matrix Σk\boldsymbol{\Sigma}_k, and it has a mixing coefficient PkP_k, the proportion of data points that belong to it. The probability density function of a GMM with KK components is

p(x)=∑k=1KPkN(x∣μk,Σk)p(\mathbf{x}) = \sum_{k=1}^K P_k \mathcal{N}(\mathbf{x}|\boldsymbol{\mu}_k, \boldsymbol{\Sigma}_k)

The EM algorithm

The parameters of a GMM are fitted with the expectation-maximization (EM) algorithm, a general method for fitting models in which some information is hidden. Such unobserved quantities are called latent variables. In a GMM, the latent variable is the cluster membership of each data point: we never observe which component generated a point. The means, covariance matrices and mixing coefficients, in contrast, are model parameters. EM alternates between estimating the memberships from the current parameters (E-step) and re-estimating the parameters from the memberships (M-step):

  1. Initialization: Choose the number of components KK and initial values for the means μk\boldsymbol{\mu}_k, the covariance matrices Σk\boldsymbol{\Sigma}_k and the mixing coefficients PkP_k, with ∑k=1KPk=1\sum_{k=1}^K P_k = 1.

  2. Expectation step (E-step): Compute the probability that data point xn\mathbf{x}_n was generated by component kk, called the responsibility γnk\gamma_{nk}:

    γnk=PkN(xn∣μk,Σk)∑j=1KPjN(xn∣μj,Σj)\gamma_{nk} = \frac{P_k \mathcal{N}(\mathbf{x}_n | \boldsymbol{\mu}_k, \boldsymbol{\Sigma}_k)}{\sum_{j=1}^K P_j \mathcal{N}(\mathbf{x}_n | \boldsymbol{\mu}_j, \boldsymbol{\Sigma}_j)}

    where N(xn∣μk,Σk)\mathcal{N}(\mathbf{x}_n | \boldsymbol{\mu}_k, \boldsymbol{\Sigma}_k) is the multivariate normal density defined above.

  3. Maximization step (M-step): Re-estimate the parameters from the responsibilities, choosing the values that maximize the likelihood of the data given these soft assignments. With Nk=∑n=1NγnkN_k = \sum_{n=1}^N \gamma_{nk}, the effective number of points in component kk, the updates are

    μknew=1Nk∑n=1Nγnkxn\boldsymbol{\mu}_k^{\text{new}} = \frac{1}{N_k} \sum_{n=1}^N \gamma_{nk} \mathbf{x}_n
    Σknew=1Nk∑n=1Nγnk(xn−μknew)(xn−μknew)T\boldsymbol{\Sigma}_k^{\text{new}} = \frac{1}{N_k} \sum_{n=1}^N \gamma_{nk} (\mathbf{x}_n - \boldsymbol{\mu}_k^{\text{new}})(\mathbf{x}_n - \boldsymbol{\mu}_k^{\text{new}})^{\textsf{T}}
    Pknew=NkNP_k^{\text{new}} = \frac{N_k}{N}
  4. Convergence check: Evaluate the log-likelihood of the data given the current parameters,

    ln⁡Pr⁡(X∣μ,Σ,P)=∑n=1Nln⁡(∑k=1KPkN(xn∣μk,Σk))\ln \Pr(\mathbf{X} | \boldsymbol{\mu}, \boldsymbol{\Sigma}, \mathbf{P}) = \sum_{n=1}^N \ln \left( \sum_{k=1}^K P_k \mathcal{N}(\mathbf{x}_n | \boldsymbol{\mu}_k, \boldsymbol{\Sigma}_k) \right)

    and repeat steps 2 and 3 until it no longer increases.

k-means can be seen as a special case of EM in which cluster membership is a hard 0 or 1 assignment instead of a probability. Its assignment step is an E-step that gives each point responsibility 1 for its nearest center and 0 for all others, and its update step is an M-step that only re-estimates the centers, so as to minimize JJ. A GMM instead keeps soft memberships, so that points near a boundary can belong partly to several clusters, and it also estimates a covariance matrix for each component, so that clusters can be elliptical and oriented in any direction. EM is used well beyond clustering, for instance to fit hidden Markov models, whose latent variables are the hidden states behind an observed sequence, as well as factor analysis and topic models.

Illustrations of GMM

  1. Correlated features: Here is a set of random data points generated from four normal distributions with correlated features, which gives tilted elliptical clusters.

<Figure size 640x480 with 1 Axes>
<Figure size 640x480 with 1 Axes>

Each fitted component is drawn as ellipses at one, two and three standard deviations, with an opacity proportional to its mixing coefficient, and each point is coloured by the component with the largest responsibility. The fitted components recover the four generated clusters, including their tilts.

  1. Clusters of different sizes: Here is a GMM fitted to the same three blobs that k-means split incorrectly above.

<Figure size 640x480 with 1 Axes>

Unlike k-means, the GMM recovers the large, wide blob and the two small ones. It still describes each cluster as a single elliptical blob, however, so it would not cleanly separate the two moons above either.

Comparison between k-means and GMM

The following table highlights the similarities and differences between the k-means and GMM algorithms in terms of their iteration steps:

Step

kk-means

GMM

Init

Select kk cluster centers (m1(1),…,mk(1))(\mathbf{m}_1^{(1)}, \ldots, \mathbf{m}_k^{(1)})

KK components with means μk\boldsymbol{\mu}_k, covariance Σk\boldsymbol{\Sigma}_k, and mixing coefficients PkP_k

E:

Allocate data points to clusters:

Update the probability that component kk generated data point xn\mathbf{x}_n:

Si(t)={xp:∥xp−mi(t)∥2≤∥xp−mj(t)∥2  ∀j}S_i^{(t)} = \{\mathbf{x}_p: \lVert\mathbf{x}_p - \mathbf{m}_i^{(t)}\rVert^2 \le \lVert\mathbf{x}_p - \mathbf{m}_j^{(t)}\rVert^2 \; \forall j \}
γnk=PkN(xn∣μk,Σk)∑j=1KPjN(xn∣μj,Σj)\gamma_{nk} = \frac{P_k \mathcal{N}(\mathbf{x}_n | \boldsymbol{\mu}_k, \boldsymbol{\Sigma}_k)}{\sum_{j=1}^K P_j \mathcal{N}(\mathbf{x}_n | \boldsymbol{\mu}_j, \boldsymbol{\Sigma}_j)}

M:

Re-estimate cluster centers:

Calculate estimated number of cluster members NkN_k, means μk\boldsymbol{\mu}_k, covariance Σk\boldsymbol{\Sigma}_k, and mixing coefficients PkP_k:

mi(t+1)=1∣Si(t)∣∑xp∈Si(t)xp\mathbf{m}_i^{(t+1)} = \frac{1}{|S_i^{(t)}|} \sum_{\mathbf{x}_p \in S_i^{(t)}} \mathbf{x}_p
Nk=∑n=1Nγnk,μknew=1Nk∑n=1Nγnkxn,Σknew=1Nk∑n=1Nγnk(xn−μknew)(xn−μknew)T,Pknew=NkNN_k = \sum_{n=1}^N \gamma_{nk}, \\ \boldsymbol{\mu}_k^{\text{new}} = \frac{1}{N_k} \sum_{n=1}^N \gamma_{nk} \mathbf{x}_n, \\ \boldsymbol{\Sigma}_k^{\text{new}} = \frac{1}{N_k} \sum_{n=1}^N \gamma_{nk} (\mathbf{x}_n - \boldsymbol{\mu}_k^{\text{new}})(\mathbf{x}_n - \boldsymbol{\mu}_k^{\text{new}})^{\textsf{T}}, \\ P_k^{\text{new}} = \frac{N_k}{N}

Stop:

Stop when there are no changes in cluster assignments.

Stop when the log-likelihood does not increase

ln⁡Pr⁡(X∣μ,Σ,P)=∑n=1Nln⁡(∑k=1KPkN(xn∣μk,Σk))\ln \Pr(\mathbf{X}|\boldsymbol{\mu}, \boldsymbol{\Sigma}, \mathbf{P}) = \sum_{n=1}^N \ln \left( \sum_{k=1}^K P_k \mathcal{N}(\mathbf{x}_n | \boldsymbol{\mu}_k, \boldsymbol{\Sigma}_k) \right)
What you should know after reading this chapter

You should be able to:

  1. Define hard and soft (fuzzy) clustering, and identify k-means as a hard and Gaussian mixture models as a soft clustering method.

  2. Describe the two alternating steps of k-means: assigning each point to its nearest cluster center, and recalculating each center mi\mathbf{m}_i as the mean of its assigned points. Calculate one such iteration by hand for a few points in two dimensions.

  3. Explain why k-means clusters form Voronoi cells with linear boundaries. Describe the drawbacks of k-means: sensitivity to the initial centers, a number of clusters kk that must be fixed in advance, and poor results for clusters that are not spherical or that differ in size.

  4. Write down the density of a Gaussian mixture model, p(x)=∑k=1KPkN(x∣μk,Σk)p(\mathbf{x}) = \sum_{k=1}^K P_k \mathcal{N}(\mathbf{x}|\boldsymbol{\mu}_k, \boldsymbol{\Sigma}_k), and explain how the mixing coefficients PkP_k, the means μk\boldsymbol{\mu}_k and the covariance matrices Σk\boldsymbol{\Sigma}_k set the weight, position and shape of each component.

  5. Describe the E-step and the M-step of the EM algorithm for a Gaussian mixture model, and when the iteration stops. Calculate the responsibilities γnk\gamma_{nk} for a data point, given the mixing coefficients and the component densities at that point.

  6. Define a latent variable, and explain k-means as a special case of the EM algorithm in which cluster membership is a hard 0 or 1 assignment instead of a probability.

  7. Contrast k-means and Gaussian mixture models, and argue which of them suits data with elliptical clusters of different sizes and orientations.