Machine LearningDimensionality Reduction & Feature Extraction

What is Principal Component Analysis (PCA), and how does it work?

Question 277 of 303 · Updated

On this page

Principal Component Analysis (PCA) is an unsupervised linear dimensionality-reduction technique. It converts a set of possibly correlated numerical features into a smaller set of new features called principal components. The first component captures the largest possible amount of variance in the data; each later component captures as much remaining variance as possible while being orthogonal (uncorrelated in the sample) to the earlier components.

PCA is useful when a dataset contains many numerical features, especially when several carry overlapping information. It can compress data, reduce redundancy, help visualize high-dimensional observations, and sometimes improve the stability or speed of downstream models. It does not automatically select the features most predictive of a target.

1. The intuition: find the directions in which data varies most#

Imagine plotting two measurements for every customer: monthly website visits and monthly purchases. If customers with more visits generally make more purchases, the points may form an elongated cloud running diagonally across the plot.

The original axes describe visits and purchases separately. PCA finds a new axis along the long direction of the cloud. Projecting each customer onto that axis gives one combined numerical feature that preserves much of the variation in both original measurements.

A second axis is perpendicular to the first. It captures the remaining variation not represented by the first component.

Original features:  X1, X2, X3, ..., Xp
              |
       Center (and often scale)
              |
      Find maximum-variance directions
              |
      PC1, PC2, PC3, ..., PCp
              |
       Keep the first k components
              |
       Lower-dimensional dataset

A principal component is a weighted linear combination of the original features. It is not simply one of the original columns.

2. A beginner-friendly numerical example#

Suppose a dataset has two standardized measurements, X1 and X2. After centering the observations, assume their sample covariance matrix is:

LaTeX

The diagonal values (4 and 4) are the variances of the two features. The off-diagonal values (2 and 2) represent their positive covariance.

PCA finds the eigenvalues and eigenvectors of this covariance matrix.

For this example:

  • Eigenvalue 1: 6, with eigenvector approximately (0.707, 0.707).
  • Eigenvalue 2: 2, with eigenvector approximately (0.707, -0.707).

The eigenvectors define the directions of the principal components. The eigenvalues tell us how much variance lies along those directions.

The first component is therefore:

[ PC1 = 0.707X1 + 0.707X2 ]

The second component is:

[ PC2 = 0.707X1 - 0.707X2 ]

Total variance is the sum of the eigenvalues:

[ 6 + 2 = 8 ]

So the explained variance ratios are:

  • PC1: 6 / 8 = 75%
  • PC2: 2 / 8 = 25%

If we retain only PC1, we reduce two features to one while retaining 75% of the variance in this example. We have compressed the representation, but discarded the 25% captured by PC2.

Important: This is a deliberately small, illustrative covariance matrix. In a real dataset, PCA estimates the covariance or correlation structure from the training observations.

3. How PCA works step by step#

Step 1: Prepare a numerical feature matrix#

Represent the data as a matrix with rows as observations and columns as numerical features:

LaTeX

Here, n is the number of observations and p is the number of features.

PCA operates on numerical values. Categorical variables need an appropriate encoding strategy first. Missing values also need to be handled before using standard PCA implementations.

Step 2: Center each feature#

For each feature, calculate its training-set mean and subtract it from every observation:

LaTeX

Centering places each feature around zero. This is important because PCA seeks directions of variation around the mean.

Step 3: Decide whether to scale#

Centering and scaling are different operations.

  • Centering subtracts the feature mean.
  • Standardization also divides by the feature standard deviation, producing unit variance.

Suppose annual income is measured in thousands of rupees while age is measured in years. If PCA uses the covariance matrix directly, a feature with a much larger numerical variance can dominate the components.

Standardizing is often appropriate when features use different units or when each feature should contribute on a comparable scale. However, scaling is not an automatic rule: if absolute variance is meaningful and measured on comparable scales, covariance-based PCA may be preferable.

In scikit-learn, PCA centers features but does not scale them automatically. If standardization is intended, apply a scaler before PCA.

Step 4: Calculate the covariance or correlation structure#

For centered data, the sample covariance matrix is:

LaTeX

It describes the variance of each feature and how pairs of features vary together.

  • Use the covariance matrix when the original feature scales are meaningful and comparable.
  • Use the correlation matrix (equivalently, standardized features followed by covariance PCA) when scale differences should not dominate.

Step 5: Find eigenvalues and eigenvectors#

Solve:

LaTeX
  • An eigenvector gives a direction in the original feature space.
  • Its corresponding eigenvalue gives the variance captured along that direction.

