Machine Learning · 8 of 20

Principal Component Analysis tutorial

Rotates data onto directions that preserve the most variance. Learn the concept, implement it from scratch, and apply it with scikit-learn.

Category
Unsupervised learning
Core idea
Z = X̃Wₖ
Typical use
Visualization, compression, and noise reduction.
Practical tool
scikit-learn

What is Principal Component Analysis?

Principal Component Analysis is a unsupervised learning technique. Rotates data onto directions that preserve the most variance. Its central idea is summarized by Z = X̃Wₖ.

This guide connects theory to practice. You will trace the input, intermediate process, and output; decode the notation; run a dependency-light implementation; then repeat the workflow with scikit-learn and evaluate the result.

By the end of this tutorial, you will be able to

  • Explain when Principal Component Analysis is appropriate and what assumptions it makes.
  • Read its mathematical notation or complexity statement without guessing what the symbols mean.
  • Follow and modify a from-scratch Python implementation.
  • Build a practical workflow with scikit-learn and choose useful evaluation checks.

Prerequisites and tools

You do not need an advanced software stack. Start with a recent Python environment and the fundamentals below, then install only the packages used by the practical example.

  • Comfort with Python functions, NumPy arrays, and basic descriptive statistics.
  • A clear distinction between training data, validation data, and untouched test data.
  • Familiarity with features, targets, preprocessing, and task-appropriate evaluation metrics.
LanguagePython 3
Primary libraryscikit-learn
Learning modeFrom scratch + library

How Principal Component Analysis works

  1. 1

    Input

    Correlated numeric features.

  2. 2

    Prepare and configure

    Check shapes, value ranges, ordering assumptions, missing values, and the parameters that control the algorithm’s behavior.

  3. 3

    Algorithm process

    Find covariance eigenvectors ordered by explained variance.

  4. 4

    Output

    Lower-dimensional principal-component coordinates.

  5. 5

    Validate

    Choose component count from cumulative explained variance and downstream validation performance.

Formula and intuition

Z = X̃Wₖ

X̃ is the centered data matrix; Wₖ contains the top k covariance eigenvectors, and Z is the projection.

The notation captures the main operation or complexity statement behind Principal Component Analysis. Read it together with the symbol key above and the step-by-step process in this guide.

When to use Principal Component Analysis

Visualization, compression, and noise reduction.

Learning tip

Change one parameter at a time in the interactive lesson, replay the animation, and connect the visible change to the input, process, and output described above.

Principal Component Analysis from scratch in Python

This dependency-light example emphasizes the algorithm’s mechanics so each important step remains visible.

PythonEducational implementation
import numpy as np

rng = np.random.default_rng(0)
X = rng.normal(0, 1, (200, 5))
X_centered = X - X.mean(axis=0)  # PCA requires zero-mean data

# eigenvectors of the covariance matrix point along directions of maximum variance
cov = np.cov(X_centered, rowvar=False)
eigvals, eigvecs = np.linalg.eigh(cov)
order = np.argsort(eigvals)[::-1]   # sort directions by variance explained, descending
components = eigvecs[:, order[:2]]  # keep the top 2 directions

projected = X_centered @ components  # coordinates of each point in the new, smaller space
explained_variance = eigvals[order[:2]] / eigvals.sum()
How to use this example

Run it once unchanged, inspect the output, and then alter one input or parameter. The compact implementation is designed for learning; use the tested library workflow below for real projects.

Build Principal Component Analysis with scikit-learn

PCA computes stable components and exposes explained-variance ratios for selecting a useful reduced dimension.

Recommended environment

JupyterLab, Google Colab, or VS Code

Create an isolated virtual environment for a local project, or paste the cells into a hosted notebook. Pin package versions before deploying a reproducible application.

Install the required package python -m pip install scikit-learn
  1. Prepare the data.Correlated numeric features. Validate its shape, type, range, and ordering before training or execution.
  2. Configure the algorithm.Begin with explicit, conservative parameters and a fixed random seed whenever the library supports one.
  3. Fit or execute.Find covariance eigenvectors ordered by explained variance.
  4. Inspect the result.Lower-dimensional principal-component coordinates. Then apply the evaluation checks in the next section.
Pythonscikit-learn workflow
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

X, _ = load_digits(return_X_y=True)
X_scaled = StandardScaler().fit_transform(X)
pca = PCA(n_components=0.95, svd_solver="full")
Z = pca.fit_transform(X_scaled)
print("original dimensions:", X.shape[1])
print("retained dimensions:", Z.shape[1])
print("variance retained:", pca.explained_variance_ratio_.sum())
X_reconstructed = pca.inverse_transform(Z)
print("reconstruction MSE:", ((X_scaled - X_reconstructed) ** 2).mean())

API details and version-specific options: official scikit-learn reference →

How to evaluate the result

A successful run is not enough. Evaluate the output against the intended use, compare it with a simple baseline, and preserve a genuinely unseen test case whenever the task involves learned parameters.

  • Choose component count from cumulative explained variance and downstream validation performance.
  • Check reconstruction error when dimensionality reduction is used for compression.
Reproducibility check

Record the data version, package versions, parameters, random seeds, and evaluation procedure. Re-run the same workflow before publishing a benchmark or deploying a model.

Pitfalls and how to avoid them

These failure modes are common in tutorials and production systems. Treat them as review questions, not just after-the-fact debugging advice.

  • PCA captures variance, not necessarily task-relevant information.
  • Results are sensitive to feature scale unless units are already comparable.
  • Component signs are arbitrary and do not change the represented subspace.

Before using Principal Component Analysis in a project

  • Define the prediction or discovery objective before selecting the algorithm.
  • Split data before fitting preprocessing and tune only inside cross-validation.
  • Record data versions, random seeds, features, hyperparameters, and evaluation metrics.
  • Compare against a simple baseline and inspect errors by meaningful subgroups.
  • Monitor input drift and real-world performance after deployment.

Official documentation and next steps

Primary software reference scikit-learn

Use the official documentation to confirm supported parameters, current defaults, input requirements, and version changes.

Read official documentation →

This guide is an educational introduction, not a substitute for domain validation. For consequential applications, review the source documentation, test against representative data, and involve a subject-matter expert.

See Principal Component Analysis in motion

Open the interactive lesson to adjust parameters, scrub through the process, replay the animation, and compare the explanation with the Python code.

Launch visualization →