PCA in Machine Learning: Meaning, Working, Formulas, and Examples

By Rahul Singh

Updated on Nov 26, 2026

Share:

Quick Overview:

  • PCA in machine learning is an unsupervised approach for dimensionality reduction in which features are converted into a smaller set of uncorrelated principal components without losing maximum variability.

  • It involves the use of data standardization, covariance matrices, eigenvalue decomposition, and data projection for dimensionality reduction.

  • The main variants of the PCA technique are Standard, Incremental, Kernel, Sparse, Randomized and Probabilistic PCA.

  • It gets rid of feature redundancy, makes the learning process fast, and keeps overfitting at bay, but at the sacrifice of poor interpretability, being sensitive to outliers, and possible information loss as some drawbacks.

  • In this blog you will learn what PCA is, how it works, mathematical formulas, numerical examples, Python code using Scikit-learn, different types, advantages, and limitations.

Understanding techniques like PCA builds a foundation in linear algebra and data processing, which are also relevant to quantum machine learning. Explore the Quantum Computing & AI Course Online – Executive Post Graduate Certificate from IIT Kharagpur to learn how quantum computing and AI work together to solve complex computational problems.

What Is PCA in Machine Learning?

PCA in machine learning is the method used to decrease the number of features in the data set while retaining the most information from the data set. Unlike feature selection, which retains selected original features, PCA creates new features by combining existing ones into principal components.

  • The first component points in the direction where the data varies the most. 

  • The second captures the most remaining variation at a right angle to the first, and so on. 

Keep the first few components, drop the rest, and you've compressed the data with little loss.

If you're wondering about the PCA full form in machine learning, it stands for Principal Component Analysis. It was introduced by Karl Pearson in 1901 and later developed by Harold Hotelling, long before machine learning became a field of its own.

So what is PCA in machine learning used for in practice? Mostly four things: shrinking datasets so models train faster, removing redundancy between correlated features, filtering out noise, and projecting high-dimensional data down to two or three dimensions so a person can plot it. 

PCA in Machine Learning Diagram

The picture below shows the idea on the small dataset used later in this blog. Each blue dot is a data point described by two features. 

  • The red arrow, PC1, runs along the direction where the points are most spread out. 

  • The green arrow, PC2, is perpendicular to it and captures what little spread is left. 

  • The orange dots show each point projected onto PC1, which is what you'd keep if you reduced the data from two dimensions to one.

Principal Component Analysis (PCA) diagram showing original data points, their projections onto PC1, and the data mean, with PC1 capturing 96.3% of the variance and PC2 capturing 3.7%.

Mathematical Concepts Behind Principal Component Analysis

There is little mathematics behind PCA in machine learning compared to what it seems. It only depends on some few concepts from statistics and linear algebra. Here are the math concepts behind PCA in machine learning:

Concept

Meaning

Purpose in PCA

Variance

How much the data of one variable is spread out

Information that is captured and maximized in PCA

Covariance

Correlation of two variables with one another

It shows us which of our features are redundant

Covariance matrix

Matrix of all variances and covariances

This is the matrix that PCA studies

Eigenvector

Vector that can be stretched by a matrix but not rotated

It gives us the direction of our components

Eigenvalue

How much eigenvector is stretched

Equivalent to the variance of the component

Standardization

Making the mean of each feature equal zero and SD=1

Avoids large-scale features dominating the others

Projection

Projecting each point on a vector

Gives us our new reduced dataset

The key formulas are short. Start with the centered data matrix X, where each column has had its mean subtracted. The covariance matrix is:

C = (1 / (n - 1)) * Xᵀ X

PCA then solves the eigenvalue equation for C:

C v = λ v

Here v is an eigenvector, which is a principal component direction, and λ is its eigenvalue, which is the variance along that direction. The reduced data is the projection of X onto the top k eigenvectors:

Z = X W

where W holds those k eigenvectors as columns. The share of variance a component explains is its eigenvalue divided by the sum of all eigenvalues.

Now after understanding the basics, let’s explore how the PCA algorithm works.

How Does the PCA Algorithm Work?

The PCA algorithm in machine learning follows the same sequence every time, whether the data has five columns or five thousand.

  1. Standardize the data. Center each feature at zero and, when the features use different units, scale them to unit variance.

  2. Compute the covariance matrix. This captures how every pair of features varies together.

  3. Find the eigenvectors and eigenvalues. These give the directions of the components and the variance along each.

  4. Sort the components. Order the eigenvectors from the largest eigenvalue to the smallest.

  5. Choose how many components to keep. Pick k based on how much variance you want to retain.

  6. Project the data. Multiply the data by the top k eigenvectors to get the new, smaller dataset.

Library implementations usually skip steps 2 and 3 and compute the same result with a singular value decomposition of the centered data, which is faster and more numerically stable. The answer is equivalent.

