TExcelTAD

PCA and Truncated SVD

A table with 64 pixel columns, 300 sensor channels or 20,000 word counts has far more columns than independent pieces of information: neighbouring pixels move together, sensors measure overlapping things, words co-occur. Dimensionality reduction replaces many correlated columns with a few new ones that keep most of the information. It speeds up training, removes noise, avoids the curse of dimensionality for distance-based models, and makes 2-D pictures of high-dimensional data possible. This lesson covers the two linear workhorses, PCA for dense data and truncated SVD for sparse data. The math is derived in the Mathematics track (PCA as maximum variance, SVD); here we use it as a preparation step.

See it first

The lab draws 120 points of two correlated features. PCA turns the cloud so that its longest direction becomes the first axis (PC1), then, with k=1k = 1, drops every point onto that axis.

−505−505PC1 scorePC2 scoreProjected onto PC1 (k = 1)PC1PC2Explained variance ratio0%25%50%75%100%90.8 %PC19.2 %PC2kept with k = 1: 90.8 %

At the default correlation of 0.8 the two variances are 2.299 and 1.961 with covariance 1.729. The eigenvalues are λ1=3.868\lambda_1 = 3.868 and λ2=0.392\lambda_2 = 0.392, so PC1 alone keeps 90.8% of the total variance, and dropping PC2 loses only 0.392. Slide the correlation to 0 and the picture changes: the eigenvalues become 2.364 and 1.784, PC1 explains only 57.0%, and one component is no longer a good summary. PCA compresses well only when features are correlated.

Definitions

Centre the data matrix XX (nn rows, dd columns) so every column has mean 0. Its covariance matrix is

C=1n−1X⊤XC = \frac{1}{n - 1} X^\top X

The principal components are the eigenvectors v1,…,vdv_1, \dots, v_d of CC, sorted by their eigenvalues λ1≥⋯≥λd\lambda_1 \ge \dots \ge \lambda_d. Eigenvalue λj\lambda_j is the variance of the data along vjv_j. Keeping the first kk gives the projection Z=XVkZ = X V_k (an n×kn \times k matrix of scores) and the explained variance ratio

λ1+⋯+λkλ1+⋯+λd\frac{\lambda_1 + \dots + \lambda_k}{\lambda_1 + \dots + \lambda_d}

The same components come out of the singular value decomposition X=UΣV⊤X = U \Sigma V^\top: the columns of VV are the principal directions and λj=σj2/(n−1)\lambda_j = \sigma_j^2 / (n - 1). Libraries use the SVD because it is numerically more stable than forming X⊤XX^\top X.

PCA from scratch

python · try it yourself
import numpy as np
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA

X = load_wine().data                       # 178 wines, 13 chemical measurements
Xs = (X - X.mean(0)) / X.std(0)            # standardise (see below why)

C = np.cov(Xs, rowvar=False)
lam, V = np.linalg.eigh(C)                 # eigh: symmetric matrix, ascending order
order = np.argsort(lam)[::-1]
lam, V = lam[order], V[:, order]
ratio = lam / lam.sum()
print("explained variance ratio, first 4:", np.round(ratio[:4], 3).tolist())
print("cumulative, first 4:             ", np.round(np.cumsum(ratio)[:4], 3).tolist())

Z = Xs @ V[:, :2]
pca = PCA(n_components=2).fit(Xs)
Z_sk = pca.transform(Xs)
print("sklearn ratio:", np.round(pca.explained_variance_ratio_, 3).tolist())
print("same scores up to sign:", np.allclose(np.abs(Z), np.abs(Z_sk)))
explained variance ratio, first 4: [0.362, 0.192, 0.111, 0.071]
cumulative, first 4:              [0.362, 0.554, 0.665, 0.736]
sklearn ratio: [0.362, 0.192]
same scores up to sign: True

On the 13 standardised wine measurements, the first component explains 36.2% of the variance and the first four together 73.6%. The eigen-decomposition and scikit-learn's SVD-based PCA give the same ratios and the same scores up to sign. The signs of components are arbitrary: vv and −v-v describe the same axis, so two libraries may disagree on the sign, never on the axis.

Choosing k, and why scaling comes first

PCA chases variance, so a feature measured in large units dominates. In the wine data, proline is measured in the hundreds and most other features below 10. Pass a float to n_components to keep the smallest number of components that reaches that share of the variance:

python · try it yourself
import numpy as np
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score

X, y = load_wine(return_X_y=True)
raw = PCA().fit(X)
print("raw data, PC1 explains:", round(float(raw.explained_variance_ratio_[0]), 3))
print("largest loading on PC1:", load_wine().feature_names[int(np.argmax(np.abs(raw.components_[0])))])

pca95 = make_pipeline(StandardScaler(), PCA(n_components=0.95)).fit(X)
print("components for 95% (scaled):", int(pca95[-1].n_components_))

