Sub topic 7
Explained Variance and the Scree Plot
This chapter assumes you can compute a covariance matrix, know that principal components are eigenvectors of it, and can use NumPy. Here you learn to measure how much information each component keeps, and to plot that measure.
What explained variance means
Each principal component has an eigenvalue. That eigenvalue equals the variance of the data after projecting it onto that component. Because the components are uncorrelated, the variances add up. The sum of all eigenvalues equals the total variance, which is the trace of the covariance matrix.
The explained variance ratio of component k is its eigenvalue divided by the sum of all eigenvalues:
ratiok = λk / (λ1 + λ2 + ... + λ_d)
The ratios sum to 1. The cumulative explained variance is the running sum of the ratios. It tells you what fraction of the total variance the first k components keep together.
Computing the ratios
This uses the same data as the from-scratch example. The third feature has a small scale, so you should expect it to contribute little.
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 = np.linalg.eigh(cov)[0][::-1] # eigh sorts ascending, so reverse
ratio = eigvals / eigvals.sum()
cumulative = np.cumsum(ratio)
print(ratio)
print(cumulative)np.linalg.eigh returns eigenvalues in ascending order. If you forget to reverse them, your ratios will be attached to the wrong components.
The first component carries most of the variance, the second carries a modest share, and the third carries almost none. The exact digits depend on the random sample.
The scree plot
A scree plot shows the eigenvalues, or the ratios, in decreasing order, one point per component. The name comes from the pile of loose rock at the foot of a cliff. The steep drop is the cliff, and the flat tail is the scree.
Read it by looking for the elbow, the point where the curve stops falling steeply and flattens. Components before the elbow carry structure. Components after it mostly carry noise or small variations.
The same data drawn with matplotlib looks like this:
import numpy as np
import matplotlib.pyplot as plt
ratio = np.array([0.52, 0.27, 0.10, 0.05, 0.04, 0.02])
ks = np.arange(1, len(ratio) + 1)
fig, ax = plt.subplots()
ax.plot(ks, ratio, "o-", label="per component")
ax.plot(ks, np.cumsum(ratio), "s--", label="cumulative")
ax.set_xlabel("Component")
ax.set_ylabel("Explained variance ratio")
ax.legend()
plt.show()Plotting the cumulative curve on the same axes lets you read off how many components reach a target such as 90%.
Common errors
| Mistake | Effect |
|---|---|
| Not sorting eigenvalues in decreasing order | Wrong components are labeled as the top ones |
| Skipping standardization when features have different units | One large-scale feature dominates the first ratio |
| Treating the elbow as exact | Real scree plots are often smooth, and the elbow is a judgment call |
| Reading the ratio as "accuracy" | It measures variance kept, not usefulness for a downstream task |
The next chapter uses these ratios to choose a number of components.
Exercise
A dataset has four eigenvalues: 6.0, 3.0, 0.8 and 0.2. Compute the explained variance ratio of each component and the cumulative ratio after two components.
Show answer
The total is 6.0 + 3.0 + 0.8 + 0.2 = 10.0. The ratios are 0.60, 0.30, 0.08 and 0.02. The cumulative ratio after two components is 0.60 + 0.30 = 0.90, so two components keep 90% of the variance.
Exercise
You run np.linalg.eigh on a covariance matrix and compute eigvals / eigvals.sum() without reordering. Why is the first printed ratio probably not the largest, and how do you fix it?
Show answer
eigh returns eigenvalues in ascending order, so the first value is the smallest. Reverse the array with eigvals[::-1], or sort with np.argsort(eigvals)[::-1], and reorder the eigenvectors the same way.