Choosing the Number of Components

The most common method is to look at the explained variance ratio and keep enough components to reach a target, often 95% of the total. Another is a scree plot, which graphs each component's eigenvalue in order and shows where the curve flattens into an elbow. When the goal is visualization, you simply keep two or three. When PCA feeds a model, treat k as a setting to tune with cross-validation, the same way you'd tune any other hyperparameter tuning.

Why Scaling Matters

PCA chases variance, and variance depends on units. If one feature is measured in dollars and another in fractions, the dollar column will dominate the first component purely because its numbers are bigger. 

Standardizing first puts every feature on equal footing. The exception is data where all features already share the same units and the differences in scale are meaningful, such as pixel intensities.

PCA in Machine Learning With a Numerical Example

The best way to see what the PCA algorithm in machine learning does is to run it on a dataset small enough to follow.

This PCA in machine learning numerical example uses ten points, so every step can be checked with a calculator. Here are ten points with two features each.

Point

Feature 1 (x)

Feature 2 (y)

Centered x

Centered y

PC1 Score

1

2.5

2.4

0.69

0.49

0.83

2

0.5

0.7

-1.31

-1.21

-1.78

3

2.2

2.9

0.39

0.99

0.99

4

1.9

2.2

0.09

0.29

0.27

5

3.1

3.0

1.29

1.09

1.68

6

2.3

2.7

0.49

0.79

0.91

7

2.0

1.6

0.19

-0.31

-0.10

8

1.0

1.1

-0.81

-0.81

-1.14

9

1.5

1.6

-0.31

-0.31

-0.44

10

1.1

0.9

-0.71

-1.01

-1.22

Step 1: Center the Data

The mean of feature 1 is 1.81 and the mean of feature 2 is 1.91. Subtracting each mean from its column gives the centered values in the table. (Both features are in similar units here, so we skip scaling to keep the arithmetic simple.)

Step 2: Compute the Covariance Matrix

Using the sample formula, the variance of feature 1 is 0.6166, the variance of feature 2 is 0.7166, and their covariance is 0.6154:

C = [[0.6166, 0.6154],

     [0.6154, 0.7166]]

The large positive covariance tells us the two features rise and fall together, so there's a lot of redundancy to remove.

Step 3: Find Eigenvalues and Eigenvectors

Solving the eigenvalue equation gives two results:

Component

Eigenvalue

Eigenvector

Share of Variance

PC1

1.2840

(0.6779, 0.7352)

96.3%

PC2

0.0491

(-0.7352, 0.6779)

3.7%

The two eigenvectors are perpendicular, as they should be. PC1 points up and to the right at roughly 45 degrees, along the line the data actually follows.

Step 4: Project the Data

To get the PC1 score for a point, multiply its centered values by the PC1 eigenvector. For point 1, that's 0.69 x 0.6779 + 0.49 x 0.7352, which is about 0.83. The last column of the table shows the result for all ten points. Those ten numbers replace the original twenty, and they keep 96.3% of the variance.

Step 5: Check What Was Lost

Mapping the scores back to the original two dimensions and measuring the average squared distance to the true points gives an error of about 0.044, which is tiny next to the data's spread. In other words, a one-dimensional description describes this dataset almost as well as the two-dimensional one. 

The signs of eigenvectors are arbitrary, so a library may return the same components flipped, and that's normal.

Performing PCA in Python Using Scikit-learn

Scikit-learn makes PCA in machine learning Python work a few lines of code. The code below does three things. It reduces the four-feature Iris dataset to two components, it finds how many components keep 95% of the variance in the 64-pixel Digits dataset, and it checks whether that compression hurts a classifier.

PCA in Machine Learning Python Code

from sklearn.datasets import load_iris, load_digits

from sklearn.decomposition import PCA

from sklearn.preprocessing import StandardScaler

from sklearn.pipeline import make_pipeline

from sklearn.linear_model import LogisticRegression

from sklearn.model_selection import train_test_split

# Iris: 4 features -> 2 components

X, y = load_iris(return_X_y=True)

X_scaled = StandardScaler().fit_transform(X)

pca = PCA(n_components=2)

X_2d = pca.fit_transform(X_scaled)

print("Shape:", X.shape, "->", X_2d.shape)

print("Explained variance ratio:", pca.explained_variance_ratio_.round(3))

print("Total kept:", round(pca.explained_variance_ratio_.sum(), 3))

# Digits: keep enough components for 95% of the variance

Xd, yd = load_digits(return_X_y=True)

pca95 = make_pipeline(StandardScaler(), PCA(n_components=0.95))

Xd_red = pca95.fit_transform(Xd)

print("Digits:", Xd.shape[1], "features ->", Xd_red.shape[1], "components")

# Does it hurt a classifier?

