Machine Learning 📂 Dimensionality reduction · 3 of 3 156 min read

Linear Discriminant Analysis (LDA)

A comprehensive tutorial on LDA covering the intuition, maths, step-by-step worked examples, 3D interactive visualisation, Python code with colour syntax, real-world stories, comparisons and golden rules.

🌐
SectionSection第 01 节

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

The Museum Security GuardMuseum का Security Guard博物馆保安
Imagine a museum security guard whose job is to separate real visitors from thieves at the exit. Every person carries a bag with two measurements: bag weight and number of items.

A naive guard looks only at one measurement, or at whatever varies the most between people. A smart guard asks a better question: "If I mix the two measurements into one score, which mix puts visitors and thieves as far apart as possible, while keeping each group tightly packed?"

That is the whole idea behind Linear Discriminant Analysis. LDA finds a direction — called a discriminant — that maximises the gap between classes while minimising the spread inside each class. It does not look for any variance; it looks for variance that separates the classes.
एक museum के security guard की कल्पना करें जिसका काम exit पर असली visitors को चोरों से अलग करना है। हर व्यक्ति के bag के दो माप हैं: bag का वज़न और चीज़ों की संख्या।

एक भोला guard सिर्फ़ एक माप देखता है, या वह जो लोगों में सबसे ज़्यादा बदलता है। एक समझदार guard बेहतर सवाल पूछता है: "अगर मैं दोनों मापों को मिलाकर एक score बनाऊँ, तो कौन सा मेल visitors और चोरों को जितना हो सके उतना दूर रखेगा, और हर group को कसकर एक साथ रखेगा?"

यही Linear Discriminant Analysis का पूरा विचार है। LDA एक दिशा खोजता है — जिसे discriminant कहते हैं — जो classes के बीच की दूरी सबसे ज़्यादा और हर class के अंदर का फैलाव सबसे कम करे। यह कोई भी variance नहीं खोजता; यह वह variance खोजता है जो classes को अलग करे।
想象一位博物馆保安,他的工作是在出口处把真正的参观者和小偷分开。 每个人的包都有两个测量值:包的重量和物品数量。

天真的保安只看其中一个测量值,或者只看人与人之间差别最大的那个。 聪明的保安会问一个更好的问题:"如果把两个测量值混合成一个分数,哪种混合能让参观者和小偷离得最远, 同时让每一组内部都紧紧聚在一起?"

这就是线性判别分析(Linear Discriminant Analysis,LDA)的全部思想。LDA 寻找一个方向 —— 叫作判别方向(discriminant)—— 让类与类之间的距离最大,同时让每个类内部的散布最小。 它要找的不是随便什么方差,而是能把类别分开的方差。

Linear Discriminant Analysis (LDA) is a supervised method for dimensionality reduction and classification, introduced by Ronald Fisher in 1936. PCA keeps the directions with the most total variance and never looks at labels. LDA uses the labels and maximises the ratio of between-class scatter to within-class scatter, so it finds the projection that makes the classes easiest to tell apart.

Linear Discriminant Analysis (LDA) dimensionality reduction और classification का एक supervised तरीका है, जिसे Ronald Fisher ने 1936 में दिया। PCA सबसे ज़्यादा कुल variance वाली दिशाएँ रखता है और labels कभी नहीं देखता। LDA labels इस्तेमाल करता है और between-class scatter और within-class scatter के अनुपात को सबसे बड़ा करता है, इसलिए यह वह projection खोजता है जिसमें classes को अलग पहचानना सबसे आसान हो।

线性判别分析(LDA)是一种用于降维和分类的有监督(supervised)方法,由 Ronald Fisher 于 1936 年提出。 PCA 保留总方差最大的方向,从不看标签;LDA 使用标签,最大化类间散布(between-class scatter)与 类内散布(within-class scatter)之比,从而找到最容易区分各类别的投影。

🌿
Two Roles of LDALDA की दो भूमिकाएँLDA 的两种角色

LDA wears two hats. As a dimensionality reducer it projects data into at most C − 1 dimensions, where C is the number of classes — a good preprocessing step before another classifier. As a classifier it assumes each class is a Gaussian with the same covariance, and assigns a new point to the class with the highest probability. In practice this means: the nearest class mean in the LDA space, adjusted by the class priors.

LDA दो काम करता है। Dimensionality reducer के रूप में यह data को ज़्यादा से ज़्यादा C − 1 dimensions में project करता है, जहाँ C classes की संख्या है — किसी दूसरे classifier से पहले यह अच्छा preprocessing step है। Classifier के रूप में यह मानता है कि हर class एक Gaussian है जिसकी covariance एक जैसी है, और नए point को सबसे ज़्यादा probability वाली class देता है। व्यवहार में: LDA space में सबसे पास का class mean, class priors के हिसाब से थोड़ा बदला हुआ।

LDA 有两种用途。作为降维工具,它把数据投影到最多 C − 1 维(C 为类别数)—— 很适合作为其他分类器之前的预处理。作为分类器,它假设每个类都是协方差相同的高斯分布, 把新点分给概率最高的类。实际效果就是:在 LDA 空间中离哪个类均值最近,再按类别先验(priors)做一点调整。


SectionSection第 02 节

The Core Intuition — Two Objectives at Onceमुख्य समझ — एक साथ दो लक्ष्य核心直觉 — 同时实现两个目标

❌ PCA-style ProjectionPCA जैसा ProjectionPCA 式投影
What it doesयह क्या करता है它做什么Resultनतीजा结果
Maximises total varianceकुल variance सबसे ज़्यादा करता है最大化总方差Classes can overlap badlyClasses बुरी तरह मिल सकती हैं类别可能严重重叠
Follows the longest side of the dataData की सबसे लंबी तरफ़ चलता है沿着数据最长的方向Red & blue may mixलाल और नीला मिल सकते हैं红蓝可能混在一起
Ignores class labelsClass labels नहीं देखता忽略类别标签Not built for classificationClassification के लिए नहीं बना不是为分类设计的
✅ LDA ProjectionLDA ProjectionLDA 投影
What it doesयह क्या करता है它做什么Resultनतीजा结果
Maximises between-class gapClasses के बीच की दूरी सबसे ज़्यादा最大化类间距离Class means far apartClass means दूर-दूर类均值相距很远
Minimises within-class spreadClass के अंदर फैलाव सबसे कम最小化类内散布Each class tightly packedहर class कसी हुई每类紧凑
Uses class labelsClass labels इस्तेमाल करता है使用类别标签Ideal for classificationClassification के लिए बढ़िया非常适合分类
LIVELIVE互动Find the Direction That Separates the Classesवह दिशा खोजें जो Classes को अलग करे寻找能分开类别的方向

Two classes, red and blue. Drag on the picture (or use the slider) to turn the amber line. The bars below are the "shadows" of each class on the line. Press PCA, then LDA, and compare the shadows.

दो classes, लाल और नीली। Amber line घुमाने के लिए picture पर drag करें (या slider इस्तेमाल करें)। नीचे की bars line पर हर class की "परछाई" हैं। पहले PCA, फिर LDA दबाएँ और परछाइयों की तुलना करें।

两个类别,红色和蓝色。在图上拖动(或使用滑块)转动琥珀色直线。下方的柱子是每个类别在直线上的"影子"。先点 PCA,再点 LDA,比较两种影子。

Gap between meansMeans के बीच दूरी均值间距
—
Spread inside classesClasses के अंदर फैलाव类内散布
—
Fisher score JFisher score JFisher 分数 J
—
Errors with one cutएक cut से गलतियाँ一刀切错误率
—

💡
Fisher's Idea in One LineFisher का विचार एक line में一句话讲清 Fisher 的思想

J = (gap between class means)² ÷ (spread inside the classes). A big gap is good, but only if each class is narrow. PCA maximises the total spread; LDA maximises J. In the simulator they pick very different lines.

J = (class means के बीच दूरी)² ÷ (classes के अंदर का फैलाव)। बड़ी दूरी अच्छी है, पर तभी जब हर class पतली हो। PCA कुल फैलाव सबसे ज़्यादा करता है; LDA, J को। Simulator में दोनों बहुत अलग lines चुनते हैं।

J =(类均值之间的距离)² ÷(类内散布)。距离大是好事,但前提是每一类都很窄。 PCA 最大化总散布;LDA 最大化 J。在模拟器里,它们选出的直线截然不同。

The LDA Words, in PicturesLDA के शब्द, तस्वीरों में用图片解释 LDA 术语

