Machine Learning 📂 Dimensionality reduction · 1 of 3 254 min read

Principal Component Analysis (PCA)

PCA is a linear technique that rotates your data into a new coordinate system where the first axis captures the most variance, the second axis captures the next most, and so on — letting you keep 95 % of the information with a fraction of the original features.

🌐
SectionSection第 01 节

The Story That Explains PCAवह कहानी जो PCA समझाती है一个解释 PCA 的故事

The Shadow on the Wallदीवार पर परछाई墙上的影子
Hold a bent piece of wire in front of a torch. Its shadow on the wall is a 2-D picture of a 3-D object. From some angles the shadow is wide and clear: you can almost rebuild the wire from it. From other angles it collapses into a small, confusing blob.

PCA is an algorithm that finds the best torch angle automatically. "Best" means the shadow keeps as much of the spread (variance) of the data as possible.

In practice: you have a table with 50 columns. PCA finds the 2 or 3 best "angles" (principal components), so you can plot the data or train a model on it without losing much detail.
Torch के सामने एक मुड़ा हुआ तार पकड़ें। दीवार पर उसकी परछाई एक 3-D चीज़ की 2-D तस्वीर है। कुछ कोणों से परछाई चौड़ी और साफ़ होती है: आप उससे तार को लगभग दोबारा बना सकते हैं। दूसरे कोणों से वह एक छोटे, उलझे धब्बे में सिमट जाती है।

PCA एक algorithm है जो torch का सबसे अच्छा कोण अपने आप खोजता है। "सबसे अच्छा" का मतलब है कि परछाई data के फैलाव (variance) का जितना हो सके उतना हिस्सा बचाए।

असल में: आपके पास 50 columns वाली table है। PCA सबसे अच्छे 2 या 3 "कोण" (principal components) खोजता है, ताकि आप data को plot कर सकें या उस पर model train कर सकें, बिना ज़्यादा जानकारी खोए।
把一根弯曲的铁丝放在手电筒前。它在墙上的影子是一个三维物体的二维图像。从某些角度看,影子又宽又清楚,几乎可以凭它还原铁丝;从另一些角度看,它会缩成一小团,让人看不明白。

PCA 就是一个自动寻找最佳手电筒角度的算法。"最佳"的意思是:影子要尽可能多地保留数据的散布(方差)。

实际应用中:你有一张 50 列的表。PCA 找出最好的 2 到 3 个"角度"(主成分),让你可以画图或训练 model,而不会丢失太多细节。

Principal Component Analysis (PCA) is an unsupervised, linear method. It does not look at labels. It describes the same data in a new set of axes, called principal components, sorted by how much variance each one explains. PC1 is the direction of the largest spread. PC2 is the direction of the largest remaining spread that is at 90° to PC1, and so on.

Principal Component Analysis (PCA) एक unsupervised, linear तरीका है। यह labels नहीं देखता। यह उसी data को नए axes में लिखता है, जिन्हें principal components कहते हैं, और उन्हें इस क्रम में रखता है कि हर एक कितना variance समझाता है। PC1 सबसे बड़े फैलाव की दिशा है। PC2 बचे हुए सबसे बड़े फैलाव की दिशा है जो PC1 से 90° पर हो, और इसी तरह आगे।

主成分分析(PCA)是一种无监督的线性方法,它不看标签。它用一组新的坐标轴来描述同样的数据,这些轴叫作主成分,并按每个轴解释的方差大小排序。PC1 是散布最大的方向;PC2 是与 PC1 成 90° 的方向中散布最大的;依此类推。

💡
One-Line Definitionएक line में परिभाषा一句话定义

PCA rotates your data into new axes that point along the directions of maximum variance, sorted from most to least, so you can drop the last few axes and lose very little.

PCA आपके data को नए axes में घुमाता है जो सबसे ज़्यादा variance की दिशाओं में होते हैं, ज़्यादा से कम के क्रम में, ताकि आप आख़िरी कुछ axes हटा सकें और बहुत कम खोएँ।

PCA 把数据旋转到新的坐标轴上,这些轴沿着方差最大的方向,从大到小排列,所以去掉最后几个轴只会损失很少的信息。


SectionSection第 02 节

PCA in Pictures — Understand It Before Any Mathsतस्वीरों में PCA — गणित से पहले समझें图解 PCA — 先理解,再学数学

Forget formulas for a moment. PCA does one simple job: it replaces many columns with a few new columns, and keeps as much information as possible. The four pictures below show how.

एक पल के लिए formulas भूल जाइए। PCA एक सरल काम करता है: यह बहुत सारे columns की जगह कुछ नए columns रखता है, और जितनी हो सके उतनी जानकारी बचाता है। नीचे की चार तस्वीरें दिखाती हैं कि कैसे।

先忘掉公式。PCA 只做一件简单的事:用少数几个新列代替很多列,同时尽量多地保留信息。下面四张图告诉你它是怎么做到的。

🖼️ PICTURE 1 — PCA IN ONE PICTUREतस्वीर 1 — एक तस्वीर में PCA图 1 — 一张图看懂 PCA
PCA in one picture BEFORE: 8 columnsपहले: 8 columns之前:8 列 many columns, much of it repeatedबहुत columns, काफ़ी दोहराव很多列,大量重复 PCA finds new directionsनई दिशाएँ खोजता है找到新的方向 keeps the top ktop k रखता है保留前 k 个 AFTER: 2 new columnsबाद में: 2 नए columns之后:2 个新列 PC1PC2 same rows, far fewer columnsवही rows, बहुत कम columns行数不变,列少了很多 keepsबचाता है保留 ~95% of the infoजानकारी的信息 Each new column is a mix (a "recipe") of all the old columns.हर नया column सभी पुराने columns का मेल (एक "recipe") है।每个新列都是所有旧列的混合(一个"配方")。

The rows (people, images, products) stay the same. Only the columns change: many old ones in, a few new ones out.

Rows (लोग, images, products) वही रहती हैं। सिर्फ़ columns बदलते हैं: बहुत पुराने अंदर, कुछ नए बाहर।

行(人、图片、商品)保持不变,只有列变了:进去很多旧列,出来少数新列。

LIVELIVE互动Picture 2 — The Torch, the Airplane and the Shadowतस्वीर 2 — Torch, Airplane और परछाई图 2 — 手电筒、飞机和影子

A 3-D toy airplane made of 138 dots. The torch throws its shadow on a wall. The wall is flat (2-D), so one dimension is lost. Press the buttons and look at the wall: from which side is the shadow still clearly an airplane?

138 dots से बना एक 3-D खिलौना airplane. Torch उसकी परछाई दीवार पर डालता है। दीवार सपाट (2-D) है, इसलिए एक dimension खो जाता है। Buttons दबाएँ और दीवार देखें: किस तरफ़ से परछाई अब भी साफ़ airplane दिखती है?

一架由 138 个点组成的三维玩具飞机。手电筒把它的影子投到墙上。墙是平的(二维),所以丢失了一个维度。点击按钮,看墙上的影子:从哪个方向照,影子仍然清楚地像一架飞机?

Shadow keepsपरछाई रखती है影子保留了
—

💡
This Is Exactly What PCA DoesPCA ठीक यही करता है这正是 PCA 做的事

Your data is the airplane. Each column is one dimension. The shadow is the smaller table you keep. PCA tries every torch angle (with maths, not by hand) and picks the one whose shadow keeps the most spread. Here the best shadow keeps about 98% of the spread, so 2 numbers per dot are almost as good as 3. Real data may have 50 or 1,000 dimensions instead of 3, but the idea is the same.

आपका data airplane है। हर column एक dimension है। परछाई वह छोटी table है जो आप रखते हैं। PCA हर torch कोण आज़माता है (गणित से, हाथ से नहीं) और वह चुनता है जिसकी परछाई सबसे ज़्यादा फैलाव रखे। यहाँ सबसे अच्छी परछाई लगभग 98% फैलाव रखती है, इसलिए हर dot के लिए 2 numbers लगभग 3 जितने अच्छे हैं। असली data में 3 की जगह 50 या 1,000 dimensions हो सकते हैं, पर विचार वही है।

你的数据就是这架飞机,每一列是一个维度,影子就是你保留下来的那张更小的表。PCA 会尝试所有手电筒角度(用数学,不是手动),选出影子保留散布最多的那个。这里最佳影子保留了约 98% 的散布,所以每个点用 2 个数几乎和用 3 个数一样好。真实数据可能有 50 或 1,000 个维度而不是 3 个,但道理完全一样。

LIVELIVE互动Picture 3 — Zip and Unzip a Tableतस्वीर 3 — Table को Zip और Unzip करें图 3 — 压缩和解压一张表

Watch PCA turn a 2-column table into a 1-column table, and then rebuild it. Press Play, or use Next and Back.

देखें कि PCA कैसे 2-column table को 1-column table बनाता है, और फिर उसे दोबारा बनाता है। Play दबाएँ, या आगे और पीछे इस्तेमाल करें।

看 PCA 如何把一张两列的表变成一列,然后再还原。点击播放,或使用"下一步/上一步"。

Picture 4 — The PCA Words, in Picturesतस्वीर 4 — PCA के शब्द, तस्वीरों में图 4 — 用图片解释 PCA 术语

Six words appear again and again in PCA. Here is what each one means in plain language.

PCA में छह शब्द बार-बार आते हैं। यहाँ हर एक का सरल मतलब है।

PCA 中有六个词反复出现。下面用大白话解释每一个。

d = 5
DimensionDimension维度
= a column= एक column= 一列
One feature, one column. A table with 50 columns lives in 50 dimensions. PCA wants to use fewer.
एक feature, एक column. 50 columns वाली table 50 dimensions में रहती है। PCA कम इस्तेमाल करना चाहता है।
一个特征就是一列。有 50 列的表就生活在 50 维空间中。PCA 想用更少的维度。
VarianceVariance方差
= spread = information= फैलाव = जानकारी= 散布 = 信息
How spread out the values are. If everybody has the same value, the column tells you nothing. Spread is the information PCA tries to keep.
Values कितनी फैली हैं। अगर सबकी value एक जैसी है, तो column कुछ नहीं बताता। फैलाव ही वह जानकारी है जिसे PCA बचाना चाहता है।
数值有多分散。如果每个人的值都一样,这一列就没有任何信息。散布就是 PCA 想要保留的信息。
PC1
Principal componentPrincipal component主成分
= a new direction= एक नई दिशा= 一个新方向
A new axis drawn through the data. PC1 follows the longest side of the cloud. PC2 is at 90° to it, and so on.
Data के बीच से खींचा गया एक नया axis. PC1 cloud की सबसे लंबी तरफ़ चलता है। PC2 उससे 90° पर है, और इसी तरह आगे।
穿过数据画出的一条新坐标轴。PC1 沿着点云最长的方向;PC2 与它成 90°,依此类推。
+12.3
ScoreScore得分
= the new value of a row= row की नई value= 一行的新数值
Where a row lands on a new axis. These scores are the new, smaller table you give to your model or your plot.
नए axis पर कोई row कहाँ आती है। ये scores ही नई, छोटी table हैं जो आप model या plot को देते हैं।
某一行落在新坐标轴上的位置。这些得分就是交给 model 或用来画图的新的、更小的表。
0.660.75
LoadingLoading载荷
= the recipe= recipe= 配方
How much of each old column goes into a new one. PC1 = 0.66 × Maths + 0.75 × Physics is a recipe. Big weight = that column matters a lot.
हर पुराने column का कितना हिस्सा नए में जाता है। PC1 = 0.66 × Maths + 0.75 × Physics एक recipe है। बड़ा weight = वह column बहुत मायने रखता है।
每个旧列有多少进入新列。PC1 = 0.66 × 数学 + 0.75 × 物理 就是一个配方。权重大 = 这一列很重要。
85%
Explained variance ratioExplained variance ratio解释方差比
= share of info kept= बची जानकारी का हिस्सा= 保留信息的比例
What share of the total spread one component holds. Add them up for the components you keep: "2 PCs keep 85%".
कुल फैलाव का कितना हिस्सा एक component में है। जो components रखें उनका जोड़ लें: "2 PCs 85% रखते हैं"।
一个主成分占总散布的比例。把保留的主成分加起来:比如"2 个 PC 保留了 85%"。

