Gap Statistic

Machine Learning
Introduced by
Robert Tibshirani, Guenther Walther, Trevor Hastie
Year
2001
Type
Statistical criterion
Family
Cluster Number Selection

What does it do?

The Gap Statistic, proposed by Tibshirani, Walther, and Hastie in 2001, is a method for estimating the number of clusters in a data set.

It compares the within-cluster dispersion obtained on the observed data with the dispersion expected under a uniform reference distribution that has no clustering structure. It can be applied on top of any clustering algorithm that produces a partition for each candidate k.

The intuition behind the method

The method asks how much tighter the clusters in the real data are than clusters that would appear in data with no structure. For each candidate k, it compares the log of the within-cluster dispersion on the real data with the log of the average dispersion on uniform reference data. A large gap means the real data are more compact than the null predicts. Because the largest gap is not, by itself, a reliable choice of k, the method applies a one-standard-error rule and selects the smallest k whose gap is nearly as large as the gap at k+1.

History

Tibshirani, Walther, and Hastie introduced the gap statistic in 2001 in the Journal of the Royal Statistical Society: Series B. The proposal uses the output of any clustering algorithm and compares the change in within-cluster dispersion with the change expected under a reference null distribution. The authors developed some theory for the method and reported a simulation study comparing it with other methods proposed in the literature.

When to use it

Choose the Gap Statistic when you need to select the number of clusters k, the clustering algorithm can be run for each candidate k (the source names K-means and hierarchical clustering as examples), and you want the choice judged against a reference model with no structure rather than read off a plot by eye. It is a poor fit when computation is limited, because every candidate k requires clustering B reference datasets. Its null model is uniform over the data range, so it is less suitable when a uniform reference is clearly unrepresentative of the data. If you already have one fixed clustering and want to judge its quality, a per-point measure such as the silhouette score is more direct, since the Gap Statistic answers the question of how many clusters to use.

Limitations and considerations

  • Each candidate k requires clustering the observed data and B reference datasets, so the computational cost grows with both the range of k and the value of B.
  • The reference model is uniform over the data range. For data whose shape is far from uniform, the null may not describe what 'no structure' looks like for that data, which changes the meaning of the gap.
  • W_k is built from squared Euclidean distances to cluster means, so the criterion tends to favour compact, roughly spherical clusters. Elongated or irregularly shaped clusters may not be reflected well in the gap values.
  • The one-standard-error rule depends on the variability across reference datasets, so the selected k is only as stable as that estimate.

Source conditions do not replace independent scientific review or validation by an analysis engine.

Strengths

  • Frames the choice of k as a comparison against an explicit null reference, rather than as a judgement on the shape of a curve.
  • Uses the output of any clustering algorithm, so it is not tied to one algorithm (the source states this explicitly).
  • Gives a single numerical criterion for each candidate k, which can be reported and compared across analyses.
  • In the original paper, a simulation study reports that the gap statistic usually outperformed other methods proposed in the literature. This is a simulation result and does not guarantee the same outcome on a given data set.

Applications

  • Choosing the number of clusters k for K-means or hierarchical clustering on numeric data, as in the original paper's setting.
  • Comparing candidate values of k on a data set, such as the principal components of the Iris data used in the library example.
  • Any numeric clustering problem in which a partition can be computed for each candidate k and a uniform reference is a reasonable model of no structure.

How it works

How it works

1

For each candidate k, cluster the observed data with the chosen algorithm and compute W_k, the sum over clusters of the squared Euclidean distances from each point to its cluster mean.

Formula
W_k = \sum_{r=1}^{k} \sum_{i \in C_r} ||x_i - \mu_r||^2
2

Generate B reference datasets that contain no clustering structure. A common choice is to sample uniformly over the range (bounding box) of the observed data; another is to sample uniformly over the principal-component axes of the data, as in the library example. Report which reference you used. The library example uses B = 200; values from 100 to 500 are a general guideline.

Formula
\text{Generate } B \text{ reference datasets under uniform random distribution}
3

For each reference dataset b and each k, cluster the reference data and compute its dispersion W*_kb. Take the logarithm of each value and average the logs over the B reference datasets to obtain the expected log dispersion under the null.

Formula
\overline{\log W^*_k} = \frac{1}{B}\sum_{b=1}^{B} \log W^*_{kb}
4

Calculate Gap(k) = (1/B) Σ_b log(W*_kb) − log(W_k). The first term is the mean of the logs of the reference dispersions, not the log of their mean. A larger value means the observed data are more tightly grouped at that k than the reference data, which indicates more structure than the null predicts.

Formula
\text{Gap}(k) = \frac{1}{B}\sum_{b=1}^{B} \log(W^*_{kb}) - \log(W_k)
5

Let s_k be the standard deviation of log W*_kb across the B reference datasets, multiplied by sqrt(1 + 1/B). Choose k* as the smallest k for which Gap(k) ≥ Gap(k+1) − s_{k+1}. In words, k* is the first k whose gap is within one standard error of the gap at k+1. This rule is not the same as taking the largest gap.

Formula
k^* = \min \{k : \text{Gap}(k) \geq \text{Gap}(k+1) - s_{k+1}\}

Common pitfalls

  • Using too few reference datasets, which gives unreliable variance estimates and an unstable choice of k.
  • Running the clustering only once on each dataset. Algorithms such as K-means depend on their starting point, so run several starts for the observed data and for each reference dataset and keep the best solution (the library example uses 100 starts per dataset); otherwise the W values, and hence the gaps, can be unstable.
  • Leaving features on very different scales. Variables with large ranges can dominate the dispersion in both the observed and the reference data. Standardizing is a common preprocessing choice; check how it affects the selected k.
  • Taking the global maximum gap instead of applying the one-standard-error rule. The maximum can favour a larger number of clusters than the rule would select.
  • Not reporting the reference distribution used. The choice of null (bounding box or principal-component axes) can affect the gaps, so state it with the result.

Frequently asked questions

How many reference datasets should I generate?

The library example uses B = 200. Values between 100 and 500 are a general guideline, not a figure from the original paper. More reference datasets give more stable standard errors but increase computation. Starting with around 100 and increasing B if the selected k seems unstable is a reasonable approach.

What if the Gap Statistic suggests k=1, meaning no clustering?

This indicates weak or absent clustering structure relative to the reference over the candidate values tested. You may need to examine the data more closely, try different clustering algorithms, or reconsider whether clustering suits your problem.

Can I use the Gap Statistic with non-Euclidean distances?

The within-cluster sum of squares in the formula is defined with squared Euclidean distances, so the criterion as written applies to that setting. Using another distance would require changing the dispersion measure and the reference model accordingly, and the behaviour of the criterion would then need to be checked.

How does the Gap Statistic compare to silhouette score?

The Gap Statistic is a selection criterion for k, while the silhouette score evaluates a given clustering. They answer different questions and can be used together: use the Gap Statistic to choose k, then use the silhouette score to inspect the resulting partition.

Related methods

Sources

  1. Tibshirani, R., Walther, G., & Hastie, T. (2001). Estimating the number of clusters in a data set via the gap statistic. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 63(2), 411-423.

    Open DOI reference
  2. book-20160121, Relative Measures: Gap statistic (Example 17.9), p. 462