Within-class scatter S_WWithin-class scatter S_W类内散布 S_W
how wide each class isहर class कितनी चौड़ी है每类有多宽
Adds up how far each point is from its own class mean. Small S_W = tight, compact classes.
हर point अपनी अपनी class mean से कितना दूर है, इसका जोड़। छोटा S_W = कसी हुई, सघन classes.
把每个点到它自己类均值的距离加起来。S_W 小 = 类别紧凑。
Between-class scatter S_BBetween-class scatter S_B类间散布 S_B
how far apart the classes areclasses कितनी दूर हैं类别相距多远
Measures how far each class mean is from the overall mean (weighted by class size). Big S_B = classes far apart.
हर class mean, कुल mean से कितनी दूर है (class के आकार के हिसाब से)। बड़ा S_B = classes दूर-दूर।
衡量每个类均值离总均值有多远(按类大小加权)。S_B 大 = 类别相距远。
w
Discriminant w (LD1, LD2…)Discriminant w (LD1, LD2…)判别方向 w(LD1、LD2…)
the new axisनया axis新坐标轴
The direction LDA projects onto. Each point gets one number per discriminant: its position along w.
वह दिशा जिस पर LDA project करता है। हर point को हर discriminant पर एक number मिलता है: w पर उसकी जगह।
LDA 投影的方向。每个点在每个判别方向上得到一个数:它在 w 上的位置。
gap²spread
Fisher criterion JFisher criterion JFisher 准则 J
the score LDA maximisesवह score जिसे LDA बढ़ाता हैLDA 要最大化的分数
J(w) = wᵀS_B w ÷ wᵀS_W w. Gap between classes divided by spread inside classes, both measured along w.
J(w) = wᵀS_B w ÷ wᵀS_W w. Classes के बीच की दूरी ÷ classes के अंदर का फैलाव, दोनों w पर मापे गए।
J(w) = wᵀS_B w ÷ wᵀS_W w。类间距离除以类内散布,两者都沿 w 测量。
80%20%
PriorPrior先验
how common each class isहर class कितनी आम है每类有多常见
The share of each class before seeing the data. LDA uses priors to place its decision cut; rare classes get a smaller region.
Data देखने से पहले हर class का हिस्सा। LDA decision cut रखने के लिए priors इस्तेमाल करता है; दुर्लभ classes को छोटा हिस्सा मिलता है।
看数据之前每个类所占的比例。LDA 用先验来确定决策切点;少数类得到的区域更小。
3 classes → 2 axes
At most C − 1 axesज़्यादा से ज़्यादा C − 1 axes最多 C − 1 条轴
a hard limitएक पक्की सीमा硬性上限
C class means always fit in a (C − 1)-dimensional space. 2 classes → 1 axis, 3 classes → 2 axes, 10 classes → 9 axes.
C class means हमेशा (C − 1)-dimensional space में आ जाते हैं। 2 classes → 1 axis, 3 classes → 2 axes, 10 classes → 9 axes.
C 个类均值总能放进 (C − 1) 维空间。2 类 → 1 条轴,3 类 → 2 条轴,10 类 → 9 条轴。
Objective (Fisher Criterion)Objective (Fisher Criterion)目标(Fisher 准则)
J(w) = wᵀ S_B w / wᵀ S_W w
Find the weight vector w that maximises the ratio of between-class scatter to within-class scatter.
वह weight vector w खोजें जो between-class scatter और within-class scatter का अनुपात सबसे बड़ा करे।
寻找使类间散布与类内散布之比最大的权重向量 w。
Solutionहल解
S_W⁻¹ S_B w = λ w
A generalised eigenvalue problem. The top eigenvectors of S_W⁻¹ S_B are the best discriminant directions. For 2 classes it simplifies to w ∝ S_W⁻¹(μ₁ − μ₂).
यह generalised eigenvalue problem है। S_W⁻¹ S_B के top eigenvectors सबसे अच्छी discriminant दिशाएँ हैं। 2 classes के लिए यह w ∝ S_W⁻¹(μ₁ − μ₂) बन जाता है।
这是一个广义特征值问题。S_W⁻¹ S_B 的前几个特征向量就是最佳判别方向。两类时简化为 w ∝ S_W⁻¹(μ₁ − μ₂)。
Between-Class ScatterBetween-Class Scatter类间散布
S_B = Σ nᵢ (μᵢ − μ)(μᵢ − μ)ᵀ
How far the class means are from the overall mean. Large S_B = well-separated classes.
Class means, कुल mean से कितनी दूर हैं। बड़ा S_B = अच्छी तरह अलग classes.
各类均值离总均值有多远。S_B 大 = 类别分得开。
Within-Class ScatterWithin-Class Scatter类内散布
S_W = Σ Σ (x − μᵢ)(x − μᵢ)ᵀ
How spread out points are around their own class mean. Small S_W = tightly clustered classes.
Points अपनी class mean के आसपास कितने फैले हैं। छोटा S_W = कसकर जमी classes.
各点围绕自己类均值的分散程度。S_W 小 = 类内紧凑。

SectionSection第 03 节

3-D Visualisation — PCA View vs LDA View3-D Visualisation — PCA View vs LDA View三维可视化 — PCA 视图与 LDA 视图

Here are three classes in 3-D. All three share a big "noise" direction (along x₃). Both PCA and LDA are computed live in your browser from the data. PCA keeps the two directions with the most total spread. LDA keeps the two directions that separate the class means. Switch between them and watch the right panel.

यहाँ 3-D में तीन classes हैं। तीनों में एक बड़ी "noise" दिशा (x₃ के साथ) साझा है। PCA और LDA दोनों आपके browser में data से live निकाले जाते हैं। PCA सबसे ज़्यादा कुल फैलाव वाली दो दिशाएँ रखता है। LDA वे दो दिशाएँ रखता है जो class means को अलग करती हैं। दोनों के बीच बदलें और दाईं panel देखें।

这里是三维空间中的三个类别。它们共有一个很大的"噪声"方向(沿 x₃)。PCA 和 LDA 都由你的浏览器根据数据实时计算。 PCA 保留总散布最大的两个方向;LDA 保留能把类均值分开的两个方向。在两者之间切换,观察右侧面板。

LIVELIVE互动3 Classes in 3-D — Which 2-D View Separates Them?3-D में 3 Classes — कौन सा 2-D View उन्हें अलग करता है?三维中的 3 个类别 — 哪个二维视图能把它们分开?

Left: the 3-D data (drag to rotate). Arrows show the two axes of the chosen method. Right: the data projected onto those two axes.

बाएँ: 3-D data (घुमाने के लिए drag करें)। तीर चुने गए तरीके के दो axes दिखाते हैं। दाएँ: उन दो axes पर project किया गया data.

左:三维数据(拖动旋转)。箭头表示所选方法的两条轴。右:投影到这两条轴上的数据。

1-NN accuracy, PCA 2-D1-NN accuracy, PCA 2-D1-NN 准确率(PCA 二维)
—
1-NN accuracy, LDA 2-D1-NN accuracy, LDA 2-D1-NN 准确率(LDA 二维)
—


SectionSection第 04 节

Step-by-Step Maths — A Worked ExampleStep-by-Step गणित — एक हल किया हुआ Example逐步推导 — 一个完整例题

Classifying Wines by ChemistryChemistry से Wines पहचानना用化学成分区分葡萄酒
A wine lab measures two chemicals in each bottle: Alcohol % and Malic Acid. They have several wine varieties, such as Barolo and Barbera. The head chemist wants one single scale that, when a new bottle is measured, immediately tells her which variety it is. LDA finds that scale.
एक wine lab हर bottle में दो रसायन मापती है: Alcohol % और Malic Acid. उनके पास कई किस्म की wines हैं, जैसे Barolo और Barbera. मुख्य chemist एक ऐसा अकेला पैमाना चाहती है जो नई bottle मापते ही बता दे कि वह कौन सी किस्म है। LDA वही पैमाना खोजता है।
一个葡萄酒实验室测量每瓶酒中的两种化学成分:酒精度 % 和苹果酸。 他们有好几个品种,比如 Barolo 和 Barbera。首席化学家想要一把唯一的"尺子":新酒一测量,就能立刻知道是哪个品种。LDA 找的就是这把尺子。
🧮 LDA — Step-by-Step AlgorithmLDA — Step-by-Step AlgorithmLDA — 逐步算法
Step 1
Compute the class means μ₁, μ₂, … μ_C and the overall mean μ for each feature. हर feature के लिए class means μ₁, μ₂, … μ_C और कुल mean μ निकालें। 对每个特征计算类均值 μ₁, μ₂, … μ_C 和总均值 μ。
Step 2
Compute the Within-Class Scatter Matrix S_W = Σ_c Σ_{x∈c} (x−μ_c)(x−μ_c)ᵀ Within-Class Scatter Matrix निकालें: S_W = Σ_c Σ_{x∈c} (x−μ_c)(x−μ_c)ᵀ 计算类内散布矩阵 S_W = Σ_c Σ_{x∈c} (x−μ_c)(x−μ_c)ᵀ
Step 3
Compute the Between-Class Scatter Matrix S_B = Σ_c n_c (μ_c−μ)(μ_c−μ)ᵀ Between-Class Scatter Matrix निकालें: S_B = Σ_c n_c (μ_c−μ)(μ_c−μ)ᵀ 计算类间散布矩阵 S_B = Σ_c n_c (μ_c−μ)(μ_c−μ)ᵀ
Step 4
Solve the generalised eigenvalue problem: S_W⁻¹ S_B w = λ w Generalised eigenvalue problem हल करें: S_W⁻¹ S_B w = λ w 求解广义特征值问题:S_W⁻¹ S_B w = λ w
Step 5
Sort eigenvectors by descending eigenvalue. Take the top k ≤ min(C−1, d) eigenvectors as discriminant axes. Eigenvectors को eigenvalue के बड़े से छोटे क्रम में रखें। Top k ≤ min(C−1, d) eigenvectors को discriminant axes बनाएँ। 按特征值从大到小排序特征向量,取前 k ≤ min(C−1, d) 个作为判别轴。
Step 6
Project the data onto these axes: Z = X · W where W = [w₁ | w₂ | … | wₖ] Data को इन axes पर project करें: Z = X · W जहाँ W = [w₁ | w₂ | … | wₖ] 把数据投影到这些轴上:Z = X · W,其中 W = [w₁ | w₂ | … | wₖ]

Numerical Mini-Example (2 Features, 2 Classes, 4 Points)छोटा Numerical Example (2 Features, 2 Classes, 4 Points)数值小例题(2 个特征、2 个类别、4 个点)

