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.
Standardize the data. Center each feature at zero and, when the features use different units, scale them to unit variance.
Compute the covariance matrix. This captures how every pair of features varies together.
Find the eigenvectors and eigenvalues. These give the directions of the components and the variance along each.
Sort the components. Order the eigenvectors from the largest eigenvalue to the smallest.
Choose how many components to keep. Pick k based on how much variance you want to retain.
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.