Reading history

Principal Component Analysis (PCA) in Python

5 min read 2 views

Learn PCA in Python with scikit-learn: principal components, explained variance, reducing data to 2D, choosing components and PCA in pipelines.

Real datasets often have dozens or hundreds of features, many of them carrying overlapping information. Principal component analysis (PCA) finds new axes, called principal components, that point in the directions where the data varies most. Keeping only the first few components compresses the data while preserving most of its structure. That makes models faster, removes noise, and lets you plot high-dimensional data in two dimensions.

In this lesson you will learn

  • What principal components are
  • Explained variance and how to choose the number of components
  • Reducing data to 2D for visualisation
  • Using PCA inside a pipeline before a classifier
  • The limits of PCA

You should know feature scaling and cross-validation.

Explained Variance

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

X, y = load_wine(return_X_y=True)
X_scaled = StandardScaler().fit_transform(X)       # PCA needs scaled features

pca = PCA().fit(X_scaled)
ratios = pca.explained_variance_ratio_
print("Variance explained by each component:")
print(np.round(ratios, 3))
print("Cumulative:", np.round(np.cumsum(ratios), 3)[:6], "...")

X_2d = PCA(n_components=2).fit_transform(X_scaled)
print("\nOriginal shape:", X.shape, "-> reduced shape:", X_2d.shape)
for cls in range(3):
    centre = X_2d[y == cls].mean(axis=0)
    print(f"class {cls} centre in PCA space: ({centre[0]:5.2f}, {centre[1]:5.2f})")

Output

Variance explained by each component:
[0.362 0.192 0.111 0.071 0.066 0.049 0.042 0.027 0.022 0.019 0.017 0.013
 0.008]
Cumulative: [0.362 0.554 0.665 0.736 0.802 0.851] ...

Original shape: (178, 13) -> reduced shape: (178, 2)
class 0 centre in PCA space: ( 2.28,  0.97)
class 1 centre in PCA space: (-0.04, -1.64)
class 2 centre in PCA space: (-2.75,  1.24)
  • Features are standardised first. PCA looks for directions of large variance, so without scaling, the feature with the biggest numbers would dominate the first component.
  • The first component captures 36.2% of the total variation in the 13 wine features, the second 19.2%, and so on. Each component is a weighted mix of all the original features, and every component is at right angles to (uncorrelated with) the others.
  • Two components together keep 55.4% of the information, five keep about 80%.
  • In the 2D space, the three classes have clearly different centres, so a plot of the two components would already show three separate groups.

PCA Before a Classifier

from sklearn.datasets import load_digits
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
from sklearn.preprocessing import StandardScaler

X, y = load_digits(return_X_y=True)                 # 8x8 images = 64 pixel features
print("Digits data:", X.shape)

pca = PCA(n_components=0.95).fit(StandardScaler().fit_transform(X))
print("Components needed for 95% of the variance:", pca.n_components_)

for k in [64, 30, 10, 5]:
    steps = [StandardScaler()]
    if k < 64:
        steps.append(PCA(n_components=k))
    steps.append(LogisticRegression(max_iter=2000))
    score = cross_val_score(make_pipeline(*steps), X, y, cv=5).mean()
    print(f"{k:2d} features -> accuracy {score:.3f}")

Output

Digits data: (1797, 64)
Components needed for 95% of the variance: 40
64 features -> accuracy 0.920
30 features -> accuracy 0.907
10 features -> accuracy 0.840
 5 features -> accuracy 0.771
  • Each handwritten digit is an 8×8 image, 64 pixel features. Passing a fraction such as n_components=0.95 asks PCA to keep just enough components for 95% of the variance: 40 here.
  • With 30 components the classifier loses only 1.3 percentage points of accuracy while using less than half the features. Going down to 5 components loses much more.
  • Putting StandardScaler, PCA and the model in one pipeline means PCA is refitted inside each cross-validation fold, avoiding data leakage (see pipelines).

When to Use PCA

Good fitPoor fit
Many correlated numeric featuresFew, already independent features
Visualising high-dimensional dataWhen each original feature must stay interpretable
Speeding up slow models such as SVMs or KNNCategorical data
Removing noise from images or signalsPatterns that are curved rather than linear (try t-SNE or UMAP for plots)

Common Mistakes

  1. Forgetting to scale before PCA.
  2. Fitting PCA on the full dataset before splitting, which leaks test information. Fit it on training data only, ideally in a pipeline.
  3. Assuming the top components are the most useful for prediction; PCA ignores the target, so a low-variance direction can still be important.
  4. Trying to explain a component as a single feature; inspect pca.components_ to see the weights of the original features.

Practice Exercises

Exercise 1. Find which original wine feature has the largest weight in the first principal component.

Show answer
import numpy as np
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

data = load_wine()
pca = PCA(n_components=1).fit(StandardScaler().fit_transform(data.data))
weights = pca.components_[0]
print(data.feature_names[np.argmax(np.abs(weights))])

Exercise 2. A dataset has 100 features, and the first 10 components explain 90% of the variance. How many numbers per row are stored after keeping 10 components?

Show answer

10 numbers per row instead of 100, a 90% reduction, while keeping 90% of the variance.

Frequently Asked Questions

Can I get the original data back from PCA?

Approximately. pca.inverse_transform(X_reduced) rebuilds the data from the kept components; the part carried by dropped components is lost. With all components kept, the reconstruction is exact.

Is PCA a supervised or unsupervised method?

Unsupervised. It uses only the features, never the labels. Linear Discriminant Analysis (LDA) is a related supervised method that looks for directions separating the classes.

Summary

  • PCA rotates data onto uncorrelated axes ordered by variance.
  • explained_variance_ratio_ shows how much each component keeps.
  • Scale first, and fit PCA inside a pipeline.
  • Use it to compress, denoise, speed up models and visualise data.

Next: Hyperparameter Tuning with Grid Search.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *