robspca: Robust sparse principal component analysis

View source: R/robspca.R

robspcaR Documentation

Robust sparse principal component analysis

Description

Fit sparse component loadings and a sparse additive error matrix to reduce the influence of large individual reconstruction residuals. The method combines variable projection with an entrywise Huber loss.

Usage

robspca(
  X,
  k = NULL,
  alpha = 1e-04,
  beta = 1e-04,
  gamma = 100,
  center = TRUE,
  scale = FALSE,
  max_iter = 1000,
  tol = 1e-05,
  verbose = TRUE,
  penalty = c("elasticnet", "l0"),
  B_init = NULL
)

Arguments

X

A real numeric matrix, numeric data frame, or real Matrix object, with observations in rows and variables in columns. Input is converted to a dense matrix. 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 processed data. The effective penalty is alpha * d1^2; see Details. Increasing alpha encourages fewer nonzero coefficients but does not impose an exact feature count.

beta

Finite nonnegative ridge penalty, using the same relative scaling as alpha. The default is 1e-4. Ridge shrinkage can improve conditioning for strongly correlated variables.

gamma

Finite nonnegative penalty on the absolute entries of the sparse error matrix (default 100). This is a threshold in the centered/scaled input units and is not scaled by a singular value. Smaller values allow more residual entries into the sparse component. A sufficiently large value leaves that component zero and recovers the ordinary squared reconstruction loss.

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.

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 matrix of initial loading coefficients. NULL initializes from leading right singular vectors. A previous fit's loadings can supply a warm start when variable order, component count, and preprocessing match. Initial loadings are not normalized.

Details

For processed data X, robust SPCA seeks to minimize

\frac{1}{2}\|X-XBA^T-S\|_F^2 + \lambda_1 P(B) + \frac{\lambda_2}{2}\|B\|_F^2 + \gamma\|S\|_1

subject to A^T A=I. The default penalty P(B) is the sum of absolute entries. With penalty = "l0", it counts nonzero entries. As in spca, \lambda_1 and \lambda_2 are the user-supplied alpha and beta multiplied by the squared leading singular value of the processed input.

For fixed B and S, an SVD of (X-S)^T X B gives the orthogonal factor A. The algorithm takes a proximal gradient step for B, then soft-thresholds X-XBA^T at gamma to update S. The objective must include S in the squared reconstruction residual as well as charging its penalty. Eliminating S gives the entrywise Huber loss: quadratic near zero and linear beyond the threshold.

The predictor matrix in the score map remains the processed X, not X-S. Consequently scores = X %*% loadings and the low-rank reconstruction is tcrossprod(scores, transform). Adding sparse gives the full fitted model in processed coordinates. To obtain original units, undo scaling for both components and add the training means only once. Prediction applies the learned linear map and does not estimate a new sparse-error matrix.

Robustness here concerns an additive sparse-error model for individual entries. It is not a guarantee against every form of contamination. Centering and scaling use ordinary means and sums of squares rather than robust location/scale estimates. gamma = 0 allows the sparse component to absorb the entire remaining residual and can give a degenerate low-rank fit. Choose the threshold with the processed measurement units and the application in mind.

robspca retains dense input, residual, and sparse-error matrices; accepting a sparse Matrix does not imply sparse-memory computation. The optimization is nonconvex, and max_iter remains a work limit. Variance diagnostics summarize the returned full-data scores; they do not measure the amount of corruption removed or certify correct identification of outliers.

Value

A list of class "robspca" with the components documented for spca, plus sparse: a dense n by p matrix S of estimated sparse errors in processed input units. Its rows correspond to retained complete observations. The additional scalar gamma records the unscaled error threshold supplied by the user. objective includes the complete squared residual and all three penalties. The print and summary methods follow the corresponding spca methods.

Interpreting the sparse error matrix

The two sparse objects have different roles. Zeros in loadings simplify the recipes for the component scores. Zeros in sparse say that a particular observation-variable residual remains entirely in the quadratic loss. For a low-rank residual r, the fitted error is zero when |r|\leq\gamma; otherwise it is \mathrm{sign}(r)(|r|-\gamma). The remaining residual is thus limited in magnitude to gamma at the completed error update.

A nonzero error is a model-based assignment, not a formal outlier test. It may reflect a recording error, an unusual observation, a component missing because k is too small, or an inappropriate scale or penalty. Inspect its pattern across observations and variables together with the low-rank reconstruction. A good low-rank fit and plausible error structure are both needed for a useful interpretation.

Choosing gamma and measurement units

alpha encourages zeros in the loading coefficients; gamma determines which reconstruction residuals are expensive to leave in the squared loss. They are not interchangeable controls. The historical default gamma = 100 is not an automatically calibrated threshold, especially after standardizing variables. Consider plausible measurement-error sizes in the processed units, inspect residuals, and compare a small range of scientifically meaningful thresholds. Residuals from an ordinary fit can provide context, but they also include low-rank truncation and regularization error.

A small gamma allows more of the observations to be explained by sparse; making it arbitrarily small is not necessarily an improvement. A large value approaches the ordinary squared-loss fit. If all measurements are multiplied by a nonzero constant c and column scaling is disabled, preserve the same model by multiplying gamma by |c|. The relative alpha and beta stay unchanged because their effective coefficients already scale with the squared data singular value.

Robust location or scale estimates can be applied externally when justified by the analysis. In that case, retain those transformations separately, fit with center = FALSE, scale = FALSE, and apply the same external transformation to future observations. The fit stores only preprocessing performed by the function itself; predict cannot recover an external preprocessing step automatically.

Note

Version 1.0.0 corrects an objective bookkeeping error reported by Maria A. Sans-Fuentes. Earlier versions charged the penalty on S but omitted it from the squared reconstruction residual, which could make the recorded objective rise and terminate optimization too early. Robust fits with nonzero sparse can therefore run longer and return different fitted values after the correction.

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")}.

See Also

spca, rspca, predict.spca.

Examples

set.seed(42)
signal <- matrix(rnorm(120 * 2), 120, 2)
weights <- matrix(0, 8, 2)
weights[1:4, 1] <- 1
weights[5:8, 2] <- 1
X <- tcrossprod(signal, weights) + matrix(rnorm(120 * 8, sd = 0.1), 120)
X[cbind(c(3, 40, 99), c(1, 6, 4))] <- c(8, -10, 9)
fit <- robspca(X, k = 2, alpha = 0.001, gamma = 0.5,
               verbose = FALSE)
summary(fit)
sum(fit$sparse != 0)
low_rank <- tcrossprod(fit$scores, fit$transform)
processed_fit <- low_rank + fit$sparse
# Here scale = FALSE; add the training means only once.
# The sparse matrix represents differences, so it receives no mean.
reconstructed <- sweep(processed_fit, 2, fit$center, "+")
low_rank_in_original_units <- sweep(low_rank, 2, fit$center, "+")
head(which(fit$sparse != 0, arr.ind = TRUE))

# Recompute the complete default elastic-net objective from the outputs.
processed <- scale(X, center = fit$center, scale = fit$scale)
remaining <- processed - low_rank - fit$sparse
criterion <- 0.5 * sum(remaining^2) +
  fit$alpha * sum(abs(fit$loadings)) +
  0.5 * fit$beta * sum(fit$loadings^2) +
  fit$gamma * sum(abs(fit$sparse))
all.equal(criterion, tail(fit$objective, 1))

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