PCA and visual projections without over-reading them
Apply PCA and a 2D projection, read explained variance, and test whether reduced features help a downstream model.
By Invicly Tech, , in AI and Machine Learning with Python. About 11 minutes to read.
In short
Dimensionality reduction squeezes many columns into a few new ones. PCA builds straight-line combinations of the features that keep as much variance as possible, and t-SNE or UMAP draw 2D maps that keep near neighbours close. Kept variance is not the same as kept usefulness, so always test reduced features on the real task.
Think of it like this: PCA is like photographing a 3D sculpture from the angle that shows the most detail; you lose depth, and the most detailed angle is not always the one that shows the face.
Explained simply
Many datasets have dozens or hundreds of columns. That makes them hard to look at and can slow models down. Dimensionality reduction creates a small number of new columns that summarise the old ones. You trade a little detail for a lot of simplicity.
PCA, short for principal component analysis, is the classic method. It finds the direction in which your data spreads out most and calls it the first component. The second component is the next most spread-out direction at a right angle to the first, and so on. Each component is a weighted mix of the original columns.
PCA tells you how much of the total spread each component keeps, called the explained variance ratio. If the first five components keep 90 percent, you might drop the rest. But spread is not the same as usefulness. A tiny direction might be exactly the one that separates fraud from normal payments.
For pictures, people often use t-SNE or UMAP. They squash the data onto a flat 2D map so that rows that were close stay close. The maps can be beautiful, but the size of the blobs and the gaps between them do not mean much. Use them to get ideas, then check those ideas properly.
Press Play on a diagram to walk through it one step at a time.
- 1Scale
Standardise so each feature has variance 1
- 2Fit PCA on training data
Find directions of largest variance
- 3Read explained variance
explained_variance_ratio_ per component
- 4Pick components
Enough to reach a target, such as 90 percent
- 5Test downstream
Compare model scores with and without PCA
- Linear and deterministic
- Has transform for new rows
- Axes have a meaning: weighted features
- Distances are roughly preserved
- Non-linear and random
- No transform for new rows in scikit-learn
- Axes have no meaning
- Cluster sizes and gaps can mislead
- Speed up or simplify a model
- PCA in a Pipeline
- Check score with and without
- Draw a 2D picture
- PCA first, as an honest baseline
- t-SNE or UMAP for local structure
- Remove correlated columns
- PCA
- Or simply drop duplicates by hand
- Need to explain features
- Prefer feature selection
- Components mix many columns
In depth
What PCA actually computes
PCA centres each column at zero, then finds orthogonal directions, called principal components, ordered by how much variance the data has along them. Under the hood scikit-learn uses a singular value decomposition. Each component is a vector of loadings, stored in components_, one weight per original feature. Projecting a row onto the components gives its new coordinates.
Scaling matters. PCA on raw data treats a column in grams as far more important than one in kilograms, because its variance is larger. Standardise first unless all columns share units and you truly want bigger spreads to count more. You can pass n_components as an integer, or as a float between 0 and 1, such as 0.9, to keep enough components to reach that share of variance.
- components_: loadings, shape (n_components, n_features)
- explained_variance_ratio_: share per component
- n_components=0.9 keeps 90 percent of variance
- inverse_transform maps back to approximate original values
Reading explained variance
Plot the cumulative sum of explained_variance_ratio_. A steep early rise means a few directions capture most of the spread, which often happens when features are strongly correlated, such as height in centimetres and height in inches. A slow, steady rise means the information is spread across many directions and PCA will not compress much.
Look at the loadings of the first few components to name them. If PC1 has large positive weights on every spending column, it is roughly overall spend. Be careful: signs can flip between runs or library versions, so a negative loading is not meaningful on its own, only relative to the others. Never claim that a component is a real-world cause; it is a summary of correlation in your sample.
- 1Cumulative variance curve
How many components you need
- 2explained_variance_ratio_
Spread kept by each component
- 3components_ (loadings)
Which features build each component
- 4Transformed data
Each row's coordinates on the new axes
Testing whether reduced features help
The real question is whether PCA improves the task you care about. Build two pipelines, one with StandardScaler and your model, one with StandardScaler, PCA and the same model, and compare them with the same cross-validation folds. Putting PCA inside the pipeline matters: each fold then fits its own components on training rows only, so no test information leaks in.
Try several n_components values, or tune it with GridSearchCV. You will often see that PCA makes a linear model faster with similar accuracy, helps a little when features are very correlated, and hurts tree models, which handle many columns well and lose interpretability on rotated axes. Keep PCA only if it wins on your metric or on speed by a margin that matters.
Reading t-SNE and UMAP plots honestly
t-SNE turns distances into neighbour probabilities and arranges points in 2D so that close neighbours stay close. It is random, so different seeds give different pictures. Its main setting, perplexity, defaults to 30 and roughly sets how many neighbours each point considers; different values can split or merge blobs.
Three rules keep you honest. First, blob sizes mean little, because t-SNE expands dense regions and shrinks sparse ones. Second, distances between blobs mean little; two far-apart blobs are not necessarily more different than two nearby ones. Third, random noise can form apparent clusters at low perplexity. UMAP, from the separate umap-learn package, is faster and keeps more global layout, but the same caution applies. Run several perplexities and seeds; trust only patterns that persist and that you can confirm with another method.
- Plot several perplexities, for example 5, 30 and 50
- Fix random_state to make a plot reproducible
- Colour points by a known label to check what the map shows
Learn it in 5 short steps
About 30m each. Track them with a timer in your plan.
- 1Fit PCA on scaled data~30m
- 2Read explained variance~30m
- 3Draw 2D projections carefully~30m
- 4Test downstream performance~30m
- 5Avoid over-reading t-SNE plots~30m
Key points
- PCA without scaling mostly rediscovers whichever column has the biggest units.
- The explained variance ratio says how much spread a component keeps, not how much signal for your target it keeps.
- Fit PCA inside a Pipeline so cross-validation does not leak test data into the components.
- Use t-SNE and UMAP plots for exploring, never as evidence of how many groups exist.
Key terms
Tap a card to flip it. 0/5 known
Examples
from sklearn.datasets import load_digits
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
X, y = load_digits(return_X_y=True)
for n in [None, 10, 20, 40]:
steps = [StandardScaler()] + ([PCA(n_components=n)] if n else [])
pipe = make_pipeline(*steps, LogisticRegression(max_iter=2000))
print(n, cross_val_score(pipe, X, y, cv=5).mean().round(3))PCA sits inside the pipeline, so each fold fits its own components.
How many components for the digits dataset?
load_digits has 64 pixel columns. Step 1: scale and fit PCA with all components. Step 2: compute the cumulative explained variance and find how many components reach 90 percent; for standardised digits it is roughly 30. Step 3: compare cross-validated accuracy for a logistic regression with all 64 columns and with that many components. Expect similar accuracy with half the columns. Step 4: try 10 components; accuracy usually drops, even though those 10 components still keep a large share of the variance.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
X, y = load_digits(return_X_y=True)
Xs = StandardScaler().fit_transform(X)
cum = np.cumsum(PCA().fit(Xs).explained_variance_ratio_)
print("components for 90%:", int(np.argmax(cum >= 0.9)) + 1)
print("variance kept by 10:", cum[9].round(2))The low-variance signal trap
Build a synthetic dataset where two columns have large variance but are pure noise, and a third column has small variance and decides the label. Step 1: without scaling, PCA with one component keeps mostly the noisy columns. Step 2: a classifier on that single component scores near 50 percent. Step 3: the same classifier on the raw columns scores near 100 percent. Lesson: high explained variance can throw away the very direction the target depends on.
import numpy as np
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
signal = rng.normal(0, 0.1, 1000); y = (signal > 0).astype(int)
X = np.c_[rng.normal(0, 10, 1000), rng.normal(0, 10, 1000), signal]
with_pca = make_pipeline(PCA(1), LogisticRegression())
print("PCA(1):", cross_val_score(with_pca, X, y).mean().round(2))
print("raw:", cross_val_score(LogisticRegression(), X, y).mean().round(2))Quick reference
- Scale, then PCA: make_pipeline(StandardScaler(), PCA(n_components=0.9), model)
- explained_variance_ratio_ is spread kept, not target signal kept
- components_ holds loadings; signs can flip, compare magnitudes
- Fit PCA inside the pipeline so cross-validation does not leak
- TSNE has fit_transform only; it cannot project new rows
- t-SNE perplexity defaults to 30; try several values and seeds
- Do not read t-SNE blob sizes or gaps as real distances
Common mistakes
- Fitting PCA on the whole dataset before the train-test split, which leaks information.
- Reading cluster size or the distance between blobs in a t-SNE plot as real.
- Keeping 95 percent of variance and assuming the model will be just as accurate.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Fit PCA on the scaled wine dataset (load_wine) and print the explained variance ratio of the first three components and their total.
- Exercise 2medium
Use GridSearchCV to choose n_components for a pipeline of StandardScaler, PCA and LogisticRegression on load_digits. Report the best value and its score.
- Exercise 3hard
Show that t-SNE can invent structure: run TSNE on 500 rows of pure Gaussian noise with 10 features at perplexity 2 and 30, and describe what you see.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is PCA a feature selection method?
- No. Feature selection keeps some original columns; PCA builds new columns that mix all the originals. If you need to explain which original features matter, use feature selection instead.
- Should I use t-SNE or UMAP?
- Both are fine for exploration. UMAP is usually faster and keeps more of the overall layout, but it is a separate package (umap-learn). Neither should be used as proof of how many groups exist.
- How many components should I keep?
- Start with the number that reaches 80 to 95 percent cumulative variance, then let downstream model performance make the final choice.