Sort the eigenvalues from largest to smallest. The corresponding eigenvectors become PC1, PC2, and so on.

The first component has the greatest possible variance among all unit-length linear combinations of the features. The next has the greatest possible variance subject to being orthogonal to the first, and this continues for later components.

Step 6: Project observations onto the components#

Put the selected eigenvectors into a component matrix W. Transform the centered observations:

[ Z = X_{centered}W ]

Each column of Z is a principal-component feature. Each row is an observation represented in the new coordinate system.

If the original data has 20 features and we retain 5 components, the transformed dataset has 5 columns instead of 20.

Step 7: Choose how many components to retain#

The explained variance ratio for component i is:

LaTeX

The cumulative explained variance is the sum of these ratios up to the selected component.

For example, imagine the first four components explain 52%, 23%, 15%, and 6% of total variance:

  • First component: 52%
  • First two: 75%
  • First three: 90%
  • First four: 96%

Keeping three components retains 90% of the variance in this illustration. A threshold such as 90%, 95%, or 99% can be a starting point, not a universal law. Select the number based on the purpose of the analysis and downstream validation.

4. How do you choose the number of principal components?#

Common approaches include:

Cumulative explained variance: Choose the smallest number of components that reaches a chosen cumulative threshold. This is simple, but a high threshold can retain noise and a lower threshold can discard useful signal.

Scree plot: Plot eigenvalues or explained variance by component. Look for an elbow where additional components contribute relatively little. The elbow can be subjective.

Downstream validation: If PCA is part of a predictive pipeline, compare candidate component counts using cross-validation and the metric that matters for the task. A component count that preserves more total variance does not necessarily produce the best predictions.

Interpretability and operating constraints: Consider how many components users can understand, how much compression is needed, and the cost of losing information.

Do not choose a component count using the test set. Component selection is a model-selection decision and belongs inside the training/validation process.

5. Why are eigenvalues and eigenvectors important?#

Think of an eigenvector as an arrow pointing in a direction through the feature space. PCA uses these arrows as new axes.

The eigenvalue associated with an arrow measures how spread out the observations are when projected onto that direction.

  • Large eigenvalue: the component captures substantial variance.
  • Small eigenvalue: the component captures relatively little variance.

PCA orders components by decreasing eigenvalue. The sign of an eigenvector is arbitrary: a component and its sign-reversed version describe the same axis and explain the same variance.

In practice, numerical software commonly uses Singular Value Decomposition (SVD) to calculate PCA rather than explicitly forming and decomposing the covariance matrix. SVD is a standard and often numerically preferable computational route.

6. A practical Python example using scikit-learn#

The following example standardizes features, retains enough components to explain at least 95% of training variance, and transforms the data.

PYTHON
from sklearn.datasets import load_breast_cancer from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.pipeline import make_pipeline X, y = load_breast_cancer(return_X_y=True) # Scaling and PCA are fitted only on the data passed to fit. pca_pipeline = make_pipeline( StandardScaler(), PCA(n_components=0.95, svd_solver="full") ) X_reduced = pca_pipeline.fit_transform(X) pca = pca_pipeline.named_steps["pca"] print("Original feature count:", X.shape[1]) print("Reduced feature count:", X_reduced.shape[1]) print("Explained variance:", pca.explained_variance_ratio_) print( "Cumulative explained variance:", pca.explained_variance_ratio_.sum() )

In this example, the pipeline learns scaling parameters and PCA directions from the data supplied to fit_transform. For a real predictive evaluation, first split the data, fit the entire pipeline on the training split (or within each cross-validation fold), and call transform on validation/test data. Do not fit the scaler or PCA on the full dataset before splitting.

For classification or regression, keep the target separate. PCA is unsupervised: it does not use y to decide which directions are useful.

7. When should you use PCA?#

PCA can be useful when:

  • Many numerical features are correlated or redundant.
  • You need a compact representation of high-dimensional measurements.
  • You want to visualize data with two or three components.
  • Model training or storage is expensive because of a large feature count.
  • A downstream method benefits from less correlated input dimensions.
  • You want to explore dominant patterns or sources of variation.

Examples include compressing sensor measurements, exploring correlated financial indicators, reducing dimensions of image or gene-expression data, and visualizing customer or product datasets.

PCA is not a guaranteed performance improvement. Always compare a model using the original features with one using PCA features on the same validation strategy.

8. When can PCA be a poor choice?#

