Machine Learning • Machine Learning Algorithms • 18 min read

Dimensionality Reduction and Principal Component Analysis

Start with a simple picture

Imagine recording 20 measurements for every plant in a greenhouse: height, leaf length, leaf width, stem thickness, and many others. Several measurements may describe nearly the same underlying pattern. Plotting all 20 numbers is impossible on an ordinary two-dimensional graph, and some models become harder to train when features are redundant.

Dimensionality reduction asks whether we can describe much of the useful structure with fewer numbers. Principal Component Analysis (PCA) provides one answer: it finds new axes along which the observations vary most, then expresses each observation using its coordinates on those axes.

For example, if plant height and stem thickness tend to increase together, PCA might identify a first direction representing overall plant size. A second direction could describe differences in proportions. These directions are mathematical combinations of the original measurements, not necessarily meaningful biological labels.

The crucial caution is that large variation is not the same as predictive usefulness. A subtle feature with little variance might still be essential for identifying disease. PCA does not know the target label when it chooses its directions.

In the sections that follow, first learn how a dataset becomes points in a feature space, then how PCA chooses and uses directions, and finally how to evaluate whether reducing dimensions helps the actual task.

Dimensionality reduction transforms a dataset into a representation with fewer features while attempting to preserve information relevant to a task. Principal Component Analysis (PCA) is a widely used linear dimensionality-reduction technique that finds mutually perpendicular directions of maximum variance and projects data onto selected directions.

Reducing the number of features can make data easier to visualize, compress, and model. But fewer dimensions do not automatically mean better predictions: the appropriate representation depends on the problem, the data, and what information must be retained.

1. What is dimensionality?

A feature is a measurable input variable describing an observation. A dataset with nn observations and dd features can be written as a matrix:

X∈Rn×d.X\in\mathbb{R}^{n\times d}.

Each row is an observation, and each column is a feature. The number dd is the feature dimension. For example, a dataset describing 1,000 devices with 20 sensor readings per device has shape 1000×201000\times20 and 20 features.

A high-dimensional dataset has many features relative to its intended analysis, available observations, or computational resources. There is no universal feature count beyond which data becomes high-dimensional. Twenty features may be challenging for a very small dataset, whereas thousands may be manageable for other systems.

High-dimensional data is common in AI:

  • An image may be represented by thousands or millions of pixel values.
  • A document may be represented by a high-dimensional vector of term frequencies or embeddings.
  • A medical dataset may contain measurements from many instruments.
  • A machine-learning pipeline may generate many features through encoding or feature engineering.

2. Why reduce dimensions?

Dimensionality reduction has several distinct purposes.

GoalHow fewer dimensions may helpImportant qualification
VisualizationPlot a dataset in two or three dimensionsA plot is only a simplified view of the original data
CompressionStore a smaller representationInformation may be lost
Noise reductionDiscard directions that mainly contain noiseLow-variance directions can also contain useful signals
Faster computationReduce the size of later calculationsFitting the transformation itself has a cost
GeneralizationSometimes reduce overfitting from irrelevant or redundant inputsPerformance improvements are not guaranteed
Discovering structureExpose dominant directions of variationLarge variance does not necessarily indicate the most important task-related variation

The curse of dimensionality

The curse of dimensionality is a group of difficulties that arise as the number of dimensions grows. For example, the amount of space increases rapidly with dimension, and observations may become sparse relative to the space in which they are represented. Neighborhood and distance-based methods can consequently become harder to use effectively.

This does not mean every high-dimensional dataset is unusable. It means that feature representations, data quantity, distance measures, and assumptions become increasingly important. PCA is one possible response, not a universal solution.

3. Two broad ways to reduce dimensions

Feature selection

Feature selection keeps a subset of the original features. For example, a model might use only temperature, vibration, and current from 20 available sensor measurements.

