Sparse, robust and functional PCA
Three changes to PCA's objective for three different problems. Sparse PCA trades variance for components you can name, robust PCA splits off gross cell errors with the nuclear norm, and functional PCA treats each row as a curve.
What runs in CodeSplash
- REP004Sparse PCA Runs in CodeSplash
- REP005Robust PCA via principal component pursuit Runs in CodeSplash
- REP006Functional PCA (FPCA) Runs in CodeSplash
- Sparse principal components Verified in Python and R
- Robust PCA (cell outliers) Verified in Python and R
- Functional PCA (main shapes of a set of curves) Verified in Python and R
You will be able to
- Write the sparse PCA objective and read what its sparsity costs in variance
- State principal component pursuit and say which kinds of corruption it can and can't separate
- Explain functional PCA's eigenfunctions and why phase variation can dominate them
Sparse PCA: components you can name
ReadOrdinary loadings are dense: every column contributes a little to every component, which makes components hard to name. Sparse PCASparse PCAPrincipal components where each component keeps only a few variables, so every component reads as a short list. adds an L1 penalty on the loadings,
under a scale constraint, so most loadings become exactly zero. Several formulations exist with different orthogonality and penalty choices; name the one you used.
Predict the price
PredictPredict first
You let each of two components use only two of US arrests' four columns. Compared with two ordinary principal components, how much variance will they explain?
Reveal
Less. No two linear components can beat the first two ordinary ones, so sparsity always costs something. The run below shows how much.
What sparsity costs
ReadSparse PCA of 4 variables (2 per component): 2 components explain 71.9% of the variance (adjusted), against 86.8% for ordinary PCA.
- Adjusted variance explained
- 71.9%
- Ordinary PCA, same components
- 86.8%
Plots
View data
| Component | Loading | Variable | Loading |
|---|---|---|---|
| SPC1 | 0.71 | Murder | 0.7071 |
| SPC2 | 0 | Murder | 0 |
| SPC1 | 0.71 | Assault | 0.7071 |
| SPC2 | 0 | Assault | 0 |
| SPC1 | 0 | UrbanPop | 0 |
| SPC2 | 0.71 | UrbanPop | 0.7071 |
| SPC1 | 0 | Rape | 0 |
| SPC2 | 0.71 | Rape | 0.7071 |
Loading arrows are rescaled to the score range; variables with a zero loading sit at the origin.
View data
| Kind | Label | SPC1 | SPC2 |
|---|---|---|---|
| point | 1.432 | −0.3708 | |
| point | 1.142 | 0.8998 | |
| point | 1.096 | 1.444 | |
| point | 0.3275 | −0.8899 | |
| point | 1.090 | 2.706 | |
| point | 0.3002 | 1.927 | |
| point | −1.244 | −0.2051 | |
| point | 0.2640 | −0.0945 | |
| point | 2.629 | 1.512 | |
| point | 1.902 | 0.0742 | |
| point | −1.462 | 0.7750 | |
| point | −1.273 | −1.095 | |
| point | 1.088 | 1.062 | |
| point | −0.5855 | −0.0439 | |
| point | −1.881 | −1.167 | |
| point | −0.7634 | −0.2215 | |
| point | −0.2136 | −1.034 | |
| point | 1.900 | 0.0955 | |
| point | −1.668 | −1.724 | |
| point | 1.667 | 0.5672 | |
| point | −0.7347 | 0.5783 | |
| point | 1.415 | 1.460 | |
| point | −1.664 | −0.4556 | |
| point | 2.098 | −1.364 | |
| point | 0.2582 | 0.7439 | |
| point | −0.8143 | −0.9774 | |
| point | −1.150 | −0.5302 | |
| point | 1.406 | 2.625 | |
| point | −1.889 | −1.352 | |
| point | −0.1628 | 0.9624 | |
| point | 1.556 | 1.038 | |
| point | 1.244 | 1.367 | |
| point | 2.257 | −1.391 | |
| point | −2.202 | −2.104 | |
| point | −0.5099 | 0.4748 | |
| point | −0.3605 | 0.0272 | |
| point | −0.5686 | 0.6804 | |
| point | −0.7911 | −0.1625 | |
| point | −0.6849 | 0.0721 | |
| point | 1.992 | −0.7611 | |
| point | −1.367 | −1.640 | |
| point | 1.025 | 0.1084 | |
| point | 1.054 | 1.029 | |
| point | −1.176 | 0.8323 | |
| point | −1.949 | −2.396 | |
| point | −0.0096 | −0.1642 | |
| point | −0.8335 | 0.7395 | |
| point | −1.101 | −2.197 | |
| point | −1.841 | −0.7651 | |
| point | −0.2432 | −0.6958 | |
| loading | Murder | 2.165 | 0 |
| loading | Assault | 2.165 | 0 |
| loading | UrbanPop | 0 | 2.165 |
| loading | Rape | 0 | 2.165 |
Adjusted variance (sparse components are correlated, so each counts only what the earlier ones don't explain)
| Component | Adjusted variance | Proportion | Cumulative | Ordinary PCA, cumulative |
|---|---|---|---|---|
| 1 | 1.802 | 45.0% | 45.0% | 62.0% |
| 2 | 1.075 | 26.9% | 71.9% | 86.8% |
Sparse loadings (2 of 4 variables per component)
| Variable | SPC1 | SPC2 |
|---|---|---|
| Murder | 0.7071 | 0 |
| Assault | 0.7071 | 0 |
| UrbanPop | 0 | 0.7071 |
| Rape | 0 | 0.7071 |
Selection stability (20 bootstrap refits): share in which the variable was kept
| Variable | SPC1 | SPC2 |
|---|---|---|
| Murder | 85.0% | 15.0% |
| Assault | 100.0% | 0.0% |
| UrbanPop | 0.0% | 100.0% |
| Rape | 15.0% | 85.0% |
The exact R script · R R version 4.5.1 (2025-06-13)
# Sparse principal components
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sparse_pca 1.0.0 · spec fbf955a44e678497
# Dataset: ml_usarrests (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("Murder", "Assault", "UrbanPop", "Rape")
LABEL <- NULL
SEED <- 42
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.parquet", col_select = unique(c(FEATURES, LABEL))))
n_input <- nrow(df)
warnings <- list()
cs_check_finite_columns(df, FEATURES)
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))
}
cs_check_rows(length(rows), 3, "Sparse PCA")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
if (all(apply(X, 2, function(x) all(x == x[1])))) cs_error("CS_E_CONSTANT", column = FEATURES[1])
# %% Sparse components (Shen & Huang sPCA-rSVD: exactly m nonzero loadings per component)
SCALE <- TRUE
Z <- cs_rep_center_scale(X, SCALE)
p <- length(FEATURES)
k_req <- min(as.integer(2), length(rows) - 1L, p)
m <- if (is.null(2)) p else min(as.integer(2), p)
V <- cs_rep_sparse_pca(Z, k_req, m)
k <- ncol(V)
if (k < k_req) warnings <- c(warnings, sprintf("Only %d of %d components were found: the remaining variation is zero.", k, k_req))
T <- Z %*% V
adj <- cs_rep_adjusted_variance(T)
total <- sum(Z * Z) / (length(rows) - 1)
adj_prop <- adj / total
adj_cum <- cumsum(adj_prop)
eig <- svd(Z, nu = 0, nv = 0)$d^2 / (length(rows) - 1)
pca_cum <- sum(eig[seq_len(k)]) / total
RESAMPLES <- as.integer(20)
share <- if (RESAMPLES > 0) cs_rep_sparse_pca_stability(X, SCALE, V, m, RESAMPLES, SEED) else NULL
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-93364/discover.sparse_pca/usarrests_two_each/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(k)) emb[[paste0("dim_", j)]] <- T[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
# %% Result
values <- list(n = length(rows), n_variables = p, n_components = k, nonzero = m,
adj_cum = if (k > 0) adj_cum[k] else NaN, pca_cum = pca_cum)
for (j in seq_len(k)) {
values[[sprintf("adj_var[%d]", j)]] <- adj[j]
values[[sprintf("adj_prop[%d]", j)]] <- adj_prop[j]
values[[sprintf("score_check[%d]", j)]] <- cs_ml_checksum(T[, j], rows)
for (i in seq_along(FEATURES)) {
values[[sprintf("loading[%d:%s]", j, FEATURES[i])]] <- V[i, j]
if (!is.null(share)) values[[sprintf("selected_share[%d:%s]", j, FEATURES[i])]] <- share[i, j]
}
}
pc_cols <- lapply(seq_len(k), function(j) list(key = paste0("pc", j), label = paste0("SPC", j), type = "number"))
tables <- list(
list(key = "variance", title = "Adjusted variance (sparse components are correlated, so each counts only what the earlier ones don't explain)",
columns = list(list(key = "component", label = "Component", type = "integer"),
list(key = "adjusted", label = "Adjusted variance", type = "number"),
list(key = "proportion", label = "Proportion", type = "percent"),
list(key = "cumulative", label = "Cumulative", type = "percent"),
list(key = "pca", label = "Ordinary PCA, cumulative", type = "percent")),
rows = lapply(seq_len(k), function(j) list(component = j, adjusted = adj[j], proportion = adj_prop[j], cumulative = adj_cum[j],
pca = sum(eig[seq_len(j)]) / total))),
list(key = "loadings", title = sprintf("Sparse loadings (%d of %d variables per component)", m, p),
columns = c(list(list(key = "variable", label = "Variable")), pc_cols),
rows = lapply(seq_along(FEATURES), function(i) {
r <- list(variable = FEATURES[i])
for (j in seq_len(k)) r[[paste0("pc", j)]] <- V[i, j]
r
}))
)
if (!is.null(share)) {
tables[[3]] <- list(key = "stability", title = sprintf("Selection stability (%d bootstrap refits): share in which the variable was kept", RESAMPLES),
columns = c(list(list(key = "variable", label = "Variable")),
lapply(seq_len(k), function(j) list(key = paste0("pc", j), label = paste0("SPC", j), type = "percent"))),
rows = lapply(seq_along(FEATURES), function(i) {
r <- list(variable = FEATURES[i])
for (j in seq_len(k)) r[[paste0("pc", j)]] <- share[i, j]
r
}))
}
comp_levels <- paste0("SPC", seq_len(k))
lv <- as.vector(t(V))
charts <- list(cs_chart("loadings", "matrix-heatmap", "Sparse loadings", list(
row = cs_col("Variable", rep(FEATURES, each = k), "categorical", levels = FEATURES),
col = cs_col("Component", rep(comp_levels, times = p), "categorical", levels = comp_levels),
value = cs_col("Loading", lv, "numeric"),
label = cs_col("Loading", ifelse(lv == 0, "0", sprintf("%.2f", lv)), "categorical")
)))
if (k >= 2) {
pick <- chart_rows(length(rows))
lab <- if (!is.null(LABEL)) as.character(df[[LABEL]][rows[pick] + 1L]) else rep("", length(pick))
lab[is.na(lab)] <- ""
reach <- max(abs(T[pick, 1:2])) / max(max(abs(V[, 1:2])), 1e-12) * 0.8
charts[[2]] <- cs_chart("biplot", "biplot", "Biplot (SPC1 × SPC2)", list(
x = cs_col("SPC1", c(T[pick, 1], V[, 1] * reach), "numeric"),
y = cs_col("SPC2", c(T[pick, 2], V[, 2] * reach), "numeric"),
kind = cs_col("Kind", c(rep("point", length(pick)), rep("loading", p)), "categorical"),
label = cs_col(if (is.null(LABEL)) "Label" else LABEL, c(lab, FEATURES), "categorical")
), note = "Loading arrows are rescaled to the score range; variables with a zero loading sit at the origin.")
}
cs_publish(list(
title = "Sparse principal components",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = sprintf("Sparse PCA of %d variables (%d per component): %d components explain %.1f%% of the variance (adjusted), against %.1f%% for ordinary PCA.",
p, m, k, 100 * values$adj_cum, 100 * pca_cum),
statistics = list(list(key = "adj_cum", label = "Adjusted variance explained", value = values$adj_cum, format = "percent"),
list(key = "pca_cum", label = "Ordinary PCA, same components", value = pca_cum, format = "percent")),
tables = tables,
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))
Sparse PCA of 4 variables (2 per component): 2 components explain 71.9% of the variance (adjusted), against 86.8% for ordinary PCA.
- Adjusted variance explained
- 71.9%
- Ordinary PCA, same components
- 86.8%
To keep this page light, the plots are shown once, under the R tab.
Adjusted variance (sparse components are correlated, so each counts only what the earlier ones don't explain)
| Component | Adjusted variance | Proportion | Cumulative | Ordinary PCA, cumulative |
|---|---|---|---|---|
| 1 | 1.802 | 45.0% | 45.0% | 62.0% |
| 2 | 1.075 | 26.9% | 71.9% | 86.8% |
Sparse loadings (2 of 4 variables per component)
| Variable | SPC1 | SPC2 |
|---|---|---|
| Murder | 0.7071 | 0 |
| Assault | 0.7071 | 0 |
| UrbanPop | 0 | 0.7071 |
| Rape | 0 | 0.7071 |
Selection stability (20 bootstrap refits): share in which the variable was kept
| Variable | SPC1 | SPC2 |
|---|---|---|
| Murder | 85.0% | 15.0% |
| Assault | 100.0% | 0.0% |
| UrbanPop | 0.0% | 100.0% |
| Rape | 15.0% | 85.0% |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Sparse principal components
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sparse_pca 1.0.0 · spec fbf955a44e678497
# Dataset: ml_usarrests (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import embed as csembed
from codesplash.ml import rep_linear as rl
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 = ["Murder", "Assault", "UrbanPop", "Rape"]
LABEL = None
SEED = 42
df = pd.read_parquet("tests/parity/fixtures/ml_usarrests.parquet", columns=list(dict.fromkeys(FEATURES + ([LABEL] if LABEL else []))))
n_input = len(df)
warnings = []
cs.check_finite_columns(df, FEATURES)
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.")
cs.check_rows(len(rows), 3, "Sparse PCA")
X = csembed.numeric_matrix(df, FEATURES, rows)
if np.all(X.std(axis=0) == 0):
cs.cs_error("CS_E_CONSTANT", column=FEATURES[0])
# %% Sparse components (Shen & Huang sPCA-rSVD: exactly m nonzero loadings per component)
SCALE = True
Z = rl.center_scale(X, SCALE) # SD with n − 1, like R's scale()
p = len(FEATURES)
k_req = min(int(2), len(rows) - 1, p)
m = p if 2 is None else min(int(2), p)
V = rl.sparse_pca(Z, k_req, m)
k = V.shape[1]
if k < k_req:
warnings.append(f"Only {k} of {k_req} components were found: the remaining variation is zero.")
T = Z @ V
adj = rl.adjusted_variance(T)
total = float(np.sum(Z * Z)) / (len(rows) - 1)
adj_prop = adj / total
adj_cum = np.cumsum(adj_prop)
sv = np.linalg.svd(Z, compute_uv=False)
eig = sv ** 2 / (len(rows) - 1)
pca_cum = float(np.sum(eig[:k]) / total)
RESAMPLES = int(20)
share = rl.sparse_pca_stability(X, SCALE, V, m, RESAMPLES, SEED) if RESAMPLES > 0 else None
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-93364/discover.sparse_pca/usarrests_two_each/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(k):
emb[f"dim_{j + 1}"] = T[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
# %% Result
values = {
"n": len(rows),
"n_variables": p,
"n_components": k,
"nonzero": m,
"adj_cum": float(adj_cum[-1]) if k else float("nan"),
"pca_cum": pca_cum,
}
for j in range(k):
values[f"adj_var[{j + 1}]"] = float(adj[j])
values[f"adj_prop[{j + 1}]"] = float(adj_prop[j])
values[f"score_check[{j + 1}]"] = csembed.checksum(T[:, j], rows)
for i, f in enumerate(FEATURES):
values[f"loading[{j + 1}:{f}]"] = float(V[i, j])
if share is not None:
values[f"selected_share[{j + 1}:{f}]"] = float(share[i, j])
tables = [
{
"key": "variance",
"title": "Adjusted variance (sparse components are correlated, so each counts only what the earlier ones don't explain)",
"columns": [
{"key": "component", "label": "Component", "type": "integer"},
{"key": "adjusted", "label": "Adjusted variance", "type": "number"},
{"key": "proportion", "label": "Proportion", "type": "percent"},
{"key": "cumulative", "label": "Cumulative", "type": "percent"},
{"key": "pca", "label": "Ordinary PCA, cumulative", "type": "percent"},
],
"rows": [{"component": j + 1, "adjusted": adj[j], "proportion": adj_prop[j], "cumulative": adj_cum[j], "pca": float(np.sum(eig[: j + 1]) / total)} for j in range(k)],
},
{
"key": "loadings",
"title": f"Sparse loadings ({m} of {p} variables per component)",
"columns": [{"key": "variable", "label": "Variable"}] + [{"key": f"pc{j + 1}", "label": f"SPC{j + 1}", "type": "number"} for j in range(k)],
"rows": [dict({"variable": f}, **{f"pc{j + 1}": V[i, j] for j in range(k)}) for i, f in enumerate(FEATURES)],
},
]
if share is not None:
tables.append({
"key": "stability",
"title": f"Selection stability ({RESAMPLES} bootstrap refits): share in which the variable was kept",
"columns": [{"key": "variable", "label": "Variable"}] + [{"key": f"pc{j + 1}", "label": f"SPC{j + 1}", "type": "percent"} for j in range(k)],
"rows": [dict({"variable": f}, **{f"pc{j + 1}": share[i, j] for j in range(k)}) for i, f in enumerate(FEATURES)],
})
charts = [
cs.chart(
"loadings",
"matrix-heatmap",
"Sparse loadings",
{
"row": cs.col("Variable", [f for f in FEATURES for _ in range(k)], "categorical", levels=FEATURES),
"col": cs.col("Component", [f"SPC{j + 1}" for _ in FEATURES for j in range(k)], "categorical", levels=[f"SPC{j + 1}" for j in range(k)]),
"value": cs.col("Loading", [float(V[i, j]) for i in range(p) for j in range(k)], "numeric"),
"label": cs.col("Loading", ["0" if V[i, j] == 0 else f"{V[i, j]:.2f}" for i in range(p) for j in range(k)], "categorical"),
},
)
]
if k >= 2:
pick = chart_rows(len(rows))
lab = ["" if LABEL is None else str(v) for v in df.iloc[rows[pick]][LABEL]] if LABEL else [""] * len(pick)
reach = np.max(np.abs(T[pick, :2])) / max(np.max(np.abs(V[:, :2])), 1e-12) * 0.8
charts.append(
cs.chart(
"biplot",
"biplot",
"Biplot (SPC1 × SPC2)",
{
"x": cs.col("SPC1", np.concatenate([T[pick, 0], V[:, 0] * reach]), "numeric"),
"y": cs.col("SPC2", np.concatenate([T[pick, 1], V[:, 1] * reach]), "numeric"),
"kind": cs.col("Kind", ["point"] * len(pick) + ["loading"] * p, "categorical"),
"label": cs.col(LABEL or "Label", lab + FEATURES, "categorical"),
},
note="Loading arrows are rescaled to the score range; variables with a zero loading sit at the origin.",
)
)
cs.publish(
{
"title": "Sparse principal components",
"engine": cs.engine_info("numpy", "pandas"),
"n": len(rows),
"summary": f"Sparse PCA of {p} variables ({m} per component): {k} components explain {values['adj_cum']:.1%} of the variance (adjusted), against {pca_cum:.1%} for ordinary PCA.",
"statistics": [
{"key": "adj_cum", "label": "Adjusted variance explained", "value": values["adj_cum"], "format": "percent"},
{"key": "pca_cum", "label": "Ordinary PCA, same components", "value": pca_cum, "format": "percent"},
],
"tables": tables,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
}
)
Allowing two variables per component on US arrests gives one component of murder and assault and one of rape and urban population. Together they explain 71.9% of the variance, against 86.8% for two ordinary components. That gap is the price of names.
Selection stabilitySelection stabilityShare of bootstrap refits in which a variable keeps a nonzero loading on the matched component. shows how dependable each choice is: murder kept its place in 85% of bootstrap refits. Correlated columns can substitute for each other, so selection can flip between them.
Sparse components aren't PCA components
Read- Sparse components need not be orthogonal, so their variances don't add up. The app reports an adjusted variance that discounts overlap.
- Sparsity is a preference you imposed, not a discovery that the zero-loading columns don't matter.
- Report results across several penalty values, not one convenient sparsity.
Robust PCA: pattern plus gross errors
ReadRobust PCARobust PCA (principal component pursuit)Splits a table into a low-rank pattern plus a sparse part holding the few cells that break it. by principal component pursuit splits the table into a low-rank pattern and a sparse part of large cell errors:
The nuclear normNuclear normThe sum of a matrix's singular values. Penalizing it pushes toward low rank, as the L1 norm pushes toward zeros. pushes toward low rank and the L1 norm pushes toward few nonzero cells. The default balances them.
Robust PCA on planted errors
ReadRobust PCA split the data into a rank-3 part and a sparse part; 15 of 960 cells (1.6%) are flagged.
- Low-rank part: rank
- 3
- Flagged cells
- 15
- Rows with a flagged cell
- 13
Plots
View data
| Component | Cumulative | Share of the low-rank part |
|---|---|---|
| 1 | 0.6409 | 0.6409 |
| 2 | 0.9990 | 0.3581 |
| 3 | 1 | 0.0010 |
View data
| Variable |
|---|
| m7 |
| m5 |
| m6 |
| m5 |
| m3 |
| m8 |
| m1 |
| m7 |
| m4 |
| m7 |
| m5 |
| m2 |
| m2 |
| m4 |
| m7 |
Loading arrows are rescaled to the score range.
View data
| Kind | Label | LC1 | LC2 |
|---|---|---|---|
| point | −0.7602 | −1.207 | |
| point | −1.268 | −1.359 | |
| point | −1.221 | 1.296 | |
| point | 0.4132 | 0.6085 | |
| point | −0.7191 | 0.1055 | |
| point | 0.0730 | 3.376 | |
| point | 1.419 | −1.365 | |
| point | −1.014 | 1.045 | |
| point | −2.697 | 0.5859 | |
| point | −1.438 | −0.1922 | |
| point | −0.3792 | 0.0315 | |
| point | 2.499 | 0.4489 | |
| point | 2.816 | −1.192 | |
| point | 0.6784 | 1.071 | |
| point | −3.345 | −1.156 | |
| point | 0.7233 | 1.959 | |
| point | 3.072 | −1.039 | |
| point | 0.2222 | 1.615 | |
| point | 0.5783 | 0.4367 | |
| point | 4.752 | −1.475 | |
| point | 0.8547 | 3.544 | |
| point | 1.781 | 0.8524 | |
| point | 0.9886 | −0.5187 | |
| point | 0.3578 | −0.6322 | |
| point | −0.1366 | −0.1460 | |
| point | −0.5690 | 2.226 | |
| point | −3.680 | 2.066 | |
| point | 3.102 | −2.976 | |
| point | −1.620 | 1.076 | |
| point | −0.9975 | −0.0467 | |
| point | 3.430 | 3.129 | |
| point | −1.301 | −0.4393 | |
| point | 1.566 | −1.441 | |
| point | 2.494 | −0.5314 | |
| point | −1.282 | −1.388 | |
| point | −0.0822 | −0.9451 | |
| point | −0.7235 | −0.5301 | |
| point | 0.3745 | −0.2345 | |
| point | 3.858 | −2.766 | |
| point | 2.440 | −1.008 | |
| point | 1.806 | −1.423 | |
| point | 0.2946 | 0.7111 | |
| point | 0.1773 | −2.442 | |
| point | −1.038 | −2.088 | |
| point | −4.860 | −0.6180 | |
| point | −0.1745 | −0.4724 | |
| point | −2.805 | −2.993 | |
| point | 0.1934 | 1.160 | |
| point | −1.292 | 2.082 | |
| point | 2.665 | 0.6096 | |
| point | −0.9358 | 1.994 | |
| point | −2.314 | −1.440 | |
| point | 0.8071 | −1.222 | |
| point | −4.393 | −0.7417 | |
| point | 1.709 | −2.261 | |
| point | 1.155 | 1.419 | |
| point | −0.1952 | 2.301 | |
| point | 3.966 | 1.389 | |
| point | −1.903 | −0.8208 | |
| point | 2.057 | 0.3706 |
First 60 of 128 rows.
Flagged cells (sparse part beyond 2 scaled units)
| Row | Variable | Value | Low-rank fit | Sparse part |
|---|---|---|---|---|
| 75 | m4 | 7.540 | 0.7269 | 6.813 |
| 111 | m4 | 6.832 | 0.6736 | 6.158 |
| 103 | m2 | 6.827 | −0.7571 | 7.584 |
| 99 | m2 | 7.555 | 0.0238 | 7.531 |
| 19 | m5 | 7.974 | 0.5421 | 7.432 |
| 19 | m6 | 5.648 | −0.4970 | 6.145 |
| 98 | m5 | −7.087 | −0.1626 | −6.925 |
| 31 | m5 | 8.997 | 2.265 | 6.732 |
| 77 | m7 | 8.675 | 0.5876 | 8.087 |
| 42 | m3 | 8.707 | 0.1939 | 8.513 |
| 72 | m1 | −6.394 | 0.0434 | −6.438 |
| 9 | m7 | −7.063 | −0.1119 | −6.951 |
| 72 | m7 | −7.084 | −0.5234 | −6.561 |
| 115 | m7 | 5.609 | −0.5466 | 6.155 |
| 51 | m8 | −11.312 | −2.556 | −8.756 |
Flagged cells by variable
| Variable | Flagged cells | Share of rows | Center | Scale |
|---|---|---|---|---|
| m1 | 1 | 0.8% | 0.2471 | 1.345 |
| m2 | 2 | 1.7% | 0.0802 | 0.8986 |
| m3 | 1 | 0.8% | 0.1645 | 1.752 |
| m4 | 2 | 1.7% | −0.0151 | 0.4654 |
| m5 | 3 | 2.5% | 0.2388 | 1.199 |
| m6 | 1 | 0.8% | −0.2309 | 1.011 |
| m7 | 4 | 3.3% | −0.0689 | 1.617 |
| m8 | 1 | 0.8% | −0.5964 | 3.408 |
Loadings of the low-rank part
| Variable | LC1 | LC2 |
|---|---|---|
| m1 | 0.4491 | 0.1197 |
| m2 | −0.2852 | 0.4072 |
| m3 | 0.4501 | −0.2007 |
| m4 | −0.1894 | 0.5481 |
| m5 | 0.4593 | 0.0342 |
| m6 | −0.4223 | −0.1572 |
| m7 | −0.1095 | −0.5254 |
| m8 | −0.2779 | −0.4210 |
- Robust PCA flags single cells, not whole rows: a row is unusual only when many of its cells are flagged.
The exact R script · R R version 4.5.1 (2025-06-13)
# Robust PCA (cell outliers)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.robust_pca 1.0.0 · spec 63c7f51a131dcaad
# Dataset: rep1_lowrank (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("m1", "m2", "m3", "m4", "m5", "m6", "m7", "m8")
LABEL <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep1_lowrank.parquet", col_select = unique(c(FEATURES, LABEL))))
n_input <- nrow(df)
warnings <- list()
cs_check_finite_columns(df, FEATURES)
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))
}
cs_check_rows(length(rows), 3, "Robust PCA")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
# %% Principal component pursuit (ADMM to primal and dual tolerance): low-rank part L + sparse part S = scaled data
rc <- cs_rep_robust_center_scale(X, "robust")
Zs <- rc$Z; center <- rc$center; scale <- rc$scale
if (!any(Zs != 0)) cs_error("CS_E_CONSTANT", column = FEATURES[1])
n <- nrow(Zs); p <- ncol(Zs)
LAM <- NULL
lam <- if (is.null(LAM)) 1 / sqrt(max(n, p)) else as.numeric(LAM)
fit <- cs_rep_robust_pca(Zs, lam)
L <- fit$L; S <- fit$S; rank <- fit$rank
if (!fit$converged) warnings <- c(warnings, "Principal component pursuit stopped after 10,000 iterations before reaching its tolerance; treat the split as approximate.")
FLAG <- as.numeric(2)
flagged <- abs(S) > FLAG
n_flagged <- sum(flagged)
rows_flagged <- sum(rowSums(flagged) > 0)
total_ss <- sum(Zs * Zs)
sparse_share <- sum(S * S) / total_ss
# low-rank part: its own principal axes give the map
sv <- svd(L)
k <- min(as.integer(2), rank)
if (k > 0) {
signs <- cs_ml_canonical_signs(sv$v[, seq_len(k), drop = FALSE])
loadings <- sweep(sv$v[, seq_len(k), drop = FALSE], 2, signs, "*")
scores <- sweep(sv$u[, seq_len(k), drop = FALSE], 2, sv$d[seq_len(k)] * signs, "*")
} else {
loadings <- matrix(0, p, 0); scores <- matrix(0, n, 0)
}
lr_ss <- sum(sv$d[seq_len(rank)]^2)
lr_prop <- if (rank > 0) sv$d[seq_len(rank)]^2 / lr_ss else numeric(0)
if (rank == 0) warnings <- c(warnings, "The low-rank part is empty: λ is so small that the sparse part takes everything. Raise λ.")
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-93840/discover.robust_pca/planted_cells/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(k)) emb[[paste0("dim_", j)]] <- scores[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
w <- which(flagged, arr.ind = TRUE)
fi <- unname(w[, 1]); fj <- unname(w[, 2])
ord <- order(-abs(S[cbind(fi, fj)]), fi, fj) # largest sparse part first; ties by row, then column
fi <- fi[ord]; fj <- fj[ord]
cells <- data.frame(row = as.integer(rows[fi]), column = FEATURES[fj], value = X[cbind(fi, fj)],
fitted = L[cbind(fi, fj)] * scale[fj] + center[fj], sparse = S[cbind(fi, fj)] * scale[fj],
stringsAsFactors = FALSE)
nanoparquet::write_parquet(cells, file.path(out, "cells.parquet"))
# %% Result
values <- list(n = n, n_variables = p, rank = rank, lambda = lam, n_flagged = n_flagged,
flagged_share = n_flagged / (n * p), rows_flagged = rows_flagged, sparse_share = sparse_share,
n_components = k)
per_var <- colSums(flagged)
for (i in seq_along(FEATURES)) values[[sprintf("flagged[%s]", FEATURES[i])]] <- per_var[i]
for (j in seq_len(rank)) values[[sprintf("lowrank_prop[%d]", j)]] <- lr_prop[j]
for (j in seq_len(k)) {
values[[sprintf("score_check[%d]", j)]] <- cs_ml_checksum(scores[, j], rows)
for (i in seq_along(FEATURES)) values[[sprintf("loading[%d:%s]", j, FEATURES[i])]] <- loadings[i, j]
}
top <- min(nrow(cells), 50L)
tables <- list(
list(key = "cells",
title = sprintf("Flagged cells (sparse part beyond %s scaled units)%s", format(FLAG), if (top == nrow(cells)) "" else sprintf(", largest %d of %d", top, nrow(cells))),
columns = list(list(key = "row", label = "Row", type = "integer"),
list(key = "variable", label = "Variable"),
list(key = "value", label = "Value", type = "number"),
list(key = "fitted", label = "Low-rank fit", type = "number"),
list(key = "sparse", label = "Sparse part", type = "number")),
rows = lapply(seq_len(top), function(i) list(row = cells$row[i] + 1L, variable = cells$column[i], value = cells$value[i],
fitted = cells$fitted[i], sparse = cells$sparse[i]))),
list(key = "variables", title = "Flagged cells by variable",
columns = list(list(key = "variable", label = "Variable"),
list(key = "flagged", label = "Flagged cells", type = "integer"),
list(key = "share", label = "Share of rows", type = "percent"),
list(key = "center", label = "Center", type = "number"),
list(key = "scale", label = "Scale", type = "number")),
rows = lapply(seq_along(FEATURES), function(i) list(variable = FEATURES[i], flagged = per_var[[i]], share = per_var[[i]] / n,
center = center[i], scale = scale[i])))
)
if (k > 0) {
tables[[3]] <- list(key = "loadings", title = "Loadings of the low-rank part",
columns = c(list(list(key = "variable", label = "Variable")),
lapply(seq_len(k), function(j) list(key = paste0("lc", j), label = paste0("LC", j), type = "number"))),
rows = lapply(seq_along(FEATURES), function(i) {
r <- list(variable = FEATURES[i])
for (j in seq_len(k)) r[[paste0("lc", j)]] <- loadings[i, j]
r
}))
}
charts <- list()
if (rank > 0) {
charts[[length(charts) + 1L]] <- cs_chart("scree", "scree-plot", "Low-rank part: variation by component", list(
component = cs_col("Component", seq_len(rank), "numeric"),
variance = cs_col("Share of the low-rank part", lr_prop, "numeric"),
cumulative = cs_col("Cumulative", cumsum(lr_prop), "numeric")
))
}
if (n_flagged > 0) {
wr <- which(flagged, arr.ind = TRUE)
wr <- wr[order(wr[, 1], wr[, 2]), , drop = FALSE] # row by row, like numpy's nonzero
charts[[length(charts) + 1L]] <- cs_chart("flagged", "bar", "Flagged cells by variable", list(
x = cs_col("Variable", FEATURES[wr[, 2]], "categorical", levels = FEATURES)
))
}
if (k >= 2) {
pick <- chart_rows(n)
lab <- if (!is.null(LABEL)) as.character(df[[LABEL]][rows[pick] + 1L]) else rep("", length(pick))
lab[is.na(lab)] <- ""
reach <- max(abs(scores[pick, 1:2])) / max(max(abs(loadings[, 1:2])), 1e-12) * 0.8
charts[[length(charts) + 1L]] <- cs_chart("biplot", "biplot", "Biplot of the low-rank part (LC1 × LC2)", list(
x = cs_col("LC1", c(scores[pick, 1], loadings[, 1] * reach), "numeric"),
y = cs_col("LC2", c(scores[pick, 2], loadings[, 2] * reach), "numeric"),
kind = cs_col("Kind", c(rep("point", length(pick)), rep("loading", p)), "categorical"),
label = cs_col(if (is.null(LABEL)) "Label" else LABEL, c(lab, FEATURES), "categorical")
), note = "Loading arrows are rescaled to the score range.")
}
cs_publish(list(
title = "Robust PCA (cell outliers)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = n,
summary = sprintf("Robust PCA split the data into a rank-%d part and a sparse part; %d of %d cells (%.1f%%) are flagged.",
rank, n_flagged, n * p, 100 * n_flagged / (n * p)),
statistics = list(list(key = "rank", label = "Low-rank part: rank", value = rank, format = "integer"),
list(key = "n_flagged", label = "Flagged cells", value = n_flagged, format = "integer"),
list(key = "rows_flagged", label = "Rows with a flagged cell", value = rows_flagged, format = "integer")),
notes = list("Robust PCA flags single cells, not whole rows: a row is unusual only when many of its cells are flagged."),
tables = tables,
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"),
list(key = "cells", path = file.path(out, "cells.parquet"), format = "parquet"))
))
Robust PCA split the data into a rank-3 part and a sparse part; 15 of 960 cells (1.6%) are flagged.
- Low-rank part: rank
- 3
- Flagged cells
- 15
- Rows with a flagged cell
- 13
To keep this page light, the plots are shown once, under the R tab.
Flagged cells (sparse part beyond 2 scaled units)
| Row | Variable | Value | Low-rank fit | Sparse part |
|---|---|---|---|---|
| 75 | m4 | 7.540 | 0.7269 | 6.813 |
| 111 | m4 | 6.832 | 0.6736 | 6.158 |
| 103 | m2 | 6.827 | −0.7571 | 7.584 |
| 99 | m2 | 7.555 | 0.0238 | 7.531 |
| 19 | m5 | 7.974 | 0.5421 | 7.432 |
| 19 | m6 | 5.648 | −0.4970 | 6.145 |
| 98 | m5 | −7.087 | −0.1626 | −6.925 |
| 31 | m5 | 8.997 | 2.265 | 6.732 |
| 77 | m7 | 8.675 | 0.5876 | 8.087 |
| 42 | m3 | 8.707 | 0.1939 | 8.513 |
| 72 | m1 | −6.394 | 0.0434 | −6.438 |
| 9 | m7 | −7.063 | −0.1119 | −6.951 |
| 72 | m7 | −7.084 | −0.5234 | −6.561 |
| 115 | m7 | 5.609 | −0.5466 | 6.155 |
| 51 | m8 | −11.312 | −2.556 | −8.756 |
Flagged cells by variable
| Variable | Flagged cells | Share of rows | Center | Scale |
|---|---|---|---|---|
| m1 | 1 | 0.8% | 0.2471 | 1.345 |
| m2 | 2 | 1.7% | 0.0802 | 0.8986 |
| m3 | 1 | 0.8% | 0.1645 | 1.752 |
| m4 | 2 | 1.7% | −0.0151 | 0.4654 |
| m5 | 3 | 2.5% | 0.2388 | 1.199 |
| m6 | 1 | 0.8% | −0.2309 | 1.011 |
| m7 | 4 | 3.3% | −0.0689 | 1.617 |
| m8 | 1 | 0.8% | −0.5964 | 3.408 |
Loadings of the low-rank part
| Variable | LC1 | LC2 |
|---|---|---|
| m1 | 0.4491 | 0.1197 |
| m2 | −0.2852 | 0.4072 |
| m3 | 0.4501 | −0.2007 |
| m4 | −0.1894 | 0.5481 |
| m5 | 0.4593 | 0.0342 |
| m6 | −0.4223 | −0.1572 |
| m7 | −0.1095 | −0.5254 |
| m8 | −0.2779 | −0.4210 |
- Robust PCA flags single cells, not whole rows: a row is unusual only when many of its cells are flagged.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Robust PCA (cell outliers)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.robust_pca 1.0.0 · spec 63c7f51a131dcaad
# Dataset: rep1_lowrank (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import embed as csembed
from codesplash.ml import rep_linear as rl
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 = ["m1", "m2", "m3", "m4", "m5", "m6", "m7", "m8"]
LABEL = None
df = pd.read_parquet("tests/parity/fixtures/rep1_lowrank.parquet", columns=list(dict.fromkeys(FEATURES + ([LABEL] if LABEL else []))))
n_input = len(df)
warnings = []
cs.check_finite_columns(df, FEATURES)
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.")
cs.check_rows(len(rows), 3, "Robust PCA")
X = csembed.numeric_matrix(df, FEATURES, rows)
# %% Principal component pursuit (ADMM to primal and dual tolerance): low-rank part L + sparse part S = scaled data
Zs, center, scale = rl.robust_center_scale(X, "robust")
if not np.any(Zs != 0):
cs.cs_error("CS_E_CONSTANT", column=FEATURES[0])
n, p = Zs.shape
LAM = None
lam = 1.0 / np.sqrt(max(n, p)) if LAM is None else float(LAM)
L, S, rank, iterations, converged = rl.robust_pca(Zs, lam)
if not converged:
warnings.append("Principal component pursuit stopped after 10,000 iterations before reaching its tolerance; treat the split as approximate.")
FLAG = float(2)
flagged = np.abs(S) > FLAG
n_flagged = int(np.sum(flagged))
rows_flagged = int(np.sum(flagged.any(axis=1)))
total_ss = float(np.sum(Zs * Zs))
sparse_share = float(np.sum(S * S)) / total_ss
# low-rank part: its own principal axes give the map
U, sv, Vt = np.linalg.svd(L, full_matrices=False)
k = min(int(2), rank)
signs = csembed.canonical_signs(Vt[:k].T) if k else np.ones(0)
loadings = Vt[:k].T * signs
scores = U[:, :k] * sv[:k] * signs
lr_ss = float(np.sum(sv[:rank] ** 2))
lr_prop = sv[:rank] ** 2 / lr_ss if rank else np.zeros(0)
if rank == 0:
warnings.append("The low-rank part is empty: λ is so small that the sparse part takes everything. Raise λ.")
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-93840/discover.robust_pca/planted_cells/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(k):
emb[f"dim_{j + 1}"] = scores[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
fi, fj = np.nonzero(flagged)
size = np.abs(S[fi, fj])
order = np.lexsort((fj, fi, -size)) # largest sparse part first; ties by row, then column
fi, fj = fi[order], fj[order]
cells = pd.DataFrame({
"row": rows[fi].astype(np.int64),
"column": [FEATURES[j] for j in fj],
"value": X[fi, fj],
"fitted": L[fi, fj] * scale[fj] + center[fj],
"sparse": S[fi, fj] * scale[fj],
})
cells.to_parquet(os.path.join(out, "cells.parquet"), index=False)
# %% Result
values = {
"n": n,
"n_variables": p,
"rank": int(rank),
"lambda": lam,
"n_flagged": n_flagged,
"flagged_share": n_flagged / (n * p),
"rows_flagged": rows_flagged,
"sparse_share": sparse_share,
"n_components": k,
}
per_var = flagged.sum(axis=0)
for i, f in enumerate(FEATURES):
values[f"flagged[{f}]"] = int(per_var[i])
for j in range(rank):
values[f"lowrank_prop[{j + 1}]"] = float(lr_prop[j])
for j in range(k):
values[f"score_check[{j + 1}]"] = csembed.checksum(scores[:, j], rows)
for i, f in enumerate(FEATURES):
values[f"loading[{j + 1}:{f}]"] = float(loadings[i, j])
top = min(len(cells), 50)
tables = [
{
"key": "cells",
"title": f"Flagged cells (sparse part beyond {FLAG:g} scaled units){'' if top == len(cells) else f', largest {top} of {len(cells)}'}",
"columns": [
{"key": "row", "label": "Row", "type": "integer"},
{"key": "variable", "label": "Variable"},
{"key": "value", "label": "Value", "type": "number"},
{"key": "fitted", "label": "Low-rank fit", "type": "number"},
{"key": "sparse", "label": "Sparse part", "type": "number"},
],
"rows": [
{"row": int(cells["row"].iloc[i]) + 1, "variable": cells["column"].iloc[i], "value": float(cells["value"].iloc[i]),
"fitted": float(cells["fitted"].iloc[i]), "sparse": float(cells["sparse"].iloc[i])}
for i in range(top)
],
},
{
"key": "variables",
"title": "Flagged cells by variable",
"columns": [
{"key": "variable", "label": "Variable"},
{"key": "flagged", "label": "Flagged cells", "type": "integer"},
{"key": "share", "label": "Share of rows", "type": "percent"},
{"key": "center", "label": "Center", "type": "number"},
{"key": "scale", "label": "Scale", "type": "number"},
],
"rows": [{"variable": f, "flagged": int(per_var[i]), "share": float(per_var[i]) / n, "center": float(center[i]), "scale": float(scale[i])} for i, f in enumerate(FEATURES)],
},
]
if k:
tables.append({
"key": "loadings",
"title": "Loadings of the low-rank part",
"columns": [{"key": "variable", "label": "Variable"}] + [{"key": f"lc{j + 1}", "label": f"LC{j + 1}", "type": "number"} for j in range(k)],
"rows": [dict({"variable": f}, **{f"lc{j + 1}": loadings[i, j] for j in range(k)}) for i, f in enumerate(FEATURES)],
})
charts = []
if rank:
charts.append(cs.chart(
"scree",
"scree-plot",
"Low-rank part: variation by component",
{
"component": cs.col("Component", list(range(1, rank + 1)), "numeric"),
"variance": cs.col("Share of the low-rank part", lr_prop, "numeric"),
"cumulative": cs.col("Cumulative", np.cumsum(lr_prop), "numeric"),
},
))
if n_flagged:
charts.append(cs.chart(
"flagged",
"bar",
"Flagged cells by variable",
{"x": cs.col("Variable", [FEATURES[j] for j in np.nonzero(flagged)[1]], "categorical", levels=FEATURES)},
))
if k >= 2:
pick = chart_rows(n)
lab = ["" if LABEL is None else str(v) for v in df.iloc[rows[pick]][LABEL]] if LABEL else [""] * len(pick)
reach = np.max(np.abs(scores[pick, :2])) / max(np.max(np.abs(loadings[:, :2])), 1e-12) * 0.8
charts.append(cs.chart(
"biplot",
"biplot",
"Biplot of the low-rank part (LC1 × LC2)",
{
"x": cs.col("LC1", np.concatenate([scores[pick, 0], loadings[:, 0] * reach]), "numeric"),
"y": cs.col("LC2", np.concatenate([scores[pick, 1], loadings[:, 1] * reach]), "numeric"),
"kind": cs.col("Kind", ["point"] * len(pick) + ["loading"] * p, "categorical"),
"label": cs.col(LABEL or "Label", lab + FEATURES, "categorical"),
},
note="Loading arrows are rescaled to the score range.",
))
cs.publish(
{
"title": "Robust PCA (cell outliers)",
"engine": cs.engine_info("numpy", "pandas"),
"n": n,
"summary": f"Robust PCA split the data into a rank-{rank} part and a sparse part; {n_flagged} of {n * p} cells ({n_flagged / (n * p):.1%}) are flagged.",
"statistics": [
{"key": "rank", "label": "Low-rank part: rank", "value": int(rank), "format": "integer"},
{"key": "n_flagged", "label": "Flagged cells", "value": n_flagged, "format": "integer"},
{"key": "rows_flagged", "label": "Rows with a flagged cell", "value": rows_flagged, "format": "integer"},
],
"notes": ["Robust PCA flags single cells, not whole rows: a row is unusual only when many of its cells are flagged."],
"tables": tables,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [
{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"},
{"key": "cells", "path": os.path.join(out, "cells.parquet"), "format": "parquet"},
],
}
)
On a table of 120 rows with planted bad cells, it recovered a rank-3 pattern and flagged 15 cells (1.6%) in 13 rows, with = 0.0913.
It works when errors are scattered cells and the pattern is spread across many rows. It is not general protection against whole bad rows, and a real sparse signal, such as one genuinely unusual store-month, gets flagged as "error" too.
Functional PCA: rows that are curves
ReadWhen each row is a curve, such as a growth trajectory or a spectrum, functional PCAFunctional PCAPCA where each observation is a whole curve: a mean curve plus a few eigenfunctions, each curve a score on each. writes
The eigenfunctionsEigenfunctionA curve φ(t) with ∫φ² dt = 1 along which the curves vary most; successive ones are orthogonal under the integral. are smooth modes of variation, orthonormal under an integral, so uneven time spacing is respected. Read each as "mean curve plus or minus a multiple of ".
Functional PCA of 45 curves of weight on 12 time points: the first 3 components explain 99.5% of the variance between curves (component 1 alone 93.0%).
- Variance explained by 3 components
- 0.9947
- Mean integrated squared error
- 138.98
Plots
View data
| Component | Cumulative share | Share of variance |
|---|---|---|
| 1 | 0.9299 | 0.9299 |
| 2 | 0.9866 | 0.0567 |
| 3 | 0.9947 | 0.0081 |
| 4 | 0.9966 | 0.0019 |
| 5 | 0.9976 | 0.0011 |
| 6 | 0.9984 | 0.0008 |
| 7 | 0.9990 | 0.0006 |
| 8 | 0.9993 | 0.0003 |
| 9 | 0.9997 | 0.0003 |
| 10 | 0.9999 | 0.0002 |
View data
| curve | Time | weight |
|---|---|---|
| Mean | 0 | 41.067 |
| Mean | 2 | 49.578 |
| Mean | 4 | 60.156 |
| Mean | 6 | 74.867 |
| Mean | 8 | 92.422 |
| Mean | 10 | 110.09 |
| Mean | 12 | 132.78 |
| Mean | 14 | 146.24 |
| Mean | 16 | 169.53 |
| Mean | 18 | 192.42 |
| Mean | 20 | 211.60 |
| Mean | 21 | 218.69 |
| Mean + 2√λ·φ | 0 | 40.396 |
| Mean + 2√λ·φ | 2 | 50.713 |
| Mean + 2√λ·φ | 4 | 64.546 |
| Mean + 2√λ·φ | 6 | 85.943 |
| Mean + 2√λ·φ | 8 | 116.99 |
| Mean + 2√λ·φ | 10 | 148.36 |
| Mean + 2√λ·φ | 12 | 191.12 |
| Mean + 2√λ·φ | 14 | 218.17 |
| Mean + 2√λ·φ | 16 | 263.32 |
| Mean + 2√λ·φ | 18 | 307.03 |
| Mean + 2√λ·φ | 20 | 340.46 |
| Mean + 2√λ·φ | 21 | 355.73 |
| Mean − 2√λ·φ | 0 | 41.737 |
| Mean − 2√λ·φ | 2 | 48.442 |
| Mean − 2√λ·φ | 4 | 55.765 |
| Mean − 2√λ·φ | 6 | 63.791 |
| Mean − 2√λ·φ | 8 | 67.857 |
| Mean − 2√λ·φ | 10 | 71.822 |
| Mean − 2√λ·φ | 12 | 74.433 |
| Mean − 2√λ·φ | 14 | 74.319 |
| Mean − 2√λ·φ | 16 | 75.747 |
| Mean − 2√λ·φ | 18 | 77.819 |
| Mean − 2√λ·φ | 20 | 82.743 |
| Mean − 2√λ·φ | 21 | 81.648 |
View data
| curve | Time | weight |
|---|---|---|
| Mean | 0 | 41.067 |
| Mean | 2 | 49.578 |
| Mean | 4 | 60.156 |
| Mean | 6 | 74.867 |
| Mean | 8 | 92.422 |
| Mean | 10 | 110.09 |
| Mean | 12 | 132.78 |
| Mean | 14 | 146.24 |
| Mean | 16 | 169.53 |
| Mean | 18 | 192.42 |
| Mean | 20 | 211.60 |
| Mean | 21 | 218.69 |
| Mean + 2√λ·φ | 0 | 41.257 |
| Mean + 2√λ·φ | 2 | 51.237 |
| Mean + 2√λ·φ | 4 | 63.476 |
| Mean + 2√λ·φ | 6 | 83.028 |
| Mean + 2√λ·φ | 8 | 108.84 |
| Mean + 2√λ·φ | 10 | 132.32 |
| Mean + 2√λ·φ | 12 | 159.10 |
| Mean + 2√λ·φ | 14 | 166.78 |
| Mean + 2√λ·φ | 16 | 177.03 |
| Mean + 2√λ·φ | 18 | 182.67 |
| Mean + 2√λ·φ | 20 | 184.23 |
| Mean + 2√λ·φ | 21 | 180.33 |
| Mean − 2√λ·φ | 0 | 40.876 |
| Mean − 2√λ·φ | 2 | 47.919 |
| Mean − 2√λ·φ | 4 | 56.835 |
| Mean − 2√λ·φ | 6 | 66.705 |
| Mean − 2√λ·φ | 8 | 76.006 |
| Mean − 2√λ·φ | 10 | 87.853 |
| Mean − 2√λ·φ | 12 | 106.46 |
| Mean − 2√λ·φ | 14 | 125.71 |
| Mean − 2√λ·φ | 16 | 162.03 |
| Mean − 2√λ·φ | 18 | 202.17 |
| Mean − 2√λ·φ | 20 | 238.97 |
| Mean − 2√λ·φ | 21 | 257.04 |
View data
| curve | Time | weight |
|---|---|---|
| Mean | 0 | 41.067 |
| Mean | 2 | 49.578 |
| Mean | 4 | 60.156 |
| Mean | 6 | 74.867 |
| Mean | 8 | 92.422 |
| Mean | 10 | 110.09 |
| Mean | 12 | 132.78 |
| Mean | 14 | 146.24 |
| Mean | 16 | 169.53 |
| Mean | 18 | 192.42 |
| Mean | 20 | 211.60 |
| Mean | 21 | 218.69 |
| Mean + 2√λ·φ | 0 | 41.138 |
| Mean + 2√λ·φ | 2 | 53.088 |
| Mean + 2√λ·φ | 4 | 65.070 |
| Mean + 2√λ·φ | 6 | 83.075 |
| Mean + 2√λ·φ | 8 | 101.34 |
| Mean + 2√λ·φ | 10 | 116.59 |
| Mean + 2√λ·φ | 12 | 133.66 |
| Mean + 2√λ·φ | 14 | 140.97 |
| Mean + 2√λ·φ | 16 | 159.27 |
| Mean + 2√λ·φ | 18 | 189.38 |
| Mean + 2√λ·φ | 20 | 218.93 |
| Mean + 2√λ·φ | 21 | 228.81 |
| Mean − 2√λ·φ | 0 | 40.995 |
| Mean − 2√λ·φ | 2 | 46.067 |
| Mean − 2√λ·φ | 4 | 55.242 |
| Mean − 2√λ·φ | 6 | 66.659 |
| Mean − 2√λ·φ | 8 | 83.507 |
| Mean − 2√λ·φ | 10 | 103.59 |
| Mean − 2√λ·φ | 12 | 131.90 |
| Mean − 2√λ·φ | 14 | 151.52 |
| Mean − 2√λ·φ | 16 | 179.80 |
| Mean − 2√λ·φ | 18 | 195.46 |
| Mean − 2√λ·φ | 20 | 204.27 |
| Mean − 2√λ·φ | 21 | 208.57 |
View data
| component | Time | φ |
|---|---|---|
| φ1 | 0 | −0.0021 |
| φ1 | 2 | 0.0036 |
| φ1 | 4 | 0.0139 |
| φ1 | 6 | 0.0351 |
| φ1 | 8 | 0.0778 |
| φ1 | 10 | 0.1212 |
| φ1 | 12 | 0.1847 |
| φ1 | 14 | 0.2278 |
| φ1 | 16 | 0.2970 |
| φ1 | 18 | 0.3629 |
| φ1 | 20 | 0.4080 |
| φ1 | 21 | 0.4339 |
| φ2 | 0 | 0.0024 |
| φ2 | 2 | 0.0213 |
| φ2 | 4 | 0.0426 |
| φ2 | 6 | 0.1047 |
| φ2 | 8 | 0.2105 |
| φ2 | 10 | 0.2852 |
| φ2 | 12 | 0.3376 |
| φ2 | 14 | 0.2634 |
| φ2 | 16 | 0.0962 |
| φ2 | 18 | −0.1251 |
| φ2 | 20 | −0.3510 |
| φ2 | 21 | −0.4919 |
| φ3 | 0 | 0.0024 |
| φ3 | 2 | 0.1190 |
| φ3 | 4 | 0.1666 |
| φ3 | 6 | 0.2783 |
| φ3 | 8 | 0.3023 |
| φ3 | 10 | 0.2206 |
| φ3 | 12 | 0.0298 |
| φ3 | 14 | −0.1789 |
| φ3 | 16 | −0.3482 |
| φ3 | 18 | −0.1031 |
| φ3 | 20 | 0.2485 |
| φ3 | 21 | 0.3433 |
View data
| Chick | Score 1 | Score 2 |
|---|---|---|
| 1 | −65.479 | −36.830 |
| 10 | −225.76 | −5.329 |
| 11 | 10.886 | 98.296 |
| 12 | −42.756 | −26.979 |
| 13 | −313.34 | −19.182 |
| 14 | 152.14 | 20.561 |
| 17 | −188.00 | 4.022 |
| 19 | −205.15 | −45.334 |
| 2 | −21.830 | −17.836 |
| 20 | −246.98 | −21.191 |
| 21 | 327.84 | 60.620 |
| 22 | −124.42 | −2.437 |
| 23 | −80.311 | 20.194 |
| 24 | −331.60 | 0.9428 |
| 25 | 101.48 | −9.684 |
| 26 | 33.167 | −19.512 |
| 27 | −79.248 | −9.996 |
| 28 | 32.152 | 10.117 |
| 29 | 98.722 | −65.907 |
| 3 | −34.858 | −17.382 |
| 30 | −116.09 | 15.346 |
| 31 | 20.557 | −43.073 |
| 32 | 181.21 | −17.030 |
| 33 | −92.733 | 59.353 |
| 34 | 248.27 | −39.530 |
| 35 | 380.35 | 8.663 |
| 36 | 66.401 | 14.062 |
| 37 | −116.83 | −26.024 |
| 38 | 101.73 | −56.682 |
| 39 | 49.318 | −41.958 |
| 4 | −130.70 | −18.369 |
| 40 | 179.10 | −33.718 |
| 41 | 3.422 | 47.037 |
| 42 | 128.22 | −0.6616 |
| 43 | 65.677 | 120.11 |
| 45 | −39.391 | 19.316 |
| 46 | 43.778 | 5.036 |
| 47 | 5.062 | 33.777 |
| 48 | 183.79 | −39.135 |
| 49 | 57.050 | 27.115 |
| 5 | 33.776 | 0.6040 |
| 50 | 120.16 | 2.607 |
| 6 | −69.305 | 63.691 |
| 7 | 153.16 | −44.446 |
| 9 | −252.61 | 26.759 |
Components
| Component | Eigenvalue | Share of variance | Cumulative |
|---|---|---|---|
| 1 | 24933.26 | 93.0% | 93.0% |
| 2 | 1519.99 | 5.7% | 98.7% |
| 3 | 217.40 | 0.8% | 99.5% |
| 4 | 50.369 | 0.2% | 99.7% |
| 5 | 28.407 | 0.1% | 99.8% |
| 6 | 20.870 | 0.1% | 99.8% |
| 7 | 16.124 | 0.1% | 99.9% |
| 8 | 8.903 | 0.0% | 99.9% |
| 9 | 8.112 | 0.0% | 100.0% |
| 10 | 5.605 | 0.0% | 100.0% |
Mean curve and eigenfunctions
| Time | Mean | φ1 | φ2 | φ3 |
|---|---|---|---|---|
| 0 | 41.067 | −0.0021 | 0.0024 | 0.0024 |
| 2 | 49.578 | 0.0036 | 0.0213 | 0.1190 |
| 4 | 60.156 | 0.0139 | 0.0426 | 0.1666 |
| 6 | 74.867 | 0.0351 | 0.1047 | 0.2783 |
| 8 | 92.422 | 0.0778 | 0.2105 | 0.3023 |
| 10 | 110.09 | 0.1212 | 0.2852 | 0.2206 |
| 12 | 132.78 | 0.1847 | 0.3376 | 0.0298 |
| 14 | 146.24 | 0.2278 | 0.2634 | −0.1789 |
| 16 | 169.53 | 0.2970 | 0.0962 | −0.3482 |
| 18 | 192.42 | 0.3629 | −0.1251 | −0.1031 |
| 20 | 211.60 | 0.4080 | −0.3510 | 0.2485 |
| 21 | 218.69 | 0.4339 | −0.4919 | 0.3433 |
Curve scores
| Chick | Score 1 | Score 2 | Score 3 | Integrated squared error |
|---|---|---|---|---|
| 1 | −65.479 | −36.830 | −5.887 | 118.19 |
| 10 | −225.76 | −5.329 | −5.353 | 103.73 |
| 11 | 10.886 | 98.296 | −3.793 | 18.797 |
| 12 | −42.756 | −26.979 | −29.337 | 122.88 |
| 13 | −313.34 | −19.182 | 2.540 | 58.762 |
| 14 | 152.14 | 20.561 | −24.329 | 79.058 |
| 17 | −188.00 | 4.022 | 8.641 | 51.345 |
| 19 | −205.15 | −45.334 | −1.879 | 69.410 |
| 2 | −21.830 | −17.836 | −3.605 | 19.740 |
| 20 | −246.98 | −21.191 | −13.882 | 42.253 |
| 21 | 327.84 | 60.620 | −16.699 | 100.41 |
| 22 | −124.42 | −2.437 | 16.146 | 179.86 |
| 23 | −80.311 | 20.194 | −0.9476 | 82.436 |
| 24 | −331.60 | 0.9428 | 5.373 | 255.23 |
| 25 | 101.48 | −9.684 | 7.122 | 64.948 |
| 26 | 33.167 | −19.512 | 12.510 | 175.20 |
| 27 | −79.248 | −9.996 | 6.263 | 54.532 |
| 28 | 32.152 | 10.117 | −14.381 | 169.50 |
| 29 | 98.722 | −65.907 | 13.118 | 201.58 |
| 3 | −34.858 | −17.382 | −18.971 | 244.06 |
| 30 | −116.09 | 15.346 | −9.689 | 99.970 |
| 31 | 20.557 | −43.073 | 7.121 | 63.574 |
| 32 | 181.21 | −17.030 | 6.474 | 84.219 |
| 33 | −92.733 | 59.353 | −4.708 | 162.30 |
| 34 | 248.27 | −39.530 | 10.938 | 245.45 |
| 35 | 380.35 | 8.663 | −8.680 | 88.855 |
| 36 | 66.401 | 14.062 | −21.559 | 435.26 |
| 37 | −116.83 | −26.024 | −6.080 | 110.31 |
| 38 | 101.73 | −56.682 | 13.432 | 193.70 |
| 39 | 49.318 | −41.958 | 18.195 | 104.41 |
| 4 | −130.70 | −18.369 | −13.926 | 209.65 |
| 40 | 179.10 | −33.718 | 6.219 | 193.07 |
| 41 | 3.422 | 47.037 | 10.078 | 190.20 |
| 42 | 128.22 | −0.6616 | 10.524 | 103.96 |
| 43 | 65.677 | 120.11 | 19.953 | 68.472 |
| 45 | −39.391 | 19.316 | 20.707 | 161.85 |
| 46 | 43.778 | 5.036 | 16.406 | 89.230 |
| 47 | 5.062 | 33.777 | 12.050 | 169.67 |
| 48 | 183.79 | −39.135 | 11.046 | 153.96 |
| 49 | 57.050 | 27.115 | 17.997 | 89.074 |
First 40 of 45 rows.
Curves left out
| Chick | Why |
|---|---|
| 15 | ends before the last time |
| 16 | ends before the last time |
| 18 | ends before the last time |
| 44 | ends before the last time |
| 8 | ends before the last time |
- 5 curve(s) don't cover the whole time range and were left out (FPCA doesn't extrapolate): 15, 16, 18, 44, 8.
- Integrals use the trapezoid rule on the common grid, so uneven time steps count by their length; eigenvalues are the variance of each component's scores (divisor n − 1) and each eigenfunction has ∫φ² dt = 1, signed so ∫φ dt ≥ 0.
- Read a component by its mean ± 2 SD chart: it shows how curves with a high or low score differ from the average curve.
- Phase variation (the same shape shifted in time) shows up as extra components; align the curves first when timing differences aren't of interest.
The exact R script · R R version 4.5.1 (2025-06-13)
# Functional PCA (main shapes of a set of curves)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.fpca 1.0.0 · spec 43928583d1219167
# Dataset: ml_chickweight (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_chickweight.parquet", col_select = c("Chick", "Time", "weight")))
n_input <- nrow(df)
df[["Chick"]] <- factor(df[["Chick"]], levels = c("1", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "2", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "3", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "4", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "5", "50", "6", "7", "8", "9")) # stored level order
df <- df[stats::complete.cases(df[c("Chick", "Time", "weight")]), , 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("Chick", "Time", "weight")) # infinite values stop the run (registry/errors.yaml)
# %% Curves
# Functional PCA (Ramsay & Silverman 2005): curves in long form (curve, time, value) on a common grid,
# trapezoid quadrature, optional Whittaker pre-smoothing, eigenfunctions orthonormal under the integral.
CURVE <- "Chick"
TIME <- "Time"
VALUE <- "weight"
TEMPORAL <- FALSE
Q <- as.integer(3)
SMOOTHING <- "none" # none | gcv | manual
LOG_LAMBDA <- as.numeric(-2)
cs_check_rows(nrow(df), 9, "Functional PCA")
cs_check_groups(as.character(df[[CURVE]]), CURVE, minimum = 3)
cs_check_not_constant(as.numeric(df[[VALUE]]), VALUE)
traw <- df[[TIME]]
tnum <- if (TEMPORAL) {
if (inherits(traw, "POSIXt")) as.numeric(traw) / 86400 else as.numeric(as.Date(traw))
} else as.numeric(traw)
cs_check_not_constant(tnum, TIME)
curve_levels <- as.character(levels(df[[CURVE]]))
g <- cs_fpca_grid(as.integer(df[[CURVE]]), length(curve_levels), tnum, as.numeric(df[[VALUE]]))
grid <- g$grid
Y <- g$Y
kept <- curve_levels[g$kept]
if (length(kept) < 3)
cs_error("CS_E_UNDEFINED", what = "Functional PCA", reason = sprintf("only %d curve(s) cover the whole time range (at least 3 are needed)", length(kept)))
if (length(grid) < 3)
cs_error("CS_E_UNDEFINED", what = "Functional PCA", reason = sprintf("the curves share only %d time point(s) (at least 3 are needed)", length(grid)))
if (length(grid) > 500)
cs_error("CS_E_UNDEFINED", what = "Functional PCA", reason = sprintf("the common grid has %d time points (at most 500; aggregate the times first)", length(grid)))
if (g$n_dup > 0) warnings <- c(warnings, sprintf("%d row(s) repeated a curve's time; each such point uses the mean of its values.", g$n_dup))
if (length(g$dropped)) {
dn <- vapply(g$dropped, function(dd) curve_levels[dd$code], "")
warnings <- c(warnings, paste0(sprintf("%d curve(s) don't cover the whole time range and were left out (FPCA doesn't extrapolate): ", length(dn)),
paste(head(dn, 10), collapse = ", "), if (length(dn) > 10) " …" else "", "."))
}
share_interp <- g$n_interp / (length(kept) * length(grid))
if (share_interp > 0.5)
cs_error("CS_E_UNDEFINED", what = "Functional PCA", reason = sprintf("%.0f%% of the grid values would be interpolated (curves measured at different times need sparse-data methods)", 100 * share_interp))
if (g$n_interp > 0)
warnings <- c(warnings, sprintf("%d grid value(s) (%.1f%%) were filled by straight lines between a curve's neighboring measurements.", g$n_interp, 100 * share_interp))
w <- cs_fpca_weights(grid)
values <- list(n_curves = length(kept), n_dropped_curves = length(g$dropped), n_grid = length(grid), n_interpolated = g$n_interp,
smoothing = SMOOTHING, log_lambda = NaN, edf = NaN, gcv = NaN)
Ys <- Y
if (SMOOTHING != "none") {
sm <- cs_fpca_smooth(Y, grid, w, if (SMOOTHING == "gcv") NULL else LOG_LAMBDA)
Ys <- sm$Y
values$log_lambda <- sm$log_lambda
values$edf <- sm$edf
values$gcv <- sm$gcv
}
# %% Decompose
fit <- cs_fpca_fit(Ys, w, Q)
q <- fit$q
if (q < Q) warnings <- c(warnings, sprintf("Only %d component(s) are available (the curves span %d dimension(s)); %d were requested.", q, fit$rank, Q))
ev <- fit$eigenvalues
values$components <- q
values$total_variance <- fit$total
values$explained <- sum(ev[seq_len(q)]) / fit$total
values$recon_error <- mean(fit$ise)
cum <- 0
comp_rows <- list()
for (k in seq_along(ev)) {
share <- ev[k] / fit$total
cum <- cum + share
if (k <= max(q, min(length(ev), 10))) comp_rows[[length(comp_rows) + 1]] <- list(component = k, eigenvalue = ev[k], share = share, cumulative = cum)
if (k <= q) {
values[[sprintf("eigen[%d]", k)]] <- ev[k]
values[[sprintf("share[%d]", k)]] <- share
values[[sprintf("cumulative[%d]", k)]] <- cum
values[[sprintf("phi_check[%d]", k)]] <- sum(seq_along(grid) * w * fit$phi[, k])
values[[sprintf("score_check[%d]", k)]] <- sum(seq_along(kept) * fit$scores[, k])
}
}
grid_labels <- if (TEMPORAL) format(as.Date(grid, origin = "1970-01-01"), "%Y-%m-%d") else sprintf("%.10g", grid)
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-82309/discover.fpca/chickweight-growth/out-r")
artifacts <- list()
modes <- list(list(name = CURVE, levels = kept, F = fit$scores), list(name = TIME, levels = grid_labels, F = fit$phi))
for (md in modes) {
fdf <- data.frame(level = md$levels, stringsAsFactors = FALSE)
for (k in seq_len(q)) fdf[[sprintf("factor_%d", k)]] <- md$F[, k]
path <- file.path(out, sprintf("factors_%s.parquet", md$name))
nanoparquet::write_parquet(fdf, path)
artifacts[[length(artifacts) + 1]] <- list(key = sprintf("factors_%s", md$name), path = path, format = "parquet")
}
# %% Charts
xkind <- if (TEMPORAL) "temporal" else "numeric"
xvals <- if (TEMPORAL) grid_labels else grid
charts <- list(cs_chart("scree", "scree-plot", "Share of the curves' variance by component", list(
component = cs_col("Component", as.numeric(vapply(comp_rows, function(r) r$component, numeric(1)))),
variance = cs_col("Share of variance", vapply(comp_rows, function(r) r$share, numeric(1))),
cumulative = cs_col("Cumulative share", vapply(comp_rows, function(r) r$cumulative, numeric(1))))))
for (k in seq_len(min(q, 3))) {
amp <- 2 * sqrt(ev[k])
ys <- c(fit$mean, fit$mean + amp * fit$phi[, k], fit$mean - amp * fit$phi[, k])
labs <- rep(c("Mean", "Mean + 2√λ·φ", "Mean − 2√λ·φ"), each = length(grid))
charts[[length(charts) + 1]] <- cs_chart(sprintf("mode%d", k), "series-line",
sprintf("Component %d (%.0f%% of the variance): the mean curve moved by ±2 SD", k, 100 * ev[k] / fit$total), list(
x = cs_col(TIME, rep(xvals, 3), kind = xkind), y = cs_col(VALUE, ys), group = cs_col("curve", labs, kind = "categorical")))
}
if (q >= 1) {
charts[[length(charts) + 1]] <- cs_chart("eigenfunctions", "series-line", "Eigenfunctions φ(t)", list(
x = cs_col(TIME, rep(xvals, q), kind = xkind), y = cs_col("φ", as.vector(fit$phi)),
group = cs_col("component", rep(sprintf("φ%d", seq_len(q)), each = length(grid)), kind = "categorical")))
}
if (q >= 2) {
charts[[length(charts) + 1]] <- cs_chart("scores", "embedding-map", "Curve scores on the first two components", list(
x = cs_col("Score 1", fit$scores[, 1]), y = cs_col("Score 2", fit$scores[, 2]), label = cs_col(CURVE, kept, kind = "categorical")))
}
# %% Tables
tables <- list(
list(key = "components", title = "Components",
columns = list(list(key = "component", label = "Component", type = "integer"), list(key = "eigenvalue", label = "Eigenvalue", type = "number"),
list(key = "share", label = "Share of variance", type = "percent"), list(key = "cumulative", label = "Cumulative", type = "percent")),
rows = comp_rows),
list(key = "functions", title = "Mean curve and eigenfunctions",
columns = c(list(list(key = "time", label = TIME, type = "string"), list(key = "mean", label = "Mean", type = "number")),
lapply(seq_len(q), function(k) list(key = sprintf("phi%d", k), label = sprintf("φ%d", k), type = "number"))),
rows = lapply(seq_along(grid), function(j) c(list(time = grid_labels[j], mean = fit$mean[j]),
stats::setNames(as.list(fit$phi[j, seq_len(q)]), sprintf("phi%d", seq_len(q)))))),
list(key = "scores", title = "Curve scores",
columns = c(list(list(key = "curve", label = CURVE, type = "string")),
lapply(seq_len(q), function(k) list(key = sprintf("s%d", k), label = sprintf("Score %d", k), type = "number")),
list(list(key = "ise", label = "Integrated squared error", type = "number"))),
rows = lapply(seq_along(kept), function(i) c(list(curve = kept[i]), stats::setNames(as.list(fit$scores[i, seq_len(q)]), sprintf("s%d", seq_len(q))),
list(ise = fit$ise[i])))))
if (length(g$dropped)) {
tables[[length(tables) + 1]] <- list(key = "dropped", title = "Curves left out",
columns = list(list(key = "curve", label = CURVE, type = "string"), list(key = "reason", label = "Why", type = "string")),
rows = lapply(g$dropped, function(dd) list(curve = curve_levels[dd$code], reason = dd$reason)))
}
# %% Result
summary <- paste0(sprintf("Functional PCA of %d curves of %s on %d time points: the first %d component%s explain %.1f%% of the variance between curves",
length(kept), VALUE, length(grid), q, if (q != 1) "s" else "", 100 * values$explained),
if (q > 1) sprintf(" (component 1 alone %.1f%%)", 100 * ev[1] / fit$total) else "", ".")
notes <- c(paste0("Integrals use the trapezoid rule on the common grid, so uneven time steps count by their length; eigenvalues are the variance of each ",
"component's scores (divisor n − 1) and each eigenfunction has ∫φ² dt = 1, signed so ∫φ dt ≥ 0."),
"Read a component by its mean ± 2 SD chart: it shows how curves with a high or low score differ from the average curve.")
if (SMOOTHING != "none") {
notes <- c(notes, paste0(sprintf("Curves were smoothed first with a second-difference penalty (λ = 10^%.2f relative to the grid, %.2f effective degrees of freedom of %d",
values$log_lambda, values$edf, length(grid)),
if (SMOOTHING == "gcv") "; chosen by generalized cross-validation" else "", ")."))
}
notes <- c(notes, "Phase variation (the same shape shifted in time) shows up as extra components; align the curves first when timing differences aren't of interest.")
cs_publish(list(
title = "Functional PCA (main shapes of a set of curves)",
engine = cs_engine_info("nanoparquet"),
n = length(kept),
summary = summary,
statistics = list(list(key = "explained", label = sprintf("Variance explained by %d components", q), value = values$explained),
list(key = "recon_error", label = "Mean integrated squared error", value = values$recon_error)),
tables = tables,
charts = charts,
values = values,
warnings = warnings,
notes = notes,
artifacts = artifacts
))
Functional PCA of 45 curves of weight on 12 time points: the first 3 components explain 99.5% of the variance between curves (component 1 alone 93.0%).
- Variance explained by 3 components
- 0.9947
- Mean integrated squared error
- 138.98
To keep this page light, the plots are shown once, under the R tab.
Components
| Component | Eigenvalue | Share of variance | Cumulative |
|---|---|---|---|
| 1 | 24933.26 | 93.0% | 93.0% |
| 2 | 1519.99 | 5.7% | 98.7% |
| 3 | 217.40 | 0.8% | 99.5% |
| 4 | 50.369 | 0.2% | 99.7% |
| 5 | 28.407 | 0.1% | 99.8% |
| 6 | 20.870 | 0.1% | 99.8% |
| 7 | 16.124 | 0.1% | 99.9% |
| 8 | 8.903 | 0.0% | 99.9% |
| 9 | 8.112 | 0.0% | 100.0% |
| 10 | 5.605 | 0.0% | 100.0% |
Mean curve and eigenfunctions
| Time | Mean | φ1 | φ2 | φ3 |
|---|---|---|---|---|
| 0 | 41.067 | −0.0021 | 0.0024 | 0.0024 |
| 2 | 49.578 | 0.0036 | 0.0213 | 0.1190 |
| 4 | 60.156 | 0.0139 | 0.0426 | 0.1666 |
| 6 | 74.867 | 0.0351 | 0.1047 | 0.2783 |
| 8 | 92.422 | 0.0778 | 0.2105 | 0.3023 |
| 10 | 110.09 | 0.1212 | 0.2852 | 0.2206 |
| 12 | 132.78 | 0.1847 | 0.3376 | 0.0298 |
| 14 | 146.24 | 0.2278 | 0.2634 | −0.1789 |
| 16 | 169.53 | 0.2970 | 0.0962 | −0.3482 |
| 18 | 192.42 | 0.3629 | −0.1251 | −0.1031 |
| 20 | 211.60 | 0.4080 | −0.3510 | 0.2485 |
| 21 | 218.69 | 0.4339 | −0.4919 | 0.3433 |
Curve scores
| Chick | Score 1 | Score 2 | Score 3 | Integrated squared error |
|---|---|---|---|---|
| 1 | −65.479 | −36.830 | −5.887 | 118.19 |
| 10 | −225.76 | −5.329 | −5.353 | 103.73 |
| 11 | 10.886 | 98.296 | −3.793 | 18.797 |
| 12 | −42.756 | −26.979 | −29.337 | 122.88 |
| 13 | −313.34 | −19.182 | 2.540 | 58.762 |
| 14 | 152.14 | 20.561 | −24.329 | 79.058 |
| 17 | −188.00 | 4.022 | 8.641 | 51.345 |
| 19 | −205.15 | −45.334 | −1.879 | 69.410 |
| 2 | −21.830 | −17.836 | −3.605 | 19.740 |
| 20 | −246.98 | −21.191 | −13.882 | 42.253 |
| 21 | 327.84 | 60.620 | −16.699 | 100.41 |
| 22 | −124.42 | −2.437 | 16.146 | 179.86 |
| 23 | −80.311 | 20.194 | −0.9476 | 82.436 |
| 24 | −331.60 | 0.9428 | 5.373 | 255.23 |
| 25 | 101.48 | −9.684 | 7.122 | 64.948 |
| 26 | 33.167 | −19.512 | 12.510 | 175.20 |
| 27 | −79.248 | −9.996 | 6.263 | 54.532 |
| 28 | 32.152 | 10.117 | −14.381 | 169.50 |
| 29 | 98.722 | −65.907 | 13.118 | 201.58 |
| 3 | −34.858 | −17.382 | −18.971 | 244.06 |
| 30 | −116.09 | 15.346 | −9.689 | 99.970 |
| 31 | 20.557 | −43.073 | 7.121 | 63.574 |
| 32 | 181.21 | −17.030 | 6.474 | 84.219 |
| 33 | −92.733 | 59.353 | −4.708 | 162.30 |
| 34 | 248.27 | −39.530 | 10.938 | 245.45 |
| 35 | 380.35 | 8.663 | −8.680 | 88.855 |
| 36 | 66.401 | 14.062 | −21.559 | 435.26 |
| 37 | −116.83 | −26.024 | −6.080 | 110.31 |
| 38 | 101.73 | −56.682 | 13.432 | 193.70 |
| 39 | 49.318 | −41.958 | 18.195 | 104.41 |
| 4 | −130.70 | −18.369 | −13.926 | 209.65 |
| 40 | 179.10 | −33.718 | 6.219 | 193.07 |
| 41 | 3.422 | 47.037 | 10.078 | 190.20 |
| 42 | 128.22 | −0.6616 | 10.524 | 103.96 |
| 43 | 65.677 | 120.11 | 19.953 | 68.472 |
| 45 | −39.391 | 19.316 | 20.707 | 161.85 |
| 46 | 43.778 | 5.036 | 16.406 | 89.230 |
| 47 | 5.062 | 33.777 | 12.050 | 169.67 |
| 48 | 183.79 | −39.135 | 11.046 | 153.96 |
| 49 | 57.050 | 27.115 | 17.997 | 89.074 |
First 40 of 45 rows.
Curves left out
| Chick | Why |
|---|---|
| 15 | ends before the last time |
| 16 | ends before the last time |
| 18 | ends before the last time |
| 44 | ends before the last time |
| 8 | ends before the last time |
- 5 curve(s) don't cover the whole time range and were left out (FPCA doesn't extrapolate): 15, 16, 18, 44, 8.
- Integrals use the trapezoid rule on the common grid, so uneven time steps count by their length; eigenvalues are the variance of each component's scores (divisor n − 1) and each eigenfunction has ∫φ² dt = 1, signed so ∫φ dt ≥ 0.
- Read a component by its mean ± 2 SD chart: it shows how curves with a high or low score differ from the average curve.
- Phase variation (the same shape shifted in time) shows up as extra components; align the curves first when timing differences aren't of interest.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Functional PCA (main shapes of a set of curves)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.fpca 1.0.0 · spec 43928583d1219167
# Dataset: ml_chickweight (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.errors import check_groups, check_not_constant
from codesplash import ml as csml
from codesplash.ml import fpca
from codesplash.stats import ts
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ml_chickweight.parquet", columns=["Chick", "Time", "weight"])
n_input = len(df)
df["Chick"] = pd.Categorical(df["Chick"], categories=["1", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "2", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "3", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "4", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "5", "50", "6", "7", "8", "9"]) # stored level order
df = df.dropna(subset=["Chick", "Time", "weight"]) # listwise deletion over the analysis columns
df["Chick"] = df["Chick"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["Chick", "Time", "weight"]) # infinite values stop the run (registry/errors.yaml)
# %% Curves
# Functional PCA (Ramsay & Silverman 2005): curves in long form (curve, time, value) on a common grid,
# trapezoid quadrature, optional Whittaker pre-smoothing, eigenfunctions orthonormal under ∫φ_j φ_k dt.
CURVE = "Chick"
TIME = "Time"
VALUE = "weight"
TEMPORAL = False
Q = int(3)
SMOOTHING = "none" # none | gcv | manual
LOG_LAMBDA = float(-2)
cs.check_rows(len(df), 9, "Functional PCA")
check_groups(df[CURVE].astype(str), CURVE, minimum=3)
check_not_constant(df[VALUE].to_numpy(dtype=float), VALUE)
if TEMPORAL:
tnum = ((pd.to_datetime(df[TIME]) - pd.Timestamp("1970-01-01")) / pd.Timedelta(days=1)).to_numpy(dtype=float)
else:
tnum = df[TIME].to_numpy(dtype=float)
check_not_constant(tnum, TIME)
curve_levels = [str(v) for v in df[CURVE].cat.categories]
g = fpca.to_grid(df[CURVE].cat.codes.to_numpy(), len(curve_levels), tnum, df[VALUE].to_numpy(dtype=float))
grid, Y = g["grid"], g["Y"]
kept = [curve_levels[c] for c in g["kept"]]
if len(kept) < 3:
cs.cs_error("CS_E_UNDEFINED", what="Functional PCA", reason=f"only {len(kept)} curve(s) cover the whole time range (at least 3 are needed)")
if len(grid) < 3:
cs.cs_error("CS_E_UNDEFINED", what="Functional PCA", reason=f"the curves share only {len(grid)} time point(s) (at least 3 are needed)")
if len(grid) > 500:
cs.cs_error("CS_E_UNDEFINED", what="Functional PCA", reason=f"the common grid has {len(grid)} time points (at most 500; aggregate the times first)")
if g["n_dup"]:
warnings.append(f"{g['n_dup']} row(s) repeated a curve's time; each such point uses the mean of its values.")
if g["dropped"]:
warnings.append(f"{len(g['dropped'])} curve(s) don't cover the whole time range and were left out (FPCA doesn't extrapolate): "
+ ", ".join(curve_levels[c] for c, _ in g["dropped"][:10]) + (" …" if len(g["dropped"]) > 10 else "") + ".")
share_interp = g["n_interp"] / (len(kept) * len(grid))
if share_interp > 0.5:
cs.cs_error("CS_E_UNDEFINED", what="Functional PCA", reason=f"{share_interp:.0%} of the grid values would be interpolated (curves measured at different times need sparse-data methods)")
if g["n_interp"]:
warnings.append(f"{g['n_interp']} grid value(s) ({share_interp:.1%}) were filled by straight lines between a curve's neighboring measurements.")
w = fpca.trapezoid_weights(grid)
values = {"n_curves": len(kept), "n_dropped_curves": len(g["dropped"]), "n_grid": len(grid), "n_interpolated": g["n_interp"],
"smoothing": SMOOTHING, "log_lambda": float("nan"), "edf": float("nan"), "gcv": float("nan")}
Ys = Y
if SMOOTHING != "none":
sm = fpca.smooth(Y, grid, w, None if SMOOTHING == "gcv" else LOG_LAMBDA)
Ys = sm["Y"]
values.update({"log_lambda": sm["log_lambda"], "edf": sm["edf"], "gcv": sm["gcv"]})
# %% Decompose
fit = fpca.fit(Ys, w, Q)
q = fit["q"]
if q < Q:
warnings.append(f"Only {q} component(s) are available (the curves span {fit['rank']} dimension(s)); {Q} were requested.")
ev = fit["eigenvalues"]
values.update({"components": q, "total_variance": fit["total"], "explained": float(np.sum(ev[:q]) / fit["total"]),
"recon_error": float(np.mean(fit["ise"]))})
cum = 0.0
comp_rows = []
for k in range(len(ev)):
share = float(ev[k] / fit["total"])
cum += share
if k < max(q, min(len(ev), 10)):
comp_rows.append({"component": k + 1, "eigenvalue": float(ev[k]), "share": share, "cumulative": cum})
if k < q:
values[f"eigen[{k + 1}]"] = float(ev[k])
values[f"share[{k + 1}]"] = share
values[f"cumulative[{k + 1}]"] = cum
values[f"phi_check[{k + 1}]"] = float(np.sum(np.arange(1, len(grid) + 1) * w * fit["phi"][:, k]))
values[f"score_check[{k + 1}]"] = float(np.sum(np.arange(1, len(kept) + 1) * fit["scores"][:, k]))
grid_labels = ts.time_labels(pd.to_datetime(grid, unit="D").to_numpy(), True) if TEMPORAL else ["%.10g" % v for v in grid]
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-82309/discover.fpca/chickweight-growth/out-python")
artifacts = []
for name, levels_, F in ((CURVE, kept, fit["scores"]), (TIME, grid_labels, fit["phi"])):
fdf = pd.DataFrame({"level": levels_})
for k in range(q):
fdf[f"factor_{k + 1}"] = F[:, k]
path = os.path.join(out, f"factors_{name}.parquet")
fdf.to_parquet(path, index=False)
artifacts.append({"key": f"factors_{name}", "path": path, "format": "parquet"})
# %% Charts
xkind = "temporal" if TEMPORAL else "numeric"
xvals = grid_labels if TEMPORAL else grid.tolist()
charts = [cs.chart("scree", "scree-plot", "Share of the curves' variance by component", {
"component": cs.col("Component", np.array([r["component"] for r in comp_rows], dtype=float)),
"variance": cs.col("Share of variance", np.array([r["share"] for r in comp_rows])),
"cumulative": cs.col("Cumulative share", np.array([r["cumulative"] for r in comp_rows]))})]
for k in range(min(q, 3)):
amp = 2.0 * np.sqrt(ev[k])
lines = [("Mean", fit["mean"]), ("Mean + 2√λ·φ", fit["mean"] + amp * fit["phi"][:, k]), ("Mean − 2√λ·φ", fit["mean"] - amp * fit["phi"][:, k])]
charts.append(cs.chart(f"mode{k + 1}", "series-line", f"Component {k + 1} ({ev[k] / fit['total']:.0%} of the variance): the mean curve moved by ±2 SD", {
"x": cs.col(TIME, [v for _ in lines for v in xvals], kind=xkind),
"y": cs.col(VALUE, np.concatenate([y for _, y in lines])),
"group": cs.col("curve", [lab for lab, _ in lines for _ in xvals], kind="categorical")}))
if q >= 1:
charts.append(cs.chart("eigenfunctions", "series-line", "Eigenfunctions φ(t)", {
"x": cs.col(TIME, [v for _ in range(q) for v in xvals], kind=xkind),
"y": cs.col("φ", fit["phi"].T.reshape(-1)),
"group": cs.col("component", [f"φ{k + 1}" for k in range(q) for _ in xvals], kind="categorical")}))
if q >= 2:
charts.append(cs.chart("scores", "embedding-map", "Curve scores on the first two components", {
"x": cs.col("Score 1", fit["scores"][:, 0]), "y": cs.col("Score 2", fit["scores"][:, 1]),
"label": cs.col(CURVE, kept, kind="categorical")}))
# %% Tables
tables = [{"key": "components", "title": "Components",
"columns": [{"key": "component", "label": "Component", "type": "integer"}, {"key": "eigenvalue", "label": "Eigenvalue", "type": "number"},
{"key": "share", "label": "Share of variance", "type": "percent"}, {"key": "cumulative", "label": "Cumulative", "type": "percent"}],
"rows": comp_rows},
{"key": "functions", "title": "Mean curve and eigenfunctions",
"columns": [{"key": "time", "label": TIME, "type": "string"}, {"key": "mean", "label": "Mean", "type": "number"}]
+ [{"key": f"phi{k + 1}", "label": f"φ{k + 1}", "type": "number"} for k in range(q)],
"rows": [{"time": grid_labels[j], "mean": float(fit["mean"][j]), **{f"phi{k + 1}": float(fit["phi"][j, k]) for k in range(q)}} for j in range(len(grid))]},
{"key": "scores", "title": "Curve scores",
"columns": [{"key": "curve", "label": CURVE, "type": "string"}] + [{"key": f"s{k + 1}", "label": f"Score {k + 1}", "type": "number"} for k in range(q)]
+ [{"key": "ise", "label": "Integrated squared error", "type": "number"}],
"rows": [{"curve": kept[i], **{f"s{k + 1}": float(fit["scores"][i, k]) for k in range(q)}, "ise": float(fit["ise"][i])} for i in range(len(kept))]}]
if g["dropped"]:
tables.append({"key": "dropped", "title": "Curves left out",
"columns": [{"key": "curve", "label": CURVE, "type": "string"}, {"key": "reason", "label": "Why", "type": "string"}],
"rows": [{"curve": curve_levels[c], "reason": why} for c, why in g["dropped"]]})
# %% Result
summary = (f"Functional PCA of {len(kept)} curves of {VALUE} on {len(grid)} time points: the first {q} component{'s' if q != 1 else ''} "
f"explain {values['explained']:.1%} of the variance between curves"
+ (f" (component 1 alone {ev[0] / fit['total']:.1%})" if q > 1 else "") + ".")
notes = ["Integrals use the trapezoid rule on the common grid, so uneven time steps count by their length; eigenvalues are the variance of each "
"component's scores (divisor n − 1) and each eigenfunction has ∫φ² dt = 1, signed so ∫φ dt ≥ 0.",
"Read a component by its mean ± 2 SD chart: it shows how curves with a high or low score differ from the average curve."]
if SMOOTHING != "none":
notes.append(f"Curves were smoothed first with a second-difference penalty (λ = 10^{values['log_lambda']:.2f} relative to the grid, "
f"{values['edf']:.2f} effective degrees of freedom of {len(grid)}" + ("; chosen by generalized cross-validation" if SMOOTHING == "gcv" else "") + ").")
notes.append("Phase variation (the same shape shifted in time) shows up as extra components; align the curves first when timing differences aren't of interest.")
cs.publish({
"title": "Functional PCA (main shapes of a set of curves)",
"engine": cs.engine_info("numpy", "pandas"),
"n": len(kept),
"summary": summary,
"statistics": [{"key": "explained", "label": f"Variance explained by {q} components", "value": values["explained"]},
{"key": "recon_error", "label": "Mean integrated squared error", "value": values["recon_error"]}],
"tables": tables,
"charts": charts,
"values": values,
"warnings": warnings,
"notes": notes,
"artifacts": artifacts,
})
For 45 chick growth curves, the first mode holds 93.0% of the variation: mostly faster or slower growth overall.
When curves differ in timing
ReadIf curves have the same shape but peak at different times, FPCA spends its first components on the timing (phase) instead of the height (amplitude). Registration, aligning curves before FPCA, separates the two, but it changes the question you're answering.
Plain PCA on curve values stored as columns ignores the spacing between time points and treats every column as unrelated, which FPCA avoids.
Check: three PCA variants
CheckpointCheck yourself
Two sparse components explain less variance than two ordinary components. Why accept that?
Show the answer
Answer: a
No linear components can explain more than the first ordinary ones. Sparsity buys interpretability, not variance.
Check yourself
Two strongly correlated columns each keep a nonzero loading in about half of the bootstrap refits. What does that suggest?
Show the answer
Answer: a
Correlated substitutes split the selection. Report them as a pair rather than naming one.
Check yourself
In principal component pursuit, which penalty makes the pattern low rank and which makes the errors sparse?
Show the answer
Answer: a
The nuclear norm is L1 on singular values, so it zeroes some out (low rank). Entrywise L1 zeroes cells (sparse).
Check yourself
Which situation suits robust PCA least?
Show the answer
Answer: c
Principal component pursuit separates sparse cells. Whole contaminated rows aren't sparse in that sense and can bend the low-rank part.
Check yourself
Growth curves have the same shape but reach their growth spurt at different ages. What will FPCA's first component mostly show?
Show the answer
Answer: a
Shifting a peak left or right changes values at many time points at once, which is a lot of variance. Register the curves first if size is the question.
Check yourself
Why use functional PCA instead of PCA on columns "week 1, week 2, …" when visits were unevenly spaced?
Show the answer
Answer: a
FPCA weights each time point by the interval it represents and gives smooth modes. Column PCA ignores the time axis entirely.
Recap
Recap- Sparse PCA adds an L1 penalty on loadings: nameable components, less variance, check selection stability.
- Robust PCA splits low-rank pattern from sparse cell errors with nuclear plus L1 norms; it can't fix whole bad rows.
- Functional PCA finds smooth modes of curves; timing differences can dominate unless curves are registered.
Concepts in this lesson