Machine Learning with scikit-learn

PCA in Python with scikit-learn

Compress 13 features into 2 with PCA, see how much information each component keeps, and pick the number of components.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • PCA with n_components
  • explained_variance_ratio_
  • How many components keep 90%
Wine data
  1. 1(178, 13)13 original features
  2. 2StandardScalerSame scale for every feature
  3. 3(178, 2)2 components, 55.4% of the variance

Fewer columns, most of the information

The problem

Datasets often have many columns that move together. They are hard to plot, slow to train on and partly redundant. You want a few columns that keep most of the information.

Think of it like this

PCA is like photographing a 3D sculpture from the angle that shows the most detail. One good photo captures most of the shape; a second photo from another angle adds what the first missed.

From photographing a sculpture to code
StandardScaler()💡 Light every side equally first
PCA(n_components=2)📷 Take the two most revealing photos
explained_variance_ratio_📊 How much of the shape each photo shows
X_2d🖼️ The data seen in 2 dimensions
Each component is a new viewing angle.
In one sentence

PCA finds new axes, called principal components, along which the data varies most, and projects the data onto the first few of them.

Key points

  1. Standardize first, or proline alone decides the first component.
  2. fit_transform turns the (178, 13) data into shape (178, 2).
  3. The first component keeps 36.2% of the variance and the second 19.2%, 55.4% together.
  4. 8 components are needed to keep 90% of the variance.

When should you use it?

  • Plotting high-dimensional data in 2D.
  • Speeding up models by removing redundant columns.
  • Reducing noise before clustering.

When not to use it

  • When you need to explain results in terms of the original features.
  • Non-linear structure: t-SNE or UMAP show clusters better for plots.

Example code

Open in editor →
main.py
import numpy as np
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

X, y = load_wine(return_X_y=True)
print("Original shape:", X.shape)

# PCA is sensitive to scale, so standardize the 13 features first
X_scaled = StandardScaler().fit_transform(X)

pca = PCA(n_components=2)
X_2d = pca.fit_transform(X_scaled)
print("Reduced shape: ", X_2d.shape)

ratios = pca.explained_variance_ratio_
print("Variance explained:", np.round(ratios, 3).tolist())
print(f"Total kept: {ratios.sum():.1%}")

# How many components keep 90% of the variance?
full = PCA().fit(X_scaled)
needed = int(np.argmax(np.cumsum(full.explained_variance_ratio_) >= 0.90)) + 1
print("Components for 90%:", needed)
Get a Run button for this example

Result of running the code

Original shape: (178, 13)
Reduced shape:  (178, 2)
Variance explained: [0.362, 0.192]
Total kept: 55.4%
Components for 90%: 8

Code explanation

The wine data has 178 rows and 13 features. StandardScaler comes first because PCA looks for directions of large variance, and unscaled proline would win on size alone. PCA(n_components=2) turns X_scaled into X_2d with shape (178, 2). explained_variance_ratio_ says the first component keeps 36.2% of the variance and the second 19.2%, 55.4% together. Fitting PCA() with all components and taking the running total with np.cumsum shows that 8 components are needed to keep 90%.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change random_state and see how much the score moves.
  2. Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
  3. Try a different model or hyperparameter and compare the scores.
Run in the Python compiler →

Common mistakes

Running PCA on unscaled data

The feature with the largest numbers takes over the first component.

Problem
PCA(n_components=2).fit_transform(X)
Fix
PCA(n_components=2).fit_transform(StandardScaler().fit_transform(X))

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges

Tools for this lesson