SampleSample样本Alcohol %Malic AcidClassClass类别
114.21.7Barolo (C₁)
213.81.9Barolo (C₁)
312.43.1Barbera (C₂)
411.93.5Barbera (C₂)
📐 Computation Walkthroughहिसाब step by step计算过程
MeansMeans均值
μ₁ = [14.0, 1.8]  |  μ₂ = [12.15, 3.3]  |  μ = [13.075, 2.55] μ₁ = [14.0, 1.8]  |  μ₂ = [12.15, 3.3]  |  μ = [13.075, 2.55] μ₁ = [14.0, 1.8]  |  μ₂ = [12.15, 3.3]  |  μ = [13.075, 2.55]
S_W
C₁ deviations [+0.2, −0.1] and [−0.2, +0.1] → S_W₁ = [[0.08, −0.04], [−0.04, 0.02]]
C₂ deviations [+0.25, −0.2] and [−0.25, +0.2] → S_W₂ = [[0.125, −0.1], [−0.1, 0.08]]
S_W = [[0.205, −0.14], [−0.14, 0.10]]
C₁ के विचलन [+0.2, −0.1] और [−0.2, +0.1] → S_W₁ = [[0.08, −0.04], [−0.04, 0.02]]
C₂ के विचलन [+0.25, −0.2] और [−0.25, +0.2] → S_W₂ = [[0.125, −0.1], [−0.1, 0.08]]
S_W = [[0.205, −0.14], [−0.14, 0.10]]
C₁ 的偏差 [+0.2, −0.1] 和 [−0.2, +0.1] → S_W₁ = [[0.08, −0.04], [−0.04, 0.02]]
C₂ 的偏差 [+0.25, −0.2] 和 [−0.25, +0.2] → S_W₂ = [[0.125, −0.1], [−0.1, 0.08]]
S_W = [[0.205, −0.14], [−0.14, 0.10]]
S_B
μ₁ − μ = [0.925, −0.75] and μ₂ − μ = [−0.925, 0.75]
S_B = 2·(μ₁−μ)(μ₁−μ)ᵀ + 2·(μ₂−μ)(μ₂−μ)ᵀ
S_B ≈ [[3.42, −2.78], [−2.78, 2.25]]
μ₁ − μ = [0.925, −0.75] और μ₂ − μ = [−0.925, 0.75]
S_B = 2·(μ₁−μ)(μ₁−μ)ᵀ + 2·(μ₂−μ)(μ₂−μ)ᵀ
S_B ≈ [[3.42, −2.78], [−2.78, 2.25]]
μ₁ − μ = [0.925, −0.75],μ₂ − μ = [−0.925, 0.75]
S_B = 2·(μ₁−μ)(μ₁−μ)ᵀ + 2·(μ₂−μ)(μ₂−μ)ᵀ
S_B ≈ [[3.42, −2.78], [−2.78, 2.25]]
S_W⁻¹S_W⁻¹S_W⁻¹
det(S_W) = 0.205 × 0.10 − 0.14² = 0.0009 → S_W⁻¹ = (1/0.0009)·[[0.10, 0.14], [0.14, 0.205]] ≈ [[111.1, 155.6], [155.6, 227.8]] det(S_W) = 0.205 × 0.10 − 0.14² = 0.0009 → S_W⁻¹ = (1/0.0009)·[[0.10, 0.14], [0.14, 0.205]] ≈ [[111.1, 155.6], [155.6, 227.8]] det(S_W) = 0.205 × 0.10 − 0.14² = 0.0009 → S_W⁻¹ = (1/0.0009)·[[0.10, 0.14], [0.14, 0.205]] ≈ [[111.1, 155.6], [155.6, 227.8]]
Optimal wसबसे अच्छा w最优 w
w = S_W⁻¹(μ₁ − μ₂) = S_W⁻¹·[1.85, −1.50] ≈ [−27.8, −53.9]
LD1 direction (unit length): [−0.46, −0.89]
w = S_W⁻¹(μ₁ − μ₂) = S_W⁻¹·[1.85, −1.50] ≈ [−27.8, −53.9]
LD1 दिशा (unit length): [−0.46, −0.89]
w = S_W⁻¹(μ₁ − μ₂) = S_W⁻¹·[1.85, −1.50] ≈ [−27.8, −53.9]
LD1 方向(单位长度):[−0.46, −0.89]
ProjectProject投影
x·w: Barolo −8.02 and −8.01; Barbera −8.44 and −8.56. A cut at about −8.24 separates them. The gap (0.48) is huge compared with the spread inside each class. x·w: Barolo −8.02 और −8.01; Barbera −8.44 और −8.56. लगभग −8.24 पर एक cut इन्हें अलग करता है। हर class के अंदर के फैलाव की तुलना में दूरी (0.48) बहुत बड़ी है। x·w:Barolo 为 −8.02 和 −8.01;Barbera 为 −8.44 和 −8.56。在约 −8.24 处切一刀就能分开。与类内散布相比,间距(0.48)非常大。
LIVELIVE互动Watch the Worked Example Step by Stepहल किया हुआ Example step by step देखें逐步观看这道例题

The same four bottles as in the table. Press Play, or use Next and Back.

Table वाली वही चार bottles. Play दबाएँ, या आगे और पीछे इस्तेमाल करें।

和表格中相同的四瓶酒。点击播放,或使用"下一步/上一步"。

🔍
Why Does w Lean on Malic Acid?w, Malic Acid की ओर क्यों झुका है?为什么 w 更偏向苹果酸?

The class means differ more in alcohol (1.85) than in malic acid (1.5), yet w puts more weight on malic acid. The reason is S_W⁻¹: inside each class, the two features move in opposite directions (negative covariance), and LDA "undoes" that shared within-class pattern. With only four points S_W is tiny and almost singular, so in real work you would use more data or shrinkage (Section 07).

Class means में alcohol (1.85) का फ़र्क malic acid (1.5) से ज़्यादा है, फिर भी w malic acid को ज़्यादा weight देता है। वजह है S_W⁻¹: हर class के अंदर दोनों features उल्टी दिशा में चलते हैं (negative covariance), और LDA उस साझा within-class pattern को "हटा" देता है। सिर्फ़ चार points के साथ S_W बहुत छोटा और लगभग singular है, इसलिए असली काम में आप ज़्यादा data या shrinkage (Section 07) इस्तेमाल करेंगे।

两类均值在酒精度上的差(1.85)比苹果酸(1.5)大,但 w 却给苹果酸更大的权重。原因在于 S_W⁻¹: 在每个类内部,两个特征朝相反方向变化(负协方差),LDA 会"抵消"这种类内共同的模式。 只有四个点时 S_W 非常小且几乎奇异,所以实际工作中应使用更多数据或收缩(第 07 节)。

🎯
Maximum Dimensions After LDALDA के बाद अधिकतम DimensionsLDA 之后的最大维数

LDA can produce at most C − 1 discriminant components, where C is the number of classes. A 3-class problem gives at most 2 LDA components. PCA can give up to min(n − 1, d) components. For classification, a 10-class dataset projected to 9 LDA dimensions is usually far more useful than 9 PCA dimensions, because LDA used the labels.

LDA ज़्यादा से ज़्यादा C − 1 discriminant components दे सकता है, जहाँ C classes की संख्या है। 3-class problem में ज़्यादा से ज़्यादा 2 LDA components. PCA, min(n − 1, d) तक components दे सकता है। Classification के लिए, 10-class dataset के 9 LDA dimensions आमतौर पर 9 PCA dimensions से कहीं ज़्यादा काम के होते हैं, क्योंकि LDA ने labels इस्तेमाल किए।

LDA 最多只能产生 C − 1 个判别分量(C 为类别数)。三分类问题最多 2 个 LDA 分量;PCA 最多可以有 min(n − 1, d) 个。 就分类而言,把 10 类数据投影到 9 个 LDA 维度,通常比 9 个 PCA 维度有用得多,因为 LDA 使用了标签。


SectionSection第 05 节

LDA Assumptions — The Fine PrintLDA की मान्यताएँ — बारीक बातेंLDA 的假设 — 细则

