Skip to content

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.

Advanced ~14 min9 steps

What runs in CodeSplash

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

Read first

01

Unmixing: the cocktail party

Read

Four 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

x=As,x = A s,

an unknown mixing matrix AA applied to sources ss whose values are statistically independent, and tries to recover ss.

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.

02

Why non-Gaussian

Read

Mixing 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 tanh⁡\tanh of the projection. A Gaussian source has no non-Gaussianity to find, so at most one source may be Gaussian.

03

ICA on mixed signals

Read
Independent component analysisRecorded · Python and R agreeRecorded 2026-11-25 · 23 values compared
R

ICA unmixed 4 variables into 3 independent components; component 1 has excess kurtosis -1.98.

Components
3
IC1 excess kurtosis
−1.982

Plots

Independent components 1 × 2Which rows group together, and how well separated are the groups?
View data
GroupIC1IC2
All rows−0.0626−0.1807
All rows0.9943−0.1632
All rows0.9506−0.1182
All rows0.9374−0.0637
All rows0.96630.0037
All rows0.95380.0578
All rows0.93040.1079
All rows0.96020.1742
All rows0.94800.2266
All rows0.98260.2930
All rows0.95480.3390
All rows0.88120.3697
All rows0.91830.4341
All rows0.94300.4935
All rows0.95270.5470
All rows0.94120.5927
All rows0.91430.6321
All rows0.96110.6933
All rows0.90780.7216
All rows0.93150.7724
All rows0.94090.8172
All rows0.89730.8436
All rows0.92760.8915
All rows0.96560.9399
All rows0.92030.9603
All rows0.93580.9979
All rows0.93641.029
All rows0.91191.050
All rows0.95561.090
All rows0.97171.120
All rows0.90671.121
All rows0.92011.146
All rows0.95611.175
All rows0.91571.178
All rows0.89851.186
All rows0.94311.211
All rows0.91601.211
All rows0.92691.220
All rows0.92601.224
All rows0.89951.217
All rows0.92451.224
All rows0.88381.209
All rows0.91141.212
All rows0.93631.212
All rows0.92431.198
All rows0.88251.172
All rows0.91831.169
All rows0.88871.142
All rows0.91331.131
All rows0.94561.119
All rows0.93731.093
All rows0.90291.056
All rows0.96101.047
All rows−1.1061.114
All rows−1.0781.091
All rows−1.1271.042
All rows−1.0741.022
All rows−1.0680.9865
All rows−1.1130.9329
All rows−1.0750.9035

First 60 of 400 rows.

Independent components

ComponentExcess kurtosisShape
1−1.982flat / bimodal
2−1.353flat / bimodal
31.065peaked / heavy-tailed

Mixing matrix (how much each component feeds each variable)

VariableIC1IC2IC3
ch10.55750.67451.297
ch22.0300.45490.8220
ch30.35700.81970.6863
ch41.0310.27881.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"))
))
Python

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

ComponentExcess kurtosisShape
1−1.982flat / bimodal
2−1.353flat / bimodal
31.065peaked / heavy-tailed

Mixing matrix (how much each component feeds each variable)

VariableIC1IC2IC3
ch10.55750.67451.297
ch22.0300.45490.8220
ch30.35700.81970.6863
ch41.0310.27881.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.

04

What ICA can't tell you

Read
  • Scale and sign: As=(AD)(D−1s)A s = (A D)(D^{-1}s) for any diagonal DD, 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 x=Asx = As.

Check recovery on mixtures you built, and stability across restarts.

05

Factor analysis: shared causes plus own noise

Read

Factor analysisFactor analysisExplains correlations among many items through a few unobserved factors. explains the correlations between columns with a few common factors:

x=μ+Λf+ε,f∼N(0,Iq),ε∼N(0,Ψ),  Ψ diagonal.x = \mu + \Lambda f + \varepsilon, \qquad f \sim N(0, I_q), \quad \varepsilon \sim N(0, \Psi),\; \Psi \text{ diagonal}.

The difference from probabilistic PCA is Ψ\Psi: each column gets its own noise variance (its uniqueness). The implied covariance is ΛΛ⊤+Ψ\Lambda\Lambda^\top + \Psi, so each column's variance splits into a communality (shared) and a uniqueness.

In the reference's example, a column with loadings 0.90.9 and 0.10.1 and uniqueness 0.20.2 has variance 1.02: 0.81+0.01+0.20.81 + 0.01 + 0.2.

06

