Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 20 min · revision 2

PCA: Finding the Directions That Matter

Fit PCA on wine and digit data to see why units matter, read explained variance to choose how many components to keep, compress and rebuild images, use PCA inside a pipeline while knowing what it cannot see, and compare PCA with t-SNE and UMAP for visualisation.

Contentsand lesson path

What you will learn

  • Reduce dimensionality with PCA, read explained variance, and use the result for visualization, compression or as a preprocessing step.

01. Why it matters

Real tables often have dozens or hundreds of columns that move together: the pixels of an image, the chemical measurements of a wine, the spend of a customer in each product category. Principal component analysis (PCA) replaces them with a few new columns that keep most of the variation. You use it for three jobs: to draw high-dimensional data in two dimensions, to compress data, and as a preprocessing step that makes a later model cheaper or more stable.

PCA is a fitted linear transform. fit learns a mean and a set of directions from training rows, and transform applies exactly the same mapping to any new row. That property separates it from t-SNE and UMAP, which this lesson also covers. The mathematics is the singular value decomposition from Similarity and Structure, so this lesson concentrates on using PCA well. The code uses Python 3.12, scikit-learn 1.9 and SciPy 1.18 with datasets that ship with scikit-learn.

02. Directions of maximum variance, and why units matter

The first principal component is the direction in feature space along which the data, projected onto it, has the largest variance. The second is the direction at right angles to the first with the largest remaining variance, and so on. Each component is a list of weights, one per feature, so a component is a linear combination of all the original features. The explained variance ratio of a component is its share of the total variance.

The wine dataset has 13 chemical measurements of 178 wines, in very different units. wine_pca.py runs PCA on the raw values and on standardised values, and checks the result against a plain SVD.

Python · wine_pca.py
import numpy as np
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

data = load_wine()
X, names = data.data, data.feature_names
std = X.std(axis=0)
print("largest feature stds:",
      ", ".join(f"{names[i]} {std[i]:.1f}" for i in np.argsort(-std)[:3]))

Z = StandardScaler().fit_transform(X)
raw, scaled = PCA().fit(X), PCA().fit(Z)
print("raw    explained variance ratio:", raw.explained_variance_ratio_[:4].round(3))
print("scaled explained variance ratio:", scaled.explained_variance_ratio_[:4].round(3))

for label, model in [("raw", raw), ("scaled", scaled)]:
    pc1 = model.components_[0]
    top = np.argsort(-np.abs(pc1))[:2]
    print(f"{label:6} PC1 top weights:",
          ", ".join(f"{names[i]} {pc1[i]:+.2f}" for i in top))
pc1 = scaled.components_[0]
print("scaled PC1, features with |weight| > 0.1:", np.sum(np.abs(pc1) > 0.1))

# PCA is the SVD of the centred data: the rows of Vt are the components
_, s, Vt = np.linalg.svd(Z - Z.mean(axis=0), full_matrices=False)
same = np.allclose(np.abs(Vt), np.abs(scaled.components_))   # signs are arbitrary
print("same directions as the SVD:", same)
print("ratio from singular values:", (s**2 / np.sum(s**2))[:4].round(3))
Terminal
python wine_pca.py
Expected output
largest feature stds: proline 314.0, magnesium 14.2, alcalinity_of_ash 3.3
raw    explained variance ratio: [0.998 0.002 0.    0.   ]
scaled explained variance ratio: [0.362 0.192 0.111 0.071]
raw    PC1 top weights: proline +1.00, magnesium +0.02
scaled PC1 top weights: flavanoids +0.42, total_phenols +0.39
scaled PC1, features with |weight| > 0.1: 11
same directions as the SVD: True
ratio from singular values: [0.362 0.192 0.111 0.071]

On raw values the first component explains 99.8% of the variance, and its weights show why: it is proline and almost nothing else. Proline is measured in mg/L with a standard deviation of 314, far above any other column, and PCA maximises variance in whatever units it is given. That component describes the units, not the wines. After standardising, the variance spreads over several components (36.2%, 19.2%, 11.1%, ...) and the first component gives weight above 0.1 to 11 of the 13 features, led by flavanoids and total phenols. It is a new axis built from almost every feature, not a selection of the best original columns.

So standardise features measured in different units. When every feature already shares one unit, such as pixel intensities, PCA on the raw values is usually the better choice, because standardising would inflate near-constant columns, such as border pixels that are almost always blank. The last two lines confirm the link to the SVD: the components are the right singular vectors of the centred data, up to sign, and each explained variance ratio is a squared singular value divided by the sum of all of them.

03. How many components to keep

How many components should you keep? The cumulative explained variance tells you how much spread a given number keeps. Passing a float such as n_components=0.90 asks scikit-learn for the smallest number that keeps 90%. choose_n.py uses the digits dataset: 1,797 handwritten digits of 8 × 8 = 64 pixels, all on the same 0–16 scale, so no standardising.

Python · choose_n.py
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA

X, _ = load_digits(return_X_y=True)       # 1,797 images of 8 x 8 = 64 pixels
pca = PCA().fit(X)
cumulative = np.cumsum(pca.explained_variance_ratio_)
for n in [2, 10, 20, 30, 40]:
    print(f"{n:2d} components keep {cumulative[n - 1]:.1%} of the variance")

pca90 = PCA(n_components=0.90).fit(X)    # a float: smallest n reaching 90%
codes = pca90.transform(X)
rebuilt = pca90.inverse_transform(codes)
print("components for 90%:", pca90.n_components_, "| codes shape:", codes.shape)
print("mean squared pixel error after rebuilding:",
      round(float(np.mean((X - rebuilt) ** 2)), 2),
      "| pixel variance:", round(float(X.var(axis=0).sum() / 64), 2))
Terminal
python choose_n.py
Expected output
 2 components keep 28.5% of the variance
10 components keep 73.8% of the variance
20 components keep 89.4% of the variance
30 components keep 95.9% of the variance
40 components keep 98.8% of the variance
components for 90%: 21 | codes shape: (1797, 21)
mean squared pixel error after rebuilding: 1.82 | pixel variance: 18.77

Ten components keep 73.8% of the variance, 21 reach 90% and 40 reach 98.8%: the first few directions capture the broad strokes of a digit and later ones add finer detail. With 21 components each image is stored as 21 numbers, its codes, instead of 64. To rebuild an image, inverse_transform multiplies the codes by the components and adds the mean, so the mean vector and the 21 × 64 component matrix must be kept too, once for the whole dataset. The rebuilt pixels are off by 1.82 squared units on average, about a tenth of the average pixel variance of 18.77, which matches the 10% of variance that was dropped.

Common rules are a variance threshold such as 90% or 95%, or the bend in a scree plot of the ratios. Both only describe spread. When PCA feeds a model, choose the number of components by validating that model, as the next section shows.

04. PCA as a preprocessing step, and its blind spot

As a preprocessing step, PCA goes inside a pipeline, so that each cross-validation fold fits the mean and components on its own training rows. pipeline.py puts PCA in front of a 5-nearest-neighbour classifier on the digits.

Python · pipeline.py
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline

X, y = load_digits(return_X_y=True)
for n in [5, 10, 20, 40, None]:
    steps = [KNeighborsClassifier(5)]
    if n is not None:
        steps.insert(0, PCA(n_components=n, random_state=0))
    # PCA sits inside the pipeline, so each fold fits it on its training rows only
    scores = cross_val_score(make_pipeline(*steps), X, y, cv=5)
    label = f"PCA {n:2d} components" if n else "all 64 pixels      "
    print(f"{label}  CV accuracy {scores.mean():.3f}")
Terminal
python pipeline.py
Expected output
PCA  5 components  CV accuracy 0.884
PCA 10 components  CV accuracy 0.940
PCA 20 components  CV accuracy 0.958
PCA 40 components  CV accuracy 0.962
all 64 pixels        CV accuracy 0.963

With 20 components the classifier scores 0.958 against 0.963 on all 64 pixels. It loses half a point of accuracy while every neighbour search works in 20 dimensions instead of 64, which cuts memory and prediction time. Five components are too few. Removing the low-variance directions can also remove pixel noise, which is why a modest number of components sometimes matches or beats the raw features.

PCA has a blind spot: it never looks at the target. blind.py builds two features. The first is wide random noise; the second has a small spread but carries the class.

Python · blind.py
import numpy as np
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline

rng = np.random.default_rng(0)
y = rng.integers(0, 2, 1000)
X = np.column_stack([
    rng.normal(0, 5, 1000),                  # wide spread, unrelated to y
    y + rng.normal(0, 0.3, 1000),            # narrow spread, carries y
])
pca = PCA(n_components=1).fit(X)
print("PC1 weights:", pca.components_[0].round(3),
      "| variance kept:", pca.explained_variance_ratio_.round(3))
for name, model in [("both features", LogisticRegression()),
                    ("PCA, 1 component", make_pipeline(PCA(1), LogisticRegression()))]:
    print(f"{name:17} CV accuracy {cross_val_score(model, X, y, cv=5).mean():.3f}")