📊
Gaussian Class DistributionsGaussian Class Distributions各类服从高斯分布
NormalityNormality正态性
Each class is assumed to follow a multivariate Gaussian (normal) distribution. LDA is robust to mild violations, but heavy skew or several clusters inside one class will hurt accuracy.
हर class को multivariate Gaussian (normal) distribution माना जाता है। हल्के उल्लंघन से LDA पर ज़्यादा असर नहीं पड़ता, पर बहुत टेढ़ा (skewed) data या एक class के अंदर कई clusters accuracy घटाते हैं।
假设每个类服从多元高斯(正态)分布。LDA 对轻微违背比较稳健,但严重偏斜或一个类内有多个簇会降低准确率。
✅ Check: Q-Q plots per classजाँच: हर class के Q-Q plots检查:每类的 Q-Q 图
❌ Fix: transform features (log, Box-Cox)इलाज: features बदलें (log, Box-Cox)修正:变换特征(log、Box-Cox)
⚖️
Equal Covariance Matricesबराबर Covariance Matrices协方差矩阵相等
HomoscedasticityHomoscedasticity方差齐性
All classes share the same covariance (same shape and tilt); only their means differ. If shapes differ a lot, use Quadratic Discriminant Analysis (QDA), which fits one covariance per class. Try it in Section 10.
सभी classes की covariance (आकार और झुकाव) एक जैसी है; सिर्फ़ means अलग हैं। अगर आकार बहुत अलग हों, तो Quadratic Discriminant Analysis (QDA) इस्तेमाल करें, जो हर class की अलग covariance लेता है। Section 10 में आज़माएँ।
所有类共享相同的协方差(形状和倾斜相同),只有均值不同。如果形状差别很大,请使用二次判别分析(QDA),它为每个类单独估计协方差。在第 10 节试试。
✅ Check: compare class covariances (Box's M test is very sensitive)जाँच: classes की covariances की तुलना करें (Box's M test बहुत संवेदनशील है)检查:比较各类协方差(Box's M 检验非常敏感)
❌ Fix: switch to QDA or regularised QDAइलाज: QDA या regularised QDA修正:改用 QDA 或正则化 QDA
🔗
Independent Samplesस्वतंत्र Samples样本独立
IndependenceIndependence独立性
Observations must be independent of each other. Repeated measures from the same person, time series, or grouped data break this. Correlated features are fine; correlated samples are not.
Observations एक-दूसरे से स्वतंत्र होनी चाहिए। एक ही व्यक्ति के बार-बार माप, time series, या grouped data इसे तोड़ते हैं। Correlated features ठीक हैं; correlated samples नहीं।
观测之间必须相互独立。同一个人的重复测量、时间序列或分组数据都会违背这一点。特征相关没问题,样本相关则不行。
✅ Check: study designजाँच: study design检查:研究设计
❌ Fix: group-aware CV, mixed modelsइलाज: group-aware CV, mixed models修正:按组交叉验证、混合模型
⚠️
The Singularity ProblemSingularity की समस्या奇异性问题

If there are about as many features as samples, or more (d ≥ n), S_W becomes singular and cannot be inverted. Fixes: apply PCA first, use solver='lsqr' or solver='eigen' with shrinkage='auto' in scikit-learn, or use Regularised LDA, which adds a shrinkage term to S_W. (The default 'svd' solver does not crash, but it can still overfit badly.)

अगर features लगभग samples जितने या उनसे ज़्यादा हों (d ≥ n), तो S_W singular हो जाता है और उसका inverse नहीं निकलता। इलाज: पहले PCA लगाएँ, scikit-learn में shrinkage='auto' के साथ solver='lsqr' या solver='eigen' इस्तेमाल करें, या Regularised LDA इस्तेमाल करें जो S_W में shrinkage जोड़ता है। (Default 'svd' solver crash नहीं होता, पर फिर भी बुरी तरह overfit कर सकता है।)

如果特征数接近或超过样本数(d ≥ n),S_W 会变成奇异矩阵,无法求逆。 解决办法:先做 PCA;在 scikit-learn 中使用 solver='lsqr' 或 solver='eigen' 并设置 shrinkage='auto'; 或者使用正则化 LDA,给 S_W 加上收缩项。(默认的 'svd' 求解器不会报错,但仍可能严重过拟合。)


SectionSection第 06 节

Python Implementation — Wine DatasetPython Implementation — Wine DatasetPython 实现 — 葡萄酒数据集

LDA as a Dimensionality Reducer + VisualiserDimensionality Reducer + Visualiser के रूप में LDALDA 作为降维与可视化工具

from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.datasets import load_wine
from sklearn.preprocessing import StandardScaler
import numpy as np
import matplotlib.pyplot as plt

# Load the UCI Wine dataset — 178 samples, 13 chemical features, 3 classes
wine = load_wine()
X, y = wine.data, wine.target
labels = wine.target_names  # ['class_0', 'class_1', 'class_2']

# Standardise features (recommended for LDA)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# Fit LDA — project down to 2 components (C-1 = 3-1 = 2 max)
lda = LinearDiscriminantAnalysis(n_components=2)
X_lda = lda.fit_transform(X_scaled, y)

# Explained variance ratio of each discriminant
print("Explained variance ratio:", lda.explained_variance_ratio_)
print(f"LD1 explains: {lda.explained_variance_ratio_[0]*100:.1f}%")
print(f"LD2 explains: {lda.explained_variance_ratio_[1]*100:.1f}%")

# Plot the 2D projection
colors = ['#f87171', '#60a5fa', '#34d399']
plt.figure(figsize=(8,6))
for i, label in enumerate(labels):
    mask = y == i
    plt.scatter(X_lda[mask, 0], X_lda[mask, 1],
                label=label, color=colors[i], alpha=0.8, edgecolors='white', s=60)
plt.xlabel('LD1'); plt.ylabel('LD2')
plt.title('Wine Dataset — LDA 2D Projection')
plt.legend(); plt.tight_layout(); plt.show()
OUTPUT
Explained variance ratio: [0.68747889 0.31252111] LD1 explains: 68.7% LD2 explains: 31.3%

LDA as a ClassifierClassifier के रूप में LDALDA 作为分类器

from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.datasets import load_wine
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline

# Build a proper pipeline: scale → LDA classifier
pipe = Pipeline([
    ('scaler', StandardScaler()),
    ('lda',    LinearDiscriminantAnalysis())   # n_components=None → uses all C-1
])

wine = load_wine()
X, y = wine.data, wine.target

# 5-fold stratified cross-validation
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(pipe, X, y, cv=cv, scoring='accuracy')

print(f"CV Accuracy: {scores.mean():.4f} +/- {scores.std():.4f}")

# Full fit + detailed report
from sklearn.model_selection import train_test_split
X_tr, X_te, y_tr, y_te = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=42
)
pipe.fit(X_tr, y_tr)
y_pred = pipe.predict(X_te)

print(classification_report(y_te, y_pred, target_names=wine.target_names))
print("Confusion Matrix:")
print(confusion_matrix(y_te, y_pred))
OUTPUT
CV Accuracy: 0.9830 +/- 0.0139 precision recall f1-score support class_0 0.94 1.00 0.97 15 class_1 0.94 0.94 0.94 18 class_2 1.00 0.92 0.96 12 accuracy 0.96 45 macro avg 0.96 0.95 0.96 45 weighted avg 0.96 0.96 0.96 45 Confusion Matrix: [[15 0 0] [ 1 17 0] [ 0 1 11]]
⚡
LDA Is Almost Perfect on WineWine पर LDA लगभग perfect हैLDA 在葡萄酒数据上几乎完美

98.3% accuracy with 5-fold cross-validation, and 96% on a held-out test set (2 mistakes out of 45). LDA has only 13 features and 3 classes to work with, so its decisions live in just 2 discriminant dimensions. When LDA's assumptions roughly hold — as they do for chemical measurements — those 2 dimensions keep almost all the information needed to classify.

5-fold cross-validation के साथ 98.3% accuracy, और अलग रखे test set पर 96% (45 में से 2 गलतियाँ)। LDA के पास सिर्फ़ 13 features और 3 classes हैं, इसलिए उसके फ़ैसले सिर्फ़ 2 discriminant dimensions में होते हैं। जब LDA की मान्यताएँ मोटे तौर पर सही हों — जैसे chemical मापों में — तो ये 2 dimensions classify करने के लिए लगभग सारी ज़रूरी जानकारी रखते हैं।

5 折交叉验证准确率 98.3%,在留出的测试集上为 96%(45 个中错 2 个)。数据只有 13 个特征和 3 个类别, 所以 LDA 的决策只发生在 2 个判别维度中。当 LDA 的假设大致成立时(化学测量数据通常如此), 这 2 个维度就保留了分类所需的几乎全部信息。


SectionSection第 07 节

Regularised LDA — Handling Small Samples & Many FeaturesRegularised LDA — कम Samples और ज़्यादा Features正则化 LDA — 应对小样本与高维特征

Standard LDA struggles when there are many features and few samples: S_W is estimated badly (or is singular). Regularised LDA adds a shrinkage penalty that pulls the within-class covariance toward a simple diagonal matrix:

जब features बहुत और samples कम हों, तो साधारण LDA मुश्किल में पड़ता है: S_W ठीक से estimate नहीं होता (या singular होता है)। Regularised LDA एक shrinkage penalty जोड़ता है जो within-class covariance को एक सरल diagonal matrix की ओर खींचती है:

特征多、样本少时,标准 LDA 会遇到困难:S_W 估计得很差(甚至是奇异的)。 正则化 LDA 加入一个收缩惩罚,把类内协方差拉向一个简单的对角矩阵:

Regularised S_WRegularised S_W正则化 S_W
S_W(λ) = (1−λ)·S_W + λ·tr(S_W)/d · I
λ = 0 is standard LDA. λ = 1 replaces the covariance by a scaled identity (all features independent, equal variance). λ is chosen by Ledoit-Wolf or cross-validation.
λ = 0 साधारण LDA है। λ = 1 पर covariance की जगह scaled identity आ जाती है (सभी features स्वतंत्र, बराबर variance)। λ को Ledoit-Wolf या cross-validation से चुना जाता है।
λ = 0 就是标准 LDA;λ = 1 时协方差被替换为缩放的单位矩阵(所有特征独立、方差相等)。λ 由 Ledoit-Wolf 或交叉验证选择。
Sklearn ParameterSklearn ParameterSklearn 参数
shrinkage='auto'
Set shrinkage='auto' with solver='lsqr' or solver='eigen' to estimate the best λ automatically with the Ledoit-Wolf formula.
solver='lsqr' या solver='eigen' के साथ shrinkage='auto' रखें, ताकि Ledoit-Wolf formula से सबसे अच्छा λ अपने आप मिले।
配合 solver='lsqr' 或 solver='eigen' 设置 shrinkage='auto',即可用 Ledoit-Wolf 公式自动估计最佳 λ。
LIVELIVE互动When Samples Are Few — Plain LDA vs Shrinkageजब Samples कम हों — साधारण LDA vs Shrinkage样本很少时 — 普通 LDA 与收缩 LDA

Two classes, 30 features, only 10 of them useful. Every point on the curves is a real experiment run in your browser: train on n samples per class, test on 600 new points, average of 8 repeats. Move the slider.

दो classes, 30 features, जिनमें सिर्फ़ 10 काम के हैं। Curves का हर point आपके browser में चला एक असली experiment है: हर class के n samples पर train, 600 नए points पर test, 8 बार का औसत। Slider चलाएँ।

两个类别、30 个特征,其中只有 10 个有用。曲线上的每个点都是在你浏览器中真实运行的实验:每类用 n 个样本训练,在 600 个新点上测试,重复 8 次取平均。拖动滑块。

Plain LDAShrinkage
Plain LDA accuracyसाधारण LDA accuracy普通 LDA 准确率
—
Shrinkage LDA accuracyShrinkage LDA accuracy收缩 LDA 准确率
—

from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline

# Simulate high-dimensional, small-sample scenario
# 200 samples, 150 features — classic small-n-large-p regime
X, y = make_classification(
    n_samples=200, n_features=150, n_informative=30,
    n_classes=3, n_clusters_per_class=1, random_state=42
)

# Standard LDA — likely to fail or be unstable
std_pipe = Pipeline([
    ('sc', StandardScaler()),
    ('lda', LinearDiscriminantAnalysis(solver='svd'))    # SVD-based, no shrinkage
])

# Regularised LDA — Ledoit-Wolf automatic shrinkage
reg_pipe = Pipeline([
    ('sc', StandardScaler()),
    ('lda', LinearDiscriminantAnalysis(
        solver='lsqr',
        shrinkage='auto'   # Ledoit-Wolf optimal shrinkage
    ))
])

std_scores = cross_val_score(std_pipe, X, y, cv=5, scoring='accuracy')
reg_scores = cross_val_score(reg_pipe, X, y, cv=5, scoring='accuracy')

print(f"Standard LDA CV:    {std_scores.mean():.4f} +/- {std_scores.std():.4f}")
print(f"Regularised LDA CV: {reg_scores.mean():.4f} +/- {reg_scores.std():.4f}")