A three-factor solution

Read
Exploratory factor analysisRecorded · Python and R agreeRecorded 2026-11-17 · 106 values compared
R

KMO = .75; Bartlett's χ²(36) = 904.10, p < .001

Factors
3
Variance explained
54.0%
KMO
0.7522
RMSR
0.0191

Plots

Parallel analysisHow many factors stand out above what random data would produce?
View data
EigenvalueFactorData
3.2161observed
1.6392observed
1.3653observed
0.69894observed
0.58435observed
0.49976observed
0.47317observed
0.28608observed
0.23779observed
1.3481simulated
1.2272simulated
1.1533simulated
1.0904simulated
1.0395simulated
0.97466simulated
0.92057simulated
0.86058simulated
0.80559simulated
LoadingsWhat do the values of a square or rectangular result matrix look like at a glance?
View data
FactorTextItemLoading
F10.20x10.1964
F20.59x10.5916
F30.03x10.0309
F10.04x20.0430
F20.51x20.5089
F3-0.12x2−0.1223
F1-0.06x3−0.0623
F20.69x30.6859
F30.02x30.0190
F10.85x40.8461
F20.02x40.0163
F30.01x40.0077
F10.89x50.8855
F2-0.06x5−0.0646
F30.01x50.0067
F10.81x60.8053
F20.08x60.0796
F3-0.01x6−0.0130
F10.04x70.0438
F2-0.15x7−0.1523
F30.74x70.7365
F1-0.03x8−0.0340
F20.13x80.1251
F30.69x80.6865
F10.03x90.0318
F20.38x90.3823
F30.46x90.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)

ItemF1F2F3h²u²
x10.19640.59160.03090.47680.5232
x20.04300.5089−0.12230.25520.7448
x3−0.06230.68590.01900.45350.5465
x40.84610.01630.00770.72790.2721
x50.8855−0.06460.00670.75370.2463
x60.80530.0796−0.01300.69140.3086
x70.0438−0.15230.73650.51860.4814
x8−0.03400.12510.68650.52020.4798
x90.03180.38230.45640.46050.5395

Variance accounted for

FactorSS loadingsProportionCumulative
F12.24024.9%24.9%
F21.34314.9%39.8%
F31.27414.2%54.0%

Factor correlations

F1F2F3
F110.32290.2133
F20.322910.2608
F30.21330.26081

Sampling adequacy by item (MSA)

ItemMSA
x10.8050
x20.7779
x30.7343
x40.7633
x50.7387
x60.8076
x70.5930
x80.6829
x90.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
))
Python

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)

ItemF1F2F3h²u²
x10.19640.59160.03090.47680.5232
x20.04300.5089−0.12230.25520.7448
x3−0.06230.68590.01900.45350.5465
x40.84610.01630.00770.72790.2721
x50.8855−0.06460.00670.75370.2463
x60.80530.0796−0.01300.69140.3086
x70.0438−0.15230.73650.51860.4814
x8−0.03400.12510.68650.52020.4798
x90.03180.38230.45640.46050.5395

Variance accounted for

FactorSS loadingsProportionCumulative
F12.24024.9%24.9%
F21.34314.9%39.8%
F31.27414.2%54.0%

Factor correlations

F1F2F3
F110.32290.2133
F20.32291.0000.2608
F30.21330.26081.000

Sampling adequacy by item (MSA)

ItemMSA
x10.8050
x20.7779
x30.7343
x40.7633
x50.7387
x60.8076
x70.5930
x80.6829
x90.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.

07

What a factor solution doesn't prove

Read

A 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.

08

Check: ICA and factor analysis

Checkpoint

Check 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 σ2\sigma^2 for all columns; factor analysis has a diagonal Ψ\Psi with one uniqueness per column.

Check yourself

A standardized item loads 0.80.8 on factor 1 and 0.20.2 on factor 2, with uncorrelated factors. What is its communality?

Show the answer

Answer: 0.68

0.82+0.22=0.64+0.04=0.680.8^2 + 0.2^2 = 0.64 + 0.04 = 0.68. Its uniqueness is 1−0.68=0.321 - 0.68 = 0.32.

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

ΛR(ΛR)⊤=ΛΛ⊤\Lambda R (\Lambda R)^\top = \Lambda\Lambda^\top for an orthogonal RR; oblique rotations move the correlation into the factors' correlation matrix. The fitted covariance is the same.

09

Recap

Recap
  • ICA unmixes x=Asx = As 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