The Same Idea in 2-D, With Numbers2-D में वही विचार, Numbers के साथ同样的想法:二维 + 数字

LIVELIVE互动Find the Best Torch AngleTorch का सबसे अच्छा कोण खोजें寻找最佳手电筒角度

Drag on the picture (or use the slider) to turn the amber line. Amber dots are the "shadows" of the data on the line. Red lines show what each point loses. Watch the two bars: when one goes up, the other goes down.

Amber line घुमाने के लिए picture पर drag करें (या slider इस्तेमाल करें)। Amber dots line पर data की "परछाइयाँ" हैं। लाल lines दिखाती हैं कि हर point क्या खोता है। दोनों bars देखें: एक बढ़ती है तो दूसरी घटती है।

在图上拖动(或使用滑块)来转动琥珀色直线。琥珀色小点是数据在直线上的"影子",红线表示每个点丢失的部分。注意两个进度条:一个上升,另一个就下降。

Spread keptबचा फैलाव保留的散布
—
Lostखोया丢失
—

🎯
Two Ways to Say the Same Thingएक ही बात के दो रूप同一件事的两种说法

For every point, (distance² along the line) + (distance² to the line) = (distance² to the centre). This is Pythagoras. The total is fixed, so maximising the kept variance and minimising the reconstruction error give the same line. That is why PCA is both "the best view" and "the best compression".

हर point के लिए, (line के साथ दूरी²) + (line तक दूरी²) = (केंद्र तक दूरी²)। यह Pythagoras है। कुल जोड़ तय है, इसलिए बचा variance सबसे ज़्यादा करना और reconstruction error सबसे कम करना एक ही line देते हैं। इसीलिए PCA "सबसे अच्छा view" भी है और "सबसे अच्छा compression" भी।

对每个点来说,(沿直线距离²)+(到直线距离²)=(到中心距离²),这就是勾股定理。总量固定,所以最大化保留的方差和最小化重建误差得到的是同一条直线。这就是为什么 PCA 既是"最佳视角",也是"最佳压缩"。

Where Is PCA Used in Real Life?असली दुनिया में PCA कहाँ इस्तेमाल होता है?现实生活中哪里用到 PCA?

👤
Face recognitionचेहरा पहचानना人脸识别
"eigenfaces""eigenfaces""特征脸"
A 100×100 face photo has 10,000 pixel columns. PCA finds about 100 "face ingredients" (eigenfaces). Each face becomes 100 numbers, which is much faster to compare.
100×100 की face photo में 10,000 pixel columns होते हैं। PCA लगभग 100 "चेहरे के ingredients" (eigenfaces) खोजता है। हर चेहरा 100 numbers बन जाता है, जिनकी तुलना बहुत तेज़ होती है।
一张 100×100 的人脸照片有 10,000 个像素列。PCA 找出约 100 个"人脸成分"(特征脸),每张脸变成 100 个数,比较起来快得多。
📝
SurveysSurveys问卷调查
30 questions → 3 themes30 सवाल → 3 विषय30 道题 → 3 个主题
Customers answer 30 questions. Many answers move together. PCA shows they really measure about 3 things, such as price, quality and service.
Customers 30 सवालों के जवाब देते हैं। कई जवाब साथ-साथ बदलते हैं। PCA दिखाता है कि असल में वे लगभग 3 चीज़ें मापते हैं, जैसे कीमत, quality और service.
顾客回答 30 道题,很多答案同涨同跌。PCA 显示它们其实只在衡量大约 3 件事,比如价格、质量和服务。
🌍
GeneticsGenetics遗传学
thousands of genes → a mapहज़ारों genes → एक नक्शा成千上万个基因 → 一张地图
Plot people by PC1 and PC2 of their DNA markers, and groups from different regions form clusters that often look like a map of where they come from.
लोगों को उनके DNA markers के PC1 और PC2 से plot करें, तो अलग-अलग इलाक़ों के groups clusters बनाते हैं जो अक्सर उनके मूल स्थान के नक्शे जैसे दिखते हैं।
用 DNA 标记的 PC1 和 PC2 给人画图,来自不同地区的人群会形成聚类,常常看起来像一张他们来源地的地图。
📈
Stock marketStock market股票市场
"the market factor""market factor""市场因子"
Daily returns of 500 stocks move together a lot. PC1 is roughly "the whole market going up or down". Risk teams use the top PCs to see hidden common risks.
500 stocks के रोज़ के returns काफ़ी साथ-साथ चलते हैं। PC1 मोटे तौर पर "पूरा market ऊपर या नीचे" है। Risk teams छिपे साझा risks देखने के लिए top PCs इस्तेमाल करती हैं।
500 只股票的日收益经常同涨同跌。PC1 大致就是"整个市场在涨或跌"。风控团队用前几个 PC 找出隐藏的共同风险。
🏭
Sensors and machinesSensors और machines传感器与机器
spot unusual behaviourअसामान्य व्यवहार पकड़ना发现异常
A machine has 40 sensors. PCA learns the normal pattern. When a new reading cannot be rebuilt well from the top PCs, something unusual is happening.
एक machine में 40 sensors हैं। PCA सामान्य pattern सीखता है। जब कोई नई reading top PCs से ठीक से दोबारा नहीं बनती, तो कुछ असामान्य हो रहा है।
一台机器有 40 个传感器。PCA 学习正常的模式。当新读数无法用前几个 PC 很好地重建时,说明出现了异常。
🖼️
Image compressionImage compression图像压缩
store less, see almost the sameकम रखें, लगभग वैसा ही देखें存得更少,看起来几乎一样
Keep only the top components of an image and rebuild it. You saw this with the handwritten digits: about 10 of 64 numbers already give a readable digit.
Image के सिर्फ़ top components रखें और उसे दोबारा बनाएँ। आपने इसे हाथ से लिखे digits में देखा: 64 में से लगभग 10 numbers से ही digit पढ़ने लायक हो जाता है।
只保留图像的前几个主成分再重建。你在手写数字里已经看到了:64 个数中大约 10 个就能得到可辨认的数字。

SectionSection第 03 节

Why Dimensionality Reduction MattersDimensionality Reduction क्यों ज़रूरी है为什么降维很重要

Modern datasets can have hundreds or thousands of features. More features sounds better, but past a point it causes three real problems:

आज के datasets में सैकड़ों या हज़ारों features हो सकते हैं। ज़्यादा features अच्छा लगता है, पर एक हद के बाद इससे तीन असली समस्याएँ आती हैं:

现代数据集可能有成百上千个特征。特征越多听起来越好,但超过一定程度就会带来三个实际问题:

📊
The Curse of DimensionalityCurse of Dimensionality维度灾难
space becomes emptyspace ख़ाली हो जाता है空间变得空旷
The space grows very fast with each new dimension, so the same number of points covers it more and more thinly. Distances between points also become almost equal (try the simulator below). Distance-based models like k-NN suffer most, and every model needs more data to learn the same pattern.
हर नए dimension के साथ space बहुत तेज़ी से बढ़ता है, इसलिए उतने ही points उसे और पतला ढकते हैं। Points के बीच की दूरियाँ भी लगभग बराबर हो जाती हैं (नीचे simulator आज़माएँ)। k-NN जैसे distance-based models को सबसे ज़्यादा नुकसान होता है, और हर model को वही pattern सीखने के लिए ज़्यादा data चाहिए।
每多一个维度,空间就增长得非常快,同样数量的点覆盖得越来越稀疏。点与点之间的距离也变得几乎相等(试试下面的模拟器)。k-NN 这类基于距离的 model 受影响最大,而且每个 model 都需要更多数据才能学到同样的规律。
⏱
Computational CostComputation की कीमत计算成本
time and memorytime और memory时间和内存
Memory and training time grow with the number of features. Some steps grow faster than linearly (a covariance matrix has d² cells). Fewer features can make large problems much cheaper. On small data, as in our digits test below, the gain can be close to zero.
Memory और training time features की संख्या के साथ बढ़ते हैं। कुछ steps linear से तेज़ बढ़ते हैं (covariance matrix में d² cells होते हैं)। कम features बड़ी problems को बहुत सस्ता बना सकते हैं। छोटे data पर, जैसे नीचे हमारे digits test में, फ़ायदा लगभग zero हो सकता है।
内存和训练时间随特征数量增长,有些步骤增长得比线性更快(协方差矩阵有 d² 个元素)。减少特征能让大规模问题便宜很多。但在小数据上(比如下面的手写数字例子),收益可能接近于零。
👁
VisualisationVisualisation可视化
humans see 2-D and 3-Dइंसान 2-D और 3-D देखते हैं人只能看二维和三维
You cannot plot 64 pixel columns directly. Projecting onto 2 principal components lets you scatter-plot thousands of images and look for clusters and outliers. Always report how much variance the plot keeps.
64 pixel columns को सीधे plot नहीं किया जा सकता। 2 principal components पर project करके आप हज़ारों images का scatter plot बना सकते हैं और clusters व outliers खोज सकते हैं। हमेशा बताएँ कि plot कितना variance रखता है।
64 个像素列无法直接画出来。投影到 2 个主成分后,你可以把成千上万张图片画成散点图,寻找聚类和异常点。一定要说明这张图保留了多少方差。
LIVELIVE互动The Curse of Dimensionality — Distances Become EqualCurse of Dimensionality — दूरियाँ बराबर हो जाती हैं维度灾难 — 距离变得一样

300 random points in a cube with d dimensions. The bars show their distances to one query point (divided by the largest distance). The green line is the nearest point. Increase d and watch the nearest point move toward the farthest one.

d dimensions वाले cube में 300 random points. Bars एक query point से उनकी दूरियाँ दिखाती हैं (सबसे बड़ी दूरी से भाग देकर)। हरी line सबसे पास का point है। d बढ़ाएँ और देखें कि सबसे पास वाला point सबसे दूर वाले की ओर कैसे खिसकता है।

