Machine LearningDimensionality Reduction

PCA vs t-SNE

Question 305 of 307 · Updated

On this page

PCA and t-SNE both reduce high-dimensional data, but they preserve different kinds of structure. Principal Component Analysis (PCA) is a linear method that finds directions capturing the greatest variance across the dataset. t-distributed Stochastic Neighbor Embedding (t-SNE) is a nonlinear, neighborhood-focused method designed mainly to visualize local relationships.

Use PCA for compression, reusable features, variance analysis, and preprocessing. Use t-SNE to explore local groups in a two-dimensional or three-dimensional visualization. They are complementary, not interchangeable.

1. Why reduce dimensionality?#

A dataset may contain hundreds or thousands of features. This can make visualization difficult, increase storage and computation, and leave redundant or noisy dimensions.

Dimensionality reduction maps an original vector into fewer coordinates:

LaTeX

For example, 100 features might be mapped to two coordinates for a scatter plot, or to 20 components before training another model. The key question is which relationships the smaller representation should preserve.

2. What is PCA?#

PCA is an unsupervised, linear dimensionality-reduction technique. It finds orthogonal directions, called principal components, along which the centered data has the greatest variance. Each component is a weighted sum of the original features; PCA creates new coordinates rather than selecting a subset of columns.

How PCA works#

  1. Arrange observations into a feature matrix.
  2. Center each feature by subtracting its training-set mean. Scale features when their units or variances are not comparable.
  3. Find principal directions using the covariance matrix or Singular Value Decomposition (SVD).
  4. Rank directions by explained variance.
  5. Keep the first (k) components and project observations onto them.

For a centered matrix (X), the first principal direction solves:

LaTeX

Later components maximize remaining variance while staying orthogonal to earlier components. PCA can also be computed using:

LaTeX

The right singular vectors in (V) give the principal directions. Squared singular values, with the appropriate sample normalization, determine the variance captured by each direction.

Numerical example: explained variance#

Suppose two centered features have covariance matrix:

LaTeX

Its eigenvalues are 6 and 2. The corresponding unit eigenvectors are approximately:

  • PC1: ((0.707, 0.707))
  • PC2: ((0.707, -0.707))

Total variance is (6+2=8), so:

  • PC1 explains (6/8=75\%\).
  • PC2 explains (2/8=25\%\).

Keeping only PC1 reduces two features to one while retaining 75% of the variance in this example. The discarded 25% might be noise—or useful information. Explained variance alone cannot decide.

What PCA preserves#

PCA prioritizes large-scale variance across the dataset. It provides a single linear coordinate system and can transform future observations using the fitted components. It can retain more than two dimensions.

PCA does not guarantee that high-variance directions are most predictive of a target. A low-variance feature can still carry important predictive information.

3. What is t-SNE?#

t-SNE is a nonlinear dimensionality-reduction technique developed primarily for visualizing high-dimensional data. It tries to place observations in a low-dimensional map so that nearby observations in the original space remain nearby in the map.

It converts pairwise similarities into probability distributions and makes the high-dimensional and low-dimensional neighborhood probabilities resemble one another.

How t-SNE works#

  1. Compute pairwise similarities in the original feature space.
  2. Convert similarities into conditional probabilities: nearby points receive higher probabilities.
  3. Symmetrize these probabilities into joint similarities.
  4. Initialize low-dimensional coordinates, often with PCA.
  5. Define map similarities using a heavy-tailed Student's t-distribution.
  6. Use gradient descent to reduce the mismatch between the original and map probabilities.

Its objective is the Kullback–Leibler (KL) divergence:

LaTeX

Here, (p_{ij}) represents the similarity probability for a pair in the original space and (q_{ij}) represents its similarity in the embedding. The heavy-tailed distribution helps reduce the crowding problem that occurs when many high-dimensional points are represented in a small space.

Numerical intuition: neighborhood preservation#

Suppose two observations have high-dimensional joint probability (p_{ij}=0.6), but the current map gives them (q_{ij}=0.2). That pair contributes:

LaTeX

to the KL objective. The map is not keeping a strongly related pair sufficiently close, so optimization adjusts coordinates. This is one illustrative pair contribution, not the complete t-SNE loss.

What t-SNE preserves#

t-SNE focuses strongly on local neighborhoods. It can reveal curved or nonlinear local arrangements and make groups easier to inspect than a simple linear projection.

However, distances between separated clusters, apparent cluster sizes, and empty space between groups should not be interpreted as faithful global geometry. A visually separated pair of groups is not proof that they are far apart in the original space.

The objective is non-convex. Different random seeds, initializations, and hyperparameters can produce different maps.

4. PCA vs t-SNE: key differences#

  • Type: PCA is linear; t-SNE is nonlinear and neighborhood-based.
  • Objective: PCA maximizes retained variance; t-SNE minimizes KL divergence between neighborhood similarity distributions.
  • Structure: PCA captures broad variance through orthogonal axes; t-SNE emphasizes local neighborhoods.
  • Interpretability: PCA components are weighted combinations of original features. t-SNE axes generally have no direct feature-level meaning.
  • Output: PCA can produce one, two, or many components. t-SNE is commonly used for two- or three-dimensional visualization.
  • New observations: A fitted PCA model supports projection of new data. Standard scikit-learn t-SNE is a fit-time embedding and does not provide the same general-purpose out-of-sample transform workflow.
  • Speed: PCA is generally much faster. t-SNE is more computationally demanding, although Barnes–Hut and other approximations improve scalability.
  • Stability: PCA is generally stable for a fixed dataset and configuration. t-SNE can vary across initializations and parameter settings.
  • Best use: PCA is useful for compression, preprocessing, and downstream modeling. t-SNE is useful for exploratory visualization of local structure.

5. Linear vs nonlinear dimensionality reduction#

A linear method maps data using a matrix projection:

LaTeX

The new coordinates are linear combinations of the original features. PCA can rotate the coordinate system and discard lower-variance directions, but it cannot unfold a curved manifold into a globally straight representation.

A nonlinear method can represent more complicated relationships. t-SNE does not search for one linear projection matrix; it optimizes the coordinates of observations directly so that local similarity relationships are reflected in the map.

Imagine points arranged along a curved, S-shaped surface. A two-dimensional linear projection may overlap parts of the curve. A neighborhood-focused nonlinear embedding may separate local sections more clearly. That visualization is useful for exploration, but it is not a globally faithful map of every distance.

6. Assumptions and limitations#

PCA#

  • Most useful when meaningful structure can be represented by linear combinations of features.
  • Prioritizes variance, not class separation, causal meaning, or predictive relevance.
  • Sensitive to feature scale: a variable measured in thousands can dominate one measured between zero and one.
  • Outliers can strongly affect covariance and principal directions.
  • Components can be difficult to interpret when many features contribute.
  • Information in discarded components is lost; select component count using explained variance and downstream validation.

t-SNE#

  • Depends on the distance metric and feature representation used to define neighborhoods. Poor scaling or irrelevant features can create misleading neighborhoods.
  • Is stochastic and non-convex; repeat runs and inspect stability.
  • Does not explicitly preserve global distances, cluster sizes, or density in the original space.
  • Can make apparent clusters even when the original structure is continuous. Validate groups in the original feature space and with domain knowledge.
  • Can be expensive for large datasets. Reduce very high-dimensional dense data with PCA first; use TruncatedSVD for sparse data when appropriate.
  • Is not a drop-in feature transformation for future production records in standard scikit-learn.

Neither method removes the need for data cleaning, thoughtful feature representation, or validation.

7. Important t-SNE hyperparameters#

  • perplexity: Controls effective neighborhood scale. Values around 5–50 are common starting points, not universal rules. It must be smaller than the number of samples. Compare several values.
  • early_exaggeration: Influences how strongly neighborhoods separate during early optimization. Excessive values can make optimization unstable.
  • learning_rate: Controls optimization step size. Too high or too low can produce poor embeddings.
  • max_iter: Sets the optimization budget. Check whether the embedding has stabilized.
  • init: PCA initialization is often more globally stable than random initialization.
  • metric: Determines how input-space distances are measured. Euclidean is common, but not appropriate for every representation.
  • random_state: Fix it for reproducibility; also compare multiple seeds when conclusions matter.
  • method and angle: Barnes–Hut approximates gradient calculations and is faster for larger datasets; angle controls the approximation trade-off.

For PCA, important choices include the number of components, whether to scale features, whether to whiten, and the SVD solver.

8. Python example with scikit-learn#

