Linear, manifold, topic, tensor, and graph representations · Linear and multiview representations · REP001 · Model
Principal component analysis (PCA)
Compress correlated quantitative variables into orthogonal directions of maximum sample variance. PCA is a baseline for denoising, visualization, and numerical preconditioning, not a clustering algorithm or a test for…
In CodeSplash
A CodeSplash method runs this entry in Python and R. Set it up from the method's page.
- Principal component analysis Verified in Python and R
Do it in CodeSplash Run it on your own data, in Python or R.
- Availability
- Runs in CodeSplash
- Code example
- Small complete fit
- Who ran it
- CodeSplash's run and the reference's record
- CodeSplash's run
- Verified in Python and R through discover.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
Compress correlated quantitative variables into orthogonal directions of maximum sample variance. PCA is a baseline for denoising, visualization, and numerical preconditioning, not a clustering algorithm or a test for latent groups.
Question / hypotheses
Which low-rank subspace preserves the greatest squared variation? This entry specifies an estimation or representation objective; it does not define a universal null hypothesis or p-value.
Architecture / computational structure
A centered feature matrix passes through an orthogonal linear encoder and its transpose decoder; the retained SVD components define both.
Assumptions
Euclidean variation must be meaningful; outliers and high-variance nuisance features can dominate.
Formula / computational definition
For centered data , minimize with . The loading matrix contains principal directions; scores are . SVD gives the global least-squares solution.
Parameters and notation
Estimated/learned quantities: Feature means, loadings, scores, and retained variances.
Hyperparameters and design choices: Rank , centering/scaling policy, whitening, and numerical solver. Numerical tolerances control computation; rank, priors, neighborhood scales, and loss weights alter the model where applicable.
Fitting, fine-tuning, and adaptation
Fine-tuning is not a separate stage. Refit on training data after distribution shifts; project new rows with the saved mean and loadings. Compare ranks using held-out reconstruction.
How to use and calibrate
Plot held-out reconstruction error, eigenvalue decay, loading stability, and sensitivity to scaling. Explained variance is not downstream usefulness. 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
Compress correlated sensor measurements before plotting operating regimes. 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
Gaussianity is unnecessary for descriptive PCA, although inferential models require additional assumptions.
Python and R code examples
Python: sklearn.decomposition.PCA. R: stats::prcomp; both can also use SVD. Lab REP-L1 implements the same deterministic problem and checks the optimal reconstruction identity.
Scope: Complete rank-two PCA fit by SVD, followed by reconstruction.
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.
Small complete fit — Complete rank-two PCA fit by SVD, followed by reconstruction.
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)
u,s,vt = np.linalg.svd(X, full_matrices=False)
scores = X @ vt[:2].T
reconstruction = scores @ vt[:2]
assert np.allclose(np.sum((X-reconstruction)**2), np.sum(s[2:]**2))
print(np.sum(s[:2]**2)/np.sum(s**2))
Small complete fit — Complete rank-two PCA fit by SVD, followed by reconstruction.
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]) }
s <- svd(X); scores <- X %*% s$v[,1:2]
reconstruction <- scores %*% t(s$v[,1:2])
stopifnot(abs(sum((X-reconstruction)^2)-sum(s$d[-(1:2)]^2)) < 1e-8)
print(sum(s$d[1:2]^2)/sum(s$d^2))
Sources
- Source 1tandfonline.com
- Source 2scikit-learn.org
From the CodeSplash reference, entry REP001.