Terminal
python blind.py
Expected output
PC1 weights: [1.    0.009] | variance kept: [0.985]
both features     CV accuracy 0.954
PCA, 1 component  CV accuracy 0.553

PCA keeps the wide noise feature as its first component (weights 1.0 and 0.009) because it has 98.5% of the variance, and that throws away the narrow feature that carries the class. Accuracy falls from 0.954 to 0.553, close to guessing. High variance and usefulness for a prediction are different things. Before reducing features for a supervised model, compare the downstream score with and without PCA, as pipeline.py does.

05. Pictures: PCA, t-SNE and UMAP

For a picture you need two dimensions. PCA's first two components give a faithful linear projection, but on the digits they keep only 28.5% of the variance, so many classes overlap. t-SNE (t-distributed stochastic neighbour embedding) takes another approach: it places the points in 2-D so that points that were close neighbours in the original space stay close, and it is free to bend and stretch everything else. tsne_vs_pca.py measures both sides of that trade on 500 digits. Trustworthiness is close to 1 when the neighbours of each point in the 2-D map were also its neighbours in the original space. The rank correlation compares all pairwise distances before and after, a rough measure of global layout.

Python · tsne_vs_pca.py
from scipy.spatial.distance import pdist
from scipy.stats import spearmanr
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE, trustworthiness

X = load_digits().data[:500]          # a subset keeps the exact method fast
maps = {"PCA": PCA(n_components=2, random_state=0).fit_transform(X),
        "t-SNE": TSNE(n_components=2, method="exact", random_state=0).fit_transform(X)}
d_orig = pdist(X)
print("        local: trustworthiness   global: distance rank correlation")
for name, Y in maps.items():
    local = trustworthiness(X, Y, n_neighbors=10)
    global_ = spearmanr(d_orig, pdist(Y)).statistic
    print(f"{name:6} {local:21.3f} {global_:29.3f}")
print("PCA has transform():", hasattr(PCA(), "transform"),
      "| TSNE has transform():", hasattr(TSNE(), "transform"))
Terminal
python tsne_vs_pca.py
Expected output
        local: trustworthiness   global: distance rank correlation
PCA                    0.857                         0.622
t-SNE                  0.993                         0.530
PCA has transform(): True | TSNE has transform(): False

t-SNE keeps neighbourhoods far better (0.993 against 0.857), which is why its plots show crisp, separate groups. PCA keeps the global layout better (0.622 against 0.530): in a t-SNE map the distance between two groups, and the size of a group, carry little meaning. t-SNE also has no transform method. It optimises positions for the points it was given, so a new point cannot be placed without rerunning everything, and the result changes with its perplexity setting and the seed. The script uses method="exact" on 500 points to make the numbers reproducible; the default Barnes-Hut method is much faster on large data, but its result can differ slightly with the number of CPU threads.

UMAP (uniform manifold approximation and projection, in the separate umap-learn package) has the same goal, usually runs faster on large datasets, often keeps more of the global layout depending on its settings, and can embed new points. Its maps still bend distances, though. Use t-SNE and UMAP to look at data and form hypotheses, then check every pattern you see with the original features. Use PCA, or a trained encoder, when you need features, compression or a mapping for new rows.

06. Check your understanding

Practice check · 3 questions

Using PCA well

Answer from the code and the numbers in this lesson.

Q1. You refit the PCA from `wine_pca.py` on next month's batch of wines. The first component now reads flavanoids −0.42, total phenols −0.39 and so on: every sign is reversed. What should you conclude?
Q2. In `blind.py` the first component keeps 98.5% of the variance, yet cross-validated accuracy falls from 0.954 to 0.553 when the model sees only that component. Why?
Q3. In `choose_n.py`, 21 components keep 90% of the variance of the 1,797 digit images. You want to store the images compressed and rebuild them later. What do you need to keep?
Practice only: not graded, not saved, not evidence.

07. Apply it

Continue the practice project with the segments from the previous lab.

  1. Standardise the four log-transformed customer features, fit PCA(n_components=2), and report the explained variance ratio of each component and the weights of each feature.
  2. Plot the customers in the two components with Matplotlib, coloured by segment from data/segments.csv, and save the figure. Describe in two sentences what each axis represents, using its weights.
  3. Run t-SNE on the same features, plot it next to the PCA view, and write down one thing that looks different between the two pictures and why.

08. Review prompt

Without looking back, explain what a principal component is and how its explained variance ratio is computed from singular values; when to standardise before PCA and when not to; what you must store to rebuild compressed rows; why a component with most of the variance can be useless for a prediction; and what t-SNE preserves, what it distorts and why it cannot be used inside a production pipeline.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check