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.
- PCA with n_components
- explained_variance_ratio_
- How many components keep 90%
- 1
(178, 13)13 original features - 2
StandardScalerSame scale for every feature - 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.
StandardScaler()💡 Light every side equally firstPCA(n_components=2)📷 Take the two most revealing photosexplained_variance_ratio_📊 How much of the shape each photo showsX_2d🖼️ The data seen in 2 dimensionsPCA finds new axes, called principal components, along which the data varies most, and projects the data onto the first few of them.
Key points
- Standardize first, or proline alone decides the first component.
fit_transformturns the (178, 13) data into shape (178, 2).- The first component keeps 36.2% of the variance and the second 19.2%, 55.4% together.
- 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
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)
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.
- Change random_state and see how much the score moves.
- Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
- Try a different model or hyperparameter and compare the scores.
Common mistakes
Running PCA on unscaled data
The feature with the largest numbers takes over the first component.
PCA(n_components=2).fit_transform(X)
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.
- Matrix Multiplication Multiply two matrices, the operation behind every layer of a neural network. Easy
Tools for this lesson
- Jupyter Notebook Online: Run Python Cells in Your BrowserFree online Jupyter notebook: run Python cells with pandas, NumPy and Matplotlib, add Markdown text, open and download .ipynb files. No install, no account.
- pandas Online Compiler: Run pandas and NumPy in Your BrowserRun pandas and NumPy code online with nothing to install. NumPy, pandas, SciPy, Matplotlib and scikit-learn are ready in the free Python editor.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.