Components you can name: sparse PCA, CUR and robust PCA
Trade a little variance for components built from a few variables or from real columns and rows, and split a table into its pattern and the odd cells that break it.
What runs in CodeSplash
- Sparse principal components Verified in Python and R
- CUR decomposition (representative columns and rows) Verified in Python and R
- Robust PCA (cell outliers) Verified in Python and R
You will be able to
- Choose how many variables a sparse component keeps and read its adjusted variance
- Pick representative columns and rows with leverage scores (CUR)
- Tell cell outliers from row outliers with robust PCA
When a component is a soup
ReadOrdinary PCAPrincipal component analysisRotates correlated variables into uncorrelated components ordered by how much variance they capture. mixes every variable into every component. With four variables that's fine. With forty, the first component is a weighted soup you can't name, and nobody acts on a soup.
This lesson covers three ways to get components made of things you can point at:
- Sparse PCA keeps only a few variables in each component.
- CUR builds the summary from real columns and real rows.
- Robust PCA splits the table into its main pattern plus the few cells that break it.
Sparse PCA: fewer variables per component
ReadSparse PCASparse PCAPrincipal components where each component keeps only a few variables, so every component reads as a short list. asks for components that use only m variables each. CodeSplash uses Shen and Huang's method: start from the ordinary component, keep the m largest contributions, shrink them by the same amount, and repeat until nothing moves.
On US arrests with two variables per component, the first sparse component keeps Murder and Assault, and the second keeps UrbanPop and Rape. Two short lists you can name: violent crime, and urban crime.
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%
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"}],
}
)
What sparsity costs
ReadSparse components are correlated, so their variances can't be added up. The card reports the adjusted varianceAdjusted varianceVariance a sparse component adds beyond the earlier ones: the score's residual variance after regressing it on them., which counts only what each component adds beyond the ones before. Together the two explain 72%, against 87% for two ordinary components. That gap is the price of components you can name.
Keep every variable and sparse PCA is ordinary PCA: the adjusted share is then 96% for three components, the same as PCA.
The selection stability table refits on bootstrap resamples and shows how often each variable is kept. A variable kept in most refits is a dependable part of its component. One kept about half the time is interchangeable with a correlated neighbor.
View data
| variable | with | r |
|---|---|---|
| age | age | 1 |
| age | BMI | 0.1207 |
| age | systolic BP | 0.1471 |
| age | cholesterol | 0.1467 |
| age | glucose | 0.1912 |
| age | activity | −0.1247 |
| BMI | age | 0.1207 |
| BMI | BMI | 1 |
| BMI | systolic BP | 0.3132 |
| BMI | cholesterol | 0.3194 |
| BMI | glucose | 0.3629 |
| BMI | activity | −0.1770 |
| systolic BP | age | 0.1471 |
| systolic BP | BMI | 0.3132 |
| systolic BP | systolic BP | 1 |
| systolic BP | cholesterol | 0.4537 |
| systolic BP | glucose | 0.5647 |
| systolic BP | activity | −0.3672 |
| cholesterol | age | 0.1467 |
| cholesterol | BMI | 0.3194 |
| cholesterol | systolic BP | 0.4537 |
| cholesterol | cholesterol | 1 |
| cholesterol | glucose | 0.6006 |
| cholesterol | activity | −0.3861 |
| glucose | age | 0.1912 |
| glucose | BMI | 0.3629 |
| glucose | systolic BP | 0.5647 |
| glucose | cholesterol | 0.6006 |
| glucose | glucose | 1 |
| glucose | activity | −0.4105 |
| activity | age | −0.1247 |
| activity | BMI | −0.1770 |
| activity | systolic BP | −0.3672 |
| activity | cholesterol | −0.3861 |
| activity | glucose | −0.4105 |
| activity | activity | 1 |
CUR: real columns, real rows
ReadCURCUR decompositionApproximates a table from a few of its own columns and rows (C and R) joined by a small matrix U. doesn't invent components at all. It picks a few actual columns (C) and actual rows (R), then finds the small matrix U that best joins them. Columns are chosen by their leverageLeverage score (CUR)How much a column (or row) weighs in the top-k singular vectors; the scores sum to 1., meaning how much they weigh in the top singular vectors.
CUR with 4 real columns and 8 real rows rebuilds the table with a relative error of 0.0%, against 36.4% for the best rank-2 approximation.
- CUR relative error
- 0.0%
- Rank-2 SVD error
- 36.4%
Plots
Leverage from the top 2 right singular vectors; the scores sum to 1.
View data
| Variable | Leverage |
|---|---|
| Murder | 0.2310 |
| Assault | 0.1877 |
| UrbanPop | 0.4196 |
| Rape | 0.1617 |
Column leverage (rank 2); the 4 chosen columns represent the table
| Variable | Leverage | Chosen |
|---|---|---|
| UrbanPop | 0.4196 | Yes |
| Murder | 0.2310 | Yes |
| Assault | 0.1877 | Yes |
| Rape | 0.1617 | Yes |
Representative rows (chosen by row leverage)
| Row | Leverage | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|
| 5 | 0.0497 | 9 | 276 | 91 | 40.600 |
| 24 | 0.0619 | 16.100 | 259 | 44 | 17.100 |
| 28 | 0.0394 | 12.200 | 252 | 81 | 46 |
| 33 | 0.0552 | 13 | 337 | 45 | 16.100 |
| 34 | 0.0397 | 0.8000 | 45 | 44 | 7.300 |
| 40 | 0.0448 | 14.400 | 279 | 48 | 22.500 |
| 45 | 0.0515 | 2.200 | 48 | 32 | 11.200 |
| 48 | 0.0384 | 5.700 | 81 | 39 | 9.300 |
The exact R script · R R version 4.5.1 (2025-06-13)
# CUR decomposition (representative columns and rows)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.cur 1.0.0 · spec 16e79dc113e0ba61
# 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)
# %% Data
FEATURES <- c("Murder", "Assault", "UrbanPop", "Rape")
SEED <- 42
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.parquet", col_select = unique(FEATURES)))
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, "CUR decomposition")
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])
# %% CUR: real columns C and rows R chosen by leverage, U = C⁺ Z R⁺
Z <- cs_rep_center_scale(X, TRUE)
n <- nrow(Z); p <- ncol(Z)
k <- min(as.integer(2), n - 1L, p)
nc <- if (is.null(NULL)) min(p, 2L * k) else min(as.integer(NULL), p)
nr <- if (is.null(NULL)) min(n, 4L * k) else min(as.integer(NULL), n)
METHOD <- "top"
res <- cs_rep_cur(Z, k, nc, nr, METHOD, SEED)
ratio <- if (res$err_svd > 0) res$err_cur / res$err_svd else NaN
sv <- svd(res$approx)
d <- sum(sv$d[seq_len(k)] > 1e-10 * max(sv$d[1], 1e-300))
if (d > 0) {
signs <- cs_ml_canonical_signs(sv$v[, seq_len(d), drop = FALSE])
scores <- sweep(sv$u[, seq_len(d), drop = FALSE], 2, sv$d[seq_len(d)] * signs, "*")
} else {
scores <- matrix(0, n, 0)
}
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.cur/usarrests_top/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(d)) emb[[paste0("dim_", j)]] <- scores[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
# %% Result
values <- list(n = n, n_variables = p, rank = k, n_columns = length(res$cols), n_rows = length(res$rows),
rel_error_cur = res$err_cur, rel_error_svd = res$err_svd, error_ratio = ratio, n_components = d)
for (i in seq_along(FEATURES)) {
values[[sprintf("leverage[%s]", FEATURES[i])]] <- res$col_lev[i]
values[[sprintf("chosen[%s]", FEATURES[i])]] <- if (i %in% res$cols) 1L else 0L
}
for (j in seq_along(res$rows)) values[[sprintf("chosen_row[%d]", j)]] <- rows[res$rows[j]] + 1L
for (j in seq_len(d)) values[[sprintf("score_check[%d]", j)]] <- cs_ml_checksum(scores[, j], rows)
by_lev <- order(-res$col_lev, method = "radix")
tables <- list(
list(key = "columns", title = sprintf("Column leverage (rank %d); the %d chosen columns represent the table", k, length(res$cols)),
columns = list(list(key = "variable", label = "Variable"),
list(key = "leverage", label = "Leverage", type = "number"),
list(key = "chosen", label = "Chosen")),
rows = lapply(by_lev, function(i) list(variable = FEATURES[i], leverage = res$col_lev[i], chosen = if (i %in% res$cols) "Yes" else "No"))),
list(key = "rows", title = "Representative rows (chosen by row leverage)",
columns = c(list(list(key = "row", label = "Row", type = "integer"),
list(key = "leverage", label = "Leverage", type = "number")),
lapply(FEATURES, function(f) list(key = f, label = f, type = "number"))),
rows = lapply(res$rows, function(i) {
r <- list(row = rows[i] + 1L, leverage = res$row_lev[i])
for (j in seq_along(FEATURES)) r[[FEATURES[j]]] <- X[i, j]
r
}))
)
charts <- list(cs_chart("leverage", "importance-bar", "Column leverage scores", list(
feature = cs_col("Variable", FEATURES, "categorical"),
importance = cs_col("Leverage", res$col_lev, "numeric")
), note = sprintf("Leverage from the top %d right singular vectors; the scores sum to 1.", k)))
cs_publish(list(
title = "CUR decomposition (representative columns and rows)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = n,
summary = sprintf("CUR with %d real columns and %d real rows rebuilds the table with a relative error of %.1f%%, against %.1f%% for the best rank-%d approximation.",
length(res$cols), length(res$rows), 100 * res$err_cur, 100 * res$err_svd, k),
statistics = list(list(key = "rel_error_cur", label = "CUR relative error", value = res$err_cur, format = "percent"),
list(key = "rel_error_svd", label = sprintf("Rank-%d SVD error", k), value = res$err_svd, format = "percent")),
tables = tables,
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))
CUR with 4 real columns and 8 real rows rebuilds the table with a relative error of 0.0%, against 36.4% for the best rank-2 approximation.
- CUR relative error
- 0.0%
- Rank-2 SVD error
- 36.4%
To keep this page light, the plots are shown once, under the R tab.
Column leverage (rank 2); the 4 chosen columns represent the table
| Variable | Leverage | Chosen |
|---|---|---|
| UrbanPop | 0.4196 | Yes |
| Murder | 0.2310 | Yes |
| Assault | 0.1877 | Yes |
| Rape | 0.1617 | Yes |
Representative rows (chosen by row leverage)
| Row | Leverage | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|
| 5 | 0.0497 | 9 | 276 | 91 | 40.600 |
| 24 | 0.0619 | 16.100 | 259 | 44 | 17.100 |
| 28 | 0.0394 | 12.200 | 252 | 81 | 46 |
| 33 | 0.0552 | 13 | 337 | 45 | 16.100 |
| 34 | 0.0397 | 0.8000 | 45 | 44 | 7.300 |
| 40 | 0.0448 | 14.400 | 279 | 48 | 22.500 |
| 45 | 0.0515 | 2.200 | 48 | 32 | 11.200 |
| 48 | 0.0384 | 5.700 | 81 | 39 | 9.300 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# CUR decomposition (representative columns and rows)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.cur 1.0.0 · spec 16e79dc113e0ba61
# 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
# %% Data
FEATURES = ["Murder", "Assault", "UrbanPop", "Rape"]
SEED = 42
df = pd.read_parquet("tests/parity/fixtures/ml_usarrests.parquet", columns=list(dict.fromkeys(FEATURES)))
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, "CUR decomposition")
X = csembed.numeric_matrix(df, FEATURES, rows)
if np.all(X.std(axis=0) == 0):
cs.cs_error("CS_E_CONSTANT", column=FEATURES[0])
# %% CUR: real columns C and rows R chosen by leverage, U = C⁺ Z R⁺
Z = rl.center_scale(X, True)
n, p = Z.shape
k = min(int(2), n - 1, p)
c = min(p, 2 * k) if None is None else min(int(None), p)
r = min(n, 4 * k) if None is None else min(int(None), n)
METHOD = "top"
res = rl.cur(Z, k, c, r, METHOD, SEED)
ratio = res["err_cur"] / res["err_svd"] if res["err_svd"] > 0 else float("nan")
U, sv, Vt = np.linalg.svd(res["approx"], full_matrices=False)
d = int(np.sum(sv[:k] > 1e-10 * max(sv[0], 1e-300)))
signs = csembed.canonical_signs(Vt[:d].T) if d else np.ones(0)
scores = U[:, :d] * sv[:d] * signs
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.cur/usarrests_top/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(d):
emb[f"dim_{j + 1}"] = scores[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
# %% Result
chosen = set(int(j) for j in res["cols"])
values = {
"n": n,
"n_variables": p,
"rank": k,
"n_columns": len(res["cols"]),
"n_rows": len(res["rows"]),
"rel_error_cur": res["err_cur"],
"rel_error_svd": res["err_svd"],
"error_ratio": ratio,
"n_components": d,
}
for i, f in enumerate(FEATURES):
values[f"leverage[{f}]"] = float(res["col_lev"][i])
values[f"chosen[{f}]"] = 1 if i in chosen else 0
for j, i in enumerate(res["rows"]):
values[f"chosen_row[{j + 1}]"] = int(rows[i]) + 1
for j in range(d):
values[f"score_check[{j + 1}]"] = csembed.checksum(scores[:, j], rows)
by_lev = np.argsort(-res["col_lev"], kind="stable")
tables = [
{
"key": "columns",
"title": f"Column leverage (rank {k}); the {len(res['cols'])} chosen columns represent the table",
"columns": [
{"key": "variable", "label": "Variable"},
{"key": "leverage", "label": "Leverage", "type": "number"},
{"key": "chosen", "label": "Chosen"},
],
"rows": [{"variable": FEATURES[i], "leverage": float(res["col_lev"][i]), "chosen": "Yes" if int(i) in chosen else "No"} for i in by_lev],
},
{
"key": "rows",
"title": "Representative rows (chosen by row leverage)",
"columns": [
{"key": "row", "label": "Row", "type": "integer"},
{"key": "leverage", "label": "Leverage", "type": "number"},
]
+ [{"key": f, "label": f, "type": "number"} for f in FEATURES],
"rows": [dict({"row": int(rows[i]) + 1, "leverage": float(res["row_lev"][i])}, **{f: float(X[i, j]) for j, f in enumerate(FEATURES)}) for i in res["rows"]],
},
]
charts = [
cs.chart(
"leverage",
"importance-bar",
"Column leverage scores",
{
"feature": cs.col("Variable", FEATURES, "categorical"),
"importance": cs.col("Leverage", res["col_lev"], "numeric"),
},
note=f"Leverage from the top {k} right singular vectors; the scores sum to 1.",
)
]
cs.publish(
{
"title": "CUR decomposition (representative columns and rows)",
"engine": cs.engine_info("numpy", "pandas"),
"n": n,
"summary": f"CUR with {len(res['cols'])} real columns and {len(res['rows'])} real rows rebuilds the table with a relative error of {res['err_cur']:.1%}, against {res['err_svd']:.1%} for the best rank-{k} approximation.",
"statistics": [
{"key": "rel_error_cur", "label": "CUR relative error", "value": res["err_cur"], "format": "percent"},
{"key": "rel_error_svd", "label": f"Rank-{k} SVD error", "value": res["err_svd"], "format": "percent"},
],
"tables": tables,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
}
)
With rank 2, CUR keeps 4 columns and 8 representative states. It rebuilds the standardized table with a relative error of 0%, against 36% for the best possible rank-2 approximation. No method made of real columns can beat the SVD, so the question is only how close it gets.
View data
| feature | drop in ROC AUC | lower | upper |
|---|---|---|---|
| tenure (months) | 0.2136 | 0.1758 | 0.2514 |
| monthly charges | 0.1456 | 0.1186 | 0.1726 |
| contract=month-to-month | 0.1218 | 0.1002 | 0.1434 |
| support calls | 0.1049 | 0.0869 | 0.1229 |
| total charges | 0.0783 | 0.0639 | 0.0927 |
| payment=electronic check | 0.0650 | 0.0542 | 0.0758 |
| age | 0.0440 | 0.0368 | 0.0512 |
| internet=fiber | 0.0316 | 0.0253 | 0.0379 |
| streaming TV | 0.0070 | 0.0048 | 0.0092 |
| paperless billing | 0.0088 | 0.0068 | 0.0108 |
| dependents | 0.0077 | 0.0057 | 0.0097 |
| region=north | 0.0040 | 0.0020 | 0.0060 |
Robust PCA: the pattern and the odd cells
ReadSometimes the task is to find a mistyped value in an otherwise regular table. Robust PCARobust PCA (principal component pursuit)Splits a table into a low-rank pattern plus a sparse part holding the few cells that break it. splits the table into a low-rank part (the shared pattern) and a sparse part (the few cells that don't fit). A larger penalty λ flags fewer cells.
This fixture has two hidden factors and 16 planted cells:
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
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"},
],
}
)
The run flags 15 cells in 13 rows. Each flagged cellFlagged cellA cell whose sparse part is larger than the flag threshold, in scaled units: the pattern can't explain its value. is listed with its value and the value the pattern expected.
Check your understanding
CheckpointCheck yourself
Two sparse components have variances 1.9 and 1.2. Why can't you add them up to say how much they explain together?
Show the answer
Answer: b
Ordinary components are uncorrelated, so their variances add. Sparse ones overlap, so the adjusted variance counts only what each adds beyond the earlier ones.
Check yourself
In the selection stability table, a variable is kept in 52% of bootstrap refits of component 1. What does that suggest?
Show the answer
Answer: b
A share near one half means the component can use this variable or a close substitute. Shares near 100% mark the dependable members.
Check yourself
Why might you prefer CUR to PCA for a summary you hand to a business team?
Show the answer
Answer: a
CUR can't beat the rank-k SVD on error. Its value is that the pieces are real variables and records rather than abstract combinations.
Check yourself
What does a column's leverage score measure in CUR?
Show the answer
Answer: b
Leverage comes from the singular vectors that carry the main directions. The scores sum to 1, and CUR keeps or samples the high ones.
Check yourself
Robust PCA flags one cell in a row of 12 variables. What's the most sensible reading?
Show the answer
Answer: b
The sparse part works cell by cell. A single flagged cell points at a single value. A row is unusual only when many of its cells are flagged.
Check yourself
You raise robust PCA's sparsity penalty λ. What happens to the flagged cells?
Show the answer
Answer: a
λ sets the price of putting a cell in the sparse part. A higher price means only the most extreme cells are moved there.
Do it on your own data
In the appAll three methods are in Discover under Map the data: Sparse principal components, CUR decomposition and Robust PCA (cell outliers). Save to dataset writes each row's map coordinates to a new dataset version.
Recap
Recap- Sparse PCA keeps m variables per component; read its adjusted variance and selection stability.
- CUR summarizes with real columns and rows chosen by leverage; compare its error with the SVD's.
- Robust PCA flags odd cells, not odd rows.
Concepts in this lesson