惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Cyberwarzone
Cyberwarzone
The GitHub Blog
The GitHub Blog
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
小众软件
小众软件
Recent Announcements
Recent Announcements
博客园 - 三生石上(FineUI控件)
Security Archives - TechRepublic
Security Archives - TechRepublic
W
WeLiveSecurity
Cloudbric
Cloudbric
博客园 - 司徒正美
美团技术团队
N
News and Events Feed by Topic
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
PCI Perspectives
PCI Perspectives
宝玉的分享
宝玉的分享
H
Help Net Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google DeepMind News
Google DeepMind News
Help Net Security
Help Net Security
Last Week in AI
Last Week in AI
S
Schneier on Security
N
News | PayPal Newsroom
B
Blog RSS Feed
L
LINUX DO - 最新话题
T
Troy Hunt's Blog
S
Secure Thoughts
雷峰网
雷峰网
aimingoo的专栏
aimingoo的专栏
L
Lohrmann on Cybersecurity
G
Google Developers Blog
Microsoft Azure Blog
Microsoft Azure Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
T
Tenable Blog
S
Securelist
L
LangChain Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
I
InfoQ
H
Heimdal Security Blog
Cisco Talos Blog
Cisco Talos Blog
F
Full Disclosure
Y
Y Combinator Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
K
Kaspersky official blog
T
Tailwind CSS Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
阮一峰的网络日志
阮一峰的网络日志
C
Cisco Blogs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
68. PCA: Shrinking Data Without Losing Information
Akhilesh · 2026-05-11 · via DEV Community

You have 100 features. Most of them are correlated. Training is slow. Visualization is impossible. KNN is useless (curse of dimensionality).

PCA is the tool that handles this. It takes your 100 features and finds 10 new features that capture 95% of the original information. Training gets faster, visualization becomes possible, and your models often get better too.

It's one of those techniques you'll use constantly once you understand it.


What You'll Learn Here

  • What PCA actually does in plain terms
  • What principal components and explained variance are
  • How to decide how many components to keep
  • PCA for visualization of high-dimensional data
  • PCA as a preprocessing step before ML models
  • What PCA can't do and when to skip it

The Core Idea: Find the Directions of Spread

Imagine you have data in 2D. A cloud of points that stretches more in one direction than another.

PCA finds the direction with the most spread (variance). That's the first principal component. Then it finds the direction with the second most spread that's perpendicular to the first. That's the second principal component.

If most of the spread is along PC1 and PC2, you can project your data onto just those two directions and keep most of the information. The other directions had little variance, meaning they contributed little signal.

import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA

# Create correlated 2D data
np.random.seed(42)
mean   = [0, 0]
cov    = [[3, 2], [2, 2]]   # correlated features
X_2d   = np.random.multivariate_normal(mean, cov, 300)

# Fit PCA
pca_2d = PCA(n_components=2)
pca_2d.fit(X_2d)

pc1 = pca_2d.components_[0]
pc2 = pca_2d.components_[1]

plt.figure(figsize=(7, 5))
plt.scatter(X_2d[:, 0], X_2d[:, 1], alpha=0.4, color='steelblue', s=25)

# Draw the principal components as arrows
origin = X_2d.mean(axis=0)
scale  = 2
plt.arrow(*origin, *(scale * pc1), head_width=0.15, head_length=0.1,
          color='red',    label='PC1 (most variance)')
plt.arrow(*origin, *(scale * pc2), head_width=0.15, head_length=0.1,
          color='orange', label='PC2 (2nd most variance)')

plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.title('Principal Components Show Directions of Maximum Variance')
plt.legend()
plt.grid(True, alpha=0.3)
plt.savefig('pca_directions.png', dpi=100)
plt.show()

print(f"PC1 direction: {pc1.round(3)}")
print(f"PC2 direction: {pc2.round(3)}")
print(f"Variance explained by PC1: {pca_2d.explained_variance_ratio_[0]:.1%}")
print(f"Variance explained by PC2: {pca_2d.explained_variance_ratio_[1]:.1%}")

Enter fullscreen mode Exit fullscreen mode

Output:

PC1 direction: [0.847 0.532]
PC2 direction: [-0.532  0.847]
Variance explained by PC1: 88.2%
Variance explained by PC2: 11.8%

Enter fullscreen mode Exit fullscreen mode

PC1 captures 88% of the variance. If you only keep PC1, you keep 88% of the information. PC2 adds another 12%. Together they explain 100% because the original data was 2D.

In practice you start with 100+ dimensions and find that the first 10-20 components explain 95%+ of the variance.


PCA on Real Data: Digits Dataset

The digits dataset has 64 features (8x8 pixel images). Let's compress it.

from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
import numpy as np
import matplotlib.pyplot as plt

digits = load_digits()
X = digits.data    # 1797 samples, 64 features
y = digits.target

print(f"Original shape: {X.shape}")

# Fit PCA to find all components
pca_full = PCA()
pca_full.fit(X)

# Explained variance ratio
evr = pca_full.explained_variance_ratio_
cumulative_evr = np.cumsum(evr)

# How many components to reach 95% variance?
n_95 = np.argmax(cumulative_evr >= 0.95) + 1
n_99 = np.argmax(cumulative_evr >= 0.99) + 1

print(f"Components for 95% variance: {n_95}")
print(f"Components for 99% variance: {n_99}")

# Plot the explained variance
plt.figure(figsize=(10, 4))

plt.subplot(1, 2, 1)
plt.bar(range(1, 21), evr[:20], color='steelblue')
plt.xlabel('Principal Component')
plt.ylabel('Variance Explained')
plt.title('Variance per Component (first 20)')

plt.subplot(1, 2, 2)
plt.plot(range(1, len(evr)+1), cumulative_evr, color='blue', linewidth=2)
plt.axhline(0.95, color='red',    linestyle='--', label='95%')
plt.axhline(0.99, color='orange', linestyle='--', label='99%')
plt.axvline(n_95, color='red',    linestyle=':',  alpha=0.7)
plt.axvline(n_99, color='orange', linestyle=':',  alpha=0.7)
plt.xlabel('Number of Components')
plt.ylabel('Cumulative Variance Explained')
plt.title('Cumulative Explained Variance')
plt.legend()

plt.tight_layout()
plt.savefig('pca_explained_variance.png', dpi=100)
plt.show()

Enter fullscreen mode Exit fullscreen mode

Output:

Original shape: (1797, 64)
Components for 95% variance: 29
Components for 99% variance: 41

Enter fullscreen mode Exit fullscreen mode

You can represent 64-dimensional digit images in just 29 dimensions and keep 95% of the information. That's a 55% reduction.


How to Decide How Many Components to Keep

Three strategies:

Strategy 1: Cumulative explained variance threshold
Keep enough components to explain 95% (or 99%) of the variance. Most common.

# Keep 95% of variance
pca_95 = PCA(n_components=0.95)   # pass float between 0 and 1
pca_95.fit(X)
print(f"Components kept: {pca_95.n_components_}")

Enter fullscreen mode Exit fullscreen mode

Strategy 2: Fixed number
When you know what you want (e.g., 2 for visualization, 50 for a pipeline).

pca_50 = PCA(n_components=50)
pca_50.fit(X)

Enter fullscreen mode Exit fullscreen mode

Strategy 3: The elbow in the scree plot
Plot variance per component. Pick the point where adding more components gives diminishing returns.

plt.figure(figsize=(8, 4))
plt.plot(range(1, 21), evr[:20], marker='o', color='blue', linewidth=2)
plt.xlabel('Principal Component')
plt.ylabel('Variance Explained')
plt.title('Scree Plot: Look for the Elbow')
plt.grid(True, alpha=0.3)
plt.savefig('scree_plot.png', dpi=100)
plt.show()

Enter fullscreen mode Exit fullscreen mode

The elbow (where the curve flattens) suggests how many components carry most of the signal. Components after the elbow add noise as much as information.


PCA for Visualization

The most common use: compress any high-dimensional data to 2D so you can see it.

from sklearn.preprocessing import StandardScaler

# Scale first (always before PCA)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# Compress to 2D
pca_2d_digits = PCA(n_components=2, random_state=42)
X_2d_digits   = pca_2d_digits.fit_transform(X_scaled)

print(f"Original: {X_scaled.shape}")
print(f"After PCA: {X_2d_digits.shape}")
print(f"Variance explained: {pca_2d_digits.explained_variance_ratio_.sum():.1%}")

# Plot colored by digit class
plt.figure(figsize=(9, 7))
scatter = plt.scatter(
    X_2d_digits[:, 0], X_2d_digits[:, 1],
    c=y, cmap='tab10', s=15, alpha=0.7
)
plt.colorbar(scatter, label='Digit')
plt.xlabel('PC1')
plt.ylabel('PC2')
plt.title('Digits Dataset in 2D via PCA')
plt.savefig('pca_digits_2d.png', dpi=100)
plt.show()

Enter fullscreen mode Exit fullscreen mode

Even in 2D, you can see clusters of similar digits. 0s cluster together. 1s cluster together. Some digits (4, 7, 9) overlap because they look similar.

Try 3D for even more separation:

from mpl_toolkits.mplot3d import Axes3D