The resulting features retain their original meanings. Selection can be based on domain knowledge, statistical criteria, or model-based procedures. When labels are used to choose features, the selection is a supervised step and must be performed within the training process.

Feature extraction

Feature extraction constructs new features from the original ones. A new feature may combine measurements that previously appeared in separate columns.

PCA belongs to feature extraction: its output dimensions are new linear combinations of the original variables. They are called principal components.

QuestionFeature selectionFeature extraction with PCA
Are the original feature names preserved?Yes, for the selected columnsUsually no; components combine original features
Can information from multiple features be combined?Not inherentlyYes
Is the method necessarily supervised?NoStandard PCA is unsupervised
Is the output easy to interpret?Often easierSometimes difficult

4. The central idea of PCA

Imagine measuring the height and arm span of many people. The two variables may be strongly correlated: people with greater height often have greater arm span. A scatter plot of the measurements might form a stretched cloud of points.

Rather than describing the cloud only through the original horizontal and vertical axes, PCA identifies a new axis pointing along the cloud’s greatest variation. That is the first principal component. It then finds a perpendicular direction with the greatest remaining variation. In two dimensions, that is the second principal component.

A two-dimensional point cloud elongated along its first principal component; a shorter perpendicular second component indicates less variation.
PCA rotates the coordinate system toward directions that explain variation in the observed data. Reducing to one dimension keeps coordinates along PC1 and discards the PC2 coordinate.

When PCA reduces a two-dimensional dataset to one dimension, it keeps each observation’s coordinate along the first component and removes the second coordinate. Some information is lost, but the largest possible variance among all one-dimensional linear projections is retained.

5. What exactly is a principal component?

A principal component direction is a unit vector in the original feature space. A principal component score is an observation’s coordinate along that direction, after centering.

These terms are related but not identical:

  • Principal direction: the axis used to measure variation.
  • Component score: a data point’s projected value on that axis.
  • Loading: an expression often used for how original variables contribute to components; its exact convention can vary across texts and software.

For dd original features, PCA can find at most min⁡(n−1,d)\min(n-1,d) directions with nonzero sample variance in a centered dataset of nn observations. The directions are orthogonal, meaning the dot product between two distinct principal directions is zero.

The first component captures the largest variance possible among unit-length linear directions. The second captures the largest remaining variance subject to being orthogonal to the first, and so on.

A key limitation follows: PCA searches for variance, not for predictive usefulness, causality, or class separation.

6. How PCA works step by step

Suppose a centered dataset has nn observations and dd features. We want to retain kk components, where k<dk<d.

Step 1: Prepare the input features

Choose relevant numerical features, deal with invalid or missing values, and decide whether scaling is appropriate. PCA does not directly accept arbitrary strings or missing values in a typical scikit-learn implementation.

If one feature is measured in thousands and another in fractions, the first may dominate the variance-based calculation. Standardization is commonly used to make each feature have comparable scale, but it changes what PCA considers important. Do not standardize automatically when original units or magnitudes should matter.

Step 2: Center the features

Subtract the training mean of each column:

Xc=X−1μT,X_c = X-\mathbf{1}\boldsymbol{\mu}^{T},

where μ\boldsymbol{\mu} contains feature means and 1\mathbf{1} is a column of ones. The centered data has zero mean in each feature, subject to floating-point rounding.

Step 3: Find directions of maximum variance

For n>1n>1, the sample covariance matrix of centered data is

S=1n−1XcTXc.S=\frac{1}{n-1}X_c^{T}X_c.

An eigenvector of SS gives a principal direction, and its corresponding eigenvalue gives the variance along that direction. The eigenvalues are ordered from largest to smallest.

In practice, implementations often compute PCA using Singular Value Decomposition (SVD) rather than explicitly building and eigendecomposing the covariance matrix. SVD can have useful numerical properties.

Step 4: Keep the first kk directions

Let the selected orthonormal directions form a matrix

Wk∈Rd×k.W_k\in\mathbb{R}^{d\times k}.

