Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Clustering things you can’t average
What is the average of “Boeing”, “Airbus” and “Embraer”? There isn’t one. k-Modes clusters categorical records by:
- counting how many attributes two records disagree on (the matching distance);
- describing each cluster by its mode, the most common value of each attribute.
Then it runs the familiar k-means loop: assign each record to the nearest mode, recompute the modes, repeat. k-Prototypes handles tables with both numbers and categories by adding the two kinds of distance, with a weight γ on the categories.
Maintenance records, incident reports and configuration databases are mostly categorical: subsystem, part number, failure mode, operator, phase of flight. k-modes and k-prototypes cluster them directly, and each cluster’s mode reads like a profile (“hydraulic, pump, leak, ground ops”).
- 1. k-Modes measures dissimilarity by…
- 2. A cluster's representative in k-modes is…
- 3. γ in k-prototypes controls…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.By hand
Matching distance. (red, SUV, diesel) and (red, van, petrol) disagree on 2 attributes, so their distance is 2.
Mode. A cluster with colour values red, red, blue and body values van, SUV, SUV has mode (red, SUV). The mode need not be any actual record.
k-Prototypes distance. Numeric (1, 2) against prototype (0, 0) gives squared distance 1 + 4 = 5. Categorical (a, b) against (a, c) gives 1 mismatch. With γ = 0.5 the total is 5 + 0.5·1 = 5.5.
Cost. The k-modes cost is the total number of mismatches between records and their cluster’s mode. Records (0, 1), (0, 2), (1, 1) with mode (0, 1) have 0 + 1 + 1 = 2 mismatches.
One-hot comparison. One-hot encoding turns a categorical attribute into indicator columns. Two different levels then differ by squared Euclidean distance 2, so one-hot k-means is k-prototypes with γ = 2, except that it averages the indicators (category frequencies) instead of taking modes.
The steps in plain English:
- Choose k initial records as prototypes (numeric part plus categorical part).
- Assign each record to the prototype with the smallest squared numeric distance + γ × mismatches.
- Update: numeric part = mean of the cluster, categorical part = per-attribute mode.
- Repeat until assignments stop changing. Run several starts and keep the lowest cost.
- 1. Matching distance between (A, B, C, D) and (A, X, C, Y)?
- 2. Mode of the values x, y, y, z, y?
- 3. Squared one-hot distance between two different levels?
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 30 minUndergraduate students and practising engineers.Why the mode, and how to choose γ
The mode minimises mismatches. For one attribute, the number of mismatches between a cluster’s values and a chosen level v is (cluster size − count of v). That is smallest when v is the most frequent level, and it works attribute by attribute. So the k-modes update can only lower the cost, just as the mean does for squared distance. With the assignment step also non-increasing, k-modes converges in finitely many steps to a local minimum (Huang, 1998).
Initialisation. Huang suggested choosing k records that are diverse. Cao et al. (2009) proposed density-based seeding. In practice, several random starts with the lowest cost kept work well. Exercise 1: on planted categorical clusters, k-modes went from 999 to 645 mismatches in 4 iterations, with ARI 0.942.
Choosing γ.
- Too small, and the categories are ignored.
- Too large, and the numbers are ignored.
- Huang suggested a value related to the spread of the numeric features. The Python kmodes package defaults to γ = 0.5 × (average numeric standard deviation), which is 0.5 for standardised features.
Exercise 2 shows the trade-off clearly. ARI rose from 0.18 at γ = 0 to 0.73 at γ = 3, then dipped slightly at γ = 10. The package default would have been suboptimal on that data. Tune γ with a stability or validity criterion when you can.
Alternatives.
- Gower distance with k-medoids, or hierarchical clustering.
- Entropy-based methods (COOLCAT).
- Embeddings learned from the categories.
- One-hot k-means is common but treats rare levels and many-level attributes unevenly.
# pip install kmodes
from kmodes.kprototypes import KPrototypes
kp = KPrototypes(n_clusters=3, init="Cao", n_init=5, gamma=None) # gamma=None → 0.5 × mean numeric std
labels = kp.fit_predict(X_mixed, categorical=[2, 3, 4, 5, 6])- 1. Why does the mode update never raise the k-modes cost?
- 2. The kmodes package's default γ for standardised numerics is…
- 3. In exercise 2, γ = 0 gave ARI…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Objective. k-Prototypes minimises
Σᵢ ‖xᵢⁿ − cⁿ₍ₐ₍ᵢ₎₎‖² + γ Σᵢ δ(xᵢᶜ, cᶜ₍ₐ₍ᵢ₎₎),
where δ counts mismatches. Each step (assignment, mean update, mode update) minimises it over one block of variables, so it is coordinate descent. It terminates, but only at a local minimum.
Non-uniqueness. Modes can tie, and a cluster’s mode may not be any actual record. Tie-breaking can affect convergence. Implementations usually break ties consistently and stop when the cost stops decreasing.
What matching distance ignores. All mismatches count the same: “A320 versus A321” costs as much as “A320 versus helicopter”. Frequency-weighted dissimilarities, or a domain-informed distance with k-medoids, can fix this.
γ as a prior on information. Doubling γ is like duplicating every categorical attribute. The best γ reflects how much separating signal each part carries relative to its noise. That is why no fixed rule is right for all data.
Interview questions.
- How would you cluster mixed data? Standardise the numeric columns. Then use k-prototypes with tuned γ, or Gower distance with k-medoids or hierarchical clustering. Validate with silhouette on the same distance and with domain review.
- Why not label-encode categories as integers? It imposes a false order and false spacing (code 3 is not “between” codes 2 and 4).
- 1. Label-encoding categories as 0, 1, 2… for k-means is bad because…
- 2. Doubling γ is equivalent to…
- 3. k-Prototypes is a form of…
Level 4: Expert
★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.What γ works on mixed data?
History.
- Z. Huang introduced k-prototypes (1997) and k-modes (1998).
- A. Chaturvedi, P. Green and J. Carroll (2001) proposed a related k-modes for marketing data.
- F. Cao, J. Liang and L. Bai (2009) gave density-based initialisation.
- J. C. Gower (1971) defined the mixed-type similarity coefficient often used instead.
Exercise 2. Mixed data: 2 standardised numeric features (clusters 1.2 standard deviations apart) and 5 categorical attributes with 4 levels (each cluster’s preferred level appears with probability 0.55, otherwise uniform). 3 clusters, 4 datasets, best of 5 starts. Values are mean ARI with the truth.
| method | ARI |
|---|---|
| k-prototypes, γ = 0 (numeric only) | 0.180 |
| γ = 0.1 | 0.223 |
| γ = 0.3 | 0.289 |
| γ = 1 | 0.574 |
| γ = 3 | 0.726 |
| γ = 10 | 0.704 |
| one-hot + k-means | 0.560 |
| k-modes on the categorical part only | 0.606 |
- Combining the evidence beat either part alone. Best γ: 0.73, against 0.61 for categories only and 0.18 for numbers only.
- The best γ here was 3, six times the package default of 0.5. Small γ values let the weak numeric separation dominate.
- One-hot k-means did worse than k-prototypes at its equivalent weight. It sat between γ = 1 and γ = 3, because averaging indicators blurs the categorical prototypes.
k-Modes in AI, robotics and aerospace
- Maintenance and incident records: grouping events by subsystem, failure mode, phase and operator to find recurring patterns.
- Configuration management: clustering vehicle or software configurations to choose representative test setups.
- Survey and pilot-report analysis where answers are categorical.
References
- Z. Huang (1998). “Extensions to the k-means algorithm for clustering large data sets with categorical values.” Data Mining and Knowledge Discovery 2(3).
- Z. Huang (1997). “Clustering large data sets with mixed numeric and categorical values.” Proc. PAKDD.
- F. Cao, J. Liang, L. Bai (2009). “A new initialization method for categorical data clustering.” Expert Systems with Applications 36.
- J. C. Gower (1971). “A general coefficient of similarity and some of its properties.” Biometrics 27(4).
- N. J. de Vos. “kmodes: Python implementations of k-modes and k-prototypes.” Software documentation.