Velamuvi AIAcademy

Lesson 4 of 8 · Techniques

Principal Component Analysis

Use PCA well in scikit-learn: standardise first, read explained variance, keep 95% of it, measure reconstruction error, and avoid leakage with a pipeline.

  • 16 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain principal components as the directions along which data varies most
  • Standardise features before PCA, and recognise what happens if you don't
  • Choose the number of components from explained_variance_ratio_, for example 95% of the variance
  • Rebuild data with inverse_transform and measure the reconstruction error
  • Use PCA in a pipeline fitted on training data only, and see the SVD behind it

The idea in plain words

Principal component analysis (PCA) replaces your features with new ones, called principal components, ordered by how much of the data's variation they capture. The first component, PC1, is the direction along which the data is most spread out. PC2 is the most spread-out direction at a right angle to PC1, and so on. Keep only the first few, and you have a shorter description of every example that still holds most of the variation.

The PCA lesson in Linear Algebra works through the maths step by step. This lesson is about using PCA well in scikit-learn: preparing the data, choosing how many components to keep, checking what was lost, and fitting PCA into a model. Start with two features that move together, people's height and arm span:

Try it yourselfPython
import numpy as np
from sklearn.decomposition import PCA

rng = np.random.default_rng(0)
height = rng.normal(170, 10, 200)                 # cm
arm_span = height + rng.normal(0, 4, 200)         # cm: close to height, but not equal
X = np.column_stack([height, arm_span])

pca = PCA().fit(X)
for i, (direction, share) in enumerate(zip(pca.components_, pca.explained_variance_ratio_), start=1):
    direction = direction * np.sign(direction[0])   # a direction and its opposite are the same line
    print(f"PC{i}: weights {direction[0]:.2f} for height, {direction[1]:5.2f} for arm span; "
          f"{share:.1%} of the variance")
Output
PC1: weights 0.68 for height,  0.73 for arm span; 95.8% of the variance
PC2: weights 0.73 for height, -0.68 for arm span; 4.2% of the variance

PC1 gives height and arm span almost equal weights: it measures a person's overall size, and it holds 95.8% of the variation. PC2 weighs height against arm span, so it measures whether someone's arms are long or short for their height, and it holds only 4.2%. Describe each person by their PC1 score alone and you use one number instead of two, losing 4.2% of the variation. A component's sign is arbitrary: a line pointing the other way is the same line, and different library versions may return either. That's why the code flips each direction so that its first weight is positive. Never give meaning to the sign itself, and describe a component by its biggest weights instead.

Standardise first

PCA chases variance, and variance depends on units. The wine dataset has 13 chemical measurements, from hue (between 0.48 and 1.71) to proline (between 278 and 1,680). Compare PCA on the raw and on the standardised measurements:

Try it yourselfPython
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          # 13 chemical measurements of 178 wines

for label, X_used in [("raw", X), ("standardised", StandardScaler().fit_transform(X))]:
    pca = PCA().fit(X_used)
    weights = np.abs(pca.components_[0])           # how much each feature counts in PC1
    top = np.argsort(weights)[::-1][:3]
    print(f"{label}: PC1 explains {pca.explained_variance_ratio_[0]:.1%}; biggest weights: "
          + ", ".join(f"{names[i]} {weights[i]:.2f}" for i in top))
Output
raw: PC1 explains 99.8%; biggest weights: proline 1.00, magnesium 0.02, alcalinity_of_ash 0.00
standardised: PC1 explains 36.2%; biggest weights: flavanoids 0.42, total_phenols 0.39, od280/od315_of_diluted_wines 0.38

On the raw data, PC1 is proline and nothing else (weight 1.00), and it "explains" 99.8% of the variance. That says nothing about wine: proline's numbers are simply the biggest. After standardising, every feature has a variance of 1, PC1 explains a more honest 36.2%, and it blends three measurements that rise and fall together. Standardise before PCA, unless every feature shares one unit and its spread is meaningful, as with the pixels of an image.

How many components?

The explained_variance_ratio_ attribute gives each component's share of the total variance, largest first. Its running total tells you how much the first k components keep together. Here it is for the 64 pixels of the handwritten digits, with a bar chart made of text:

Try it yourselfPython
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA

X, _ = load_digits(return_X_y=True)        # 64 pixels per image, all in the same unit
pca = PCA().fit(X)
ratios = pca.explained_variance_ratio_
running = np.cumsum(ratios)