for k in [1, 2, 5, 13]:
    pipe = make_pipeline(StandardScaler(), PCA(n_components=k), LogisticRegression(max_iter=1000))
    acc = cross_val_score(pipe, X, y, cv=5).mean()
    print(f"k={k:>2}: 5-fold CV accuracy {acc:.3f}")
raw data, PC1 explains: 0.998
largest loading on PC1: proline
components for 95% (scaled): 10
k= 1: 5-fold CV accuracy 0.849
k= 2: 5-fold CV accuracy 0.955
k= 5: 5-fold CV accuracy 0.978
k=13: 5-fold CV accuracy 0.983

Without scaling, PC1 "explains" 99.8% of the variance, and its largest loading is proline: the component is just the feature with the biggest numbers. After standardising, 10 of the 13 components are needed for 95%, because the wine features are only partly redundant. The cross-validated accuracy of a logistic regression shows what matters for the task: one component gives 0.849, two already 0.955, five 0.978 and all thirteen 0.983. Two or five components keep almost all of the predictive information.

PCA sits inside the pipeline, after the scaler and before the model, so cross-validation refits both on each training fold. Fitting PCA on all rows before splitting is a (usually small) leak: the components have seen the test rows. More practical advice on choosing kk is in PCA in Practice.

Truncated SVD for sparse data

Text turned into TF-IDF vectors is sparse: thousands of columns, almost all zero. Centring would subtract the column means and make every entry non-zero, which can blow up memory. TruncatedSVD skips the centring and computes only the top kk singular vectors of the sparse matrix directly. On text this is called latent semantic analysis (LSA): the components group words that occur in similar documents.

python · try it yourself
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD

docs = ["the striker scored a late goal", "the keeper saved the penalty",
        "a goal from the penalty spot", "the striker and the keeper",
        "the bank raised interest rates", "rates and inflation worry the bank",
        "inflation pushed interest higher", "the central bank and inflation"]
tfidf = TfidfVectorizer(stop_words="english")
X = tfidf.fit_transform(docs)
print("matrix:", X.shape, " non-zero share:", round(X.nnz / np.prod(X.shape), 3))

svd = TruncatedSVD(n_components=2, random_state=0)
Z = svd.fit_transform(X)
terms = tfidf.get_feature_names_out()
for j, comp in enumerate(svd.components_):
    top = terms[np.argsort(comp)[::-1][:4]]
    print(f"component {j}: {', '.join(top)}")
print("doc scores on component 1:", np.round(Z[:, 1], 2).tolist())
matrix: (8, 16)  non-zero share: 0.195
component 0: bank, inflation, rates, worry
component 1: keeper, striker, penalty, goal
doc scores on component 1: [0.58, 0.69, 0.55, 0.72, 0.0, 0.0, 0.0, 0.0]

Eight short documents give an 8×168 \times 16 matrix in which only 19.5% of the entries are non-zero. Without being told anything about topics, the two components separate them: one is led by bank, inflation, rates, worry; the other by keeper, striker, penalty, goal. On the second component the four football documents score between 0.55 and 0.72 and the four finance documents 0.

Pitfalls

  • No scaling before PCA on features with different units: the components then describe units, not structure.
  • Fitting PCA on all data before splitting: put it in the pipeline.
  • Reading components as causes: a component is a direction of variance, a mix of many features; it need not mean anything.
  • PCA on categorical codes or IDs: variance of arbitrary integers is meaningless.
  • Keeping 95% of variance for a supervised task by default: the label may live in a low-variance direction. Tune kk by cross-validation (or use LDA, which looks at the label).

Practice

  1. A PCA on 10 standardised features gives eigenvalues 4, 2, 1.5, 1, 0.5 and five times 0.2. How many components keep at least 90% of the variance?
Answer

The total is 4+2+1.5+1+0.5+5⋅0.2=104 + 2 + 1.5 + 1 + 0.5 + 5 \cdot 0.2 = 10 (as it must be for 10 standardised features). Cumulative: 40%, 60%, 75%, 85%, 90%. Five components reach 90%.

  1. Why does TruncatedSVD not centre the data, and what is the consequence for its first component on TF-IDF data?
Answer

Centring would turn a sparse matrix into a dense one. Without centring, the first component mostly points towards the mean document (the overall word frequencies), so it often captures "how much text/which common words" rather than a contrast; the later components carry the topic contrasts.

Test yourself

What does the eigenvalue λj\lambda_j of the covariance matrix measure?

  1. The mean of feature jj
  2. The variance of the data along principal direction vjv_j
  3. The correlation of PC jj with the label
  4. The number of rows

Why standardise features before PCA when they have different units?

  1. PCA needs integers
  2. Otherwise the feature with the largest numbers dominates the variance and the first component
  3. Standardising removes correlations
  4. It makes PCA supervised

Which tool reduces a sparse TF-IDF matrix without making it dense?

  1. PCA with centring
  2. TruncatedSVD
  3. StandardScaler
  4. t-SNE

Two libraries return principal components with opposite signs. What does that mean?

  1. One of them is wrong
  2. Nothing: vv and −v-v span the same axis
  3. The data is not centred
  4. The eigenvalues differ