pca_3d_digits = PCA(n_components=3, random_state=42)
X_3d_digits   = pca_3d_digits.fit_transform(X_scaled)

fig = plt.figure(figsize=(9, 7))
ax  = fig.add_subplot(111, projection='3d')
sc  = ax.scatter(
    X_3d_digits[:, 0], X_3d_digits[:, 1], X_3d_digits[:, 2],
    c=y, cmap='tab10', s=10, alpha=0.6
)
plt.colorbar(sc, label='Digit')
ax.set_xlabel('PC1')
ax.set_ylabel('PC2')
ax.set_zlabel('PC3')
plt.title('Digits in 3D via PCA')
plt.savefig('pca_digits_3d.png', dpi=100)
plt.show()

Enter fullscreen mode Exit fullscreen mode


PCA as a Preprocessing Step

PCA often improves downstream model performance on high-dimensional data. It removes noise dimensions and speeds up training.

Always: scale first, then PCA, then model. Use a Pipeline so no leakage happens.

from sklearn.pipeline import 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
import numpy as np

# Compare: with and without PCA
pipeline_no_pca = Pipeline([
    ('scaler', StandardScaler()),
    ('model',  LogisticRegression(max_iter=1000, random_state=42))
])

pipeline_pca = Pipeline([
    ('scaler', StandardScaler()),
    ('pca',    PCA(n_components=0.95, random_state=42)),
    ('model',  LogisticRegression(max_iter=1000, random_state=42))
])

scores_no_pca = cross_val_score(pipeline_no_pca, X, y, cv=5)
scores_pca    = cross_val_score(pipeline_pca,    X, y, cv=5)

print(f"Without PCA: {scores_no_pca.mean():.3f} +/- {scores_no_pca.std():.3f}")
print(f"With PCA:    {scores_pca.mean():.3f} +/- {scores_pca.std():.3f}")

Enter fullscreen mode Exit fullscreen mode

Output:

Without PCA: 0.952 +/- 0.010
With PCA:    0.921 +/- 0.013

Enter fullscreen mode Exit fullscreen mode

On this dataset, PCA slightly reduces accuracy. That's common with clean, well-structured data. PCA helps more on noisy datasets with many redundant features.


Reconstructing Data From Components

PCA is reversible. You can compress data and then approximately reconstruct it. The reconstruction error tells you how much information was lost.

from sklearn.datasets import load_digits

digits = load_digits()
X_orig = digits.data

# Scale
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_orig)

# Compress and reconstruct with different numbers of components
fig, axes = plt.subplots(3, 6, figsize=(14, 7))
sample_idx = 0  # show first digit

# Original
axes[0, 0].imshow(X_orig[sample_idx].reshape(8, 8), cmap='gray')
axes[0, 0].set_title('Original')
axes[0, 0].axis('off')

for i, n_comp in enumerate([1, 2, 5, 10, 20, 29]):
    pca_r = PCA(n_components=n_comp, random_state=42)
    X_comp = pca_r.fit_transform(X_scaled)
    X_recon_scaled = pca_r.inverse_transform(X_comp)
    X_recon = scaler.inverse_transform(X_recon_scaled)

    variance_kept = pca_r.explained_variance_ratio_.sum()

    axes[1, i].imshow(X_recon[sample_idx].reshape(8, 8), cmap='gray')
    axes[1, i].set_title(f'n={n_comp}\n({variance_kept:.0%})')
    axes[1, i].axis('off')

    # Reconstruction error
    mse = np.mean((X_orig[sample_idx] - X_recon[sample_idx]) ** 2)
    axes[2, i].bar(['Error'], [mse], color='steelblue')
    axes[2, i].set_ylim(0, 50)
    axes[2, i].set_title(f'MSE={mse:.1f}')

plt.tight_layout()
plt.savefig('pca_reconstruction.png', dpi=100)
plt.show()

Enter fullscreen mode Exit fullscreen mode

With 1 component you get a blurry mess. With 29 components (95% variance) the digit is clearly recognizable. With more components the reconstruction gets closer to the original.

This visualization is a great way to feel what "explaining 95% of variance" actually means.


What PCA Assumes and When It Fails

PCA is powerful but has real limitations.

PCA assumes linear relationships.
It finds linear combinations of features. If the important structure in your data is non-linear (like a spiral or a manifold), PCA will miss it. Use t-SNE or UMAP for non-linear visualization.

PCA is unsupervised.
It finds directions of maximum variance, not directions that best separate classes. Sometimes the most variance in data has nothing to do with what you're trying to predict.