Project the centered data into the lower-dimensional space:

Z=XcWk,Z=X_cW_k,

where Z∈Rn×kZ\in\mathbb{R}^{n\times k} contains the component scores.

Step 5: Optionally reconstruct an approximation

An approximate reconstruction in the original feature space is

X^=ZWkT+1μT.\widehat X=ZW_k^{T}+\mathbf{1}\boldsymbol{\mu}^{T}.

If kk is smaller than the number of nonzero-variance components, the reconstruction generally differs from the original. Discarded components account for the information lost under PCA’s squared-error criterion.

PCA workflow showing input features, centering and optional scaling, component fitting on training data, projection to fewer dimensions, and downstream modeling.
The fitted PCA transformation maps the same original feature space into a smaller coordinate system for subsequent data.

7. A small numerical example

Consider three two-dimensional observations:

X=[112233].X=\begin{bmatrix}1&1\\2&2\\3&3\end{bmatrix}.

Their feature means are (2,2)(2,2), so the centered matrix is

Xc=[−1−10011].X_c=\begin{bmatrix}-1&-1\\0&0\\1&1\end{bmatrix}.

The sample covariance matrix is

S=[1111].S=\begin{bmatrix}1&1\\1&1\end{bmatrix}.

Its largest eigenvalue is 22, with a corresponding unit eigenvector

w1=12[11].\mathbf{w}_1=\frac{1}{\sqrt{2}}\begin{bmatrix}1\\1\end{bmatrix}.

The second eigenvalue is 00. This tells us all observed variation lies along a single straight line. Projecting onto the first component produces

Z=[−202].Z=\begin{bmatrix}-\sqrt{2}\\0\\\sqrt{2}\end{bmatrix}.

We reduced two original features to one without losing any variance in this particular dataset. Real datasets are rarely this perfectly redundant.

Note: The sign of a principal direction is arbitrary. Replacing w1\mathbf{w}_1 with −w1-\mathbf{w}_1 reverses the signs of its scores but describes the same one-dimensional subspace.

8. Explained variance and choosing the number of components

PCA reports how much dataset variance is associated with each component. If the covariance eigenvalues are λ1≥λ2≥⋯≥λd≥0\lambda_1\geq\lambda_2\geq\cdots\geq\lambda_d\geq0, the explained variance ratio of component jj is

rj=λj∑i=1dλi,r_j=\frac{\lambda_j}{\sum_{i=1}^{d}\lambda_i},

provided total variance is nonzero.

The cumulative explained variance ratio after retaining kk components is

Rk=∑j=1krj.R_k=\sum_{j=1}^{k}r_j.

For illustration, suppose a dataset produces these ratios:

ComponentExplained varianceCumulative variance
PC155%55%
PC225%80%
PC312%92%
PC48%100%

Keeping the first three components retains 92% of the variance under the particular preprocessing and dataset used. This does not mean 92% predictive accuracy or that 92% of every possible kind of information survives.

Ways to select kk include:

  1. Set a target for cumulative explained variance, such as 90% or 95%, when appropriate for the application.
  2. Inspect an explained-variance or scree plot for diminishing returns.
  3. For visualization, choose two or three components and explain the information lost.
  4. For a supervised downstream model, select the component count using validation or cross-validation rather than the test set.
  5. Measure task-specific results, including accuracy or error, runtime, memory use, and relevant safety constraints.

A fixed variance threshold is a useful engineering heuristic, not a universal rule.

9. Implementing PCA with scikit-learn

The following example demonstrates dimensionality reduction on an existing labeled dataset. The class labels are used only to evaluate a downstream classifier; PCA itself does not use them.

import numpy as np
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_wine(return_X_y=True)

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.25,
    random_state=42,
    stratify=y,
)

# Both scaling and PCA are fitted using training data only.
model = make_pipeline(
    StandardScaler(),
    PCA(n_components=0.95, svd_solver="full"),
    LogisticRegression(max_iter=2000),
)

