Look for the interactive boxes: The Overfitting Cure (Section 01), Multicollinearity Lab (02), Geometry Explorer (05), Shrinkage Rules (06), Alpha Tuner (08), Scaling Matters (09), Coefficient Paths (12) and ElasticNet Mixer (13). Every model in them is fitted live in your browser.
The Story That Explains Everything
Student B reads the same notes but forces himself to keep only the simple, core rules. If an idea needs a long list of special cases, he drops the details. Practice paper: 88%. Real exam: 85%. Almost no gap.
Regularisation is Student B's discipline. It is a penalty that punishes complexity, so the model learns the pattern instead of memorising the noise. Ridge and Lasso are the two most popular forms of this discipline.
Overfitting happens when a model learns the training data too well — including its noise and random ups and downs. It does brilliantly on data it has seen, and badly on data it has not. Regularisation adds a penalty term to the loss function. The penalty grows when the coefficients grow, so the model prefers small, calm coefficients. Such models usually work much better on new data.
Ridge and Lasso both start from the normal Linear Regression loss and add a penalty for large coefficients. Ridge adds the sum of squared coefficients (the L2 penalty). Lasso adds the sum of absolute coefficients (the L1 penalty). One number, alpha (α), sets how strong the penalty is.
Try It — The Overfitting Cure
A very flexible model (a degree-12 polynomial) is fitted to only 14 points. With no penalty it wiggles wildly. Move the α slider to the right and watch the curve calm down — and the giant coefficients shrink.
इन interactive boxes को देखिए: The Overfitting Cure (सेक्शन 01), Multicollinearity Lab (02), Geometry Explorer (05), Shrinkage Rules (06), Alpha Tuner (08), Scaling Matters (09), Coefficient Paths (12) और ElasticNet Mixer (13)। इनका हर model आपके browser में live fit होता है।
वह कहानी जो सब कुछ समझाती है
छात्र B वही notes पढ़ता है, पर ख़ुद को सिर्फ़ आसान, मूल नियम याद रखने पर मजबूर करता है। अगर किसी idea के लिए special cases की लंबी list चाहिए, तो वह details छोड़ देता है। Practice paper: 88%। असली exam: 85%। लगभग कोई फ़र्क़ नहीं।
Regularisation छात्र B का यही अनुशासन है। यह एक penalty है जो complexity को सज़ा देती है, ताकि model noise रटने के बजाय pattern सीखे। Ridge और Lasso इस अनुशासन के दो सबसे popular रूप हैं।
Overfitting तब होता है जब model training data को ज़रूरत से ज़्यादा अच्छी तरह सीख लेता है — उसके noise और random उतार-चढ़ाव समेत। जो data उसने देखा है, उस पर वह कमाल करता है, और जो नहीं देखा, उस पर बुरा। Regularisation loss function में एक penalty term जोड़ता है। Coefficients बढ़ें तो penalty भी बढ़ती है, इसलिए model छोटे, शांत coefficients पसंद करता है। ऐसे models आमतौर पर नए data पर कहीं बेहतर काम करते हैं।
Ridge और Lasso दोनों सामान्य Linear Regression loss से शुरू करते हैं और बड़े coefficients पर penalty जोड़ते हैं। Ridge coefficients के squares का जोड़ जोड़ता है (L2 penalty)। Lasso coefficients की absolute values का जोड़ जोड़ता है (L1 penalty)। एक नंबर, alpha (α), तय करता है कि penalty कितनी तेज़ है।
ख़ुद आज़माइए — The Overfitting Cure
एक बहुत लचीला model (degree-12 polynomial) सिर्फ़ 14 points पर fit किया गया है। बिना penalty के यह बुरी तरह लहराता है। α slider को दाईं तरफ़ खिसकाइए और देखिए कि curve शांत होता है — और बड़े-बड़े coefficients shrink होते हैं।
请留意这些可以互动的方框:The Overfitting Cure(第 01 节)、Multicollinearity Lab(02)、Geometry Explorer(05)、Shrinkage Rules(06)、Alpha Tuner(08)、Scaling Matters(09)、Coefficient Paths(12)和 ElasticNet Mixer(13)。里面的每个 model 都是在你的浏览器里实时拟合的。
一个能解释一切的故事
学生 B 读同样的笔记,但他逼自己只记住简单的核心规则。如果一个想法需要一长串特殊情况,他就把细节丢掉。 练习卷:88%。真正的考试:85%。几乎没有差距。
Regularisation 就是学生 B 的这种自律。它是一种惩罚复杂度的 penalty,让 model 学到规律,而不是死记噪声。 Ridge 和 Lasso 是这种自律最常用的两种形式。
当一个 model 把 training 数据学得太好 —— 连里面的噪声和随机起伏也学进去时,就发生了 overfitting。 它在见过的数据上表现很棒,在没见过的数据上表现很差。 Regularisation 在 loss function 里加上一个 penalty 项。coefficient 变大时,penalty 也会变大,所以 model 更喜欢小而平稳的 coefficient。这样的 model 在新数据上通常好得多。
Ridge 和 Lasso 都从普通 Linear Regression 的 loss 出发,再给大的 coefficient 加上一个 penalty。 Ridge 加上 coefficient 的平方之和(L2 penalty)。 Lasso 加上 coefficient 的绝对值之和(L1 penalty)。 一个数字 alpha (α) 决定 penalty 有多强。
动手试试 —— The Overfitting Cure
一个非常灵活的 model(12 次多项式)只用 14 个点来拟合。没有 penalty 时,它会疯狂地扭来扭去。把 α 滑块往右移,看曲线慢慢变平稳 —— 那些巨大的 coefficient 也会变小。
The Problem — Why Plain Linear Regression Can Fail
Ordinary Least Squares (OLS) regression only tries to make the training error as small as possible. It will choose any coefficients that do that — even huge, unstable ones.
1. More features than rows (p > n): OLS has infinitely many perfect solutions, so it cannot choose one.
2. Multicollinearity: when features are strongly correlated, the coefficients swing wildly from one sample to the next.
3. Useless features: OLS gives every feature some weight, so noise features add noise to every prediction.
Try It — Multicollinearity Lab
Here x₁ and x₂ are almost the same feature, and the true answer is β₁ = β₂ = 1. Each dot is the result of fitting one random dataset. Watch how far OLS (orange) wanders compared with Ridge (green).
समस्या — सादा Linear Regression क्यों fail हो सकता है
Ordinary Least Squares (OLS) regression सिर्फ़ training error को जितना हो सके छोटा करने की कोशिश करता है। ऐसा करने वाले कोई भी coefficients वह चुन लेगा — चाहे वे बहुत बड़े और अस्थिर ही क्यों न हों।
1. Rows से ज़्यादा features (p > n): OLS के पास अनगिनत perfect जवाब होते हैं, इसलिए वह एक नहीं चुन पाता।
2. Multicollinearity: जब features आपस में strongly correlated हों, तो coefficients एक sample से दूसरे sample में बुरी तरह झूलते हैं।
3. बेकार features: OLS हर feature को कुछ weight देता है, इसलिए noise features हर prediction में noise जोड़ देते हैं।
ख़ुद आज़माइए — Multicollinearity Lab
यहाँ x₁ और x₂ लगभग एक ही feature हैं, और असली जवाब β₁ = β₂ = 1 है। हर dot एक random dataset को fit करने का नतीजा है। देखिए कि Ridge (हरा) की तुलना में OLS (नारंगी) कितनी दूर भटकता है।
问题所在 —— 为什么普通的 Linear Regression 会失败
Ordinary Least Squares(OLS)回归只想让 training error 尽可能小。 只要能做到这一点,它会选任何 coefficient —— 哪怕是巨大又不稳定的。
1. feature 比行还多(p > n):OLS 有无穷多个完美解,所以它没法选出一个。
2. Multicollinearity:当 feature 之间有很强的 correlation 时,coefficient 会从一个样本到另一个样本剧烈摆动。
3. 没用的 feature:OLS 会给每个 feature 一些权重,所以噪声 feature 会给每次预测都加上噪声。
动手试试 —— Multicollinearity Lab
这里 x₁ 和 x₂ 几乎是同一个 feature,真实答案是 β₁ = β₂ = 1。每个点是拟合一个随机 dataset 得到的结果。看看 OLS(橙色)比 Ridge(绿色)跑得远多少。
Ridge Regression — L2 Regularisation
Ridge Regression adds the sum of squared coefficients, multiplied by α, to the loss:
Ridge uses.Lasso Regression — L1 Regularisation
Lasso (Least Absolute Shrinkage and Selection Operator) uses the sum of absolute values of the coefficients as its penalty:
The pull of the L2 penalty gets weaker as a coefficient gets close to zero (the slope of β² is 2β). The pull of the L1 penalty does not get weaker (the slope of |β| is always ±1). So Lasso keeps pushing small coefficients until they reach exactly zero. With 100 features, Lasso might keep only 12. That makes the model easier to explain — but the chosen 12 are not always exactly the "true" ones, especially when features are correlated.
The Geometry — Why L1 Gives Zeros and L2 Does Not
The clearest way to see the difference is to draw it. Think of the penalty as a budget: the coefficients must stay inside a region. For L1 the region is a diamond. For L2 it is a circle. The loss has oval contour lines (ellipses) around the OLS answer. The regularised answer is the point where the smallest ellipse first touches the region.
Try It — Geometry Explorer
Drag the orange OLS point. Make the budget smaller. Press Grow the ellipse to watch the contour grow until it touches the shape.
Ridge Regression — L2 Regularisation
Ridge Regression loss में coefficients के squares का जोड़, α से गुणा करके, जोड़ता है:
Ridge ठीक यही रूप इस्तेमाल करता है।Lasso Regression — L1 Regularisation
Lasso (Least Absolute Shrinkage and Selection Operator) penalty के तौर पर coefficients की absolute values का जोड़ इस्तेमाल करता है:
जैसे-जैसे coefficient zero के पास आता है, L2 penalty का खिंचाव कमज़ोर होता जाता है (β² का slope 2β है)। L1 penalty का खिंचाव कमज़ोर नहीं होता (|β| का slope हमेशा ±1 है)। इसलिए Lasso छोटे coefficients को तब तक धकेलता रहता है जब तक वे बिल्कुल zero न हो जाएँ। 100 features में से Lasso शायद सिर्फ़ 12 रखे। इससे model समझाना आसान हो जाता है — पर चुने गए 12 हमेशा ठीक "असली" वाले नहीं होते, ख़ासकर जब features correlated हों।
Geometry — L1 zeros क्यों देता है और L2 क्यों नहीं
फ़र्क़ देखने का सबसे साफ़ तरीका है इसे draw करना। Penalty को एक budget समझिए: coefficients को एक हिस्से के अंदर रहना है। L1 के लिए यह हिस्सा एक हीरा है। L2 के लिए यह एक गोला है। Loss की OLS जवाब के चारों तरफ़ अंडाकार contour lines (ellipses) होती हैं। Regularised जवाब वह point है जहाँ सबसे छोटा ellipse पहली बार उस हिस्से को छूता है।
ख़ुद आज़माइए — Geometry Explorer
नारंगी OLS point को खींचिए। Budget छोटा कीजिए। Ellipse बड़ा करें दबाइए और देखिए कि contour तब तक बढ़ता है जब तक वह shape को छू न ले।
Ridge Regression —— L2 Regularisation
Ridge Regression 把 coefficient 的平方之和乘以 α,加到 loss 上:
Ridge 用的形式。Lasso Regression —— L1 Regularisation
Lasso(Least Absolute Shrinkage and Selection Operator)用 coefficient 的绝对值之和作为 penalty:
当 coefficient 接近 zero 时,L2 penalty 的拉力会变弱(β² 的斜率是 2β)。L1 penalty 的拉力不会变弱(|β| 的斜率永远是 ±1)。 所以 Lasso 会一直推小的 coefficient,直到它们正好变成 zero。 如果有 100 个 feature,Lasso 可能只保留 12 个。这让 model 更容易解释 —— 但选出的 12 个不一定正好是“真正”的那些,特别是 feature 之间有 correlation 的时候。
几何图 —— 为什么 L1 会给出 zero,而 L2 不会
看清区别最好的办法是把它画出来。把 penalty 想成一个预算:coefficient 必须待在一个区域里面。 对 L1 来说,这个区域是一个菱形。对 L2 来说,它是一个圆形。 loss 在 OLS 答案周围有一圈圈椭圆形的 contour 线。regularisation 后的答案,就是最小的椭圆第一次碰到这个区域的那个点。
动手试试 —— Geometry Explorer
拖动橙色的 OLS 点。把预算调小。按 放大椭圆,看 contour 一直变大,直到碰到这个形状。
The diamond has sharp corners, and every corner sits on an axis — where one coefficient is exactly zero. Growing ellipses very often hit a corner first, so Lasso often gives zeros. The circle has no corners. The ellipse touches it at a smooth point, almost never exactly on an axis, so Ridge shrinks both coefficients but keeps them non-zero. In more dimensions the diamond has even more corners and edges, so Lasso zeros become even more common.
Shrinkage Rules — What Each Penalty Does to One Coefficient
In the simplest case (features that are standardised and not correlated), the two penalties follow very simple rules:
Try It — Shrinkage Rules
Move the penalty slider. The left chart shows the rule for any coefficient. The bars show what happens to eight example coefficients.
हीरे के नुकीले कोने होते हैं, और हर कोना एक axis पर होता है — जहाँ एक coefficient बिल्कुल zero है। बढ़ते ellipses अक्सर पहले किसी कोने से टकराते हैं, इसलिए Lasso अक्सर zeros देता है। गोले में कोई कोना नहीं होता। Ellipse उसे एक smooth point पर छूता है, लगभग कभी ठीक axis पर नहीं, इसलिए Ridge दोनों coefficients को shrink करता है पर उन्हें non-zero रखता है। ज़्यादा dimensions में हीरे के और भी ज़्यादा कोने और किनारे होते हैं, इसलिए Lasso के zeros और भी आम हो जाते हैं।
Shrinkage Rules — हर penalty एक coefficient के साथ क्या करती है
सबसे आसान case में (features जो standardised हैं और correlated नहीं हैं), दोनों penalties बहुत सीधे नियम मानती हैं:
ख़ुद आज़माइए — Shrinkage Rules
Penalty slider को खिसकाइए। बायाँ chart किसी भी coefficient के लिए नियम दिखाता है। Bars दिखाते हैं कि आठ example coefficients के साथ क्या होता है।
菱形有尖尖的角,而且每个角都在一条坐标轴上 —— 那里有一个 coefficient 正好是 zero。不断变大的椭圆常常最先碰到一个角,所以 Lasso 经常给出 zero。 圆形没有角。椭圆在一个平滑的点上碰到它,几乎从来不会正好在坐标轴上,所以 Ridge 会缩小两个 coefficient,但让它们都不是 zero。 在更多维度里,菱形有更多的角和边,所以 Lasso 的 zero 会更加常见。
Shrinkage 规则 —— 每种 penalty 对一个 coefficient 做了什么
在最简单的情况下(feature 已经 standardise,并且没有 correlation),两种 penalty 遵守非常简单的规则:
动手试试 —— Shrinkage Rules
移动 penalty 滑块。左边的图显示了对任意 coefficient 的规则。条形图显示八个示例 coefficient 会发生什么。
Ridge vs Lasso — Side by Side
| Property | Ridge (L2) | Lasso (L1) |
|---|---|---|
| Penalty | α × Σβⱼ² | α × Σ|βⱼ| |
| Constraint shape | Smooth circle / sphere | Diamond with corners |
| Coefficients become exactly 0? | Almost never | Yes, often |
| Feature selection? | No — keeps all features | Yes — automatic |
| Correlated features | Shares weight, stable | Often keeps one, drops others — can be unstable |
| p > n (more features than rows) | Works | Works, but keeps at most n features |
| Closed-form solution? | Yes | No — coordinate descent |
| Pull of the penalty near 0 | Fades to zero (slope 2αβ) | Stays constant (±α) |
| Best for | Many features that all help a little; correlated features | Many features where only a few really matter |
The Alpha Hyperparameter — Bias–Variance Trade-off
α is the most important setting in regularised regression. It controls the balance between underfitting and overfitting. As α grows, training error goes up (more bias). Test error usually goes down first (less variance), then up again. The best α is at the bottom of the test-error curve — and cross-validation finds it without touching the test set.
Try It — Alpha Tuner
50 training rows, 20 features, but only 5 features really matter (bold). Slide α and compare training error, test error and 5-fold CV error. Switch between Ridge and Lasso.
Ridge बनाम Lasso — आमने-सामने
| ख़ासियत | Ridge (L2) | Lasso (L1) |
|---|---|---|
| Penalty | α × Σβⱼ² | α × Σ|βⱼ| |
| Constraint का shape | Smooth गोला / sphere | कोनों वाला हीरा |
| Coefficients बिल्कुल 0 बनते हैं? | लगभग कभी नहीं | हाँ, अक्सर |
| Feature selection? | नहीं — सारे features रखता है | हाँ — अपने-आप |
| Correlated features | Weight बाँटता है, stable | अक्सर एक रखता है, बाकी हटाता है — unstable हो सकता है |
| p > n (rows से ज़्यादा features) | चलता है | चलता है, पर ज़्यादा से ज़्यादा n features रखता है |
| Closed-form solution? | हाँ | नहीं — coordinate descent |
| 0 के पास penalty का खिंचाव | घटकर zero हो जाता है (slope 2αβ) | एक जैसा रहता है (±α) |
| किसके लिए सबसे अच्छा | बहुत सारे features जो सब थोड़ी मदद करते हैं; correlated features | बहुत सारे features जिनमें सिर्फ़ कुछ ही सच में मायने रखते हैं |
Alpha Hyperparameter — Bias–Variance Trade-off
α regularised regression की सबसे ज़रूरी setting है। यह underfitting और overfitting के बीच संतुलन को control करता है। α बढ़ने पर training error ऊपर जाता है (ज़्यादा bias)। Test error आमतौर पर पहले नीचे जाता है (कम variance), फिर फिर से ऊपर। सबसे अच्छा α test-error curve के सबसे निचले हिस्से पर है — और cross-validation इसे test set को छुए बिना ढूँढ लेता है।
ख़ुद आज़माइए — Alpha Tuner
50 training rows, 20 features, पर सिर्फ़ 5 features सच में मायने रखते हैं (bold)। α को खिसकाइए और training error, test error और 5-fold CV error की तुलना कीजिए। Ridge और Lasso के बीच बदलिए।
Ridge vs Lasso —— 放在一起比较
| 特点 | Ridge (L2) | Lasso (L1) |
|---|---|---|
| Penalty | α × Σβⱼ² | α × Σ|βⱼ| |
| 约束区域的形状 | 平滑的圆 / 球 | 有角的菱形 |
| coefficient 会正好变成 0 吗? | 几乎从不 | 会,而且经常 |
| Feature selection? | 没有 —— 保留所有 feature | 有 —— 自动完成 |
| 有 correlation 的 feature | 分担权重,很稳定 | 常常只留一个,丢掉其他 —— 可能不稳定 |
| p > n(feature 比行多) | 可以用 | 可以用,但最多保留 n 个 feature |
| 有 closed-form 解吗? | 有 | 没有 —— 用 coordinate descent |
| penalty 在 0 附近的拉力 | 逐渐减到 zero(斜率 2αβ) | 保持不变(±α) |
| 最适合 | 很多 feature 都有一点帮助;feature 之间有 correlation | 很多 feature 中只有少数真正重要 |
Alpha 这个 Hyperparameter —— Bias–Variance Trade-off
α 是 regularisation 回归里最重要的设置。它控制 underfitting 和 overfitting 之间的平衡。 α 变大时,training error 会上升(bias 更多)。test error 通常先下降(variance 更少),然后再上升。最好的 α 在 test error 曲线的最低点 —— cross-validation 不用碰 test set 就能找到它。
动手试试 —— Alpha Tuner
50 行 training 数据,20 个 feature,但只有 5 个 feature 真正重要(粗体)。滑动 α,比较 training error、test error 和 5-fold CV error。在 Ridge 和 Lasso 之间切换。
RidgeCV or LassoCV.Why Feature Scaling Is a Must
The penalty only looks at the size of the coefficient. So it hardly touches area and hits bedrooms hard — even if both features matter equally. Change the units (area in square metres, or in square kilometres) and the penalty would change, even though the house is the same. That is unfair.
Try It — Scaling Matters
Both features truly matter equally. Increase the Lasso α with and without scaling, and watch which feature the penalty attacks.
RidgeCV या LassoCV।Feature Scaling क्यों ज़रूरी है
Penalty सिर्फ़ coefficient का size देखती है। इसलिए वह area को मुश्किल से छूती है और bedrooms पर ज़ोर से चोट करती है — चाहे दोनों features बराबर मायने रखते हों। Units बदल दीजिए (area square metres में, या square kilometres में) और penalty बदल जाएगी, जबकि घर वही है। यह नाइंसाफ़ी है।
ख़ुद आज़माइए — Scaling Matters
दोनों features सच में बराबर मायने रखते हैं। Scaling के साथ और बिना scaling के Lasso α बढ़ाइए, और देखिए कि penalty किस feature पर हमला करती है।
RidgeCV 或 LassoCV。为什么 Feature Scaling 是必须的
penalty 只看 coefficient 的大小。所以它几乎不碰面积,却狠狠地打击卧室数 —— 即使两个 feature 一样重要。 换一下单位(面积用平方米,或者平方公里),penalty 就会变,可房子还是同一套。这不公平。
动手试试 —— Scaling Matters
这两个 feature 其实一样重要。在有 scaling 和没有 scaling 的情况下调大 Lasso α,看看 penalty 攻击的是哪个 feature。
Use StandardScaler (mean 0, standard deviation 1) before Ridge or Lasso. Then the penalty treats every feature fairly — it punishes real complexity, not the choice of units.
Put the scaler and the model in one Pipeline, so the scaler learns only from training rows.
Python — Ridge Regression with Cross-Validation
This example uses scikit-learn's built-in diabetes dataset: 442 patients, 10 measurements each (age, sex, BMI, blood pressure and six blood tests s1–s6), and a number that says how much the disease progressed after one year.
The scaler and the model live in one pipeline, and RidgeCV picks α with 10-fold cross-validation.
Ridge या Lasso से पहले StandardScaler (mean 0, standard deviation 1) इस्तेमाल कीजिए। तब penalty हर feature के साथ बराबरी का बर्ताव करती है — वह असली complexity को सज़ा देती है, units के चुनाव को नहीं।
Scaler और model को एक Pipeline में रखिए, ताकि scaler सिर्फ़ training rows से सीखे।
Python — Cross-Validation के साथ Ridge Regression
यह example scikit-learn का built-in diabetes dataset इस्तेमाल करता है: 442 मरीज़, हर एक के 10 measurements (age, sex, BMI, blood pressure और छह blood tests s1–s6), और एक नंबर जो बताता है कि एक साल बाद बीमारी कितनी बढ़ी।
Scaler और model एक pipeline में रहते हैं, और RidgeCV 10-fold cross-validation से α चुनता है।
在 Ridge 或 Lasso 之前使用 StandardScaler(平均值 0,标准差 1)。这样 penalty 对每个 feature 都公平 —— 它惩罚的是真正的复杂度,而不是单位的选择。
把 scaler 和 model 放进同一个 Pipeline,这样 scaler 只从 training 行学习。
Python —— 用 Cross-Validation 做 Ridge Regression
这个例子用 scikit-learn 自带的 diabetes dataset:442 个病人,每人 10 项测量(age、sex、BMI、血压,以及六项血液检查 s1–s6),还有一个数字,表示一年后病情发展了多少。
scaler 和 model 放在同一个 pipeline 里,RidgeCV 用 10-fold cross-validation 来选 α。
import numpy as np
import pandas as pd
from sklearn.datasets import load_diabetes
from sklearn.linear_model import RidgeCV
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
# ── 1. Load data: 442 patients, 10 features, target = disease progression after 1 year ──
X, y = load_diabetes(return_X_y=True, as_frame=True)
# ── 2. Train / test split ───────────────────────────────
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# ── 3. Pipeline = scaler + model (the scaler learns from training rows only) ──
alphas = np.logspace(-3, 4, 100) # 0.001 … 10,000
model = make_pipeline(StandardScaler(), RidgeCV(alphas=alphas, cv=10))
model.fit(X_train, y_train)
ridge = model[-1]
print(f"Best alpha: {ridge.alpha_:.4f}")
# ── 4. Evaluate on the test set ─────────────────────────
y_pred = model.predict(X_test)
print(f"Test RMSE : {mean_squared_error(y_test, y_pred) ** 0.5:.2f}")
print(f"Test R² : {r2_score(y_test, y_pred):.4f}")
# ── 5. Coefficients (on standardised features) ──────────
coef = pd.Series(ridge.coef_, index=X.columns).sort_values(key=abs, ascending=False)
print("\nRidge coefficients:")
print(coef.round(2).to_string())
Even the smallest coefficient (age, 2.03) is not zero. That is Ridge: every feature stays, just shrunk.
Look at s1 and s2: they are strongly correlated (r = 0.90), and Ridge gives them almost the same small weight (−4.44 and −4.28). It shares the weight.
RidgeCV tried 100 α values and chose 54.6.
Python — Lasso Regression with Feature Selection
Now the same data with Lasso. Watch for coefficients that become exactly zero.
सबसे छोटा coefficient (age, 2.03) भी zero नहीं है। यही Ridge है: हर feature रहता है, बस shrink होकर।
s1 और s2 को देखिए: ये strongly correlated हैं (r = 0.90), और Ridge इन्हें लगभग एक जैसा छोटा weight देता है (−4.44 और −4.28)। वह weight बाँटता है।
RidgeCV ने 100 α values आज़माईं और 54.6 चुना।
Python — Feature Selection के साथ Lasso Regression
अब वही data Lasso के साथ। उन coefficients पर नज़र रखिए जो बिल्कुल zero बन जाते हैं।
连最小的 coefficient(age,2.03)也不是 zero。这就是 Ridge:每个 feature 都留着,只是变小了。
看看 s1 和 s2:它们有很强的 correlation(r = 0.90),Ridge 给了它们几乎一样的小权重(−4.44 和 −4.28)。它在分担权重。
RidgeCV 试了 100 个 α 值,选了 54.6。
Python —— 用 Lasso Regression 做 Feature Selection
现在用 Lasso 处理同样的数据。注意看哪些 coefficient 正好变成了 zero。
import numpy as np
import pandas as pd
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LassoCV
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
X, y = load_diabetes(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# ── LassoCV: tries 100 alphas (by default) with 10-fold cross-validation ──
model = make_pipeline(StandardScaler(),
LassoCV(cv=10, max_iter=10000, random_state=42))
model.fit(X_train, y_train)
lasso = model[-1]
print(f"Best alpha: {lasso.alpha_:.4f}")
y_pred = model.predict(X_test)
print(f"Test RMSE : {mean_squared_error(y_test, y_pred) ** 0.5:.2f}")
print(f"Test R² : {r2_score(y_test, y_pred):.4f}")
# ── Feature selection report ─────────────────────────────
coef = pd.Series(lasso.coef_, index=X.columns)
print(f"\nFeatures kept: {(coef != 0).sum()} / {len(coef)}")
for name, c in coef.items():
print(f" {name:4s}: {c + 0.0:8.2f} {'kept' if c != 0 else 'ZEROED'}")
Lasso removed s3 completely. s3 is strongly linked to s4 (r = −0.74), so most of its information is already in the model.
Now compare s1 and s2 again. Ridge gave them −4.44 and −4.28. Lasso gave them −27.10 and +11.29 — large and with opposite signs. With correlated features, Lasso's choices can be unstable, and individual coefficients are hard to interpret.
Also notice the best α: 0.144 for Lasso vs 54.6 for Ridge. The two penalties are scaled differently in scikit-learn, so α values are not comparable.
Test R² is almost the same for both (0.456 vs 0.461). Neither is "always better" — it depends on your data and your goal.
Coefficient Paths — How Coefficients Change with Alpha
A regularisation path plots every coefficient as α goes from very small (close to OLS) to very large (everything near zero). It is the best picture of the difference between Ridge and Lasso.
Try It — Coefficient Paths
Five features really matter (coloured, labelled). Three are noise (grey). Press Play to sweep α, and switch between Ridge and Lasso.
Lasso ने s3 को पूरी तरह हटा दिया। s3, s4 से गहराई से जुड़ा है (r = −0.74), इसलिए उसकी ज़्यादातर जानकारी पहले से model में है।
अब s1 और s2 की फिर से तुलना कीजिए। Ridge ने इन्हें −4.44 और −4.28 दिए थे। Lasso ने इन्हें −27.10 और +11.29 दिए — बड़े और उल्टे signs वाले। Correlated features के साथ Lasso के चुनाव unstable हो सकते हैं, और अलग-अलग coefficients को समझना मुश्किल होता है।
Best α पर भी ध्यान दीजिए: Lasso के लिए 0.144 बनाम Ridge के लिए 54.6। scikit-learn में दोनों penalties अलग तरह से scale होती हैं, इसलिए α values की तुलना नहीं की जा सकती।
Test R² दोनों के लिए लगभग एक जैसा है (0.456 बनाम 0.461)। कोई भी "हमेशा बेहतर" नहीं है — यह आपके data और आपके लक्ष्य पर निर्भर करता है।
Coefficient Paths — Alpha के साथ Coefficients कैसे बदलते हैं
एक regularisation path हर coefficient को plot करता है, जब α बहुत छोटे (OLS के क़रीब) से बहुत बड़े (सब कुछ zero के पास) तक जाता है। Ridge और Lasso का फ़र्क़ दिखाने वाली यह सबसे अच्छी तस्वीर है।
ख़ुद आज़माइए — Coefficient Paths
पाँच features सच में मायने रखते हैं (रंगीन, नाम के साथ)। तीन noise हैं (स्लेटी)। α को चलाने के लिए चलाएँ दबाइए, और Ridge और Lasso के बीच बदलिए।
Lasso 把 s3 完全删掉了。s3 和 s4 关系很强(r = −0.74),所以它的大部分信息已经在 model 里了。
现在再比较一下 s1 和 s2。Ridge 给了它们 −4.44 和 −4.28。Lasso 给了它们 −27.10 和 +11.29 —— 很大,而且符号相反。feature 之间有 correlation 时,Lasso 的选择可能不稳定,单个 coefficient 也很难解释。
还要注意最佳 α:Lasso 是 0.144,Ridge 是 54.6。在 scikit-learn 里,两种 penalty 的尺度不一样,所以 α 值不能直接比较。
两者的 test R² 几乎一样(0.456 vs 0.461)。没有哪一个“永远更好” —— 这取决于你的数据和你的目标。
Coefficient 路径 —— Coefficient 怎样随 Alpha 变化
regularisation path 画出 α 从很小(接近 OLS)变到很大(全部接近 zero)时,每个 coefficient 的变化。 它是展示 Ridge 和 Lasso 区别最好的一张图。
动手试试 —— Coefficient Paths
五个 feature 真正重要(有颜色,有标签)。三个是噪声(灰色)。按 播放 来扫过 α,并在 Ridge 和 Lasso 之间切换。
Ridge: the lines glide smoothly toward zero together. They can cross each other, and a coefficient can even change sign, but they do not land on zero.
Lasso: lines hit zero one by one. Each line that lands on zero is a feature leaving the model. Reading the path from right to left shows the order in which features "enter" — a quick ranking of their usefulness.
ElasticNet — The Best of Both Worlds
ElasticNet mixes both penalties. You get Lasso's feature selection and Ridge's stability with correlated features. It has two settings: α (total strength) and l1_ratio (how much of the penalty is L1).
Try It — ElasticNet Mixer
Three features (A1, A2, A3) are near-copies of the same signal. Slide l1_ratio from Ridge to Lasso and watch what happens to the A group.
Ridge: lines एक साथ धीरे-धीरे zero की तरफ़ सरकती हैं। वे एक-दूसरे को काट सकती हैं, और कोई coefficient अपना sign भी बदल सकता है, पर वे zero पर नहीं आतीं।
Lasso: lines एक-एक करके zero पर पहुँचती हैं। Zero पर आने वाली हर line एक feature है जो model छोड़ रहा है। Path को दाएँ से बाएँ पढ़ने पर दिखता है कि features किस क्रम में "आते" हैं — उनकी उपयोगिता की एक झटपट ranking।
ElasticNet — दोनों दुनिया का सबसे अच्छा
ElasticNet दोनों penalties को मिलाता है। आपको Lasso का feature selection और correlated features के साथ Ridge की stability, दोनों मिलते हैं। इसकी दो settings हैं: α (कुल ताक़त) और l1_ratio (penalty का कितना हिस्सा L1 है)।
ख़ुद आज़माइए — ElasticNet Mixer
तीन features (A1, A2, A3) एक ही signal की लगभग copies हैं। l1_ratio को Ridge से Lasso की तरफ़ खिसकाइए और देखिए कि A group के साथ क्या होता है।
Ridge:线一起平滑地滑向 zero。它们可以互相交叉,coefficient 甚至可以改变符号,但它们不会落到 zero 上。
Lasso:线一条一条地碰到 zero。每条落到 zero 的线,就是一个离开 model 的 feature。从右往左看路径,能看到 feature “进入”的顺序 —— 这是它们有用程度的一个快速排名。
ElasticNet —— 两全其美
ElasticNet 把两种 penalty 混在一起。你既得到 Lasso 的 feature selection,又得到 Ridge 在有 correlation 的 feature 上的稳定性。 它有两个设置:α(总强度)和 l1_ratio(penalty 中 L1 占多少)。
动手试试 —— ElasticNet Mixer
三个 feature(A1、A2、A3)几乎是同一个信号的复制品。把 l1_ratio 从 Ridge 滑到 Lasso,看看 A 组会发生什么。
Python — ElasticNetCV
Python — ElasticNetCV
Python —— ElasticNetCV
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import ElasticNetCV
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
X, y = load_diabetes(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# ── ElasticNetCV searches alpha AND l1_ratio together ──
model = make_pipeline(StandardScaler(), ElasticNetCV(
l1_ratio=[.1, .3, .5, .7, .9, .95, 1.0],
alphas=np.logspace(-3, 2, 60),
cv=10, max_iter=10000, random_state=42))
model.fit(X_train, y_train)
enet = model[-1]
print(f"Best alpha : {enet.alpha_:.4f}")
print(f"Best l1_ratio : {enet.l1_ratio_:.2f}")
print(f"Test R² : {r2_score(y_test, model.predict(X_test)):.4f}")
print(f"Features zeroed: {(enet.coef_ == 0).sum()} / {len(enet.coef_)}")
On the diabetes data, cross-validation chose l1_ratio = 0.90 — close to Lasso — and one feature was zeroed. Test R² (0.455) is almost the same as Ridge and Lasso. That is normal: with only 10 features, the three methods give similar accuracy. ElasticNet matters most when you have many features in correlated groups, such as genes or word counts.
When to Use Ridge, Lasso or ElasticNet
| Situation | Good first choice | Why |
|---|---|---|
| Many features, most probably help a little | Ridge | Shrinks all coefficients, keeps every feature |
| Many features, only a few really matter | Lasso | Automatic sparse feature selection |
| Strongly correlated features | Ridge or ElasticNet | Share weight inside the group; more stable |
| p > n (more features than rows) | Ridge or ElasticNet | Both work; Lasso can keep at most n features |
| You need a short, easy-to-explain model | Lasso | Few non-zero coefficients |
| Correlated groups AND you want selection | ElasticNet | Keeps groups together, still removes noise |
| Genes, text, very wide data | ElasticNet or Lasso | Thousands of features, few useful |
| Not sure | ElasticNetCV | Let cross-validation choose α and l1_ratio |
Real-World Example — Many Features, Few Matter
The code below recreates this situation with synthetic data where we know the truth: 100 features, only 10 of them real.
Diabetes data पर cross-validation ने l1_ratio = 0.90 चुना — Lasso के क़रीब — और एक feature zero हो गया। Test R² (0.455) लगभग Ridge और Lasso जितना ही है। यह आम बात है: सिर्फ़ 10 features के साथ तीनों तरीके मिलती-जुलती accuracy देते हैं। ElasticNet सबसे ज़्यादा तब काम आता है जब आपके पास correlated groups में बहुत सारे features हों, जैसे genes या word counts।
Ridge, Lasso या ElasticNet कब इस्तेमाल करें
| हालात | अच्छा पहला चुनाव | क्यों |
|---|---|---|
| बहुत सारे features, ज़्यादातर शायद थोड़ी मदद करते हैं | Ridge | सारे coefficients shrink करता है, हर feature रखता है |
| बहुत सारे features, सिर्फ़ कुछ ही सच में मायने रखते हैं | Lasso | अपने-आप sparse feature selection |
| Strongly correlated features | Ridge या ElasticNet | Group के अंदर weight बाँटते हैं; ज़्यादा stable |
| p > n (rows से ज़्यादा features) | Ridge या ElasticNet | दोनों चलते हैं; Lasso ज़्यादा से ज़्यादा n features रख सकता है |
| आपको छोटा, आसानी से समझाने वाला model चाहिए | Lasso | कम non-zero coefficients |
| Correlated groups और साथ में selection भी चाहिए | ElasticNet | Groups को साथ रखता है, फिर भी noise हटाता है |
| Genes, text, बहुत चौड़ा data | ElasticNet या Lasso | हज़ारों features, काम के बहुत कम |
| पक्का नहीं पता | ElasticNetCV | Cross-validation को α और l1_ratio चुनने दीजिए |
असल ज़िंदगी का Example — Features बहुत, काम के कम
नीचे का code synthetic data से यही हालात दोबारा बनाता है, जहाँ हमें सच पता है: 100 features, जिनमें से सिर्फ़ 10 असली हैं।
在 diabetes 数据上,cross-validation 选了 l1_ratio = 0.90 —— 接近 Lasso —— 并且有一个 feature 被变成了 zero。 test R²(0.455)和 Ridge、Lasso 几乎一样。这很正常:只有 10 个 feature 时,三种方法的准确度差不多。当你有很多分成相关小组的 feature 时(比如基因或词频),ElasticNet 才最重要。
什么时候用 Ridge、Lasso 或 ElasticNet
| 情况 | 好的首选 | 原因 |
|---|---|---|
| 很多 feature,大多数可能都有一点帮助 | Ridge | 缩小所有 coefficient,保留每个 feature |
| 很多 feature,只有少数真正重要 | Lasso | 自动做 sparse 的 feature selection |
| feature 之间有很强的 correlation | Ridge 或 ElasticNet | 在组内分担权重;更稳定 |
| p > n(feature 比行多) | Ridge 或 ElasticNet | 两者都能用;Lasso 最多保留 n 个 feature |
| 你需要一个简短、容易解释的 model | Lasso | 非 zero 的 coefficient 很少 |
| 有相关的 feature 组,并且你想做选择 | ElasticNet | 让组保持在一起,同时还能去掉噪声 |
| 基因、文本、非常宽的数据 | ElasticNet 或 Lasso | 成千上万个 feature,有用的很少 |
| 不确定 | ElasticNetCV | 让 cross-validation 来选 α 和 l1_ratio |
真实案例 —— 很多 Feature,只有少数重要
下面的代码用合成数据重现了这个情况,我们知道真实答案:100 个 feature,其中只有 10 个是真的。
import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression, RidgeCV, LassoCV
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
# ── 150 rows, 100 features, but only 10 features really matter ──
X, y, true_coef = make_regression(n_samples=150, n_features=100, n_informative=10,
noise=20, coef=True, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
models = {
"OLS ": make_pipeline(StandardScaler(), LinearRegression()),
"Ridge": make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 4, 50))),
"Lasso": make_pipeline(StandardScaler(), LassoCV(cv=5, max_iter=20000, random_state=0)),
}
for name, m in models.items():
m.fit(X_train, y_train)
print(f"{name} train R² = {r2_score(y_train, m.predict(X_train)):.3f} "
f"test R² = {r2_score(y_test, m.predict(X_test)):.3f}")
lasso = models["Lasso"][-1]
kept = np.flatnonzero(lasso.coef_)
real = np.flatnonzero(true_coef)
print(f"\nLasso kept {len(kept)} of 100 features")
print(f"Real features found: {len(set(kept) & set(real))} of {len(real)}")
OLS: training R² 0.999, test R² 0.271 — classic overfitting. Ridge: test R² 0.893. Lasso: test R² 0.979, using only 10 of 100 features. But look closely: only 7 of the 10 real features were found. Lasso is a great filter, not a perfect one — always check the chosen features with domain knowledge.
Common Mistakes — And How to Fix Them
StandardScaler first.RidgeCV, LassoCV or ElasticNetCV to search for α with cross-validation.Pipeline.
Mistake 4 — Penalising the intercept: β₀ should not be penalised. scikit-learn handles this for you (fit_intercept=True), but watch out if you write the maths yourself.
Mistake 5 — Comparing raw coefficients: coefficients are only comparable if the features were standardised. Otherwise a big coefficient may just mean a feature with small units.
Mistake 6 — Copying α between models: scikit-learn scales the Ridge and Lasso losses differently, so α = 1 means something very different in each.
Golden Rules
StandardScaler inside a Pipeline, so it learns only from training rows. Without scaling, the penalty depends on units, not on usefulness.
RidgeCV or LassoCV. The best α changes a lot from dataset to dataset.
ConvergenceWarning, raise max_iter (for example to 10,000).
OLS: training R² 0.999, test R² 0.271 — पक्का overfitting। Ridge: test R² 0.893। Lasso: test R² 0.979, 100 में से सिर्फ़ 10 features इस्तेमाल करके। पर ग़ौर से देखिए: 10 असली features में से सिर्फ़ 7 मिले। Lasso एक बढ़िया filter है, perfect नहीं — चुने गए features को हमेशा अपनी domain की समझ से जाँचिए।
आम गलतियाँ — और उन्हें कैसे ठीक करें
StandardScaler इस्तेमाल कीजिए।RidgeCV, LassoCV या ElasticNetCV इस्तेमाल कीजिए।Pipeline के अंदर रखिए।
गलती 4 — Intercept पर penalty लगाना: β₀ पर penalty नहीं लगनी चाहिए। scikit-learn यह आपके लिए संभाल लेता है (fit_intercept=True), पर अगर आप maths ख़ुद लिखते हैं तो ध्यान रखिए।
गलती 5 — Raw coefficients की तुलना करना: coefficients की तुलना तभी हो सकती है जब features standardised हों। वरना बड़े coefficient का मतलब बस छोटी units वाला feature हो सकता है।
गलती 6 — एक model से दूसरे में α copy करना: scikit-learn Ridge और Lasso के losses को अलग तरह से scale करता है, इसलिए α = 1 का मतलब दोनों में बहुत अलग है।
सुनहरे नियम
StandardScaler को Pipeline के अंदर इस्तेमाल कीजिए, ताकि वह सिर्फ़ training rows से सीखे। बिना scaling के penalty units पर निर्भर करती है, उपयोगिता पर नहीं।
RidgeCV या LassoCV से एक log-spaced grid खोजिए (जैसे Ridge के लिए 0.001 से 10,000)। सबसे अच्छा α एक dataset से दूसरे dataset में बहुत बदलता है।
ConvergenceWarning दिखे, तो max_iter बढ़ाइए (जैसे 10,000 तक)।
OLS:training R² 0.999,test R² 0.271 —— 典型的 overfitting。Ridge:test R² 0.893。Lasso:test R² 0.979,只用了 100 个 feature 中的 10 个。 但仔细看:10 个真 feature 中只找到了 7 个。Lasso 是一个很好的过滤器,但不是完美的 —— 一定要用领域知识检查选出的 feature。
常见错误 —— 以及怎样改正
StandardScaler。RidgeCV、LassoCV 或 ElasticNetCV,通过 cross-validation 来搜索 α。Pipeline 里。
错误 4 —— 对 intercept 加 penalty:β₀ 不应该受 penalty。scikit-learn 会帮你处理(fit_intercept=True),但如果你自己写数学公式,就要小心。
错误 5 —— 直接比较原始 coefficient:只有 feature 做过 standardise,coefficient 才能互相比较。否则,一个大的 coefficient 可能只是说明这个 feature 的单位很小。
错误 6 —— 在不同 model 之间照搬 α:scikit-learn 对 Ridge 和 Lasso 的 loss 用了不同的尺度,所以 α = 1 在两者中的意思很不一样。
黄金法则
StandardScaler 放进 Pipeline 里,这样它只从 training 行学习。没有 scaling,penalty 取决于单位,而不是有用程度。
RidgeCV 或 LassoCV 在一个对数间隔的网格上搜索(例如 Ridge 用 0.001 到 10,000)。最佳 α 在不同 dataset 之间变化很大。
ConvergenceWarning,就把 max_iter 调大(例如调到 10,000)。