# Manual shrinkage tuning (grid search over λ)
from sklearn.model_selection import GridSearchCV
param_grid = {'lda__shrinkage': [0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0, 'auto']}
gs = GridSearchCV(reg_pipe, param_grid, cv=5, scoring='accuracy')
gs.fit(X, y)
print(f"Best shrinkage: {gs.best_params_}")
print(f"Best CV accuracy: {gs.best_score_:.4f}")
OUTPUT
Standard LDA CV: 0.4800 +/- 0.0187 Regularised LDA CV: 0.8000 +/- 0.0570 Best shrinkage: {'lda__shrinkage': 'auto'} Best CV accuracy: 0.8000
🎯
Shrinkage Rescues LDAShrinkage, LDA को बचाता है收缩挽救了 LDA

With 150 features and only 160 training rows per fold, plain LDA scores 48% (barely above the 33% of guessing among 3 classes). Ledoit-Wolf shrinkage lifts it to 80% with one extra argument. The grid search agrees: 'auto' is as good as the best hand-picked value.

150 features और हर fold में सिर्फ़ 160 training rows के साथ, साधारण LDA 48% पर है (3 classes में अंदाज़े के 33% से बस थोड़ा ऊपर)। Ledoit-Wolf shrinkage सिर्फ़ एक argument से इसे 80% तक ले जाता है। Grid search भी यही कहता है: 'auto' हाथ से चुनी सबसे अच्छी value जितना अच्छा है।

150 个特征、每折只有 160 行训练数据时,普通 LDA 只有 48%(三分类随机猜测是 33%,只高一点点)。 加一个参数使用 Ledoit-Wolf 收缩,准确率就升到 80%。网格搜索也给出同样结论:'auto' 与手工挑选的最佳值一样好。


SectionSection第 08 节

Real-World Example — Face Recognition (Fisherfaces)Real-World Example — चेहरा पहचानना (Fisherfaces)实战案例 — 人脸识别(Fisherfaces)

Recognising Faces in a Crowdभीड़ में चेहरे पहचानना在人群中识别人脸
The Olivetti (AT&T) face set has 40 people with 10 photos each = 400 images. In scikit-learn each photo is 64×64 grey pixels, so 4,096 features per image. You cannot run LDA directly on 4,096 dimensions with only 400 samples: S_W would be singular. The classic solution is PCA first, then LDA. PCA (the "Eigenfaces" step) reduces the images to ~150 numbers, then LDA (the "Fisherfaces" step) finds the 39 directions that best separate the 40 people.
Olivetti (AT&T) face set में 40 लोग हैं और हर एक की 10 photos = 400 images. scikit-learn में हर photo 64×64 grey pixels की है, यानी हर image में 4,096 features. सिर्फ़ 400 samples के साथ 4,096 dimensions पर सीधे LDA नहीं चल सकता: S_W singular होगा। पुराना और भरोसेमंद हल है पहले PCA, फिर LDA. PCA ("Eigenfaces" step) images को ~150 numbers में घटाता है, फिर LDA ("Fisherfaces" step) वे 39 दिशाएँ खोजता है जो 40 लोगों को सबसे अच्छी तरह अलग करती हैं।
Olivetti(AT&T)人脸数据集有 40 个人,每人 10 张照片,共 400 张。在 scikit-learn 中每张照片是 64×64 的灰度像素, 即每张图 4,096 个特征。只有 400 个样本时,无法直接在 4,096 维上做 LDA:S_W 会是奇异的。 经典解法是先 PCA,再 LDA。PCA("特征脸 Eigenfaces"步骤)把图像压缩到约 150 个数, 然后 LDA("Fisherfaces"步骤)找出最能区分 40 个人的 39 个方向。
from sklearn.datasets import fetch_olivetti_faces
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.preprocessing import StandardScaler

# Olivetti Faces: 400 images, 4096 features, 40 classes
data = fetch_olivetti_faces(shuffle=True, random_state=42)
X, y = data.data, data.target  # X shape: (400, 4096)

# Fisherfaces pipeline: PCA (Eigenfaces) → LDA (Fisherfaces)
fisherfaces = Pipeline([
    ('scale', StandardScaler()),
    ('pca',   PCA(n_components=150, whiten=True, random_state=42)),
    ('lda',   LinearDiscriminantAnalysis())   # max 39 components (40 classes - 1)
])

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(fisherfaces, X, y, cv=cv, scoring='accuracy')

print("=== Fisherfaces (PCA → LDA) ===")
print(f"CV Accuracy: {scores.mean()*100:.1f}% +/- {scores.std()*100:.1f}%")
print(f"Input dims:  4096 → PCA: 150 → LDA: 39")

# Compare: PCA-only nearest centroid
from sklearn.neighbors import NearestCentroid
pca_only = Pipeline([
    ('scale', StandardScaler()),
    ('pca',   PCA(n_components=150, whiten=True, random_state=42)),
    ('clf',   NearestCentroid())
])
pca_scores = cross_val_score(pca_only, X, y, cv=cv, scoring='accuracy')
print("\n=== PCA-only nearest centroid ===")
print(f"CV Accuracy: {pca_scores.mean()*100:.1f}% +/- {pca_scores.std()*100:.1f}%")
💾
About This Exampleइस Example के बारे में关于这个例子

fetch_olivetti_faces() downloads the images the first time (about 1.5 MB), so run it on your own machine. Our test machine had no internet access, so below we run the same PCA → LDA pipeline on the handwritten digits that ship with scikit-learn. These numbers are real.

fetch_olivetti_faces() पहली बार images download करता है (लगभग 1.5 MB), इसलिए इसे अपनी machine पर चलाएँ। हमारी test machine पर internet नहीं था, इसलिए नीचे हम वही PCA → LDA pipeline scikit-learn के साथ आने वाले हाथ से लिखे digits पर चलाते हैं। ये numbers असली हैं।

fetch_olivetti_faces() 第一次运行时会下载图片(约 1.5 MB),请在你自己的电脑上运行。 我们的测试机器无法联网,所以下面在 scikit-learn 自带的手写数字数据上运行同样的 PCA → LDA 流水线。这些数字是真实的。

from sklearn.datasets import load_digits
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.decomposition import PCA
from sklearn.neighbors import NearestCentroid
from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.preprocessing import StandardScaler

