CDiscover · discover.lca
Latent class analysis
Which hidden types of respondent explain the patterns in these categorical answers?
A mixture model for categorical items: each latent class has its own probability for every answer to every item, and within a class the items are independent (local independence). Fitted by EM from host-drawn starting responsibilities with poLCA's updates. Each row gets its most probable class and the probability of each class; the item-response table says what each class tends to answer. BIC, ICL and entropy R² compare numbers of classes; with complete rows, G² and χ² test the model against the observed answer patterns. Missing answers either drop the row or are left out of that item only.
A real result
Example “Survey three classes”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
3-class model on 5 items and 350 rows: log-likelihood -1354.2, BIC 2843.1, entropy R² 0.55.
- Classes
- 3
- BIC
- 2843.08
- Entropy R²
- 0.5523
Plots
View data
| Class | Answer | Probability |
|---|---|---|
| 1 | trust_news: low | 0.7448 |
| 2 | trust_news: low | 0.3781 |
| 3 | trust_news: low | 0.0737 |
| 1 | trust_news: medium | 0.1702 |
| 2 | trust_news: medium | 0.4062 |
| 3 | trust_news: medium | 0.2985 |
| 1 | trust_news: high | 0.0850 |
| 2 | trust_news: high | 0.2158 |
| 3 | trust_news: high | 0.6278 |
| 1 | votes: never | 0.6579 |
| 2 | votes: never | 0.3522 |
| 3 | votes: never | 0.0710 |
| 1 | votes: sometimes | 0.2243 |
| 2 | votes: sometimes | 0.4399 |
| 3 | votes: sometimes | 0.1593 |
| 1 | votes: always | 0.1177 |
| 2 | votes: always | 0.2078 |
| 3 | votes: always | 0.7696 |
| 1 | volunteers: no | 0.9074 |
| 2 | volunteers: no | 0.7851 |
| 3 | volunteers: no | 0.2489 |
| 1 | volunteers: yes | 0.0926 |
| 2 | volunteers: yes | 0.2149 |
| 3 | volunteers: yes | 0.7511 |
| 1 | donates: no | 1.0000 |
| 2 | donates: no | 0.5189 |
| 3 | donates: no | 0.2944 |
| 1 | donates: yes | 1.922e-6 |
| 2 | donates: yes | 0.4811 |
| 3 | donates: yes | 0.7056 |
| 1 | reads_local: no | 0.6968 |
| 2 | reads_local: no | 0.4231 |
| 3 | reads_local: no | 0.1737 |
| 1 | reads_local: yes | 0.3032 |
| 2 | reads_local: yes | 0.5769 |
| 3 | reads_local: yes | 0.8263 |
View data
| Center | Class | PC1 (34%) | PC2 (14%) |
|---|---|---|---|
| false | 2 | −0.3023 | −0.7591 |
| false | 1 | −0.2578 | 0.7053 |
| false | 1 | −1.068 | −0.1659 |
| false | 3 | 0.6470 | 0.4327 |
| false | 1 | −1.217 | −0.3262 |
| false | 1 | −0.2578 | 0.7053 |
| false | 1 | −1.432 | −0.3006 |
| false | 3 | 0.3887 | −0.9873 |
| false | 2 | −0.5028 | −0.3857 |
| false | 3 | 0.9973 | 0.2385 |
| false | 3 | 1.013 | −0.0278 |
| false | 2 | −0.4595 | 1.060 |
| false | 2 | −0.3772 | −0.3941 |
| false | 1 | −1.217 | −0.3262 |
| false | 1 | −1.432 | −0.3006 |
| false | 1 | −0.6081 | 0.8996 |
| false | 3 | 0.9973 | 0.2385 |
| false | 1 | −0.2578 | 0.7053 |
| false | 2 | 0.0987 | 0.4051 |
| false | 3 | 1.704 | −0.2560 |
| false | 3 | 0.1881 | −0.6140 |
| false | 3 | 1.704 | −0.2560 |
| false | 3 | 1.704 | −0.2560 |
| false | 1 | −1.432 | −0.3006 |
| false | 1 | −1.432 | −0.3006 |
| false | 3 | 1.140 | −0.0174 |
| false | 1 | −0.8231 | 0.9252 |
| false | 1 | −0.8676 | −0.5392 |
| false | 1 | −1.432 | −0.3006 |
| false | 1 | −0.6081 | 0.8996 |
| false | 2 | −0.1609 | −1.034 |
| false | 2 | 0.6628 | 0.1664 |
| false | 2 | −0.1164 | 0.4307 |
| false | 1 | −1.217 | −0.3262 |
| false | 2 | 0.1058 | 0.8401 |
| false | 2 | −0.4595 | 1.060 |
| false | 1 | −1.432 | −0.3006 |
| false | 1 | −1.217 | −0.3262 |
| false | 3 | 0.6470 | 0.4327 |
| false | 1 | −0.8231 | 0.9252 |
| false | 3 | 1.704 | −0.2560 |
| false | 1 | −1.432 | −0.3006 |
| false | 2 | −0.3614 | −0.6604 |
| false | 3 | 0.5313 | −1.243 |
| false | 1 | −0.1322 | 0.6969 |
| false | 1 | −1.217 | −0.3262 |
| false | 1 | −0.8664 | −0.5205 |
| false | 1 | −1.068 | −0.1659 |
| false | 2 | 0.0541 | −1.059 |
| false | 1 | −0.6081 | 0.8996 |
| false | 3 | 1.503 | 0.1173 |
| false | 2 | 0.4477 | 0.1921 |
| false | 2 | −0.1164 | 0.4307 |
| false | 3 | 1.013 | −0.0278 |
| false | 3 | 0.7968 | 0.6118 |
| false | 3 | 1.704 | −0.2560 |
| false | 2 | 0.2472 | 0.5654 |
| false | 1 | −1.217 | −0.3262 |
| false | 2 | −0.1609 | −1.034 |
| false | 3 | 1.354 | −0.0618 |
First 60 of 353 rows.
Classes
| Class | Size | Share (by membership) |
|---|---|---|
| 1 | 124 | 31.1% |
| 2 | 114 | 35.8% |
| 3 | 112 | 33.1% |
Item-response probabilities
| Item | Answer | Class 1 | Class 2 | Class 3 |
|---|---|---|---|---|
| trust_news | low | 74.5% | 37.8% | 7.4% |
| trust_news | medium | 17.0% | 40.6% | 29.8% |
| trust_news | high | 8.5% | 21.6% | 62.8% |
| votes | never | 65.8% | 35.2% | 7.1% |
| votes | sometimes | 22.4% | 44.0% | 15.9% |
| votes | always | 11.8% | 20.8% | 77.0% |
| volunteers | no | 90.7% | 78.5% | 24.9% |
| volunteers | yes | 9.3% | 21.5% | 75.1% |
| donates | no | 100.0% | 51.9% | 29.4% |
| donates | yes | 0.0% | 48.1% | 70.6% |
| reads_local | no | 69.7% | 42.3% | 17.4% |
| reads_local | yes | 30.3% | 57.7% | 82.6% |
- 50 of 400 rows were left out because an item was missing.
3-class model on 5 items and 350 rows: log-likelihood -1354.2, BIC 2843.1, entropy R² 0.55.
- Classes
- 3
- BIC
- 2843.08
- Entropy R²
- 0.5523
To keep this page light, the plots are shown once, under the R tab.
Classes
| Class | Size | Share (by membership) |
|---|---|---|
| 1 | 124 | 31.1% |
| 2 | 114 | 35.8% |
| 3 | 112 | 33.1% |
Item-response probabilities
| Item | Answer | Class 1 | Class 2 | Class 3 |
|---|---|---|---|---|
| trust_news | low | 74.5% | 37.8% | 7.4% |
| trust_news | medium | 17.0% | 40.6% | 29.8% |
| trust_news | high | 8.5% | 21.6% | 62.8% |
| votes | never | 65.8% | 35.2% | 7.1% |
| votes | sometimes | 22.4% | 44.0% | 15.9% |
| votes | always | 11.8% | 20.8% | 77.0% |
| volunteers | no | 90.7% | 78.5% | 24.9% |
| volunteers | yes | 9.3% | 21.5% | 75.1% |
| donates | no | 100.0% | 51.9% | 29.4% |
| donates | yes | 0.0% | 48.1% | 70.6% |
| reads_local | no | 69.7% | 42.3% | 17.4% |
| reads_local | yes | 30.3% | 57.7% | 82.6% |
- 50 of 400 rows were left out because an item was missing.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Survey three classesw5_lca · features: trust_news, votes, volunteers, donates, reads_local · label: profile
- Survey available answersw5_lca · features: trust_news, votes, volunteers, donates, reads_local
- Survey two classesw5_lca · features: trust_news, votes, volunteers, donates, reads_local
- Mass survey habitss1_survey · features: writing_hand, fold, clap, exercise, smoke · label: sex
- Baskets booleanml_baskets · features: bread, milk, eggs, butter, cereal, coffee · id: basket
- Degenerate constantw5_lca · features: trust_news, votes, volunteers, donates, reads_local · label: profile
- Degenerate all naw5_lca · features: trust_news, votes, volunteers, donates, reads_local · label: profile
- Degenerate n3w5_lca · features: trust_news, votes, volunteers, donates, reads_local · label: profile
In the guides
Where it sits in the decision guides
- Clustering (k-means, hierarchical) · DS & ML Decision Guide · Discover — find structure without labels
What you need
- Itemscategorical / boolean · 2–50 columns
- Categorical or yes/no items, such as survey questions (each with at most 20 answers).
- Known groupscategorical / boolean · 0–1 column
- Optional — compared with the classes (adjusted Rand index, AMI, NMI); never used to fit.
- Row labelscategorical / numeric · 0–1 column
- Optional names shown on the chart points.
Choices you make
model
- Classes (k)default 3
Number of latent classes.
- Startsdefault 10
Independent EM runs; the one with the highest log-likelihood wins (latent class models often have local optima).
Advanced
- Maximum iterationsdefault 1000
Upper limit on EM iterations. Raise it if the fit warns that it did not converge.
- Convergence tolerancedefault 1e-8
Stop when the mean log-likelihood changes by less than this.
preprocess
- Missing answersdefault drop
Leave out rows with any missing answer, or keep the answers each row has.
- Leave the row out(default) — Uses complete rows only; G² and χ² are reported. The clean choice when few answers are missing.
- Use the answers each row has — Each item's part of the likelihood uses the rows that answered it (missing at random), as poLCA does with na.rm = FALSE.
What it reports
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- n_used
- How many independent units the analysis used; it sets precision and power.
- n_noise
- How many independent units the analysis used; it sets precision and power.
- n_par
- How many numbers the mixture estimates; BIC, AIC and ICL charge for each one.
- loglik
- The logarithm of the likelihood; higher (less negative) means the model fits the data better.
- bic
- Like AIC but with a stronger penalty for parameters as n grows; favors simpler models.
- aic
- A model score balancing fit against complexity; lower is better, and only differences matter.
- icl
- BIC plus a penalty for fuzzy assignments; lower is better, and it prefers components that form well-separated clusters.
- entropy_r2
- 1 minus the responsibilities' entropy over its maximum: 1 means every row belongs to one component with near certainty, 0 means coin flips.
- gsq
- How far the observed answer patterns are from the patterns the model expects; small relative to the residual df means a good fit.
- chisq
- How far the observed answer patterns are from the patterns the model expects; small relative to the residual df means a good fit.
- resid_df
- How far the observed answer patterns are from the patterns the model expects; small relative to the residual df means a good fit.
- silhouette
- How well each point sits in its cluster compared with the nearest other cluster, from −1 to 1.
- calinski_harabasz
- Between-cluster spread over within-cluster spread. Higher means tighter, better-separated clusters.
- davies_bouldin
- How much each cluster overlaps its most similar neighbor, on average. Lower is better; 0 is the floor.
Per group, level or term: size[<cluster>], weight[<cluster>], prob[<cluster>,<item>: <answer>], ari, ami, nmi
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses numpy; R uses codesplashr.
Default traps between the two languages
- Both engines run the latent class twin (codesplash.ml.lca ↔ codesplashr::cs_lca_*) from the same host-drawn responsibilities, with poLCA's EM updates and the same stopping rule; answer patterns for G² are sorted the same way in both.
The exact script CodeSplash ran for example “Survey three classes” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Latent class analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.lca 1.0.0 · spec 90b3dbce383d12e1
# Dataset: w5_lca (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
import codesplash as cs
from codesplash import ml as csml
from codesplash.errors import check_rows
from codesplash.ml import cluster as csc
from codesplash.ml import lca as cslca
from codesplash.stats.rng import Rng
# %% Data
ITEMS = ["trust_news", "votes", "volunteers", "donates", "reads_local"]
LABEL = "profile" # known groups (external validation only)
ROW_ID = None # row labels for charts
SEED = 42
K = 3
KINDS = {
"trust_news": "categorical",
"votes": "categorical",
"volunteers": "categorical",
"donates": "categorical",
"reads_local": "categorical",
}
LEVELS = {
"trust_news": ["low", "medium", "high"],
"votes": ["never", "sometimes", "always"],
"volunteers": ["no", "yes"],
"donates": ["no", "yes"],
"reads_local": ["no", "yes"],
}
df = pd.read_parquet("tests/parity/fixtures/w5_lca.parquet", columns=list(dict.fromkeys(ITEMS + [c for c in (LABEL, ROW_ID) if c])))
n_input = len(df)
codes_all, _ = cslca.encode(df, ITEMS, KINDS, LEVELS)
answered = (codes_all >= 0).sum(axis=1)
MISSING = "drop"
keep = answered == len(ITEMS) if MISSING == "drop" else answered > 0
rows = np.flatnonzero(keep)
frame = df.iloc[rows]
warnings = []
if len(rows) < n_input:
why = "an item was missing" if MISSING == "drop" else "every item was missing"
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because {why}.")
check_rows(len(rows), K + 1, f"A {K}-class model")
codes, level_names = cslca.encode(frame, ITEMS, KINDS, LEVELS)
cslca.check_items(codes, level_names, ITEMS)
L = [len(v) for v in level_names]
truth = frame[LABEL].astype("object").to_numpy() if LABEL else None
out = csml.out_dir("target/academy-parity/run-52084/discover.lca/survey_three_classes/out-python")
# %% Latent classes
rng = Rng(SEED) # shared stream: identical starting responsibilities in Python and R
best = cslca.fit(codes, L, K, rng, n_init=10, tol=1e-8, max_iter=1000)
if not best["converged"]:
warnings.append("EM stopped at the iteration limit before converging.")
resp = best["resp"]
raw = best["labels"]
labels = csc.canonical(raw)
ids = [int(c) for c in sorted(set(labels.tolist()))]
comp = {int(labels[np.flatnonzero(raw == j)[0]]): j for j in range(K) if np.any(raw == j)}
values = {"n_used": len(rows), "k": len(ids), "n_noise": 0, "n_par": int(best["n_par"])}
values["loglik"] = best["loglik"]
values.update(cslca.criteria(best["loglik"], best["n_par"], len(rows), resp))
if MISSING == "drop":
values.update(cslca.goodness_of_fit(codes, best["params"], L))
else:
values.update({"gsq": None, "chisq": None, "resid_df": None})
extra = {}
for c in ids:
j = comp[c]
values[f"weight[{c}]"] = float(best["params"]["weights"][j])
extra[f"membership_{c}"] = resp[:, j]
extra["probability"] = resp.max(axis=1)
for c, m in csc.sizes(labels).items():
values[f"size[{c}]"] = m
# %% Item-response probabilities, validation on the answer indicators
names = [f"{f}: {lv}" for f, lvs in zip(ITEMS, level_names) for lv in lvs]
X = np.zeros((len(rows), len(names)))
pos = 0
for j, lvs in enumerate(level_names):
for r in range(len(lvs)):
X[:, pos] = (codes[:, j] == r).astype(np.float64)
pos += 1
centers = np.array([np.concatenate([best["params"]["probs"][j][comp[c]] for j in range(len(ITEMS))]) for c in ids])
prob_rows = []
pos = 0
for j, (f, lvs) in enumerate(zip(ITEMS, level_names)):
for r, lv in enumerate(lvs):
row = {"item": f, "answer": lv}
for i, c in enumerate(ids):
v = float(centers[i, pos])
values[f"prob[{c},{f}: {lv}]"] = v
row[f"class_{c}"] = v
prob_rows.append(row)
pos += 1
check = csc.validation(X, labels, truth, cap=3000, seed=SEED)
widths, picked = check.pop("_widths")
values.update(check)
tables = [
{
"key": "classes",
"title": "Classes",
"columns": [{"key": "cluster", "label": "Class", "type": "integer"}, {"key": "size", "label": "Size", "type": "integer"},
{"key": "share", "label": "Share (by membership)", "type": "percent"}],
"rows": [{"cluster": c, "size": int(np.sum(labels == c)), "share": float(best["params"]["weights"][comp[c]])} for c in ids],
},
{
"key": "item_probabilities",
"title": "Item-response probabilities",
"columns": [{"key": "item", "label": "Item"}, {"key": "answer", "label": "Answer"}]
+ [{"key": f"class_{c}", "label": f"Class {c}", "type": "percent"} for c in ids],
"rows": prob_rows,
},
]
# %% Labels file and charts
path = csc.write_labels(out, rows, labels, **extra)
charts = [cs.chart(
"item_probabilities", "matrix-heatmap", "Probability of each answer by class",
{
"row": cs.col("Answer", [n for n in names for _ in ids], "categorical", names),
"col": cs.col("Class", [str(c) for _ in names for c in ids], "categorical", [str(c) for c in ids]),
"value": cs.col("Probability", [float(centers[i, p]) for p in range(len(names)) for i in range(len(ids))], "numeric"),
},
controls={"scale": "sequential"},
)]
P, C, axes = csc.project2(X, centers, names)
show = csc.even_sample(len(rows))
xs, ys = list(P[show, 0]) + list(C[:, 0]), list(P[show, 1]) + list(C[:, 1])
cl = [str(c) for c in labels[show]] + [str(c) for c in ids]
cent = [False] * len(show) + [True] * len(ids)
lab = None
if ROW_ID:
lab = [str(v) for v in frame[ROW_ID].astype("object").to_numpy()[show]] + [f"center {c}" for c in ids]
charts.append(cs.chart(
"clusters", "cluster-scatter", "Classes on the answer indicators",
{
"x": cs.col(axes[0], xs, "numeric"),
"y": cs.col(axes[1], ys, "numeric"),
"cluster": cs.col("Class", cl, "categorical", levels=[str(c) for c in ids]),
"centroid": cs.col("Center", cent, "boolean"),
"label": cs.col("Row", lab, "categorical") if lab is not None else None,
},
note=None if len(show) == len(rows) else f"{len(show):,} of {len(rows):,} rows shown.",
))
# %% Result
summary = (
f"{len(ids)}-class model on {len(ITEMS)} items and {len(rows):,} rows: log-likelihood {values['loglik']:.1f}, "
f"BIC {values['bic']:.1f}, entropy R² {values['entropy_r2']:.2f}."
)
cs.publish({
"title": "Latent class analysis",
"engine": cs.engine_info("numpy", "pandas"),
"n": len(rows),
"summary": summary,
"statistics": [
{"key": "k", "label": "Classes", "value": len(ids), "format": "integer"},
{"key": "bic", "label": "BIC", "value": values["bic"]},
{"key": "entropy_r2", "label": "Entropy R²", "value": values["entropy_r2"]},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
"artifacts": [{"key": "labels", "path": path, "format": "parquet"}],
"model": {"kind": "clusterer", "features": names, "params": {
"k": 3,
"n_init": 10,
"max_iter": 1000,
"tol": 1e-8,
"missing": "drop",
}},
})
The exact script CodeSplash ran for example “Survey three classes” · R version 4.5.1 (2025-06-13)
# Latent class analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.lca 1.0.0 · spec 90b3dbce383d12e1
# Dataset: w5_lca (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
ITEMS <- c("trust_news", "votes", "volunteers", "donates", "reads_local")
LABEL <- "profile" # known groups (external validation only)
ROW_ID <- NULL # row labels for charts
SEED <- 42
K <- 3
KINDS <- list(
trust_news = "categorical",
votes = "categorical",
volunteers = "categorical",
donates = "categorical",
reads_local = "categorical"
)
LEVELS <- list(
trust_news = c("low", "medium", "high"),
votes = c("never", "sometimes", "always"),
volunteers = c("no", "yes"),
donates = c("no", "yes"),
reads_local = c("no", "yes")
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/w5_lca.parquet", col_select = unique(c(ITEMS, LABEL, ROW_ID))))
n_input <- nrow(df)
enc_all <- cs_lca_encode(df, ITEMS, KINDS, LEVELS)
answered <- rowSums(enc_all$codes >= 0)
MISSING <- "drop"
keep <- if (MISSING == "drop") answered == length(ITEMS) else answered > 0
rows <- which(keep) - 1L
frame <- df[rows + 1L, , drop = FALSE]
warnings <- list()
if (length(rows) < n_input) {
why <- if (MISSING == "drop") "an item was missing" else "every item was missing"
warnings <- c(warnings, sprintf("%d of %d rows were left out because %s.", n_input - length(rows), n_input, why))
}
cs_check_rows(length(rows), K + 1L, sprintf("A %d-class model", K))
enc <- cs_lca_encode(frame, ITEMS, KINDS, LEVELS)
codes <- enc$codes
level_names <- enc$levels
cs_lca_check_items(codes, level_names, ITEMS)
L <- vapply(level_names, length, integer(1))
truth <- if (!is.null(LABEL)) as.character(frame[[LABEL]]) else NULL
out <- cs_ml_out_dir("target/academy-parity/run-52084/discover.lca/survey_three_classes/out-r")
# %% Latent classes
rng <- cs_rng(SEED) # shared stream: identical starting responsibilities in Python and R
best <- cs_lca_fit(codes, L, K, rng, n_init = 10, tol = 1e-8, max_iter = 1000)
if (!best$converged) warnings <- c(warnings, "EM stopped at the iteration limit before converging.")
resp <- best$resp
raw <- best$labels
labels <- cs_ml_canonical(raw)
ids <- sort(unique(labels))
comp <- integer(0)
for (j in seq_len(K)) if (any(raw == j - 1L)) comp[as.character(labels[which(raw == j - 1L)[1]])] <- j
values <- list(n_used = length(rows), k = length(ids), n_noise = 0L, n_par = as.integer(best$n_par))
values$loglik <- best$loglik
values <- c(values, cs_mx_criteria(best$loglik, best$n_par, length(rows), resp))
if (MISSING == "drop") {
values <- c(values, cs_lca_goodness_of_fit(codes, best$params, L))
} else {
values["gsq"] <- list(NULL); values["chisq"] <- list(NULL); values["resid_df"] <- list(NULL)
}
extra <- list()
for (c in ids) {
j <- comp[[as.character(c)]]
values[[sprintf("weight[%d]", c)]] <- best$params$weights[j]
extra[[sprintf("membership_%d", c)]] <- resp[, j]
}
extra$probability <- apply(resp, 1, max)
sz <- cs_ml_cluster_sizes(labels)
for (c in names(sz)) values[[sprintf("size[%s]", c)]] <- sz[[c]]
# %% Item-response probabilities, validation on the answer indicators
names_ <- unlist(lapply(seq_along(ITEMS), function(j) paste0(ITEMS[j], ": ", level_names[[j]])))
X <- matrix(0, length(rows), length(names_))
pos <- 0L
for (j in seq_along(level_names)) for (r in seq_along(level_names[[j]])) {
pos <- pos + 1L
X[, pos] <- as.numeric(codes[, j] == r - 1L)
}
centers <- t(vapply(ids, function(c) unlist(lapply(seq_along(ITEMS), function(j) best$params$probs[[j]][comp[[as.character(c)]], ])), numeric(length(names_))))
if (length(ids) == 1L) centers <- matrix(centers, nrow = 1L)
prob_rows <- list()
pos <- 0L
for (j in seq_along(ITEMS)) for (r in seq_along(level_names[[j]])) {
pos <- pos + 1L
row_ <- list(item = ITEMS[j], answer = level_names[[j]][r])
for (i in seq_along(ids)) {
v <- centers[i, pos]
values[[sprintf("prob[%d,%s: %s]", ids[i], ITEMS[j], level_names[[j]][r])]] <- v
row_[[sprintf("class_%d", ids[i])]] <- v
}
prob_rows[[length(prob_rows) + 1L]] <- row_
}
check <- cs_ml_cluster_validation(X, labels, truth, cap = 3000, seed = SEED)
check$.widths <- NULL
values <- c(values, check)
tables <- list(
list(key = "classes", title = "Classes",
columns = list(list(key = "cluster", label = "Class", type = "integer"), list(key = "size", label = "Size", type = "integer"),
list(key = "share", label = "Share (by membership)", type = "percent")),
rows = lapply(ids, function(c) list(cluster = c, size = sum(labels == c), share = best$params$weights[comp[[as.character(c)]]]))),
list(key = "item_probabilities", title = "Item-response probabilities",
columns = c(list(list(key = "item", label = "Item"), list(key = "answer", label = "Answer")),
lapply(ids, function(c) list(key = sprintf("class_%d", c), label = sprintf("Class %d", c), type = "percent"))),
rows = prob_rows)
)
# %% Labels file and charts
path <- do.call(cs_ml_write_labels, c(list(out, rows, labels), extra))
charts <- list(cs_chart(
"item_probabilities", "matrix-heatmap", "Probability of each answer by class",
list(row = cs_col("Answer", rep(names_, each = length(ids)), "categorical", names_),
col = cs_col("Class", rep(as.character(ids), times = length(names_)), "categorical", as.character(ids)),
value = cs_col("Probability", as.numeric(centers), "numeric")),
controls = list(scale = "sequential")
))
pr <- cs_ml_project2(X, centers, names_)
show <- cs_ml_even_sample(length(rows))
xs <- c(pr$P[show + 1L, 1], pr$C[, 1]); ys <- c(pr$P[show + 1L, 2], pr$C[, 2])
cl <- c(as.character(labels[show + 1L]), as.character(ids))
cent <- c(rep(FALSE, length(show)), rep(TRUE, length(ids)))
lab <- if (!is.null(ROW_ID)) c(as.character(frame[[ROW_ID]])[show + 1L], sprintf("center %d", ids)) else NULL
charts[[length(charts) + 1L]] <- cs_chart(
"clusters", "cluster-scatter", "Classes on the answer indicators",
list(x = cs_col(pr$labels[1], xs, "numeric"), y = cs_col(pr$labels[2], ys, "numeric"),
cluster = cs_col("Class", cl, "categorical", levels = as.character(ids)),
centroid = cs_col("Center", cent, "boolean"),
label = if (!is.null(lab)) cs_col("Row", lab, "categorical")),
note = if (length(show) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(show), big.mark = ","), format(length(rows), big.mark = ","))
)
# %% Result
summary <- sprintf("%d-class model on %d items and %s rows: log-likelihood %.1f, BIC %.1f, entropy R² %.2f.",
length(ids), length(ITEMS), format(length(rows), big.mark = ","), values$loglik, values$bic, values$entropy_r2)
cs_publish(list(
title = "Latent class analysis",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = summary,
statistics = list(list(key = "k", label = "Classes", value = length(ids), format = "integer"),
list(key = "bic", label = "BIC", value = values$bic),
list(key = "entropy_r2", label = "Entropy R²", value = values$entropy_r2)),
tables = tables,
values = values,
charts = charts,
warnings = warnings,
artifacts = list(list(key = "labels", path = path, format = "parquet")),
model = list(kind = "clusterer", features = I(names_), params = list(
k = 3,
n_init = 10,
max_iter = 1000,
tol = 1e-8,
missing = "drop"
))
))
Sources
- Lazarsfeld PF, Henry NW (1968). Latent structure analysis. Houghton Mifflin.
- Linzer DA, Lewis JB (2011). poLCA: an R package for polytomous variable latent class analysis. Journal of Statistical Software 42(10):1–29.
- Collins LM, Lanza ST (2010). Latent class and latent transition analysis. Wiley.
From the CodeSplash method registry · discover.lca v1.0.0.