Skip to content

Clustering, density estimation, and anomaly detection · Partition clustering · UCL011 · Algorithm

K-modes

Cluster categorical observations by representative category modes. Appropriate for nominal feature vectors when equality versus inequality is a meaningful dissimilarity and numerical category codes have no metric…

Runs in CodeSplash Component demo, not a trained model CodeSplash's run and the reference's record

In CodeSplash

A CodeSplash method runs this entry in Python and R. Set it up from the method's page.

Do it in CodeSplash Run it on your own data, in Python or R.

Availability
Runs in CodeSplash
Code example
Component demo, not a trained model
Who ran it
CodeSplash's run and the reference's record
CodeSplash's run
Verified in Python and R through discover.kmodes. The reference's example ran in Python and R here, and they agree.
The reference's record
Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

Cluster categorical observations by representative category modes. Appropriate for nominal feature vectors when equality versus inequality is a meaningful dissimilarity and numerical category codes have no metric interpretation.

Question / hypotheses

Which partition best represents the chosen distance-based notion of within-group similarity? This entry defines an estimation or optimization objective, not an intrinsic null/alternative hypothesis test.

Architecture / computational structure

Categorical prototypes and assignment updates driven by mismatch counts.

Assumptions

Rare but informative levels can be overwhelmed by common categories; many high-cardinality attributes can dominate the distance. Ordinal variables lose their ordering if treated as ordinary nominal categories.

Formula / computational definition

Minimize ∑i,j1[xij≠qzi,j]\sum_{i,j}\mathbf1[x_{ij}\ne q_{z_i,j}], where qk,jq_{k,j} is cluster kk's mode for feature jj. Updating a mode minimizes categorical mismatches for fixed assignments. Weighted versions alter the contribution of features or category frequencies and should be identified explicitly.

Parameters and notation

Learned or fitted quantities: Per-feature modal categories and labels. User-set hyperparameters/design choices: Choose KK, initialization, tie rules, missing-category policy, and optional feature weights. Tune these against the stated objective and stability/validation criteria; do not select settings on the final evaluation set.

Fitting, fine-tuning, and adaptation

Neural fine-tuning is not applicable. Refit after changing the metric or scaling. Where the objective permits, warm-start from previous representatives, then compare against independent restarts; assign new cases using the same stored representation and distance.

How to use and calibrate

Inspect contingency tables for every cluster, mismatch cost, stability under resampling, and whether clusters merely isolate missingness or administrative codes. ARI is useful only when defensible reference labels exist.

Example application

Group products by categorical attributes without imposing numeric coding distances. Define the reference population, measurement units, and success criterion before fitting; investigate whether discovered groups or alerts reflect the intended phenomenon.

Interpretation / pitfalls

Watch out

The reported result is conditional on the representation and objective. A stable partition can reflect nuisance structure such as batch, collection site, or missingness. Confirm the interpretation in original variables and an independent sample.

Python and R code examples

A custom Python loop uses categorical mismatch matrices and per-cluster frequency modes. R provides klaR::kmodes. Keep categorical values as labels; arbitrary integer encoding followed by Euclidean K-means solves a different and generally inappropriate problem.

Component: Categorical mismatch cost. Python: executed successfully; R: not executed (Rscript unavailable). These small fixtures establish the arithmetic operation, not full-method accuracy or reproduction of paper results.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Component demo, not a trained model — Categorical mismatch cost. · needs numpy

import numpy as np
X=np.array([['red','S'],['blue','S'],['red','L']]); mode=np.array(['red','S'])
result=(X!=mode).sum(1)
print(result)
R

Component demo, not a trained model — Categorical mismatch cost.

X=rbind(c('red','S'),c('blue','S'),c('red','L')); mode=c('red','S')
result=rowSums(sweep(X,2,mode,FUN='!='))
print(result)

Sources

From the CodeSplash reference, entry UCL011.