d 维立方体中的 300 个随机点。柱子表示它们到一个查询点的距离(除以最大距离)。绿线是最近的点。增大 d,看最近的点如何向最远的点靠拢。

Nearest pointसबसे पास最近的点
—
Farthest pointसबसे दूर最远的点
—
Nearest ÷ farthestपास ÷ दूर最近 ÷ 最远
—

⚠️
PCA Is Not Feature SelectionPCA, Feature Selection नहीं हैPCA 不是特征选择

Feature selection keeps a subset of the original columns. PCA creates new columns, and each one is a weighted mix of all the original features. The new columns are optimal for keeping variance, but they do not have a direct real-world meaning.

Feature selection original columns में से कुछ रखता है। PCA नए columns बनाता है, और हर एक सभी original features का weighted मेल होता है। नए columns variance बचाने के लिए सबसे अच्छे हैं, पर उनका सीधा असली-दुनिया वाला मतलब नहीं होता।

特征选择是保留原始列中的一部分。PCA 会创建新的列,每一列都是所有原始特征的加权组合。新列在保留方差方面是最优的,但没有直接的现实含义。


SectionSection第 04 节

The PCA Algorithm — Five StepsPCA Algorithm — पाँच StepsPCA 算法 — 五个步骤

01
Standardise the dataData को standardise करें标准化数据
For each feature, subtract the mean and divide by the standard deviation. Every column then has mean 0 and standard deviation 1. Without this, a feature measured in big numbers (salary) dominates one measured in small numbers (age). Try it in the simulator below. Centring (subtracting the mean) is always required; scaling is required when features use different units.
हर feature में से mean घटाएँ और standard deviation से भाग दें। तब हर column का mean 0 और standard deviation 1 होता है। इसके बिना, बड़े numbers वाला feature (salary) छोटे numbers वाले (उम्र) पर हावी हो जाता है। नीचे simulator में आज़माएँ। Centring (mean घटाना) हमेशा ज़रूरी है; scaling तब ज़रूरी है जब features की units अलग हों।
对每个特征减去均值、再除以标准差,于是每一列的均值为 0、标准差为 1。不这样做的话,数值大的特征(月薪)会压倒数值小的特征(年龄)。在下面的模拟器里试试。中心化(减去均值)总是必需的;当特征单位不同时,缩放也是必需的。
02
Compute the covariance matrixCovariance matrix निकालें计算协方差矩阵
With centred data X: C = XᵀX / (n−1). It is a d×d symmetric matrix. The diagonal holds the variance of each feature. Cell C[i, j] shows how features i and j move together.
Centred data X के साथ: C = XᵀX / (n−1). यह d×d symmetric matrix है। Diagonal में हर feature का variance है। Cell C[i, j] दिखाता है कि features i और j साथ-साथ कैसे बदलते हैं।
对中心化后的数据 X:C = XᵀX / (n−1)。它是一个 d×d 的对称矩阵。对角线是每个特征的方差,C[i, j] 表示特征 i 和 j 如何一起变化。
03
Eigen-decomposition of CC का Eigen-decomposition对 C 做特征分解
Solve Cv = λv. Each eigenvector v is a direction (a principal component). Its eigenvalue λ is the variance of the data along that direction. Sort the pairs from the largest λ to the smallest.
Cv = λv हल करें। हर eigenvector v एक दिशा (principal component) है। उसका eigenvalue λ उस दिशा में data का variance है। Pairs को सबसे बड़े λ से सबसे छोटे तक sort करें।
求解 Cv = λv。每个特征向量 v 是一个方向(主成分),对应的特征值 λ 是数据在这个方向上的方差。把它们按 λ 从大到小排序。
04
Project the dataData को project करें投影数据
Take the top k eigenvectors (k is much smaller than d) as the columns of W (d×k). Compute Z = X·W. Z has shape n×k: your data in the new, smaller space.
सबसे ऊपर के k eigenvectors (k, d से बहुत छोटा) को W (d×k) के columns बनाएँ। Z = X·W निकालें। Z का shape n×k है: नए, छोटे space में आपका data.
取前 k 个特征向量(k 远小于 d)作为 W(d×k)的列,计算 Z = X·W。Z 的形状是 n×k:这就是你的数据在新的低维空间中的样子。
05
Decide how many components to keepकितने components रखने हैं, तय करें决定保留多少个主成分
Use the explained variance ratio λₖ / Σλ. Look at the scree plot for an "elbow", or keep enough components for a target such as 95% of the variance. Best of all: pick k by cross-validating your final model.
Explained variance ratio λₖ / Σλ इस्तेमाल करें। Scree plot में "elbow" देखें, या इतने components रखें कि कोई लक्ष्य, जैसे 95% variance, पूरा हो। सबसे अच्छा: अपने final model को cross-validate करके k चुनें।
使用解释方差比 λₖ / Σλ。在碎石图上找"肘部",或者保留足够的主成分以达到某个目标(比如 95% 的方差)。最好的办法:通过交叉验证最终 model 来选 k。
🔧
What sklearn Actually Doessklearn असल में क्या करता हैsklearn 实际上怎么做

sklearn usually does not build C at all. It centres X and runs a singular value decomposition (SVD), X = UΣVᵀ. The rows of Vᵀ are the same principal components, and λ = σ² / (n−1). SVD gives the same answer and is more stable numerically. The covariance route is still the clearest way to understand PCA.

sklearn आमतौर पर C बनाता ही नहीं। यह X को centre करके singular value decomposition (SVD) चलाता है, X = UΣVᵀ. Vᵀ की rows वही principal components हैं, और λ = σ² / (n−1). SVD वही जवाब देता है और numerically ज़्यादा stable है। फिर भी PCA समझने का सबसे साफ़ रास्ता covariance वाला है।

sklearn 通常根本不构建 C。它把 X 中心化后做奇异值分解(SVD),X = UΣVᵀ。Vᵀ 的各行就是同样的主成分,λ = σ² / (n−1)。SVD 结果相同,数值上更稳定。不过,协方差这条路仍然是理解 PCA 最清楚的方式。

LIVELIVE互动Why Step 1 Matters — Standardise or Not?Step 1 क्यों ज़रूरी है — Standardise करें या नहीं?为什么第 1 步很重要 — 要不要标准化?

50 people: age (22–60 years) and monthly salary (about 15,000–90,000). Both axes use the same scale. Switch between raw units and standardised units and watch PC1 turn.

50 लोग: उम्र (22–60 साल) और मासिक salary (लगभग 15,000–90,000)। दोनों axes एक ही scale पर हैं। Raw units और standardised units के बीच बदलें और PC1 को घूमते देखें।

50 个人:年龄(22–60 岁)和月薪(约 15,000–90,000)。两个坐标轴使用相同的比例。在原始单位和标准化单位之间切换,看 PC1 如何转动。


SectionSection第 05 节

The Maths — Made Concrete with Numbersगणित — Numbers के साथ数学 — 用具体数字说明

Numerical Example: 2 Features → 1 Principal ComponentNumerical Example: 2 Features → 1 Principal Component数值例子:2 个特征 → 1 个主成分

Let's run PCA by hand on a tiny dataset: 5 students with two exam scores. We want the one direction (PC1) that best summarises both scores. Both scores use the same 0–100 scale, so here we only centre the data and do not divide by the standard deviation.

चलिए एक छोटे dataset पर हाथ से PCA करते हैं: 5 students और दो exam scores. हमें वह एक दिशा (PC1) चाहिए जो दोनों scores को सबसे अच्छी तरह summarise करे। दोनों scores एक ही 0–100 scale पर हैं, इसलिए यहाँ हम data को सिर्फ़ centre करते हैं, standard deviation से भाग नहीं देते।

我们在一个很小的数据集上手算 PCA:5 个学生、两门考试成绩。我们想找到最能概括两门成绩的那一个方向(PC1)。两门成绩都是 0–100 分制,所以这里只做中心化,不除以标准差。

StudentStudent学生Maths (x₁)Maths (x₁)数学 (x₁)Physics (x₂)Physics (x₂)物理 (x₂)
Alice8588
Bob7072
Carol9295
Dan6058
Eve7880
📝 Step-by-Step CalculationStep-by-Step हिसाब逐步计算
Step 1
Means: μ₁ = (85+70+92+60+78)/5 = 77.0, μ₂ = (88+72+95+58+80)/5 = 78.6 Means: μ₁ = (85+70+92+60+78)/5 = 77.0, μ₂ = (88+72+95+58+80)/5 = 78.6 均值:μ₁ = (85+70+92+60+78)/5 = 77.0,μ₂ = (88+72+95+58+80)/5 = 78.6
Step 2
Centre the data (subtract the means): Alice (8, 9.4), Bob (−7, −6.6), Carol (15, 16.4), Dan (−17, −20.6), Eve (1, 1.4) Data को centre करें (means घटाएँ): Alice (8, 9.4), Bob (−7, −6.6), Carol (15, 16.4), Dan (−17, −20.6), Eve (1, 1.4) 中心化(减去均值):Alice (8, 9.4)、Bob (−7, −6.6)、Carol (15, 16.4)、Dan (−17, −20.6)、Eve (1, 1.4)
Step 3
Covariance matrix (divide by n−1 = 4): Var(x₁) = 628/4 = 157.0 | Var(x₂) = 827.2/4 = 206.8 | Cov(x₁,x₂) = 719/4 = 179.75
C = [[157.0, 179.75], [179.75, 206.8]]
Covariance matrix (n−1 = 4 से भाग): Var(x₁) = 628/4 = 157.0 | Var(x₂) = 827.2/4 = 206.8 | Cov(x₁,x₂) = 719/4 = 179.75
C = [[157.0, 179.75], [179.75, 206.8]]
协方差矩阵(除以 n−1 = 4):Var(x₁) = 628/4 = 157.0 | Var(x₂) = 827.2/4 = 206.8 | Cov(x₁,x₂) = 719/4 = 179.75
C = [[157.0, 179.75], [179.75, 206.8]]
Step 4
Eigenvalues: solving det(C − λI) = 0 gives λ₁ ≈ 363.37 and λ₂ ≈ 0.43. Check: λ₁ + λ₂ = 363.8 = 157.0 + 206.8 (the total variance). Eigenvalues: det(C − λI) = 0 हल करने पर λ₁ ≈ 363.37 और λ₂ ≈ 0.43. जाँच: λ₁ + λ₂ = 363.8 = 157.0 + 206.8 (कुल variance). 特征值:解 det(C − λI) = 0 得 λ₁ ≈ 363.37,λ₂ ≈ 0.43。验证:λ₁ + λ₂ = 363.8 = 157.0 + 206.8(总方差)。
Step 5
Eigenvectors: v₁ ≈ [0.657, 0.754] (PC1) | v₂ ≈ [−0.754, 0.657] (PC2). They are at exactly 90° to each other. Eigenvectors: v₁ ≈ [0.657, 0.754] (PC1) | v₂ ≈ [−0.754, 0.657] (PC2). दोनों एक-दूसरे से ठीक 90° पर हैं। 特征向量:v₁ ≈ [0.657, 0.754](PC1)| v₂ ≈ [−0.754, 0.657](PC2)。两者正好互相垂直。
Step 6
Scores on PC1 (centred point · v₁): Alice 12.34, Bob −9.57, Carol 22.22, Dan −26.70, Eve 1.71 PC1 पर scores (centred point · v₁): Alice 12.34, Bob −9.57, Carol 22.22, Dan −26.70, Eve 1.71 PC1 得分(中心化后的点 · v₁):Alice 12.34、Bob −9.57、Carol 22.22、Dan −26.70、Eve 1.71
Resultनतीजा结果
Explained variance: PC1 explains 363.37 / 363.80 = 99.88% of the variance. One number per student is almost perfect, because the two scores rise and fall together. Explained variance: PC1, 363.37 / 363.80 = 99.88% variance समझाता है। हर student के लिए एक number लगभग perfect है, क्योंकि दोनों scores साथ-साथ ऊपर-नीचे होते हैं। 解释方差:PC1 解释了 363.37 / 363.80 = 99.88% 的方差。每个学生用一个数就几乎完美,因为两门成绩同涨同跌。
LIVELIVE互动Watch PCA Happen — The 5 StudentsPCA होते देखें — 5 Students看 PCA 一步步发生 — 5 个学生

