rspca: Randomized sparse principal component analysis

View source: R/rspca.R

rspcaR Documentation

Randomized sparse principal component analysis

Description

Approximate a sparse principal component fit by compressing the rows into a randomized subspace before optimizing the loading coefficients. The final component scores use the complete processed data.

Usage

rspca(
  X,
  k = NULL,
  alpha = 1e-04,
  beta = 1e-04,
  center = TRUE,
  scale = FALSE,
  max_iter = 1000,
  tol = 1e-05,
  o = 20,
  q = 2,
  verbose = TRUE,
  penalty = c("elasticnet", "l0"),
  B_init = NULL
)

Arguments

X

A real numeric matrix, numeric data frame, or real Matrix object. Observations are rows and variables are columns. Sparse Matrix inputs retain sparse storage for matrix products and implicit centering/scaling. Missing rows are omitted with a warning; at least two complete rows are required. Infinite and complex values are unsupported.

k

Positive integer number of components. NULL uses min(nrow(X), ncol(X)) after incomplete rows are omitted. Larger values are reduced to that limit. A component can have zero scores when the data are rank deficient or its loadings are all zero.

alpha

Finite nonnegative sparsity penalty (default 1e-4), relative to the squared largest singular value of the sketch. Its effective value is alpha * d1^2, with d1 computed from the sketch, not the full input.

beta

Finite nonnegative ridge penalty (default 1e-4), using the same sketch-based relative scaling as alpha.

center

Logical; subtract column means before fitting (default TRUE). The fitted means are stored for prediction.

scale

Logical; divide each processed column by its scale factor (default FALSE). Factors are square roots of column sums of squares divided by n-1, after any centering. This is the sample standard deviation for centered data and a root-mean-square quantity otherwise. Factors below 1e-8 are replaced by one.

max_iter

Positive integer limit on optimization iterations. Reaching the limit does not establish convergence.

tol

Finite nonnegative tolerance for relative objective change. This controls an optimization stopping rule, not a reconstruction-error bound or a statistical accuracy guarantee. An objective increase larger than a roundoff allowance stops with a warning and does not count as convergence; see Details.

o

Nonnegative integer oversampling parameter (default 20). The sketch width is min(k + o, nrow(X), ncol(X)) after incomplete rows are omitted. Additional columns can improve the approximation while increasing memory and computation.

q

Nonnegative integer number of power iterations (default 2). Each iteration requires additional products with the processed input and its transpose, with intermediate orthogonalization. Increasing q can help for a slowly decaying singular spectrum.

verbose

Logical, or the equivalent numeric zero/one; print optimization progress when enabled.

penalty

Sparsity penalty: "elasticnet" (the default) uses an entrywise absolute-value penalty and soft thresholding; "l0" counts nonzero coefficients and uses hard thresholding. With penalty = "l0" and beta > 0, the combination of cardinality and ridge penalties is also called ZeroNet.

B_init

Optional real finite p by k initial loading matrix. NULL uses the leading right singular vectors of the sketch. A warm start must use the same variable order, component count, and preprocessing. It does not reuse a sketch from an earlier function call; use spca_path for that.

Details

The algorithm forms an orthonormal basis Q of width at most k+o, using random combinations of the processed input columns. Power iterations refine this basis. It then replaces X with C=Q^T X in the sparse fitting objective described by spca. The coefficients still correspond to the original variables. Returned scores are XB, and reconstruction is XBA^T in processed coordinates.

Both relative penalties are scaled by the squared leading singular value of the sketch C. The objective history refers to the sketched optimization problem, not the full-data reconstruction loss. Variance statistics are calculated from the full-data scores using the conventions documented for spca. Use full-data residuals or another common reference when comparing randomized and deterministic fit quality. The converged flag concerns optimization on the sketch; it does not certify the accuracy of that sketch. Oversampling and power iterations control subspace approximation, whereas tol and max_iter control optimizer stopping.

Randomized compression is most useful when k+o is much smaller than the matrix dimensions and the data have a useful low-rank approximation. Small matrices, a large requested rank, or a flat singular spectrum reduce the advantage. A full-rank noisy matrix can still admit an accurate low-rank approximation; the relevant quantity is the energy outside the retained subspace. Omitting k requests the full available component count and offers no compression advantage.

Call set.seed before fitting to reproduce random draws. The function uses R's current random-number stream and does not reset it. Numerical libraries can still choose different signs or bases for tied subspaces. A warm start reuses loading coefficients but a separate call creates its own sketch; spca_path reuses one sketch across the whole path.

Value

