Skip to content
AI.info

Unsupervised learning

Categorical and Mixed-Type Clustering

Design dissimilarities and algorithms for nominal, ordinal, binary, count, and mixed-feature datasets.

By the end you can

Analogy

Sorting museum objects with several catalog systems

A museum catalog records weight, historical period, material, condition grade, and whether a rare inscription is present. Each field supports a different kind of comparison. Weight can be subtracted. Period can be ordered. Material can only be matched or not matched. The inscription is interesting when it is present, and says almost nothing when it is absent from both objects.

A curator can revise a judgment with semantic knowledge. A fixed dissimilarity cannot. It applies the encoded weights mechanically, so someone has to set those weights before the comparison runs. That negotiation is the modeling work. The rest of this lesson is about where it has already been settled on your behalf, in real coefficients and real software.

Mixed features need a negotiated comparison, not one universal ruler.

The average country, browser, and subscription plan that never existed

A customer table mixes age, country, device, plan, and purchase counts. Ordinary K-Means answers with centroids carrying fractional categories, and a one-hot country field quietly outvotes two carefully engineered behavior features. The usual reflex is to flatten the table until some algorithm will accept it.

That reflex has a price. Costa and colleagues open their benchmark of mixed-type methods by naming it: “Among the most simple and intuitive strategies for clustering mixed-type data is to convert all variables to a single type, continuous or categorical, via discretization, dummy-coding or fuzzy-coding. Such a strategy may lead to a significant loss of information from the original data and may consequently lead to increased bias (Foss and Markatou, 2018).”

So the problem is not merely interpretability. Nominal categories have no arithmetic mean. A dissimilarity inherited accidentally from an encoding is still a dissimilarity somebody chose. The same paper states why the honest version is hard: “Cluster analysis of mixed-type data sets can be a particularly challenging task because it requires to weigh and aggregate different variables against each other (Hennig and Liao, 2013)”. Foss and Markatou had framed the field the same way in 2018, in the Journal of Statistical Software — as a problem of equitable combination, not of encoding.

Data type is part of the clustering objective.

Example

Encoding failures that create artificial segments

Mixed data contains hidden weighting decisions. In each of these five cases the decision has already been made — by a default, a convention, or a column count.

  • High-cardinality country: Hundreds of one-hot columns dominate two carefully engineered behavior features. Dummy-coding a nominal field is precisely the convert-everything-to-one-type move that benchmark flags as a route to information loss and increased bias. It leaves the country field's influence set by how many levels the field happens to have.
  • Ordinal plan tier: Treating Bronze, Silver, and Gold as equally spaced 0, 1, and 2 invents a numerical interval. The interval does not come from the coefficient you are using. D'Orazio's 2024 paper on Gower's similarity coefficients with automatic weight selection puts the gap plainly: “The Gower’s proposal does not provide guidance for categorical ordered variables.” Two published patches fill it, and they disagree. Kaufman and Rousseeuw replace the level index o with (o−1)/(max(o)−1) and treat the result as ratio-scaled. Podani (1999) substitutes ranks and rescales by the rank range, a rule that “requires a correction to account for tied ranks”. R's daisy exposes the choice as two declared types, "ordered" ("O") and "ordratio" ("T"). The distance from Bronze to Silver is a line in your code, not a property of the tier.
  • Shared absence: Two patients match on thousands of absent rare codes and look similar despite different positive findings. Gower's coefficient carries a switch for exactly this. Declare the variable asymmetric binary and the pairwise indicator δ, in the words of the daisy reference manual, “becomes zero when the variable x[,k] is missing in either or both rows (i and j), or when the variable is asymmetric binary and both values are zero. In all other situations it is 1.” The variable drops out of that pair's average, and the coefficient becomes the Jaccard index. D'Orazio's Table 1 records that “s_ijt corresponds to the Jaccard index”, and adds: “Unfortunately, this distinction is often not considered in applications or in the implementation of the Gower's similarity in statistical software packages.” R's daisy at least protests: “Note that daisy signals a warning when 2-valued numerical variables do not have an explicit type specified, because the reference authors recommend to consider using "asymm"; the warning may be silenced by warnBin = FALSE.” One line of output stands between a practitioner and a similarity built on absences.
  • Exposure bias: Customers with longer tenure cluster together because they had more time to accumulate purchases. The count field is measuring opportunity rather than behavior, until it is divided by the window that produced it.
  • Rare category: A small but meaningful device type disappears when the mismatch cost it contributes is overwhelmed by the continuous block. What decides that is the scalar joining the two losses, not the device type's importance.