Press Play, or step with Next and Back. The points move exactly as the maths above says. The table shows the real numbers at each step.

Play दबाएँ, या आगे और पीछे से एक-एक step चलें। Points ठीक वैसे ही चलते हैं जैसा ऊपर का गणित कहता है। Table हर step पर असली numbers दिखाती है।

点击播放,或用"下一步/上一步"逐步查看。点的移动与上面的数学完全一致,表格显示每一步的真实数字。

🌟
Intuition CheckIntuition जाँच直觉检验

v₁ = [0.657, 0.754] points at about 49° from the Maths axis, a little toward Physics because Physics scores are more spread out. Students who score high in Maths also score high in Physics, so almost everything is captured by one "overall exam ability" axis. Note: the sign of an eigenvector is arbitrary. Software may give [−0.657, −0.754] instead; that is the same axis.

v₁ = [0.657, 0.754] Maths axis से लगभग 49° पर है, थोड़ा Physics की ओर, क्योंकि Physics के scores ज़्यादा फैले हैं। जो Maths में अच्छा करते हैं वे Physics में भी अच्छा करते हैं, इसलिए लगभग सब कुछ एक "कुल exam क्षमता" axis में आ जाता है। ध्यान दें: eigenvector का sign मनमाना है। Software [−0.657, −0.754] भी दे सकता है; वह वही axis है।

v₁ = [0.657, 0.754] 与数学轴大约成 49°,稍微偏向物理,因为物理成绩更分散。数学好的学生物理也好,所以几乎所有信息都被一个"总体考试能力"轴捕获。注意:特征向量的正负号是任意的,软件可能给出 [−0.657, −0.754],那是同一条轴。

Key Formulasमुख्य Formulas关键公式

Covariance MatrixCovariance Matrix协方差矩阵
C = XᵀX / (n−1)
X must be centred. A symmetric d×d matrix. Cᵢⱼ measures how features i and j vary together.
X centred होना चाहिए। Symmetric d×d matrix. Cᵢⱼ मापता है कि features i और j साथ कैसे बदलते हैं।
X 必须已中心化。这是一个 d×d 对称矩阵,Cᵢⱼ 衡量特征 i 和 j 如何一起变化。
Eigen EquationEigen Equation特征方程
C · v = λ · v
v = eigenvector (a direction). λ = eigenvalue (the variance along that direction). C only stretches v, it does not turn it.
v = eigenvector (एक दिशा)। λ = eigenvalue (उस दिशा में variance)। C, v को सिर्फ़ खींचता है, घुमाता नहीं।
v = 特征向量(一个方向),λ = 特征值(该方向上的方差)。C 只拉伸 v,不旋转它。
Explained Variance RatioExplained Variance Ratio解释方差比
EVRₖ = λₖ / Σᵢ λᵢ
Share of the total variance explained by component k. All ratios add up to 1.
Component k द्वारा समझाया गया कुल variance का हिस्सा। सभी ratios का जोड़ 1 है।
第 k 个主成分解释的总方差占比,所有比值之和为 1。
ProjectionProjection投影
Z = X · Wₖ
Wₖ holds the top-k eigenvectors as columns (d×k). Z is the reduced n×k dataset.
Wₖ में top-k eigenvectors columns के रूप में हैं (d×k)। Z छोटा n×k dataset है।
Wₖ 的各列是前 k 个特征向量(d×k),Z 是降维后的 n×k 数据集。
ReconstructionReconstruction重建
X̂ = Z · Wₖᵀ + μ
Go back to the original features. With all d components X̂ = X exactly; with fewer you get the best possible rank-k approximation.
Original features में वापस जाएँ। सभी d components के साथ X̂ = X बिल्कुल; कम के साथ सबसे अच्छा rank-k approximation मिलता है।
回到原始特征空间。用全部 d 个主成分时 X̂ = X;用更少时得到最好的秩 k 近似。
What You Loseआप क्या खोते हैं损失了什么
error = Σi>k λᵢ
The total squared reconstruction error equals the sum of the eigenvalues you dropped (up to the n−1 scaling). Dropping small λ costs little.
कुल squared reconstruction error, हटाए गए eigenvalues के जोड़ के बराबर है (n−1 scaling तक)। छोटे λ हटाने की कीमत कम है।
总平方重建误差等于被丢弃的特征值之和(相差 n−1 的缩放)。丢掉小的 λ 代价很小。
LIVELIVE互动What Is an Eigenvector? Turn v and Watch CvEigenvector क्या है? v घुमाएँ और Cv देखें什么是特征向量?转动 v,观察 Cv

Blue = a unit vector v. Orange = Cv, the same vector after multiplying by the matrix C. Usually C turns v. At two special angles it only stretches it: those are the eigenvectors. "Power iteration" repeats v ← Cv and always ends on PC1.

नीला = एक unit vector v. नारंगी = Cv, यानी matrix C से गुणा करने के बाद वही vector. आमतौर पर C, v को घुमा देता है। दो ख़ास कोणों पर यह सिर्फ़ खींचता है: वही eigenvectors हैं। "Power iteration" बार-बार v ← Cv करता है और हमेशा PC1 पर पहुँचता है।

蓝色 = 单位向量 v;橙色 = Cv,即乘以矩阵 C 之后的同一个向量。通常 C 会让 v 转向。只有在两个特殊角度上,它只拉伸不转向:这就是特征向量。"幂迭代"不断重复 v ← Cv,最后总会停在 PC1 上。


SectionSection第 06 节

Visual Diagram — What PCA Does in 3-DVisual Diagram — 3-D में PCA क्या करता है可视化 — PCA 在三维中做了什么

Here is a real 3-D cloud of 90 points. The three arrows are its real principal components, computed in your browser from the covariance matrix. Arrow length grows with √λ.

यह 90 points का एक असली 3-D cloud है। तीनों तीर इसके असली principal components हैं, जो आपके browser में covariance matrix से निकाले गए हैं। तीर की लंबाई √λ के साथ बढ़ती है।

这是一个由 90 个点组成的真实三维点云。三个箭头是它真实的主成分,由你的浏览器根据协方差矩阵现场计算。箭头长度随 √λ 增长。

LIVELIVE互动PCA in 3-D — Rotate, Look, Flatten3-D में PCA — घुमाएँ, देखें, चपटा करें三维 PCA — 旋转、观察、压平

Drag to rotate. "Look along PC3" shows the widest shadow (this is what a 2-component PCA plot shows). "Look along PC1" hides the main spread. "Flatten" moves every point onto the PC1–PC2 plane, which is exactly what keeping k = 2 does.

घुमाने के लिए drag करें। "PC3 की दिशा से देखें" सबसे चौड़ी परछाई दिखाता है (2-component PCA plot यही दिखाता है)। "PC1 की दिशा से देखें" मुख्य फैलाव छिपा देता है। "चपटा करें" हर point को PC1–PC2 plane पर ले आता है, k = 2 रखने पर ठीक यही होता है।

拖动来旋转。"沿 PC3 看"显示最宽的影子(这正是二维 PCA 图显示的内容)。"沿 PC1 看"会藏住主要的散布。"压平"把每个点移到 PC1–PC2 平面上,这正是保留 k = 2 时发生的事。

PC1
—
PC2
—
PC3
—

Bars = explained variance ratio of each component.

Bars = हर component का explained variance ratio.

柱子 = 每个主成分的解释方差比。


SectionSection第 07 节

Scree Plot — Choosing How Many Components to KeepScree Plot — कितने Components रखें碎石图 — 选择保留多少个主成分

The Mountain Ridgeपहाड़ों की कतार山脊
Imagine ranking hills by height. The first few are huge and dominate the view. Then the heights drop sharply, and the rest are small bumps that look like noise. The point where the big drop ends is the "elbow". Keep the hills before the elbow; they tell you something real.

That is a scree plot: the y-axis is the variance explained by each component, the x-axis is the component number. Real data is not always so neat. Often there is no clear elbow, and then a cumulative target (90% or 95%) or cross-validation is a better guide.
पहाड़ियों को ऊँचाई के क्रम में रखने की कल्पना करें। पहली कुछ बहुत ऊँची हैं और नज़ारे पर छाई हैं। फिर ऊँचाई तेज़ी से गिरती है, और बाकी छोटे उभार हैं जो noise जैसे दिखते हैं। जहाँ बड़ी गिरावट ख़त्म होती है वह "elbow" है। Elbow से पहले वाली पहाड़ियाँ रखें; वे कुछ असली बताती हैं।

यही scree plot है: y-axis हर component का समझाया variance है, x-axis component का number. असली data हमेशा इतना साफ़ नहीं होता। अक्सर कोई साफ़ elbow नहीं होता, और तब cumulative लक्ष्य (90% या 95%) या cross-validation बेहतर रास्ता है।
想象把一排山按高度排序。前几座非常高,主宰了整个视野;然后高度急剧下降,剩下的都是像噪声一样的小土包。急剧下降结束的地方就是"肘部"。保留肘部之前的山,它们代表真实的结构。

这就是碎石图:y 轴是每个主成分解释的方差,x 轴是主成分编号。真实数据并不总是这么整齐,常常没有明显的肘部,这时用累计目标(90% 或 95%)或交叉验证来选更可靠。
LIVELIVE互动Rebuild a Handwritten Digit from k Componentsk Components से हाथ से लिखा Digit दोबारा बनाएँ用 k 个主成分重建手写数字

Real PCA of all 1,797 sklearn digit images (8×8 = 64 pixels, raw pixel values). Move k: the image is rebuilt from the mean image plus k weighted components. The scree plot below shows the real variance of each component.