Xtr, Xte, ytr, yte = train_test_split(Xd, yd, test_size=0.3, random_state=0)

full = make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000)).fit(Xtr, ytr)

red = make_pipeline(StandardScaler(), PCA(n_components=0.95), LogisticRegression(max_iter=2000)).fit(Xtr, ytr)

print("Accuracy, all features:", round(full.score(Xte, yte), 3))

print("Accuracy, PCA 95%:", round(red.score(Xte, yte), 3))

When run, it prints the following:

Shape: (150, 4) -> (150, 2)

Explained variance ratio: [0.73  0.229]

Total kept: 0.958

Digits: 64 features -> 40 components

Accuracy, all features: 0.961

Accuracy, PCA 95%: 0.963

It also checks whether dimensionality reduction affects the accuracy of a logistic regression classifier.

Different Types of PCA in Machine Learning

Standard PCA isn't always the right fit, so several variants of PCA in machine learning exist. Each one trades a little simplicity for speed, flexibility, or robustness.

Type

Key Idea

Best For

Standard (linear) PCA

Finds linear directions of maximum variance using the full data

Medium-sized datasets with roughly linear structure

Incremental PCA

Processes data in small batches instead of all at once

Datasets too large for memory or streaming data

Kernel PCA

Applies a kernel to capture curved, nonlinear structure

Data that a straight line can't describe well

Sparse PCA

Forces each component to use only a few original features

When you need components that are easy to interpret

Randomized PCA

Uses a fast approximate decomposition

Large datasets where only a few components are needed

Probabilistic PCA

Treats PCA as a statistical model with noise

Data with missing values or when uncertainty matters

Robust PCA

Separates the data into a low-rank part and sparse outliers

Data with gross errors or corrupted entries

Truncated SVD

Same math as PCA but without centering the data

Sparse data such as text matrices

Most projects never need more than the first three rows, and it's fine to start simple and move on only when you hit a specific problem. The rest solve specific problems, such as data that doesn't fit in memory or relationships that aren't straight lines. 

It also helps to know that several of these types are not interchangeable with the PCA algorithm in machine learning. Kernel PCA, for example, returns coordinates in an implicit feature space, so you can't read component weights off it the way you can with standard PCA.

Advantages and Limitations of PCA in Machine Learning

The PCA algorithm in machine learning can help machine learning algorithms process high-dimensional data by reducing the number of input features, although the algorithm faces some drawbacks that have to be taken into account before its usage.

Here are the pros and cons of PCA:

Advantages

Limitations

Cuts the number of features, which speeds up training and lowers memory use

Components are blends of original features, so they're hard to explain to non-technical readers

Removes redundancy between correlated features

Captures only linear relationships in its standard form

Helps reduce overfitting on high-dimensional data

High variance isn't the same as usefulness, so it can discard a small but predictive signal

Filters out low-variance noise

Sensitive to feature scaling, so data must be standardized first

Makes high-dimensional data easy to plot in 2D or 3D

Sensitive to outliers, which can pull components off course

Needs no labels, so it works on unlabeled data

Doesn't handle categorical features or missing values directly

Fast, well understood, and available in every major library

Assumes the directions of largest variance are the ones that matter

Components are uncorrelated, which suits models that dislike correlated inputs

Reduces interpretability, since the original feature meanings are lost

Conclusion

In some cases, the PCA algorithm in machine learning can be useful for reducing dimensionality, removing redundant features, and improving model performance. If you decide to make use of PCA, remember to compare model performance before and after the technique is ‍‍‍applied.


Rahul Singh

Rahul Singh

38+ of articles published


Current role in the industry :

Associate - Content Marketing

Education Qualification :

B.Tech in Computer Science & Engineering

Expertise :

Artificial intelligenceMachine Learning (ML)Data ScienceFull-Stack DevelopmentData Structures & Algorithms

Tools & Technologies :

PythonReact.js & Next.jsJavaScript (ES6+)SQLTailwind CSSNode.js & MongoDBGit & GitHubSEO Tools (SEMRush)Google Search ConsoleTableau / Power BIFigma

About

Rahul Singh is an Associate Content Writer, with a strong interest in Generative AI, Agentic AI and AI-Native Software Engineering. He combines technical development skills with data-driven strategies to build scalable applications and optimize digital content. Rahul specializes in simplifying complex concepts across AI, ML and software development into practical, easy-to-understand insights, helping learners understand how AI products, systems and services are built and applied. He focuses on real world applications and explains advanced topics in a clear, step by step manner so you can follow along without confusion. His work connects theory with hands-on examples, covering AI-assisted development, intelligent automation and AI integration in software applications. He aims to help you learn faster, create better projects, and apply your knowledge confidently in real scenarios.

Follow me on :

No blogs published yet.

Frequently Asked Questions

FAQ

Ready to Take the Next Step? Enroll Today!