Skip to main content
Dimensionality Reduction Concept
Dimensionality Reduction Real World Example

Dimensionality Reduction

The Curse of Dimensionality

Imagine searching for your friend in a 1D hallway — easy. Now imagine a 2D football field — harder. Now a 3D building — much harder. Now imagine a 100-dimensional space. The volume of that space grows so fast that any reasonable dataset becomes absurdly sparse. As features increase:
  • Data becomes sparse — Points are so far apart that “nearby” neighbors are barely closer than distant ones
  • Models need exponentially more data — To have the same density of examples in 100D as in 2D, you would need roughly 10^50 times more data
  • Distance metrics become meaningless — In high dimensions, the farthest point and the nearest point are almost the same distance away (this is mathematically provable, and it breaks KNN, clustering, and any distance-based method)
  • Training time explodes — More features means more parameters to learn and more computation per step
This is the “curse of dimensionality,” and it is why blindly throwing 500 features at a model often performs worse than carefully picking 20.

Why Reduce Dimensions?

Visualization

Plot 100D data in 2D

Speed

Faster training and inference

Noise Reduction

Remove noisy features

Better Models

Reduce overfitting

PCA: Principal Component Analysis

PCA finds new axes (directions) that capture the most variance in your data. It answers the question: “If I could only look at this data from a few angles, which angles would show me the most information?”

The Intuition

Imagine photographing a cigar from different angles. From the side, you see its full length — lots of information about shape. From the tip, you just see a circle — almost no useful information. PCA automatically finds the “best side view” (most variance) first, then the next most informative angle perpendicular to that, and so on.
  • First principal component: Along the cigar (direction of most variance — the most informative angle)
  • Second principal component: Across the cigar (direction of second most variance, perpendicular to the first)
Math Connection: PCA uses eigendecomposition of the covariance matrix. See Linear Algebra Course for the full theory.

Choosing the Number of Components

Method 1: Explained Variance

Method 2: Preserve Target Variance


Visualizing High-Dimensional Data

Digits in 2D


t-SNE: For Visualization

While PCA preserves global structure (overall spread and distances), t-SNE focuses on preserving local structure — it ensures that points that are close in high-dimensional space remain close in the 2D projection. This makes it excellent for revealing clusters that PCA might smear together.

PCA vs t-SNE

t-SNE is for visualization only! Do not use it as a preprocessing step for models. The distances between clusters in a t-SNE plot are meaningless — two clusters that appear far apart may actually be close in the original space. t-SNE can also create apparent clusters in random data, so always verify patterns with other methods.

UMAP: Best of Both Worlds

UMAP has largely replaced t-SNE as the go-to visualization tool in production settings. It is significantly faster (especially on large datasets), preserves more global structure (cluster distances are more meaningful), and can even transform new unseen data — something t-SNE cannot do.

PCA for Preprocessing

Speed Up Training

Noise Reduction


Feature Selection vs Feature Extraction

These are two fundamentally different strategies for reducing dimensions, and knowing when to use which is a practical skill that matters in production.

LDA: Supervised Dimensionality Reduction

While PCA asks “which directions have the most variance?”, LDA asks “which directions best separate my classes?” This makes LDA ideal when your goal is classification rather than general-purpose compression. The tradeoff: LDA can only produce at most (n_classes - 1) components, so for binary classification you get exactly one dimension.

When to Use What


Practical Example: Image Compression


Key Takeaways

PCA for Preprocessing

Reduce dimensions while keeping variance

t-SNE/UMAP for Visualization

See high-dimensional data in 2D/3D

LDA for Classification

Maximize class separation

Choose Components Wisely

Use explained variance or CV performance

What’s Next?

Congratulations! You’ve completed the advanced topics. Now let’s bring everything together in a capstone project!

Continue to Capstone Project

Build a complete ML system from scratch

Interview Deep-Dive

PCA can absolutely hurt, and understanding when requires thinking about what PCA optimizes for versus what your model needs.
  • PCA maximizes variance, not predictive power. The directions of maximum variance are not necessarily the directions that separate your classes. Imagine a medical dataset where 90% of the variance comes from patient height and weight (wide spread), but the actual disease signal is in a subtle protein biomarker with low variance. PCA would keep the height/weight components and throw away the protein signal. LDA would be the right choice here because it maximizes class separation, not variance.
  • Tree-based models rarely benefit from PCA. Random forests and gradient boosting are invariant to feature scale and can handle high-dimensional, correlated features natively. PCA actually removes the interpretability of individual features (each PC is a weighted mix of all originals) and can hurt trees by obscuring the axis-aligned splits they rely on.
  • PCA destroys sparsity. If your original features are sparse (many zeros, like text bag-of-words), PCA produces dense components. A sparse 10,000-feature matrix might be efficient in memory and computation, but after PCA it becomes a dense 100-feature matrix that loses the computational advantages of sparsity.
  • PCA assumes linear relationships. If the meaningful structure in your data is nonlinear (e.g., a spiral in 2D), PCA will project it into components that do not capture that structure. Kernel PCA or autoencoders handle nonlinear manifolds better.
  • Small datasets with many features can benefit. This is where PCA shines — it acts as regularization by reducing the effective dimensionality, which reduces overfitting. The classic case: 50 samples with 500 features. Without PCA (or some other reduction), most models will overfit badly.