Sklearn की सभी 1,797 digit images (8×8 = 64 pixels, raw pixel values) का असली PCA. k बदलें: image, mean image और k weighted components से दोबारा बनती है। नीचे scree plot हर component का असली variance दिखाता है।

对 sklearn 全部 1,797 张手写数字图片(8×8 = 64 个像素,原始像素值)做的真实 PCA。移动 k:图像由平均图像加上 k 个加权主成分重建。下方碎石图显示每个主成分的真实方差。

Pick a digit:एक digit चुनें:选择一个数字:
Variance keptबचा variance保留的方差
—
Pixel error (RMSE)Pixel error (RMSE)像素误差(RMSE)
—

Orange = positive weight, blue = negative weight in the component images. Pixel values go from 0 to 16.

Component images में नारंगी = positive weight, नीला = negative weight. Pixel values 0 से 16 तक हैं।

主成分图像中,橙色 = 正权重,蓝色 = 负权重。像素值范围是 0 到 16。

📊
What the Real Scree Plot Saysअसली Scree Plot क्या कहता है真实碎石图告诉我们什么

On the digits data there is no sharp elbow. The first component explains 14.9% and the values fall off slowly. 13 components keep 80%, 21 keep 90% and 29 keep 95% of the variance. Around k = 10 the digit is already easy to read. So the "right" k depends on the job: a 2-D plot, compression, or input for a model.

Digits data में कोई तेज़ elbow नहीं है। पहला component 14.9% समझाता है और values धीरे-धीरे गिरती हैं। 13 components 80%, 21 components 90% और 29 components 95% variance रखते हैं। लगभग k = 10 पर digit पढ़ना आसान हो जाता है। इसलिए "सही" k काम पर निर्भर है: 2-D plot, compression, या model के लिए input.

在手写数字数据上没有明显的肘部。第一个主成分解释 14.9%,之后缓慢下降。13 个主成分保留 80%,21 个保留 90%,29 个保留 95% 的方差。k = 10 左右数字就已经很容易认出来。所以"正确"的 k 取决于用途:二维作图、压缩,还是作为 model 的输入。


SectionSection第 08 节

Python Implementation — Step by StepPython Implementation — Step by StepPython 实现 — 逐步讲解

Step 1: PCA from Scratch with NumPyStep 1: NumPy से शुरू से PCA第 1 步:用 NumPy 从零实现 PCA

import numpy as np
np.set_printoptions(suppress=True)   # plain decimals, no 1e-04

# ── Toy dataset: 6 students × 4 exam scores ──────────────────
X = np.array([
    [85, 88, 82, 90],
    [70, 72, 68, 74],
    [92, 95, 91, 96],
    [60, 58, 63, 55],
    [78, 80, 76, 82],
    [55, 52, 57, 50],
], dtype=float)

# Step 1 — Standardise (zero mean, unit variance)
mean = X.mean(axis=0)
std = X.std(axis=0, ddof=1)
X_std = (X - mean) / std

# Step 2 — Covariance matrix (of standardised data = correlation matrix)
C = np.cov(X_std.T)
print("Covariance matrix shape:", C.shape)
print(np.round(C, 3))

# Step 3 — Eigendecomposition (eigh: for symmetric matrices)
eigenvalues, eigenvectors = np.linalg.eigh(C)
idx = np.argsort(eigenvalues)[::-1]          # largest first
eigenvalues = eigenvalues[idx]
eigenvectors = eigenvectors[:, idx]

# Step 4 — Explained variance ratio
evr = eigenvalues / eigenvalues.sum()
print("\nEigenvalues:         ", np.round(eigenvalues, 4))
print("Explained var ratio: ", np.round(evr, 4))
print("Cumulative EVR:      ", np.round(np.cumsum(evr), 4))

# Step 5 — Project onto the top-2 PCs
W = eigenvectors[:, :2]
Z = X_std @ W
print("\nProjected data (2 PCs):\n", np.round(Z, 3))

# Check: sklearn gives the same answer (it uses SVD internally)
from sklearn.decomposition import PCA
pca = PCA().fit(X_std)
print("\nsklearn eigenvalues:  ", np.round(pca.explained_variance_, 4))
print("Same directions?     ", np.allclose(np.abs(pca.components_), np.abs(eigenvectors.T)))
OUTPUT
Covariance matrix shape: (4, 4) [[1. 0.998 0.992 0.991] [0.998 1. 0.984 0.997] [0.992 0.984 1. 0.968] [0.991 0.997 0.968 1. ]] Eigenvalues: [3.9657 0.0339 0.0003 0.0001] Explained var ratio: [0.9914 0.0085 0.0001 0. ] Cumulative EVR: [0.9914 0.9999 1. 1. ] Projected data (2 PCs): [[-1.596 0.075] [ 0.385 0.263] [-2.565 -0.214] [ 1.857 -0.188] [-0.663 0.107] [ 2.581 -0.043]] sklearn eigenvalues: [3.9657 0.0339 0.0003 0.0001] Same directions? True
🌟
What the Output Tells UsOutput क्या बताता है输出告诉了我们什么

The first eigenvalue (3.97) is huge next to the others (0.034, 0.0003, 0.0001). PC1 alone explains 99.14% of the variance: the four exam scores mostly measure one thing. We go from 4 numbers to 1 per student and lose less than 1%. Two more details: (1) the eigenvalues add up to 4, because each standardised feature has variance 1; (2) the strongest students get negative PC1 scores here. That is only the arbitrary sign of the eigenvector.

पहला eigenvalue (3.97) बाकियों (0.034, 0.0003, 0.0001) के सामने बहुत बड़ा है। सिर्फ़ PC1 99.14% variance समझाता है: चारों exam scores ज़्यादातर एक ही चीज़ मापते हैं। हम हर student के 4 numbers से 1 पर आते हैं और 1% से कम खोते हैं। दो और बातें: (1) eigenvalues का जोड़ 4 है, क्योंकि हर standardised feature का variance 1 है; (2) यहाँ सबसे अच्छे students को negative PC1 scores मिलते हैं। यह सिर्फ़ eigenvector का मनमाना sign है।

第一个特征值(3.97)远大于其他特征值(0.034、0.0003、0.0001)。仅 PC1 就解释了 99.14% 的方差:四门考试主要在衡量同一件事。每个学生从 4 个数变成 1 个数,损失不到 1%。另外两点:(1) 特征值之和为 4,因为每个标准化特征的方差都是 1;(2) 这里成绩最好的学生 PC1 得分是负数,这只是特征向量正负号的任意性。

Step 2: sklearn PCA — The Production WayStep 2: sklearn PCA — Production का तरीका第 2 步:sklearn PCA — 生产环境的做法

from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris
import numpy as np

iris = load_iris()
X, y = iris.data, iris.target
feature_names = iris.feature_names

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

pca_full = PCA(n_components=None)            # keep all 4 components
pca_full.fit(X_scaled)

print("Explained variance ratio per component:")
for i, ev in enumerate(pca_full.explained_variance_ratio_):
    print(f"  PC{i+1}: {ev:.4f}  ({ev*100:.2f}%)")
cum = np.cumsum(pca_full.explained_variance_ratio_)
print(f"\n95% variance threshold: {np.argmax(cum >= 0.95) + 1} components")

pca_2d = PCA(n_components=2)
X_2d = pca_2d.fit_transform(X_scaled)

print(f"\nOriginal shape:  {X.shape}")
print(f"Reduced shape:   {X_2d.shape}")
print(f"Total variance retained: {pca_2d.explained_variance_ratio_.sum():.4f}")

print("\nComponent loadings (how much each feature contributes):")
for i, comp in enumerate(pca_2d.components_):
    print(f"  PC{i+1}:")
    for fname, loading in zip(feature_names, comp):
        print(f"    {fname:20s}: {loading:+.4f}")
OUTPUT
Explained variance ratio per component: PC1: 0.7296 (72.96%) PC2: 0.2285 (22.85%) PC3: 0.0367 (3.67%) PC4: 0.0052 (0.52%) 95% variance threshold: 2 components Original shape: (150, 4) Reduced shape: (150, 2) Total variance retained: 0.9581 Component loadings (how much each feature contributes): PC1: sepal length (cm) : +0.5211 sepal width (cm) : -0.2693 petal length (cm) : +0.5804 petal width (cm) : +0.5649 PC2: sepal length (cm) : +0.3774 sepal width (cm) : +0.9233 petal length (cm) : +0.0245 petal width (cm) : +0.0669
📖
Reading the LoadingsLoadings पढ़ना解读载荷

PC1 has large positive weights for petal length (+0.58), petal width (+0.56) and sepal length (+0.52), and a negative weight for sepal width (−0.27). It works like an "overall flower size" axis. PC2 is dominated by sepal width (+0.92): a different aspect of the shape. Each row of components_ is a unit vector, so the squared weights add up to 1.

PC1 में petal length (+0.58), petal width (+0.56) और sepal length (+0.52) के बड़े positive weights हैं, और sepal width (−0.27) का negative weight. यह "फूल का कुल आकार" axis जैसा काम करता है। PC2 पर sepal width (+0.92) हावी है: आकार का एक अलग पहलू। components_ की हर row एक unit vector है, इसलिए squared weights का जोड़ 1 है।

PC1 对花瓣长度(+0.58)、花瓣宽度(+0.56)和萼片长度(+0.52)有较大的正权重,对萼片宽度(−0.27)是负权重,相当于"花的整体大小"轴。PC2 主要由萼片宽度(+0.92)决定:反映了形状的另一个方面。components_ 的每一行都是单位向量,所以权重的平方和为 1。

Step 3: Choosing n_componentsStep 3: n_components चुनना第 3 步:选择 n_components

from sklearn.decomposition import PCA

# A float between 0 and 1 = "keep enough PCs for this much variance"
pca_95 = PCA(n_components=0.95)
X_95 = pca_95.fit_transform(X_scaled)
print(f"Components needed for 95% variance: {pca_95.n_components_}")

# 'mle' = Minka's automatic choice
pca_mle = PCA(n_components='mle')
X_mle = pca_mle.fit_transform(X_scaled)
print(f"MLE auto-selected components:       {pca_mle.n_components_}")

# How much do we lose? Go back to 4-D and measure the error
X_reconstructed = pca_2d.inverse_transform(X_2d)
mse = ((X_scaled - X_reconstructed) ** 2).mean()
print(f"Reconstruction MSE (2 PCs):         {mse:.6f}")
print(f"Lost variance share (1 - retained): {1 - pca_2d.explained_variance_ratio_.sum():.6f}")
OUTPUT
Components needed for 95% variance: 2 MLE auto-selected components: 3 Reconstruction MSE (2 PCs): 0.041868 Lost variance share (1 - retained): 0.041868
🔑
Two Useful Facts from This Outputइस Output से दो काम की बातें从输出中得到的两个有用事实

n_components='mle' picked 3 components here, not 2. MLE and the 95% rule answer different questions, so they can disagree. Also, the reconstruction MSE (0.041868) is exactly the share of variance we dropped (1 − 0.9581). That is the "what you lose" formula from Section 05, seen in real numbers.

