Maps of categories: CA, MCA and FAMD
Categories have no means or variances to hand to PCA. Correspondence analysis maps a contingency table by its departure from independence, MCA extends that to many categorical columns, and FAMD balances numbers and categories in one map.
What runs in CodeSplash
- REP013Factor analysis of mixed data (FAMD) Runs in CodeSplash
- REP014Multiple correspondence analysis (MCA) Runs in CodeSplash
- REP015Correspondence analysis (CA) Runs in CodeSplash
- Correspondence analysis (CA) 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 correspondence analysis as an SVD of standardized residuals from independence, and read inertia
- Say why MCA's raw inertia percentages look small and what the total inertia depends on
- Describe how FAMD weights numeric and categorical columns, and the pitfalls of rare categories
Numbers for categories, done honestly
ReadCoding "red, green, blue" as 1, 2, 3 and running PCA invents an order and equal spacing that don't exist. One-hot columns fix the order but bring their own problem: rare categories get tiny variances and common ones large ones, so the map reflects frequencies more than relationships.
The correspondence family measures categories against independence, using chi-square weighting so frequent and rare categories are compared fairly.
Correspondence analysis
ReadCorrespondence analysisCorrespondence analysisMaps the rows and columns of a two-way table so similar profiles sit close; its dimensions split the χ² association. starts from a two-way table of counts. Divide by the total to get proportions , with row masses and column masses . Under independence would equal . CA takes the SVD of the standardized residuals
The squared singular values are the inertias of each dimension; they add up to the total inertia, which is the chi-square statistic divided by .
Hair and eye color
ReadCorrespondence analysis, total inertia = 0.234, χ²(9) = 138.29, p < .001
- Total inertia
- 0.2336
- χ²
- 138.29
- p
- < .001
- Shown by 2 dimensions
- 98.9%
Plots
View data
| Level | Mass | Set | Dimension 1 (89.4%) | Dimension 2 (9.5%) |
|---|---|---|---|---|
| Black | 0.1824 | hair | −0.5046 | −0.2148 |
| Brown | 0.4831 | hair | −0.1483 | 0.0327 |
| Red | 0.1199 | hair | −0.1295 | 0.3196 |
| Blond | 0.2145 | hair | 0.8353 | −0.0696 |
| Brown | 0.3716 | eye | −1.077 | −0.5924 |
| Blue | 0.3632 | eye | 1.198 | −0.5564 |
| Hazel | 0.1571 | eye | −0.4653 | 1.123 |
| Green | 0.1081 | eye | 0.3540 | 2.274 |
View data
| Dimension | Cumulative share | Share of inertia |
|---|---|---|
| 1 | 0.8937 | 0.8937 |
| 2 | 0.9889 | 0.0951 |
| 3 | 1 | 0.0111 |
Assumptions
- Expected counts (for the χ² p-value) — 0% of cells expect fewer than 5 (smallest 7.7). The χ² p-value is reliable.
- Counts of independent units — CA describes the table; the χ² test treats every count as an independent unit.
Principal inertias
| Dimension | Principal inertia | Share | Cumulative |
|---|---|---|---|
| 1 | 0.2088 | 89.4% | 89.4% |
| 2 | 0.0222 | 9.5% | 98.9% |
| 3 | 0.0026 | 1.1% | 100.0% |
Rows (hair)
| hair | Mass | Share of inertia | Quality (2 dim.) | Dim. 1 | Contribution 1 | cos² 1 | Dim. 2 | Contribution 2 | cos² 2 |
|---|---|---|---|---|---|---|---|---|---|
| Black | 0.1824 | 23.7% | 0.9899 | −0.5046 | 22.2% | 0.8380 | −0.2148 | 37.9% | 0.1519 |
| Brown | 0.4831 | 5.3% | 0.9063 | −0.1483 | 5.1% | 0.8644 | 0.0327 | 2.3% | 0.0420 |
| Red | 0.1199 | 6.5% | 0.9451 | −0.1295 | 1.0% | 0.1333 | 0.3196 | 55.1% | 0.8118 |
| Blond | 0.2145 | 64.6% | 0.9996 | 0.8353 | 71.7% | 0.9927 | −0.0696 | 4.7% | 0.0069 |
Columns (eye)
| eye | Mass | Share of inertia | Quality (2 dim.) | Dim. 1 | Contribution 1 | cos² 1 | Dim. 2 | Contribution 2 | cos² 2 |
|---|---|---|---|---|---|---|---|---|---|
| Brown | 0.3716 | 39.8% | 0.9981 | −0.4922 | 43.1% | 0.9670 | −0.0883 | 13.0% | 0.0311 |
| Blue | 0.3632 | 47.7% | 0.9999 | 0.5474 | 52.1% | 0.9775 | −0.0830 | 11.2% | 0.0224 |
| Hazel | 0.1571 | 5.6% | 0.8787 | −0.2126 | 3.4% | 0.5424 | 0.1674 | 19.8% | 0.3363 |
| Green | 0.1081 | 6.9% | 0.9484 | 0.1618 | 1.4% | 0.1759 | 0.3390 | 55.9% | 0.7726 |
- Principal coordinates in the tables; the map shows rows in principal and columns in standard coordinates (row-principal biplot). Signs make each dimension's row with the largest absolute coordinate positive; contributions sum to 100% per dimension; cos² is the share of a level's inertia on that dimension.
The exact R script · R R version 4.5.1 (2025-06-13)
# Correspondence analysis (CA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method contingency.ca 1.0.0 · spec 02655aeb1367f1a8
# Dataset: hair_eye (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/hair_eye.parquet", col_select = c("hair", "eye")))
n_input <- nrow(df)
df[["hair"]] <- factor(df[["hair"]], levels = c("Black", "Brown", "Red", "Blond")) # stored level order
df[["eye"]] <- factor(df[["eye"]], levels = c("Brown", "Blue", "Hazel", "Green")) # stored level order
df <- df[stats::complete.cases(df[c("hair", "eye")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("hair", "eye")) # infinite values stop the run (registry/errors.yaml)
# %% Analysis
# Correspondence analysis (Benzécri 1973; Greenacre 2017): the χ² distances between the row profiles and
# between the column profiles of a two-way table, shown on a few dimensions from the SVD of the
# standardized residuals.
row_var <- "hair"
col_var <- "eye"
count_var <- NULL
K_REQ <- as.integer(2)
MAP <- "row_principal" # symmetric | row_principal | column_principal
alpha <- 0.05
w <- if (!is.null(count_var)) as.double(df[[count_var]]) else rep(1, nrow(df))
if (!is.null(count_var) && any(w < 0)) cs_error("CS_E_INVALID_VALUES", column = count_var, requirement = "non-negative counts", count = sum(w < 0))
row_levels <- levels(df[[row_var]])
col_levels <- levels(df[[col_var]])
N <- matrix(0, length(row_levels), length(col_levels))
ri <- as.integer(df[[row_var]])
ci <- as.integer(df[[col_var]])
for (t in seq_along(w)) N[ri[t], ci[t]] <- N[ri[t], ci[t]] + w[t]
keep_r <- rowSums(N) > 0
keep_c <- colSums(N) > 0
notes <- character(0)
if (!all(keep_r) || !all(keep_c)) {
notes <- c(notes, sprintf("Levels with a total count of zero were left out: %s.", paste(c(row_levels[!keep_r], col_levels[!keep_c]), collapse = ", ")))
}
N <- N[keep_r, keep_c, drop = FALSE]
row_levels <- row_levels[keep_r]
col_levels <- col_levels[keep_c]
cs_check_groups(row_levels, row_var, minimum = 2)
cs_check_groups(col_levels, col_var, minimum = 2)
fit <- cs_mview_ca(N)
dims <- fit$dims
K <- min(K_REQ, dims)
total <- fit$total
share <- if (total > 0) fit$eigen / total else rep(NaN, dims)
df_chi <- (length(row_levels) - 1) * (length(col_levels) - 1)
p_chi <- stats::pchisq(fit$chisq, df_chi, lower.tail = FALSE)
expected <- outer(rowSums(N), colSums(N)) / fit$n
# %% Assumptions
small <- mean(expected < 5)
ok_exp <- small <= 0.2 && min(expected) >= 1
assumptions <- list(
list(key = "expected", label = "Expected counts (for the χ² p-value)", status = if (ok_exp) "ok" else "warn",
detail = paste0(sprintf("%.0f%% of cells expect fewer than 5 (smallest %s). ", 100 * small, format(signif(min(expected), 2))),
if (ok_exp) "The χ² p-value is reliable."
else "The χ² p-value is approximate; the map itself does not depend on it, but rare levels can dominate a dimension — check their contributions.")),
list(key = "profiles", label = "Counts of independent units", status = "info",
detail = "CA describes the table; the χ² test treats every count as an independent unit.")
)
# %% Result
values <- list(n = fit$n, n_rows = length(row_levels), n_cols = length(col_levels), dims = dims,
total_inertia = total, chisq = fit$chisq, df = df_chi, p = p_chi,
cum2 = if (total > 0) sum(share[seq_len(min(2, dims))]) else NaN)
for (j in seq_len(dims)) {
values[[sprintf("eigen[%d]", j)]] <- fit$eigen[j]
values[[sprintf("share[%d]", j)]] <- share[j]
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
cum <- cumsum(share)
tables <- list(list(key = "inertia", title = "Principal inertias",
columns = list(list(key = "dimension", label = "Dimension", type = "integer"), list(key = "eigen", label = "Principal inertia", type = "number"),
list(key = "share", label = "Share", type = "percent"), list(key = "cumulative", label = "Cumulative", type = "percent")),
rows = lapply(seq_len(dims), function(j) list(dimension = j, eigen = fit$eigen[j], share = share[j], cumulative = cum[j]))))
side_table <- function(key, title, var, levs, mass, inertia, coord, ctr, cos2) {
cols <- list(list(key = "level", label = var, type = "string"), list(key = "mass", label = "Mass", type = "number"),
list(key = "inertia", label = "Share of inertia", type = "percent"), list(key = "quality", label = sprintf("Quality (%d dim.)", K), type = "number"))
for (j in seq_len(K)) {
cols <- c(cols, list(list(key = sprintf("coord%d", j), label = sprintf("Dim. %d", j), type = "number"),
list(key = sprintf("ctr%d", j), label = sprintf("Contribution %d", j), type = "percent"),
list(key = sprintf("cos%d", j), label = sprintf("cos² %d", j), type = "number")))
}
rows <- lapply(seq_along(levs), function(i) {
cq <- cos2[i, seq_len(K)]
row <- list(level = levs[i], mass = mass[i], inertia = if (total > 0) inertia[i] / total else NaN,
quality = if (all(is.nan(cq))) NaN else sum(cq, na.rm = TRUE))
for (j in seq_len(K)) {
row[[sprintf("coord%d", j)]] <- coord[i, j]
row[[sprintf("ctr%d", j)]] <- ctr[i, j]
row[[sprintf("cos%d", j)]] <- cos2[i, j]
}
row
})
list(key = key, title = title, columns = cols, rows = rows)
}
tables[[2]] <- side_table("rows", sprintf("Rows (%s)", row_var), row_var, row_levels, fit$row_mass, fit$row_inertia, fit$row_coord, fit$row_ctr, fit$row_cos2)
tables[[3]] <- side_table("cols", sprintf("Columns (%s)", col_var), col_var, col_levels, fit$col_mass, fit$col_inertia, fit$col_coord, fit$col_ctr, fit$col_cos2)
charts <- list(cs_chart("scree", "scree-plot", "Principal inertias", list(
component = cs_col("Dimension", as.double(seq_len(dims))),
variance = cs_col("Share of inertia", share),
cumulative = cs_col("Cumulative share", cum))))
if (dims >= 2 && K >= 2) {
rc <- if (MAP %in% c("symmetric", "row_principal")) fit$row_coord else fit$row_std
cc <- if (MAP %in% c("symmetric", "column_principal")) fit$col_coord else fit$col_std
charts <- c(list(cs_chart("map", "ca-map", "Correspondence analysis map", list(
x = cs_col(sprintf("Dimension 1 (%.1f%%)", 100 * share[1]), c(rc[, 1], cc[, 1])),
y = cs_col(sprintf("Dimension 2 (%.1f%%)", 100 * share[2]), c(rc[, 2], cc[, 2])),
set = cs_col("Set", c(rep(row_var, length(row_levels)), rep(col_var, length(col_levels))), "categorical"),
label = cs_col("Level", c(row_levels, col_levels), "categorical"),
mass = cs_col("Mass", c(fit$row_mass, fit$col_mass))), controls = list(map = MAP))), charts)
}
summary <- paste0(sprintf("Correspondence analysis of %s (%d levels) by %s (%d levels), total count %s: total inertia %.4f (χ² = %.2f, df = %d, %s). ",
row_var, length(row_levels), col_var, length(col_levels), format(fit$n), total, fit$chisq, as.integer(df_chi), cs_fmt_p(p_chi)),
if (dims >= 2) sprintf("The first two dimensions show %.1f%% and %.1f%% of it (%.1f%% together).", 100 * share[1], 100 * share[2], 100 * (share[1] + share[2]))
else "The one dimension shows all of it.")
map_note <- switch(MAP,
symmetric = "both sets in principal coordinates (symmetric map: compare rows with rows and columns with columns, not across)",
row_principal = "rows in principal and columns in standard coordinates (row-principal biplot)",
"columns in principal and rows in standard coordinates (column-principal biplot)")
cs_publish(list(
method = "contingency.ca",
methodVersion = "1.0.0",
title = "Correspondence analysis",
engine = cs_engine_info("stats", "nanoparquet"),
n = fit$n,
summary = summary,
apa = sprintf("Correspondence analysis, total inertia = %.3f, χ²(%d) = %.2f, %s", total, as.integer(df_chi), fit$chisq, cs_fmt_p(p_chi)),
statistics = list(list(key = "total_inertia", label = "Total inertia", value = total),
list(key = "chisq", label = "χ²", value = fit$chisq), list(key = "p", label = "p", value = p_chi, format = "p"),
list(key = "cum2", label = "Shown by 2 dimensions", value = values$cum2, format = "percent")),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = as.list(c(notes, paste0("Principal coordinates in the tables; the map shows ", map_note, ". ",
"Signs make each dimension's row with the largest absolute coordinate positive; contributions sum to 100% per dimension; cos² is the share of a level's inertia on that dimension."))),
values = values,
charts = charts
))
Correspondence analysis, total inertia = 0.234, χ²(9) = 138.29, p < .001
- Total inertia
- 0.2336
- χ²
- 138.29
- p
- < .001
- Shown by 2 dimensions
- 98.9%
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Expected counts (for the χ² p-value) — 0% of cells expect fewer than 5 (smallest 7.7). The χ² p-value is reliable.
- Counts of independent units — CA describes the table; the χ² test treats every count as an independent unit.
Principal inertias
| Dimension | Principal inertia | Share | Cumulative |
|---|---|---|---|
| 1 | 0.2088 | 89.4% | 89.4% |
| 2 | 0.0222 | 9.5% | 98.9% |
| 3 | 0.0026 | 1.1% | 100.0% |
Rows (hair)
| hair | Mass | Share of inertia | Quality (2 dim.) | Dim. 1 | Contribution 1 | cos² 1 | Dim. 2 | Contribution 2 | cos² 2 |
|---|---|---|---|---|---|---|---|---|---|
| Black | 0.1824 | 23.7% | 0.9899 | −0.5046 | 22.2% | 0.8380 | −0.2148 | 37.9% | 0.1519 |
| Brown | 0.4831 | 5.3% | 0.9063 | −0.1483 | 5.1% | 0.8644 | 0.0327 | 2.3% | 0.0420 |
| Red | 0.1199 | 6.5% | 0.9451 | −0.1295 | 1.0% | 0.1333 | 0.3196 | 55.1% | 0.8118 |
| Blond | 0.2145 | 64.6% | 0.9996 | 0.8353 | 71.7% | 0.9927 | −0.0696 | 4.7% | 0.0069 |
Columns (eye)
| eye | Mass | Share of inertia | Quality (2 dim.) | Dim. 1 | Contribution 1 | cos² 1 | Dim. 2 | Contribution 2 | cos² 2 |
|---|---|---|---|---|---|---|---|---|---|
| Brown | 0.3716 | 39.8% | 0.9981 | −0.4922 | 43.1% | 0.9670 | −0.0883 | 13.0% | 0.0311 |
| Blue | 0.3632 | 47.7% | 0.9999 | 0.5474 | 52.1% | 0.9775 | −0.0830 | 11.2% | 0.0224 |
| Hazel | 0.1571 | 5.6% | 0.8787 | −0.2126 | 3.4% | 0.5424 | 0.1674 | 19.8% | 0.3363 |
| Green | 0.1081 | 6.9% | 0.9484 | 0.1618 | 1.4% | 0.1759 | 0.3390 | 55.9% | 0.7726 |
- Principal coordinates in the tables; the map shows rows in principal and columns in standard coordinates (row-principal biplot). Signs make each dimension's row with the largest absolute coordinate positive; contributions sum to 100% per dimension; cos² is the share of a level's inertia on that dimension.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Correspondence analysis (CA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method contingency.ca 1.0.0 · spec 02655aeb1367f1a8
# Dataset: hair_eye (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.errors import check_groups, check_not_constant
from codesplash.stats import multiview as mvw
# %% Data
df = pd.read_parquet("tests/parity/fixtures/hair_eye.parquet", columns=["hair", "eye"])
n_input = len(df)
df["hair"] = pd.Categorical(df["hair"], categories=["Black", "Brown", "Red", "Blond"]) # stored level order
df["eye"] = pd.Categorical(df["eye"], categories=["Brown", "Blue", "Hazel", "Green"]) # stored level order
df = df.dropna(subset=["hair", "eye"]) # listwise deletion over the analysis columns
df["hair"] = df["hair"].cat.remove_unused_categories()
df["eye"] = df["eye"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["hair", "eye"]) # infinite values stop the run (registry/errors.yaml)
# %% Analysis
# Correspondence analysis (Benzécri 1973; Greenacre 2017): the χ² distances between the row profiles and
# between the column profiles of a two-way table, shown on a few dimensions from the SVD of the
# standardized residuals.
row_var = "hair"
col_var = "eye"
count_var = None
K_REQ = int(2)
MAP = "row_principal" # symmetric | row_principal | column_principal
alpha = 0.05
w = df[count_var].to_numpy(dtype=float) if count_var else np.ones(len(df))
if count_var and np.any(w < 0):
cs.cs_error("CS_E_INVALID_VALUES", column=count_var, requirement="non-negative counts", count=int(np.sum(w < 0)))
row_levels = [str(x) for x in df[row_var].cat.categories]
col_levels = [str(x) for x in df[col_var].cat.categories]
N = np.zeros((len(row_levels), len(col_levels)))
np.add.at(N, (df[row_var].cat.codes.to_numpy(), df[col_var].cat.codes.to_numpy()), w)
keep_r = N.sum(axis=1) > 0
keep_c = N.sum(axis=0) > 0
notes = []
if not keep_r.all() or not keep_c.all():
gone = [row_levels[i] for i in np.flatnonzero(~keep_r)] + [col_levels[j] for j in np.flatnonzero(~keep_c)]
notes.append(f"Levels with a total count of zero were left out: {', '.join(gone)}.")
N = N[keep_r][:, keep_c]
row_levels = [lv for lv, k_ in zip(row_levels, keep_r) if k_]
col_levels = [lv for lv, k_ in zip(col_levels, keep_c) if k_]
check_groups(row_levels, row_var, minimum=2)
check_groups(col_levels, col_var, minimum=2)
fit = mvw.ca(N)
dims = fit["dims"]
K = min(K_REQ, dims)
total = fit["total"]
share = fit["eigen"] / total if total > 0 else np.full(dims, np.nan)
df_chi = (len(row_levels) - 1) * (len(col_levels) - 1)
p_chi = float(stats.chi2.sf(fit["chisq"], df_chi))
expected = np.outer(N.sum(axis=1), N.sum(axis=0)) / fit["n"]
# %% Assumptions
small = float(np.mean(expected < 5))
assumptions = [
{"key": "expected", "label": "Expected counts (for the χ² p-value)", "status": "ok" if small <= 0.2 and expected.min() >= 1 else "warn",
"detail": f"{small:.0%} of cells expect fewer than 5 (smallest {expected.min():.2g}). " + ("The χ² p-value is reliable." if small <= 0.2 and expected.min() >= 1
else "The χ² p-value is approximate; the map itself does not depend on it, but rare levels can dominate a dimension — check their contributions.")},
{"key": "profiles", "label": "Counts of independent units", "status": "info",
"detail": "CA describes the table; the χ² test treats every count as an independent unit."},
]
# %% Result
values = {"n": fit["n"], "n_rows": len(row_levels), "n_cols": len(col_levels), "dims": dims,
"total_inertia": total, "chisq": fit["chisq"], "df": df_chi, "p": p_chi,
"cum2": float(np.sum(share[:2])) if total > 0 else float("nan")}
for j in range(dims):
values[f"eigen[{j + 1}]"] = float(fit["eigen"][j])
values[f"share[{j + 1}]"] = float(share[j])
values["missing_share"] = n_dropped / n_input if n_input else 0.0
cum = np.cumsum(share)
tables = [{"key": "inertia", "title": "Principal inertias",
"columns": [{"key": "dimension", "label": "Dimension", "type": "integer"}, {"key": "eigen", "label": "Principal inertia", "type": "number"},
{"key": "share", "label": "Share", "type": "percent"}, {"key": "cumulative", "label": "Cumulative", "type": "percent"}],
"rows": [{"dimension": j + 1, "eigen": float(fit["eigen"][j]), "share": float(share[j]), "cumulative": float(cum[j])} for j in range(dims)]}]
def side_table(key, title, var, levels, mass, inertia, coord, ctr, cos2):
cols = [{"key": "level", "label": var, "type": "string"}, {"key": "mass", "label": "Mass", "type": "number"},
{"key": "inertia", "label": "Share of inertia", "type": "percent"}, {"key": "quality", "label": f"Quality ({K} dim.)", "type": "number"}]
for j in range(K):
cols += [{"key": f"coord{j + 1}", "label": f"Dim. {j + 1}", "type": "number"},
{"key": f"ctr{j + 1}", "label": f"Contribution {j + 1}", "type": "percent"},
{"key": f"cos{j + 1}", "label": f"cos² {j + 1}", "type": "number"}]
rows = []
for i, lv in enumerate(levels):
row = {"level": lv, "mass": float(mass[i]), "inertia": float(inertia[i] / total) if total > 0 else float("nan"),
"quality": float(np.nansum(cos2[i, :K])) if not np.all(np.isnan(cos2[i, :K])) else float("nan")}
for j in range(K):
row.update({f"coord{j + 1}": float(coord[i, j]), f"ctr{j + 1}": float(ctr[i, j]), f"cos{j + 1}": float(cos2[i, j])})
rows.append(row)
return {"key": key, "title": title, "columns": cols, "rows": rows}
tables.append(side_table("rows", f"Rows ({row_var})", row_var, row_levels, fit["row_mass"], fit["row_inertia"], fit["row_coord"], fit["row_ctr"], fit["row_cos2"]))
tables.append(side_table("cols", f"Columns ({col_var})", col_var, col_levels, fit["col_mass"], fit["col_inertia"], fit["col_coord"], fit["col_ctr"], fit["col_cos2"]))
charts = [cs.chart("scree", "scree-plot", "Principal inertias", {
"component": cs.col("Dimension", np.arange(1, dims + 1, dtype=float)),
"variance": cs.col("Share of inertia", share),
"cumulative": cs.col("Cumulative share", cum)})]
if dims >= 2 and K >= 2:
rc = fit["row_coord"] if MAP in ("symmetric", "row_principal") else fit["row_std"]
cc = fit["col_coord"] if MAP in ("symmetric", "column_principal") else fit["col_std"]
charts.insert(0, cs.chart("map", "ca-map", "Correspondence analysis map", {
"x": cs.col(f"Dimension 1 ({share[0]:.1%})", np.concatenate([rc[:, 0], cc[:, 0]])),
"y": cs.col(f"Dimension 2 ({share[1]:.1%})", np.concatenate([rc[:, 1], cc[:, 1]])),
"set": cs.col("Set", [row_var] * len(row_levels) + [col_var] * len(col_levels), "categorical"),
"label": cs.col("Level", row_levels + col_levels, "categorical"),
"mass": cs.col("Mass", np.concatenate([fit["row_mass"], fit["col_mass"]]))},
controls={"map": MAP}))
summary = (f"Correspondence analysis of {row_var} ({len(row_levels)} levels) by {col_var} ({len(col_levels)} levels), total count {fit['n']:g}: "
f"total inertia {total:.4f} (χ² = {fit['chisq']:.2f}, df = {df_chi}, {cs.fmt_p(p_chi)}). "
+ (f"The first two dimensions show {share[0]:.1%} and {share[1]:.1%} of it ({share[0] + share[1]:.1%} together)." if dims >= 2
else f"The one dimension shows all of it."))
cs.publish({
"method": "contingency.ca",
"methodVersion": "1.0.0",
"title": "Correspondence analysis",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": int(round(fit["n"])) if float(fit["n"]).is_integer() else fit["n"],
"summary": summary,
"apa": f"Correspondence analysis, total inertia = {total:.3f}, χ²({df_chi}) = {fit['chisq']:.2f}, {cs.fmt_p(p_chi)}",
"statistics": [{"key": "total_inertia", "label": "Total inertia", "value": total},
{"key": "chisq", "label": "χ²", "value": fit["chisq"]}, {"key": "p", "label": "p", "value": p_chi, "format": "p"},
{"key": "cum2", "label": "Shown by 2 dimensions", "value": values["cum2"], "format": "percent"}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes + [f"Principal coordinates in the tables; the map shows {'both sets in principal coordinates (symmetric map: compare rows with rows and columns with columns, not across)' if MAP == 'symmetric' else ('rows in principal and columns in standard coordinates (row-principal biplot)' if MAP == 'row_principal' else 'columns in principal and rows in standard coordinates (column-principal biplot)')}. "
"Signs make each dimension's row with the largest absolute coordinate positive; contributions sum to 100% per dimension; cos² is the share of a level's inertia on that dimension."],
"values": values,
"charts": charts,
})
For 592 people, chi-square is 138.3, so total inertia is 0.234. The first dimension holds 89.4% of it: one axis, from dark hair and brown eyes to blond hair and blue eyes, carries almost all the association.
Rows close together have similar profiles; so do columns. A striking map is still not a test: report the chi-square test separately.
Many categorical columns: MCA
ReadMCAMultiple correspondence analysisA PCA-like map for categorical columns, which places categories and rows that occur together close to each other. applies CA to the indicator matrix of several categorical columns (one 0/1 column per category). Each person and each category gets coordinates.
Its total inertia depends only on the counts: with categories across columns it is . For Titanic passengers, four columns with ten categories give = 1.50, whatever the data say. The first dimension holds 29.7% of it. Raw MCA percentages always look low for that reason; adjusted inertias (Benzécri, Greenacre) are a fairer summary. Say which one you report.
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 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.
Mixed tables: FAMD
ReadFAMDFactor analysis of mixed dataA map for tables with both numbers and categories, balancing the two kinds so neither dominates. handles numbers and categories together. Numeric columns are standardized; category indicators are weighted by their frequency, as in MCA. A weighted PCA of the combined table then gives each kind of column comparable influence.
FAMD of 4 numeric and 3 categorical variables: the first dimension explains 46.7% of the variance.
Plots
View data
| Dimension | Cumulative | Proportion of variance |
|---|---|---|
| 1 | 0.4668 | 0.4668 |
| 2 | 0.6888 | 0.2220 |
| 3 | 0.8452 | 0.1565 |
| 4 | 0.9229 | 0.0777 |
| 5 | 0.9549 | 0.0321 |
| 6 | 0.9741 | 0.0191 |
| 7 | 0.9852 | 0.0111 |
| 8 | 0.9956 | 0.0104 |
| 9 | 1 | 0.0044 |
Numeric variables: correlations with the dimensions; categories: centers of their rows.
View data
| Kind | Variable | Dim 1 | Dim 2 |
|---|---|---|---|
| point | −2.260 | −1.080 | |
| point | −1.997 | −1.760 | |
| point | −2.064 | −1.593 | |
| point | −2.467 | −1.728 | |
| point | −2.349 | −0.7809 | |
| point | −2.363 | −1.775 | |
| point | −1.452 | −0.8935 | |
| point | −2.396 | −1.618 | |
| point | −2.383 | −0.7540 | |
| point | −2.047 | −1.079 | |
| point | −2.329 | −1.959 | |
| point | −2.229 | −1.591 | |
| point | −1.482 | −0.4588 | |
| point | −2.806 | −2.075 | |
| point | −1.678 | −0.0644 | |
| point | −2.019 | −1.422 | |
| point | −1.607 | −0.8020 | |
| point | −1.585 | −1.412 | |
| point | −1.116 | −0.8203 | |
| point | −1.164 | −0.9081 | |
| point | −1.633 | −1.510 | |
| point | −1.346 | −0.5595 | |
| point | −1.472 | −1.210 | |
| point | −2.269 | −1.382 | |
| point | −1.284 | −0.5294 | |
| point | −2.278 | −0.5636 | |
| point | −2.126 | −0.0065 | |
| point | −2.121 | −0.3843 | |
| point | −1.852 | 0.4363 | |
| point | −1.921 | −0.7374 | |
| point | −1.818 | 0.6285 | |
| point | −1.951 | 0.4242 | |
| point | −2.209 | −0.0774 | |
| point | −2.731 | −0.3638 | |
| point | −1.543 | 0.3818 | |
| point | −2.613 | −0.6340 | |
| point | −1.410 | 0.3919 | |
| point | −2.630 | −0.5981 | |
| point | −1.139 | 0.8621 | |
| point | −2.371 | −0.7342 | |
| point | −1.333 | 0.3406 | |
| point | −2.183 | 0.4532 | |
| point | −2.200 | −0.6620 | |
| point | −1.814 | 0.8929 | |
| point | −1.358 | −1.312 | |
| point | −0.8557 | −0.5345 | |
| point | −1.566 | −1.668 | |
| point | −0.5948 | −0.2596 | |
| point | −2.030 | −1.702 | |
| point | −0.9549 | −0.4652 | |
| point | −1.331 | −1.390 | |
| point | −0.9185 | −0.4990 | |
| point | −1.866 | −1.752 | |
| point | −1.146 | −0.7130 | |
| point | −1.672 | −1.764 | |
| point | −0.8941 | −0.1111 | |
| point | −1.330 | −1.580 | |
| point | −0.6772 | −0.5364 | |
| point | −1.863 | −1.684 | |
| point | −0.6664 | −0.5224 |
First 60 of 345 rows.
Eigenvalues
| Dimension | Eigenvalue | Proportion |
|---|---|---|
| 1 | 4.201 | 46.7% |
| 2 | 1.998 | 22.2% |
| 3 | 1.408 | 15.6% |
| 4 | 0.6990 | 7.8% |
| 5 | 0.2885 | 3.2% |
| 6 | 0.1721 | 1.9% |
| 7 | 0.1001 | 1.1% |
| 8 | 0.0936 | 1.0% |
| 9 | 0.0398 | 0.4% |
Variable coordinates
| Variable or category | Dim 1 | Dim 2 | Dim 3 |
|---|---|---|---|
| bill_len | 0.6688 | 0.6606 | 0.0119 |
| bill_dep | −0.7201 | 0.3772 | 0.4858 |
| flipper_len | 0.9356 | 0.0577 | 0.1160 |
| body_mass | 0.9018 | 0.0189 | 0.3237 |
| species=Adelie | −1.717 | −0.7822 | 0.4722 |
| species=Chinstrap | −0.8937 | 2.397 | −0.7355 |
| species=Gentoo | 2.617 | −0.4098 | −0.1590 |
| island=Biscoe | 1.582 | −0.5655 | −0.0378 |
| island=Dream | −1.335 | 1.274 | −0.3946 |
| island=Torgersen | −1.992 | −1.372 | 1.164 |
| sex=female | −0.3897 | −0.5575 | −1.018 |
| sex=male | 0.3827 | 0.5476 | 0.9995 |
- 11 of 344 rows were left out because a value was missing.
The exact R script · R R version 4.5.1 (2025-06-13)
# Factor analysis of mixed data
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.famd 1.0.0 · spec d18ac443e7be524b
# Dataset: ml_penguins (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
NUMERIC <- c("bill_len", "bill_dep", "flipper_len", "body_mass")
CATEGORICAL <- c("species", "island", "sex")
LEVELS <- list(
species = c("Adelie", "Chinstrap", "Gentoo"),
island = c("Biscoe", "Dream", "Torgersen"),
sex = c("female", "male")
)
COLUMNS <- unique(c(NUMERIC, CATEGORICAL))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.parquet", col_select = COLUMNS))
n_input <- nrow(df)
warnings <- list()
rows <- cs_ml_complete_rows(df, COLUMNS)
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, COLUMNS, drop = FALSE]
rownames(data) <- NULL
for (f in NUMERIC) data[[f]] <- as.numeric(data[[f]])
for (f in CATEGORICAL) {
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))
}
labels <- c(NUMERIC, unlist(lapply(CATEGORICAL, function(f) paste0(f, "=", levels(data[[f]])))))
# %% Factor analysis of mixed data (FactoMineR)
n_cat <- sum(vapply(CATEGORICAL, function(f) nlevels(data[[f]]), integer(1)))
rank <- min(length(NUMERIC) + n_cat - length(CATEGORICAL), length(rows) - 1L)
k <- min(3, rank)
m <- FactoMineR::FAMD(data, ncp = rank, graph = FALSE) # all dimensions (eig is truncated to ncp)
eig <- unname(m$eig[seq_len(rank), 1])
prop <- eig / sum(eig)
coords <- rbind(as.matrix(m$quanti.var$coord), as.matrix(m$quali.var$coord))[, seq_len(k), drop = FALSE]
signs <- cs_ml_canonical_signs(coords)
col_coord <- sweep(unname(coords), 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-72273/discover.famd/penguins/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_numeric = length(NUMERIC), n_categorical = length(CATEGORICAL),
n_dims = length(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("Proportion of variance", prop, "numeric"),
cumulative = cs_col("Cumulative", cumsum(prop), "numeric")
)))
if (k >= 2) {
pick <- chart_rows(length(rows))
charts[[2]] <- cs_chart("map", "biplot", "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("Variable", c(rep("", length(pick)), labels), "categorical")
), note = "Numeric variables: correlations with the dimensions; categories: centers of their rows.")
}
cs_publish(list(
title = "Factor analysis of mixed data",
engine = cs_engine_info("FactoMineR", "nanoparquet"),
n = length(rows),
summary = sprintf("FAMD of %d numeric and %d categorical variables: the first dimension explains %.1f%% of the variance.",
length(NUMERIC), length(CATEGORICAL), 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 = "Proportion", type = "percent")),
rows = lapply(seq_along(eig), function(j) list(dim = j, eigenvalue = eig[j], proportion = prop[j]))),
list(key = "coordinates", title = "Variable coordinates",
columns = c(list(list(key = "variable", label = "Variable or 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(variable = 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"))
))
FAMD of 4 numeric and 3 categorical variables: the first dimension explains 46.7% of the variance.
To keep this page light, the plots are shown once, under the R tab.
Eigenvalues
| Dimension | Eigenvalue | Proportion |
|---|---|---|
| 1 | 4.201 | 46.7% |
| 2 | 1.998 | 22.2% |
| 3 | 1.408 | 15.6% |
| 4 | 0.6990 | 7.8% |
| 5 | 0.2885 | 3.2% |
| 6 | 0.1721 | 1.9% |
| 7 | 0.1001 | 1.1% |
| 8 | 0.0936 | 1.0% |
| 9 | 0.0398 | 0.4% |
Variable coordinates
| Variable or category | Dim 1 | Dim 2 | Dim 3 |
|---|---|---|---|
| bill_len | 0.6688 | 0.6606 | 0.0119 |
| bill_dep | −0.7201 | 0.3772 | 0.4858 |
| flipper_len | 0.9356 | 0.0577 | 0.1160 |
| body_mass | 0.9018 | 0.0189 | 0.3237 |
| species=Adelie | −1.717 | −0.7822 | 0.4722 |
| species=Chinstrap | −0.8937 | 2.397 | −0.7355 |
| species=Gentoo | 2.617 | −0.4098 | −0.1590 |
| island=Biscoe | 1.582 | −0.5655 | −0.0378 |
| island=Dream | −1.335 | 1.274 | −0.3946 |
| island=Torgersen | −1.992 | −1.372 | 1.164 |
| sex=female | −0.3897 | −0.5575 | −1.018 |
| sex=male | 0.3827 | 0.5476 | 0.9995 |
- 11 of 344 rows were left out because a value was missing.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Factor analysis of mixed data
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.famd 1.0.0 · spec d18ac443e7be524b
# Dataset: ml_penguins (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
NUMERIC = ["bill_len", "bill_dep", "flipper_len", "body_mass"]
CATEGORICAL = ["species", "island", "sex"]
LEVELS = {
"species": ["Adelie", "Chinstrap", "Gentoo"],
"island": ["Biscoe", "Dream", "Torgersen"],
"sex": ["female", "male"],
}
COLUMNS = list(dict.fromkeys(NUMERIC + CATEGORICAL))
df = pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=COLUMNS)
n_input = len(df)
warnings = []
rows = csembed.complete_rows(df, COLUMNS)
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].reset_index(drop=True)
# %% Factor analysis of mixed data (as FactoMineR::FAMD)
n_cat = sum(len({str(v) for v in data[c]}) for c in CATEGORICAL)
rank = min(len(NUMERIC) + n_cat - len(CATEGORICAL), len(rows) - 1)
k = min(3, rank)
res = csembed.famd(data, NUMERIC, CATEGORICAL, LEVELS, k)
eig = res["eig"][:rank]
prop = eig / eig.sum()
signs = csembed.canonical_signs(res["col"])
col_coord = res["col"] * signs
row_coord = res["row"] * signs
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-72273/discover.famd/penguins/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
labels = res["labels"]
values = {
"n": len(rows),
"n_numeric": len(NUMERIC),
"n_categorical": len(CATEGORICAL),
"n_dims": len(eig),
"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(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("Proportion of variance", prop, "numeric"),
"cumulative": cs.col("Cumulative", np.cumsum(prop), "numeric"),
})
]
if k >= 2:
pick = chart_rows(len(rows))
charts.append(cs.chart("map", "biplot", "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(labels), "categorical"),
"label": cs.col("Variable", [""] * len(pick) + labels, "categorical"),
}, note="Numeric variables: correlations with the dimensions; categories: centers of their rows."))
cs.publish({
"title": "Factor analysis of mixed data",
"engine": cs.engine_info("numpy", "pandas"),
"n": len(rows),
"summary": f"FAMD of {len(NUMERIC)} numeric and {len(CATEGORICAL)} categorical variables: the first dimension explains {prop[0]:.1%} of the variance.",
"tables": [
{"key": "variance", "title": "Eigenvalues", "columns": [
{"key": "dim", "label": "Dimension", "type": "integer"},
{"key": "eigenvalue", "label": "Eigenvalue", "type": "number"},
{"key": "proportion", "label": "Proportion", "type": "percent"}],
"rows": [{"dim": j + 1, "eigenvalue": eig[j], "proportion": prop[j]} for j in range(len(eig))]},
{"key": "coordinates", "title": "Variable coordinates", "columns": [{"key": "variable", "label": "Variable or category"}]
+ [{"key": f"d{j + 1}", "label": f"Dim {j + 1}", "type": "number"} for j in range(show)],
"rows": [dict({"variable": lab}, **{f"d{j + 1}": col_coord[i, j] for j in range(show)}) for i, lab in enumerate(labels)]},
],
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
})
On penguins, with three categorical and four numeric columns, the first two dimensions keep 68.9%. Species, island and the body measurements pull together on the first.
Pitfalls shared by all three
Read- Rare categories sit at the edges of the map and pull dimensions toward themselves. Pool very rare levels, or check how much each contributes.
- Row-to-column distances on a joint plot have no simple meaning; compare rows with rows and categories with categories.
- Order is lost. "Low, medium, high" become unordered categories.
- A dominant dimension can be an artifact, such as missing-value codes or the batch that collected the data.
Check: categorical maps
CheckpointCheck yourself
A 3 × 4 table of 400 counts has a chi-square statistic of 100. What is its total inertia?
Show the answer
Answer: 0.25
Total inertia is .
Check yourself
The CA map shows two categories far from the center. What can you conclude?
Show the answer
Answer: a
CA describes the residuals from independence. Rare categories can look extreme on the map, so check counts and test separately.
Check yourself
Five categorical columns with fifteen categories in all. What is MCA's total inertia, whatever the data?
Show the answer
Answer: 2
.
Check yourself
MCA's first dimension holds only 12% of the raw inertia. Does that mean the map is useless?
Show the answer
Answer: a
Part of MCA's inertia comes from coding each column as several indicators. Benzécri or Greenacre adjustments remove that.
Check yourself
Why not code a categorical column as 1, 2, 3 and run ordinary PCA, instead of FAMD?
Show the answer
Answer: a
"Island 3" is not three times "island 1". FAMD's indicators and frequency weights let categories contribute without a fake scale.
Check yourself
A category held by 3 of 2,000 rows dominates the second FAMD dimension. What should you check first?
Show the answer
Answer: a
Frequency weighting gives rare categories large influence. Pool or inspect them before naming a dimension after one.
Recap
Recap- CA is an SVD of standardized residuals from independence; total inertia is .
- MCA applies CA to indicators; its total inertia is fixed by the category counts, so raw shares run low.
- FAMD balances numbers and categories; in all three, rare levels and row-to-column distances need care.
Concepts in this lesson