Follow-up: How would you decide the number of PCA components to keep in a production pipeline?I would never use the “keep 95% variance” rule blindly. Instead, I would put PCA inside a pipeline and use cross-validation with different n_components values, scoring on the downstream task metric (accuracy, AUC, whatever matters). The optimal number of components is the one that maximizes task performance, not explained variance. In my experience, the “95% variance” heuristic often keeps too many components. The task-optimal number is frequently 60-70% of explained variance because the remaining variance is mostly noise that hurts generalization.
These three tools solve fundamentally different problems, and confusing them is a common mistake in interviews.
  • PCA: preprocessing and compression. PCA is the only one of the three that should be used as a preprocessing step before modeling. It is deterministic, fast, invertible (you can reconstruct the original features), and can transform new unseen data. In production, I use PCA to reduce feature dimensionality before feeding data into a model, to speed up training on high-dimensional datasets, and for denoising (reconstruct from top-K components).
  • t-SNE: visualization only. t-SNE produces beautiful 2D scatter plots that reveal cluster structure, but the output is not stable (different random seeds give different plots), the axes are meaningless, and you cannot transform new data points without rerunning the entire algorithm. Never use t-SNE output as features for a model. The distances between clusters in a t-SNE plot are meaningless — two clusters that appear far apart may be close in the original space, and vice versa.
  • UMAP: visualization with some production uses. UMAP is faster than t-SNE, preserves more global structure (cluster distances are more meaningful), and crucially can transform new data points. This makes UMAP usable in light production scenarios — for example, projecting new data into an existing 2D space for anomaly visualization dashboards. However, I still would not use UMAP embeddings as features for a downstream model in most cases because the embedding is sensitive to hyperparameters (n_neighbors, min_dist) and small changes can produce very different geometries.
  • A common production pattern: Use PCA for the actual model pipeline (reduce 500 features to 50), then use UMAP or t-SNE to create monitoring visualizations that show how new data clusters compared to training data. This gives you the best of both worlds: a robust, reproducible model with informative visual monitoring.
Follow-up: A data scientist on your team used t-SNE embeddings as features for a classifier and got great accuracy. What would you say?I would say the accuracy is likely misleading and the approach will fail in production. t-SNE is fit on the entire dataset (train + test) simultaneously, which means test data influences the embedding of training data and vice versa. This is a form of data leakage. Additionally, t-SNE embeddings are not stable — rerunning with a different seed gives different features, making the model non-reproducible. Even if you fix the seed, you cannot embed new production data without rerunning t-SNE on the entire dataset including the new point, which is computationally prohibitive at scale. Replace t-SNE with PCA in the pipeline, or if you need nonlinear reduction, use a trained autoencoder that can transform new data independently.
This is a great production-reality question because it tests whether you understand the operational challenges of maintaining ML systems over time.
  • PCA trained on old features cannot handle new features. PCA learns a projection matrix based on a specific set of input features. If the data engineering team adds 5 new features next quarter, you cannot simply append them — the PCA model expects the original feature set. You have three options: retrain PCA including the new features (requires retraining the downstream model too), ignore the new features in the existing model (lose potential signal), or maintain a separate model for new features and ensemble.
  • Use a feature store with versioning. Each model version should be pinned to a specific feature set version. When new features are added, they go into a new feature set version. The existing model continues to use the old feature set until you explicitly retrain and validate a new model version with the expanded features.
  • Design for feature evolution from the start. Instead of hard-coding PCA with n_components=50, use a pipeline that dynamically selects the top K features by importance (e.g., using SelectFromModel with a tree-based estimator) and then applies PCA on the selected features. When new features arrive, the selection step can automatically include them if they are informative.
  • Monitor feature importance after adding new features. After retraining with new features, check if the new features rank highly in importance. If a newly added feature dominates, investigate whether it is genuinely informative or leaking information. New features that immediately become the most important are suspicious.
  • Automate the retrain-evaluate-deploy cycle. If features change quarterly, you need a pipeline that can retrain the model (including PCA), evaluate against a holdout set, compare performance to the current production model, and deploy only if the new model is better. This should be triggered automatically when the feature schema changes.
Follow-up: How do you handle the case where a feature that was previously important gets deprecated by the data engineering team?This is a production emergency if not handled carefully. If the model was trained with that feature and it suddenly becomes null or is removed, predictions will either fail (if the model expects it) or degrade silently (if it defaults to zero). I would implement a feature availability monitoring check that alerts immediately if any expected feature is missing or has an unusual null rate. The short-term fix is to impute the missing feature based on training-time statistics (mean/median). The long-term fix is to retrain the model without that feature. The key lesson is that feature contracts between teams need to be explicit and versioned, just like API contracts.