n_components='mle' ने यहाँ 2 नहीं, 3 components चुने। MLE और 95% rule अलग सवालों के जवाब देते हैं, इसलिए वे अलग हो सकते हैं। साथ ही, reconstruction MSE (0.041868) ठीक उतना है जितना variance हमने हटाया (1 − 0.9581)। यह Section 05 का "आप क्या खोते हैं" formula है, असली numbers में।

这里 n_components='mle' 选了 3 个主成分,而不是 2 个。MLE 和 95% 规则回答的是不同的问题,所以结果可能不同。另外,重建 MSE(0.041868)正好等于我们丢掉的方差比例(1 − 0.9581)。这就是第 04 节"损失了什么"公式的真实体现。


SectionSection第 09 节

Complete Real-World Example — Digits Datasetपूरा Real-World Example — Digits Dataset完整实战案例 — 手写数字数据集

The digits dataset has 1,797 handwritten digit images of 8×8 pixels, so 64 features. We split the data first, then fit the scaler and PCA on the training images only, and compare a classifier with and without PCA.

Digits dataset में 8×8 pixels की 1,797 हाथ से लिखी digit images हैं, यानी 64 features. हम पहले data split करते हैं, फिर scaler और PCA सिर्फ़ training images पर fit करते हैं, और PCA के साथ और बिना एक classifier की तुलना करते हैं।

手写数字数据集有 1,797 张 8×8 像素的图片,也就是 64 个特征。我们先划分数据,再只在训练图片上拟合缩放器和 PCA,然后比较使用和不使用 PCA 的分类器。

from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline

digits = load_digits()
X, y = digits.data, digits.target
print(f"Dataset: {X.shape[0]} images × {X.shape[1]} pixel features")

# Split FIRST, so the test images never influence the scaler or the PCA
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y)

for k in [2, 10, 20, 30]:
    pca = make_pipeline(StandardScaler(), PCA(n_components=k)).fit(X_train)
    kept = pca[-1].explained_variance_ratio_.sum()
    print(f"Variance retained ({k:2d} PCs): {kept:.4f}")

print()
for name, k in [("No PCA (64 features)", None), ("PCA 30 components", 30), ("PCA 10 components", 10)]:
    steps = [StandardScaler()] + ([PCA(n_components=k)] if k else []) + [LogisticRegression(max_iter=2000)]
    model = make_pipeline(*steps)
    model.fit(X_train, y_train)
    print(f"  {name:22s}: test accuracy {model.score(X_test, y_test):.4f}")
OUTPUT
Dataset: 1797 images × 64 pixel features Variance retained ( 2 PCs): 0.2170 Variance retained (10 PCs): 0.5898 Variance retained (20 PCs): 0.7899 Variance retained (30 PCs): 0.8933 No PCA (64 features) : test accuracy 0.9722 PCA 30 components : test accuracy 0.9556 PCA 10 components : test accuracy 0.8778
👉
Key Takeaway — An Honest Resultमुख्य सीख — एक ईमानदार नतीजा关键结论 — 一个诚实的结果

With 30 of 64 features, PCA kept 89.3% of the variance and accuracy fell from 97.2% to 95.6% (−1.7 points). With 10 features it fell to 87.8%. On this small dataset there is no speed reason to use PCA, so the full features win. PCA pays off when data is large, features are noisy or strongly correlated, or the model is slow (k-NN, SVM on many rows). Always measure, as here.

64 में से 30 features के साथ PCA ने 89.3% variance रखा और accuracy 97.2% से 95.6% पर गिरी (−1.7 points)। 10 features के साथ यह 87.8% पर आ गई। इस छोटे dataset पर PCA इस्तेमाल करने की speed वाली कोई वजह नहीं, इसलिए पूरे features जीतते हैं। PCA तब फ़ायदा देता है जब data बड़ा हो, features noisy या बहुत correlated हों, या model धीमा हो (बहुत rows पर k-NN, SVM)। हमेशा मापें, जैसे यहाँ।

用 64 个特征中的 30 个,PCA 保留了 89.3% 的方差,准确率从 97.2% 降到 95.6%(−1.7 个百分点);只用 10 个时降到 87.8%。在这个小数据集上,用 PCA 没有速度上的理由,所以完整特征更好。PCA 的价值在于数据量大、特征噪声多或高度相关、或者 model 很慢(如大量样本上的 k-NN、SVM)的时候。一定要像这里一样实际测量。

🖼️
Images: Scaling Can HurtImages: Scaling नुकसान कर सकता है图像:缩放可能有害

All pixels already use the same 0–16 scale. StandardScaler gives almost-always-blank border pixels the same weight as the centre pixels. On raw pixels, 30 components keep 95.9% of the variance; after standardising, only 89.3%. For pixels or other same-unit features, try PCA without scaling too (the simulator in Section 07 uses raw pixels).

सभी pixels पहले से एक ही 0–16 scale पर हैं। StandardScaler लगभग हमेशा ख़ाली रहने वाले border pixels को बीच के pixels जितना weight दे देता है। Raw pixels पर 30 components 95.9% variance रखते हैं; standardise करने के बाद सिर्फ़ 89.3%. Pixels या एक ही unit वाले features के लिए बिना scaling के PCA भी आज़माएँ (Section 07 का simulator raw pixels इस्तेमाल करता है)।

所有像素本来就在同样的 0–16 范围内。StandardScaler 会让几乎总是空白的边缘像素与中心像素拥有同样的权重。在原始像素上,30 个主成分保留 95.9% 的方差;标准化后只有 89.3%。对于像素或单位相同的特征,也试试不缩放直接做 PCA(第 07 节的模拟器用的就是原始像素)。


SectionSection第 10 节

PCA in a Full Machine-Learning Pipelineपूरी Machine-Learning Pipeline में PCA完整机器学习流水线中的 PCA

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV, cross_val_score, StratifiedKFold
from sklearn.datasets import load_wine

wine = load_wine()
X, y = wine.data, wine.target            # 178 wines × 13 chemical features

pipe = Pipeline([
    ('scaler', StandardScaler()),
    ('pca',    PCA(n_components=0.95)),
    ('svm',    SVC(kernel='rbf')),
])

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
cv_scores = cross_val_score(pipe, X, y, cv=cv, scoring='accuracy')
print(f"With PCA (95%):  CV accuracy {cv_scores.mean():.4f} ± {cv_scores.std():.4f}")

no_pca = Pipeline([('scaler', StandardScaler()), ('svm', SVC(kernel='rbf'))])
base = cross_val_score(no_pca, X, y, cv=cv, scoring='accuracy')
print(f"Without PCA:     CV accuracy {base.mean():.4f} ± {base.std():.4f}")

param_grid = {
    'pca__n_components': [2, 5, 8, 0.90, 0.95, 0.99],
    'svm__C':            [0.1, 1.0, 10.0],
    'svm__gamma':        ['scale', 'auto'],
}

grid = GridSearchCV(pipe, param_grid, cv=cv, scoring='accuracy', n_jobs=-1)
grid.fit(X, y)

print(f"Best CV accuracy: {grid.best_score_:.4f}")
print(f"Best params:      {grid.best_params_}")
print(f"PCs used:         {grid.best_estimator_.named_steps['pca'].n_components_}")
OUTPUT
With PCA (95%): CV accuracy 0.9833 ± 0.0222 Without PCA: CV accuracy 0.9833 ± 0.0222 Best CV accuracy: 0.9833 Best params: {'pca__n_components': 0.99, 'svm__C': 10.0, 'svm__gamma': 'scale'} PCs used: 12
🔍
Reading the Resultनतीजा पढ़ना解读结果

On the wine data, PCA neither helps nor hurts: 98.3% with and without it. The grid search picked n_components=0.99 (12 of 13 components), which is almost no reduction. This is common on small, clean datasets. The pipeline is still the right pattern, because it lets cross-validation tell you honestly whether PCA helps.

Wine data पर PCA न मदद करता है न नुकसान: इसके साथ और बिना, दोनों 98.3%. Grid search ने n_components=0.99 चुना (13 में से 12 components), यानी लगभग कोई कमी नहीं। छोटे, साफ़ datasets पर ऐसा अक्सर होता है। फिर भी pipeline सही तरीका है, क्योंकि यह cross-validation को ईमानदारी से बताने देता है कि PCA मदद करता है या नहीं।

在葡萄酒数据上,PCA 既没帮忙也没拖后腿:用和不用都是 98.3%。网格搜索选了 n_components=0.99(13 个中的 12 个),几乎没有降维。这在小而干净的数据集上很常见。但流水线仍然是正确的写法,因为它让交叉验证如实告诉你 PCA 是否有用。

⚠️
Data Leakage WarningData Leakage चेतावनी数据泄漏警告

Always put the scaler and PCA inside a Pipeline when you cross-validate. If you fit PCA on the full dataset before splitting, the test fold has already shaped the components, and your score is too optimistic. The Pipeline refits the scaler and PCA on the training folds only, every time.

Cross-validate करते समय scaler और PCA को हमेशा Pipeline के अंदर रखें। अगर आप split से पहले पूरे dataset पर PCA fit करते हैं, तो test fold पहले ही components को आकार दे चुका होता है, और आपका score ज़रूरत से ज़्यादा अच्छा दिखता है। Pipeline हर बार scaler और PCA को सिर्फ़ training folds पर दोबारा fit करती है।

做交叉验证时,一定要把缩放器和 PCA 放在 Pipeline 内部。如果在划分之前就在整个数据集上拟合 PCA,测试折已经影响了主成分,得到的分数会过于乐观。Pipeline 每次都只在训练折上重新拟合缩放器和 PCA。


SectionSection第 11 节

Incremental PCA — When Data Doesn't Fit in RAMIncremental PCA — जब Data RAM में न आए增量 PCA — 数据大到内存放不下时

import numpy as np
from sklearn.decomposition import IncrementalPCA, PCA

# Pretend this is a huge file: 100,000 rows × 50 features with real structure
# (5 hidden factors + noise). In real life you would read it chunk by chunk.
rng = np.random.default_rng(42)
factors = rng.normal(size=(100_000, 5))
mixing = rng.normal(size=(5, 50))
X_large = factors @ mixing + 0.5 * rng.normal(size=(100_000, 50))

ipca = IncrementalPCA(n_components=10)
for chunk in np.array_split(X_large, 50):       # 50 chunks of 2,000 rows
    ipca.partial_fit(chunk)                     # only one chunk in memory

print("IncrementalPCA explained variance ratio (top 10):")
print(np.round(ipca.explained_variance_ratio_, 4))
print(f"Top-5 total: {ipca.explained_variance_ratio_[:5].sum():.4f}")

# Compare with ordinary PCA (which needs all rows in memory at once)
pca = PCA(n_components=10).fit(X_large)
print(f"Ordinary PCA top-5 total: {pca.explained_variance_ratio_[:5].sum():.4f}")
cos = np.abs(np.sum(ipca.components_[:5] * pca.components_[:5], axis=1))
print("Direction match |cos| for PC1–PC5:", np.round(cos, 4))

