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 observations and features can be written as a matrix:
Each row is an observation, and each column is a feature. The number is the feature dimension. For example, a dataset describing 1,000 devices with 20 sensor readings per device has shape 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.
| Goal | How fewer dimensions may help | Important qualification |
|---|---|---|
| Visualization | Plot a dataset in two or three dimensions | A plot is only a simplified view of the original data |
| Compression | Store a smaller representation | Information may be lost |
| Noise reduction | Discard directions that mainly contain noise | Low-variance directions can also contain useful signals |
| Faster computation | Reduce the size of later calculations | Fitting the transformation itself has a cost |
| Generalization | Sometimes reduce overfitting from irrelevant or redundant inputs | Performance improvements are not guaranteed |
| Discovering structure | Expose dominant directions of variation | Large 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.
| Question | Feature selection | Feature extraction with PCA |
|---|---|---|
| Are the original feature names preserved? | Yes, for the selected columns | Usually no; components combine original features |
| Can information from multiple features be combined? | Not inherently | Yes |
| Is the method necessarily supervised? | No | Standard PCA is unsupervised |
| Is the output easy to interpret? | Often easier | Sometimes 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.
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 original features, PCA can find at most directions with nonzero sample variance in a centered dataset of 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 observations and features. We want to retain components, where .
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:
where contains feature means and 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 , the sample covariance matrix of centered data is
An eigenvector of 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 directions
Let the selected orthonormal directions form a matrix
Project the centered data into the lower-dimensional space:
where contains the component scores.
Step 5: Optionally reconstruct an approximation
An approximate reconstruction in the original feature space is
If 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.
7. A small numerical example
Consider three two-dimensional observations:
Their feature means are , so the centered matrix is
The sample covariance matrix is
Its largest eigenvalue is , with a corresponding unit eigenvector
The second eigenvalue is . This tells us all observed variation lies along a single straight line. Projecting onto the first component produces
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 with 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 , the explained variance ratio of component is
provided total variance is nonzero.
The cumulative explained variance ratio after retaining components is
For illustration, suppose a dataset produces these ratios:
| Component | Explained variance | Cumulative variance |
|---|---|---|
| PC1 | 55% | 55% |
| PC2 | 25% | 80% |
| PC3 | 12% | 92% |
| PC4 | 8% | 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 include:
- Set a target for cumulative explained variance, such as 90% or 95%, when appropriate for the application.
- Inspect an explained-variance or scree plot for diminishing returns.
- For visualization, choose two or three components and explain the information lost.
- For a supervised downstream model, select the component count using validation or cross-validation rather than the test set.
- 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:
| Attribute | What 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.
| Method | Basic idea | Typical use or caution |
|---|---|---|
| PCA | Linear projection that preserves maximum variance | General compression, preprocessing, exploratory analysis |
| Truncated SVD | Low-rank matrix approximation without requiring prior centering | Often useful for sparse term-document matrices |
| t-SNE | Nonlinear embedding emphasizing local neighborhoods | Exploratory visualization; plot distances and cluster sizes require care |
| UMAP | Nonlinear manifold-based embedding | Visualization and some embedding workflows; sensitive to settings |
| Autoencoder | Neural network learns a compressed representation through a reconstruction objective | Can model nonlinear structure but requires more choices and training |
| Feature selection | Retain original columns | Useful 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 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:
- Linear algebra: It relies on vectors, projections, covariance matrices, eigenvectors, eigenvalues, or singular value decomposition.
- Statistics: It uses variance and covariance to characterize the spread of observations.
- Data preprocessing: Scaling, missing-value treatment, and outlier handling affect the components.
- Unsupervised learning: Standard PCA learns structure without target labels.
- Clustering: PCA may help compress or visualize data before or after clustering, although projected clusters can be misleading.
- Model evaluation: The benefit of PCA must be measured against baseline systems on data not used to fit it.
15. Check your understanding
- What is the difference between choosing three existing features and computing three principal components?
- Does preserving 95% explained variance mean the classifier will achieve 95% accuracy?
- Why is centering important to the usual mathematical definition of PCA?
- How does standardizing features potentially change PCA’s results?
- What is the difference between a principal direction and a component score?
- Why should PCA be fitted only on training data during supervised evaluation?
- Why might a low-variance direction still matter for classification?
- When might truncated SVD be preferable to ordinary centered PCA?
Show suggested answers
- Feature selection keeps original variables; PCA computes new variables by projecting onto linear combinations of the original features.
- No. Explained variance measures retained variation in the input representation, not prediction accuracy.
- Centering lets the covariance-based directions describe variation around the feature means rather than offset from the origin.
- Scaling changes relative feature variances and therefore which directions maximize variance.
- A principal direction is an axis in feature space; a score is an observation’s coordinate along that axis.
- Fitting on held-out examples leaks their feature distribution into the model-development process and can bias evaluation.
- The target may depend strongly on a small but consistent difference in a low-variance direction.
- Truncated SVD can work directly with sparse matrices and does not require explicitly centering them first.
16. Related concepts
- AI Knowledge Map — overview of the connected AI curriculum.
- Vectors and Matrices — feature matrices and vector notation.
- Vector and Matrix Operations — dot products, transformations, and projections.
- Descriptive and Inferential Statistics — means, variance, and covariance.
- Feature Engineering, Encoding, and Scaling — preparing features for PCA.
- Data Splitting, Labeling, and Leakage — preventing data leakage.
- Clustering and K-Means — another unsupervised learning method.
- Evaluating Machine Learning Models — task-level evaluation of PCA pipelines.
- Naive Bayes and Probabilistic Classification — next algorithm in the AI knowledge map.
References and further reading
- scikit-learn User Guide: PCA — dimensionality reduction, PCA, and its variants.
- scikit-learn API: PCA — estimator options and documented attributes.
- scikit-learn: Common pitfalls and recommended practices — preprocessing and data leakage.
- An Introduction to Statistical Learning — dimensionality reduction and unsupervised learning in context.
- The Elements of Statistical Learning — mathematical background for statistical learning methods.
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.