This example compares a two-component PCA projection with a t-SNE visualization using the handwritten digits dataset. It standardizes the features and first reduces the input to 30 PCA dimensions before running t-SNE. Labels are used only to color the plots after fitting; neither method receives them.

PYTHON
import matplotlib.pyplot as plt from sklearn.datasets import load_digits from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.manifold import TSNE digits = load_digits() X, y = digits.data, digits.target # Demonstration preprocessing. X_scaled = StandardScaler().fit_transform(X) # Linear projection into two dimensions. pca_2d = PCA(n_components=2, random_state=42) X_pca = pca_2d.fit_transform(X_scaled) print("PCA explained variance:", pca_2d.explained_variance_ratio_) print("Total variance retained:", pca_2d.explained_variance_ratio_.sum()) # PCA preprocessing followed by t-SNE. X_30d = PCA(n_components=30, random_state=42).fit_transform(X_scaled) tsne = TSNE( n_components=2, perplexity=30, init="pca", learning_rate="auto", max_iter=1000, random_state=42 ) X_tsne = tsne.fit_transform(X_30d) fig, axes = plt.subplots(1, 2, figsize=(12, 5)) axes[0].scatter(X_pca[:, 0], X_pca[:, 1], c=y, cmap="tab10", s=8) axes[0].set_title("PCA") axes[1].scatter(X_tsne[:, 0], X_tsne[:, 1], c=y, cmap="tab10", s=8) axes[1].set_title("t-SNE") plt.tight_layout() plt.show()

Interpretation:

  • PCA gives a global linear projection. Some digit classes may overlap because the first two directions maximize overall variance, not class separation.
  • t-SNE may make local neighborhoods of similar digits appear more distinct.
  • Colors are ground-truth labels used only to inspect the plot. They did not guide either unsupervised method.
  • A t-SNE plot with separated colors does not prove that a classifier will achieve high accuracy. Evaluate predictive performance separately.

For a real prediction pipeline, fit the scaler and PCA only on training data, then reuse those fitted transformations on validation, test, and production data. Never fit preprocessing on the complete dataset before splitting; that leaks information.

9. When should you use each method?#

Choose PCA when:

  • You need a compact representation for a downstream model.
  • You want to reduce redundancy among numerical features.
  • You need a repeatable transformation for future observations.
  • You want to inspect explained variance or reconstruct approximate inputs.
  • You need a fast baseline before more expensive methods.

Choose t-SNE when:

  • You want to visualize local neighborhoods in embeddings, images, or other high-dimensional observations.
  • You are exploring whether observations form local groups or lie on nonlinear structures.
  • You want an exploratory plot rather than a production feature transformer.

A practical workflow:

  1. Clean the data and choose a meaningful feature representation.
  2. Scale numerical features when their units make raw distances or variance incomparable.
  3. Use PCA to inspect variance and, when appropriate, reduce dense high-dimensional data to a manageable number of components.
  4. Run t-SNE on that reduced representation for visualization.
  5. Repeat t-SNE with several perplexities and random seeds.
  6. Validate apparent groups using original-space distances, domain knowledge, and downstream evaluation.

For very large datasets, consider whether a faster visualization method such as UMAP is more appropriate. Do not select a method solely because its plot looks attractive.

10. Production guidance#

PCA can be deployed as part of a feature pipeline: persist the fitted scaler and PCA model, version them with the downstream model, and apply exactly the same transformations at inference time. Monitor input distributions and transformed features. Refit only through a controlled training and validation process.

Treat t-SNE primarily as an offline analysis and debugging tool. It can help investigate embedding quality, data slices, potential outliers, and local group structure. Avoid using visual cluster separation as a production acceptance criterion. Standard scikit-learn t-SNE does not provide a fitted transform equivalent to PCA, so a separate embedding strategy is needed if stable out-of-sample coordinates are a product requirement.

11. Final takeaway#

PCA preserves high-variance linear structure; t-SNE emphasizes local neighborhood structure for visualization. PCA is usually the practical choice for compression and reusable features. t-SNE is often the better exploratory plot when nonlinear local patterns are hard to see. They can be combined: PCA first to reduce dimensions and t-SNE afterward to visualize local relationships.

Choose based on what the reduced representation must preserve and what decision it will support—not on which visualization looks more separated.

Related questions

Explore other topics:Forward Deployed EngineeringDeep LearningMLOps