Skip to content

Linear, manifold, topic, tensor, and graph representations · Linear and multiview representations · REP004 · Model

Sparse PCA

Obtain components involving fewer original variables, improving interpretability when dense PCA loadings obscure a meaningful feature subset.

Runs in CodeSplash Component demo, not a trained model CodeSplash's run and the reference's record

In CodeSplash

A CodeSplash method runs this entry in Python and R. Set it up from the method's page.

Do it in CodeSplash Run it on your own data, in Python or R.

Availability
Runs in CodeSplash
Code example
Component demo, not a trained model
Who ran it
CodeSplash's run and the reference's record
CodeSplash's run
Verified in Python and R through discover.sparse_pca. The reference's example ran in Python and R here, and they agree.
The reference's record
Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

Obtain components involving fewer original variables, improving interpretability when dense PCA loadings obscure a meaningful feature subset.

Question / hypotheses

Can useful variance be represented by components involving fewer variables? This entry specifies an estimation or representation objective; it does not define a universal null hypothesis or p-value.

Architecture / computational structure

A low-rank linear factorization is constrained or penalized to produce sparse loading vectors.

Assumptions

Sparse structure is an inductive preference, not proof that selected variables are scientifically causal.

Formula / computational definition

One common formulation minimizes ∥X−ZWT∥F2+λ∥W∥1\|X-ZW^T\|_F^2+\lambda\|W\|_1 under appropriate scale constraints. Different sparse-PCA formulations impose different orthogonality and regression penalties; the exact estimator must be named.

Parameters and notation

Estimated/learned quantities: Sparse loadings and observation scores.

Hyperparameters and design choices: Number of components, sparsity penalty, ridge stabilization where used, initialization, and convergence thresholds. Numerical tolerances control computation; rank, priors, neighborhood scales, and loss weights alter the model where applicable.

Fitting, fine-tuning, and adaptation

Tune sparsity jointly with rank; project new observations by the solver appropriate to the fitted formulation. Warm starts can trace a penalty path but need stability checks.

How to use and calibrate

Compare reconstruction versus number of nonzero loadings, bootstrap selection stability, and robustness to feature scaling. Report sensitivity across penalty values rather than a single preferred sparsity. Select these choices using the data split appropriate to the intended deployment; retain the final test split for evaluation. Report the actual objective or prediction metric rather than an invented significance level.

Example application

Build components using a small set of interpretable biomarkers. The included synthetic calculation illustrates the computational mechanism; a real analysis must preserve the corresponding sampling unit and missing-data policy.

Interpretation / pitfalls

Watch out

Correlated substitutes cause unstable selection; sparse components may cease to be orthogonal and need not explain variance additively like ordinary PCA.

Python and R code examples

Python: sklearn.decomposition.SparsePCA for its documented formulation. R: implement the same alternating penalized regression objective or use a separately verified sparse-PCA package; compare objectives before claiming equivalence.

Scope: Component demonstration: sparse-loading proximal update, not a complete sparse-PCA estimator.

Dependencies/validation: Python: NumPy/SciPy, executed successfully. R: base R, not executed. Run the corresponding shared setup first. These short examples are not evidence of complete package-level validation.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Component demo, not a trained model — Component demonstration: sparse-loading proximal update, not a complete sparse-PCA estimator.

Shared setup for this chapter
import numpy as np
from scipy.linalg import eigh
from scipy.spatial.distance import pdist, squareform
rng = np.random.default_rng(17)
X = np.array([[1,2,0,1],[2,1,1,0],[3,4,1,2],[4,3,2,1],
              [5,6,2,3],[6,5,3,2],[7,8,3,4],[8,7,4,3]], dtype=float)
X = X - X.mean(axis=0)
V = X[:, :2] + np.array([0.3,-0.2])
N = np.abs(X) + 0.2
D = squareform(pdist(X))
K = np.exp(-D**2 / 20)
H = np.eye(len(X)) - np.ones((len(X),len(X)))/len(X)
G = np.array([[0,1,1,0],[1,0,1,0],[1,1,0,1],[0,0,1,0]], dtype=float)
P = G / G.sum(axis=1, keepdims=True)
E = np.array([[0.,0.],[1.,0.],[0.,1.],[1.,1.]])
C = np.array([[8.,1.,0.,2.],[1.,7.,2.,0.],[2.,0.,8.,1.]])
theta = np.array([[0.8,0.2],[0.3,0.7],[0.5,0.5]])
phi = np.array([[0.6,0.2,0.1,0.1],[0.1,0.2,0.3,0.4]])
def softmax(a):
    a = np.asarray(a); e = np.exp(a-a.max(axis=-1,keepdims=True))
    return e / e.sum(axis=-1,keepdims=True)

w=np.linalg.svd(X,full_matrices=False)[2][0]
threshold=0.2
sparse=np.sign(w)*np.maximum(np.abs(w)-threshold,0)
if np.linalg.norm(sparse)>0: sparse/=np.linalg.norm(sparse)
print(sparse, np.count_nonzero(sparse))
R

Component demo, not a trained model — Component demonstration: sparse-loading proximal update, not a complete sparse-PCA estimator.

Shared setup for this chapter
set.seed(17)
X <- matrix(c(1,2,0,1, 2,1,1,0, 3,4,1,2, 4,3,2,1,
              5,6,2,3, 6,5,3,2, 7,8,3,4, 8,7,4,3), ncol=4, byrow=TRUE)
X <- scale(X, center=TRUE, scale=FALSE)
V <- sweep(X[,1:2], 2, c(0.3,-0.2), "+")
N <- abs(X)+0.2
D <- as.matrix(dist(X)); K <- exp(-D^2/20)
H <- diag(nrow(X))-matrix(1/nrow(X),nrow(X),nrow(X))
G <- matrix(c(0,1,1,0, 1,0,1,0, 1,1,0,1, 0,0,1,0),4,byrow=TRUE)
P <- G/rowSums(G)
E <- matrix(c(0,0,1,0,0,1,1,1),ncol=2,byrow=TRUE)
C <- matrix(c(8,1,0,2,1,7,2,0,2,0,8,1),ncol=4,byrow=TRUE)
theta <- matrix(c(.8,.2,.3,.7,.5,.5),ncol=2,byrow=TRUE)
phi <- matrix(c(.6,.2,.1,.1,.1,.2,.3,.4),ncol=4,byrow=TRUE)
softmax <- function(a) { z <- exp(a-max(a)); z/sum(z) }
pinv <- function(a) { s <- svd(a); keep <- s$d > max(s$d)*1e-10
    s$v[,keep,drop=FALSE] %*% diag(1/s$d[keep],sum(keep)) %*% t(s$u[,keep,drop=FALSE]) }

w <- svd(X)$v[,1]; threshold <- .2
sparse <- sign(w)*pmax(abs(w)-threshold,0)
if(sum(sparse^2)>0) sparse <- sparse/sqrt(sum(sparse^2))
print(sparse); print(sum(sparse!=0))

Sources

From the CodeSplash reference, entry REP004.