X_transformed = ipca.transform(X_large[:1000])
print(f"Transformed shape: {X_transformed.shape}")
OUTPUT
IncrementalPCA explained variance ratio (top 10): [0.2863 0.2292 0.1984 0.1361 0.1105 0.0009 0.0009 0.0009 0.0009 0.0009] Top-5 total: 0.9606 Ordinary PCA top-5 total: 0.9606 Direction match |cos| for PC1–PC5: [1. 1. 1. 1. 1.] Transformed shape: (1000, 10)
📊
When to Use IncrementalPCAIncrementalPCA कब इस्तेमाल करें什么时候用 IncrementalPCA

Ordinary PCA needs the whole dataset in memory. IncrementalPCA reads one chunk at a time with partial_fit, so memory depends on the chunk size, not the dataset size. Use it when the data is bigger than your RAM or arrives as a stream. Here it found the same 5 directions as ordinary PCA (|cos| = 1.0000) and the same 96.06% variance. Results are usually very close, not guaranteed identical. Each chunk must have at least n_components rows.

साधारण PCA को पूरा dataset memory में चाहिए। IncrementalPCA partial_fit से एक बार में एक chunk पढ़ता है, इसलिए memory chunk के आकार पर निर्भर है, dataset के आकार पर नहीं। इसे तब इस्तेमाल करें जब data आपकी RAM से बड़ा हो या stream में आए। यहाँ इसने साधारण PCA जैसी ही 5 दिशाएँ खोजीं (|cos| = 1.0000) और वही 96.06% variance. नतीजे आमतौर पर बहुत क़रीब होते हैं, बिल्कुल एक जैसे होने की गारंटी नहीं। हर chunk में कम से कम n_components rows होनी चाहिए।

普通的 PCA 需要把整个数据集放进内存。IncrementalPCA 用 partial_fit 每次读取一块数据,所以内存取决于块的大小,而不是数据集的大小。数据比内存大或以流的形式到来时就用它。这里它找到的 5 个方向与普通 PCA 完全相同(|cos| = 1.0000),方差也同为 96.06%。结果通常非常接近,但不保证完全一样。每一块至少要有 n_components 行。


SectionSection第 12 节

PCA Diagram — The Full Data FlowPCA Diagram — पूरा Data FlowPCA 示意图 — 完整的数据流

⚙️ PCA END-TO-END DATA FLOWPCA END-TO-END DATA FLOWPCA 端到端数据流
PCA data flow Raw dataRaw data原始数据n × d matrixn × d matrixn × d 矩阵e.g. 1797 × 64जैसे 1797 × 64如 1797 × 64 StandardiseStandardise标准化mean 0, std 1mean 0, std 1均值 0,标准差 1fit on train onlyसिर्फ़ train पर fit只在训练集上 fit Covariance CCovariance C协方差 CC = XᵀX / (n−1)d × d, symmetricd × d, symmetricd × d,对称 EigenvectorsEigenvectors特征向量sorted by λλ के क्रम में按 λ 排序(or SVD of X)(या X का SVD)(或对 X 做 SVD) choose kk चुनें选 k W matrixW matrixW 矩阵top-k eigenvectorstop-k eigenvectors前 k 个特征向量shape d × kshape d × k形状 d × k projectproject投影 Z = X · Wreduced dataछोटा data降维后的数据shape n × kshape n × k形状 n × k VisualiseVisualise可视化2-D / 3-D scatter2-D / 3-D scatter二维 / 三维散点图 Train a modelModel train करें训练模型SVM, LR, k-NN …SVM, LR, k-NN …SVM、LR、k-NN … ReconstructReconstruct重建X̂ = Z·Wᵀ + μ

Fit the scaler, the covariance and W on training data only. Then apply the same μ, σ and W to new data.

Scaler, covariance और W सिर्फ़ training data पर fit करें। फिर नए data पर वही μ, σ और W लगाएँ।

缩放器、协方差和 W 只在训练数据上拟合,然后把同样的 μ、σ 和 W 用到新数据上。


SectionSection第 13 节

Key Hyperparametersमुख्य Hyperparameters关键超参数

ParameterDefaultWhat it controlsक्या नियंत्रित करता है控制什么Tuning adviceTuning सलाह调参建议
n_componentsNoneHow many PCs to keep. An int, a float in (0, 1) for a variance share, or 'mle'. None keeps min(n_samples, n_features).कितने PCs रखने हैं। int, variance हिस्से के लिए (0, 1) में float, या 'mle'. None, min(n_samples, n_features) रखता है।保留多少个 PC。可以是整数、(0, 1) 之间表示方差比例的小数,或 'mle'。None 保留 min(n_samples, n_features) 个。Most important. Start with 0.95, then confirm k with cross-validation.सबसे ज़रूरी। 0.95 से शुरू करें, फिर cross-validation से k पक्का करें।最重要。从 0.95 开始,再用交叉验证确认 k。
svd_solver'auto'Algorithm: 'auto', 'full', 'covariance_eigh', 'arpack', 'randomized'.Algorithm: 'auto', 'full', 'covariance_eigh', 'arpack', 'randomized'.算法:'auto'、'full'、'covariance_eigh'、'arpack'、'randomized'。'auto' picks well. 'randomized' is fast for large data and small k; 'covariance_eigh' is fast when rows ≫ features.'auto' अच्छा चुनता है। बड़े data और छोटे k के लिए 'randomized' तेज़ है; rows ≫ features हों तो 'covariance_eigh' तेज़ है।'auto' 通常选得好。数据大、k 小时 'randomized' 快;行数远多于特征数时 'covariance_eigh' 快。
whitenFalseDivide each component by its standard deviation, so every PC has variance 1.हर component को उसके standard deviation से भाग दें, ताकि हर PC का variance 1 हो।把每个主成分除以它的标准差,使每个 PC 的方差为 1。Can help models that expect equal-scale inputs (RBF SVM, k-means). It also boosts noisy small components, so test it with CV.Equal-scale inputs चाहने वाले models (RBF SVM, k-means) की मदद कर सकता है। यह noisy छोटे components को भी बढ़ाता है, इसलिए CV से test करें।对期望输入尺度相同的 model(RBF SVM、k-means)可能有帮助。但它也会放大有噪声的小主成分,所以要用 CV 测试。
random_stateNoneSeed for the 'arpack' and 'randomized' solvers.'arpack' और 'randomized' solvers के लिए seed.'arpack' 和 'randomized' 求解器的随机种子。Set it for reproducible results.Reproducible नतीजों के लिए इसे set करें।设置它以获得可复现的结果。
copyTrueWhether X is copied before centring.Centring से पहले X copy होगा या नहीं।中心化之前是否复制 X。Set False to save memory, but then do not reuse X: it may be changed.Memory बचाने के लिए False करें, पर फिर X दोबारा इस्तेमाल न करें: वह बदल सकता है।设为 False 可以省内存,但之后不要再用 X:它可能被修改。
✅
Attributes You Will Use Mostसबसे ज़्यादा इस्तेमाल होने वाले Attributes最常用的属性

components_ (k×d, the directions), explained_variance_ (the λ values), explained_variance_ratio_ (λ / Σλ), mean_ (μ), n_components_ (the k actually chosen) and inverse_transform() (go back to the original features).

components_ (k×d, दिशाएँ), explained_variance_ (λ values), explained_variance_ratio_ (λ / Σλ), mean_ (μ), n_components_ (असल में चुना गया k) और inverse_transform() (original features में वापस जाना)।

components_(k×d,方向)、explained_variance_(λ 值)、explained_variance_ratio_(λ / Σλ)、mean_(μ)、n_components_(实际选择的 k)以及 inverse_transform()(回到原始特征空间)。


SectionSection第 14 节

When to Use PCA — and When Not ToPCA कब इस्तेमाल करें — और कब नहीं什么时候用 PCA — 什么时候不用

✅
Visualisation (2-D / 3-D)Visualisation (2-D / 3-D)可视化(二维 / 三维)
Project any dataset onto 2 or 3 PCs and scatter-plot it. Clusters, outliers and class separation often become visible. Always state the variance the plot keeps.
किसी भी dataset को 2 या 3 PCs पर project करके scatter plot बनाएँ। Clusters, outliers और class separation अक्सर दिखने लगते हैं। हमेशा बताएँ कि plot कितना variance रखता है।
把任何数据集投影到 2 或 3 个 PC 上画散点图,聚类、异常点和类别区分常常一目了然。一定要说明图中保留了多少方差。
exploratory data analysisexploratory data analysis探索性数据分析
✅
Noise ReductionNoise कम करना降噪
The last components often hold mostly noise. Project and reconstruct (X̂ = Z·Wᵀ + μ) to get a cleaner version of the data, as in the digits simulator.
आख़िरी components में अक्सर ज़्यादातर noise होता है। Project और reconstruct (X̂ = Z·Wᵀ + μ) करके data का साफ़ रूप पाएँ, जैसे digits simulator में।
最后几个主成分通常主要是噪声。先投影再重建(X̂ = Z·Wᵀ + μ),就能得到更干净的数据,就像手写数字模拟器那样。
denoising, compressiondenoising, compression去噪、压缩
✅
Multicollinearity RemovalMulticollinearity हटाना消除多重共线性
PC scores are uncorrelated with each other on the training data. If your features are highly correlated (e.g. many financial ratios), regression on PCs (PCR) is stable. The price: coefficients are harder to explain.
Training data पर PC scores आपस में uncorrelated होते हैं। अगर आपके features बहुत correlated हैं (जैसे कई financial ratios), तो PCs पर regression (PCR) stable रहता है। कीमत: coefficients समझाना मुश्किल होता है।
在训练数据上,各 PC 得分彼此不相关。如果特征高度相关(比如很多财务比率),在 PC 上做回归(PCR)会很稳定。代价是:系数更难解释。
linear and logistic regressionlinear और logistic regression线性回归、逻辑回归
❌
Interpretability Requiredजब Interpretability ज़रूरी हो需要可解释性时
Each PC is a mix of all features. "PC1 = 0.52·A + 0.58·B − 0.27·C …" has no direct business meaning. If you must explain individual predictions, keep the original features.
हर PC सभी features का मेल है। "PC1 = 0.52·A + 0.58·B − 0.27·C …" का कोई सीधा business मतलब नहीं। अगर आपको हर prediction समझानी है, तो original features रखें।
每个 PC 都是所有特征的混合。"PC1 = 0.52·A + 0.58·B − 0.27·C …"没有直接的业务含义。如果必须解释每个预测,就保留原始特征。
regulated industries, clinical AIregulated industries, clinical AI受监管行业、临床 AI
❌
Non-Linear StructureNon-Linear ढाँचा非线性结构
PCA only finds straight directions. If the data lies on a curve (moons, rings, a Swiss roll), PCA mixes things that should stay apart. See the simulator below.
PCA सिर्फ़ सीधी दिशाएँ खोजता है। अगर data किसी curve पर है (moons, rings, Swiss roll), तो PCA उन चीज़ों को मिला देता है जिन्हें अलग रहना चाहिए। नीचे simulator देखें।
PCA 只能找到直线方向。如果数据分布在曲线上(月牙、圆环、瑞士卷),PCA 会把本该分开的东西混在一起。见下面的模拟器。
use Kernel PCA, UMAP, t-SNEKernel PCA, UMAP, t-SNE इस्तेमाल करें用 Kernel PCA、UMAP、t-SNE
❌
Few Samples, Many Featuresकम Samples, बहुत Features样本少、特征多
When there are fewer rows than features, the covariance estimate is noisy and the top components can capture noise. Check stability (bootstrap the components) and consider sparse or regularised PCA.
जब rows, features से कम हों, तो covariance का अनुमान noisy होता है और top components noise पकड़ सकते हैं। Stability जाँचें (components को bootstrap करें) और sparse या regularised PCA पर विचार करें।
当行数少于特征数时,协方差估计噪声很大,排在前面的主成分可能捕获的是噪声。要检查稳定性(对主成分做 bootstrap),并考虑稀疏 PCA 或正则化 PCA。
n < d, e.g. genomicsn < d, जैसे genomicsn < d,如基因组学
LIVELIVE互动Where PCA Fails — Straight Lines vs CurvesPCA कहाँ Fail होता है — सीधी Lines vs CurvesPCA 在哪里失效 — 直线与曲线