A list of class "rspca" with the same components and dimensions as a spca result. objective, effective alpha, and effective beta refer to the sketch; scores, var, score_variance, eigenvalues, and sdev use the full processed data. The print and summary methods follow the corresponding spca methods.

Understanding the compression

Random combinations of the columns reveal a space of observation patterns that the data can express. The columns of Q describe that space. Projecting onto them replaces many observation rows by \ell linear combinations, while retaining all p original variable columns. The sparse coefficients therefore still refer to the original measured variables; the method does not select a random subset of variables or observations and fit only that subset.

If most data energy lies in a few directions, the smaller problem can contain almost all the information relevant to the requested fit. Truncation error from choosing k, sparsity-induced error from choosing alpha, and approximation error from the random sketch are distinct. More optimizer iterations address none of the energy omitted by the sketch.

Choosing and checking a sketch

Choose k for the statistical representation first. Oversampling o gives the sketch extra directions in which to find it; those directions are not extra returned components. The defaults o = 20 and q = 2 are a useful starting point. Setting q = 0 avoids the additional power-iteration products; increasing q emphasizes stronger singular directions and can improve accuracy when their separation is weak. Increasing either o or q costs extra work; increasing o also increases the dense sketch and basis storage.

On a manageable problem, compare full-data reconstruction error with spca at the same rank, preprocessing, and relative penalties, remembering that their effective penalties can differ slightly because the sketch estimates d1. For a pure PCA approximation check, set both penalties to zero and compare with prcomp. For a large problem, repeat a fit with a larger sketch or more power iterations and compare the represented model and selected-variable patterns. Repeating selected seeds can reveal sketch sensitivity; signs or rotations within tied subspaces alone are not evidence of a bad fit.

A dense full-data residual is convenient for a small diagnostic, as in the example below. For large sparse input, evaluate residuals in row blocks using the fitted means and scales rather than densifying the entire matrix just to assess a sparse-memory fit. A small residual and stable support are useful evidence, not a guarantee of statistical generalization or a global sparse-PCA optimum.

Sparse input and memory

For sparse input, products with the centered/scaled matrix are evaluated without creating the entire centered dense matrix. For example, (X-\mathbf{1}\mu^T)W=XW-\mathbf{1}(\mu^T W). This preserves sparse storage of X; the mean correction uses smaller dense factors. The basis Q, projected matrix C, loading factors, and score matrix are generally dense, with dimensions n by \ell, \ell by p, p by k, and n by k, respectively, where \ell=\min(k+o,n,p). A full reconstruction is dense.

Sparse input and sparse loading coefficients are separate concepts: rspca supports both, but zero coefficients in the returned loadings are stored in an ordinary matrix. See spca and robspca for methods that use dense input workspace. Common sparse storage formats are converted to a general compressed column representation before fitting. That conversion and intermediate products can make copies; sparse support is not a promise of zero-copy execution. Memory savings diminish when \ell approaches the input dimensions or when the dense score matrix itself is large.

References

Erichson, N. B., Zheng, P., Manohar, K., Brunton, S. L., Kutz, J. N., and Aravkin, A. Y. (2020). Sparse Principal Component Analysis via Variable Projection. SIAM Journal on Applied Mathematics, 80(2), 977–1002. \Sexpr[results=rd]{tools:::Rd_expr_doi("10.1137/18M1211350")}.

Erichson, N. B., Voronin, S., Brunton, S. L., and Kutz, J. N. (2019). Randomized Matrix Decompositions Using R. Journal of Statistical Software, 89(11), 1–48. \Sexpr[results=rd]{tools:::Rd_expr_doi("10.18637/jss.v089.i11")}.

See Also

spca, robspca, spca_path, predict.spca.

Examples

# A small example illustrating sparse storage and sparse coefficients.
X <- Matrix::bdiag(outer(1:20, 1:6), outer(1:20, 6:1),
                   outer(1:20, 1:6))
set.seed(42)
fit <- rspca(X, k = 3, alpha = 0.005, scale = TRUE,
             o = 5, q = 2, verbose = FALSE)
colSums(fit$loadings != 0)
summary(fit)
predict(fit, X[1:3, , drop = FALSE])

# This example is small enough for an explicit dense quality check.
# Keep the same training preprocessing for both the data and residual.
processed <- scale(as.matrix(X), center = fit$center, scale = fit$scale)
reconstructed <- tcrossprod(fit$scores, fit$transform)
norm(processed - reconstructed, "F") / norm(processed, "F")
c(iterations = fit$iterations, converged = fit$converged)

sparsepca documentation built on Nov. 6, 2026, 5:06 p.m.