PCA may be unsuitable or require extra care when:

  • Interpretability matters: A component may combine dozens of original variables, making it harder to explain than the original features.
  • The signal is nonlinear: PCA finds linear directions. Nonlinear structure may remain hidden.
  • Low-variance features carry predictive signal: PCA can discard a direction with little overall variance even if that direction is highly informative for the target.
  • Outliers dominate: PCA is based on variance and can be strongly influenced by extreme observations.
  • Features have incompatible scales: Unscaled large-magnitude features may dominate covariance-based PCA.
  • Sparse data must remain sparse: Centering can destroy sparsity. Methods such as TruncatedSVD may be more suitable for some sparse matrices, but they are not identical to centered PCA.
  • The dataset is small relative to its feature count: Components may be unstable and generalize poorly.

PCA also does not guarantee statistically independent components. It produces orthogonal directions and uncorrelated component scores under the sample covariance representation; independence requires stronger conditions.

9. Does PCA require normally distributed data?#

No. PCA can be calculated without assuming that the original features follow a multivariate normal distribution.

However, distributional shape, outliers, sample size, and the stability of the covariance structure can affect how useful and reproducible the estimated components are. Some inferential procedures built around PCA may make additional distributional assumptions, but basic PCA as a dimensionality-reduction method does not require normality.

PCA maximizes variance, not predictive relevance. A high-variance direction may reflect measurement scale, noise, or an irrelevant source of variation.

10. PCA versus feature selection#

These are different approaches:

  • Feature selection keeps a subset of the original columns.
  • PCA creates new columns as combinations of the original features.

For example, feature selection might retain income and spending while dropping other columns. PCA might create PC1 = 0.6 × income + 0.5 × spending + 0.4 × visits.

Feature selection preserves original variable meanings. PCA can compress correlated information more effectively, but its components may be harder to interpret.

11. PCA versus standardization#

Standardization changes the scale of each original feature. PCA changes the coordinate system and can reduce the number of dimensions.

A common workflow is:

Raw numerical features
       |
StandardScaler (if appropriate)
       |
PCA
       |
Selected principal components
       |
Downstream model

Standardization alone does not reduce feature count. PCA can be applied without standardization, but the choice should reflect units and the meaning of variance.

12. Practical checklist for production ML#

  1. Identify the numerical features and decide how categorical variables and missing values will be handled.
  2. Inspect feature scales, correlations, distributions, and outliers.
  3. Decide whether covariance-based or standardized/correlation-based PCA is appropriate.
  4. Split data before fitting any learned preprocessing.
  5. Put imputation, scaling, and PCA in one training pipeline.
  6. Select component count using training-only analysis and validation or cross-validation.
  7. Compare predictive quality, runtime, memory use, and interpretability against a no-PCA baseline.
  8. Persist the fitted preprocessing and PCA objects with the model. Apply exactly the same transformation to new observations.
  9. Monitor input distributions and downstream performance. Refit components only through a controlled retraining process.
  10. Document explained variance, component loadings, feature order, scaling choices, and the component count.

If PCA is used before a supervised model, fit it separately inside each cross-validation training fold. Fitting PCA once on all observations before cross-validation leaks information about the validation folds into the learned representation, even though PCA does not use the target labels.

13. Common interview questions#

Q: What does the first principal component represent?

It is the unit direction along which the projected observations have the largest variance.

Q: Are principal components correlated?

The component scores are uncorrelated in the sample under the standard PCA construction. This does not imply statistical independence in general.

Q: Why do we standardize before PCA?

When features have different units or ranges, standardization prevents a large-scale feature from dominating simply because of its numerical scale. It is not always appropriate when the original variances are meaningful and comparable.

Q: How do you decide the number of components?

Use explained variance, a scree plot, and—when the goal is prediction—validation performance. A variance threshold alone does not guarantee the best predictive model.

Q: Does PCA use the target variable?

Ordinary PCA is unsupervised and does not use the target. It can therefore preserve variance that is unrelated to the prediction objective.

Q: Does PCA always improve model performance?

No. It can reduce noise and redundancy, but it can also discard useful low-variance information and make features harder to interpret. Validate it against a baseline.

Key takeaway#

PCA converts correlated numerical features into ordered, orthogonal principal components. Eigenvectors define the new directions, eigenvalues quantify the variance captured by those directions, and explained-variance ratios help decide how many components to retain. It is a powerful tool for compression and exploration, but scaling, outliers, interpretability, leakage prevention, and downstream validation determine whether it is a good choice for a particular machine-learning problem.

Related questions

Explore other topics:Deep LearningMLOps