The Story: Dr. Sharma's Diagnosis Machine
She calls her data-science intern, Arjun, and says: "Build me a model that looks at these numbers and tells me the probability that a tumour is malignant. Not a continuous value — a probability between 0 and 1."
Arjun immediately knows that Linear Regression won't work here. A straight line can predict values below 0 and above 1 — meaningless for a probability. He reaches for Logistic Regression.
Logistic Regression is the go-to algorithm for binary classification — problems where the output is one of two classes (Yes/No, Spam/Not-Spam, Fraud/Legit, Malignant/Benign). Despite its name, it is a classification algorithm, not regression. It predicts the probability that an observation belongs to a class, then applies a threshold to make the final class decision.
Look for the interactive boxes: Line vs S-Curve (Section 02), the Sigmoid Pipeline (04), the Odds Converter (05), the Log Loss Lab (06), the Gradient Descent Trainer (07), the Decision Boundary Playground (08), the Threshold Lab (10), the ROC Builder (11), the Regularisation Lab (14) and the Softmax Explorer (15). Move sliders, click to add points, and step through the maths. Every number is computed live with the formulas of this tutorial.
Why Linear Regression Fails for Classification
| Problem | Example Output |
|---|---|
| Predictions go below 0 | ŷ = −0.34 for a small tumour |
| Predictions go above 1 | ŷ = 1.72 for a huge tumour |
| No natural threshold | What does 0.73 kg of "malignant" mean? |
| Sensitive to outliers | One extreme point tilts the whole line |
| Property | Result |
|---|---|
| Output always in [0, 1] | ŷ = 0.82 → 82% chance of malignant |
| Interpretable threshold | ŷ ≥ 0.5 → predict Malignant |
| Probabilistic output | "82% confident it is malignant" |
| Well-defined loss function | Binary Cross-Entropy (Log Loss) |
Logistic Regression takes the linear equation z = β₀ + β₁x₁ + … + βₙxₙ
and passes it through a Sigmoid function that squashes any real number
into the range (0, 1). This output is then interpreted as a probability.
Try It — Line vs S-Curve
The orange line is linear regression. The green curve is logistic regression. Both are fitted to the same tumours (red = malignant, blue = benign). Click an empty spot to add a tumour (top half = malignant, bottom half = benign). Drag a tumour sideways to move it. Click a tumour to flip its label. Then press Add one huge tumour.
कहानी: डॉ. शर्मा की Diagnosis Machine
वो अपने data-science intern, अर्जुन, को बुलाती हैं और कहती हैं: "मेरे लिए एक model बनाओ जो इन numbers को देखे और बताए कि tumour के malignant होने की probability कितनी है। कोई continuous value नहीं — 0 और 1 के बीच एक probability।"
अर्जुन तुरंत समझ जाता है कि यहाँ Linear Regression काम नहीं करेगा। एक सीधी लाइन 0 से नीचे और 1 से ऊपर की values भी बता सकती है — probability के लिए इसका कोई मतलब नहीं। इसलिए वो Logistic Regression चुनता है।
binary classification के लिए Logistic Regression सबसे पहली पसंद है — यानी ऐसे सवाल जहाँ जवाब दो classes में से एक होता है (हाँ/ना, Spam/Not-Spam, Fraud/Legit, Malignant/Benign)। नाम में regression है, फिर भी यह एक classification algorithm है, regression नहीं। यह probability बताता है कि कोई observation किसी class में है, फिर एक threshold लगाकर आख़िरी class तय करता है।
इन interactive बॉक्स को देखिए: Line vs S-Curve (सेक्शन 02), Sigmoid Pipeline (04), Odds Converter (05), Log Loss Lab (06), Gradient Descent Trainer (07), Decision Boundary Playground (08), Threshold Lab (10), ROC Builder (11), Regularisation Lab (14) और Softmax Explorer (15)। sliders खिसकाइए, क्लिक करके points जोड़िए, और maths को एक-एक step में देखिए। हर number इसी tutorial के formulas से उसी समय calculate होता है।
Classification में Linear Regression क्यों फेल होता है
| समस्या | उदाहरण Output |
|---|---|
| Predictions 0 से नीचे चली जाती हैं | छोटे tumour के लिए ŷ = −0.34 |
| Predictions 1 से ऊपर चली जाती हैं | बहुत बड़े tumour के लिए ŷ = 1.72 |
| कोई सहज threshold नहीं | 0.73 kg "malignant" का क्या मतलब है? |
| Outliers का असर बहुत ज़्यादा | एक बहुत दूर का point पूरी लाइन को झुका देता है |
| ख़ासियत | नतीजा |
|---|---|
| Output हमेशा [0, 1] में | ŷ = 0.82 → malignant होने का 82% chance |
| समझ में आने वाला threshold | ŷ ≥ 0.5 → Malignant predict करो |
| Probability वाला output | "82% भरोसा है कि यह malignant है" |
| साफ़ तय loss function | Binary Cross-Entropy (Log Loss) |
Logistic Regression linear equation z = β₀ + β₁x₁ + … + βₙxₙ लेता है
और उसे एक Sigmoid function से गुज़ारता है, जो किसी भी real number को दबाकर
(0, 1) की range में ले आता है। फिर इस output को probability माना जाता है।
ख़ुद करके देखें — Line vs S-Curve
नारंगी लाइन linear regression है। हरी curve logistic regression है। दोनों एक ही tumours पर fit की गई हैं (लाल = malignant, नीला = benign)। नया tumour जोड़ने के लिए किसी ख़ाली जगह पर क्लिक करें (ऊपर का आधा = malignant, नीचे का आधा = benign)। किसी tumour को खिसकाने के लिए उसे बगल में drag करें। उसका label बदलने के लिए tumour पर क्लिक करें। फिर एक बहुत बड़ा tumour जोड़ें दबाएँ।
故事:Sharma 医生的诊断机器
她把数据科学实习生 Arjun 叫来,对他说:“帮我做一个 model,让它看 这些数字,然后告诉我这个肿瘤是恶性的 probability。 我不要一个连续的数值 —— 我要一个 0 到 1 之间的 probability。”
Arjun 马上就知道,Linear Regression 在这里行不通。 一条直线可能预测出小于 0 或大于 1 的值 —— 这对 probability 来说没有意义。 于是他选择了 Logistic Regression。
Logistic Regression 是做 binary classification 时最常用的算法 —— 也就是输出只有两个 class 之一的问题(是/否、垃圾邮件/非垃圾邮件、欺诈/正常、 恶性/良性)。别看它的名字里有“regression”,它其实是一个 classification 算法,不是 regression 算法。它先预测一个样本属于某个 class 的 probability, 然后用一个 threshold 来做出最终的 class 判断。
请留意这些互动框:Line vs S-Curve(第 02 节)、Sigmoid Pipeline(04)、 Odds Converter(05)、Log Loss Lab(06)、Gradient Descent Trainer(07)、 Decision Boundary Playground(08)、Threshold Lab(10)、ROC Builder(11)、 Regularisation Lab(14)和 Softmax Explorer(15)。 你可以拖动滑块、点击添加数据点,并一步一步看数学过程。每个数字都是用本教程里的公式实时算出来的。
为什么 Linear Regression 不适合做 classification
| 问题 | 输出示例 |
|---|---|
| prediction 会小于 0 | 小肿瘤得到 ŷ = −0.34 |
| prediction 会大于 1 | 巨大肿瘤得到 ŷ = 1.72 |
| 没有自然的 threshold | 0.73 kg 的“恶性”是什么意思? |
| 容易受离群点影响 | 一个极端点就能让整条线倾斜 |
| 特点 | 结果 |
|---|---|
| 输出永远在 [0, 1] 之内 | ŷ = 0.82 → 82% 的可能是恶性 |
| threshold 容易理解 | ŷ ≥ 0.5 → 预测为恶性 |
| 输出是 probability | “有 82% 的把握是恶性” |
| 有明确定义的 loss function | Binary Cross-Entropy(Log Loss) |
Logistic Regression 先拿到线性方程 z = β₀ + β₁x₁ + … + βₙxₙ,
再把它送进一个 Sigmoid function。这个函数会把任何实数
压缩到 (0, 1) 的范围里。然后,我们把这个输出看作一个 probability。
动手试试 —— Line vs S-Curve
橙色的线是 Linear Regression。绿色的曲线是 Logistic Regression。它们都用同一批肿瘤数据来拟合 (红色 = 恶性,蓝色 = 良性)。点击空白处可以添加一个肿瘤(上半部分 = 恶性,下半部分 = 良性)。 左右拖动一个肿瘤可以移动它。点击一个肿瘤可以翻转它的 label。然后按下 添加一个超大肿瘤。
The Sigmoid Function — The Heart of Logistic Regression
The sigmoid squashes any linear score z into (0,1). Below z=0 the model leans toward Class 0; above z=0 it leans toward Class 1. The exact threshold is tunable.
Sigmoid Key Values at a Glance
| z (linear score) | σ(z) (probability) | Interpretation |
|---|---|---|
| −6 | 0.002 | Very confident — Class 0 |
| −2 | 0.119 | Likely Class 0 |
| 0 | 0.500 | Completely uncertain |
| +2 | 0.881 | Likely Class 1 |
| +6 | 0.998 | Very confident — Class 1 |
The Full Logistic Regression Model
z = β₀ + β₁x₁ + β₂x₂ + … + βₙxₙFor Dr. Sharma:
z = β₀ + β₁·(tumour_size) + β₂·(cell_uniformity)
p̂ = σ(z) = 1 / (1 + e−z)This is the model's estimated probability that the sample belongs to Class 1 (Malignant). E.g. p̂ = 0.87 → 87% chance of malignancy.
ŷ = 1 if p̂ ≥ 0.5, else ŷ = 0The default threshold is 0.5 but it is tunable. In cancer screening you might lower it to 0.3 to minimise false negatives (missed cancers).
Report both the hard label and the probability to the doctor. "87% confident this is malignant" is far more actionable than just "Malignant."
Try It — The Sigmoid Pipeline
Follow one tumour through the whole model: size x → score z → e−z → probability p̂ → class. Move the sliders and watch each box update. The left plot is the sigmoid itself. The right plot shows the S-curve over tumour size.
Sigmoid Function — Logistic Regression का दिल
Sigmoid किसी भी linear score z को दबाकर (0,1) में ले आता है। z=0 से नीचे model का झुकाव Class 0 की तरफ़ होता है; z=0 से ऊपर Class 1 की तरफ़। असली threshold को बदला जा सकता है।
Sigmoid की मुख्य values एक नज़र में
| z (linear score) | σ(z) (probability) | मतलब |
|---|---|---|
| −6 | 0.002 | बहुत पक्का — Class 0 |
| −2 | 0.119 | शायद Class 0 |
| 0 | 0.500 | बिलकुल पक्का नहीं |
| +2 | 0.881 | शायद Class 1 |
| +6 | 0.998 | बहुत पक्का — Class 1 |
पूरा Logistic Regression Model
z = β₀ + β₁x₁ + β₂x₂ + … + βₙxₙडॉ. शर्मा के लिए:
z = β₀ + β₁·(tumour_size) + β₂·(cell_uniformity)
p̂ = σ(z) = 1 / (1 + e−z)यह model का अंदाज़ा है कि sample के Class 1 (Malignant) में होने की probability कितनी है। जैसे p̂ = 0.87 → malignant होने का 87% chance।
ŷ = 1 if p̂ ≥ 0.5, else ŷ = 0Default threshold 0.5 है, लेकिन इसे बदला जा सकता है। Cancer screening में आप इसे घटाकर 0.3 कर सकते हैं, ताकि false negatives (छूटे हुए cancer) कम से कम हों।
डॉक्टर को पक्का label और probability, दोनों बताएँ। "87% भरोसा है कि यह malignant है" सिर्फ़ "Malignant" कहने से कहीं ज़्यादा काम का है।
ख़ुद करके देखें — Sigmoid Pipeline
एक tumour को पूरे model में से गुज़रते देखिए: साइज़ x → score z → e−z → probability p̂ → class। sliders खिसकाइए और हर बॉक्स को बदलते देखिए। बाईं plot ख़ुद sigmoid है। दाईं plot tumour साइज़ पर S-curve दिखाती है।
Sigmoid Function —— Logistic Regression 的核心
sigmoid 会把任何线性分数 z 压缩到 (0,1) 之间。当 z 小于 0 时,model 偏向 Class 0;当 z 大于 0 时,它偏向 Class 1。具体的 threshold 是可以调整的。
一眼看懂 Sigmoid 的关键值
| z(线性分数) | σ(z)(probability) | 解读 |
|---|---|---|
| −6 | 0.002 | 非常确定 —— Class 0 |
| −2 | 0.119 | 很可能是 Class 0 |
| 0 | 0.500 | 完全不确定 |
| +2 | 0.881 | 很可能是 Class 1 |
| +6 | 0.998 | 非常确定 —— Class 1 |
完整的 Logistic Regression model
z = β₀ + β₁x₁ + β₂x₂ + … + βₙxₙ对 Sharma 医生来说:
z = β₀ + β₁·(tumour_size) + β₂·(cell_uniformity)
p̂ = σ(z) = 1 / (1 + e−z)这是 model 估计的样本属于 Class 1(恶性)的 probability。 例如 p̂ = 0.87 → 有 87% 的可能是恶性。
ŷ = 1 if p̂ ≥ 0.5, else ŷ = 0默认的 threshold 是 0.5,但它可以调整。在癌症筛查中,你也许会 把它降到 0.3,以尽量减少 False Negative(漏掉的癌症)。
把确定的 label 和 probability 都告诉医生。 “有 87% 的把握是恶性”比单单一句“恶性”更有参考价值。
动手试试 —— Sigmoid Pipeline
跟着一个肿瘤走完整个 model:大小 x → 分数 z → e−z → probability p̂ → class。 拖动滑块,看每个框怎么更新。左边的图就是 sigmoid 本身。右边的图展示了随肿瘤大小变化的 S 形曲线。
The Math Behind It — Log-Odds and the Logit
Why is it called logistic regression? Because it models the log-odds of the outcome as a linear function of the features.
p̂ = 1 / (1 + e−z)Rearrange to isolate z: multiply both sides by
(1 + e−z)p̂ · (1 + e−z) = 1 →
e−z = (1 − p̂) / p̂
−z = ln((1 − p̂) / p̂) →
z = ln(p̂ / (1 − p̂))The term p̂ / (1 − p̂) is called the odds ratio.
ln( p̂ / (1−p̂) ) = β₀ + β₁x₁ + β₂x₂ + … + βₙxₙThe log-odds (left side) is modelled as a linear combination of features. This is why the algorithm is called logistic regression: logistic transformation of a regression equation.
| Probability p̂ | Odds p̂/(1−p̂) | Log-Odds (z) |
|---|---|---|
| 0.10 | 0.111 | −2.20 |
| 0.25 | 0.333 | −1.10 |
| 0.50 | 1.000 | 0.00 |
| 0.75 | 3.000 | +1.10 |
| 0.90 | 9.000 | +2.20 |
Each β coefficient represents the change in log-odds per unit
increase in the feature. Exponentiate it to get the odds ratio:
eβ₁. If β₁ = 0.8 for tumour size, then
e0.8 ≈ 2.23 — each extra mm of tumour size multiplies
the odds of malignancy by 2.23×. This is the medical interpretation
Dr. Sharma cares about.
Try It — Odds Converter
Probability, odds and log-odds are three ways to say the same thing. Move either slider — the other one follows. Then set β₁ and look at the table: each extra mm adds the same amount to the log-odds and multiplies the odds by the same factor. The probability does not move by a fixed step.
इसके पीछे का Math — Log-Odds और Logit
इसे logistic regression क्यों कहते हैं? क्योंकि यह नतीजे के log-odds को features के एक linear function की तरह model करता है।
p̂ = 1 / (1 + e−z)z को अलग करने के लिए दोनों तरफ़
(1 + e−z) से गुणा करेंp̂ · (1 + e−z) = 1 →
e−z = (1 − p̂) / p̂
−z = ln((1 − p̂) / p̂) →
z = ln(p̂ / (1 − p̂))p̂ / (1 − p̂) वाले हिस्से को odds ratio कहते हैं।
ln( p̂ / (1−p̂) ) = β₀ + β₁x₁ + β₂x₂ + … + βₙxₙlog-odds (बायाँ हिस्सा) को features के एक linear combination की तरह model किया जाता है। इसीलिए इस algorithm का नाम logistic regression है: एक regression equation का logistic transformation।
| Probability p̂ | Odds p̂/(1−p̂) | Log-Odds (z) |
|---|---|---|
| 0.10 | 0.111 | −2.20 |
| 0.25 | 0.333 | −1.10 |
| 0.50 | 1.000 | 0.00 |
| 0.75 | 3.000 | +1.10 |
| 0.90 | 9.000 | +2.20 |
हर β coefficient बताता है कि feature में एक unit बढ़ने पर log-odds
कितना बदलता है। odds ratio पाने के लिए इसका exponent लें:
eβ₁। अगर tumour साइज़ के लिए β₁ = 0.8 है, तो
e0.8 ≈ 2.23 — tumour साइज़ का हर एक्स्ट्रा mm malignancy के
odds को 2.23× से गुणा कर देता है। डॉ. शर्मा को medical नज़र से
यही मतलब चाहिए।
ख़ुद करके देखें — Odds Converter
Probability, odds और log-odds एक ही बात कहने के तीन तरीके हैं। कोई भी slider खिसकाइए — दूसरा अपने आप साथ चलेगा। फिर β₁ सेट करें और table देखें: हर एक्स्ट्रा mm log-odds में उतनी ही मात्रा जोड़ता है और odds को उसी factor से गुणा करता है। Probability किसी तय step से नहीं बढ़ती।
背后的数学 —— log-odds 和 logit
为什么它叫 logistic regression?因为它把结果的 log-odds 建模为 feature 的线性函数。
p̂ = 1 / (1 + e−z)整理式子,把 z 单独留出来:两边同时乘以
(1 + e−z)p̂ · (1 + e−z) = 1 →
e−z = (1 − p̂) / p̂
−z = ln((1 − p̂) / p̂) →
z = ln(p̂ / (1 − p̂))其中 p̂ / (1 − p̂) 这一项叫作 odds ratio。
ln( p̂ / (1−p̂) ) = β₀ + β₁x₁ + β₂x₂ + … + βₙxₙ左边的 log-odds 被建模为 feature 的 线性 组合。这就是这个算法叫作 logistic regression 的原因:它是对 regression 方程做了 logistic 变换。
| probability p̂ | odds p̂/(1−p̂) | log-odds (z) |
|---|---|---|
| 0.10 | 0.111 | −2.20 |
| 0.25 | 0.333 | −1.10 |
| 0.50 | 1.000 | 0.00 |
| 0.75 | 3.000 | +1.10 |
| 0.90 | 9.000 | +2.20 |
每个 β coefficient 表示:feature 每增加一个单位,log-odds
会变化多少。对它取指数,就得到 odds ratio:
eβ₁。如果肿瘤大小的 β₁ = 0.8,那么
e0.8 ≈ 2.23 —— 肿瘤每大 1 mm,恶性的
odds 就会乘以 2.23 倍。这正是 Sharma 医生关心的
医学解读。
动手试试 —— Odds Converter
probability、odds 和 log-odds 是同一件事的三种说法。拖动任意一个滑块 —— 另一个会跟着变。 然后设置 β₁ 并看看表格:每多 1 mm,log-odds 就 加上 同样的量, odds 就 乘以 同样的倍数。而 probability 并不是按固定步长变化的。
The Cost Function — Binary Cross-Entropy (Log Loss)
Logistic Regression cannot use the same Mean Squared Error cost as Linear Regression — that gives a non-convex surface with many local minima. Instead it uses Binary Cross-Entropy, also called Log Loss.
−log(p̂) matters → penalises low confidence.When y=0 (actual negative): only
−log(1−p̂) matters → penalises high confidence.
Log Loss is asymmetric and explodes toward infinity when the model is confidently wrong. This harsh penalty pushes the model toward well-calibrated probabilities.
Try It — Log Loss Lab
Top: one tumour. Choose its true label and move the prediction p̂. Being confidently wrong is punished very hard. Bottom: ten tumours. Move β₀ and β₁. Each bar is one tumour's loss; their average is J. Try to make J as small as you can, then press Best fit.
Cost Function — Binary Cross-Entropy (Log Loss)
Logistic Regression वो Mean Squared Error cost इस्तेमाल नहीं कर सकता जो Linear Regression करता है — उससे एक non-convex surface बनती है जिसमें कई local minima होते हैं। इसकी जगह यह Binary Cross-Entropy इस्तेमाल करता है, जिसे Log Loss भी कहते हैं।
−log(p̂) मायने रखता है → कम भरोसे पर सज़ा देता है।जब y=0 (असल में negative): सिर्फ़
−log(1−p̂) मायने रखता है → ज़्यादा भरोसे पर सज़ा देता है।
Log Loss symmetric नहीं है। जब model पूरे भरोसे से ग़लत होता है, तो यह infinity की तरफ़ बढ़ जाता है। यह कड़ी सज़ा model को सही ढंग से calibrated probabilities की तरफ़ धकेलती है।
ख़ुद करके देखें — Log Loss Lab
ऊपर: एक tumour। उसका सही label चुनें और prediction p̂ खिसकाएँ। पूरे भरोसे से ग़लत होने पर बहुत कड़ी सज़ा मिलती है। नीचे: दस tumours। β₀ और β₁ खिसकाएँ। हर bar एक tumour का loss है; इनका औसत J है। J को जितना हो सके उतना छोटा करने की कोशिश करें, फिर Best fit दबाएँ।
cost function —— Binary Cross-Entropy(log loss)
Logistic Regression 不能用和 Linear Regression 一样的均方误差(Mean Squared Error)作为 cost —— 那样会得到一个非凸的曲面,上面有很多局部最小值。所以它改用 Binary Cross-Entropy,也叫 Log Loss。
−log(p̂) 起作用 → 惩罚低把握的预测。当 y=0(实际为负)时:只有
−log(1−p̂) 起作用 → 惩罚高把握的预测。
log loss 是不对称的。当 model 自信地猜错时,它会冲向无穷大。这种严厉的惩罚会推动 model 给出更准确、更合理的 probability。
动手试试 —— Log Loss Lab
上半部分:一个肿瘤。选择它的真实 label,然后移动 prediction p̂。自信地猜错会受到非常重的惩罚。 下半部分:十个肿瘤。移动 β₀ 和 β₁。每根柱子是一个肿瘤的 loss;它们的平均值就是 J。试着让 J 尽可能小, 然后按下 最佳拟合。
Gradient Descent — Finding the Best Weights
Unlike Linear Regression, Logistic Regression has no closed-form solution. We minimise J(β) iteratively using Gradient Descent.
Training data: 4 tumours — sizes [2, 3, 5, 7], labels [0, 0, 1, 1].
Apply sigmoid: p̂ = σ(z) = [0.5, 0.5, 0.5, 0.5].
Errors (p̂ − y): [0.5−0, 0.5−0, 0.5−1, 0.5−1] = [0.5, 0.5, −0.5, −0.5].
∂J/∂β₁ = (1/4)·(0.5·2 + 0.5·3 + (−0.5)·5 + (−0.5)·7) = (1/4)·(1+1.5−2.5−3.5) = (1/4)·(−3.5) = −0.875
β₁ ← 0 − 0.1 · (−0.875) = +0.0875
The weight for tumour size has gone positive — larger tumours now get higher probability. ✓
The Binary Cross-Entropy loss surface is convex with respect to β. This means gradient descent is guaranteed to find the global minimum — there are no local minima to get trapped in. This is why Logistic Regression is so reliable compared to non-convex models like neural networks.
Try It — Gradient Descent Trainer
This is the exact loop from above. The starting data is the four tumours of the worked example (sizes 2, 3, 5, 7). Press 1 step and check iteration 1 against the hand calculation (β₁ = 0.0875 with α = 0.1). Then run many steps, change the learning rate, or type your own data.
Gradient Descent — सबसे अच्छे Weights ढूँढना
Linear Regression के उलट, Logistic Regression का कोई closed-form solution नहीं है। हम J(β) को Gradient Descent से बार-बार थोड़ा-थोड़ा कम करते हैं।
Training data: 4 tumours — साइज़ [2, 3, 5, 7], labels [0, 0, 1, 1]।
Sigmoid लगाएँ: p̂ = σ(z) = [0.5, 0.5, 0.5, 0.5]।
ग़लतियाँ (p̂ − y): [0.5−0, 0.5−0, 0.5−1, 0.5−1] = [0.5, 0.5, −0.5, −0.5]।
∂J/∂β₁ = (1/4)·(0.5·2 + 0.5·3 + (−0.5)·5 + (−0.5)·7) = (1/4)·(1+1.5−2.5−3.5) = (1/4)·(−3.5) = −0.875
β₁ ← 0 − 0.1 · (−0.875) = +0.0875
Tumour साइज़ का weight positive हो गया है — अब बड़े tumours को ज़्यादा probability मिलती है। ✓
β के हिसाब से Binary Cross-Entropy loss की surface convex है। इसका मतलब gradient descent को global minimum ज़रूर मिलेगा — फँसने के लिए कोई local minima नहीं हैं। इसीलिए Logistic Regression neural networks जैसे non-convex models के मुक़ाबले इतना भरोसेमंद है।
ख़ुद करके देखें — Gradient Descent Trainer
यह ऊपर वाला बिलकुल वही loop है। शुरुआती data हल किए गए उदाहरण के चार tumours हैं (साइज़ 2, 3, 5, 7)। 1 step दबाएँ और iteration 1 को हाथ से किए गए हिसाब से मिलाएँ (α = 0.1 के साथ β₁ = 0.0875)। फिर कई steps चलाएँ, learning rate बदलें, या अपना ख़ुद का data टाइप करें।
gradient descent —— 找到最好的 weight
和 Linear Regression 不同,Logistic Regression 没有闭式解(直接算出答案的公式)。 我们用 gradient descent 一轮一轮地去最小化 J(β)。
training 数据:4 个肿瘤 —— 大小 [2, 3, 5, 7],label [0, 0, 1, 1]。
应用 sigmoid:p̂ = σ(z) = [0.5, 0.5, 0.5, 0.5]。
误差 (p̂ − y):[0.5−0, 0.5−0, 0.5−1, 0.5−1] = [0.5, 0.5, −0.5, −0.5]。
∂J/∂β₁ = (1/4)·(0.5·2 + 0.5·3 + (−0.5)·5 + (−0.5)·7) = (1/4)·(1+1.5−2.5−3.5) = (1/4)·(−3.5) = −0.875
β₁ ← 0 − 0.1 · (−0.875) = +0.0875
肿瘤大小的 weight 变成了正数 —— 现在越大的肿瘤,得到的 probability 越高。✓
Binary Cross-Entropy 的 loss 曲面对 β 来说是 凸的。 这意味着 gradient descent 一定能找到 全局 最小值 —— 不会被困在局部最小值里。所以和神经网络这类非凸的 model 相比, Logistic Regression 非常可靠。
动手试试 —— Gradient Descent Trainer
这就是上面那个循环。初始数据就是例子里的四个肿瘤 (大小 2、3、5、7)。按下 1 step,把第 1 次 iteration 的结果和手算结果对比一下 (α = 0.1 时 β₁ = 0.0875)。然后多跑几步、改变 learning rate,或者输入你自己的数据。
The Decision Boundary
Once trained, Logistic Regression draws a linear decision boundary in feature space. Points on one side get Class 0, points on the other get Class 1.
Logistic Regression creates a linear boundary: β₀ + β₁·size + β₂·uniformity = 0.
Points above the boundary are predicted Benign; points below are predicted Malignant.
The decision boundary is always a straight line (2D), plane (3D), or hyperplane (nD). If your classes are not linearly separable — for example, one class forms a ring around the other — Logistic Regression will struggle. Solutions: add polynomial features, use kernel methods, or switch to tree-based models.
Try It — Decision Boundary Playground
Two features this time: tumour size and cell uniformity. Choose a brush, then click to add a malignant or benign tumour. Click a tumour to remove it. The model refits after every click. The black line is the decision boundary. Try the ring data: a straight line fails. Tick add squared features and the boundary can curve.
Decision Boundary
Training के बाद, Logistic Regression feature space में एक linear decision boundary खींचता है। एक तरफ़ के points को Class 0 मिलता है, दूसरी तरफ़ वालों को Class 1।
Logistic Regression एक linear boundary बनाता है: β₀ + β₁·size + β₂·uniformity = 0।
Boundary के ऊपर वाले points को Benign predict किया जाता है; नीचे वालों को Malignant।
Decision boundary हमेशा एक सीधी लाइन (2D), plane (3D), या hyperplane (nD) होती है। अगर आपकी classes को सीधी लाइन से अलग नहीं किया जा सकता — जैसे, एक class दूसरी के चारों तरफ़ एक छल्ला बना ले — तो Logistic Regression को दिक़्क़त होगी। हल: polynomial features जोड़ें, kernel methods इस्तेमाल करें, या tree-based models पर जाएँ।
ख़ुद करके देखें — Decision Boundary Playground
इस बार दो features हैं: tumour साइज़ और cell uniformity। एक brush चुनें, फिर क्लिक करके malignant या benign tumour जोड़ें। किसी tumour को हटाने के लिए उस पर क्लिक करें। हर क्लिक के बाद model फिर से fit होता है। काली लाइन decision boundary है। छल्ला data आज़माइए: सीधी लाइन फेल हो जाती है। squared features जोड़ें पर tick करें, तो boundary मुड़ सकती है।
decision boundary
training 完成后,Logistic Regression 会在 feature 空间里画出一条 线性 decision boundary。 一边的点被判为 Class 0,另一边的点被判为 Class 1。
Logistic Regression 会生成一条线性边界:β₀ + β₁·size + β₂·uniformity = 0。
边界上方的点被预测为良性;边界下方的点被预测为恶性。
decision boundary 永远是一条 直线(2D)、一个平面(3D) 或一个超平面(nD)。如果你的 class 不能被线性分开 —— 比如 一个 class 围成一个圆环,把另一个 class 包在中间 —— Logistic Regression 就会很吃力。 解决办法:加入多项式 feature、使用核方法,或者换成基于树的 model。
动手试试 —— Decision Boundary Playground
这次有两个 feature:肿瘤大小和细胞均匀度。先选一支画笔,然后点击添加一个恶性或良性的肿瘤。 点击一个肿瘤可以删除它。每点击一次,model 都会重新拟合。黑色的线就是 decision boundary。 试试 环形 数据:直线会失败。勾选 添加 squared features,边界就可以弯曲了。
Evaluating the Model — The Confusion Matrix
Accuracy alone is dangerous for classification. If 95% of tumours are benign, a model that always predicts "Benign" gets 95% accuracy — but misses every malignant case. The Confusion Matrix gives the full picture.
| Term | Abbr | Count | What Happened |
|---|---|---|---|
| True Negative | TN | 57 | Actual Benign, predicted Benign ✓ |
| False Positive | FP | 5 | Actual Benign, predicted Malignant (unnecessary biopsy) |
| False Negative | FN | 3 | Actual Malignant, predicted Benign — most dangerous! |
| True Positive | TP | 35 | Actual Malignant, predicted Malignant ✓ |
Precision, Recall, and F1-Score
So Dr. Sharma sets the decision threshold at 0.3 instead of 0.5 — more tumours are flagged as suspicious, reducing FN at the cost of more FP. Recall goes up from 92% to 97%; Precision drops to 74%. The F1 score drops slightly — but in medicine, high recall is worth the trade.
This is why you should never optimise for accuracy alone. Always ask: "What is the cost of a False Negative vs a False Positive in this domain?"
| Metric | Use When | Avoid When |
|---|---|---|
| Accuracy | Classes are balanced | Imbalanced datasets (95% Class 0) |
| Precision | Cost of FP is high (spam filter — annoying if legitimate email goes to spam) | Cost of FN is high |
| Recall | Cost of FN is high (disease detection, fraud) | Cost of FP is high |
| F1-Score | Need a single metric balancing P and R | When P and R should not be equally weighted |
| ROC-AUC | Comparing models at all thresholds | Severely imbalanced data (use PR-AUC instead) |
Try It — Threshold Lab
Here are the 100 test tumours from Section 09, each placed at its predicted probability. At threshold 0.5 you get the same confusion matrix (TN 57, FP 5, FN 3, TP 35). Slide the threshold and see which tumours change colour. Press 0.3 to reproduce Dr. Sharma's choice.
Model को परखना — Confusion Matrix
Classification में सिर्फ़ accuracy देखना ख़तरनाक है। अगर 95% tumours benign हैं, तो जो model हमेशा "Benign" predict करे, उसे 95% accuracy मिल जाएगी — पर वो हर malignant case छोड़ देगा। Confusion Matrix पूरी तस्वीर दिखाता है।
| शब्द | छोटा रूप | गिनती | क्या हुआ |
|---|---|---|---|
| True Negative | TN | 57 | असल में Benign, predict हुआ Benign ✓ |
| False Positive | FP | 5 | असल में Benign, predict हुआ Malignant (बेवजह biopsy) |
| False Negative | FN | 3 | असल में Malignant, predict हुआ Benign — सबसे ख़तरनाक! |
| True Positive | TP | 35 | असल में Malignant, predict हुआ Malignant ✓ |
Precision, Recall, और F1-Score
इसलिए डॉ. शर्मा decision threshold 0.5 की जगह 0.3 रखती हैं — ज़्यादा tumours को शक वाला माना जाता है, जिससे FN कम होते हैं पर FP बढ़ जाते हैं। Recall 92% से बढ़कर 97% हो जाता है; Precision गिरकर 74% हो जाता है। F1 score थोड़ा गिरता है — लेकिन medicine में ऊँचा recall इस सौदे के लायक है।
इसीलिए आपको कभी भी सिर्फ़ accuracy के लिए optimise नहीं करना चाहिए। हमेशा पूछिए: "इस क्षेत्र में False Negative की क़ीमत क्या है और False Positive की क्या?"
| Metric | कब इस्तेमाल करें | कब न करें |
|---|---|---|
| Accuracy | Classes संतुलित हों | Imbalanced datasets (95% Class 0) |
| Precision | FP की क़ीमत ज़्यादा हो (spam filter — सही email spam में चला जाए तो परेशानी) | FN की क़ीमत ज़्यादा हो |
| Recall | FN की क़ीमत ज़्यादा हो (बीमारी पकड़ना, fraud) | FP की क़ीमत ज़्यादा हो |
| F1-Score | P और R को संतुलित करने वाला एक metric चाहिए | जब P और R को बराबर वज़न नहीं देना हो |
| ROC-AUC | सभी thresholds पर models की तुलना | बहुत ज़्यादा imbalanced data (इसकी जगह PR-AUC लें) |
ख़ुद करके देखें — Threshold Lab
ये सेक्शन 09 के 100 test tumours हैं, हर एक अपनी predicted probability पर रखा है। Threshold 0.5 पर आपको वही confusion matrix मिलता है (TN 57, FP 5, FN 3, TP 35)। Threshold खिसकाइए और देखिए कौन से tumours का रंग बदलता है। डॉ. शर्मा वाला चुनाव दोहराने के लिए 0.3 दबाएँ।
评估 model —— confusion matrix
在 classification 中,只看 accuracy 是很危险的。如果 95% 的肿瘤都是良性的, 那么一个永远预测“良性”的 model 也能得到 95% 的 accuracy —— 但它会漏掉每一个 恶性病例。confusion matrix 能给出完整的情况。
| 术语 | 缩写 | 数量 | 发生了什么 |
|---|---|---|---|
| True Negative | TN | 57 | 实际为良性,预测为良性 ✓ |
| False Positive | FP | 5 | 实际为良性,预测为恶性(做了不必要的活检) |
| False Negative | FN | 3 | 实际为恶性,预测为良性 —— 最危险! |
| True Positive | TP | 35 | 实际为恶性,预测为恶性 ✓ |
precision、recall 和 F1-score
所以 Sharma 医生把决策 threshold 设为 0.3,而不是 0.5 —— 这样会有更多肿瘤被标记为可疑,FN 减少了,但代价是 FP 变多。 recall 从 92% 升到了 97%;precision 降到了 74%。F1 score 稍微下降了一点 —— 但在医学上,高 recall 值得这样的取舍。
这就是为什么你 永远不要只追求 accuracy。 一定要问自己:“在这个领域里,一个 False Negative 和一个 False Positive 的代价分别是什么?”
| 指标 | 适用情况 | 避免情况 |
|---|---|---|
| accuracy | 各个 class 比较平衡 | 不平衡的 dataset(95% 是 Class 0) |
| precision | FP 的代价很高(垃圾邮件过滤 —— 正常邮件被放进垃圾箱会很烦人) | FN 的代价很高 |
| recall | FN 的代价很高(疾病检测、欺诈检测) | FP 的代价很高 |
| F1-score | 需要一个兼顾 P 和 R 的单一指标 | P 和 R 不应该同等重要时 |
| ROC-AUC | 在所有 threshold 下比较 model | 数据极度不平衡(改用 PR-AUC) |
动手试试 —— Threshold Lab
这里是第 09 节中的 100 个 test 肿瘤,每个都放在它的预测 probability 位置上。threshold 为 0.5 时,你会得到同样的 confusion matrix(TN 57、FP 5、FN 3、TP 35)。滑动 threshold,看看哪些肿瘤会变色。按下 0.3,重现 Sharma 医生的选择。
ROC Curve and AUC
The ROC Curve (Receiver Operating Characteristic) plots the True Positive Rate (Recall) against the False Positive Rate at every possible threshold from 0 to 1. The area under this curve — AUC — summarises model quality in a single number.
AUC = 0.97 means the model ranks a random positive sample above a random negative sample 97% of the time. AUC is threshold-independent and works for imbalanced datasets.
Try It — ROC Builder
Press Sweep to watch the curve being drawn: the threshold starts at 1 and slides down to 0, and every threshold adds one (FPR, TPR) point. Compare the four models. Then press Pair test to see what AUC means in plain words.
ROC Curve और AUC
ROC Curve (Receiver Operating Characteristic) 0 से 1 तक हर मुमकिन threshold पर True Positive Rate (Recall) को False Positive Rate के सामने plot करती है। इस curve के नीचे का area — AUC — model की क्वालिटी को एक ही number में बता देता है।
AUC = 0.97 का मतलब है कि 97% बार model किसी random positive sample को किसी random negative sample से ऊपर रखता है। AUC threshold पर निर्भर नहीं करता और imbalanced datasets पर भी काम करता है।
ख़ुद करके देखें — ROC Builder
Curve को बनते देखने के लिए ▶ सरकाएँ दबाएँ: threshold 1 से शुरू होकर 0 तक नीचे खिसकता है, और हर threshold एक (FPR, TPR) point जोड़ता है। चारों models की तुलना करें। फिर यह देखने के लिए जोड़ी test दबाएँ कि AUC का आसान शब्दों में क्या मतलब है।
ROC curve 和 AUC
ROC curve(Receiver Operating Characteristic,受试者工作特征)会在 0 到 1 之间的每一个 threshold 下,画出 True Positive Rate(recall)和 False Positive Rate 的关系。 这条曲线下面的面积 —— AUC —— 用一个数字概括了 model 的好坏。
AUC = 0.97 的意思是:随机拿一个正样本和一个负样本,model 有 97% 的情况会把正样本排在负样本前面。AUC 不依赖 threshold,也适用于不平衡的 dataset。
动手试试 —— ROC Builder
按下 扫描,看曲线是怎么画出来的:threshold 从 1 开始,一路滑到 0,每个 threshold 都会添加一个 (FPR, TPR) 点。比较一下这四个 model。然后按下 配对 test,用大白话看看 AUC 到底是什么意思。
Python — Logistic Regression from Scratch
Python — शुरू से Logistic Regression बनाना
Python —— 从零实现 Logistic Regression
import numpy as np
# ── Sigmoid function ─────────────────────────────────────────
def sigmoid(z):
return 1 / (1 + np.exp(-z))
# ── Binary Cross-Entropy Loss ────────────────────────────────
def log_loss(y, p_hat):
n = len(y)
eps = 1e-15 # clip to avoid log(0)
p_hat = np.clip(p_hat, eps, 1 - eps)
return -(1 / n) * np.sum(
y * np.log(p_hat) + (1 - y) * np.log(1 - p_hat)
)
# ── Training with Gradient Descent ──────────────────────────
def train_logistic(X, y, lr=0.1, epochs=1000):
n, p = X.shape
beta = np.zeros(p + 1) # β₀ + p weights
X_b = np.column_stack([np.ones(n), X]) # add bias column
for epoch in range(epochs):
z = X_b @ beta # linear score
p_hat = sigmoid(z) # predicted probability
error = p_hat - y # residual (p̂ᵢ − yᵢ)
grad = (1 / n) * (X_b.T @ error) # gradient vector
beta -= lr * grad # update weights
if epoch % 100 == 0:
loss = log_loss(y, p_hat)
print(f"Epoch {epoch:4d} | Loss: {loss:.4f}")
return beta
# ── Prediction ───────────────────────────────────────────────
def predict_proba(X, beta):
X_b = np.column_stack([np.ones(len(X)), X])
return sigmoid(X_b @ beta)
def predict(X, beta, threshold=0.5):
return (predict_proba(X, beta) >= threshold).astype(int)
# ── Toy dataset: tumour sizes ────────────────────────────────
np.random.seed(42)
X_train = np.random.randn(100, 2) # 100 samples, 2 features
y_train = ((X_train[:, 0] + X_train[:, 1]) > 0).astype(float)
beta = train_logistic(X_train, y_train, lr=0.5, epochs=500)
print(f"\nLearned weights: β₀={beta[0]:.3f} β₁={beta[1]:.3f} β₂={beta[2]:.3f}")
proba = predict_proba(X_train[:3], beta)
print(f"Predicted probabilities (first 3): {proba.round(3)}")
Python — Full Pipeline with scikit-learn
Python — scikit-learn के साथ पूरी Pipeline
Python —— 用 scikit-learn 搭建完整流程
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
classification_report, confusion_matrix,
roc_auc_score, RocCurveDisplay
)
# ── 1. Load Data ─────────────────────────────────────────────
data = load_breast_cancer() # Wisconsin Breast Cancer dataset
X, y = data.data, data.target # 569 samples, 30 features
# ── 2. Train / Test Split ────────────────────────────────────
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# ── 3. Feature Scaling (critical for Logistic Regression) ───
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test) # transform only — no fit!
# ── 4. Train Model ───────────────────────────────────────────
model = LogisticRegression(
C=1.0, # inverse of regularisation strength (1/λ)
solver='lbfgs', # efficient solver for small-medium datasets
max_iter=1000,
random_state=42
)
model.fit(X_train, y_train)
# ── 5. Evaluate ──────────────────────────────────────────────
y_pred = model.predict(X_test)
y_proba = model.predict_proba(X_test)[:, 1] # P(Class=1)
print("Confusion Matrix:")
print(confusion_matrix(y_test, y_pred))
print("\nClassification Report:")
print(classification_report(y_test, y_pred, target_names=data.target_names))
auc = roc_auc_score(y_test, y_proba)
print(f"ROC-AUC Score: {auc:.4f}")
# ── 6. Tune threshold for high Recall ───────────────────────
threshold = 0.3
y_pred_low = (y_proba >= threshold).astype(int)
print(f"\nAt threshold={threshold}:")
print(classification_report(y_test, y_pred_low, target_names=data.target_names))
Logistic Regression uses gradient descent or solver optimisation, both of which
converge far slower (or incorrectly) when features have very different scales.
A feature in thousands (income) will dominate one in decimals (age in decades).
Always apply StandardScaler or MinMaxScaler first — and
fit the scaler only on training data, then transform both train and test.
Regularisation — Preventing Overfitting
When there are many features (especially more features than samples), Logistic Regression can overfit — it memorises training noise. Regularisation adds a penalty term to the cost function to keep weights small.
λ · Σβⱼ² to the cost. Shrinks all weights toward zero but
never to exactly zero. Keeps all features in the model with smaller coefficients.
Best when most features are useful.
λ · Σ|βⱼ| to the cost. Can shrink weights to exactly
zero, performing automatic feature selection. Best when most features are irrelevant.
| C Value (sklearn) | Regularisation Strength | Effect |
|---|---|---|
C = 0.001 | Very Strong (λ = 1000) | Heavily penalised weights; high bias, low variance |
C = 0.1 | Strong | Simpler model, good generalisation |
C = 1.0 | Moderate (default) | Balanced — good starting point |
C = 10 | Weak | Near-unregularised; may overfit |
C = 1000 | None (λ ≈ 0) | Pure maximum likelihood; overfits on small datasets |
Try It — Regularisation Lab
The model below uses 20 polynomial features (x₁, x₂, x₁², x₁x₂, … up to power 5) and only 40 training points — an easy way to overfit. Move C (small C = strong penalty). Watch the boundary, the weights, and the gap between training accuracy and accuracy on 300 new points. Switch to L1 to see weights become exactly zero.
Logistic Regression gradient descent या solver optimisation इस्तेमाल करता है। जब features के scale बहुत अलग-अलग हों,
तो ये दोनों बहुत धीरे (या ग़लत) converge करते हैं।
हज़ारों में चलने वाला feature (आमदनी) दशमलव वाले feature (दशकों में उम्र) पर हावी हो जाएगा।
हमेशा पहले StandardScaler या MinMaxScaler लगाएँ — और
scaler को सिर्फ़ training data पर fit करें, फिर train और test दोनों को transform करें।
Regularisation — Overfitting से बचाव
जब features बहुत ज़्यादा हों (ख़ासकर samples से भी ज़्यादा features), तो Logistic Regression overfit कर सकता है — यह training के noise को रट लेता है। Regularisation cost function में एक penalty term जोड़ता है, ताकि weights छोटे रहें।
λ · Σβⱼ² जोड़ता है। सभी weights को zero की तरफ़ छोटा करता है, पर
कभी बिलकुल zero नहीं करता। सभी features को model में रखता है, बस छोटे coefficients के साथ।
तब सबसे अच्छा जब ज़्यादातर features काम के हों।
λ · Σ|βⱼ| जोड़ता है। Weights को बिलकुल
zero कर सकता है, यानी अपने आप feature selection कर देता है। तब सबसे अच्छा जब ज़्यादातर features बेकार हों।
| C Value (sklearn) | Regularisation की ताक़त | असर |
|---|---|---|
C = 0.001 | बहुत ज़्यादा (λ = 1000) | Weights पर भारी penalty; high bias, low variance |
C = 0.1 | ज़्यादा | सरल model, अच्छा generalisation |
C = 1.0 | मध्यम (default) | संतुलित — शुरू करने के लिए अच्छा |
C = 10 | कम | लगभग बिना regularisation के; overfit कर सकता है |
C = 1000 | कुछ नहीं (λ ≈ 0) | सिर्फ़ maximum likelihood; छोटे datasets पर overfit करता है |
ख़ुद करके देखें — Regularisation Lab
नीचे वाला model 20 polynomial features (x₁, x₂, x₁², x₁x₂, … power 5 तक) और सिर्फ़ 40 training points इस्तेमाल करता है — overfit करने का एक आसान तरीका। C खिसकाइए (छोटा C = ज़्यादा penalty)। Boundary, weights, और training accuracy व 300 नए points पर accuracy के बीच का फ़ासला देखिए। Weights को बिलकुल zero होते देखने के लिए L1 पर जाएँ।
Logistic Regression 使用 gradient descent 或求解器(solver)来优化。当 feature 的尺度相差很大时,
这两种方法都会收敛得慢很多(甚至收敛到错误的结果)。
一个以千为单位的 feature(收入)会压过一个只有小数的 feature(以十年为单位的年龄)。
一定要先用 StandardScaler 或 MinMaxScaler —— 并且
只在 training 数据上 fit 这个 scaler,然后再同时 transform training 数据和 test 数据。
regularisation —— 防止 overfitting
当 feature 很多时(尤其是 feature 比样本还多时),Logistic Regression 可能会 overfitting —— 它会把 training 数据里的噪声也记下来。regularisation 会在 cost function 里加一个惩罚项,让 weight 保持较小。
λ · Σβⱼ²。它会把所有 weight 往 0 的方向缩小,但
永远不会刚好变成 0。所有 feature 都留在 model 里,只是 coefficient 更小。
当大多数 feature 都有用时,它最合适。
λ · Σ|βⱼ|。它可以把 weight 缩小到 刚好
等于 0,相当于自动做 feature 选择。当大多数 feature 都没用时,它最合适。
| C 值(sklearn) | regularisation 强度 | 效果 |
|---|---|---|
C = 0.001 | 非常强(λ = 1000) | weight 受到很重的惩罚;bias 高,方差低 |
C = 0.1 | 强 | model 更简单,泛化能力好 |
C = 1.0 | 适中 (默认) | 比较平衡 —— 很好的起点 |
C = 10 | 弱 | 几乎没有 regularisation;可能会 overfitting |
C = 1000 | 无(λ ≈ 0) | 纯 Maximum Likelihood;在小 dataset 上会 overfitting |
动手试试 —— Regularisation Lab
下面的 model 使用了 20 个多项式 feature(x₁、x₂、x₁²、x₁x₂……最高到 5 次方),却只有 40 个 training 点 —— 这样很容易 overfitting。移动 C(C 越小 = 惩罚越强)。观察边界、各个 weight,以及 training accuracy 和 300 个新点上的 accuracy 之间的差距。切换到 L1,看看 weight 怎样变成刚好等于 0。
Multiclass Logistic Regression
Standard Logistic Regression is binary. Two strategies extend it to multiple classes:
Multiclass Logistic Regression
आम Logistic Regression binary होता है। इसे कई classes तक ले जाने के दो तरीके हैं:
multiclass Logistic Regression
标准的 Logistic Regression 只能做二分类。有两种策略可以把它扩展到多个 class:
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
# ── Iris: 3 classes ──────────────────────────────────────────
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# ── Multinomial (Softmax) Logistic Regression ────────────────
model = LogisticRegression(
multi_class='multinomial',
solver='lbfgs',
C=1.0,
max_iter=500
)
model.fit(X_train, y_train)
print(f"Test Accuracy : {model.score(X_test, y_test):.4f}") # ~0.967
# Probability distribution for first test sample
print("Class probabilities (sample 1):", model.predict_proba(X_test[:1]).round(3))
# [[0.001 0.072 0.927]] → Class 2 (Virginica) with 92.7% confidence
Try It — Softmax Explorer
One flower, three scores z (one per species). Move the scores. Softmax turns them into probabilities that add up to 1. Below, compare with three separate sigmoids (one-vs-rest): they do not add up to 1.
ख़ुद करके देखें — Softmax Explorer
एक फूल, तीन scores z (हर species के लिए एक)। Scores खिसकाइए। Softmax इन्हें ऐसी probabilities में बदलता है जिनका जोड़ 1 होता है। नीचे, तीन अलग sigmoids (one-vs-rest) से तुलना करें: इनका जोड़ 1 नहीं होता।
动手试试 —— Softmax Explorer
一朵花,三个分数 z(每个品种一个)。移动这些分数。softmax 会把它们变成加起来等于 1 的 probability。 在下面,和三个独立的 sigmoid(one-vs-rest)比较一下:它们加起来不等于 1。
Assumptions of Logistic Regression
Golden Rules
StandardScaler before training. Fit the scaler
on the training set only — never leak test-set statistics into preprocessing.
C=1.0 (L2) is a safe starting point. If you have many irrelevant
features, try L1 (penalty='l1') for automatic feature selection.
Always tune C with cross-validation.
Logistic Regression की मान्यताएँ (Assumptions)
सुनहरे नियम
StandardScaler इस्तेमाल करें। Scaler को
सिर्फ़ training set पर fit करें — test-set के आँकड़ों को कभी भी preprocessing में न जाने दें।
C=1.0 (L2) शुरू करने के लिए सुरक्षित है। अगर आपके पास बहुत सारे बेकार
features हैं, तो अपने आप feature selection के लिए L1 (penalty='l1') आज़माएँ।
C को हमेशा cross-validation से tune करें।
Logistic Regression 的前提假设
黄金法则
StandardScaler。只在 training 集上
fit 这个 scaler —— 永远不要让 test 集的统计信息泄漏到预处理中。
C=1.0(L2)是一个安全的起点。如果你有很多没用的
feature,试试 L1(penalty='l1')来自动做 feature 选择。
一定要用 cross-validation 来调 C。