Visual

Feature semantics before algorithm choice

Different field types support different comparisons and transformations. Each row below is a declaration somebody has to make before a distance is computed.

Continuous fields carry magnitude in their differences and usually need scaling. Ordinal fields carry order without spacing. The spacing is supplied from outside the data, by whichever convention you pick — Kaufman and Rousseeuw's rescaled level index, or Podani's tie-corrected ranks. Nominal fields differ without ordering and have no arithmetic average to update. Asymmetric binary fields are the ones where presence means more than shared absence. Declared as such, a pair of zeros sets the indicator δ to 0 and the variable is dropped from that pair's average, which turns the coefficient into the Jaccard index. Left undeclared, the two zeros count as agreement. Counts need interpreting against the time, opportunity, or population that generated them. Nothing in the data announces which row a column belongs to.

FigureHierarchy · 5 levels
  • Continuous

    Differences can carry magnitude and often require scaling.

    • Ordinal

      Order matters, but spacing between levels may be unknown.

      • Nominal

        Categories differ without a natural ordering or arithmetic average.

        • Asymmetric binary

          Presence can matter more than shared absence, as with rare diagnoses.

          • Counts and exposure

            Raw totals need interpretation relative to time, opportunity, or population.

Encoding should preserve the distinctions the field can legitimately support.

Key idea

A weighted mixed distance can hide arbitrary policy

Gower-style averaging looks objective because each feature contributes a normalized dissimilarity. Yet block weights determine whether demographics, behavior, products, or geography dominate the result. The default is a weighting scheme too, not the absence of one. Gower's original formula assigns every variable a weight of 1, and daisy's weights argument exists to put a number of your own where that 1 was.

The untouched default is not balanced but tilted, and tilted in a direction few users check: “The discussion on the weighting schemes is sometimes misleading since it often ignores that the unweighted “standard” setting hides an unbalanced contribution of the single variables to the overall dissimilarity.” That is D'Orazio, in 2024. He also says which side it favours: in the unweighted standard version the categorical variables have a higher impact on the final similarity than the numeric ones.

R's daisy function is a good place to see where that policy is written down. With mixed columns it applies “a generalization of Gower’s formula”, named for a paper from 1971. The manual also warns that mixed input quietly overrides a standardization you asked for yourself: “If not all columns of x are numeric, stand will be ignored and Gower’s standardization (based on the range) will be applied in any case”.

So publish sensitivity analyses across plausible weights. If cluster meaning changes dramatically, the partition reflects an unresolved policy choice rather than robust structure.

Normalization does not eliminate the need to justify feature importance.

Comparison

Four approaches to mixed-type groups

Each method embeds a different compromise between type-awareness and scalability. One of those compromises has been measured rather than argued. Costa and colleagues ran a full factorial design of 1,620 data scenarios with fifty replications each — 81,000 simulated data sets. They scored eight distance-based methods by Adjusted Rand Index, in a 2023 paper in Advances in Data Analysis and Classification. Gower's dissimilarity followed by PAM finished last of the eight. Its mean ARI was .136, against .366 for KAMILA, .340 for FAMD/K-Means and .336 for K-Prototypes. More than 75% of Gower/PAM's ARI values fell below .20. Their own summary: “KAMILA, K-Prototypes and sequential Factor Analysis and K-Means clustering typically performed better than other methods.” The interpretable exemplars and the missing-value tolerance of a Gower-plus-medoids partition are real. In that benchmark they cost most of the recoverable structure.

K-Prototypes does not escape the negotiation. It names it. Szepannek, documenting the clustMixType package in The R Journal in December 2018, writes: “The trade off between both terms can be controlled by the parameter λ which has to be specified in advance as well as the number of clusters k. For larger values of λ, the impact of the categorical variables increases.” Both endpoints are known. Costa and colleagues describe the same scalar from the other side: “γl is a weight coefficient for categorical variables in the lth cluster; setting it to zero (thus indicating the absence of categorical variables), one can recover the K-Means algorithm”. Huang's own suggestion was the average standard deviation σ of the numeric variables, with values between σ/3 and 2σ/3 used in his applications. clustMixType therefore sets λ from the data by default, with a caution attached to the convenience: “Note that this should be considered a starting point for further analysis; the explicit choice of λ should be done carefully based on the application context.”

