The Story: Vikram's Three Models and Coach Arjun's Two Archers
He tries three models: a straight line, a very wiggly curve and a smooth, gently bending curve. His manager asks one question: "Which model do I trust?"
Vikram's friend, Coach Arjun, trains archers. He says: "I have the same problem. Priya shoots tight groups — but always in the bottom-left corner. Ravi sprays arrows everywhere — sometimes near the centre, often not. I want an archer whose arrows are tight and centred."
Priya has bias. Ravi has variance. Vikram's straight line behaves like Priya, and his wiggly curve behaves like Ravi. This tutorial shows exactly why — with numbers you can measure yourself.
Look for the interactive boxes: the Archery Lab (Section 04), Many Training Sets (05), The U-Curve, Computed (06), The Split Lottery (08), Learning Curves (09) and Taming a Wiggly Model (12). They train real models on random data in your browser, so every bias, variance and error you see is measured, not drawn by hand.
Where Prediction Error Comes From
Every price in Vikram's data has two parts: the true pattern (what a home of that size is really worth on average) and noise (location, age, a pushy buyer — things the model cannot see).
f(x) = the true pattern (unknown to us).
ε = noise with average 0 and variance σ².
This is the key idea of the whole topic. Vikram's 21 homes are only one random sample. If he had collected 21 other homes, his model — and its predictions — would come out a bit different. Bias and variance describe how a model behaves across all the training sets it could have been given.
| Part of the error | Where it comes from | Can we reduce it? | Archery picture |
|---|---|---|---|
| Bias² | The model is too simple for the true pattern (wrong assumptions) | Yes — more flexible model | Priya's group is centred in the wrong place |
| Variance | The model changes a lot when the training sample changes | Yes — simpler model, penalty, more data | Ravi's arrows land in a different place every time |
| Noise σ² | Randomness in the data itself | No — it is the floor | A gust of wind no archer can control |
The Exact Definitions of Bias and Variance
Fix one home size, x₀ (say 2 300 sq ft). Now imagine training the same kind of model on many different training sets D₁, D₂, D₃, … Each model gives its own prediction for x₀. ED[ … ] means "the average over all those training sets".
Variance = (4 + 4 + 0 + 16 + 16) / 5 = 8 (spread ≈ ±2.8)
1. Variance is not the train–test gap. A big gap between training and test error is a symptom
that often comes with high variance, but it is not the definition. Variance is the spread of predictions across training sets.
2. Variance is not the spread of the data. The scatter of prices around the true curve is the noise σ². A model can have
tiny variance on very noisy data (a flat line barely moves).
3. Bias compares with f(x), not with y. The true pattern has no noise; one observed price does.
4. Bias and variance belong to a model type plus a data size (for example "a degree-10 polynomial trained on 20 homes"),
not to one fitted model. One fitted model has an error; only many training sets have a bias and a variance.
The Archery Picture — Four Targets
Think of each arrow as one model trained on one training set, and the bullseye as the true value f(x₀). Bias is the distance from the bullseye to the centre of the group. Variance is how widely the arrows spread around their own centre.
Each dot is one model trained on a different sample of training data. The bullseye is the true target value. Green = ideal, Amber = overfitting, Blue = underfitting, Red = worst possible outcome.
Try It — Archery Lab
Set Priya's aim offset (bias) and Ravi's shaky hands (spread), then shoot. For any group of arrows, the average squared miss is exactly bias² + variance — the same split as above, just without noise.
कहानी: विक्रम के तीन model और कोच अर्जुन के दो तीरंदाज़
वह तीन model आज़माता है: एक सीधी लाइन, एक बहुत टेढ़ी-मेढ़ी curve और एक smooth, हल्की-सी मुड़ने वाली curve। उसका manager एक ही सवाल पूछता है: "मैं किस model पर भरोसा करूँ?"
विक्रम का दोस्त, कोच अर्जुन, तीरंदाज़ों को सिखाता है। वह कहता है: "मेरी भी यही दिक्कत है। प्रिया के तीर पास-पास लगते हैं — पर हमेशा नीचे बाएँ कोने में। रवि के तीर हर तरफ़ बिखरते हैं — कभी बीच के पास, अक्सर नहीं। मुझे ऐसा तीरंदाज़ चाहिए जिसके तीर पास-पास और बीच में लगें।"
प्रिया में bias है। रवि में variance है। विक्रम की सीधी लाइन प्रिया जैसी है, और उसकी टेढ़ी-मेढ़ी curve रवि जैसी। यह tutorial ठीक-ठीक दिखाता है क्यों — ऐसे numbers के साथ जिन्हें आप ख़ुद माप सकते हैं।
ये interactive box ढूँढिए: Archery Lab (सेक्शन 04), Many Training Sets (05), The U-Curve, Computed (06), The Split Lottery (08), Learning Curves (09) और Taming a Wiggly Model (12)। ये आपके browser में random data पर असली model train करते हैं, इसलिए जो भी bias, variance और error आप देखते हैं, वह मापा हुआ है, हाथ से बनाया हुआ नहीं।
Prediction error आता कहाँ से है
विक्रम के data में हर कीमत के दो हिस्से हैं: असली pattern (उस साइज़ का घर औसतन सच में कितने का है) और noise (जगह, घर की उम्र, ज़िद्दी ख़रीदार — वे चीज़ें जो model नहीं देख सकता)।
f(x) = असली pattern (हमें पता नहीं)।
ε = noise, जिसका औसत 0 है और variance σ² है।
यही इस पूरे topic का मुख्य idea है। विक्रम के 21 घर बस एक random sample हैं। अगर वह 21 दूसरे घर जमा करता, तो उसका model — और उसकी predictions — थोड़े अलग आते। Bias और variance बताते हैं कि model उन सभी training sets पर कैसा बर्ताव करता है जो उसे मिल सकते थे।
| Error का हिस्सा | यह कहाँ से आता है | क्या हम इसे घटा सकते हैं? | तीरंदाज़ी वाली तस्वीर |
|---|---|---|---|
| Bias² | Model असली pattern के लिए बहुत simple है (ग़लत मान्यताएँ) | हाँ — ज़्यादा flexible model | प्रिया का group ग़लत जगह पर केंद्रित है |
| Variance | Training sample बदलने पर model बहुत बदल जाता है | हाँ — simpler model, penalty, ज़्यादा data | रवि के तीर हर बार अलग जगह लगते हैं |
| Noise σ² | ख़ुद data में मौजूद randomness | नहीं — यही सबसे निचली सीमा (floor) है | हवा का झोंका, जिसे कोई तीरंदाज़ काबू नहीं कर सकता |
Bias और Variance की सटीक परिभाषाएँ
एक घर का साइज़ तय कर लीजिए, x₀ (मान लीजिए 2 300 sq ft)। अब सोचिए कि एक ही तरह का model कई अलग-अलग training sets D₁, D₂, D₃, … पर train होता है। हर model x₀ के लिए अपनी prediction देता है। ED[ … ] का मतलब है "उन सभी training sets का औसत"।
Variance = (4 + 4 + 0 + 16 + 16) / 5 = 8 (फैलाव ≈ ±2.8)
1. Variance, train–test gap नहीं है। Training और test error के बीच बड़ा gap एक लक्षण है
जो अक्सर high variance के साथ आता है, पर यह परिभाषा नहीं है। Variance है training sets के पार predictions का फैलाव।
2. Variance, data का फैलाव नहीं है। असली curve के आसपास कीमतों का बिखराव noise σ² है। एक model का
बहुत noisy data पर भी variance बहुत छोटा हो सकता है (एक flat लाइन मुश्किल से हिलती है)।
3. Bias की तुलना f(x) से होती है, y से नहीं। असली pattern में noise नहीं होता; एक देखी गई कीमत में होता है।
4. Bias और variance किसी model type और data size के होते हैं (जैसे "20 घरों पर train हुआ degree-10 polynomial"),
किसी एक fitted model के नहीं। एक fitted model का एक error होता है; bias और variance सिर्फ़ कई training sets के होते हैं।
तीरंदाज़ी वाली तस्वीर — चार निशाने
हर तीर को एक training set पर train हुआ एक model समझिए, और निशाने के बीच (bullseye) को असली value f(x₀)। Bias है bullseye से group के केंद्र तक की दूरी। Variance है कि तीर अपने ही केंद्र के आसपास कितने फैले हैं।
हर बिंदु एक model है, जो training data के एक अलग sample पर train हुआ है। Bullseye असली target value है। हरा = आदर्श, पीला (Amber) = overfitting, नीला = underfitting, लाल = सबसे बुरा नतीजा।
ख़ुद आज़माइए — Archery Lab
प्रिया का निशाना कितना हटा है (bias) और रवि के हाथ कितने काँपते हैं (फैलाव), यह set कीजिए, फिर तीर चलाइए। तीरों के किसी भी group के लिए औसत squared चूक ठीक-ठीक bias² + variance होती है — ऊपर वाला ही बँटवारा, बस noise के बिना।
故事:Vikram 的三个 model 和 Arjun 教练的两名弓箭手
他试了三个 model:一条直线,一条弯来弯去的曲线, 还有一条平滑、轻轻弯曲的曲线。他的经理只问了一个问题: "我该相信哪个 model?"
Vikram 的朋友 Arjun 教练训练弓箭手。他说:"我也有同样的问题。 Priya 射得很集中,但总是偏在左下角。 Ravi 的箭到处乱飞,有时靠近中心,但大多数时候不是。 我想要的弓箭手,箭要集中,而且要在中心。"
Priya 有 bias。Ravi 有 variance。 Vikram 的直线就像 Priya,他那条弯来弯去的曲线就像 Ravi。 本教程会告诉你确切的原因,而且用的是你自己能测量的数字。
请留意这些互动框:Archery Lab(第 04 节)、Many Training Sets(05)、 The U-Curve, Computed(06)、The Split Lottery(08)、Learning Curves(09)和 Taming a Wiggly Model(12)。它们在你的浏览器里用随机数据训练真实的 model,所以你看到的每个 bias、variance 和 error 都是测量出来的,不是手画的。
Prediction error 从哪里来
Vikram 数据中的每个价格都有两部分:真实规律(这么大的房子 平均真正值多少钱)和 noise(位置、房龄、一个急躁的买家,这些 model 都看不到)。
f(x) = 真实规律(我们不知道)。
ε = 平均值为 0、variance 为 σ² 的 noise。
这是整个主题的核心思想。Vikram 的 21 套房子只是一个随机样本。 如果他收集的是另外 21 套其他房子,他的 model 和它的 prediction 都会有点不同。 Bias 和 variance 描述的是:在所有可能拿到的 training set 上,一个 model 的表现如何。
| Error 的组成部分 | 来自哪里 | 能减少吗? | 射箭比喻 |
|---|---|---|---|
| Bias² | Model 对真实规律来说太简单了(假设错了) | 能 — 用更灵活的 model | Priya 的箭集中在错误的位置 |
| Variance | Training 样本一变,model 就变化很大 | 能 — 用更简单的 model、加惩罚、加数据 | Ravi 的箭每次都落在不同的地方 |
| Noise σ² | 数据本身的随机性 | 不能 — 它是下限 | 一阵风,没有弓箭手能控制 |
Bias 和 variance 的准确定义
固定一个房子面积 x₀(比如 2 300 平方英尺)。现在想象用同一种 model,在很多不同的 training set D₁、D₂、D₃ …… 上训练。每个 model 都会对 x₀ 给出自己的 prediction。ED[ … ] 的意思是 "在所有这些 training set 上取平均"。
Variance = (4 + 4 + 0 + 16 + 16) / 5 = 8(分散程度 ≈ ±2.8)
1. Variance 不是 train–test 差距。Training error 和 test error 差距大,是一个症状,
常常和高 variance 一起出现,但它不是定义。Variance 是 prediction 在不同 training set 之间的分散程度。
2. Variance 不是数据的分散程度。价格围绕真实曲线的散布是 noise σ²。一个 model 在 noise 很大的数据上
也可以有很小的 variance(一条水平线几乎不动)。
3. Bias 是和 f(x) 比,不是和 y 比。真实规律没有 noise,而一个观察到的价格有。
4. Bias 和 variance 属于一种 model 类型加上一个数据量(例如"在 20 套房子上训练的 degree-10 polynomial"),
而不属于某一个已训练好的 model。一个训练好的 model 只有一个 error;只有很多 training set 才有 bias 和 variance。
射箭图 — 四个靶子
把每支箭想成在一个 training set 上训练出来的一个 model,靶心就是真实值 f(x₀)。 Bias 是靶心到箭群中心的距离。 Variance 是箭围绕它们自己的中心分散得有多开。
每个点是在不同 training data 样本上训练出来的一个 model。靶心是真实的目标值。 绿色 = 理想,琥珀色 = overfitting,蓝色 = underfitting,红色 = 最差的结果。
动手试试 — Archery Lab
设置 Priya 的瞄准偏移(bias)和 Ravi 手抖的程度(分散),然后射箭。对任何一组箭, 平均平方偏差正好等于 bias² + variance。这和上面的分解一样,只是没有 noise。
Watch It Live — One Model Type, Many Training Sets
Now we do the definition for real. The dashed curve is the true pattern f(x) behind Vikram's homes. Each press draws a new random training set of homes (blue dots) and fits the chosen model (green). After many presses, the purple curve is the average model ED[f̂(x)].
The right panel zooms in on one home size (the purple dashed line — drag it on the chart). Every green dot is one model's prediction. The red arrow from the truth to the average is the bias. The shaded band is ± one standard deviation — its square is the variance.
लाइव देखिए — एक model type, कई training sets
अब हम परिभाषा को सच में करके देखते हैं। Dashed curve विक्रम के घरों के पीछे का असली pattern f(x) है। हर बार दबाने पर घरों का एक नया random training set (नीले बिंदु) बनता है और चुना हुआ model (हरा) fit होता है। कई बार दबाने के बाद, बैंगनी curve औसत model ED[f̂(x)] होती है।
दायाँ panel घर के एक साइज़ पर zoom करता है (बैंगनी dashed लाइन — इसे chart पर खींचिए)। हर हरा बिंदु एक model की prediction है। सच से औसत तक का लाल तीर bias है। छायांकित पट्टी ± एक standard deviation है — इसका square variance है।
实时观看 — 一种 model 类型,很多 training set
现在我们真正按定义来做。虚线是 Vikram 房子背后的真实规律 f(x)。 每按一次,就会抽取一个新的随机 training set(蓝色点),并训练所选的 model(绿色)。 按很多次之后,紫色曲线就是平均 model ED[f̂(x)]。
右边的面板放大显示一个房子面积(紫色虚线,可以在图上拖动它)。每个绿色点是一个 model 的 prediction。 从真实值指向平均值的红色箭头就是 bias。阴影带是 ± 一个标准差,它的平方就是 variance。
Add 50 training sets with the straight line: the curves hug each other, but their average never bends — high bias, low variance. Switch to degree 10 (the same training sets are refitted): the average curve now follows the truth, but single curves swing wildly — low bias, high variance. Then raise the number of homes to 100 and watch the degree-10 spread shrink.
The Bias-Variance Tradeoff — The U-Curve, Measured
As the model becomes more flexible, bias² falls (it can follow the true curve) but variance rises (it also follows the noise of each training set). Their sum with the noise floor makes a U-shape. The bottom of the U is the sweet spot.
The chart below is not a sketch. For every degree it trains 300 models on 300 fresh training sets and measures bias², variance and the real error on new homes. Click a degree to see its numbers.
सीधी लाइन के साथ 50 training sets जोड़िए: curves एक-दूसरे से चिपकी रहती हैं, पर उनका औसत कभी नहीं मुड़ता — high bias, low variance। degree 10 पर जाइए (वही training sets फिर से fit होते हैं): अब औसत curve सच के साथ चलती है, पर अकेली curves बुरी तरह झूलती हैं — low bias, high variance। फिर घरों की संख्या 100 कीजिए और degree-10 का फैलाव सिकुड़ते देखिए।
Bias-Variance Tradeoff — U-Curve, मापकर
जैसे-जैसे model ज़्यादा flexible होता है, bias² घटता है (वह असली curve के साथ चल पाता है), पर variance बढ़ता है (वह हर training set के noise के साथ भी चलने लगता है)। Noise floor के साथ इनका जोड़ एक U-आकार बनाता है। U का सबसे निचला हिस्सा सबसे सही जगह (sweet spot) है।
नीचे का chart कोई अंदाज़े से बनाया चित्र नहीं है। हर degree के लिए यह 300 नए training sets पर 300 models train करता है और bias², variance और नए घरों पर असली error मापता है। किसी degree पर click करके उसके numbers देखिए।
用直线加 50 个 training set:曲线彼此紧贴,但它们的平均值永远不会弯曲, 这是高 bias、低 variance。切换到 degree 10(同样的 training set 会重新训练):平均曲线现在跟着真实值走,但单条曲线 摆动得很厉害,这是低 bias、高 variance。然后把房子数量提高到 100,看 degree-10 的分散程度变小。
Bias-variance trade-off — 测量出来的 U 形曲线
当 model 变得更灵活时,bias² 下降(它能跟上真实曲线),但 variance 上升(它也会跟着每个 training set 的 noise 走)。它们的和再加上 noise 下限, 就形成一个 U 形。U 的底部就是最佳点。
下面的图不是草图。对每个 degree,它在 300 个新的 training set 上训练 300 个 model,并测量 bias²、variance 和在新房子上的真实 error。点击一个 degree,就能看到它的数字。
| Few parameters (e.g. a line: 2) | Right number (e.g. degree 2–3) | Many parameters (e.g. degree 10: 11) | |
|---|---|---|---|
| What it can draw | Only straight lines — cannot bend | The real curve, but not every bump | Almost any shape — including the noise |
| Effect of a new training set | Line barely moves | Curve moves a little | Curve changes shape completely |
| Result | High bias · low variance | Low bias · low variance | Low bias · high variance |
Underfitting vs Good Fit vs Overfitting — Side by Side
The first rows below are measured with the simulator (20 homes per training set, noise σ = 10 lakh, so σ² = 100). Notice that training error keeps falling while test error does not.
| Property | Underfitting | Good fit | Overfitting |
|---|---|---|---|
| Vikram's model | Straight line (degree 1) | Gentle curve (degree 2) | Wiggly curve (degree 10) |
| Bias² (measured) | ≈ 111 — high | ≈ 2 | ≈ 0 |
| Variance (measured) | ≈ 10 | ≈ 15 | ≈ 270 — high |
| Expected test error | ≈ 221 | ≈ 118 — lowest | ≈ 370 |
| Average training error | ≈ 200 (high) | ≈ 87 | ≈ 45 (looks great!) |
| Train–test gap | Small — both bad | Small — both good | Large |
| More training data helps? | No — bias stays | A little | Yes — variance falls |
| Decision tree example | max_depth = 1 (stump) | max_depth ≈ 3–6 (tune it) | max_depth = None |
| Neural network example | Too few neurons, heavy penalty | Tuned size + early stopping | Huge network, tiny data, no penalty |
The noise floor is σ² = 100, yet the good model's training error is only ≈ 87 and the wiggly one's ≈ 45. A model always fits the homes it was trained on a little too well: with p parameters and n homes, the training error is roughly σ² × (1 − p/n) — for degree 10: 100 × (1 − 11/20) = 45. That is why training error alone can never tell you a model is good.
Diagnosing From Train and Test Errors
In real life Vikram has only one dataset. He cannot draw 300 fresh training sets, so he cannot measure bias and variance directly. Instead he splits his homes into a training set (blue) and a test set (orange), and reads the errors as clues:
Try It — The Split Lottery
These are Vikram's 21 homes. Each press puts 14 random homes in training and 7 in testing. Press New split a few times for each model, then Run 200 splits to see how much the test error depends on luck.
| कम parameters (जैसे एक लाइन: 2) | सही संख्या (जैसे degree 2–3) | बहुत parameters (जैसे degree 10: 11) | |
|---|---|---|---|
| यह क्या बना सकता है | सिर्फ़ सीधी लाइनें — मुड़ नहीं सकता | असली curve, पर हर उभार नहीं | लगभग कोई भी आकार — noise समेत |
| नए training set का असर | लाइन मुश्किल से हिलती है | Curve थोड़ी हिलती है | Curve का आकार पूरा बदल जाता है |
| नतीजा | High bias · low variance | Low bias · low variance | Low bias · high variance |
Underfitting vs Good Fit vs Overfitting — साथ-साथ
नीचे की पहली rows simulator से मापी गई हैं (हर training set में 20 घर, noise σ = 10 लाख, यानी σ² = 100)। ध्यान दीजिए कि training error घटता रहता है, जबकि test error नहीं घटता।
| गुण | Underfitting | Good fit | Overfitting |
|---|---|---|---|
| विक्रम का model | सीधी लाइन (degree 1) | हल्की curve (degree 2) | टेढ़ी-मेढ़ी curve (degree 10) |
| Bias² (मापा गया) | ≈ 111 — ज़्यादा | ≈ 2 | ≈ 0 |
| Variance (मापा गया) | ≈ 10 | ≈ 15 | ≈ 270 — ज़्यादा |
| Expected test error | ≈ 221 | ≈ 118 — सबसे कम | ≈ 370 |
| औसत training error | ≈ 200 (ज़्यादा) | ≈ 87 | ≈ 45 (बहुत बढ़िया दिखता है!) |
| Train–test gap | छोटा — दोनों ख़राब | छोटा — दोनों अच्छे | बड़ा |
| क्या ज़्यादा training data मदद करता है? | नहीं — bias बना रहता है | थोड़ा-सा | हाँ — variance घटता है |
| Decision tree का उदाहरण | max_depth = 1 (stump) | max_depth ≈ 3–6 (tune कीजिए) | max_depth = None |
| Neural network का उदाहरण | बहुत कम neurons, भारी penalty | Tune किया गया size + early stopping | बहुत बड़ा network, बहुत कम data, कोई penalty नहीं |
Noise floor σ² = 100 है, फिर भी अच्छे model का training error सिर्फ़ ≈ 87 है और टेढ़े-मेढ़े वाले का ≈ 45। Model हमेशा उन घरों पर थोड़ा ज़्यादा ही अच्छा fit होता है जिन पर वह train हुआ: p parameters और n घरों के साथ, training error लगभग σ² × (1 − p/n) होता है — degree 10 के लिए: 100 × (1 − 11/20) = 45। इसीलिए सिर्फ़ training error कभी नहीं बता सकता कि model अच्छा है।
Train और Test errors से बीमारी पहचानना
असल ज़िंदगी में विक्रम के पास सिर्फ़ एक dataset है। वह 300 नए training sets नहीं बना सकता, इसलिए bias और variance सीधे नहीं माप सकता। इसके बजाय वह अपने घरों को एक training set (नीला) और एक test set (नारंगी) में बाँटता है, और errors को सुराग की तरह पढ़ता है:
ख़ुद आज़माइए — The Split Lottery
ये विक्रम के 21 घर हैं। हर बार दबाने पर 14 random घर training में और 7 testing में जाते हैं। हर model के लिए नया split कुछ बार दबाइए, फिर 200 splits चलाओ दबाकर देखिए कि test error क़िस्मत पर कितना निर्भर है।
| 参数少(例如一条直线:2 个) | 参数数量合适(例如 degree 2–3) | 参数多(例如 degree 10:11 个) | |
|---|---|---|---|
| 它能画出什么 | 只能画直线,不能弯曲 | 能画出真实曲线,但不是每个小起伏 | 几乎任何形状,包括 noise |
| 换一个新 training set 的影响 | 直线几乎不动 | 曲线动一点点 | 曲线形状完全改变 |
| 结果 | 高 bias · 低 variance | 低 bias · 低 variance | 低 bias · 高 variance |
Underfitting vs good fit vs overfitting — 并排比较
下面前几行是用模拟器测量的(每个 training set 20 套房子,noise σ = 10 lakh,所以 σ² = 100)。 注意:training error 一直在下降,而 test error 却没有。
| 性质 | Underfitting | Good fit | Overfitting |
|---|---|---|---|
| Vikram 的 model | 直线(degree 1) | 平缓曲线(degree 2) | 弯来弯去的曲线(degree 10) |
| Bias²(测量值) | ≈ 111 — 高 | ≈ 2 | ≈ 0 |
| Variance(测量值) | ≈ 10 | ≈ 15 | ≈ 270 — 高 |
| Expected test error | ≈ 221 | ≈ 118 — 最低 | ≈ 370 |
| 平均 training error | ≈ 200(高) | ≈ 87 | ≈ 45(看起来很棒!) |
| Train–test 差距 | 小 — 两个都差 | 小 — 两个都好 | 大 |
| 更多 training data 有用吗? | 没用 — bias 还在 | 有一点 | 有用 — variance 下降 |
| Decision tree 例子 | max_depth = 1(树桩) | max_depth ≈ 3–6(需要调) | max_depth = None |
| 神经网络例子 | 神经元太少,惩罚太重 | 调好的大小 + early stopping | 巨大的网络,很少的数据,没有惩罚 |
Noise 下限是 σ² = 100,但好 model 的 training error 只有 ≈ 87,弯来弯去的那个只有 ≈ 45。 Model 对它训练用的房子总是拟合得有点太好:有 p 个参数和 n 套房子时,training error 大约是 σ² × (1 − p/n)。对 degree 10:100 × (1 − 11/20) = 45。所以只看 training error,永远无法判断一个 model 好不好。
从 training error 和 test error 来诊断
在现实中,Vikram 只有一个 dataset。他不能抽取 300 个新的 training set,所以他不能直接测量 bias 和 variance。 他的做法是把房子分成 training set(蓝色)和 test set(橙色), 然后把 error 当作线索来看:
动手试试 — The Split Lottery
这是 Vikram 的 21 套房子。每按一次,就随机放 14 套房子进 training,7 套进 test。对每个 model 按几次新划分, 然后按运行 200 次划分,看看 test error 有多依赖运气。
Learning Curves — What More Data Can and Cannot Fix
A learning curve plots training error and test (validation) error against the number of training examples. Its shape tells you which problem you have — and whether collecting more data is worth it.
Learning Curves — ज़्यादा data क्या ठीक कर सकता है और क्या नहीं
learning curve training examples की संख्या के मुक़ाबले training error और test (validation) error को plot करती है। इसका आकार बताता है कि आपकी समस्या कौन-सी है — और क्या ज़्यादा data जमा करना फ़ायदेमंद है।
Learning curve — 更多数据能解决什么,不能解决什么
Learning curve 画出 training error 和 test(validation)error 随 training 样本数量的变化。 它的形状告诉你遇到的是哪种问题,以及收集更多数据值不值得。
| Shape of the curves | Diagnosis | Will more data help? |
|---|---|---|
| Both curves meet quickly, far above the noise floor | High bias (underfitting) | No |
| Wide gap; test error falls slowly as data grows | High variance (overfitting) | Yes |
| Curves meet close to the noise floor | Good fit | Only a little |
Fixes for Underfitting (High Bias)
You have an underfitting problem if: training error is high, validation error is also high, and the gap between them is small. Collecting more data will not help. You need to give the model more capacity to learn.
Fixes for Overfitting (High Variance)
You have an overfitting problem if: training error is very low, validation error is significantly higher, and the gap is large. The model has memorised training data. Fixes focus on constraining the model or exposing it to more diverse data.
λ controls the strength.
max_depth), reduce neurons / layers, or use fewer
features. Directly reduces the model's capacity to memorise noise.
Regularisation, More Data and Bagging — Three Ways to Tame Variance
alpha in Ridge / Lasso; C, which works like 1/λ, in LogisticRegression and SVM) via
cross-validation. Try values on a logarithmic scale:
[0.0001, 0.001, 0.01, 0.1, 1, 10, 100].Use
RidgeCV, LassoCV, or
GridSearchCV to find the optimal value.
Try It — Taming a Wiggly Model
Start with a high-variance model trained on 20 homes: a degree-10 polynomial for the first two tabs, and a fully grown decision tree for bagging. Each tab tries one cure. The left chart shows 30 fitted models and their average; the right chart shows how bias² and variance move along the slider.
| Curves का आकार | पहचान | क्या ज़्यादा data मदद करेगा? |
|---|---|---|
| दोनों curves जल्दी मिल जाती हैं, noise floor से काफ़ी ऊपर | High bias (underfitting) | नहीं |
| चौड़ा gap; data बढ़ने पर test error धीरे-धीरे घटता है | High variance (overfitting) | हाँ |
| Curves noise floor के पास मिलती हैं | Good fit | बस थोड़ा-सा |
Underfitting (High Bias) के इलाज
आपको underfitting की समस्या है अगर: training error ज़्यादा है, validation error भी ज़्यादा है, और दोनों के बीच gap छोटा है। ज़्यादा data जमा करने से मदद नहीं मिलेगी। आपको model को सीखने की ज़्यादा क्षमता देनी होगी।
Overfitting (High Variance) के इलाज
आपको overfitting की समस्या है अगर: training error बहुत कम है, validation error काफ़ी ज़्यादा है, और gap बड़ा है। Model ने training data रट लिया है। इलाज का ध्यान model पर पाबंदी लगाने या उसे ज़्यादा विविध data दिखाने पर होता है।
λ controls the strength।
max_depth), neurons / layers घटाइए, या कम
features इस्तेमाल कीजिए। इससे model की noise रटने की क्षमता सीधे घटती है।
Regularisation, ज़्यादा Data और Bagging — Variance को काबू करने के तीन तरीक़े
alpha; LogisticRegression और SVM में C, जो 1/λ की तरह काम करता है)।
Values logarithmic scale पर आज़माइए:
[0.0001, 0.001, 0.01, 0.1, 1, 10, 100]।सबसे अच्छी value ढूँढने के लिए
RidgeCV, LassoCV, या
GridSearchCV इस्तेमाल कीजिए।
ख़ुद आज़माइए — Taming a Wiggly Model
20 घरों पर train हुए एक high-variance model से शुरू कीजिए: पहले दो tabs के लिए degree-10 polynomial, और bagging के लिए पूरा बढ़ा हुआ decision tree। हर tab एक इलाज आज़माता है। बायाँ chart 30 fitted models और उनका औसत दिखाता है; दायाँ chart दिखाता है कि slider के साथ bias² और variance कैसे बदलते हैं।
| 曲线的形状 | 诊断 | 更多数据有用吗? |
|---|---|---|
| 两条曲线很快相遇,但远高于 noise 下限 | 高 bias(underfitting) | 没用 |
| 差距很大;数据增加时 test error 慢慢下降 | 高 variance(overfitting) | 有用 |
| 曲线在接近 noise 下限的地方相遇 | Good fit | 只有一点点 |
解决 underfitting(高 bias)的方法
如果出现以下情况,你就遇到了 underfitting:training error 高,validation error 也高,而且两者差距小。收集更多数据没有用。 你需要给 model 更强的学习能力。
解决 overfitting(高 variance)的方法
如果出现以下情况,你就遇到了 overfitting:training error 很低,validation error 明显更高,而且差距很大。Model 把 training data 背下来了。解决方法的重点是限制 model,或者让它见到更多样的数据。
λ controls the strength。
max_depth),减少神经元 / 层数,或者使用更少的
feature。这会直接降低 model 记住 noise 的能力。
Regularisation、更多数据和 bagging — 驯服 variance 的三种方法
alpha;LogisticRegression 和 SVM 中是 C,它的作用类似 1/λ)。
在对数刻度上尝试这些值:
[0.0001, 0.001, 0.01, 0.1, 1, 10, 100]。使用
RidgeCV、LassoCV 或
GridSearchCV 来找到最佳值。
动手试试 — Taming a Wiggly Model
先从一个在 20 套房子上训练的高 variance model 开始:前两个标签页用 degree-10 polynomial,bagging 用一棵完全长开的 decision tree。每个标签页试一种解药。左边的图显示 30 个训练好的 model 和它们的平均值;右边的图 显示 bias² 和 variance 随滑块如何变化。
Python — Measuring Bias and Variance by Simulation
This code does exactly what the simulators do: it invents a true pattern, draws 2 000 training sets, trains the same model type on each, and applies the definitions. It also measures the real error on fresh homes, so you can check that bias² + variance + noise adds up.
Python — Simulation से Bias और Variance मापना
यह code ठीक वही करता है जो simulators करते हैं: यह एक असली pattern बनाता है, 2 000 training sets बनाता है, हर एक पर एक ही model type train करता है, और परिभाषाएँ लागू करता है। यह नए घरों पर असली error भी मापता है, ताकि आप जाँच सकें कि bias² + variance + noise का जोड़ सही बैठता है।
Python — 用模拟来测量 bias 和 variance
这段代码做的事情和模拟器完全一样:它先编一个真实规律,抽取 2 000 个 training set,在每个上面训练 同一种 model,然后套用定义。它还会测量在新房子上的真实 error,这样你就能 检查 bias² + variance + noise 加起来是否吻合。
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, PolynomialFeatures
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(0)
NOISE = 10 # noise sd (₹ lakh) → σ² = 100
def true_price(sqft): # the real pattern f(x)
u = (sqft - 1600) / 1000
return 100 + 55*u + 35*u**2 + 10*u**3
def new_training_set(n=20): # one random sample of n homes
sqft = 600 + 2000 * (np.arange(n) + rng.random(n)) / n # spread over 600–2600 sq ft
price = true_price(sqft) + rng.normal(0, NOISE, n)
return sqft.reshape(-1, 1), price
def make_model(degree): # scale size to [-1, 1], then polynomial
return make_pipeline(FunctionTransformer(lambda s: (s - 1600) / 1000),
PolynomialFeatures(degree), LinearRegression())
x0 = (600 + 2000 * (np.arange(60) + 0.5) / 60).reshape(-1, 1) # homes to price
f0 = true_price(x0.ravel())
K = 2000 # number of training sets
print(f"{'Model':<14}{'Bias²':>8}{'Variance':>10}{'Noise':>7}{'Sum':>8}{'Measured':>10}{'Train':>8}")
print("-" * 65)
for degree in [1, 2, 10]:
preds = np.empty((K, len(x0)))
train = test = 0.0
for k in range(K):
X, y = new_training_set()
model = make_model(degree).fit(X, y)
preds[k] = model.predict(x0)
train += np.mean((y - model.predict(X)) ** 2)
y_new = f0 + rng.normal(0, NOISE, len(f0)) # fresh homes
test += np.mean((y_new - preds[k]) ** 2)
avg = preds.mean(axis=0) # E_D[ f̂(x) ]
bias2 = np.mean((avg - f0) ** 2) # (E_D[f̂(x)] − f(x))²
variance = np.mean(preds.var(axis=0)) # E_D[(f̂(x) − E_D[f̂(x)])²]
print(f"{'degree ' + str(degree):<14}{bias2:>8.1f}{variance:>10.1f}{NOISE**2:>7}"
f"{bias2 + variance + NOISE**2:>8.1f}{test / K:>10.1f}{train / K:>8.1f}")
Degree 1: bias² ≈ 111 dominates → underfitting. Degree 10: variance ≈ 262 dominates → overfitting, even though its training error (45) is the best of the three. Degree 2: both small → the one to deploy. In every row, Sum ≈ Measured: the decomposition holds. You can only run this kind of check when you know the true pattern — with real data, use the clues from Sections 08 and 09.
Python — Learning Curves, Validation Curves and Cross-Validation
With real data you cannot draw new training sets, so you use learning curves and cross-validation instead.
Learning curves for three model complexities
Degree 1: bias² ≈ 111 हावी है → underfitting। Degree 10: variance ≈ 262 हावी है → overfitting, भले ही इसका training error (45) तीनों में सबसे अच्छा है। Degree 2: दोनों छोटे → इसी को deploy करना है। हर row में Sum ≈ Measured: decomposition सही बैठता है। ऐसी जाँच आप तभी कर सकते हैं जब आपको असली pattern पता हो — असली data के साथ, सेक्शन 08 और 09 के सुराग इस्तेमाल कीजिए।
Python — Learning Curves, Validation Curves और Cross-Validation
असली data के साथ आप नए training sets नहीं बना सकते, इसलिए उनकी जगह learning curves और cross-validation इस्तेमाल करते हैं।
तीन model complexities के लिए learning curves
Degree 1:bias² ≈ 111 占主导 → underfitting。Degree 10:variance ≈ 262 占主导 → overfitting, 虽然它的 training error(45)是三个里最好的。Degree 2:两者都小 → 就部署这个。 每一行里,Sum ≈ Measured:分解成立。只有当你知道真实规律时,才能做这种检查。 对于真实数据,请使用第 08 节和第 09 节里的线索。
Python — learning curve、validation curve 和 cross-validation
对于真实数据,你不能抽取新的 training set,所以要改用 learning curve 和 cross-validation。
三种 model complexity 的 learning curve
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import Ridge
from sklearn.model_selection import learning_curve, validation_curve
from sklearn.datasets import make_regression
# ── Generate data with a cubic relationship + noise ──────────
np.random.seed(42)
X_raw = np.random.uniform(-3, 3, (200, 1))
y = 0.5*X_raw[:,0]**3 - X_raw[:,0]**2 + np.random.randn(200)*1.5
# ── Helper: plot learning curve ───────────────────────────────
def plot_learning_curve(model, X, y, title, ax, cv=5):
sizes, train_s, val_s = learning_curve(
model, X, y,
train_sizes=np.linspace(0.1, 1.0, 10),
cv=cv, scoring='neg_mean_squared_error'
)
train_err = -train_s.mean(axis=1)
val_err = -val_s.mean(axis=1)
ax.plot(sizes, train_err, 'o-', label='Train MSE', color='#f59e0b')
ax.plot(sizes, val_err, 's--', label='Validation MSE', color='#6366f1')
ax.set_title(title, fontsize=12)
ax.set_xlabel('Training set size')
ax.set_ylabel('MSE')
ax.legend()
ax.grid(True, alpha=0.3)
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
# ── Three model complexities ──────────────────────────────────
models = [
('Underfit — Degree 1',
Pipeline([('poly', PolynomialFeatures(1)),
('ridge', Ridge(alpha=1.0))])),
('Normal Fit — Degree 3',
Pipeline([('poly', PolynomialFeatures(3)),
('ridge', Ridge(alpha=1.0))])),
('Overfit — Degree 15',
Pipeline([('poly', PolynomialFeatures(15)),
('ridge', Ridge(alpha=0.0001))])),
]
for ax, (title, model) in zip(axes, models):
plot_learning_curve(model, X_raw, y, title, ax)
plt.tight_layout()
plt.savefig('learning_curves.png', dpi=150)
plt.show()
Validation curve, Ridge tuning and cross-validation
Validation curve, Ridge tuning और cross-validation
Validation curve、Ridge 调参和 cross-validation
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge, Lasso, RidgeCV
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import (
validation_curve, cross_val_score,
train_test_split, KFold
)
from sklearn.preprocessing import StandardScaler
X, y = load_diabetes(return_X_y=True)
scaler = StandardScaler()
X_sc = scaler.fit_transform(X)
# ── 1. Validation curve: Decision Tree max_depth ─────────────
depths = np.arange(1, 16)
train_s, val_s = validation_curve(
DecisionTreeRegressor(random_state=42), X_sc, y,
param_name='max_depth', param_range=depths,
scoring='neg_mean_squared_error', cv=5
)
plt.figure(figsize=(8, 4))
plt.plot(depths, -train_s.mean(1), 'o-', label='Train MSE', color='#f59e0b')
plt.plot(depths, -val_s.mean(1), 's--', label='Validation MSE', color='#6366f1')
plt.axvline(x=depths[np.argmin(-val_s.mean(1))], # depth with the lowest validation MSE
color='#34d399', linestyle='--', label='Optimal depth')
plt.xlabel('max_depth')
plt.ylabel('MSE')
plt.title('Validation Curve — Bias-Variance vs Tree Depth')
plt.legend()
plt.show()
# ── 2. Ridge alpha tuning via RidgeCV ────────────────────────
alphas = np.logspace(-4, 4, 50)
ridge_cv = RidgeCV(alphas=alphas, cv=5)
ridge_cv.fit(X_sc, y)
print(f"Best Ridge alpha (λ): {ridge_cv.alpha_:.4f}")
# ── 3. Cross-validation score comparison ─────────────────────
kf = KFold(n_splits=5, shuffle=True, random_state=42)
models_cv = {
'Ridge (best λ)' : Ridge(alpha=ridge_cv.alpha_),
'Decision Tree d=1 (underfit)': DecisionTreeRegressor(max_depth=1, random_state=42),
'Decision Tree d=3 (good)' : DecisionTreeRegressor(max_depth=3, random_state=42),
'Decision Tree d=None (overfit)': DecisionTreeRegressor(random_state=42),
}
print(f"\n{'Model':<35} {'CV MSE':>10} {'Std':>8}")
print("-"*58)
for name, model in models_cv.items():
scores = cross_val_score(
model, X_sc, y,
cv=kf, scoring='neg_mean_squared_error'
)
print(f"{name:<35} {-scores.mean():>10.1f} {scores.std():>8.1f}")
The depth-1 tree underfits: high CV MSE (4 714) but a small spread across folds (120) — consistently wrong, a bias clue. The unlimited tree overfits: the highest CV MSE (6 631) and by far the largest spread (868) — its score depends on which rows land in each fold, a variance clue. The depth-3 tree sits near the sweet spot (the validation curve bottoms out at depth 2–3), and the tuned Ridge model is best of all here. Note that the fold spread also includes how hard each fold happens to be, so compare spreads between models, not in isolation.
Golden Rules
GridSearchCV, RidgeCV or LassoCV. Report the average and the spread of the fold scores.
Depth-1 tree underfit करता है: CV MSE ज़्यादा (4 714) पर folds के बीच फैलाव छोटा (120) — लगातार ग़लत, यह bias का सुराग है। बिना सीमा वाला tree overfit करता है: सबसे ज़्यादा CV MSE (6 631) और सबसे बड़ा फैलाव (868) — इसका score इस पर निर्भर है कि हर fold में कौन-सी rows आती हैं, यह variance का सुराग है। Depth-3 tree sweet spot के पास है (validation curve depth 2–3 पर सबसे नीचे आती है), और tune किया हुआ Ridge model यहाँ सबसे अच्छा है। ध्यान दीजिए कि fold के फैलाव में यह भी शामिल है कि हर fold संयोग से कितना कठिन है, इसलिए फैलाव की तुलना models के बीच कीजिए, अकेले मत देखिए।
सुनहरे नियम
GridSearchCV, RidgeCV या LassoCV से खोजिए। Fold scores का औसत और फैलाव दोनों बताइए।
深度为 1 的树 underfitting:CV MSE 高(4 714),但各 fold 之间的分散小(120)。一直错得差不多,这是 bias 线索。 不限深度的树 overfitting:CV MSE 最高(6 631),分散也远远最大(868)。它的分数取决于哪些行落进了哪个 fold,这是 variance 线索。 深度为 3 的树接近最佳点(validation curve 在深度 2–3 处到达最低),而调好的 Ridge model 在这里是最好的。 注意:fold 之间的分散也包含了每个 fold 本身的难度,所以要在不同 model 之间比较分散,不要单独看。
黄金法则
GridSearchCV、RidgeCV 或 LassoCV 搜索 polynomial degree、树的深度或 λ。报告 fold 分数的平均值和分散程度。