for i in range(6):                          # the first few components, as a text bar chart
    print(f"PC{i + 1:<2} {ratios[i]:6.1%} {'#' * round(ratios[i] * 200)}")

for target in [0.80, 0.90, 0.95, 0.99]:
    k = np.argmax(running >= target) + 1    # first position where the running total reaches the target
    print(f"{target:.0%} of the variance needs {k} of 64 components")

print("PCA(n_components=0.95) keeps", PCA(n_components=0.95).fit(X).n_components_)
Output
PC1   14.9% ##############################
PC2   13.6% ###########################
PC3   11.8% ########################
PC4    8.4% #################
PC5    5.8% ############
PC6    4.9% ##########
80% of the variance needs 13 of 64 components
90% of the variance needs 21 of 64 components
95% of the variance needs 29 of 64 components
99% of the variance needs 41 of 64 components
PCA(n_components=0.95) keeps 29

No single component dominates: PC1 holds 14.9%, and the shares shrink slowly. Keeping 80% of the variance takes 13 components, and 95% takes 29, under half of the 64 pixels. Three common ways to choose:

  • A target share, such as 90% or 95%. Give n_components a number between 0 and 1, and PCA picks the smallest k that reaches it, as the last line shows.
  • The elbow of the bar chart, called a scree plot: the point where the bars flatten out, like the elbow in k-means.
  • The needs of the next step: 2 or 3 components for a picture, or, when PCA feeds a model, whatever number gives the best validation score.

Rebuilding the data: inverse_transform

transform turns every row into k component scores. inverse_transform goes back: it turns the k scores into a row of the original features. The rebuilt row is an approximation, because the dropped components are treated as 0. The reconstruction error, the average squared difference between the original and the rebuilt values, measures what was lost:

Try it yourselfPython
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA

X, _ = load_digits(return_X_y=True)
for k in [2, 5, 10, 20, 40, 64]:
    pca = PCA(n_components=k).fit(X)
    rebuilt = pca.inverse_transform(pca.transform(X))       # 64 -> k numbers -> 64 again
    error = np.mean((X - rebuilt) ** 2)
    print(f"{k:>2} components: reconstruction error {error:5.2f}")
Output
 2 components: reconstruction error 13.42
 5 components: reconstruction error  8.54
10 components: reconstruction error  4.91
20 components: reconstruction error  1.98
40 components: reconstruction error  0.22
64 components: reconstruction error  0.00

The error falls as k grows, and with all 64 components the data comes back exactly. Reconstruction error and explained variance are two views of the same loss: the error equals the variance of the dropped components, averaged over the features. Numbers are abstract, so here is the first digit in the dataset, drawn with characters from light to dark, as stored and as rebuilt from 5 and from 20 numbers:

Try it yourselfPython
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA

X, _ = load_digits(return_X_y=True)
shades = " .:-=+*#%@"                                  # from light (0) to dark (16)

def draw(image):
    pixels = np.clip(image, 0, 16).reshape(8, 8)
    return ["".join(shades[int(p / 16 * 9.99)] * 2 for p in row) for row in pixels]

pictures = [draw(X[0])]
for k in [5, 20]:
    pca = PCA(n_components=k).fit(X)
    pictures.append(draw(pca.inverse_transform(pca.transform(X[:1]))[0]))

print("original           5 components       20 components")
for rows in zip(*pictures):
    print("   ".join(rows).rstrip())
Output
original           5 components       20 components
    --%%++             --%%##--           --%%++....
    %%@@**@@--         @@##==##..         %%%%**##::
  ..@@..  **==       ::@@    ##::       ..@@..  ##==
  ::##    ====       --##  ..##==       ::##    ++==
  --==    ++==       --**....##==       --++    ++==
  ::**    ##==       ::##..  ##==       ::##  ..##--
  ..%%--**##           ##++==**..         %%==++##
    --%%**             --%%##::           --@@##

From 5 numbers, the 0 is recognisable but smudged. From 20, it is close to the original. Rebuilding is useful in its own right: the denoising in the previous lesson rebuilt noisy images from their strongest components, and a row that rebuilds badly doesn't look like the rest of the data, an idea Anomaly Detection builds on.

PCA inside a pipeline

When PCA feeds a model, it is part of the model, so it must learn from the training data only, just like a scaler. In a pipeline, cross-validation refits the scaler and PCA inside every fold, and n_components becomes a hyperparameter you can tune with GridSearchCV, as in Choosing an Algorithm:

