PCA — মাত্রা কমানো
এই পাঠে যা শিখবেন
- PCA-এর geometric intuition — variance maximize directions
- Covariance matrix ও eigendecomposition
- SVD — modern computational পথ
- Explained variance ও scree plot — $k$ বাছাই
- scikit-learn ও NumPy দিয়ে hands-on; Bangladesh census data project
১ · কেন dimensionality reduction?
AI-তে আমরা প্রায়ই অনেক feature দিয়ে কাজ করি। একটি ছবি — ১৫০,০০০ pixel। একজন গ্রাহকের ১০০টি behavioral feature। কিন্তু এই feature-গুলো অনেক সময় redundantRedundant featureএকে অপরের সাথে strongly correlated feature — যেমন height ও arm-length। একটি থাকলেই অন্যটা অনেকটা predict করা যায়। ML মডেল-এ এই redundancy noise বাড়ায়। — height ও arm-length, income ও spending — দু'টোই প্রায় একই তথ্য।
PCA (Karl Pearson, ১৯০১; Hotelling, ১৯৩৩) — অনেক correlated feature থেকে কম, uncorrelated direction বের করে। ১০০টি feature-এর variance-এর ৯৫% যদি ২০টি direction-এই থাকে — বাকি ৮০টি ফেলে দাও। ডেটা ছোট, ML মডেল দ্রুত, noise কম।
Data যে দিকে সবচেয়ে বেশি ছড়ানো (variance maximum) — সেটাই প্রথম principal component (PC1)। PC1-এর সাথে orthogonal হয়ে variance maximize দ্বিতীয় দিক — PC2। এভাবে $d$ orthogonal direction। বেশিরভাগ variance প্রথম কয়টিতে — বাকি বাদ।
২ · Math — covariance ও eigenvector
Data matrix $\mathbf{X} \in \mathbb{R}^{n \times d}$ ($n$ sample, $d$ feature)। প্রথমে centering — প্রতিটি column-এর mean ০:
$$\tilde{\mathbf{X}} = \mathbf{X} - \bar{\mathbf{X}}$$
Covariance matrix:
$$\mathbf{C} = \frac{1}{n-1} \tilde{\mathbf{X}}^\top \tilde{\mathbf{X}} \in \mathbb{R}^{d \times d}$$
$\mathbf{C}$-এর eigendecomposition:
$$\mathbf{C} \mathbf{v}_i = \lambda_i \mathbf{v}_i$$
$\mathbf{v}_i$ — eigenvector (PC direction), $\lambda_i$ — eigenvalue (সেই direction-এ variance)। $\lambda_1 \geq \lambda_2 \geq \ldots \geq \lambda_d$ — descending sort।
$k$ component-এ projection: $\mathbf{X}_{\text{new}} = \tilde{\mathbf{X}} \mathbf{V}_k$, যেখানে $\mathbf{V}_k$ = top-$k$ eigenvector।
৩ · SVD — preferred computational path
Covariance matrix বানিয়ে eigendecomposition — numerically unstable, $d$ বড় হলে ($d = 10000$) memory issue। বদলে — directly $\tilde{\mathbf{X}}$-এর SVD:
$$\tilde{\mathbf{X}} = \mathbf{U} \boldsymbol{\Sigma} \mathbf{V}^\top$$
$\mathbf{V}$-এর column = eigenvector of $\tilde{\mathbf{X}}^\top \tilde{\mathbf{X}}$ = PC direction। $\boldsymbol{\Sigma}$-এর diagonal = singular value = $\sqrt{(n-1) \lambda_i}$।
sklearn-এর PCA ভেতরে SVD ব্যবহার — randomized SVD ($n, d$ বড় হলে)। আপনাকে এটা বুঝতে হবে না, কিন্তু "SVD = PCA-এর computational backbone" — এই connection মনে রাখুন।
৪ · Explained variance ও $k$ বাছাই
প্রতিটি component-এর "explained variance ratio":
$$r_i = \frac{\lambda_i}{\sum_j \lambda_j}$$
Cumulative — $r_1 + r_2 + \ldots + r_k$ যত percent of total variance retain। Common rules:
- Cumulative threshold: ৯৫% retain — সেই $k$।
- Scree plot: eigenvalue-গুলো descending plot — "elbow" যেখানে।
- Kaiser criterion: $\lambda_i > 1$ (standardized data-তে) component রাখুন।
- Domain-driven: visualization-এ $k=2$ বা ৩।
৫ · Standardization কেন অপরিহার্য
Income (BDT, scale ১০⁵) ও age (year, scale ১০) — variance income-এ অনেক বেশি। PCA variance বেশি যেদিকে — সেই দিকেই ছুটে যাবে, age-এর কোনো contribution থাকবে না। তাই — সবসময় StandardScaler (mean ০, std ১) PCA-এর আগে।
৬ · sklearn-এ PCA — Bangladesh census
৬৪টি জেলার ১০টি socio-economic indicator-এর synthetic data — PCA দিয়ে ২-D-তে নিয়ে আসি।
import numpy as np
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
np.random.seed(0)
n_districts, n_features = 64, 10
# 10 indicator: GDP, literacy, poverty, urbanization, mortality,
# electricity, sanitation, female_employment, internet, road_density
X = np.random.randn(n_districts, n_features)
# scaling — অপরিহার্য
X_s = StandardScaler().fit_transform(X)
pca = PCA()
X_p = pca.fit_transform(X_s)
print("Explained variance ratio:")
for i, r in enumerate(pca.explained_variance_ratio_, 1):
print(f" PC{i}: {r:.3f}")
print(f"\nCumulative @ PC2: {pca.explained_variance_ratio_[:2].sum():.3f}")
print(f"Cumulative @ PC5: {pca.explained_variance_ratio_[:5].sum():.3f}")
# 2D-এ project
pca_2 = PCA(n_components=2)
X_2 = pca_2.fit_transform(X_s)
print(f"\nShape after PCA: {X_2.shape}")
৭ · NumPy দিয়ে scratch implementation
import numpy as np
def pca_scratch(X, k):
# 1. center
Xc = X - X.mean(axis=0)
# 2. covariance
C = (Xc.T @ Xc) / (len(X) - 1)
# 3. eigendecomposition
eigvals, eigvecs = np.linalg.eigh(C)
# eigh ascending → reverse
idx = eigvals.argsort()[::-1]
eigvals, eigvecs = eigvals[idx], eigvecs[:, idx]
# 4. project on top-k eigenvectors
return Xc @ eigvecs[:, :k], eigvals
X = np.random.randn(100, 5)
X_p, evals = pca_scratch(X, k=2)
print(f"Projected shape: {X_p.shape}")
print(f"Eigenvalues: {evals.round(3)}")
print(f"Explained ratio: {(evals / evals.sum()).round(3)}")
np.linalg.eigh symmetric matrix-এর জন্য optimized। sklearn-এর PCA এর সাথে result match করবে (sign-difference হতে পারে — eigenvector-এর arbitrary sign)।
৮ · PCA-এর বাস্তব প্রয়োগ
- Image compression: ১০০×১০০ pixel = ১০K-D → PCA → ৫০-D, ৯৫% variance preserved।
- Speedup: KNN, K-Means high-D-এ slow → PCA → ১০-D → fast।
- Visualization: high-D data-এর ২-D scatter — interpretation-এ unmissable।
- Multicollinearity removal: regression-এ correlated feature-এর problem PCA-তে দূর।
- Noise reduction: low-variance component noise — discard করে signal বাঁচান।
- Eigenfaces: face recognition-এর প্রথম breakthrough (Turk-Pentland, ১৯৯১)।
৯ · PCA-এর সীমাবদ্ধতা
- Linear: non-linear manifold (swiss roll, sphere) flatten করতে পারে না। তখন kernel PCA, t-SNE, UMAP, autoencoder।
- Variance ≠ importance: high-variance feature class-এর জন্য discriminative না হতে পারে। Supervised হলে — LDA।
- Outlier sensitive: outlier covariance matrix বিকৃত। Robust PCA বিকল্প।
- Interpretability: PC = original feature-এর linear combo — শুনতে magic-এর মত।
ভাবনার প্রশ্ন
প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।
প্র ০১ PCA "variance maximize" — কিন্তু classification task-এ class separability matter। PCA কখন discriminative information হারিয়ে দেয়?
চমৎকার question — supervised vs unsupervised dim-reduction-এর মূল contrast।
PCA-এর objective:
- Total variance retain — যেদিকে data সবচেয়ে spread।
- Class label সম্পূর্ণ ignore।
- Unsupervised।
চিত্রিত counter-example:
- 2D data — class A horizontal line-এ ছড়ানো (high variance but)।
- Class B vertical small spread।
- দু'টি class only vertical-এ আলাদা — small variance।
- PCA — horizontal axis (PC1) — variance বেশি — কিন্তু এখানে class indistinguishable।
- Vertical axis (PC2) — সব discrimination — কিন্তু low variance, discard হবে।
ফলস্বরূপ:
- Top-1 PC-এ সব class merge — classifier accuracy ০।
- "PCA cleared noise" — actually cleared signal।
Solution: LDA (Linear Discriminant Analysis):
- Supervised counterpart।
- Within-class variance / between-class variance maximize।
- Discriminative direction খোঁজে।
- sklearn-এ
LinearDiscriminantAnalysis।
কখন PCA ভাল classification-এ:
- High-variance direction-গুলোই class-discriminative।
- Sample size ছোট, feature বেশি — PCA overfitting কমায়।
- Noise high — variance retain = signal retain।
- Pure visualization দরকার — class label later overlay।
কখন PCA ভুল:
- Class spread ছোট কিন্তু important।
- Noise high-variance, signal low-variance।
- Sample size যথেষ্ট, supervised possible।
Hybrid:
- PCA → LDA — first noise reduce, then discriminate।
- PCA-LDA pipeline classical face recognition-এ।
- Modern alternative — supervised autoencoder, contrastive learning।
Bangladesh case:
- Disease diagnosis (X-ray TB vs healthy) — PCA may discard subtle abnormality। LDA বা CNN feature better।
- Loan default classification — variance + supervision both useful। PCA → logistic, or LDA direct।
মূল উপলব্ধি: PCA "feature engineering for unknown task"। Classification task জানলে — supervised methods। Don't blindly PCA before classifier।
প্র ০২ SVD ও eigendecomposition — কখন কোনটা ব্যবহার? Numerical stability-এর সম্পর্ক?
সংযোগটি গভীর। PCA implement করতে হলে দু'পথ আছে।
Eigendecomposition path:
- $\mathbf{X}$ center।
- $\mathbf{C} = \frac{1}{n-1} \mathbf{X}^\top \mathbf{X}$ compute।
- $\mathbf{C}$-এর eigendecomposition।
- Top-$k$ eigenvector।
SVD path:
- $\mathbf{X}$ center।
- $\mathbf{X} = \mathbf{U} \boldsymbol{\Sigma} \mathbf{V}^\top$।
- $\mathbf{V}$-এর top-$k$ column = PC direction।
Numerical stability — eigendecomposition-এর সমস্যা:
- $\mathbf{X}^\top \mathbf{X}$ — condition number $\mathbf{X}$-এর square।
- $\mathbf{X}$-এর small singular value — squaring এ আরও tiny।
- Floating-point precision-এ vanish।
- "Catastrophic cancellation" — small but important component হারায়।
SVD-এর advantage:
- $\mathbf{X}$ সরাসরি decompose, $\mathbf{X}^\top \mathbf{X}$ avoid।
- Singular value precise।
- Numerically stable।
Computational cost:
- Eigen of $\mathbf{X}^\top \mathbf{X}$ — $O(d^3)$ + $O(nd^2)$ for $\mathbf{X}^\top\mathbf{X}$।
- Full SVD — $O(\min(n^2 d, n d^2))$।
- Truncated/randomized SVD — $O(ndk)$ — much faster, $k$ small।
কখন কোনটা:
- Eigendecomposition: $d$ small ($<100$), মুখস্ত exposition।
- Full SVD: $n$ ও $d$ moderate (numpy default)।
- Randomized SVD: bigtech-scale, $k \ll d$, sklearn default for big matrices।
- Sparse SVD (ARPACK): sparse matrix (text TF-IDF)।
sklearn-এর strategy:
- $d \leq n$, small data — full SVD।
- $d$ বড় বা $n$ বড় — randomized SVD।
- Sparse — TruncatedSVD।
- সব এক unified API।
Modern alternative:
- Iterative power method — top-$k$ component।
- Online/streaming PCA — IPCA।
- GPU SVD — cuSOLVER, cuML।
মূল উপলব্ধি: Math-এ eigen ও SVD equivalent — কিন্তু numerical implementation-এ SVD superior। Production-এ blindly SVD-based PCA — sklearn এটাই করে।
প্র ০৩ Image compression-এ PCA — JPEG-এর সাথে compare? কেন JPEG দাঁড়িয়ে আছে?
চমৎকার practical comparison। দু'টিই lossy compression — কিন্তু philosophy ভিন্ন।
PCA-based image compression:
- Image dataset-এ PCA — eigenfaces বা eigen-image।
- প্রতিটি image — top-$k$ PC-এর coefficient।
- Storage = $k$ float per image।
- Reconstruction = $k$ PC × coefficient।
JPEG compression:
- Image-কে ৮×৮ block-এ ভাগ।
- প্রতিটি block-এ DCT (Discrete Cosine Transform)।
- High-frequency coefficient discard/quantize।
- Huffman encoding।
মূল পার্থক্য:
(১) Basis choice:
- PCA — data-driven, dataset-specific basis।
- JPEG (DCT) — fixed cosine basis, universal।
(২) Generality:
- PCA — train করতে হবে; new image domain-এ retrain।
- JPEG — যেকোনো image-এ apply।
(৩) Local vs global:
- JPEG block-wise — local adaptive।
- PCA full-image — global structure।
(৪) Perceptual quality:
- JPEG — human visual system-এর perceptual model integrate (chroma subsampling)।
- PCA — pure MSE — perceptually inferior।
(৫) Storage efficiency:
- JPEG entropy coding — bit allocation efficient।
- PCA — float32 coefficient — verbose।
JPEG কেন winner:
- Universal — model অমেরিকা, ছবি বাংলাদেশের — same JPEG decoder।
- Hardware acceleration ubiquitous।
- Standard since 1992।
- Perceptual optimization built-in।
PCA-এর জায়গা:
- Dataset-specific compression — face database, satellite image।
- Feature extraction (downstream ML), pure compression নয়।
- Eigenfaces — ৩০ component-এ thousands of face represent।
Modern landscape:
- JPEG → JPEG 2000 (wavelet)।
- WebP, AVIF — better than JPEG।
- Neural compression (Ballé, ২০১৭+) — PCA's spiritual successor + perceptual loss।
- Stable Diffusion latent — perceptual + generative compression।
মূল উপলব্ধি: PCA general-purpose dim-reduction। JPEG specialized image compression — perceptual + standardization. Compression battle universal codec wins; PCA unique dataset-এ value।
প্র ০৪ Bangladesh-এর ৬৪টি জেলার ৫০টি socio-economic indicator — PCA করে regional pattern বের করতে চান। কী challenges? Pipeline ডিজাইন।
Real Bangladesh policy research — BBS, BRAC Institute-এর জাতীয় relevance।
(১) Data sources:
- BBS census, HIES survey।
- HDI report।
- UNDP Bangladesh Atlas।
- Education Ministry, Health Ministry indicators।
(২) Feature categories:
- Economic: GDP/capita, employment, agriculture %, industry %।
- Education: literacy, primary completion, tertiary %।
- Health: infant mortality, maternal health, nutrition।
- Infrastructure: electricity, sanitation, road density, internet।
- Social: female employment, gender index, poverty।
(৩) Preprocessing:
- Missing impute — district-region median।
- Skewed feature — log transform (GDP, income)।
- StandardScaler — অপরিহার্য।
- Outlier detect — Dhaka extreme high (cap বা separate analysis)।
(৪) PCA application:
- Full PCA → all 50 components।
- Scree plot — explained variance।
- Top-3 PC সম্ভবত interpretable: development, health, gender।
- Cumulative ৯৫% — সম্ভবত ১০-১৫ component।
(৫) PC interpretation:
- Loading matrix — কোন original feature কোন PC-তে dominant।
- PC1 likely "overall development" — সব positive indicator high।
- PC2 — sectoral (industry vs agriculture)।
- PC3 — gender dimension।
- Domain expert qualitative naming।
(৬) Visualization:
- PC1 vs PC2 scatter — district label।
- Color by region (Dhaka, Chittagong, Sylhet, Rajshahi)।
- Outlier district highlight।
- Time-series — over decade development trajectory।
(৭) Clustering on PC space:
- Top-5 PC-এ K-Means বা hierarchical।
- ৩-৫ regional cluster।
- Policy targeting — cluster-specific intervention।
(৮) Validation:
- Independent dataset (next census) — cluster persist?
- Domain expert agreement।
- Bootstrap stability।
(৯) Communication:
- Policy maker — interpretable PC, not eigenvalue jargon।
- Visual map — color-coded district।
- "Tier 1 developed", "Tier 2 emerging", "Tier 3 lagging" — naming।
(১০) Ethical considerations:
- "Lagging" stigma avoid।
- Religion, ethnicity-based feature exclude।
- Equity-oriented framing।
(১১) Action items:
- Resource allocation cluster-wise।
- Best-practice transfer (well-doing district → similar cluster)।
- Targeted scheme (e.g., women's literacy in low-PC2)।
- Annual update।
মূল উপলব্ধি: Real Bangladesh policy ML — PCA brilliant exploratory tool, কিন্তু interpretation domain-driven, not algorithmic। Statistical insight policy direction-এ translate — সেটাই challenge।
অনুশীলন
-
হিসাব করুন: 2D data: $\mathbf{X} = \begin{pmatrix} 1 & 1 \\ 2 & 2 \\ 3 & 3 \end{pmatrix}$। Centered, covariance, eigenvalue?
- Mean = (2, 2), centered: ((-1,-1), (0,0), (1,1))।
- Covariance: $\frac{1}{2}\begin{pmatrix} 2 & 2 \\ 2 & 2 \end{pmatrix} = \begin{pmatrix} 1 & 1 \\ 1 & 1 \end{pmatrix}$।
- Eigenvalue: $\lambda_1 = 2$ (direction $(1,1)/\sqrt{2}$), $\lambda_2 = 0$ (direction $(1,-1)/\sqrt{2}$)।
- Explained: PC1 ১০০%, PC2 ০% — data perfectly 1D।
-
NumPy-তে চেষ্টা: Random 100×5 data PCA → 2D, variance retained কত?
import numpy as np from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler X = np.random.randn(100, 5) X_s = StandardScaler().fit_transform(X) pca = PCA(n_components=2) X_p = pca.fit_transform(X_s) print(f"Shape: {X_p.shape}") print(f"Explained: {pca.explained_variance_ratio_.sum():.3f}") # Random data-এ ~40% (uniform spread)। Real data-এ অনেক বেশি। -
ভাবুন: ২২৪×২২৪ RGB ছবি = ১৫০,৫২৮-D। PCA-এর strength-weakness কী এই scale-এ? Modern alternative?
- Strength: linear, deterministic, fast (randomized SVD)।
- Weakness: ১৫০K × ১৫০K covariance impossible — computational।
- Workaround: randomized SVD top-৫০ component।
- Quality: face image — eigenfaces ভাল; natural image — limited।
- Linear limit: rotation, scaling — non-linear, PCA struggle।
- Modern: CNN feature (ResNet pretrained) → ৫১২-D dense vector — much better।
- Production: CLIP embedding, autoencoder latent।
- PCA — historical brilliant; modern image-এ neural superior।
আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ
- পাঠ ৩৫ · t-SNE ও UMAP পরবর্তী পাঠ Non-linear dim-reduction — PCA-র limit যেখানে।
- পাঠ ৩৩ · DBSCAN আগের পাঠ PCA-এর পর প্রায়ই — DBSCAN দিয়ে cluster।
- পাঠ ১৫ · Ridge ও Lasso এই পাঠের সাথে সম্পর্কিত Multicollinearity — PCA-এর সাথে regularization-এর alternative।
- সব AI Courses ABCL TECH Python, ML, DL, NLP, CV, GenAI, RL, MLOps।