Two classes (blue and orange). PCA does not see the colours. Press "Project onto PC1" to squash each dataset onto its PC1 line, then compare the 1-nearest-neighbour accuracy in 2-D and on PC1 alone.

दो classes (नीला और नारंगी)। PCA रंग नहीं देखता। हर dataset को उसकी PC1 line पर दबाने के लिए "PC1 पर project करें" दबाएँ, फिर 2-D में और सिर्फ़ PC1 पर 1-nearest-neighbour accuracy की तुलना करें।

两个类别(蓝色和橙色)。PCA 看不到颜色。点击"投影到 PC1"把每个数据集压到它的 PC1 直线上,然后比较二维和只用 PC1 时的 1-最近邻准确率。

1-NN accuracy, 2-D1-NN accuracy, 2-D1-NN 准确率(二维)
—
1-NN accuracy, PC1 only1-NN accuracy, सिर्फ़ PC11-NN 准确率(仅 PC1)
—


SectionSection第 15 节

PCA vs Other Dimensionality Reduction MethodsPCA vs दूसरे Dimensionality Reduction तरीकेPCA 与其他降维方法对比

Methodतरीका方法Typeप्रकार类型Preservesक्या बचाता है保留什么SpeedSpeed速度Best forकिसके लिए सबसे अच्छा最适合
PCALinear, unsupervisedLinear, unsupervised线性,无监督Global varianceGlobal variance全局方差Fastतेज़快Preprocessing, compression, denoising, first look at dataPreprocessing, compression, denoising, data पर पहली नज़र预处理、压缩、去噪、初步查看数据
Kernel PCANon-linearNon-linear非线性Variance in a kernel feature spaceKernel feature space में variance核特征空间中的方差Slow: n×n kernel matrixधीमा: n×n kernel matrix慢:n×n 核矩阵Curved structure in small-to-medium dataछोटे-मध्यम data में मुड़ा ढाँचा中小规模数据中的弯曲结构
t-SNENon-linearNon-linear非线性Local neighbourhoodsLocal neighbourhoods局部邻域Slow on big dataबड़े data पर धीमा大数据上慢2-D/3-D cluster pictures only (distances between clusters are not reliable)सिर्फ़ 2-D/3-D cluster pictures (clusters के बीच की दूरी भरोसेमंद नहीं)只用于二维/三维聚类图(簇间距离不可靠)
UMAPNon-linearNon-linear非线性Local + some global structureLocal + कुछ global structure局部 + 部分全局结构Medium to fastमध्यम से तेज़中等到快Large datasets, visualisation, can also transform new dataबड़े datasets, visualisation, नए data को भी transform कर सकता है大数据集、可视化,也能变换新数据
AutoencoderNon-linear, neural networkNon-linear, neural network非线性,神经网络Learned latent featuresसीखे हुए latent features学到的潜在特征Slow to trainTrain करने में धीमा训练慢Images, audio, very complex dataImages, audio, बहुत complex data图像、音频、非常复杂的数据
LDALinear, supervisedLinear, supervised线性,有监督Class separation (at most C−1 components)Class separation (अधिकतम C−1 components)类别区分(最多 C−1 个分量)Fastतेज़快Preprocessing for classification when labels existLabels हों तो classification के लिए preprocessing有标签时作为分类的预处理
🏆
The Practitioner's Ruleव्यावहारिक नियम实践者的规则

Start with PCA: it is fast, deterministic, its loadings can be inspected, and it fits cleanly inside a Pipeline. If clusters stay hidden in a PCA plot, try UMAP for visualisation. If the structure is clearly non-linear and you need features for a model, try Kernel PCA or an autoencoder.

PCA से शुरू करें: यह तेज़ है, deterministic है, इसकी loadings जाँची जा सकती हैं, और यह Pipeline में आसानी से फ़िट होता है। अगर PCA plot में clusters छिपे रहें, तो visualisation के लिए UMAP आज़माएँ। अगर ढाँचा साफ़ तौर पर non-linear है और model के लिए features चाहिए, तो Kernel PCA या autoencoder आज़माएँ।

从 PCA 开始:它快速、结果确定、载荷可以检查,而且能干净地放进 Pipeline。如果在 PCA 图中看不出聚类,就用 UMAP 做可视化。如果结构明显是非线性的,而且需要给 model 提供特征,就试试 Kernel PCA 或自编码器。


SectionSection第 16 节

Golden Rulesसुनहरे नियम黄金法则

🌟 PCA — Rules to RememberPCA — याद रखने के नियमPCA — 必记规则
1
Always centre; scale when units differ. PCA chases variance, so big-number features win unfairly. Use StandardScaler when features have different units. When all features share one unit (pixels, sensor readings in the same unit), compare with and without scaling.
हमेशा centre करें; units अलग हों तो scale करें। PCA variance के पीछे भागता है, इसलिए बड़े numbers वाले features ग़लत तरीके से जीतते हैं। Features की units अलग हों तो StandardScaler इस्तेमाल करें। जब सभी features की एक ही unit हो (pixels, एक ही unit के sensor readings), तो scaling के साथ और बिना, दोनों की तुलना करें।
总是中心化;单位不同时要缩放。 PCA 追逐方差,所以数值大的特征会不公平地占上风。特征单位不同时用 StandardScaler。所有特征单位相同时(像素、同一单位的传感器读数),比较一下缩放与不缩放的效果。
2
Always put PCA inside a Pipeline. Fitting PCA on all data before splitting leaks test information. Pipeline([...]) fits the scaler and PCA on training folds only.
PCA को हमेशा Pipeline के अंदर रखें। Split से पहले पूरे data पर PCA fit करने से test की जानकारी leak होती है। Pipeline([...]) scaler और PCA को सिर्फ़ training folds पर fit करती है।
总是把 PCA 放进 Pipeline。 在划分之前用全部数据拟合 PCA 会泄漏测试信息。Pipeline([...]) 只在训练折上拟合缩放器和 PCA。
3
Check the explained variance before choosing k. Do not set n_components=2 blindly. Look at the scree plot and the cumulative ratio. If 2 components keep only 22% (as on standardised digits), your 2-D plot hides most of the data. Report the retained variance with every PCA plot.
k चुनने से पहले explained variance जाँचें। बिना सोचे n_components=2 न रखें। Scree plot और cumulative ratio देखें। अगर 2 components सिर्फ़ 22% रखते हैं (जैसे standardised digits पर), तो आपका 2-D plot ज़्यादातर data छिपाता है। हर PCA plot के साथ बचा variance बताएँ।
选 k 之前先看解释方差。 不要盲目设置 n_components=2。看碎石图和累计比例。如果 2 个主成分只保留 22%(比如标准化后的手写数字),你的二维图就隐藏了大部分数据。每张 PCA 图都要注明保留的方差。
4
Measure the effect on your real task. PCA is a means to an end. In our tests it cost 1.7 accuracy points on digits and changed nothing on wine. Keep it only if your metric, speed or memory actually improves.
अपने असली काम पर असर मापें। PCA एक साधन है, लक्ष्य नहीं। हमारे tests में इसकी कीमत digits पर 1.7 accuracy points थी और wine पर कुछ नहीं बदला। इसे तभी रखें जब आपका metric, speed या memory सच में सुधरे।
在实际任务上衡量效果。 PCA 是手段而不是目的。在我们的测试中,它让手写数字的准确率下降了 1.7 个百分点,在葡萄酒数据上没有任何变化。只有当指标、速度或内存真的改善时才保留它。
5
Handle missing values first. sklearn PCA does not accept NaN. Impute first (SimpleImputer or KNNImputer), then scale, then PCA, all inside one Pipeline. PCA also does nothing for class imbalance.
Missing values पहले संभालें। sklearn PCA, NaN स्वीकार नहीं करता। पहले impute करें (SimpleImputer या KNNImputer), फिर scale, फिर PCA, सब एक Pipeline में। PCA class imbalance के लिए भी कुछ नहीं करता।
先处理缺失值。 sklearn 的 PCA 不接受 NaN。先填补(SimpleImputer 或 KNNImputer),再缩放,再做 PCA,全部放在同一个 Pipeline 里。PCA 也解决不了类别不平衡问题。
6
Use IncrementalPCA for data bigger than RAM. Feed chunks with partial_fit (often 1,000–10,000 rows each, and at least n_components). Memory stays bounded and the result is usually very close to ordinary PCA.
RAM से बड़े data के लिए IncrementalPCA इस्तेमाल करें। partial_fit से chunks दें (अक्सर हर एक में 1,000–10,000 rows, और कम से कम n_components)। Memory सीमित रहती है और नतीजा आमतौर पर साधारण PCA के बहुत क़रीब होता है।
数据比内存大时用 IncrementalPCA。 用 partial_fit 分块输入(每块通常 1,000–10,000 行,且至少 n_components 行)。内存保持有限,结果通常与普通 PCA 非常接近。
7
Components are not features. Name them carefully. Loadings help you interpret a component, but treat the name as a guess. PC1 of iris looks like "flower size", yet it is a mathematical construction, and its sign can flip between runs or library versions.
Components, features नहीं हैं। नाम सोच-समझकर दें। Loadings किसी component को समझने में मदद करती हैं, पर नाम को एक अनुमान मानें। Iris का PC1 "फूल का आकार" जैसा दिखता है, फिर भी यह एक गणितीय रचना है, और इसका sign अलग runs या library versions में पलट सकता है।
主成分不是特征,命名要谨慎。 载荷可以帮助你解读主成分,但名字只是猜测。鸢尾花的 PC1 看起来像"花的大小",但它仍然是数学构造,而且正负号可能在不同运行或不同库版本之间翻转。