PCA components are not interpretable.
Each component is a linear combination of all original features. You can't easily say "PC1 means house size." It means: 0.23 * size + 0.18 * age - 0.14 * distance + ... This is a tradeoff for compression.

PCA requires scaling.
If one feature has values in millions and another in 0 to 1, PCA will find directions that mostly capture the variance of the big-scale feature. Always StandardScale before PCA.

# Proof that scaling matters
from sklearn.datasets import fetch_california_housing
from sklearn.decomposition import PCA

housing = fetch_california_housing()
X_h = housing.data

# Without scaling
pca_unscaled = PCA(n_components=2)
pca_unscaled.fit(X_h)
print("Without scaling - variance explained by PC1:")
print(f"  {pca_unscaled.explained_variance_ratio_[0]:.1%}  <- first feature dominates")

# With scaling
from sklearn.preprocessing import StandardScaler
X_h_scaled = StandardScaler().fit_transform(X_h)
pca_scaled = PCA(n_components=2)
pca_scaled.fit(X_h_scaled)
print("With scaling - variance explained by PC1:")
print(f"  {pca_scaled.explained_variance_ratio_[0]:.1%}  <- more balanced")

Enter fullscreen mode Exit fullscreen mode

Output:

Without scaling - variance explained by PC1:
  99.9%  <- first feature dominates

With scaling - variance explained by PC1:
  34.8%  <- more balanced

Enter fullscreen mode Exit fullscreen mode

Without scaling, one feature with large numeric values owns 99.9% of PC1. That tells you almost nothing useful.


PCA for Noise Reduction

Another use: reduce noise in data by keeping only the top components and discarding the noisy ones.

# Add noise to digits data and see if PCA helps denoise
X_noisy = X + np.random.normal(0, 4, X.shape)

# Scale
scaler_n = StandardScaler()
X_noisy_s = scaler_n.fit_transform(X_noisy)
X_clean_s = scaler_n.fit_transform(X)

# Compress and reconstruct to denoise
pca_denoise = PCA(n_components=29, random_state=42)
pca_denoise.fit(X_clean_s)

X_noisy_comp  = pca_denoise.transform(X_noisy_s)
X_denoised_s  = pca_denoise.inverse_transform(X_noisy_comp)
X_denoised    = scaler_n.inverse_transform(X_denoised_s)

# Compare original, noisy, denoised
fig, axes = plt.subplots(3, 5, figsize=(12, 7))
for i in range(5):
    axes[0, i].imshow(X[i].reshape(8, 8),          cmap='gray')
    axes[1, i].imshow(X_noisy[i].reshape(8, 8),    cmap='gray')
    axes[2, i].imshow(X_denoised[i].reshape(8, 8), cmap='gray')

axes[0, 0].set_ylabel('Original')
axes[1, 0].set_ylabel('Noisy')
axes[2, 0].set_ylabel('Denoised')
for ax in axes.flat:
    ax.axis('off')

plt.suptitle('PCA for Noise Reduction')
plt.tight_layout()
plt.savefig('pca_denoising.png', dpi=100)
plt.show()

Enter fullscreen mode Exit fullscreen mode

The denoised images are much cleaner than the noisy ones. PCA projected the noisy data into a lower-dimensional clean space, then reconstructed it. The noise, which spreads across many components with low variance, gets discarded.


Quick Cheat Sheet

Task Code
Fit PCA PCA(n_components=50).fit(X_scaled)
Keep 95% variance PCA(n_components=0.95)
Transform data pca.transform(X)
Fit and transform pca.fit_transform(X)
Reconstruct pca.inverse_transform(X_compressed)
Variance explained pca.explained_variance_ratio_
Cumulative variance np.cumsum(pca.explained_variance_ratio_)
Components pca.components_ (shape: n_components x n_features)
Full pipeline Pipeline([('scaler', StandardScaler()), ('pca', PCA(0.95)), ('model', ...)])

Practice Challenges

Level 1:
Load load_breast_cancer(). Scale it. Apply PCA keeping 95% variance. How many components does that require from the original 30? Train a LogisticRegression before and after PCA. Does accuracy change?

Level 2:
Load any dataset with many features. Plot the scree plot and cumulative explained variance. Find the elbow. Try three different component counts: at the elbow, 50% variance, and 99% variance. Compare classifier performance for each.

Level 3:
Load the digits dataset. Add Gaussian noise (std=5). Apply PCA with 10, 20, and 40 components. For each, reconstruct the images and calculate MSE vs the original clean images. Which component count gives the best denoising? Plot original, noisy, and all three reconstructions side by side.


References


Next up, Post 69: Feature Engineering: Building Better Inputs. The algorithm matters less than what you feed it. Here's how to create, transform, and select features that actually help your model learn.