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

推荐订阅源

Jina AI
Jina AI
T
The Blog of Author Tim Ferriss
B
Blog
L
LangChain Blog
Y
Y Combinator Blog
美团技术团队
博客园 - 三生石上(FineUI控件)
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
G
Google Developers Blog
量子位
博客园_首页
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
C
Check Point Blog
D
Docker
小众软件
小众软件
The Cloudflare Blog
大猫的无限游戏
大猫的无限游戏
T
Tailwind CSS Blog
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 聂微东
Blog — PlanetScale
Blog — PlanetScale
GbyAI
GbyAI
Google DeepMind News
Google DeepMind News
IT之家
IT之家

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
Dimensionality Reduction in Machine Learning: PCA and t-SNE.
Kelvin · 2026-05-01 · via DEV Community
Cover image for Dimensionality Reduction in Machine Learning: PCA and t-SNE.

Kelvin

Dimensionality reduction is a fundamental concept in machine learning used to reduce the number of input features (dimensions) in a dataset while preserving as much important information as possible.

Principal Component Analysis (PCA)
Principal Component Analysis (PCA) is a linear dimensionality reduction technique that transforms data into a new coordinate system.

Instead of using the original features, PCA creates new variables called principal components, which are:

  • Linear combinations of the original features
  • Ordered by importance (variance explained)

PCA works by identifying directions (called principal axes) where the data varies the most.

The first principal component captures the maximum variance while the second principal component captures the next highest variance.

This allows us to:

  • Keep only the most informative components
  • Discard less important ones

How PCA Works

  1. Standardize the data - Features must be scaled (very important for PCA)
  2. Compute the covariance matrix - Shows relationships between features.
  3. Compute eigenvalues and eigenvectors
  4. Eigenvectors - directions (principal components)
  5. Eigenvalues - importance (variance explained)
  6. Sort components by eigenvalues - Highest variance first.
  7. Select top K components - Reduce dimensions.
  8. Transform the data - Project data onto new axes.

Workflow
Splitting data.

#splitting data
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X,y, random_state=42, test_size=0.2)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

Enter fullscreen mode Exit fullscreen mode

Scaling data.

#scaling
from sklearn.preprocessing import StandardScaler
X_scaled = StandardScaler().fit_transform(X)

Enter fullscreen mode Exit fullscreen mode

Training

#PCA Principal Components
from sklearn.decomposition import PCA

pca_full = PCA()
pca_full.fit(X_scaled)

Enter fullscreen mode Exit fullscreen mode

This line of code is about understanding how much information the PCA model is capturing as you add more components.

import numpy as np
cumvar = np.cumsum(pca_full.explained_variance_ratio_)

Enter fullscreen mode Exit fullscreen mode

Plotting a cumvar on 95% threshold.
You look for the point where the curve starts flattening (diminishing returns).

import matplotlib.pyplot as plt

plt.figure(figsize = (9,4))
plt.plot (cumvar, linewidth = 2)
plt.axhline(0.95, c = 'red', linestyle = '--', label = '95% threshold')
plt.axhline(0.99, c = 'orange', linestyle = '--', label = '99% threshold')
plt.xlabel('number of components')
plt.ylabel('cumulative explained variance')
plt.title('how many components to explain 95% of the variance')
plt.grid(alpha= 0.3)
plt.legend()
plt.show()

Enter fullscreen mode Exit fullscreen mode

Training

# fit pca on training only
pca_train = PCA(n_components=0.95)

X_train_r = pca_train.fit_transform(X_train)
X_test_r = pca_train.transform(X_test)

Enter fullscreen mode Exit fullscreen mode

Visualization
using the trained PCA model dimensions.

import matplotlib.pyplot as plt

plt.figure(figsize=(6,3))
scatter = plt.scatter(X_2d[:,0], X_2d[:,1], c = y, cmap = 'tab10', alpha=0.7, s = 20)
plt.colorbar(scatter, label = 'digit class')

plt.title('64-dimensional digit data projected to 2d via PCA')
plt.xlabel('PC1(highest variance direction)')
plt.ylabel('pc2(second highest variance direction)')
plt.show()

Enter fullscreen mode Exit fullscreen mode

Distributed Stochastic Neighbor Embedding (t-SNE)

t-SNE is a non-linear dimensionality reduction technique specifically designed for visualizing high-dimensional data in 2D or 3D spaces. It works by modelling focuses pairwise similarities between data points in the high-dimensional space and optimizing their representation in a lower-dimensional space to preserve these similarities.

Unlike PCA t-SNE focuses on maintaining local relationships by minimizing the Kullback–Leibler divergence (KL divergence) between the high-dimensional and low-dimensional distributions of data points making it highly effective to find clusters and patterns in complex datasets.
However it takes a lot of time to run the results and it doesn't work well with very large datasets.
t-SNE is primarily used for exploratory data analysis and visualization rather than feature reduction or pre processing.

Importing load digits from sklearn datasets.

from sklearn.datasets import load_digits
data = load_digits()

X = data.data
y = data.target

Enter fullscreen mode Exit fullscreen mode

Scaling data

# scaling data
from sklearn.preprocessing import StandardScaler
X_scaled = StandardScaler().fit_transform(X)

Enter fullscreen mode Exit fullscreen mode

Generating 1000 figures randomly for easy training from the scaled data.

import numpy as np
ids = np.random.choice(len(X_scaled),1000, replace=False)
X_sub, y_sub = X_scaled[ids], y[ids]

Enter fullscreen mode Exit fullscreen mode

Running t-sne.

from sklearn.manifold import TSNE
tsne = TSNE(n_components=2,
           perplexity=30,
           max_iter=1000,
           random_state=42,
)

X_tsne = tsne.fit_transform(X_sub)

Enter fullscreen mode Exit fullscreen mode

Visualization.

#plotting
import matplotlib.pyplot as plt
plt.figure(figsize= (10,7))
scatter = plt.scatter(X_tsne[:,0],X_tsne[:,1], c = y_sub,cmap='tab10',alpha=0.7, s=25)
cbar= plt.colorbar(scatter)
cbar.set_ticks(range(10))
cbar.set_ticklabels([str(i)for i in range(10)])
cbar.set_label('Digit class')

Enter fullscreen mode Exit fullscreen mode