Independent components and common factors
ICA looks for directions whose values are statistically independent, which unmixes signals. Factor analysis explains correlations with a few shared factors plus a separate noise for each column. Same linear form, different goals.
What runs in CodeSplash
- REP007Independent component analysis (ICA/FastICA) Runs in CodeSplash
- REP008Exploratory factor analysis Runs in CodeSplash
- Independent component analysis Verified in Python and R
- Exploratory factor analysis Verified in Python and R
You will be able to
- Explain why ICA needs non-Gaussian sources and what it can't identify (scale, sign, order)
- Write the factor model and contrast its noise with probabilistic PCA's
- Read communalities and rotations, and say what a factor solution does not prove
Unmixing: the cocktail party
ReadFour microphones each record a different blend of three voices. ICAIndependent component analysisUnmixes variables into statistically independent, non-Gaussian sources and the matrix that mixed them. assumes
an unknown mixing matrix applied to sources whose values are statistically independent, and tries to recover .
Uncorrelated isn't enough: PCA already gives uncorrelated components, and any rotation of whitened data stays uncorrelated. Independence is stronger, and it pins down the rotation.
Why non-Gaussian
ReadMixing independent signals makes the mixture more Gaussian (the central limit theorem at work). So ICA searches for directions whose projections are as non-Gaussian as possible.
FastICA first whitens the data, then rotates to maximize an approximation of negentropy, often through of the projection. A Gaussian source has no non-Gaussianity to find, so at most one source may be Gaussian.
ICA on mixed signals
ReadICA unmixed 4 variables into 3 independent components; component 1 has excess kurtosis -1.98.
- Components
- 3
- IC1 excess kurtosis
- −1.982
Plots
View data
| Group | IC1 | IC2 |
|---|---|---|
| All rows | −0.0626 | −0.1807 |
| All rows | 0.9943 | −0.1632 |
| All rows | 0.9506 | −0.1182 |
| All rows | 0.9374 | −0.0637 |
| All rows | 0.9663 | 0.0037 |
| All rows | 0.9538 | 0.0578 |
| All rows | 0.9304 | 0.1079 |
| All rows | 0.9602 | 0.1742 |
| All rows | 0.9480 | 0.2266 |
| All rows | 0.9826 | 0.2930 |
| All rows | 0.9548 | 0.3390 |
| All rows | 0.8812 | 0.3697 |
| All rows | 0.9183 | 0.4341 |
| All rows | 0.9430 | 0.4935 |
| All rows | 0.9527 | 0.5470 |
| All rows | 0.9412 | 0.5927 |
| All rows | 0.9143 | 0.6321 |
| All rows | 0.9611 | 0.6933 |
| All rows | 0.9078 | 0.7216 |
| All rows | 0.9315 | 0.7724 |
| All rows | 0.9409 | 0.8172 |
| All rows | 0.8973 | 0.8436 |
| All rows | 0.9276 | 0.8915 |
| All rows | 0.9656 | 0.9399 |
| All rows | 0.9203 | 0.9603 |
| All rows | 0.9358 | 0.9979 |
| All rows | 0.9364 | 1.029 |
| All rows | 0.9119 | 1.050 |
| All rows | 0.9556 | 1.090 |
| All rows | 0.9717 | 1.120 |
| All rows | 0.9067 | 1.121 |
| All rows | 0.9201 | 1.146 |
| All rows | 0.9561 | 1.175 |
| All rows | 0.9157 | 1.178 |
| All rows | 0.8985 | 1.186 |
| All rows | 0.9431 | 1.211 |
| All rows | 0.9160 | 1.211 |
| All rows | 0.9269 | 1.220 |
| All rows | 0.9260 | 1.224 |
| All rows | 0.8995 | 1.217 |
| All rows | 0.9245 | 1.224 |
| All rows | 0.8838 | 1.209 |
| All rows | 0.9114 | 1.212 |
| All rows | 0.9363 | 1.212 |
| All rows | 0.9243 | 1.198 |
| All rows | 0.8825 | 1.172 |
| All rows | 0.9183 | 1.169 |
| All rows | 0.8887 | 1.142 |
| All rows | 0.9133 | 1.131 |
| All rows | 0.9456 | 1.119 |
| All rows | 0.9373 | 1.093 |
| All rows | 0.9029 | 1.056 |
| All rows | 0.9610 | 1.047 |
| All rows | −1.106 | 1.114 |
| All rows | −1.078 | 1.091 |
| All rows | −1.127 | 1.042 |
| All rows | −1.074 | 1.022 |
| All rows | −1.068 | 0.9865 |
| All rows | −1.113 | 0.9329 |
| All rows | −1.075 | 0.9035 |
First 60 of 400 rows.
Independent components
| Component | Excess kurtosis | Shape |
|---|---|---|
| 1 | −1.982 | flat / bimodal |
| 2 | −1.353 | flat / bimodal |
| 3 | 1.065 | peaked / heavy-tailed |
Mixing matrix (how much each component feeds each variable)
| Variable | IC1 | IC2 | IC3 |
|---|---|---|---|
| ch1 | 0.5575 | 0.6745 | 1.297 |
| ch2 | 2.030 | 0.4549 | 0.8220 |
| ch3 | 0.3570 | 0.8197 | 0.6863 |
| ch4 | 1.031 | 0.2788 | 1.200 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Independent component analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ica 1.0.0 · spec 75b76cce380f11b3
# Dataset: ds1_mixed (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
chart_rows <- function(n, cap = 2000) if (n <= cap) seq_len(n) else unique(round(seq(1, n, length.out = cap)))
# %% Data
FEATURES <- c("ch1", "ch2", "ch3", "ch4")
LABEL <- NULL
SEED <- 42
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ds1_mixed.parquet", col_select = unique(c(FEATURES, LABEL))))
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))
}
if (length(rows) < length(FEATURES) + 2) stop("ICA needs more rows than variables.")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
# %% Independent components (FastICA twin: whitening, host start matrix, log-cosh contrast)
K <- 3
K <- if (is.null(K)) length(FEATURES) else min(as.integer(K), length(FEATURES))
fit <- cs_ml_fastica(X, K, SEED, max_iter = 200, tol = 0.0001)
S <- fit$sources; A <- fit$mixing; kurt <- fit$kurtosis
if (!fit$converged) {
warnings <- c(warnings, sprintf("FastICA did not converge in %d iterations (largest change %s); raise the iterations or ask for fewer components.",
fit$n_iter, format(signif(fit$lim, 2))))
}
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.ica/mixed_signals/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(K)) emb[[paste0("dim_", j)]] <- S[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
# %% Result
values <- list(n = length(rows), n_variables = length(FEATURES), n_components = K, n_iter = fit$n_iter, converged = as.integer(fit$converged))
for (j in seq_len(K)) {
values[[sprintf("kurtosis[%d]", j)]] <- kurt[j]
values[[sprintf("source_check[%d]", j)]] <- cs_ml_checksum(S[, j], rows)
for (i in seq_along(FEATURES)) values[[sprintf("mixing[%d:%s]", j, FEATURES[i])]] <- A[i, j]
}
shape_of <- function(k) if (k > 0.5) "peaked / heavy-tailed" else if (k < -0.5) "flat / bimodal" else "near Gaussian"
tables <- list(
list(key = "components", title = "Independent components",
columns = list(list(key = "component", label = "Component", type = "integer"),
list(key = "kurtosis", label = "Excess kurtosis", type = "number"),
list(key = "shape", label = "Shape")),
rows = lapply(seq_len(K), function(j) list(component = j, kurtosis = kurt[j], shape = shape_of(kurt[j])))),
list(key = "mixing", title = "Mixing matrix (how much each component feeds each variable)",
columns = c(list(list(key = "variable", label = "Variable")),
lapply(seq_len(K), function(j) list(key = paste0("ic", j), label = paste0("IC", j), type = "number"))),
rows = lapply(seq_along(FEATURES), function(i) {
r <- list(variable = FEATURES[i])
for (j in seq_len(K)) r[[paste0("ic", j)]] <- A[i, j]
r
}))
)
charts <- list()
if (K >= 2) {
pick <- chart_rows(length(rows))
groups <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
g <- as.character(df[[LABEL]][rows[pick] + 1L]); g[is.na(g)] <- "(missing)"; g
}
charts[[1]] <- cs_chart("map", "cluster-scatter", "Independent components 1 × 2", list(
x = cs_col("IC1", S[pick, 1], "numeric"),
y = cs_col("IC2", S[pick, 2], "numeric"),
cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ",")))
}
cs_publish(list(
title = "Independent component analysis",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = sprintf("ICA unmixed %d variables into %d independent components; component 1 has excess kurtosis %.2f.", length(FEATURES), K, kurt[1]),
statistics = list(list(key = "n_components", label = "Components", value = K, format = "integer"),
list(key = "kurtosis1", label = "IC1 excess kurtosis", value = kurt[1])),
tables = tables,
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))
ICA unmixed 4 variables into 3 independent components; component 1 has excess kurtosis -1.98.
- Components
- 3
- IC1 excess kurtosis
- −1.982
To keep this page light, the plots are shown once, under the R tab.
Independent components
| Component | Excess kurtosis | Shape |
|---|---|---|
| 1 | −1.982 | flat / bimodal |
| 2 | −1.353 | flat / bimodal |
| 3 | 1.065 | peaked / heavy-tailed |
Mixing matrix (how much each component feeds each variable)
| Variable | IC1 | IC2 | IC3 |
|---|---|---|---|
| ch1 | 0.5575 | 0.6745 | 1.297 |
| ch2 | 2.030 | 0.4549 | 0.8220 |
| ch3 | 0.3570 | 0.8197 | 0.6863 |
| ch4 | 1.031 | 0.2788 | 1.200 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Independent component analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ica 1.0.0 · spec 75b76cce380f11b3
# Dataset: ds1_mixed (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 discover_ext as dx
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 = ["ch1", "ch2", "ch3", "ch4"]
LABEL = None
SEED = 42
df = pd.read_parquet("tests/parity/fixtures/ds1_mixed.parquet", columns=list(dict.fromkeys(FEATURES + ([LABEL] if LABEL else []))))
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.")
if len(rows) < len(FEATURES) + 2:
raise ValueError("ICA needs more rows than variables.")
X = csembed.numeric_matrix(df, FEATURES, rows)
# %% Independent components (FastICA twin: whitening, host start matrix, log-cosh contrast)
K = 3
K = len(FEATURES) if K is None else min(int(K), len(FEATURES))
fit = dx.fastica(X, K, SEED, max_iter=200, tol=0.0001)
S, A, kurt = fit["sources"], fit["mixing"], fit["kurtosis"]
if not fit["converged"]:
warnings.append(f"FastICA did not converge in {fit['n_iter']} iterations (largest change {fit['lim']:.2g}); raise the iterations or ask for fewer components.")
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.ica/mixed_signals/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(K):
emb[f"dim_{j + 1}"] = S[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
# %% Result
values = {"n": len(rows), "n_variables": len(FEATURES), "n_components": K, "n_iter": fit["n_iter"], "converged": int(fit["converged"])}
for j in range(K):
values[f"kurtosis[{j + 1}]"] = float(kurt[j])
values[f"source_check[{j + 1}]"] = csembed.checksum(S[:, j], rows)
for i, f in enumerate(FEATURES):
values[f"mixing[{j + 1}:{f}]"] = float(A[i, j])
tables = [
{
"key": "components",
"title": "Independent components",
"columns": [
{"key": "component", "label": "Component", "type": "integer"},
{"key": "kurtosis", "label": "Excess kurtosis", "type": "number"},
{"key": "shape", "label": "Shape"},
],
"rows": [{"component": j + 1, "kurtosis": float(kurt[j]),
"shape": "peaked / heavy-tailed" if kurt[j] > 0.5 else ("flat / bimodal" if kurt[j] < -0.5 else "near Gaussian")} for j in range(K)],
},
{
"key": "mixing",
"title": "Mixing matrix (how much each component feeds each variable)",
"columns": [{"key": "variable", "label": "Variable"}] + [{"key": f"ic{j + 1}", "label": f"IC{j + 1}", "type": "number"} for j in range(K)],
"rows": [dict({"variable": f}, **{f"ic{j + 1}": float(A[i, j]) for j in range(K)}) for i, f in enumerate(FEATURES)],
},
]
charts = []
if K >= 2:
pick = chart_rows(len(rows))
groups = ["All rows"] * len(pick) if LABEL is None else [("(missing)" if pd.isna(v) else str(v)) for v in df[LABEL].iloc[rows[pick]]]
charts.append(cs.chart("map", "cluster-scatter", "Independent components 1 × 2", {
"x": cs.col("IC1", S[pick, 0], "numeric"),
"y": cs.col("IC2", S[pick, 1], "numeric"),
"cluster": cs.col(LABEL or "Group", groups, "categorical"),
}, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown."))
cs.publish({
"title": "Independent component analysis",
"engine": cs.engine_info("numpy", "pandas"),
"n": len(rows),
"summary": f"ICA unmixed {len(FEATURES)} variables into {K} independent components; component 1 has excess kurtosis {kurt[0]:.2f}.",
"statistics": [
{"key": "n_components", "label": "Components", "value": K, "format": "integer"},
{"key": "kurtosis1", "label": "IC1 excess kurtosis", "value": float(kurt[0])},
],
"tables": tables,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
})
Three components were unmixed from four channels in 3 iterations. Their excess kurtosis is −1.98, −1.35 and 1.07: two flat-topped sources (negative, like a square wave) and one spiky source (positive). A Gaussian would sit near 0.
What ICA can't tell you
Read- Scale and sign: for any diagonal , so a source can be doubled or flipped.
- Order: sources come out in no natural order; align them before comparing runs.
- Mixing model: delays, echoes or a nonlinear mix break .
Check recovery on mixtures you built, and stability across restarts.
Factor analysis: shared causes plus own noise
ReadFactor analysisFactor analysisExplains correlations among many items through a few unobserved factors. explains the correlations between columns with a few common factors:
The difference from probabilistic PCA is : each column gets its own noise variance (its uniqueness). The implied covariance is , so each column's variance splits into a communality (shared) and a uniqueness.
In the reference's example, a column with loadings and and uniqueness has variance 1.02: .
A three-factor solution
ReadKMO = .75; Bartlett's χ²(36) = 904.10, p < .001
- Factors
- 3
- Variance explained
- 54.0%
- KMO
- 0.7522
- RMSR
- 0.0191
Plots
View data
| Eigenvalue | Factor | Data |
|---|---|---|
| 3.216 | 1 | observed |
| 1.639 | 2 | observed |
| 1.365 | 3 | observed |
| 0.6989 | 4 | observed |
| 0.5843 | 5 | observed |
| 0.4997 | 6 | observed |
| 0.4731 | 7 | observed |
| 0.2860 | 8 | observed |
| 0.2377 | 9 | observed |
| 1.348 | 1 | simulated |
| 1.227 | 2 | simulated |
| 1.153 | 3 | simulated |
| 1.090 | 4 | simulated |
| 1.039 | 5 | simulated |
| 0.9746 | 6 | simulated |
| 0.9205 | 7 | simulated |
| 0.8605 | 8 | simulated |
| 0.8055 | 9 | simulated |
View data
| Factor | Text | Item | Loading |
|---|---|---|---|
| F1 | 0.20 | x1 | 0.1964 |
| F2 | 0.59 | x1 | 0.5916 |
| F3 | 0.03 | x1 | 0.0309 |
| F1 | 0.04 | x2 | 0.0430 |
| F2 | 0.51 | x2 | 0.5089 |
| F3 | -0.12 | x2 | −0.1223 |
| F1 | -0.06 | x3 | −0.0623 |
| F2 | 0.69 | x3 | 0.6859 |
| F3 | 0.02 | x3 | 0.0190 |
| F1 | 0.85 | x4 | 0.8461 |
| F2 | 0.02 | x4 | 0.0163 |
| F3 | 0.01 | x4 | 0.0077 |
| F1 | 0.89 | x5 | 0.8855 |
| F2 | -0.06 | x5 | −0.0646 |
| F3 | 0.01 | x5 | 0.0067 |
| F1 | 0.81 | x6 | 0.8053 |
| F2 | 0.08 | x6 | 0.0796 |
| F3 | -0.01 | x6 | −0.0130 |
| F1 | 0.04 | x7 | 0.0438 |
| F2 | -0.15 | x7 | −0.1523 |
| F3 | 0.74 | x7 | 0.7365 |
| F1 | -0.03 | x8 | −0.0340 |
| F2 | 0.13 | x8 | 0.1251 |
| F3 | 0.69 | x8 | 0.6865 |
| F1 | 0.03 | x9 | 0.0318 |
| F2 | 0.38 | x9 | 0.3823 |
| F3 | 0.46 | x9 | 0.4564 |
Assumptions
- Sample size — 301 cases for 9 items (33.4 per item).
- Sampling adequacy — KMO = 0.75; Bartlett χ²(36) = 904.1, p < .001.
- Communalities below 1 — Every communality is below 1.
- Convergence — Extraction converged in 137 iterations.
Pattern loadings (oblimin rotation)
| Item | F1 | F2 | F3 | h² | u² |
|---|---|---|---|---|---|
| x1 | 0.1964 | 0.5916 | 0.0309 | 0.4768 | 0.5232 |
| x2 | 0.0430 | 0.5089 | −0.1223 | 0.2552 | 0.7448 |
| x3 | −0.0623 | 0.6859 | 0.0190 | 0.4535 | 0.5465 |
| x4 | 0.8461 | 0.0163 | 0.0077 | 0.7279 | 0.2721 |
| x5 | 0.8855 | −0.0646 | 0.0067 | 0.7537 | 0.2463 |
| x6 | 0.8053 | 0.0796 | −0.0130 | 0.6914 | 0.3086 |
| x7 | 0.0438 | −0.1523 | 0.7365 | 0.5186 | 0.4814 |
| x8 | −0.0340 | 0.1251 | 0.6865 | 0.5202 | 0.4798 |
| x9 | 0.0318 | 0.3823 | 0.4564 | 0.4605 | 0.5395 |
Variance accounted for
| Factor | SS loadings | Proportion | Cumulative |
|---|---|---|---|
| F1 | 2.240 | 24.9% | 24.9% |
| F2 | 1.343 | 14.9% | 39.8% |
| F3 | 1.274 | 14.2% | 54.0% |
Factor correlations
| F1 | F2 | F3 | |
|---|---|---|---|
| F1 | 1 | 0.3229 | 0.2133 |
| F2 | 0.3229 | 1 | 0.2608 |
| F3 | 0.2133 | 0.2608 | 1 |
Sampling adequacy by item (MSA)
| Item | MSA |
|---|---|
| x1 | 0.8050 |
| x2 | 0.7779 |
| x3 | 0.7343 |
| x4 | 0.7633 |
| x5 | 0.7387 |
| x6 | 0.8076 |
| x7 | 0.5930 |
| x8 | 0.6829 |
| x9 | 0.7879 |
- Minimum-residual (iterated principal axis) extraction of the Pearson correlation matrix; oblimin rotation. Root mean square residual 0.019.
- Parallel analysis: 100 random normal datasets of 301 × 9 (seed 42); 3 eigenvalue(s) exceed the 95th percentile of the random eigenvalues.
- Likelihood-ratio fit (Bartlett-corrected): χ²(12) = 22.56, p = .032, RMSEA 0.054, TLI 0.964.
The exact R script · R R version 4.5.1 (2025-06-13)
# Exploratory factor analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.efa 2.0.1 · spec 9c15d9b0d307c56a
# Dataset: s3_hs (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# psych::fa(R, nfactors, fm = "minres" | "ml", rotate = …) fits the same model; cs_meas_efa runs the
# iterations to 1e-12 so R and Python agree exactly.
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s3_hs.parquet", col_select = c("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9")]), , 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("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9")) # infinite values stop the run (registry/errors.yaml)
# %% Correlations, adequacy and parallel analysis
items <- c("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9")
X <- as.matrix(df[items])
storage.mode(X) <- "double"
n <- nrow(X)
p <- ncol(X)
if (n <= p) cs_error("CS_E_TOO_FEW_ROWS", what = "Factor analysis", min = p + 1, n = n) # the correlation matrix is singular with no more cases than items
for (j in seq_len(p)) {
if (length(unique(X[, j])) < 2) cs_error("CS_E_CONSTANT", column = items[j]) # a constant item has no correlations
}
R <- stats::cor(X)
if (qr(R)$rank < p) stop("The correlation matrix is singular (an item is constant or a linear combination of others)")
km <- cs_meas_kmo(R)
bt <- cs_meas_bartlett(R, n)
eigen_r <- cs_meas_eig(R)$values
reps <- as.integer(100)
n_factors <- 3
pa_threshold <- "p95" # "p95" (95th percentile of the random eigenvalues) or "mean" (Horn 1965)
seed <- 42 # parallel analysis: the same random data in Python and R for this seed
suggested <- NULL
pa <- NULL
if (reps > 0 || is.null(n_factors)) {
pa <- cs_meas_parallel(n, p, max(reps, 20L), seed)
above <- eigen_r > pa[[pa_threshold]]
suggested <- if (all(above)) p else which(!above)[1] - 1
suggested <- max(suggested, 1)
}
k <- if (!is.null(n_factors)) as.integer(n_factors) else as.integer(suggested)
method <- "minres"
rotation <- "oblimin"
if (method == "ml" && ((p - k)^2 - (p + k)) / 2 < 0) {
stop(sprintf("%d factors are too many for %d items with maximum likelihood (negative degrees of freedom)", k, p))
}
if (k >= p) stop(sprintf("Choose fewer factors than items (%d)", p))
# %% Factor analysis
res <- cs_meas_efa(R, n, k, method, rotation)
L <- res$loadings
phi <- res$phi
fac <- paste0("F", seq_len(k))
nz <- function(v) if (is.null(v)) NA else v
values <- list(n = n, items = p, n_factors = k, suggested_factors = nz(suggested), kmo = km$overall, bartlett_chi2 = bt$chi2,
bartlett_df = bt$df, bartlett_p = bt$p, rmsr = res$rmsr, chi2 = if (res$df > 0) res$chi2 else NA, df = res$df,
chi2_p = nz(res$p), rmsea = nz(res$rmsea), tli = nz(res$tli), bic = nz(res$bic), var_explained = sum(res$prop_var))
for (i in seq_along(items)) {
for (j in seq_along(fac)) values[[sprintf("loading[%s|%s]", items[i], fac[j])]] <- L[i, j]
values[[sprintf("communality[%s]", items[i])]] <- res$communality[i]
values[[sprintf("uniqueness[%s]", items[i])]] <- res$uniqueness[i]
values[[sprintf("msa[%s]", items[i])]] <- km$per[i]
}
for (j in seq_along(fac)) {
values[[sprintf("ss[%s]", fac[j])]] <- res$ss[j]
values[[sprintf("prop_var[%s]", fac[j])]] <- res$prop_var[j]
}
if (!is.null(phi) && k > 1) {
for (a in 1:(k - 1)) for (b in (a + 1):k) values[[sprintf("phi[%s|%s]", fac[a], fac[b])]] <- phi[a, b]
}
for (i in seq_len(p)) {
values[[sprintf("eigen[%d]", i)]] <- eigen_r[i]
if (!is.null(pa)) {
values[[sprintf("pa_mean[%d]", i)]] <- pa$mean[i]
values[[sprintf("pa_p95[%d]", i)]] <- pa$p95[i]
}
}
# %% Assumptions
heywood <- items[res$communality >= 0.999]
small <- n < 100 || n < 5 * p
assumptions <- list(
list(key = "sample_size", label = "Sample size", status = if (small) "warn" else "pass",
detail = paste0(sprintf("%d cases for %d items (%.1f per item)", n, p, n / p), if (small) " — factor solutions may be unstable." else ".")),
list(key = "adequacy", label = "Sampling adequacy", status = if (km$overall < 0.6 || bt$p >= 0.05) "warn" else "pass",
detail = paste0(sprintf("KMO = %.2f", km$overall), if (km$overall < 0.6) " (below .60: the items share little common variance)" else "",
sprintf("; Bartlett χ²(%.0f) = %.1f, %s.", bt$df, bt$chi2, cs_fmt_p(bt$p)))),
list(key = "heywood", label = "Communalities below 1", status = if (length(heywood)) "fail" else "pass",
detail = if (length(heywood)) sprintf("Heywood case: %s — try fewer factors or another extraction.", paste(heywood, collapse = ", ")) else "Every communality is below 1."),
list(key = "convergence", label = "Convergence", status = if (res$converged) "pass" else "warn",
detail = if (res$converged) sprintf("Extraction converged in %d iterations.", res$iterations) else sprintf("Extraction stopped after %d iterations without converging.", res$iterations))
)
# %% Result
load_rows <- lapply(seq_along(items), function(i) {
r <- list(item = items[i])
for (j in seq_along(fac)) r[[fac[j]]] <- L[i, j]
r$h2 <- res$communality[i]
r$u2 <- res$uniqueness[i]
r
})
cumv <- cumsum(res$prop_var)
fac_rows <- lapply(seq_along(fac), function(j) list(factor = fac[j], ss = res$ss[j], prop = res$prop_var[j], cum = cumv[j]))
fcols <- lapply(fac, function(f) list(key = f, label = f, type = "number"))
tables <- list(
list(key = "loadings", title = sprintf("%s loadings (%s rotation)", if (!is.null(phi)) "Pattern" else "Factor", rotation),
columns = c(list(list(key = "item", label = "Item", type = "string")), fcols,
list(list(key = "h2", label = "h²", type = "number"), list(key = "u2", label = "u²", type = "number"))), rows = load_rows),
list(key = "factors", title = "Variance accounted for", columns = list(
list(key = "factor", label = "Factor", type = "string"), list(key = "ss", label = "SS loadings", type = "number"),
list(key = "prop", label = "Proportion", type = "percent"), list(key = "cum", label = "Cumulative", type = "percent")), rows = fac_rows)
)
if (!is.null(phi)) {
tables <- c(tables, list(list(key = "phi", title = "Factor correlations", columns = c(list(list(key = "factor", label = "", type = "string")), fcols),
rows = lapply(seq_along(fac), function(a) { r <- list(factor = fac[a]); for (b in seq_along(fac)) r[[fac[b]]] <- phi[a, b]; r }))))
}
tables <- c(tables, list(list(key = "msa", title = "Sampling adequacy by item (MSA)", columns = list(
list(key = "item", label = "Item", type = "string"), list(key = "msa", label = "MSA", type = "number")),
rows = lapply(seq_along(items), function(i) list(item = items[i], msa = km$per[i])))))
lv <- as.vector(t(L))
charts <- list(cs_chart("loadings", "matrix-heatmap", "Loadings", list(
row = cs_col("Item", rep(items, each = k), "categorical", levels = items),
col = cs_col("Factor", rep(fac, times = p), "categorical", levels = fac),
value = cs_col("Loading", lv, "numeric"),
label = cs_col("Text", sprintf("%.2f", lv), "categorical")
), controls = list(scale = "diverging")))
if (!is.null(pa)) {
charts <- c(list(cs_chart("parallel", "parallel-analysis", "Parallel analysis", list(
factor = cs_col("Factor", rep(as.double(seq_len(p)), 2), "numeric"),
eigenvalue = cs_col("Eigenvalue", c(eigen_r, pa[[pa_threshold]]), "numeric"),
kind = cs_col("Data", rep(c("observed", "simulated"), each = p), "categorical", levels = c("observed", "simulated"))
))), charts)
}
notes <- list(sprintf("%s extraction of the Pearson correlation matrix; %s rotation%s. Root mean square residual %.3f.",
if (method != "ml") "Minimum-residual (iterated principal axis)" else "Maximum-likelihood", rotation,
if (rotation %in% c("varimax", "quartimax", "promax")) " (Kaiser-normalized)" else "", res$rmsr))
if (!is.null(pa)) notes <- c(notes, sprintf("Parallel analysis: %d random normal datasets of %d × %d (seed %s); %d eigenvalue(s) exceed the %s of the random eigenvalues.",
max(reps, 20L), n, p, seed, suggested, if (pa_threshold == "p95") "95th percentile" else "mean"))
if (res$df > 0) notes <- c(notes, sprintf("Likelihood-ratio fit (Bartlett-corrected): χ²(%.0f) = %.2f, %s, RMSEA %.3f, TLI %.3f.", res$df, res$chi2, cs_fmt_p(res$p), res$rmsea, res$tli))
cs_publish(list(
method = "measurement.efa",
methodVersion = "2.0.1",
title = "Exploratory factor analysis",
engine = cs_engine_info("stats", "codesplashr"),
n = n,
summary = sprintf("%d factor%s explain %.0f%% of the variance of %d items (KMO = %.2f).", k, if (k != 1) "s" else "", 100 * sum(res$prop_var), p, km$overall),
apa = sprintf("KMO = %s; Bartlett's χ²(%.0f) = %s, %s", cs_fmt_num(km$overall, 2, leading_zero = FALSE), bt$df, cs_fmt_num(bt$chi2), cs_fmt_p(bt$p)),
statistics = list(list(key = "factors", label = "Factors", value = k), list(key = "var", label = "Variance explained", value = sum(res$prop_var), format = "percent"),
list(key = "kmo", label = "KMO", value = km$overall), list(key = "rmsr", label = "RMSR", value = res$rmsr)),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = values
))
KMO = .75; Bartlett's χ²(36) = 904.10, p < .001
- Factors
- 3
- Variance explained
- 54.0%
- KMO
- 0.7522
- RMSR
- 0.0191
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Sample size — 301 cases for 9 items (33.4 per item).
- Sampling adequacy — KMO = 0.75; Bartlett χ²(36) = 904.1, p < .001.
- Communalities below 1 — Every communality is below 1.
- Convergence — Extraction converged in 137 iterations.
Pattern loadings (oblimin rotation)
| Item | F1 | F2 | F3 | h² | u² |
|---|---|---|---|---|---|
| x1 | 0.1964 | 0.5916 | 0.0309 | 0.4768 | 0.5232 |
| x2 | 0.0430 | 0.5089 | −0.1223 | 0.2552 | 0.7448 |
| x3 | −0.0623 | 0.6859 | 0.0190 | 0.4535 | 0.5465 |
| x4 | 0.8461 | 0.0163 | 0.0077 | 0.7279 | 0.2721 |
| x5 | 0.8855 | −0.0646 | 0.0067 | 0.7537 | 0.2463 |
| x6 | 0.8053 | 0.0796 | −0.0130 | 0.6914 | 0.3086 |
| x7 | 0.0438 | −0.1523 | 0.7365 | 0.5186 | 0.4814 |
| x8 | −0.0340 | 0.1251 | 0.6865 | 0.5202 | 0.4798 |
| x9 | 0.0318 | 0.3823 | 0.4564 | 0.4605 | 0.5395 |
Variance accounted for
| Factor | SS loadings | Proportion | Cumulative |
|---|---|---|---|
| F1 | 2.240 | 24.9% | 24.9% |
| F2 | 1.343 | 14.9% | 39.8% |
| F3 | 1.274 | 14.2% | 54.0% |
Factor correlations
| F1 | F2 | F3 | |
|---|---|---|---|
| F1 | 1 | 0.3229 | 0.2133 |
| F2 | 0.3229 | 1.000 | 0.2608 |
| F3 | 0.2133 | 0.2608 | 1.000 |
Sampling adequacy by item (MSA)
| Item | MSA |
|---|---|
| x1 | 0.8050 |
| x2 | 0.7779 |
| x3 | 0.7343 |
| x4 | 0.7633 |
| x5 | 0.7387 |
| x6 | 0.8076 |
| x7 | 0.5930 |
| x8 | 0.6829 |
| x9 | 0.7879 |
- Minimum-residual (iterated principal axis) extraction of the Pearson correlation matrix; oblimin rotation. Root mean square residual 0.019.
- Parallel analysis: 100 random normal datasets of 301 × 9 (seed 42); 3 eigenvalue(s) exceed the 95th percentile of the random eigenvalues.
- Likelihood-ratio fit (Bartlett-corrected): χ²(12) = 22.56, p = .032, RMSEA 0.054, TLI 0.964.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Exploratory factor analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.efa 2.0.1 · spec 9c15d9b0d307c56a
# Dataset: s3_hs (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.stats import measurement as ms # EFA twin of R's cs_meas_efa
# factor_analyzer.FactorAnalyzer(n_factors, method="minres"|"ml", rotation=…) and psych::fa fit the
# same models; the twin runs both engines' iterations to 1e-12 so Python and R agree exactly.
# %% Data
df = pd.read_parquet("tests/parity/fixtures/s3_hs.parquet", columns=["x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"])
n_input = len(df)
df = df.dropna(subset=["x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"]) # listwise deletion over the analysis columns
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, ["x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"]) # infinite values stop the run (registry/errors.yaml)
# %% Correlations, adequacy and parallel analysis
items = ["x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"]
X = df[items].to_numpy(dtype=float)
n, p = X.shape
if n <= p: # the correlation matrix is singular with no more cases than items
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Factor analysis", min=p + 1, n=n)
for j, item in enumerate(items):
if len(np.unique(X[:, j])) < 2: # a constant item has no correlations
cs.cs_error("CS_E_CONSTANT", column=item)
R = np.corrcoef(X, rowvar=False)
if np.linalg.matrix_rank(R) < p:
raise ValueError("The correlation matrix is singular (an item is constant or a linear combination of others)")
kmo, msa = ms.kmo(R)
b_chi2, b_df, b_p = ms.bartlett(R, n)
eigen = ms.eigenvalues(R)
reps = int(100)
n_factors = 3
PA_THRESHOLD = "p95" # "p95" (95th percentile of the random eigenvalues) or "mean" (Horn 1965)
seed = 42 # parallel analysis: the same random data in Python and R for this seed
suggested = None
pa = None
if reps > 0 or n_factors is None:
pa = ms.parallel_analysis(n, p, max(reps, 20), seed)
above = eigen > pa[PA_THRESHOLD]
suggested = int(np.argmin(above)) if not above.all() else p
suggested = max(suggested, 1)
k = int(n_factors) if n_factors is not None else suggested
method = "minres"
rotation = "oblimin"
if method == "ml" and ((p - k) ** 2 - (p + k)) / 2 < 0:
raise ValueError(f"{k} factors are too many for {p} items with maximum likelihood (negative degrees of freedom)")
if k >= p:
raise ValueError(f"Choose fewer factors than items ({p})")
# %% Factor analysis
res = ms.efa(R, n, k, method, rotation)
L, phi = res["loadings"], res["phi"]
fac = [f"F{j + 1}" for j in range(k)]
values = {"n": float(n), "items": float(p), "n_factors": float(k), "suggested_factors": None if suggested is None else float(suggested),
"kmo": kmo, "bartlett_chi2": b_chi2, "bartlett_df": b_df, "bartlett_p": b_p, "rmsr": res["rmsr"],
"chi2": res["chi2"] if res["df"] > 0 else None, "df": res["df"], "chi2_p": res.get("p"), "rmsea": res.get("rmsea"),
"tli": res.get("tli"), "bic": res.get("bic"), "var_explained": float(np.sum(res["prop_var"]))}
for i, it in enumerate(items):
for j, f in enumerate(fac):
values[f"loading[{it}|{f}]"] = float(L[i, j])
values[f"communality[{it}]"] = float(res["communality"][i])
values[f"uniqueness[{it}]"] = float(res["uniqueness"][i])
values[f"msa[{it}]"] = float(msa[i])
for j, f in enumerate(fac):
values[f"ss[{f}]"] = float(res["ss"][j])
values[f"prop_var[{f}]"] = float(res["prop_var"][j])
if phi is not None:
for a in range(k):
for b in range(a + 1, k):
values[f"phi[{fac[a]}|{fac[b]}]"] = float(phi[a, b])
for i in range(p):
values[f"eigen[{i + 1}]"] = float(eigen[i])
if pa is not None:
values[f"pa_mean[{i + 1}]"] = float(pa["mean"][i])
values[f"pa_p95[{i + 1}]"] = float(pa["p95"][i])
# %% Assumptions
heywood = [it for i, it in enumerate(items) if res["communality"][i] >= 0.999]
assumptions = [
{"key": "sample_size", "label": "Sample size", "status": "warn" if n < 100 or n < 5 * p else "pass",
"detail": f"{n} cases for {p} items ({n / p:.1f} per item)" + (" — factor solutions may be unstable." if n < 100 or n < 5 * p else ".")},
{"key": "adequacy", "label": "Sampling adequacy", "status": "warn" if kmo < 0.6 or b_p >= 0.05 else "pass",
"detail": f"KMO = {kmo:.2f}" + (" (below .60: the items share little common variance)" if kmo < 0.6 else "")
+ f"; Bartlett χ²({b_df:.0f}) = {b_chi2:.1f}, {cs.fmt_p(b_p)}."},
{"key": "heywood", "label": "Communalities below 1", "status": "fail" if heywood else "pass",
"detail": f"Heywood case: {', '.join(heywood)} — try fewer factors or another extraction." if heywood else "Every communality is below 1."},
{"key": "convergence", "label": "Convergence", "status": "pass" if res["converged"] else "warn",
"detail": f"Extraction converged in {res['iterations']} iterations." if res["converged"] else f"Extraction stopped after {res['iterations']} iterations without converging."},
]
# %% Result
load_rows = [{"item": it, **{f: float(L[i, j]) for j, f in enumerate(fac)}, "h2": float(res["communality"][i]), "u2": float(res["uniqueness"][i])}
for i, it in enumerate(items)]
cum = np.cumsum(res["prop_var"])
fac_rows = [{"factor": f, "ss": float(res["ss"][j]), "prop": float(res["prop_var"][j]), "cum": float(cum[j])} for j, f in enumerate(fac)]
tables = [
{"key": "loadings", "title": f"{'Pattern' if phi is not None else 'Factor'} loadings ({rotation} rotation)", "columns": [
{"key": "item", "label": "Item", "type": "string"}, *[{"key": f, "label": f, "type": "number"} for f in fac],
{"key": "h2", "label": "h²", "type": "number"}, {"key": "u2", "label": "u²", "type": "number"}], "rows": load_rows},
{"key": "factors", "title": "Variance accounted for", "columns": [
{"key": "factor", "label": "Factor", "type": "string"}, {"key": "ss", "label": "SS loadings", "type": "number"},
{"key": "prop", "label": "Proportion", "type": "percent"}, {"key": "cum", "label": "Cumulative", "type": "percent"}], "rows": fac_rows},
]
if phi is not None:
tables.append({"key": "phi", "title": "Factor correlations", "columns": [
{"key": "factor", "label": "", "type": "string"}, *[{"key": f, "label": f, "type": "number"} for f in fac]],
"rows": [{"factor": f, **{g: float(phi[a, b]) for b, g in enumerate(fac)}} for a, f in enumerate(fac)]})
tables.append({"key": "msa", "title": "Sampling adequacy by item (MSA)", "columns": [
{"key": "item", "label": "Item", "type": "string"}, {"key": "msa", "label": "MSA", "type": "number"}],
"rows": [{"item": it, "msa": float(msa[i])} for i, it in enumerate(items)]})
charts = [cs.chart("loadings", "matrix-heatmap", "Loadings", {
"row": cs.col("Item", [it for it in items for _ in fac], "categorical", levels=items),
"col": cs.col("Factor", [f for _ in items for f in fac], "categorical", levels=fac),
"value": cs.col("Loading", [float(L[i, j]) for i in range(p) for j in range(k)], "numeric"),
"label": cs.col("Text", [f"{L[i, j]:.2f}" for i in range(p) for j in range(k)], "categorical"),
}, controls={"scale": "diverging"})]
if pa is not None:
charts.insert(0, cs.chart("parallel", "parallel-analysis", "Parallel analysis", {
"factor": cs.col("Factor", [float(i + 1) for i in range(p)] * 2, "numeric"),
"eigenvalue": cs.col("Eigenvalue", [float(v) for v in eigen] + [float(v) for v in pa[PA_THRESHOLD]], "numeric"),
"kind": cs.col("Data", ["observed"] * p + ["simulated"] * p, "categorical", levels=["observed", "simulated"]),
}))
notes = [f"{'Minimum-residual (iterated principal axis)' if method != 'ml' else 'Maximum-likelihood'} extraction of the Pearson correlation matrix; "
f"{rotation} rotation{' (Kaiser-normalized)' if rotation in ('varimax', 'quartimax', 'promax') else ''}. Root mean square residual {res['rmsr']:.3f}."]
if pa is not None:
notes.append(f"Parallel analysis: {max(reps, 20)} random normal datasets of {n} × {p} (seed {seed}); {suggested} eigenvalue(s) exceed the "
f"{'95th percentile' if PA_THRESHOLD == 'p95' else 'mean'} of the random eigenvalues.")
if res["df"] > 0:
notes.append(f"Likelihood-ratio fit (Bartlett-corrected): χ²({res['df']:.0f}) = {res['chi2']:.2f}, {cs.fmt_p(res['p'])}, RMSEA {res['rmsea']:.3f}, TLI {res['tli']:.3f}.")
cs.publish({
"method": "measurement.efa",
"methodVersion": "2.0.1",
"title": "Exploratory factor analysis",
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(n),
"summary": f"{k} factor{'s' if k != 1 else ''} explain {np.sum(res['prop_var']):.0%} of the variance of {p} items (KMO = {kmo:.2f}).",
"apa": f"KMO = {cs.fmt_num(kmo, 2, leading_zero=False)}; Bartlett's χ²({b_df:.0f}) = {cs.fmt_num(b_chi2)}, {cs.fmt_p(b_p)}",
"statistics": [{"key": "factors", "label": "Factors", "value": float(k)}, {"key": "var", "label": "Variance explained", "value": float(np.sum(res["prop_var"])), "format": "percent"},
{"key": "kmo", "label": "KMO", "value": kmo}, {"key": "rmsr", "label": "RMSR", "value": res["rmsr"]}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
})
Nine ability tests, three factors, oblique rotation. Test x5 has communality 0.75: most of its variance is shared. Test x2 has only 0.26, mostly its own.
Rotation (varimax, oblimin, promax) changes the loadings you read without changing the fitted covariance. It is a choice of description, not a discovery.
What a factor solution doesn't prove
ReadA tidy three-factor table does not show that three real abilities cause the scores. The model assumes residuals are independent given the factors, and that assumption is substantive.
Small samples, too many factors or weak items give unstable solutions and uniqueness estimates stuck at zero (Heywood cases). Check covariance residuals, compare rotations, and replicate on new data before naming factors.
Check: ICA and factor analysis
CheckpointCheck yourself
Why does ICA fail when all sources are Gaussian?
Show the answer
Answer: a
Independence identifies the rotation only through non-Gaussian structure. Whitened Gaussian data look the same from every angle.
Check yourself · choose all that apply
Two ICA runs on the same recordings give the same sources, but differently. Which differences are expected and harmless? Pick all that apply.
Show the answer
Answer: a, b, c
Scale, sign and order are never identified. A blend means the unmixing itself disagrees, which is a real problem.
Check yourself
PCA components are uncorrelated. Why aren't they the independent sources ICA looks for?
Show the answer
Answer: a
PCA fixes directions by variance. ICA goes further and picks the rotation that makes components independent, which needs non-Gaussianity.
Check yourself
What does factor analysis allow that probabilistic PCA doesn't?
Show the answer
Answer: a
PPCA uses one for all columns; factor analysis has a diagonal with one uniqueness per column.
Check yourself
A standardized item loads on factor 1 and on factor 2, with uncorrelated factors. What is its communality?
Show the answer
Answer: 0.68
. Its uniqueness is .
Check yourself
Switching from varimax to oblimin rotation changes every loading. What happens to how well the model fits the correlations?
Show the answer
Answer: a
for an orthogonal ; oblique rotations move the correlation into the factors' correlation matrix. The fitted covariance is the same.
Recap
Recap- ICA unmixes by seeking independent, non-Gaussian sources; scale, sign and order stay unknown.
- Factor analysis gives each column its own noise, splitting variance into communality and uniqueness.
- Rotations redescribe a factor solution; neither method proves that its components are real causes.
Concepts in this lesson