Skip to content

CDiscover · discover.sparse_pca

Sparse principal components

Which few variables carry each main direction of variation?

Principal components where each component uses only a few variables, so every component reads as a short list. Shen and Huang's sPCA-rSVD with soft thresholding: each component keeps exactly the number of variables you choose, starting from the ordinary component and deflating after each one. Because sparse components are correlated, the variance is reported as Zou, Hastie and Tibshirani's adjusted variance, next to ordinary PCA for the same number of components; bootstrap refits show how often each variable is kept.

Verified in Python and R Python and R agree to 6 decimals Seeded Also called sparse PCA, SPCA, penalized PCA…

A real result

Example “Usarrests two each”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Sparse principal componentsRecorded · Python and R agreeRecorded 2026-11-21 · 28 values compared
R

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

Sparse loadingsWhat do the values of a square or rectangular result matrix look like at a glance?
View data
ComponentLoadingVariableLoading
SPC10.71Murder0.7071
SPC20Murder0
SPC10.71Assault0.7071
SPC20Assault0
SPC10UrbanPop0
SPC20.71UrbanPop0.7071
SPC10Rape0
SPC20.71Rape0.7071
Biplot (SPC1 × SPC2)How do rows spread on the main components, and which variables drive each direction?

Loading arrows are rescaled to the score range; variables with a zero loading sit at the origin.

View data
KindLabelSPC1SPC2
point1.432−0.3708
point1.1420.8998
point1.0961.444
point0.3275−0.8899
point1.0902.706
point0.30021.927
point−1.244−0.2051
point0.2640−0.0945
point2.6291.512
point1.9020.0742
point−1.4620.7750
point−1.273−1.095
point1.0881.062
point−0.5855−0.0439
point−1.881−1.167
point−0.7634−0.2215
point−0.2136−1.034
point1.9000.0955
point−1.668−1.724
point1.6670.5672
point−0.73470.5783
point1.4151.460
point−1.664−0.4556
point2.098−1.364
point0.25820.7439
point−0.8143−0.9774
point−1.150−0.5302
point1.4062.625
point−1.889−1.352
point−0.16280.9624
point1.5561.038
point1.2441.367
point2.257−1.391
point−2.202−2.104
point−0.50990.4748
point−0.36050.0272
point−0.56860.6804
point−0.7911−0.1625
point−0.68490.0721
point1.992−0.7611
point−1.367−1.640
point1.0250.1084
point1.0541.029
point−1.1760.8323
point−1.949−2.396
point−0.0096−0.1642
point−0.83350.7395
point−1.101−2.197
point−1.841−0.7651
point−0.2432−0.6958
loadingMurder2.1650
loadingAssault2.1650
loadingUrbanPop02.165
loadingRape02.165

Adjusted variance (sparse components are correlated, so each counts only what the earlier ones don't explain)

ComponentAdjusted varianceProportionCumulativeOrdinary PCA, cumulative
11.80245.0%45.0%62.0%
21.07526.9%71.9%86.8%

Sparse loadings (2 of 4 variables per component)

VariableSPC1SPC2
Murder0.70710
Assault0.70710
UrbanPop00.7071
Rape00.7071

Selection stability (20 bootstrap refits): share in which the variable was kept

VariableSPC1SPC2
Murder85.0%15.0%
Assault100.0%0.0%
UrbanPop0.0%100.0%
Rape15.0%85.0%
Python

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)

ComponentAdjusted varianceProportionCumulativeOrdinary PCA, cumulative
11.80245.0%45.0%62.0%
21.07526.9%71.9%86.8%

Sparse loadings (2 of 4 variables per component)

VariableSPC1SPC2
Murder0.70710
Assault0.70710
UrbanPop00.7071
Rape00.7071

Selection stability (20 bootstrap refits): share in which the variable was kept

VariableSPC1SPC2
Murder85.0%15.0%
Assault100.0%0.0%
UrbanPop0.0%100.0%
Rape15.0%85.0%

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Usarrests two eachml_usarrests · features: Murder, Assault, UrbanPop, Rape
  • Usarrests all is pcaml_usarrests · features: Murder, Assault, UrbanPop, Rape
  • Iris covariance threeml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Penguins imputeml_penguins · features: bill_len, bill_dep, flipper_len, body_mass
  • Degenerate all naml_usarrests · features: Murder, Assault, UrbanPop, Rape
  • Degenerate empty after filterml_usarrests · features: Murder, Assault, UrbanPop, Rape
  • Degenerate infml_usarrests · features: Murder, Assault, UrbanPop, Rape
  • Degenerate n1ml_usarrests · features: Murder, Assault, UrbanPop, Rape

In the guides

Where it sits in the decision guides

  • Dimensionality reduction (PCA, ICA, NMF) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Variablesnumeric · 2–500 columns
Numeric columns to summarize; each component keeps only some of them.
Color points bycategorical / boolean · 0–1 column
Optional: shown on the biplot only.

Choices you make

model

Componentsdefault 2

Number of sparse components to find, one after another.

Variables per componentdefault —

How many variables each component keeps. Fewer is easier to name but explains less; empty keeps all, which gives ordinary PCA.

Standardize variablesdefault on

Divide each variable by its SD first (correlation scale). Off = covariance scale in the original units.

Advanced

Bootstrap refitsdefault 50

Refits on resampled rows to show how often each variable is kept; 0 turns it off.

preprocess

Missing valuesdefault listwise

Leave out rows with a missing value, or replace it with the column median.

  • Leave out rows with a missing value(default) — Leaves out rows with any missing value; the clean choice when few are missing.
  • Replace with the column median — Replaces gaps with the column median; keeps every row, and pulls the components a little towards the center.

What it reports

n
How many independent units the analysis used; it sets precision and power.
n_variables
How many independent units the analysis used; it sets precision and power.
n_components
Principal components where each component keeps only a few variables, so every component reads as a short list.
nonzero
Principal components where each component keeps only a few variables, so every component reads as a short list.
adj_cum
Variance a sparse component adds beyond the earlier ones: the score's residual variance after regressing it on them.
pca_cum
Share of variance the first k ordinary principal components explain — the most any k linear components can.

Per group, level or term: adj_var[<k>], adj_prop[<k>], loading[<k>:<variable>], selected_share[<k>:<variable>], score_check[<k>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses numpy; R uses codesplashr.

Default traps between the two languages

  • Both engines run the same sPCA-rSVD twin (power iterations from the leading singular pair, signs fixed so the largest loading is positive, stop when no loading moves by 1e-10). scikit-learn's SparsePCA and R's elasticnet::spca solve other formulations (L1-penalized dictionary learning, the elastic-net SPCA) and give different loadings.
Python

The exact script CodeSplash ran for example “Usarrests two each” · 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"}],
    }
)
R

The exact script CodeSplash ran for example “Usarrests two each” · 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"))
))

Sources

  • Shen H, Huang JZ (2008). Sparse principal component analysis via regularized low rank matrix approximation. J Multivariate Anal 99(6):1015–1034.
  • Zou H, Hastie T, Tibshirani R (2006). Sparse principal component analysis. J Comput Graph Stat 15(2):265–286.
  • Witten DM, Tibshirani R, Hastie T (2009). A penalized matrix decomposition, with applications to sparse principal components and canonical correlation analysis. Biostatistics 10(3):515–534.

From the CodeSplash method registry · discover.sparse_pca v1.0.0.