Learning path: Find Structure Without Labels: Clustering, PCA and Recommenders · Step 4 of 6
Dimensionality Reduction with PCA: 13 Columns Down to 2
PCA squeezes many columns into a few new ones and keeps most of the information. Reduce 178 wines from 13 columns to 2, see why scaling comes first, pick the number of components and use PCA in a pipeline.
What you will learn
- Explain principal components and explained variance
- Show why you must scale before PCA
- Reduce 13 wine columns to 2 and plot them
- Choose n_components and use PCA inside a pipeline
Before you start
- Feature Scaling: StandardScaler and MinMaxScaler
- Pipelines and ColumnTransformer
PCA stands for principal component analysis. The idea is simple: squeeze many columns into a few new ones and still keep most of the information. It needs no labels, which is why it sits with clustering in unsupervised learning, but you'll mostly use it in the prepare stage, before a model sees the data.
Too many columns cause real trouble, as you saw in the curse of dimensionality. Feature selection keeps some of the original columns. PCA does something different: it builds new columns.
Find the best angle for the photo
Our data is 178 wines with 13 measurements each, and we can't draw 13 dimensions. So think of a toy bus instead. It's a 3D object and you want one flat photo of it. Shoot from the front and you get a small box; most of the bus is lost. Shoot from the side and the same bus shows up whole.
PCA does exactly this with data. It looks for the angle where the points spread out the most, so we lose as little as possible.
Two columns, one direction
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
wine = load_wine(as_frame=True)
X, y = wine.data, wine.target
print(X.shape)
(178, 13)
Look at two of the columns:
X[["total_phenols", "flavanoids"]].head()
total_phenols flavanoids
0 2.80 3.06
1 2.65 2.76
2 2.80 3.24
3 3.85 3.49
4 2.80 2.69
print(round(X["total_phenols"].corr(X["flavanoids"]), 2))
0.86
A correlation of 0.86: these two move together, so they tell almost the same story. Scale them and fit a PCA:
two = StandardScaler().fit_transform(
X[["total_phenols", "flavanoids"]])
pca2 = PCA().fit(two)
print(pca2.explained_variance_ratio_.round(3))
[0.932 0.068]
PCA found the line along which the wines spread the most. That's the first principal component, PC1, and it keeps 93.2% of the spread. PC2 sits at a right angle to it and holds only the remaining 6.8%. Drop every wine onto PC1, and two numbers per wine become one while about 93% of the spread is kept. That's the whole trick.
explained_variance_ratio_ is the share of the total spread (variance) that each component keeps.
Scale first, or the big numbers win
PCA hunts for spread, so a column with big numbers looks like it has the most to say.
print(X["hue"].std().round(2), X["proline"].std().round(1))
print(PCA().fit(X).explained_variance_ratio_[0].round(3))
0.23 314.9
0.998
proline spreads 314.9, hue only 0.23. On the raw numbers, PC1 keeps 0.998 of the spread, and that's just proline shouting. After scaling, every column has the same spread and PC1 keeps 0.362, because every column now counts. So: scale first, then PCA. (Feature Scaling covers StandardScaler.)
13 columns in, 2 columns out
X_scaled = StandardScaler().fit_transform(X)
pca = PCA(n_components=2)
X_2d = pca.fit_transform(X_scaled)
print(X_2d.shape)
ratio = pca.explained_variance_ratio_
print(ratio.round(3), ratio.sum().round(3))
(178, 2)
[0.362 0.192] 0.554
The table goes in with 13 columns and comes out with 2. PC1 keeps 36.2%, PC2 19.2%, together 55.4%. More than half of the spread, in just two columns. Now we can draw it:
plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y, s=18)
plt.xlabel("PC1")
plt.ylabel("PC2")
plt.show()

Every dot is one wine. The colour shows the farm it came from (the target y). PCA never saw that column; we only used it to paint the dots. And you can clearly see three groups, something you simply couldn't see in 13 columns.
How many components?
Fit PCA with all 13 components and add up the shares as a running total:
full = PCA().fit(X_scaled)
cum = full.explained_variance_ratio_.cumsum()
print(cum.round(2))
print("components for 95%:", np.argmax(cum >= 0.95) + 1)
[0.36 0.55 0.67 0.74 0.8 0.85 0.89 0.92 0.94 0.96 0.98 0.99 1. ]
components for 95%: 10
plt.bar(range(1, 14), full.explained_variance_ratio_)
plt.plot(range(1, 14), cum, marker="o", color="red")
plt.xlabel("component")
plt.ylabel("share of variance")
plt.show()

Each new component adds less and less. Keep enough for the job: two if you want to draw it (screens are still flat), ten if you want 95% of the spread.
PCA inside a pipeline
Now use PCA in a real model. Split first, then put the scaler, PCA and the model in one pipeline, so the scaler and PCA are fitted on the training rows only (the rule from Train-Test Split and Data Leakage).
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y)
for n in [2, 0.95, None]:
model = make_pipeline(
StandardScaler(), PCA(n_components=n),
LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
print(n, model[1].n_components_,
round(model.score(X_test, y_test), 3))
2 2 0.911
0.95 10 0.978
None 13 1.0
n_components takes three kinds of value:
- a whole number, like
2: keep exactly that many components. - a fraction, like
0.95: keep enough components for 95% of the spread (here, 10). None: keep all 13.
Two columns score 0.911, ten score 0.978, all thirteen score 1.0. Fewer columns cost a little accuracy. PCA is a trade-off, not free magic.
Common mistakes
- Running PCA on unscaled columns. The column with the biggest numbers takes over PC1 (0.998 here).
- Fitting PCA on all rows before the split. Put it in a pipeline so it learns from the train rows only.
- Expecting PC1 to have a meaning. Each component is a mix of every column, so the new columns lose their names and are harder to explain.
- Assuming fewer columns is always better. Check the score: 2 components cost us accuracy here.
Quick recap
| Step | Code | Wine result |
|---|---|---|
| Scale first | StandardScaler() | Unscaled PC1 = 0.998 (proline) |
| New axes, most spread first | PCA(n_components=2) | 0.362 + 0.192 = 0.554 |
| How many to keep | explained_variance_ratio_.cumsum() | 10 components for 95% |
| Use in a model | make_pipeline(scaler, PCA, model) | 0.911 / 0.978 / 1.0 |
Try it yourself
Run the pipeline with n_components=3, then 5. Where does the accuracy stop improving?
The notebook is in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
Next →Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
K-Means Clustering: Find Groups in Data With No Labels
How k-means finds groups without labels: the assign-update loop worked by hand on eight homes, then KMeans on 2,600 customers, bad random starts, k-means++ and why you scale first.
Choosing k for K-Means: the Elbow Method and the Silhouette Score
K-means always returns exactly k groups, even when k is wrong. Use the elbow plot and the silhouette score to pick k for 2,600 customers, then describe each group in plain words.
Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
Two more ways to find groups: agglomerative clustering builds a family tree of merges (the dendrogram), and DBSCAN grows clusters from crowds and leaves loners out as noise. Shown on eight homes, 2,600 customers and two moons.
Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
Which items are bought together? Work out support, confidence and lift by hand on eight baskets, then let Apriori in mlxtend find 240 rules in 14,963 real grocery baskets.