EconStatsCraft › Cluster analysis

Cluster analysis

Groups observations that resemble each other - countries into development types, households into segments, firms into strategy groups. It always returns clusters, so the diagnostics that tell you whether the grouping is real matter more than the grouping itself.

What it needs

Frequently asked questions

What is cluster analysis?

Cluster analysis groups observations so that those in the same group are more similar to each other than to those in other groups, without being told the groups in advance. It is unsupervised learning: there is no outcome variable, only the features you choose to compare on.

What is the difference between k-means and hierarchical clustering?

K-means needs the number of clusters k in advance and assigns each point to the nearest of k centroids, which suits large data and round, similar-sized groups. Hierarchical clustering builds a tree of nested merges (a dendrogram) and lets you choose the number of clusters afterwards by cutting the tree, which suits smaller data and exploring structure.

How do I choose the number of clusters?

Look for an elbow in the within-cluster sum of squares as k rises, and for the k with the highest average silhouette score. When the two disagree or neither has a clear peak, the data may not have strong clusters at all, which is itself a finding.

Should I standardise variables before clustering?

Yes, almost always. Clustering uses distances, so a variable measured in thousands swamps one measured in fractions. Standardising to mean 0 and standard deviation 1 gives every variable equal say, unless some deserve more weight on purpose.

How do I know the clusters are real?

Check the silhouette score (above about 0.5 is strong, below 0.25 weak), rerun with a different seed or method and see whether the same groups come back, and describe each cluster by its means. Groups that only exist for one seed, or that cannot be described in words, are probably noise.

The intuition

Clustering asks whether the rows fall into groups, without being told what the groups are. That freedom is also the danger: every clustering algorithm will return clusters, including on data with no group structure whatsoever. The honest workflow is to cluster, then to ask whether the structure found is stronger than what random data of the same shape would produce.

When to use it

To build a typology - country development types, household segments, firm strategy groups - when the groups are not observed and you want the data to suggest them.

Where the estimator comes from

k-means minimises within-cluster sum of squares, \sum_{k}\sum_{i\in C_k}\lVert x_i-\mu_k\rVert^2, alternating between assigning each point to its nearest centroid and recomputing centroids. Each step cannot increase the objective, so it converges - but to a LOCAL minimum that depends on the initialisation, which is why k-means++ seeding and multiple restarts are standard. Hierarchical clustering instead builds a tree by repeatedly merging the closest pair, where "closest" depends on the linkage: single linkage uses the nearest pair of points and chains, complete uses the farthest and makes compact balls, and Ward merges whichever pair increases within-cluster variance least, which makes it the closest analogue of k-means.

The model

\min_{C_1..C_k}\sum_{j=1}^{k}\sum_{i\in C_j}\lVert x_i-\mu_j\rVert^2, \qquad s(i)=\frac{b(i)-a(i)}{\max\{a(i),b(i)\}}

What it assumes

Statistical properties

How to read the output

A worked reading

Run k-means with k = 3 on data generated with no group structure at all and it returns three clusters with a tidy chart and plausible-looking centroids. The silhouette is 0.11. That number is the entire finding: the algorithm did its job, partitioned the space, and found nothing, because the objective it minimises has no way to report failure. Always compute a validity measure, and always compare it against what the same procedure yields on random data of the same dimension - the gap statistic formalises exactly that comparison.

Symptom → diagnosis → what to do

If you see thisIt meansDo this
Different runs giving different clustersLocal minimaUse k-means++ and many restarts; instability is itself informative
One giant cluster and several tiny onesScaling, or genuine outliersStandardise; consider a robust method
Silhouette near zeroNo real group structureDo not proceed to name the clusters
No elbow in the scree of within-cluster sumsCommon. The elbow is not guaranteed to existUse the gap statistic
Single-linkage clusters forming long chainsKnown behaviour of single linkageUse Ward or complete linkage
Clusters not differing on any outside variableThey may be an artefactA segmentation nobody can act on is not a segmentation

Common mistakes

Where to read this properly

See also

Principal components, often run first to reduce dimension before clustering. Perceptual mapping, for the marketing version of the same geometry.

Related Multivariate statistics

Principal components (PCA) · Factor analysis

All analyses

Charts

Line chart · Area chart · Bar chart · Stacked bar · Scatter plot · Bubble chart · Histogram · Box plot · Pie chart · Heat map · Rebased to 100 · Lorenz curve and Gini

Maps

World map · Bivariate map · Flow map · India - state map · India - district map

Explore

Descriptive statistics · Summary by group · Two-way table · Classical statistical tests

Regression

Multiple regression (OLS) · Logit / Probit · Tobit (censored) · Truncated regression · Multinomial logit · Ordered logit / probit · Quantile regression · Poisson / Negative binomial

Time series - one series

Time-varying coefficients (Kalman) · Unit root tests · Correlogram (ACF / PACF) · ARIMA / SARIMA · Rolling-origin cross-validation · Theta method · Unobserved components · STL forecasting · Forecast combination · Markov regime switching · Change frequency (resample) · ARCH / GARCH volatility · Decompose & filter · Spectral analysis · Exponential smoothing · Forecast accuracy

Time series - several series

Yield curve (Nelson–Siegel / Svensson) · Dynamic factor model · Dynamic regression (ARIMAX) · Structural VAR · VAR · Granger causality · Cointegration · VECM · ARDL & bounds test

Panel data

Panel regression · Panel cointegration tests · Heterogeneous panel: Mean Group & PMG · Gravity model of trade · Dynamic panel GMM · Panel diagnostics · Panel unit-root tests

Multivariate statistics

Principal components (PCA) · Factor analysis · Cluster analysis

Marketing research

Conjoint analysis · MaxDiff (best–worst scaling) · TURF - reach of a product line · Price sensitivity (Van Westendorp) · Market basket analysis · Perceptual map · Scale reliability (Cronbach’s alpha) · Key driver analysis

Causal

Spatial autocorrelation · Spatial regression · Heckman selection · Instrumental variables (2SLS) · Difference-in-differences · Staggered difference-in-differences · Regression discontinuity · Matching & weighting · Oaxaca–Blinder decomposition

Finance & risk

Black–Scholes option pricing · Bond price, duration & convexity · Merton distance to default · EMI / home loan planner · CAPM / beta estimation · Multi-factor model · Portfolio optimization · Value at Risk & Expected Shortfall · Performance & drawdown · Time value of money & NPV/IRR · Equity valuation (DDM, FCF, residual income) · Cost of capital (WACC) · Binomial option pricing · Option strategies (payoff & profit) · Forwards, futures & swaps · Credit risk & Basel capital · Extreme value theory (tail risk)

Actuarial

Life table · Life annuity · Life insurance pricing · Chain ladder reserving · Buhlmann credibility · Survival analysis · Mortality graduation · Aggregate loss model · Ruin probability · Multi-state Markov model · Loss severity fitting

Tests & breaks

Monte Carlo experiment · F-test, Wald & Chow · Structural breaks & stability

Machine learning

Regression vs machine learning · Ridge / Lasso / Elastic Net · Random forest · Gradient boosting

Open the workspace →

Starting engine…

EconStatsCraft rigorous, plain-spoken econometrics

Econometrics that explains itself.

Regression, panel data, time series and the whole battery of tests. Every result is followed by a verdict you can defend.

Load a dataset to see it here.