K-Modes drops the arithmetic mean entirely. It represents each cluster by observed category modes and counts mismatches, which keeps representatives real but treats every mismatch alike unless extended. A learned embedding buries the same weighting inside a proxy objective. There it can no longer be read off a single parameter at all, and has to be recovered through neighborhood audits.

FigureComparison · 4 columns

K-Modes

Uses categorical modes and mismatch counts.

  • Designed for nominal attributes
  • Produces observed category representatives
  • Needs K in advance
  • Treats category mismatches uniformly unless extended

K-Prototypes

Combines numeric centroid loss with categorical mismatch loss.

  • Handles mixed numeric and nominal fields
  • Requires a tradeoff weight
  • Inherits K-Means geometry for numerics
  • Can be sensitive to category frequency

Gower plus medoids

Uses type-aware per-feature dissimilarity with observed representatives.

  • Supports mixed and missing fields
  • Offers interpretable exemplars
  • Requires feature weighting
  • Can be costly at large scale

Learned embedding

Maps heterogeneous records into a common vector space.

  • Can capture interactions
  • Needs a proxy objective or supervision
  • May obscure field contributions
  • Requires neighborhood audits

Steps

Design and test a mixed-data dissimilarity

Move from field semantics to pairwise examples before fitting a global partition. Classify field types. Define exposure. Set block weights rather than letting column count decide. Review contrast pairs that should match and pairs that should separate. Only then compare algorithms with stability checks.

That last step has a published worked instance to copy. Preud'homme and colleagues benchmarked nine ready-to-use R clustering tools for mixed data. Four were model-based: Kamila, Latent Class Analysis, Latent Class Model, Clustering by Mixture Modeling. Five were distance-based: Gower or Unsupervised Extra Trees dissimilarity followed by hierarchical clustering or PAM, plus K-prototypes. They scored all nine by Adjusted Rand Index on 1,000 generated virtual populations across 7 scenarios. Then they carried every method through to real data — the EPHESUS randomized trial, “conducted on 6632 patients having a recent acute Myocardial Infarction (MI) and a Left Ventricular Ejection Fraction (LVEF) lower than 40%”. Their result, published in Scientific Reports in February 2021: “The simulations revealed the dominance of K-prototypes, Kamila and LCM models over all other methods.” Costa and colleagues, reviewing that study in their related-work section, record the same ordering from outside: “K-Prototypes was the only efficient distance-based method, outperforming all other techniques for larger numbers of clusters”.

Notice what the design supplies that a single fit cannot: a stated metric, many generated populations rather than one dataset, seven varied scenarios, and a named cohort to carry the surviving methods into.

FigureProcess · 5 steps
  1. 1. Classify field types

    Document nominal, ordinal, asymmetric binary, count, and continuous variables.

  2. 2. Define exposure

    Normalize counts by relevant opportunity, duration, or population when appropriate.

  3. 3. Set block weights

    Choose contributions for feature families rather than letting column count decide.

  4. 4. Review contrast pairs

    Test cases that should match despite categorical differences and cases that should separate.

  5. 5. Compare algorithms

    Evaluate modes, prototypes, medoids, and learned representations with stability checks.

Mixed-data clustering is partly a governance exercise

The final groups reflect decisions about which differences matter and how much: the λ you fixed, the variable weights you left at 1, the two-valued column you never declared asymmetric, the ordinal convention you inherited from a package default. Those decisions can affect people, offers, eligibility, or resource allocation.

Document type handling and weights alongside the cluster model. A technically valid dissimilarity can still encode an indefensible operational policy. Foss and Markatou framed the problem in 2018, in the Journal of Statistical Software. Their subject is “the challenge of equitably combining continuous (quantitative) and categorical (qualitative) variables for the purpose of cluster analysis”. Their verdict on existing methods is blunt: “Existing techniques require strong parametric assumptions, or difficult-to-specify tuning parameters.” Eight years of benchmarks later, the tuning parameters are better measured. They are no less yours to justify.

Feature weighting in mixed data is a substantive decision disguised as preprocessing.

Key takeaways