t-SNE Memory Crash — Why 500K Rows Needs 2TB RAM
t-SNE allocates n²×8 bytes for pairwise distances — 2TB for 500K points.
20+ years shipping production ML systems and the infrastructure behind them. Written from production experience, not tutorials.
- ✓Deep production experience
- ✓Understanding of internals and trade-offs
- ✓Experience debugging complex systems
- Dimensionality reduction maps high-dimensional data (10,000+ features) into 2-50 dimensions while preserving variance (PCA) or neighbourhood structure (t-SNE/UMAP).
- PCA: linear, deterministic, O(n·d²) time — interpretable components, best for pre-processing before linear models.
- t-SNE: non-linear, stochastic, O(n²) time — great for visualisation but sensitive to perplexity; can create false clusters.
- UMAP: non-linear, O(n log n) with approximate neighbours — scales to millions of points, preserves more global structure than t-SNE.
- LDA: supervised, finds axes that maximise class separation — use only when labels are available and classes are roughly Gaussian.
- Production insight: PCA can be inverted to detect outliers; t-SNE transforms are not reusable on new data — embed once, discard the model.
Imagine you're describing every person at a party using 500 different facts — their shoe size, hair length, what they had for breakfast, etc. Most of those facts are redundant or useless for figuring out who's similar to whom. Dimensionality reduction is like a smart assistant that says: 'forget 490 of those facts — these 10 actually capture who people are.' You lose a little detail, but you gain the ability to actually SEE patterns, run models faster, and stop drowning in noise. That's it. That's dimensionality reduction.
High-dimensional data is everywhere in production ML — a user's click history might span 10,000 features, a raw image 50,176 pixels, a genomics dataset half a million SNP markers. Models trained directly on this data suffer from the curse of dimensionality: distances become meaningless, overfitting skyrockets, training slows to a crawl, and visualisation becomes impossible. Dimensionality reduction isn't a pre-processing nicety — it's often the difference between a model that generalises and one that memorises noise.
The core problem these techniques solve is geometric. In high dimensions, every point is roughly equidistant from every other point. That breaks nearest-neighbour search, makes clustering unstable, and bloats the covariance matrix your model has to estimate. By projecting data into a lower-dimensional space that preserves what actually matters — variance, local structure, class separability — you give your downstream algorithms a fighting chance.
By the end of this article you'll understand the internal mechanics of PCA, t-SNE, UMAP, and LDA well enough to choose the right one for a production problem, tune hyperparameters with confidence, avoid the subtle bugs that silently corrupt results, and answer the interview questions that trip up even experienced ML engineers.
What is Dimensionality Reduction Techniques?
High-dimensional data is the norm in production ML, not the exception. Each new feature adds a dimension, and as dimensions grow, the volume of the feature space explodes exponentially. This is the curse of dimensionality: distances between any two points become nearly identical, making nearest-neighbour algorithms useless; the sample density plummets, so you need exponentially more data to cover the space; and models overfit because they can memorise noise in the extra dimensions instead of learning signal.
Dimensionality reduction tackles this by projecting the data into a lower-dimensional subspace that preserves the structure you care about. The four dominant techniques — PCA, t-SNE, UMAP, LDA — each make different trade-offs between linearity, scalability, interpretability, and the type of structure they preserve.
PCA keeps global variance; t-SNE keeps local neighbourhoods; UMAP keeps a fuzzy topology that balances local and global; LDA keeps class separability. Pick the wrong one and you'll either destroy the signal you're trying to capture or get misled by false patterns.
PCA — Linear Reduction with Interpretable Components
Principal Component Analysis finds the orthogonal axes that maximise the variance of the projected data. It's a linear transformation — the output dimensions are linear combinations of the original features. This makes PCA the most interpretable method: you can inspect the loadings (eigenvectors) to understand which original features drive each component.
The algorithm centres the data, computes the covariance matrix, then performs eigenvalue decomposition. The top-k eigenvectors become the principal components. In practice, you should always standardise data before PCA — otherwise high-variance features dominate.
PCA is also the fastest method: O(n·d² + d³) for n samples and d features. It's a deterministic closed-form solution — no hyperparameter tuning, no stochasticity. That's why it's the go-to for feature extraction in linear models and for anomaly detection (reconstruction error).
- The first principal component points where variance is highest.
- Each component is orthogonal to the previous — no redundancy.
- The eigenvalues tell you how much variance each component explains.
- You drop the smallest eigenvalue components — that's the reduction.
t-SNE — Capturing Local Neighbourhood Structure
t-Distributed Stochastic Neighbour Embedding (t-SNE) is a non-linear technique that focuses on preserving the pairwise distances between nearby points. It converts high-dimensional Euclidean distances into conditional probabilities of similarity in the original space, then matches those with a similar distribution in the low-dimensional space using a heavy-tailed t-distribution.
The key hyperparameter is perplexity — roughly the number of neighbours considered. Common mistake: using default perplexity=30 for all datasets. If your dataset is small (<500 points), reduce perplexity. If it's large (>10,000), increase it, but be aware of memory limits.
t-SNE is stochastic and each run gives a different embedding. It is not a function you can apply to new data — you must re-run on the full dataset. That makes it unsuitable for production ML pipelines that embed new points. Its only safe production use is exploratory visualisation and interpretation of learned features.
UMAP() . t-SNE cannot do this — you must re-run on the entire dataset.UMAP — Scalable Non-Linear Reduction
Uniform Manifold Approximation and Projection (UMAP) is a manifold learning technique that builds a fuzzy topological representation of the data in high dimensions, then optimises a similar representation in low dimensions. It uses nearest neighbours to create a weighted graph, then minimises cross-entropy between the high-dimensional and low-dimensional graphs.
UMAP's key advantages: it scales to millions of points (O(n log n) with approximate neighbours), preserves more global structure than t-SNE, and — crucially — provides a transform method for embedding new data points after training. This makes it the only non-linear method suitable for production pipelines.
Two main hyperparameters: n_neighbors (controls local vs global balance, default 15) and min_dist (controls how tightly points pack together in the embedding, default 0.1). Lower n_neighbors focuses on local structure; higher values capture global topology.
- Step 1: Construct a weighted nearest-neighbour graph with fuzzy set membership.
- Step 2: Optimise a low-dimensional graph to minimise cross-entropy between the two graphs.
- The graph captures the topological structure — local AND global.
- The transform method embeds new points using the same graph (parametric extension).
LDA — Supervised Dimensionality Reduction
Linear Discriminant Analysis is a supervised technique. Unlike PCA which finds directions of maximum variance, LDA finds the linear axes that maximise class separability. It does this by maximising the ratio of between-class variance to within-class variance.
LDA assumes: (1) the data is normally distributed per class, (2) classes have identical covariance matrices, and (3) the number of features is less than the number of samples (otherwise the within-class scatter matrix is singular). It's limited to C-1 components where C is the number of classes, so for binary classification you get only 1 dimension.
When these assumptions hold, LDA often outperforms PCA for classification tasks because it's directly optimising for class separation. It's commonly used in face recognition (Fisherfaces) and as a pre-processing step for algorithms that benefit from class-discriminative features.
Choosing the Right Technique — Decision Tree and Trade-offs
You've now seen four techniques. The right choice depends on your goal: interpretability, visualisation, scalability, or classification accuracy.
- Need interpretable, fast, linear? → PCA
- Need to visualise small datasets (<10k) with pretty clusters? → t-SNE
- Need to visualise large datasets or embed new points? → UMAP
- Have labels, want to separate classes? → LDA
But beyond the initial choice, monitor the embedding quality: for t-SNE/UMAP, check the KL divergence or cross-entropy loss. For PCA/LDA, check the explained variance ratio or classification accuracy on a hold-out set.
A common pitfall: applying dimensionality reduction once and never re-validating. Data distributions shift. The embedding that worked last quarter may be useless today. Treat your reduction pipeline as a trainable component with regular monitoring.
Feature Selection: Stop Chasing Noise. Start Cutting Dimensions with Real Impact.
Most dimensionality reduction tutorials treat feature extraction like PCA as the only game in town. They're wrong. When you have 500 columns of customer survey data, PCA will give you 500 new abstract components that break your model's explainability. Feature selection is faster, cheaper, and keeps your model honest. You keep the real column names—the ones your product team understands.
Start with variance thresholding. Ditch columns where 95% of values are identical. It's free speed. After that, use mutual information for classification or correlation with target for regression. It's not sexy, but it works in production where every millisecond of inference latency matters.
The real trick: use a Lasso regression or a Random Forest's feature_importances_ to automatically prune low-signal columns. You get a stable feature set that doesn't change when you retrain next quarter. No mysterious dimension shifts.
Why this matters: Feature selection gives you a reproducible, debuggable pipeline. When your ML product breaks at 2AM, you can trace a prediction back to 'monthly_spend > 500'—not 'component 7 of PCA'.
Feature Extraction: When You Need Lower Dimensionality but Must Keep All Signals
Feature extraction—like PCA, Autoencoders, or Truncated SVD—isn't for the faint of heart. You do it when you can't drop columns without losing predictive power. Think image embeddings, user-item recommendation matrices, or sensor arrays where every axis carries information. The price: you lose interpretability.
The workflow is brutal. First, standardize everything. PCA without scaling is a disaster because features with larger magnitudes dominate components. You'll blame the algorithm, but it's your fault. Second, choose the number of components based on explained variance ratio—shoot for 90-95% unless you need extreme compression for real-time serving.
For non-linear signals, skip PCA. Use a denoising autoencoder or UMAP's embedding as a feature transform. This hits when you have high-order interactions—like clickstream data—that linear transformations miss. Train your extraction on training data only, then transform validation and test sets. Leaking the test set into PCA's covariance matrix is a cardinal sin I've seen twice this year.
The payoff: you can push a 10,000-dim image feature vector down to 64 components and still get 98% of your model's F1 score. That's hours of training saved.
Real-World Use Case: Purging 90% of Features from a Fraud Detection Pipeline—Without Losing Revenue
I inherited a fraud model with 412 features. It trained in 6 hours, took 800MB of RAM, and had 97% precision. The problem: retraining cost $200/month in compute, and inference latency was 45ms—too slow for real-time payment gateways. Feature extraction wasn't an option because compliance required every feature to be a named business rule.
Here's the play-by-play. First, I binned correlated features (Pearson |r| > 0.95) into proxy groups. Then, I ran Lasso regression with five-fold cross-validation. Lasso's L1 penalty zeroes out weak features—no manual decisions. I kept features with non-zero coefficients after regularization. This dropped us from 412 to 48 features.
Training time fell to 12 minutes. Inference latency dropped to 6ms. Precision held at 96.8%. The saved compute paid for two dev sprints. The operational win: when a fraud pattern shifted, we could trace the drift to specific 'transaction_count_30d' changes versus some abstract latent component.
That's the real-world trade-off. Feature selection for explainability, feature extraction for raw compression. Your business context dictates the choice. Always pick the method that doesn't get you called into a 10AM compliance meeting.
Working: The Nuts and Bolts of Crummy Data Beating a Path to Lower Dimensions
Dimensionality reduction is a two-step military operation: mapping your high-dimensional data to a lower-dimensional space while preserving some structure. That structure is what you make your bet on. PCA bets on variance — it finds orthogonal axes that maximize variance in your data. t-SNE bets on local neighborhoods — it keeps nearby points close in the low-dimensional map. UMAP bets on both local and global structure using a graph-based approach.
Each technique works by defining a cost function and iteratively minimizing it. PCA solves this analytically via eigendecomposition of the covariance matrix. Non-linear methods like t-SNE and UMAP use gradient descent. They start with random positions in the low-dimensional space and nudge points around until the arrangement matches the high-dimensional pairwise distances. This is why they are computationally expensive — t-SNE runs O(n²) per iteration.
When you hit run, your data enters a pipeline: standardization, distance computation, optimization, and validation. If your data has 1000 features, you are computing distances in a 1000-dimensional space. Curse of dimensionality means those distances become meaningless. The working principle of any reduction method must account for this — either by projecting onto a subspace (PCA) or using graph heuristics (UMAP) to make distances robust.
Disadvantages: Where Your Fancy Reduction Technique Breaks in Production
Dimensionality reduction is not a free lunch. The number one disadvantage is information loss. Every reduction discards dimensions. If those discarded dimensions carry signal for your downstream task (e.g., a rare class in fraud detection), you are torching predictive performance. PCA throws away the directions with smallest variance — but variance does not equal relevance. I have seen teams lose 20% of model AUC because they naively cut to 10 components.
Second: interpretability goes out the window for non-linear methods. t-SNE and UMAP produce beautiful 2D scatter plots. That is all they produce. You cannot say "feature 12 drives this cluster" because the mapping is non-linear and coordinate values are meaningless. Your stakeholders will ask "why is that point there?" and you will shrug.
Third: computational cost. t-SNE is O(n²). UMAP is faster but still O(n log n). In production pipelines handling millions of rows, you cannot run t-SNE every inference batch. You need to precompute embeddings and serve them stale — which breaks if your data distribution drifts.
Finally: stochasticity. Non-linear methods produce different embeddings each run. Run t-SNE twice and get two different visualizations. Great for exploration, terrible for reproducibility. Pin your random seed and document it as a hyperparameter.
Naïve Bayes: Why Simplicity Beats Complexity in High Dimensions
When reducing dimensionality, most techniques assume complex relationships between features. Naïve Bayes flips that assumption on its head: it explicitly assumes all features are independent given the class label. This 'naïve' assumption is why it scales gracefully to thousands of dimensions without needing explicit reduction. Instead of projecting data into a lower space, Naïve Bayes uses the full dimensionality but models each feature's contribution separately via probability distributions. This makes it incredibly robust to noise and irrelevant features—something that KNN or SVMs struggle with in high dimensions. In production, Naïve Bayes often serves as a fast baseline before investing in PCA or t-SNE for feature extraction. The real power comes from its speed: training is a single pass through the data, and inference is a simple lookup of conditional probabilities. For text classification with bag-of-words (extremely high-dimensional), it consistently beats more complex models on both latency and F1 score. The independence assumption also simplifies missing data handling—features can be dropped without retraining.
Unsupervised Learning: Dimensionality Reduction Without Target Labels
Module 3 addresses unsupervised dimensionality reduction—techniques that don't need labeled data. This is critical when you have millions of data points but zero labels, a common scenario in anomaly detection or customer segmentation. The most production-ready unsupervised methods are PCA (linear), UMAP (non-linear), and autoencoders (deep learning). PCA remains the workhorse for its deterministic output and variable importance scores. UMAP handles complicated manifolds where PCA fails, but at a computational cost—O(n^2) memory for large datasets. Autoencoders offer the most flexibility: you can reconstruct any distribution and even add constraints like sparsity or variational bottlenecks. The golden rule: for less than 1000 features, try PCA first; for non-linear structures, start with UMAP's mini-batch mode; for streaming data, use incremental PCA. Unsupervised methods require vigilance in validation: since there's no ground truth, you must use reconstruction error, neighbor preservation, or silhouette scores to gauge quality. In production pipelines, always normalize features before applying these techniques—failure to do so is the #1 cause of unusable embeddings.
t-SNE OOM crash on a 500k row customer dataset
- Always estimate memory before running t-SNE on large datasets: n² × 8 bytes.
- Use UMAP when you need to visualise more than 50,000 points.
- Never use t-SNE for dimensionality reduction as a pre-processing step for downstream models — it's non-parametric and cannot embed new points.
python -c "import numpy as np; n=500000; d=1000; print('Memory (GB):', (n*d*8)/1e9)"from sklearn.decomposition import IncrementalPCA; ipca = IncrementalPCA(n_components=50, batch_size=1000)| File | Command / Code | Purpose |
|---|---|---|
| io | public class ReductionDemo { | What is Dimensionality Reduction Techniques? |
| io | public class PCA { | PCA |
| io | public class TSNE { | t-SNE |
| io | public class UMAP { | UMAP |
| io | public class LDA { | LDA |
| io | public class ReductionMonitor { | Choosing the Right Technique |
| SelectFeaturesByImportance.py | from sklearn.ensemble import RandomForestClassifier | Feature Selection |
| ExtractComponentsWithPipeline.py | from sklearn.decomposition import PCA | Feature Extraction |
| FraudFeatureSelectionLasso.py | from sklearn.linear_model import LogisticRegression | Real-World Use Case: Purging 90% of Features from a Fraud Detection Pipeline |
| pca_working_example.py | from sklearn.decomposition import PCA | Working |
| pca_info_loss_demo.py | from sklearn.decomposition import PCA | Disadvantages |
| naive_bayes_high_dim.py | from sklearn.naive_bayes import GaussianNB | Naïve Bayes |
| unsupervised_reduction.py | from sklearn.decomposition import PCA | Unsupervised Learning |
Key takeaways
Interview Questions on This Topic
Explain the difference between PCA and t-SNE. When would you use each in a production ML pipeline?
Frequently Asked Questions
20+ years shipping production ML systems and the infrastructure behind them. Written from production experience, not tutorials.
That's Algorithms. Mark it forged?
9 min read · try the examples if you haven't