# Same idea, runs offline: 1,797 digit images (8×8 = 64 pixels), 10 classes
X, y = load_digits(return_X_y=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

pca_only = Pipeline([
    ('scale', StandardScaler()),
    ('pca',   PCA(n_components=30, random_state=42)),
    ('clf',   NearestCentroid()),            # PCA alone, then nearest class mean
])
pca_lda = Pipeline([
    ('scale', StandardScaler()),
    ('pca',   PCA(n_components=30, random_state=42)),
    ('lda',   LinearDiscriminantAnalysis()), # max 9 components (10 classes - 1)
])

for name, model in [("PCA-only nearest centroid", pca_only), ("PCA -> LDA (Fisher)", pca_lda)]:
    s = cross_val_score(model, X, y, cv=cv, scoring='accuracy')
    print(f"{name:26s}: {s.mean()*100:.1f}% +/- {s.std()*100:.1f}%")
print("Dims: 64 -> PCA: 30 -> LDA: 9")
OUTPUT
PCA-only nearest centroid : 87.9% +/- 0.6% PCA -> LDA (Fisher) : 93.6% +/- 0.8% Dims: 64 -> PCA: 30 -> LDA: 9
🏆
Adding LDA After PCA HelpsPCA के बाद LDA जोड़ने से फ़ायदा在 PCA 之后加 LDA 有明显帮助

PCA finds the directions of maximum variance, not maximum separability. Adding LDA after PCA raises accuracy from 87.9% to 93.6% on the digits, because LDA knows which class each image belongs to and rotates the space to separate the 10 digits. On faces the same idea is the famous Fisherfaces method (Belhumeur et al., 1997).

PCA सबसे ज़्यादा variance की दिशाएँ खोजता है, सबसे ज़्यादा अलगाव की नहीं। Digits पर PCA के बाद LDA जोड़ने से accuracy 87.9% से 93.6% हो जाती है, क्योंकि LDA जानता है कि हर image किस class की है और space को घुमाकर 10 digits को अलग करता है। चेहरों पर यही विचार मशहूर Fisherfaces तरीका है (Belhumeur et al., 1997)।

PCA 找的是方差最大的方向,而不是区分度最大的方向。在手写数字上,在 PCA 之后加上 LDA,准确率从 87.9% 提高到 93.6%, 因为 LDA 知道每张图属于哪个类别,并旋转空间把 10 个数字分开。用在人脸上,这就是著名的 Fisherfaces 方法(Belhumeur 等,1997)。


SectionSection第 09 节

LDA vs PCA — When to Use EachLDA vs PCA — कब कौन साLDA 与 PCA — 各自何时使用

Propertyगुण属性PCALDA
Typeप्रकार类型UnsupervisedUnsupervised无监督SupervisedSupervised有监督
Objectiveलक्ष्य目标Maximise total varianceकुल variance सबसे ज़्यादा最大化总方差Maximise class separabilityClasses का अलगाव सबसे ज़्यादा最大化类别可分性
Uses class labels?Class labels इस्तेमाल करता है?使用类别标签?Noनहीं否Yesहाँ是
Max componentsअधिकतम components最大分量数min(n−1, d)C−1 (number of classes minus 1)C−1 (classes की संख्या − 1)C−1(类别数减 1)
Best forकिसके लिए सबसे अच्छा最适合Visualisation, noise reduction, no labelsVisualisation, noise कम करना, बिना labels可视化、降噪、无标签Classification preprocessing, supervised DRClassification preprocessing, supervised DR分类预处理、有监督降维
Assumes Gaussian?Gaussian मानता है?假设高斯分布?Noनहीं否Yes (within each class, as a classifier)हाँ (हर class के अंदर, classifier के रूप में)是(作为分类器时,每类内部)
Sensitive to outliers?Outliers से प्रभावित?对异常值敏感?Moderatelyकुछ हद तक中等Moderatelyकुछ हद तक中等
Works with many classes?कई classes के साथ?适用于多类别?Yes — labels not usedहाँ — labels इस्तेमाल नहीं होते是 —— 不使用标签Yes — but only C−1 axesहाँ — पर सिर्फ़ C−1 axes是 —— 但只有 C−1 条轴
When to chooseकब चुनें何时选择Feature compression, exploring dataFeature compression, data को समझना特征压缩、探索数据Classification, face recognition, biometricsClassification, चेहरा पहचान, biometrics分类、人脸识别、生物识别
🔑
The Golden Comboसुनहरी जोड़ी黄金组合

PCA and LDA work well together. Use PCA first to remove noise and fix the singularity problem (especially when d > n), then LDA to find the class-separating axes. This PCA → LDA chain is used in face recognition, medical imaging and text classification. The PCA step typically keeps ~100–300 components; LDA then extracts the C − 1 truly class-separating directions from those.

PCA और LDA साथ मिलकर अच्छा काम करते हैं। Noise हटाने और singularity समस्या ठीक करने के लिए पहले PCA (ख़ासकर जब d > n), फिर classes को अलग करने वाले axes के लिए LDA. यह PCA → LDA chain चेहरा पहचानने, medical imaging और text classification में इस्तेमाल होती है। PCA step आमतौर पर ~100–300 components रखता है; फिर LDA उनमें से C − 1 असली अलग करने वाली दिशाएँ निकालता है।

PCA 和 LDA 配合得很好。先用 PCA 去除噪声、解决奇异性问题(尤其当 d > n 时), 再用 LDA 找出能分开类别的坐标轴。这条 PCA → LDA 流水线广泛用于人脸识别、医学影像和文本分类。 PCA 一般保留约 100–300 个分量,LDA 再从中提取 C − 1 个真正区分类别的方向。


SectionSection第 10 节

LDA vs QDA — Covariance AssumptionsLDA vs QDA — Covariance की मान्यताएँLDA 与 QDA — 协方差假设

When LDA's equal-covariance assumption fails, Quadratic Discriminant Analysis (QDA) can help. QDA estimates a separate covariance matrix Σ_c for each class, which gives quadratic (curved) decision boundaries instead of straight ones.

जब LDA की बराबर-covariance वाली मान्यता टूटती है, तो Quadratic Discriminant Analysis (QDA) मदद कर सकता है। QDA हर class के लिए अलग covariance matrix Σ_c निकालता है, जिससे सीधी की जगह quadratic (मुड़ी हुई) decision सीमाएँ बनती हैं।

当 LDA 的等协方差假设不成立时,二次判别分析(QDA)可以帮忙。QDA 为每个类单独估计协方差矩阵 Σ_c, 得到的是二次(弯曲)的决策边界,而不是直线。

LIVELIVE互动LDA vs QDA — Straight Line or Curve?LDA vs QDA — सीधी Line या Curve?LDA 与 QDA — 直线还是曲线?

Red class A is a small round blob. Change the size and tilt of blue class B. The background shows which class the chosen model predicts; the bright line is its boundary. Accuracies are measured on 600 new points.

लाल class A एक छोटा गोल ढेर है। नीली class B का आकार और झुकाव बदलें। Background दिखाता है कि चुना गया model कौन सी class predict करता है; चमकीली line उसकी सीमा है। Accuracy 600 नए points पर मापी गई है।

红色 A 类是一个小圆团。改变蓝色 B 类的大小和倾斜。背景颜色表示所选模型预测的类别,亮线是它的决策边界。准确率在 600 个新点上测量。

Show
LDA test accuracyLDA test accuracyLDA 测试准确率
—
QDA test accuracyQDA test accuracyQDA 测试准确率
—

Try size 2.5: class B becomes a wide cloud around A. QDA draws a closed curve around A and pulls ahead; LDA's straight line cannot.

आकार 2.5 आज़माएँ: class B, A के चारों ओर एक चौड़ा बादल बन जाता है। QDA, A के चारों ओर एक बंद curve बनाकर आगे निकल जाता है; LDA की सीधी line ऐसा नहीं कर सकती।

试试大小 2.5:B 类变成包围 A 的一大片点云。QDA 会在 A 周围画出一条闭合曲线并明显领先,而 LDA 的直线做不到。

from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline

# Generate data with UNEQUAL class covariances — LDA assumption violated
import numpy as np
np.random.seed(42)

X_c1 = np.random.multivariate_normal([0,0], [[1,0],[0,1]], 200)     # circular
X_c2 = np.random.multivariate_normal([3,3], [[4,2],[2,4]], 200)     # elongated ellipse
X_c3 = np.random.multivariate_normal([6,0], [[0.5,0],[0,3]],200)    # narrow tall

X = np.vstack([X_c1, X_c2, X_c3])
y = np.array([0]*200 + [1]*200 + [2]*200)

lda_pipe = Pipeline([('sc', StandardScaler()), ('clf', LinearDiscriminantAnalysis())])
qda_pipe = Pipeline([('sc', StandardScaler()), ('clf', QuadraticDiscriminantAnalysis())])

lda_cv = cross_val_score(lda_pipe, X, y, cv=5).mean()
qda_cv = cross_val_score(qda_pipe, X, y, cv=5).mean()

print(f"LDA CV Accuracy: {lda_cv:.4f}  (assumption violated)")
print(f"QDA CV Accuracy: {qda_cv:.4f}  (no equal-covariance assumption)")
OUTPUT
LDA CV Accuracy: 0.8900 (assumption violated) QDA CV Accuracy: 0.9117 (no equal-covariance assumption)
🔍
Reading the Resultनतीजा पढ़ना解读结果

QDA wins, but only by about 2 points (91.2% vs 89.0%), because the three classes still overlap a lot. When class shapes differ more, or classes overlap less, the gap grows — try it in the simulator above. QDA pays for its flexibility with many more parameters, so it needs more data.

QDA जीतता है, पर सिर्फ़ लगभग 2 points से (91.2% vs 89.0%), क्योंकि तीनों classes अब भी काफ़ी मिली हुई हैं। जब classes के आकार ज़्यादा अलग हों, या classes कम मिली हों, तो फ़र्क बढ़ता है — ऊपर simulator में आज़माएँ। QDA अपनी लचक की कीमत बहुत ज़्यादा parameters से चुकाता है, इसलिए उसे ज़्यादा data चाहिए।

QDA 赢了,但只领先约 2 个百分点(91.2% 对 89.0%),因为三个类别仍有大量重叠。类别形状差异越大、重叠越少,差距就越大 —— 在上面的模拟器里试试。 QDA 的灵活性是用更多参数换来的,所以它需要更多数据。

Aspectपहलू方面LDAQDA
Decision boundaryDecision सीमा决策边界Linear hyperplaneLinear hyperplane线性超平面Quadratic surfaceQuadratic surface二次曲面
CovarianceCovariance协方差One shared Σएक साझा Σ一个共享的 ΣOne Σ per classहर class का अलग Σ每类一个 Σ
BiasBias偏差Higher (if covariances differ)ज़्यादा (अगर covariances अलग हों)较高(如果协方差不同)Lowerकम较低
VarianceVariance方差Lower (fewer parameters)कम (कम parameters)较低(参数少)Higherज़्यादा较高
Needs more data?ज़्यादा data चाहिए?需要更多数据?No — fewer parametersनहीं — कम parameters不 —— 参数较少Yes — d(d+1)/2 covariance values per classहाँ — हर class के d(d+1)/2 covariance values是 —— 每类 d(d+1)/2 个协方差参数
Dimensionality reduction?Dimensionality reduction?能降维吗?Yes — up to C−1 componentsहाँ — C−1 components तक能 —— 最多 C−1 个分量Noनहीं不能
Choose when…कब चुनें…何时选择…Classes have roughly the same shapeClasses का आकार लगभग एक जैसा हो各类形状大致相同Classes have very different spreads/shapes and you have enough dataClasses के फैलाव/आकार बहुत अलग हों और data काफ़ी हो各类散布/形状差异很大且数据充足

SectionSection第 11 节

Medical Diagnosis Example — Breast Cancer LDAMedical Diagnosis Example — Breast Cancer LDA医学诊断案例 — 乳腺癌 LDA

Malignant vs Benign Tumour ProjectionMalignant vs Benign Tumour का Projection恶性与良性肿瘤的投影
A hospital lab measures 30 cell-nucleus features from fine needle aspirate biopsies: radius, texture, perimeter, area, smoothness, compactness, concavity, symmetry and fractal dimension — each as mean, standard error and worst value. The goal is to project these 30 numbers onto one axis that best separates Malignant from Benign tumours. With two classes, LDA gives exactly one such axis.
एक hospital lab, fine needle aspirate biopsies से cell-nucleus के 30 features मापती है: radius, texture, perimeter, area, smoothness, compactness, concavity, symmetry और fractal dimension — हर एक का mean, standard error और worst value. लक्ष्य है इन 30 numbers को एक ऐसे axis पर project करना जो Malignant और Benign tumours को सबसे अच्छी तरह अलग करे। दो classes के साथ LDA ठीक एक ऐसा axis देता है।
医院实验室从细针穿刺活检中测量 30 个细胞核特征:半径、纹理、周长、面积、光滑度、紧密度、凹度、对称性和分形维数 —— 每项都有均值、标准误和最差值。目标是把这 30 个数投影到一条最能区分恶性(Malignant)与良性(Benign)肿瘤的轴上。 两类问题时,LDA 正好给出一条这样的轴。
from sklearn.datasets import load_breast_cancer
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.metrics import roc_auc_score, classification_report
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import numpy as np

bc = load_breast_cancer()
X, y = bc.data, bc.target   # 569 samples, 30 features, 2 classes

pipe = Pipeline([
    ('sc',  StandardScaler()),
    ('lda', LinearDiscriminantAnalysis())
])

# 10-fold stratified CV — important for medical data
cv = StratifiedKFold(n_splits=10, shuffle=True, random_state=42)
acc_scores = cross_val_score(pipe, X, y, cv=cv, scoring='accuracy')
auc_scores = cross_val_score(pipe, X, y, cv=cv, scoring='roc_auc')

print(f"CV Accuracy: {acc_scores.mean():.4f} +/- {acc_scores.std():.4f}")
print(f"CV AUC-ROC:  {auc_scores.mean():.4f} +/- {auc_scores.std():.4f}")

# Full fit for feature weights (discriminant coefficients)
pipe.fit(X, y)
coef = pipe.named_steps['lda'].coef_[0]
top_idx = np.argsort(np.abs(coef))[::-1][:5]
print("\nTop 5 coefficients - plain LDA (signed):")
for i in top_idx:
    print(f"  {bc.feature_names[i]:25s}: {coef[i]:+8.2f}")

# Same model with shrinkage: much smaller, more stable weights
shr = Pipeline([('sc', StandardScaler()),
                ('lda', LinearDiscriminantAnalysis(solver='lsqr', shrinkage='auto'))]).fit(X, y)
coef_s = shr.named_steps['lda'].coef_[0]
print("\nTop 5 coefficients - shrinkage LDA (signed):")
for i in np.argsort(np.abs(coef_s))[::-1][:5]:
    print(f"  {bc.feature_names[i]:25s}: {coef_s[i]:+8.2f}")
print(f"\nShrinkage LDA CV accuracy: {cross_val_score(shr, X, y, cv=cv).mean():.4f}")
OUTPUT
CV Accuracy: 0.9596 +/- 0.0248 CV AUC-ROC: 0.9930 +/- 0.0092 Top 5 coefficients - plain LDA (signed): worst radius : -17.87 mean radius : +14.53 mean perimeter : -10.92 worst area : +10.90 mean compactness : +4.22 Top 5 coefficients - shrinkage LDA (signed): worst radius : -2.60 radius error : -1.92 mean compactness : +1.60 mean concave points : -1.50 worst concave points : -1.47 Shrinkage LDA CV accuracy: 0.9579
⚠️
Do Not Read Plain LDA Coefficients as Importanceसाधारण LDA Coefficients को Importance न समझें不要把普通 LDA 系数当作特征重要性

Look at plain LDA: worst radius −17.9 and mean radius +14.5. These two features measure almost the same thing, so their huge weights with opposite signs mostly cancel out. That is a sign of multicollinearity, not of importance. With shrinkage the weights become small and stable (top weight 2.6) while accuracy stays the same (95.8%). (Class 0 = malignant here, so a negative weight on worst radius means "bigger radius → more malignant".) For importance, use shrinkage weights, permutation importance or SHAP.

साधारण LDA देखें: worst radius −17.9 और mean radius +14.5. ये दोनों features लगभग एक ही चीज़ मापते हैं, इसलिए उल्टे signs वाले उनके बड़े weights ज़्यादातर एक-दूसरे को काट देते हैं। यह multicollinearity का संकेत है, importance का नहीं। Shrinkage के साथ weights छोटे और stable हो जाते हैं (सबसे बड़ा weight 2.6) और accuracy वैसी ही रहती है (95.8%)। (यहाँ class 0 = malignant है, इसलिए worst radius पर negative weight का मतलब "बड़ा radius → ज़्यादा malignant"।) Importance के लिए shrinkage weights, permutation importance या SHAP इस्तेमाल करें।

看普通 LDA:worst radius 为 −17.9,mean radius 为 +14.5。这两个特征几乎在测量同一件事, 所以它们符号相反的巨大权重大部分互相抵消了。这是多重共线性的信号,而不是重要性。 使用收缩后,权重变得小而稳定(最大权重 2.6),准确率不变(95.8%)。(这里类别 0 = 恶性, 所以 worst radius 的负权重表示"半径越大 → 越可能恶性"。)要看特征重要性,请用收缩后的权重、置换重要性或 SHAP。


SectionSection第 12 节

LDA Solvers in Scikit-LearnScikit-Learn में LDA SolversScikit-Learn 中的 LDA 求解器

🔢
SVD SolverSVD SolverSVD 求解器
solver='svd' (default)
Singular Value Decomposition. Does not form S_W explicitly, so it is the most stable and fast for many features. Cannot use shrinkage.
Singular Value Decomposition. यह S_W सीधे नहीं बनाता, इसलिए बहुत features पर भी सबसे stable और तेज़ है। Shrinkage इस्तेमाल नहीं कर सकता।
奇异值分解。不显式构造 S_W,所以最稳定,特征很多时也很快。不能使用收缩。
✅ Default, stable, supports transform()Default, stable, transform() चलता है默认、稳定、支持 transform()
❌ No shrinkageShrinkage नहीं不支持收缩
📉
LSQR SolverLSQR SolverLSQR 求解器
solver='lsqr'
Least-squares solution. Supports shrinkage, including 'auto' (Ledoit-Wolf). Efficient for classification. It cannot be used for dimensionality reduction: transform() is not available.
Least-squares हल। shrinkage चलता है, 'auto' (Ledoit-Wolf) समेत। Classification के लिए कुशल। Dimensionality reduction के लिए इस्तेमाल नहीं हो सकता: transform() उपलब्ध नहीं।
最小二乘解。支持 shrinkage,包括 'auto'(Ledoit-Wolf)。用于分类时很高效,但不能用于降维:没有 transform()。
✅ Shrinkage for small n, has predict_probaकम n के लिए shrinkage, predict_proba है小样本可用收缩,有 predict_proba
❌ No transform()transform() नहीं没有 transform()
🎯
Eigen SolverEigen SolverEigen 求解器
solver='eigen'
Eigen-decomposition of S_W⁻¹ S_B. Supports shrinkage and transform(). It builds the full d×d covariance, so it gets slow when d is large.
S_W⁻¹ S_B का eigen-decomposition. Shrinkage और transform() दोनों चलते हैं। यह पूरा d×d covariance बनाता है, इसलिए d बड़ा होने पर धीमा हो जाता है।
对 S_W⁻¹ S_B 做特征分解。同时支持收缩和 transform()。它要构造完整的 d×d 协方差,所以 d 很大时会变慢。
✅ Shrinkage + transform()Shrinkage + transform()收缩 + transform()
❌ Slower with many featuresबहुत features पर धीमा特征多时较慢
SolverShrinkage?Shrinkage?支持收缩?predict_proba?transform()?Best useसबसे अच्छा इस्तेमाल最佳用途
svd (default)Noनहीं否Yesहाँ是Yesहाँ是Standard LDA, many featuresसाधारण LDA, बहुत features标准 LDA、特征多
lsqrYesहाँ是Yesहाँ是Noनहीं否Classification with small n (shrinkage)कम n पर classification (shrinkage)小样本分类(收缩)
eigenYesहाँ是Yesहाँ是Yesहाँ是Need shrinkage and dimensionality reductionShrinkage और dimensionality reduction दोनों同时需要收缩和降维

SectionSection第 13 节

LDA for Multi-Class — IrisMulti-Class के लिए LDA — Iris多类别 LDA — 鸢尾花

from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
import numpy as np

iris = load_iris()
X, y = iris.data, iris.target   # 150 samples, 4 features, 3 classes

pipe = Pipeline([
    ('sc',  StandardScaler()),
    ('lda', LinearDiscriminantAnalysis(n_components=2))
])

# Cross-validated accuracy
scores = cross_val_score(pipe, X, y, cv=10)
print(f"CV Accuracy: {scores.mean():.4f} +/- {scores.std():.4f}")

# Fit and show explained variance per discriminant
pipe.fit(X, y)
lda = pipe.named_steps['lda']
print(f"\nLD1 explains {lda.explained_variance_ratio_[0]*100:.1f}% of between-class variance")
print(f"LD2 explains {lda.explained_variance_ratio_[1]*100:.1f}% of between-class variance")

# Class separation quality: Mahalanobis-like distances between centroids in LDA space
X_lda = lda.transform(pipe.named_steps['sc'].transform(X))
centroids = [X_lda[y==i].mean(axis=0) for i in range(3)]
for i in range(3):
  for j in range(i+1, 3):
    d = np.linalg.norm(np.array(centroids[i])-np.array(centroids[j]))
    print(f"Distance {iris.target_names[i]} ↔ {iris.target_names[j]}: {d:.3f}")
OUTPUT
CV Accuracy: 0.9800 +/- 0.0427 LD1 explains 99.1% of between-class variance LD2 explains 0.9% of between-class variance Distance setosa ↔ versicolor: 9.576 Distance setosa ↔ virginica: 13.529 Distance versicolor ↔ virginica: 4.190
🌸
LD1 Does 99% of the WorkLD1 99% काम करता हैLD1 完成了 99% 的工作

On Iris, a single discriminant (LD1) captures 99.1% of the between-class variance. In the LDA space setosa is far from the other two (distances 9.6 and 13.5), while versicolor and virginica are much closer (4.2) — exactly where the few mistakes happen. One dimension would classify almost as well as two.

Iris पर एक अकेला discriminant (LD1) between-class variance का 99.1% पकड़ता है। LDA space में setosa बाकी दोनों से बहुत दूर है (दूरी 9.6 और 13.5), जबकि versicolor और virginica काफ़ी पास हैं (4.2) — गलतियाँ ठीक यहीं होती हैं। एक dimension लगभग दो जितना अच्छा classify करेगा।

在鸢尾花数据上,单个判别方向(LD1)就捕获了 99.1% 的类间方差。在 LDA 空间中,setosa 离另外两类很远(距离 9.6 和 13.5), 而 versicolor 与 virginica 很近(4.2)—— 少数错误正好发生在这里。只用一维分类,效果几乎和二维一样好。


SectionSection第 14 节

When to Use (and Avoid) LDALDA कब इस्तेमाल करें (और कब नहीं)什么时候用(以及不用)LDA

✅
Multi-class ClassificationMulti-class Classification多类别分类
A natural fit for multi-class problems on numeric tabular data when classes are roughly Gaussian with similar shapes: lab measurements, sensor readings, chemistry.
Numeric tabular data पर multi-class problems के लिए स्वाभाविक, जब classes लगभग Gaussian हों और आकार मिलते-जुलते हों: lab measurements, sensor readings, chemistry.
当类别大致服从形状相近的高斯分布时,非常适合数值型表格数据的多分类问题:实验室测量、传感器读数、化学成分等。
works well nativelyसीधे अच्छा काम करता है原生表现好
✅
Dimensionality Reduction Before ClassificationClassification से पहले Dimensionality Reduction分类前的降维
Project 100+ features to C−1 dimensions before k-NN, SVM or a small neural network. Less noise, less computation, and most of the separating power is kept.
k-NN, SVM या छोटे neural network से पहले 100+ features को C−1 dimensions में project करें। कम noise, कम computation, और अलग करने की ज़्यादातर ताक़त बची रहती है।
在 k-NN、SVM 或小型神经网络之前,把 100+ 个特征投影到 C−1 维。噪声更少、计算更少,并保留大部分区分能力。
preprocessing steppreprocessing step预处理步骤
✅
Face & Biometric Recognitionचेहरा और Biometric पहचान人脸与生物特征识别
PCA → LDA (Fisherfaces) is a proven pipeline for face recognition, speaker identification and handwriting recognition with many classes.
PCA → LDA (Fisherfaces) चेहरा पहचान, speaker identification और handwriting recognition के लिए, बहुत classes के साथ, आज़माई हुई pipeline है।
PCA → LDA(Fisherfaces)是人脸识别、说话人识别和手写识别等多类别任务中久经考验的流水线。
Fisherfaces pipelineFisherfaces pipelineFisherfaces 流水线
❌
Non-Gaussian Feature DistributionsNon-Gaussian Features非高斯特征
Binary, count or heavily skewed features break the Gaussian assumption. Try a transform first, or use tree-based models, Naive Bayes with a matching distribution, or logistic regression.
Binary, count या बहुत टेढ़े features Gaussian मान्यता तोड़ते हैं। पहले transform आज़माएँ, या tree-based models, सही distribution वाला Naive Bayes, या logistic regression इस्तेमाल करें।
二值、计数或严重偏斜的特征会破坏高斯假设。先试试变换,或者改用树模型、匹配分布的朴素贝叶斯或逻辑回归。
use trees or logistic regressiontrees या logistic regression用树模型或逻辑回归
❌
Very Unequal Class Sizesबहुत असमान Class Sizes类别大小悬殊
By default LDA uses the class frequencies as priors, so the decision cut moves toward the rare class and many rare cases are missed. Set priors deliberately (see the simulator below).
Default में LDA class frequencies को priors मानता है, इसलिए decision cut दुर्लभ class की ओर खिसकता है और कई दुर्लभ cases छूट जाते हैं। priors सोच-समझकर set करें (नीचे simulator देखें)।
默认情况下 LDA 把类别频率当作先验,决策切点会向少数类移动,导致很多少数类样本被漏掉。请有意识地设置 priors(见下方模拟器)。
set priorspriors set करें设置先验
❌
Complex Non-Linear Boundariesजटिल Non-Linear सीमाएँ复杂的非线性边界
If classes interleave in a spiral, ring or XOR pattern, no straight line can separate them. Use QDA, kernel methods, an RBF SVM, trees or neural networks.
अगर classes spiral, ring या XOR pattern में गुँथी हों, तो कोई सीधी line उन्हें अलग नहीं कर सकती। QDA, kernel तरीके, RBF SVM, trees या neural networks इस्तेमाल करें।
如果类别呈螺旋、圆环或 XOR 形交织,任何直线都分不开。请使用 QDA、核方法、RBF SVM、树模型或神经网络。
use kernel methods or SVMkernel तरीके या SVM用核方法或 SVM
LIVELIVE互动Priors Move the Decision CutPriors, Decision Cut को खिसकाते हैं先验会移动决策切点

Two classes on one LDA axis, same spread. Make class B rare and watch the cut move. Then switch to equal priors.

एक LDA axis पर दो classes, एक जैसा फैलाव। Class B को दुर्लभ बनाएँ और cut को खिसकते देखें। फिर बराबर priors पर जाएँ।

一条 LDA 轴上的两个类别,散布相同。让 B 类变得稀少,观察切点如何移动;然后切换到相等先验。

Class A caughtClass A पकड़ी गईA 类被找出
—
Class B caughtClass B पकड़ी गईB 类被找出
—


SectionSection第 15 节

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

🌿 LDA — Rules to RememberLDA — याद रखने के नियमLDA — 必记规则
1
Standardise features before LDA when you want to read or compare weights. LDA predictions do not change when you rescale a feature, but shrinkage and the size of the coefficients do. Put StandardScaler in a Pipeline: it never hurts and makes shrinkage fair across features.
जब weights पढ़ने या तुलना करनी हो, तो LDA से पहले features standardise करें। किसी feature का scale बदलने से LDA की predictions नहीं बदलतीं, पर shrinkage और coefficients का आकार बदलता है। StandardScaler को Pipeline में रखें: इससे कभी नुकसान नहीं होता और shrinkage सभी features पर बराबर लगता है।
想解读或比较权重时,先标准化特征。 缩放某个特征不会改变 LDA 的预测,但会改变收缩效果和系数大小。把 StandardScaler 放进 Pipeline:没有坏处,还能让收缩对所有特征一视同仁。
2
Remember: at most C−1 discriminants. A 5-class problem gives at most 4 LDA components, however many features you have. If you need more axes for another model, combine LDA with other features or use PCA.
याद रखें: ज़्यादा से ज़्यादा C−1 discriminants. 5-class problem में ज़्यादा से ज़्यादा 4 LDA components, चाहे features कितने भी हों। अगर किसी दूसरे model के लिए ज़्यादा axes चाहिए, तो LDA को दूसरे features के साथ मिलाएँ या PCA इस्तेमाल करें।
记住:最多 C−1 个判别方向。 五分类问题最多只有 4 个 LDA 分量,无论特征有多少。如果其他模型需要更多轴,就把 LDA 与其他特征结合,或使用 PCA。
3
Use shrinkage='auto' when samples are few compared with features. A useful rule of thumb: consider it when you have fewer than about 10 samples per feature. Ledoit-Wolf shrinkage costs almost nothing. Use solver='lsqr' (classification) or solver='eigen' (if you also need transform()).
जब features की तुलना में samples कम हों, तो shrinkage='auto' इस्तेमाल करें। एक काम का अनुमानित नियम: जब हर feature पर लगभग 10 से कम samples हों, तो इस पर विचार करें। Ledoit-Wolf shrinkage की कीमत लगभग कुछ नहीं। solver='lsqr' (classification) या solver='eigen' (अगर transform() भी चाहिए) इस्तेमाल करें।
样本相对特征较少时,使用 shrinkage='auto'。 一个实用的经验法则:当每个特征平均不到约 10 个样本时就考虑它。Ledoit-Wolf 收缩几乎没有成本。分类用 solver='lsqr',如果还需要 transform() 就用 solver='eigen'。
4
Check class balance and set priors on purpose. By default LDA uses the training class frequencies as priors. If missing a rare class is costly, set priors=[0.5, 0.5] (or values that match the real world) and check the recall of each class.
Class balance जाँचें और priors सोच-समझकर set करें। Default में LDA training की class frequencies को priors मानता है। अगर दुर्लभ class छूटना महँगा है, तो priors=[0.5, 0.5] (या असली दुनिया से मेल खाती values) set करें और हर class का recall जाँचें।
检查类别平衡,并有意识地设置先验。 默认情况下 LDA 把训练集中的类别频率当作先验。如果漏掉少数类代价很高,就设置 priors=[0.5, 0.5](或符合真实情况的值),并检查每个类别的召回率。
5
LDA is a classifier, not just a transformer. You can call lda.predict(X) directly. It is very fast and often competitive with much heavier models. Always try LDA (and logistic regression) as a baseline before random forests or gradient boosting.
LDA एक classifier है, सिर्फ़ transformer नहीं। आप सीधे lda.predict(X) चला सकते हैं। यह बहुत तेज़ है और अक्सर बहुत भारी models से टक्कर लेता है। Random forests या gradient boosting से पहले हमेशा LDA (और logistic regression) को baseline के रूप में आज़माएँ।
LDA 是分类器,不只是变换器。 你可以直接调用 lda.predict(X)。它非常快,常常能与重得多的模型一较高下。在用随机森林或梯度提升之前,先用 LDA(和逻辑回归)做基线。
6
Use PCA before LDA when features are many and samples few. A PCA step (a few dozen to a few hundred components) removes noise dimensions and fixes the singularity. Choose its size by cross-validating the whole Pipeline, not by a fixed formula.
जब features बहुत और samples कम हों, तो LDA से पहले PCA लगाएँ। एक PCA step (कुछ दर्जन से कुछ सौ components) noise dimensions हटाता है और singularity ठीक करता है। इसका आकार किसी तय formula से नहीं, पूरी Pipeline को cross-validate करके चुनें।
特征多、样本少时,在 LDA 之前先做 PCA。 PCA 步骤(几十到几百个分量)能去掉噪声维度并解决奇异性。它的大小应通过对整个 Pipeline 做交叉验证来选,而不是套用固定公式。
7
Inspect explained_variance_ratio_ after fitting. If LD1 explains more than ~95% of the between-class variance (as on Iris), one dimension is enough. You can then plot the whole dataset as a 1-D histogram coloured by class — a great sanity check.
Fit करने के बाद explained_variance_ratio_ देखें। अगर LD1 between-class variance का ~95% से ज़्यादा समझाता है (जैसे Iris पर), तो एक dimension काफ़ी है। तब आप पूरे dataset को class के रंग वाले 1-D histogram में plot कर सकते हैं — एक बढ़िया जाँच।
拟合后查看 explained_variance_ratio_。 如果 LD1 解释了超过约 95% 的类间方差(如鸢尾花),一维就够了。这时可以把整个数据集画成按类别着色的一维直方图 —— 一个很好的检查手段。
You have completed Dimensionality reduction. View all sections →