model.fit(X_train, y_train)
predictions = model.predict(X_test)

pca = model.named_steps["pca"]
print("Original feature count:", X.shape[1])
print("Retained components:", pca.n_components_)
print("Retained variance ratio:", round(
    np.sum(pca.explained_variance_ratio_), 4
))
print("Test accuracy:", round(accuracy_score(y_test, predictions), 4))

PCA(n_components=0.95, svd_solver="full") retains enough components to reach at least 95% explained variance on the training data, subject to the estimator’s documented behavior. It does not guarantee a corresponding percentage of downstream model accuracy.

The Pipeline is important: when it is fitted, the scaler and PCA learn their parameters from the training split. When it predicts on the test split, it applies those fitted transformations without recomputing them from the test data.

Compare against a baseline

To determine whether PCA helped, compare its downstream results to a similar model without PCA:

baseline = make_pipeline(
    StandardScaler(),
    LogisticRegression(max_iter=2000),
)

baseline.fit(X_train, y_train)
baseline_predictions = baseline.predict(X_test)

print("PCA pipeline accuracy:", accuracy_score(y_test, predictions))
print("Baseline accuracy:", accuracy_score(y_test, baseline_predictions))

If the PCA pipeline performs worse, this is not necessarily an implementation error. Discarded low-variance directions may have contained information useful for predicting the labels. For serious model selection, compare candidate pipelines using cross-validation on the training data and reserve the test split for the final assessment.

10. Understanding PCA outputs in Python

After fitting a scikit-learn PCA estimator, commonly used attributes include:

AttributeWhat it represents
components_Principal direction vectors, as rows of a matrix
explained_variance_Variance accounted for by each retained component
explained_variance_ratio_Fraction of total training-data variance explained by each retained component
singular_values_Singular values associated with retained components
mean_Feature means learned by the PCA estimator from its input
n_components_Number of components actually retained

If PCA follows StandardScaler, its mean_ concerns the scaled input it receives, not the means of the original raw columns. The scaler separately stores parameters learned from the original training features.

You can inspect a fitted pipeline like this:

print("Component matrix shape:", pca.components_.shape)
print("Variance by component:", pca.explained_variance_ratio_)

A large absolute component coefficient indicates a strong contribution from a given standardized input direction, but interpreting components as real-world causal factors is not justified by PCA alone.

11. PCA versus other reduction methods

Not all dimensionality-reduction methods optimize the same objective.

MethodBasic ideaTypical use or caution
PCALinear projection that preserves maximum varianceGeneral compression, preprocessing, exploratory analysis
Truncated SVDLow-rank matrix approximation without requiring prior centeringOften useful for sparse term-document matrices
t-SNENonlinear embedding emphasizing local neighborhoodsExploratory visualization; plot distances and cluster sizes require care
UMAPNonlinear manifold-based embeddingVisualization and some embedding workflows; sensitive to settings
AutoencoderNeural network learns a compressed representation through a reconstruction objectiveCan model nonlinear structure but requires more choices and training
Feature selectionRetain original columnsUseful when interpretability and original units matter

PCA’s strengths are simplicity, relatively clear mathematics, and a reproducible linear transformation for new observations. Nonlinear embedding tools may show visually striking patterns, but an attractive two-dimensional plot is not evidence of real, well-separated categories in the original space.

12. Common limitations and failure modes

High variance is not necessarily useful signal

PCA does not know the target label in ordinary unsupervised use. A direction with modest variance may be extremely important for classifying an observation, while a high-variance direction may reflect nuisance conditions.

PCA captures linear structure

Its components are linear combinations of original features. Strongly curved or other nonlinear relationships may not be represented compactly by a few linear directions.

Outliers can distort components

The mean and covariance are sensitive to unusually extreme observations. A small number of extreme records can rotate the leading components considerably. Investigate data quality before fitting.

