Sub topic 7
Explained variance and the scree plot
This chapter assumes you can compute a covariance matrix, know that PCA components are eigenvectors of it, and can run NumPy and scikit-learn code. Here you learn to measure how much information each component carries and to read that measurement. The next chapter uses it to decide how many components to keep.
What "explained variance" means
PCA treats the total variance of the data as the quantity to preserve. The total variance is the sum of the variances of all features, which equals the trace of the covariance matrix.
The eigenvalues of the covariance matrix split that total across components:
- Each eigenvalue λ_k is the variance of the data along principal component k.
- The eigenvalues add up to the trace, so Σ λ_k = total variance.
- The explained variance ratio of component k is λk / Σ λj.
- The cumulative explained variance after k components is the running sum of these ratios.
Components are sorted so that λ1 ≥ λ2 ≥ … ≥ λ_p. The first component therefore always explains the most variance, and the ratios form a non-increasing list that sums to 1.
Computing the ratios by hand
The covariance matrix is symmetric, so np.linalg.eigh returns real eigenvalues in ascending order. Reverse them before using them. The sketch below also checks the trace identity.
import numpy as np
rng = np.random.default_rng(0)
mixing = np.array([[3.0, 0.0, 0.0],
[1.0, 1.0, 0.0],
[0.0, 0.0, 0.2]])
X = rng.normal(size=(200, 3)) @ mixing
Xc = X - X.mean(axis=0)
cov = np.cov(Xc, rowvar=False)
eigvals, eigvecs = np.linalg.eigh(cov)
order = np.argsort(eigvals)[::-1]
eigvals = eigvals[order]
eigvecs = eigvecs[:, order]
ratio = eigvals / eigvals.sum()
cumulative = np.cumsum(ratio)
print("trace equals eigenvalue sum:", np.isclose(np.trace(cov), eigvals.sum()))
print("ratio:", ratio)
print("cumulative:", cumulative)In this synthetic data, the first two features are strongly mixed and the third feature has a tiny scale of 0.2. The population covariance is block diagonal, and its eigenvalues are about 10.11, 0.89 and 0.04. The first component explains roughly 92% of the variance, the second about 8%, and the third well under 1%. Your sample values will differ slightly because the sample has only 200 rows.
The scree plot
A scree plot shows the eigenvalues (or ratios) against the component index. The name comes from geology. Scree is the pile of loose rock at the foot of a cliff, and the plot is usually a steep drop followed by a flat tail.
Read it in three parts:
- The steep part at the left holds components that capture structure, such as correlations between features.
- The elbow is the point where the curve bends from steep to flat.
- The flat tail holds components with similar small variances. These often reflect noise, because pure noise spreads variance roughly equally in all directions.
A cumulative line is often drawn on the same axes. It shows where you cross a target such as 90% or 95%.
Getting the numbers from scikit-learn
A fitted PCA object stores the eigenvalues and ratios for you:
explained_variance_holds the eigenvalues, computed withn - 1in the denominator.explained_variance_ratio_holds the ratios.singular_values_holds the singular values of the centered data.
The following code fits PCA on standardized Iris data, prints the numbers, and draws the scree plot. It writes the figure to a file so it also runs without a display.
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, _ = load_iris(return_X_y=True)
pipe = make_pipeline(StandardScaler(), PCA())
pipe.fit(X)
pca = pipe.named_steps["pca"]
print("eigenvalues:", pca.explained_variance_)
print("ratio:", pca.explained_variance_ratio_)
cumulative = np.cumsum(pca.explained_variance_ratio_)
print("cumulative:", cumulative)
k = np.arange(1, len(cumulative) + 1)
fig, ax = plt.subplots(figsize=(5, 3.5))
ax.bar(k, pca.explained_variance_ratio_, label="per component")
ax.plot(k, cumulative, marker="o", color="black", label="cumulative")
ax.set_xticks(k)
ax.set_xlabel("Component")
ax.set_ylabel("Explained variance ratio")
ax.legend()
fig.tight_layout()
fig.savefig("scree.png", dpi=120)For standardized Iris, the ratios are about 0.730, 0.229, 0.037 and 0.005. The eigenvalues are about 2.93, 0.91, 0.15 and 0.02. They add up to 4, the number of features, because each standardized feature has variance 1.
Finding the component count from the cumulative curve
Once you have the cumulative ratio, the smallest k that reaches a threshold is one search away. np.searchsorted works because the cumulative sum is sorted:
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
X, _ = load_digits(return_X_y=True)
X_std = StandardScaler().fit_transform(X)
pca = PCA().fit(X_std)
cumulative = np.cumsum(pca.explained_variance_ratio_)
for target in (0.80, 0.90, 0.95, 0.99):
k = int(np.searchsorted(cumulative, target) + 1)
print(f"{target:.0%} of variance needs {k} of {X_std.shape[1]} components")Passing PCA(n_components=0.95) does the same thing internally. The explicit version is better when you want to compare several thresholds from a single fit.
Explained variance and reconstruction error
The discarded eigenvalues also measure what you lose when you reconstruct. If you keep k components, the total squared reconstruction error divided by n - 1 equals the sum of the discarded eigenvalues. That gives a direct link between the scree plot and the error:
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 3)) @ np.array([[3.0, 0.0, 0.0],
[1.0, 1.0, 0.0],
[0.0, 0.0, 0.2]])
Xc = X - X.mean(axis=0)
n = Xc.shape[0]
eigvals, eigvecs = np.linalg.eigh(np.cov(Xc, rowvar=False))
eigvals = eigvals[::-1]
eigvecs = eigvecs[:, ::-1]
k = 2
V = eigvecs[:, :k]
residual = Xc - Xc @ V @ V.T
lhs = (residual ** 2).sum() / (n - 1)
rhs = eigvals[k:].sum()
print(lhs, rhs, np.isclose(lhs, rhs))So "95% of the variance explained" also means "the squared reconstruction error is 5% of the total variance". This holds for the centered (and, if you scaled, standardized) data. It does not hold in the original units if you scaled the features first.
Edge cases and pitfalls
- Scaling changes the answer. Without standardization, a feature measured in large units dominates the first component and inflates its ratio. With standardization, every feature contributes a variance of 1. Compare the scree plots of raw and standardized data on the same dataset to see this.
- Ratios depend on the data you fit on. Compute them on the training set only. A held-out set gives different ratios when projected onto the training components.
- Truncated fits still report ratios against the full total. With
PCA(n_components=2),explained_variance_ratio_has two entries that sum to less than 1. The missing share is the variance you dropped. - Ties and near-ties. If two eigenvalues are nearly equal, their directions are poorly determined. Any rotation within that plane explains the same variance, so the individual components are unstable across samples even though their combined variance is not.
- Few samples. When
n < p, the covariance matrix has at mostn - 1nonzero eigenvalues. The remaining ratios are zero (or numerically tiny), and the cumulative curve reaches 1 early. - High explained variance is not the same as usefulness. A low-variance direction can carry the signal that separates two classes. Check task performance, not only the ratio.
Rules of thumb for reading the plot
| Rule | How it works | Weakness |
|---|---|---|
| Elbow | Keep components before the bend in the scree plot. | Subjective, and some plots have no clear bend. |
| Cumulative threshold | Keep enough components to reach 90% to 95%. | The threshold is arbitrary and the right value depends on the task. |
| Kaiser criterion | On standardized data, keep components with eigenvalue above 1. | Keeps too many on noisy data and too few on small datasets. |
| Parallel analysis | Keep components whose eigenvalues exceed those from shuffled or random data. | Requires extra computation and a choice of null model. |
For standardized Iris, the Kaiser criterion keeps one component (eigenvalue 2.93, then 0.91). The 95% threshold keeps two. The two rules disagree, which is common and is a reason to treat each rule as a guide rather than an answer.
Exercise
You fit PCA on 10 standardized features and get eigenvalues 5.0, 2.0, 1.2, 0.6, 0.4, 0.3, 0.2, 0.15, 0.1, 0.05. What are the explained variance ratio of the first component and the cumulative ratio after three components? How many components does the Kaiser criterion keep, and what is the sum of the discarded eigenvalues if you keep three?
Show answer
The eigenvalues sum to 10, matching the 10 standardized features. The first ratio is 5.0 / 10 = 0.50. After three components the cumulative sum is (5.0 + 2.0 + 1.2) / 10 = 0.82. The Kaiser criterion keeps eigenvalues above 1, so it keeps three components. If you keep three, the discarded eigenvalues sum to 0.6 + 0.4 + 0.3 + 0.2 + 0.15 + 0.1 + 0.05 = 1.8, which is 18% of the total variance and equals the squared reconstruction error divided by n - 1.
Exercise
A colleague fits PCA on raw features and reports that the first component explains 99% of the variance, so they conclude the data is essentially one-dimensional. What is the likely problem, and how would you check it?
Show answer
One feature probably has a much larger scale (for example, a value in the thousands next to values near 1), so it dominates the covariance matrix and the first component points almost along that feature. Standardize the features with StandardScaler, refit, and compare the scree plots. If the first ratio drops sharply, the 99% came from the scale of one feature and not from real one-dimensional structure.