Categories in the mix: Gower, PAM, MCA and FAMD
Real tables mix numbers and categories. Choose a distance and a map that treat both fairly, and see how categories can take over.
What runs in CodeSplash
- k-medoids (PAM) Verified in Python and R
- Multiple correspondence analysis Verified in Python and R
- Factor analysis of mixed data Verified in Python and R
You will be able to
- Explain how Gower distance combines numbers and categories
- Use PAM to cluster with a Gower distance
- Choose MCA for all-categorical tables and FAMD for mixed ones
How far is "Biscoe" from 40 mm?
Readk-means needs a mean, and "island" has none. Turning categories into 0/1 columns works, but those columns then compete with scaled numbers on arbitrary terms.
Gower distanceGower distanceA distance for mixed tables that scales each column to 0–1, compares it, and averages over the columns. takes another route. For each column it computes a difference between 0 and 1, then averages them:
- Numbers: absolute difference, divided by the column's range.
- Categories: 0 if the same, 1 if different.
So one mismatch on a category costs as much as the full range of a number.
Make a guess
PredictPredict first
Cluster penguins into three groups with PAM and Gower distance on bill length, flipper length, island and sex. What do you expect the clusters to follow most?
Reveal
Island and sex. Agreement with species is low: adjusted Rand = 0.222, yet the silhouette is 0.416. Each category mismatch costs a full 1, while a number rarely differs by its whole range, so the categories dominate the distance. Not wrong, but likely not what you wanted to know.
PAM keeps a real row at the center
Readk-medoids, run here as PAM, chooses real rows as centers and swaps them until the total dissimilarity stops falling.
Because it never computes a mean, it works with any distance. Because each center is a real row, you can read one and describe the group: "this penguin is typical of cluster 2".
PAM is also deterministic: no random starts, and Python and R find the same medoids. On 342 rows with a Gower distance, silhouette recommends = 3. Its cost grows quickly with rows, so keep it to thousands, not millions.
Think about your columns
ReflectGower treats each column as equally important. So does the choice of columns.
Adding five binary flags gives "flags" five votes against one for income. Before you cluster, count how many columns speak for each idea in your table. Would you weigh them this way if you were comparing two customers by hand? If not, leave some out.
Maps for categories
ReadMCAMultiple correspondence analysisA PCA-like map for categorical columns, which places categories and rows that occur together close to each other. is PCA's counterpart for categorical tables. It maps categories that occur together close to each other, and it reports inertia instead of variance.
On Titanic, four columns with 10 categories: the first two dimensions hold 50% of the inertia. MCA percentages run low, because the indicator coding inflates the total. Don't read that as a failed map.
Maps for mixed tables
ReadFAMDFactor analysis of mixed dataA map for tables with both numbers and categories, balancing the two kinds so neither dominates. standardizes numbers, weights categories by their frequency, and analyses them together. A rare category gets more weight per row, because knowing it tells you more.
On penguins, four numeric and three categorical columns: the first two dimensions hold 69% of the variance over 333 complete rows.
| Your columns | Map with |
|---|---|
| All numeric | PCA |
| All categorical | MCA |
| A mix | FAMD |
Read the card
In the appMCA of 4 variables: the first dimension explains 29.7% of the inertia.
Eigenvalues
| Dimension | Eigenvalue | Share of inertia |
|---|---|---|
| 1 | 0.4451 | 29.7% |
| 2 | 0.3050 | 20.3% |
| 3 | 0.2500 | 16.7% |
| 4 | 0.2050 | 13.7% |
| 5 | 0.1785 | 11.9% |
| 6 | 0.1163 | 7.8% |
Category coordinates
| Category | Dim 1 | Dim 2 | Dim 3 |
|---|---|---|---|
| Class=1st | 1.152 | −1.231 | −0.8900 |
| Class=2nd | 0.6513 | 0.2525 | 2.392 |
| Class=3rd | 0.1306 | 1.070 | −0.6591 |
| Class=Crew | −0.7369 | −0.4827 | 0.0823 |
| Sex=Male | −0.4276 | −0.0024 | 0.0025 |
| Sex=Female | 1.575 | 0.0089 | −0.0093 |
| Age=Child | 1.302 | 2.943 | 0.0238 |
| Age=Adult | −0.0678 | −0.1533 | −0.0012 |
| Survived=No | −0.5095 | 0.1902 | −0.0038 |
| Survived=Yes | 1.068 | −0.3987 | 0.0079 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Multiple correspondence analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.mca 1.0.0 · spec 93e96b2019049eb0
# Dataset: ml_titanic (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
suppressPackageStartupMessages(library(FactoMineR))
chart_rows <- function(n, cap = 2000) if (n <= cap) seq_len(n) else unique(round(seq(1, n, length.out = cap)))
# %% Data
FEATURES <- c("Class", "Sex", "Age", "Survived")
LEVELS <- list(
Class = c("1st", "2nd", "3rd", "Crew"),
Sex = c("Male", "Female"),
Age = c("Child", "Adult"),
Survived = c("No", "Yes")
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_titanic.parquet", col_select = FEATURES))
n_input <- nrow(df)
warnings <- list()
rows <- cs_ml_complete_rows(df, FEATURES)
if (length(rows) < n_input) {
warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
}
data <- df[rows + 1L, FEATURES, drop = FALSE]
for (f in FEATURES) {
lv <- if (is.null(LEVELS[[f]])) sort(unique(as.character(data[[f]])), method = "radix") else LEVELS[[f]]
data[[f]] <- droplevels(factor(as.character(data[[f]]), levels = lv)) # stored order, unused levels dropped
}
labels <- unlist(lapply(FEATURES, function(f) paste0(f, "=", levels(data[[f]]))))
# %% Multiple correspondence analysis (FactoMineR)
n_dims_all <- length(labels) - length(FEATURES)
k <- min(3, n_dims_all, length(rows) - 1L)
m <- FactoMineR::MCA(data, ncp = min(n_dims_all, length(rows) - 1L), graph = FALSE) # all dimensions (eig is truncated to ncp)
eig <- unname(m$eig[, 1])
prop <- eig / sum(eig)
signs <- cs_ml_canonical_signs(m$var$coord[, seq_len(k), drop = FALSE]) # largest |category coordinate| positive
col_coord <- sweep(unname(as.matrix(m$var$coord[, seq_len(k), drop = FALSE])), 2, signs, "*")
row_coord <- sweep(unname(as.matrix(m$ind$coord[, seq_len(k), drop = FALSE])), 2, signs, "*")
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-57623/discover.mca/titanic/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(k)) emb[[paste0("dim_", j)]] <- row_coord[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
# %% Result
values <- list(n = length(rows), n_variables = length(FEATURES), n_categories = length(labels),
n_dims = length(eig), inertia = sum(eig), cum2 = if (length(eig) >= 2) sum(prop[1:2]) else NaN)
for (j in seq_along(eig)) {
values[[sprintf("eigen[%d]", j)]] <- eig[j]
values[[sprintf("prop[%d]", j)]] <- prop[j]
}
for (j in seq_len(k)) {
values[[sprintf("row_check[%d]", j)]] <- cs_ml_checksum(row_coord[, j], rows)
for (i in seq_along(labels)) values[[sprintf("coord[%d:%s]", j, labels[i])]] <- col_coord[i, j]
}
show <- min(k, 3L)
charts <- list(cs_chart("scree", "scree-plot", "Scree plot", list(
component = cs_col("Dimension", seq_along(eig), "numeric"),
variance = cs_col("Share of inertia", prop, "numeric"),
cumulative = cs_col("Cumulative", cumsum(prop), "numeric")
)))
if (k >= 2) {
pick <- chart_rows(length(rows))
charts[[2]] <- cs_chart("map", "biplot", "Category map (dimensions 1 × 2)", list(
x = cs_col("Dim 1", c(row_coord[pick, 1], col_coord[, 1]), "numeric"),
y = cs_col("Dim 2", c(row_coord[pick, 2], col_coord[, 2]), "numeric"),
kind = cs_col("Kind", c(rep("point", length(pick)), rep("loading", length(labels))), "categorical"),
label = cs_col("Category", c(rep("", length(pick)), labels), "categorical")
))
}
cs_publish(list(
title = "Multiple correspondence analysis",
engine = cs_engine_info("FactoMineR", "nanoparquet"),
n = length(rows),
summary = sprintf("MCA of %d variables: the first dimension explains %.1f%% of the inertia.", length(FEATURES), 100 * prop[1]),
tables = list(
list(key = "variance", title = "Eigenvalues",
columns = list(list(key = "dim", label = "Dimension", type = "integer"),
list(key = "eigenvalue", label = "Eigenvalue", type = "number"),
list(key = "proportion", label = "Share of inertia", type = "percent")),
rows = lapply(seq_along(eig), function(j) list(dim = j, eigenvalue = eig[j], proportion = prop[j]))),
list(key = "categories", title = "Category coordinates",
columns = c(list(list(key = "category", label = "Category")),
lapply(seq_len(show), function(j) list(key = paste0("d", j), label = paste("Dim", j), type = "number"))),
rows = lapply(seq_along(labels), function(i) {
r <- list(category = labels[i])
for (j in seq_len(show)) r[[paste0("d", j)]] <- col_coord[i, j]
r
}))
),
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))
MCA of 4 variables: the first dimension explains 29.7% of the inertia.
Eigenvalues
| Dimension | Eigenvalue | Share of inertia |
|---|---|---|
| 1 | 0.4451 | 29.7% |
| 2 | 0.3050 | 20.3% |
| 3 | 0.2500 | 16.7% |
| 4 | 0.2050 | 13.7% |
| 5 | 0.1785 | 11.9% |
| 6 | 0.1163 | 7.8% |
Category coordinates
| Category | Dim 1 | Dim 2 | Dim 3 |
|---|---|---|---|
| Class=1st | 1.152 | −1.231 | −0.8900 |
| Class=2nd | 0.6513 | 0.2525 | 2.392 |
| Class=3rd | 0.1306 | 1.070 | −0.6591 |
| Class=Crew | −0.7369 | −0.4827 | 0.0823 |
| Sex=Male | −0.4276 | −0.0024 | 0.0025 |
| Sex=Female | 1.575 | 0.0089 | −0.0093 |
| Age=Child | 1.302 | 2.943 | 0.0238 |
| Age=Adult | −0.0678 | −0.1533 | −0.0012 |
| Survived=No | −0.5095 | 0.1902 | −0.0038 |
| Survived=Yes | 1.068 | −0.3987 | 0.0079 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Multiple correspondence analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.mca 1.0.0 · spec 93e96b2019049eb0
# Dataset: ml_titanic (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import embed as csembed
def chart_rows(n, cap=2000):
return np.arange(n) if n <= cap else np.unique(np.linspace(0, n - 1, cap).round().astype(int))
# %% Data
FEATURES = ["Class", "Sex", "Age", "Survived"]
LEVELS = {
"Class": ["1st", "2nd", "3rd", "Crew"],
"Sex": ["Male", "Female"],
"Age": ["Child", "Adult"],
"Survived": ["No", "Yes"],
}
df = pd.read_parquet("tests/parity/fixtures/ml_titanic.parquet", columns=FEATURES)
n_input = len(df)
warnings = []
rows = csembed.complete_rows(df, FEATURES)
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
data = df.iloc[rows].astype("object")
# %% Multiple correspondence analysis (= CA of the indicator matrix, as FactoMineR::MCA)
n_dims_all = sum(len({str(v) for v in data[c]}) for c in FEATURES) - len(FEATURES)
k = min(3, n_dims_all, len(rows) - 1)
res = csembed.mca(data, FEATURES, LEVELS, k)
eig = res["eig"][: min(n_dims_all, len(rows) - 1)]
prop = eig / eig.sum()
signs = csembed.canonical_signs(res["col"]) # largest |category coordinate| positive
col_coord = res["col"] * signs
row_coord = res["row"] * signs
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-57623/discover.mca/titanic/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(k):
emb[f"dim_{j + 1}"] = row_coord[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
# %% Result
values = {
"n": len(rows),
"n_variables": len(FEATURES),
"n_categories": len(res["labels"]),
"n_dims": len(eig),
"inertia": float(eig.sum()),
"cum2": float(prop[:2].sum()) if len(eig) >= 2 else float("nan"),
}
for j in range(len(eig)):
values[f"eigen[{j + 1}]"] = float(eig[j])
values[f"prop[{j + 1}]"] = float(prop[j])
for j in range(k):
values[f"row_check[{j + 1}]"] = csembed.checksum(row_coord[:, j], rows)
for i, lab in enumerate(res["labels"]):
values[f"coord[{j + 1}:{lab}]"] = float(col_coord[i, j])
show = min(k, 3)
charts = [
cs.chart("scree", "scree-plot", "Scree plot", {
"component": cs.col("Dimension", list(range(1, len(eig) + 1)), "numeric"),
"variance": cs.col("Share of inertia", prop, "numeric"),
"cumulative": cs.col("Cumulative", np.cumsum(prop), "numeric"),
})
]
if k >= 2:
pick = chart_rows(len(rows))
charts.append(cs.chart("map", "biplot", "Category map (dimensions 1 × 2)", {
"x": cs.col("Dim 1", np.concatenate([row_coord[pick, 0], col_coord[:, 0]]), "numeric"),
"y": cs.col("Dim 2", np.concatenate([row_coord[pick, 1], col_coord[:, 1]]), "numeric"),
"kind": cs.col("Kind", ["point"] * len(pick) + ["loading"] * len(res["labels"]), "categorical"),
"label": cs.col("Category", [""] * len(pick) + res["labels"], "categorical"),
}))
cs.publish({
"title": "Multiple correspondence analysis",
"engine": cs.engine_info("numpy", "pandas"),
"n": len(rows),
"summary": f"MCA of {len(FEATURES)} variables: the first dimension explains {prop[0]:.1%} of the inertia.",
"tables": [
{"key": "variance", "title": "Eigenvalues", "columns": [
{"key": "dim", "label": "Dimension", "type": "integer"},
{"key": "eigenvalue", "label": "Eigenvalue", "type": "number"},
{"key": "proportion", "label": "Share of inertia", "type": "percent"}],
"rows": [{"dim": j + 1, "eigenvalue": eig[j], "proportion": prop[j]} for j in range(len(eig))]},
{"key": "categories", "title": "Category coordinates", "columns": [{"key": "category", "label": "Category"}]
+ [{"key": f"d{j + 1}", "label": f"Dim {j + 1}", "type": "number"} for j in range(show)],
"rows": [dict({"category": lab}, **{f"d{j + 1}": col_coord[i, j] for j in range(show)}) for i, lab in enumerate(res["labels"])]},
],
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
})
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.
On a category map, read closeness from the origin outward: categories far from the center in the same direction tend to occur together. Rare categories sit far out, so check their counts before you build a story on them.
Check your understanding
CheckpointCheck yourself
Two rows are compared on two columns. Their weights differ by 7 kg on a column with a range of 20 kg, and they have the same category on the second column. What is their Gower distance? Give three decimals.
Show the answer
Answer: 0.175
The number contributes 7 / 20 = 0.35 and the matching category contributes 0. The average over the two columns is (0.35 + 0) / 2 = 0.175.
Check yourself
You have a survey with 12 multiple-choice questions and no numeric columns. Which map fits?
Show the answer
Answer: b
MCA is built for categorical tables. FAMD reduces to something close to MCA when there are no numbers, but it exists for mixtures.
Check yourself
What can you do with a medoid that you can't do with a k-means center?
Show the answer
Answer: a
A mean of categories doesn't exist, and a mean of numbers may describe nobody. A medoid is a real row you can show to someone.
Do it on your own data
In the appUnder Find segments, choose k-medoids (PAM) and leave distance on auto. Under Map the data, choose Multiple correspondence analysis or Factor analysis of mixed data.
import numpy as np
import pandas as pd
df = pd.read_csv("penguins.csv").dropna(subset=["bill_len", "flipper_len", "island", "sex"]).reset_index(drop=True)
def gower(a, b):
num = [abs(df.loc[a, c] - df.loc[b, c]) / (df[c].max() - df[c].min()) for c in ["bill_len", "flipper_len"]]
cat = [float(df.loc[a, c] != df.loc[b, c]) for c in ["island", "sex"]]
return np.mean(num + cat)
print(round(gower(0, 1), 3))df <- read.csv("penguins.csv", stringsAsFactors = TRUE)
df <- na.omit(df[, c("bill_len", "flipper_len", "island", "sex")])
d <- cluster::daisy(df, metric = "gower")
pam <- cluster::pam(d, k = 3)
table(pam$clustering)
df[pam$id.med, ]Recap
Recap- Gower averages per-column differences on a 0-to-1 scale, so categories count fully.
- PAM uses real rows as centers and any distance, at a higher cost.
- Use PCA for numbers, MCA for categories and FAMD for a mix.
Concepts in this lesson