Interpretation can be difficult

A principal component often mixes numerous measurements. It should not be assigned a substantive name such as “health” or “intelligence” without domain evidence.

Scaling changes the result

Using standardized data and using original units can produce quite different directions. Neither is correct in every situation; the choice must reflect the meaning of the variables.

Information is discarded

Reducing to k<dk<d dimensions generally destroys some variation and can erase information valuable for future tasks. Keep original data where appropriate, and measure reconstruction or predictive performance.

Data leakage makes evaluation misleading

Fitting PCA on the entire dataset before splitting allows information about the held-out feature distribution to influence the transformation. Even though PCA does not use labels, this is a form of data leakage for a predictive evaluation. Fit transformations on the training portion only and apply them to validation and test examples.

13. Practical applications of PCA

Sensor analytics: Compress correlated measurements from machines before clustering or anomaly detection. Validate whether unusual but important sensor patterns are preserved.

Image processing: Explore low-dimensional image representations or approximate images with fewer components. PCA is a classic baseline, though more specialized modern methods are frequently preferred for complex visual tasks.

Exploratory data analysis: Plot component scores to inspect variation and potential outliers. Avoid treating visual separation as proof of distinct classes.

Preprocessing before conventional ML: Reduce redundant features before a regression or classification model. Compare the result against a non-PCA baseline on properly held-out data.

Document analysis: Related matrix factorization methods such as truncated SVD can reduce large sparse text-feature spaces. Standard centered PCA can be impractical for such sparse representations.

14. How PCA connects to the rest of machine learning

PCA connects several foundational ideas:

  1. Linear algebra: It relies on vectors, projections, covariance matrices, eigenvectors, eigenvalues, or singular value decomposition.
  2. Statistics: It uses variance and covariance to characterize the spread of observations.
  3. Data preprocessing: Scaling, missing-value treatment, and outlier handling affect the components.
  4. Unsupervised learning: Standard PCA learns structure without target labels.
  5. Clustering: PCA may help compress or visualize data before or after clustering, although projected clusters can be misleading.
  6. Model evaluation: The benefit of PCA must be measured against baseline systems on data not used to fit it.

15. Check your understanding

  1. What is the difference between choosing three existing features and computing three principal components?
  2. Does preserving 95% explained variance mean the classifier will achieve 95% accuracy?
  3. Why is centering important to the usual mathematical definition of PCA?
  4. How does standardizing features potentially change PCA’s results?
  5. What is the difference between a principal direction and a component score?
  6. Why should PCA be fitted only on training data during supervised evaluation?
  7. Why might a low-variance direction still matter for classification?
  8. When might truncated SVD be preferable to ordinary centered PCA?
Show suggested answers
  1. Feature selection keeps original variables; PCA computes new variables by projecting onto linear combinations of the original features.
  2. No. Explained variance measures retained variation in the input representation, not prediction accuracy.
  3. Centering lets the covariance-based directions describe variation around the feature means rather than offset from the origin.
  4. Scaling changes relative feature variances and therefore which directions maximize variance.
  5. A principal direction is an axis in feature space; a score is an observation’s coordinate along that axis.
  6. Fitting on held-out examples leaks their feature distribution into the model-development process and can bias evaluation.
  7. The target may depend strongly on a small but consistent difference in a low-variance direction.
  8. Truncated SVD can work directly with sparse matrices and does not require explicitly centering them first.

References and further reading

Related articles in

  • Clustering and K-Means — Learn how unsupervised clustering discovers groups in data, how K-Means optimizes cluster centroids, and how to evaluate and use its results responsibly.
  • Data, Model, and Experiment Versioning — Learn to trace ML results to exact datasets, code revisions, configurations, and artifacts.
  • Decision Trees, Random Forests, and Boosting — Learn how decision trees partition data, how random forests reduce variance through bagging, and how boosting combines sequential learners to improve predictions.

Image preview

Fit