The Story That Explains PCAवह कहानी जो PCA समझाती है一个解释 PCA 的故事
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.
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° 的方向中散布最大的;依此类推。
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 把数据旋转到新的坐标轴上,这些轴沿着方差最大的方向,从大到小排列,所以去掉最后几个轴只会损失很少的信息。
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 只做一件简单的事:用少数几个新列代替很多列,同时尽量多地保留信息。下面四张图告诉你它是怎么做到的。
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 बदलते हैं: बहुत पुराने अंदर, कुछ नए बाहर।
行(人、图片、商品)保持不变,只有列变了:进去很多旧列,出来少数新列。
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 个点组成的三维玩具飞机。手电筒把它的影子投到墙上。墙是平的(二维),所以丢失了一个维度。点击按钮,看墙上的影子:从哪个方向照,影子仍然清楚地像一架飞机?
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 个,但道理完全一样。
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 中有六个词反复出现。下面用大白话解释每一个。
The Same Idea in 2-D, With Numbers2-D में वही विचार, Numbers के साथ同样的想法:二维 + 数字
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 देखें: एक बढ़ती है तो दूसरी घटती है।
在图上拖动(或使用滑块)来转动琥珀色直线。琥珀色小点是数据在直线上的"影子",红线表示每个点丢失的部分。注意两个进度条:一个上升,另一个就下降。
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?
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 अच्छा लगता है, पर एक हद के बाद इससे तीन असली समस्याएँ आती हैं:
现代数据集可能有成百上千个特征。特征越多听起来越好,但超过一定程度就会带来三个实际问题:
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,看最近的点如何向最远的点靠拢。
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 会创建新的列,每一列都是所有原始特征的加权组合。新列在保留方差方面是最优的,但没有直接的现实含义。
The PCA Algorithm — Five StepsPCA Algorithm — पाँच StepsPCA 算法 — 五个步骤
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 最清楚的方式。
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 如何转动。
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₂) |
|---|---|---|
| Alice | 85 | 88 |
| Bob | 70 | 72 |
| Carol | 92 | 95 |
| Dan | 60 | 58 |
| Eve | 78 | 80 |
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]]
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 दिखाती है।
点击播放,或用"下一步/上一步"逐步查看。点的移动与上面的数学完全一致,表格显示每一步的真实数字。
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关键公式
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 上。
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 个点组成的真实三维点云。三个箭头是它真实的主成分,由你的浏览器根据协方差矩阵现场计算。箭头长度随 √λ 增长。
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 时发生的事。
Bars = explained variance ratio of each component.
Bars = हर component का explained variance ratio.
柱子 = 每个主成分的解释方差比。
Scree Plot — Choosing How Many Components to KeepScree Plot — कितने Components रखें碎石图 — 选择保留多少个主成分
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.
यही scree plot है: y-axis हर component का समझाया variance है, x-axis component का number. असली data हमेशा इतना साफ़ नहीं होता। अक्सर कोई साफ़ elbow नहीं होता, और तब cumulative लक्ष्य (90% या 95%) या cross-validation बेहतर रास्ता है।
这就是碎石图:y 轴是每个主成分解释的方差,x 轴是主成分编号。真实数据并不总是这么整齐,常常没有明显的肘部,这时用累计目标(90% 或 95%)或交叉验证来选更可靠。
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 个加权主成分重建。下方碎石图显示每个主成分的真实方差。
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。
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 的输入。
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)))
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}")
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}")
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 节"损失了什么"公式的真实体现。
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}")
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)的时候。一定要像这里一样实际测量。
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 节的模拟器用的就是原始像素)。
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_}")
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 是否有用。
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。
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}")
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 行。
PCA Diagram — The Full Data FlowPCA Diagram — पूरा Data FlowPCA 示意图 — 完整的数据流
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 用到新数据上。
Key Hyperparametersमुख्य Hyperparameters关键超参数
| Parameter | Default | What it controlsक्या नियंत्रित करता है控制什么 | Tuning adviceTuning सलाह调参建议 |
|---|---|---|---|
n_components | None | How 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' 快。 |
whiten | False | Divide 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_state | None | Seed for the 'arpack' and 'randomized' solvers.'arpack' और 'randomized' solvers के लिए seed.'arpack' 和 'randomized' 求解器的随机种子。 | Set it for reproducible results.Reproducible नतीजों के लिए इसे set करें।设置它以获得可复现的结果。 |
copy | True | Whether 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:它可能被修改。 |
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()(回到原始特征空间)。
When to Use PCA — and When Not ToPCA कब इस्तेमाल करें — और कब नहीं什么时候用 PCA — 什么时候不用
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-最近邻准确率。
PCA vs Other Dimensionality Reduction MethodsPCA vs दूसरे Dimensionality Reduction तरीकेPCA 与其他降维方法对比
| Methodतरीका方法 | Typeप्रकार类型 | Preservesक्या बचाता है保留什么 | SpeedSpeed速度 | Best forकिसके लिए सबसे अच्छा最适合 |
|---|---|---|---|---|
| PCA | Linear, unsupervisedLinear, unsupervised线性,无监督 | Global varianceGlobal variance全局方差 | Fastतेज़快 | Preprocessing, compression, denoising, first look at dataPreprocessing, compression, denoising, data पर पहली नज़र预处理、压缩、去噪、初步查看数据 |
| Kernel PCA | Non-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-SNE | Non-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 के बीच की दूरी भरोसेमंद नहीं)只用于二维/三维聚类图(簇间距离不可靠) |
| UMAP | Non-linearNon-linear非线性 | Local + some global structureLocal + कुछ global structure局部 + 部分全局结构 | Medium to fastमध्यम से तेज़中等到快 | Large datasets, visualisation, can also transform new dataबड़े datasets, visualisation, नए data को भी transform कर सकता है大数据集、可视化,也能变换新数据 |
| Autoencoder | Non-linear, neural networkNon-linear, neural network非线性,神经网络 | Learned latent featuresसीखे हुए latent features学到的潜在特征 | Slow to trainTrain करने में धीमा训练慢 | Images, audio, very complex dataImages, audio, बहुत complex data图像、音频、非常复杂的数据 |
| LDA | Linear, 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有标签时作为分类的预处理 |
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 或自编码器。
Golden Rulesसुनहरे नियम黄金法则
StandardScaler when features have different units. When all features share one unit (pixels, sensor readings in the same unit), compare with and without scaling.StandardScaler इस्तेमाल करें। जब सभी features की एक ही unit हो (pixels, एक ही unit के sensor readings), तो scaling के साथ और बिना, दोनों की तुलना करें।StandardScaler。所有特征单位相同时(像素、同一单位的传感器读数),比较一下缩放与不缩放的效果。Pipeline([...]) fits the scaler and PCA on training folds only.Pipeline([...]) scaler और PCA को सिर्फ़ training folds पर fit करती है।Pipeline([...]) 只在训练折上拟合缩放器和 PCA。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.n_components=2 न रखें। Scree plot और cumulative ratio देखें। अगर 2 components सिर्फ़ 22% रखते हैं (जैसे standardised digits पर), तो आपका 2-D plot ज़्यादातर data छिपाता है। हर PCA plot के साथ बचा variance बताएँ।n_components=2。看碎石图和累计比例。如果 2 个主成分只保留 22%(比如标准化后的手写数字),你的二维图就隐藏了大部分数据。每张 PCA 图都要注明保留的方差。SimpleImputer or KNNImputer), then scale, then PCA, all inside one Pipeline. PCA also does nothing for class imbalance.SimpleImputer या KNNImputer), फिर scale, फिर PCA, सब एक Pipeline में। PCA class imbalance के लिए भी कुछ नहीं करता।SimpleImputer 或 KNNImputer),再缩放,再做 PCA,全部放在同一个 Pipeline 里。PCA 也解决不了类别不平衡问题。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.partial_fit से chunks दें (अक्सर हर एक में 1,000–10,000 rows, और कम से कम n_components)। Memory सीमित रहती है और नतीजा आमतौर पर साधारण PCA के बहुत क़रीब होता है।partial_fit 分块输入(每块通常 1,000–10,000 行,且至少 n_components 行)。内存保持有限,结果通常与普通 PCA 非常接近。