Try it yourselfPython
from sklearn.datasets import load_breast_cancer
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)

pipe = make_pipeline(StandardScaler(), PCA(), LogisticRegression())
options = [1, 2, 3, 5, 10, 30]
search = GridSearchCV(pipe, {"pca__n_components": options}, cv=5)
search.fit(X_train, y_train)          # scaler, PCA and model only ever see training rows

for k, score in zip(options, search.cv_results_["mean_test_score"]):
    print(f"n_components={k:<2}  cross-validated accuracy {score:.3f}")
print("best:", search.best_params_, f"-> test accuracy {search.score(X_test, y_test):.3f}")
Output
n_components=1   cross-validated accuracy 0.920
n_components=2   cross-validated accuracy 0.960
n_components=3   cross-validated accuracy 0.965
n_components=5   cross-validated accuracy 0.977
n_components=10  cross-validated accuracy 0.982
n_components=30  cross-validated accuracy 0.972
best: {'pca__n_components': 10} -> test accuracy 0.965

A single component already separates malignant from benign tumours 92% of the time, and 10 components do best (0.982). Keeping all 30, which is no reduction at all, scores slightly lower. The test set, untouched until the end, gives an honest 0.965. Had PCA been fitted on all 569 tumours before splitting, the test rows would have helped choose the components: a small leak, but enough to make the test score less trustworthy.

The SVD behind PCA

scikit-learn computes PCA with the singular value decomposition (SVD) of the centred data, which the SVD lesson in Linear Algebra explains. A few lines of NumPy reproduce it:

Try it yourselfPython
import numpy as np
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

X = StandardScaler().fit_transform(load_wine().data)
pca = PCA(n_components=2).fit(X)

X_centred = X - X.mean(axis=0)                            # 1. centre each column
U, S, Vt = np.linalg.svd(X_centred, full_matrices=False)  # 2. X_centred = U x diag(S) x Vt
shares = S ** 2 / np.sum(S ** 2)                          # 3. variance shares from singular values
print("variance shares from the SVD:", np.round(shares[:2], 3))
print("explained_variance_ratio_:   ", np.round(pca.explained_variance_ratio_, 3))
print("same directions, up to sign: ", np.allclose(np.abs(Vt[:2]), np.abs(pca.components_)))
scores = X_centred @ Vt[:2].T                             # 4. project onto the top 2 directions
print("same coordinates, up to sign:", np.allclose(np.abs(scores), np.abs(pca.transform(X))))
Output
variance shares from the SVD: [0.362 0.192]
explained_variance_ratio_:    [0.362 0.192]
same directions, up to sign:  True
same coordinates, up to sign: True

The rows of Vt are the principal components, the squared singular values give the explained variance ratios, and projecting the centred data onto the top rows gives exactly what transform returns. The checks compare absolute values because the SVD, like PCA, may return any direction flipped.

Common mistakes

Practice

Practice exercise

Choose the number of components that keeps 95% of the variance of the wine data, then measure how much is lost by rebuilding the data from them. Compare your error with the share of variance you dropped: what do you notice?

Your solutionPython
import numpy as np
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

X = StandardScaler().fit_transform(load_wine().data)   # 178 wines, 13 standardised features

# 1. Fit PCA() with all components. Find the smallest number of components k
#    whose cumulative explained variance ratio reaches at least 0.95.
# 2. Fit PCA(n_components=k), rebuild X with transform and then inverse_transform,
#    and work out the reconstruction error: the mean of the squared differences.
# Print exactly two lines, like:
# components for 95%: 3
# reconstruction error: 0.123
Knowledge check

PCA on raw wine measurements says PC1 explains 99.8% of the variance, and PC1 is almost entirely one feature. What is the most likely explanation?

Summary

  • PCA finds perpendicular directions of greatest variance. Each component is a weighted mix of the original features, and its sign is arbitrary.
  • Standardise first, unless every feature shares one unit; otherwise the feature with the biggest numbers takes over.
  • explained_variance_ratio_ and its running total show what each choice of k keeps; PCA(n_components=0.95) picks k for 95% automatically.
  • inverse_transform rebuilds the data from k components, and the reconstruction error measures what was lost, which is useful for denoising and spotting unusual rows.
  • Put PCA in a pipeline after the scaler, fitted on training data only, and tune n_components like any hyperparameter. Underneath, it is the SVD of the centred data.

Next: t-SNE and UMAP.

Finished reading? Tick it off to track your progress.