The Story: Priya Wants to Price Her Flat
Priya knows she can't just take the average price — that ignores the fact that bigger flats cost more. She needs a formula that takes size as input and spits out a predicted price. That formula is a Linear Regression model.
Linear Regression is the most fundamental supervised machine-learning algorithm. It finds the straight line that best describes the relationship between one or more input variables (features) and a continuous output variable (target). Once the line is found, predicting new values is as simple as plugging a number into a formula.
Look for the interactive boxes: Beat the Computer (Section 02), the Loss Valley (04), the OLS Table Builder (05), the Error Metrics Lab (06), the R² Visualizer (07), the Noise Feature Experiment (08) and the Assumption Checker (11). Drag points, move lines, add features — every number is computed live with the same formulas as the tutorial.
Visualising the Idea
Priya plots her data on a graph. Each dot is a flat — x-axis = size, y-axis = price. The dots form a rough upward trend. Linear Regression draws the best-fit line through those dots.
The regression line minimises the total squared distance between itself and every data point.
Try It — Beat the Computer
Drag the two purple handles to place your line through the flats. Your score compares your total squared error with the best possible line. Tick show squares to see the squared residuals as real squares — the best line is the one with the smallest total red area. You can also drag points, click empty space to add a flat, and double-click a point to remove it.
कहानी: प्रिया अपने फ्लैट की कीमत तय करना चाहती है
प्रिया जानती है कि वह बस औसत कीमत नहीं ले सकती। ऐसा करने से यह बात छूट जाती है कि बड़े फ्लैट ज़्यादा महंगे होते हैं। उसे एक ऐसा formula चाहिए जो साइज़ को input ले और predicted कीमत दे दे। यही formula एक Linear Regression model है।
Linear Regression सबसे बुनियादी Supervised Machine Learning algorithm है। यह वह सीधी लाइन ढूंढता है जो एक या ज़्यादा input variables (features) और एक continuous output variable (target) के बीच के रिश्ते को सबसे अच्छे से दिखाती है। एक बार लाइन मिल गई, तो नई values का prediction करना बहुत आसान है। बस formula में एक नंबर डालो और जवाब मिल जाता है।
इन interactive boxes को देखिए: Beat the Computer (सेक्शन 02), Loss Valley (04), OLS Table Builder (05), Error Metrics Lab (06), R² Visualizer (07), Noise Feature Experiment (08) और Assumption Checker (11)। Points को drag करें, लाइन को हिलाएं, features जोड़ें। हर नंबर उन्हीं formulas से live calculate होता है जो इस tutorial में हैं।
Idea को तस्वीर में देखें
प्रिया अपना data एक graph पर बनाती है। हर बिंदु एक फ्लैट है — x-axis = साइज़, y-axis = कीमत। बिंदु मोटे तौर पर ऊपर की ओर जाते दिखते हैं। Linear Regression इन बिंदुओं के बीच से best-fit line खींचता है।
Regression line अपने और हर data point के बीच की कुल squared दूरी को सबसे कम कर देती है।
खुद करके देखें — Beat the Computer
दो बैंगनी handles को drag करके फ्लैटों के बीच से अपनी लाइन बनाइए। आपका score आपके कुल squared error की तुलना सबसे अच्छी लाइन से करता है। squares दिखाएँ पर टिक करें तो squared residuals असली वर्गों (squares) की तरह दिखेंगे। सबसे अच्छी लाइन वही है जिसका कुल लाल क्षेत्र सबसे छोटा हो। आप points को drag भी कर सकते हैं, खाली जगह पर click करके नया फ्लैट जोड़ सकते हैं, और किसी point पर double-click करके उसे हटा सकते हैं।
故事:Priya 想给她的公寓定价
Priya 知道,她不能只用平均价格——那样就忽略了一个事实:大一点的 公寓更贵。她需要一个公式:输入面积,输出一个 预测价格。这个公式就是一个 Linear Regression model。
Linear Regression 是最基础的 Supervised Learning 算法。 它会找到一条直线,最好地描述 一个或多个输入变量(feature)和一个连续输出变量 (target)之间的关系。找到这条线以后,预测新的值就很简单: 把一个数字代入公式就行。
请留意这些互动框:Beat the Computer(第 02 节)、Loss Valley(04)、 OLS Table Builder(05)、Error Metrics Lab(06)、R² Visualizer(07)、 Noise Feature Experiment(08)和 Assumption Checker(11)。 你可以拖动点、移动直线、添加 feature——每个数字都是实时算出来的,用的公式和教程里完全一样。
把想法画出来
Priya 把她的 data 画在图上。每个点是一套公寓——x 轴 = 面积,y 轴 = 价格。 这些点大致呈上升趋势。Linear Regression 会穿过这些点,画出一条 best-fit line。
Regression line 让它和每个数据点之间的平方距离总和最小。
动手试试——Beat the Computer
拖动两个紫色手柄,在这些公寓之间放一条你自己的直线。你的得分会比较你的总 平方 error 和最好的那条线。勾选 显示正方形,就能把平方 residual 画成真正的正方形—— 最好的线就是红色总面积最小的那条。你也可以拖动点,点击空白处 添加一套公寓,双击一个点就能删除它。
The Equation of a Straight Line
In school you learned y = mx + c. Linear Regression uses the same idea,
just with machine-learning notation:
After fitting her model, Priya finds β₀ = −5 (intercept) and
β₁ = 0.115 (slope). For a 1 200 sq ft flat:
ŷ = −5 + 0.115 × 1200 = −5 + 138 = 133 lakhs.
The model says: list it at ₹1.33 crore.
The Math: How the Best Line is Found (OLS)
"Best fit" is not guesswork. The algorithm minimises the Sum of Squared Residuals (SSR) — also called the Residual Sum of Squares (RSS) or Sum of Squared Errors (SSE). A residual is the gap between a real data point and the line's prediction.
OLS finds β₀ and β₁ that make the sum of all (red dashed lines)² as small as possible.
The Cost Function
We want to minimise the Loss function L:
Differential Equations — Finding the Minimum
To minimise L, take the partial derivative with respect to each parameter and set it to zero. This is where calculus meets machine learning.
∂L/∂β₀ = −2 · Σ(yᵢ − β₀ − β₁xᵢ) = 0Simplifying:
Σyᵢ = n·β₀ + β₁·ΣxᵢDivide by n:
ȳ = β₀ + β₁·x̄ → β₀ = ȳ − β₁·x̄
∂L/∂β₁ = −2 · Σxᵢ(yᵢ − β₀ − β₁xᵢ) = 0Simplifying:
Σ(xᵢyᵢ) = β₀·Σxᵢ + β₁·Σxᵢ²
β₁ = Σ(xᵢ − x̄)(yᵢ − ȳ) / Σ(xᵢ − x̄)²This is the OLS closed-form solution. No iteration needed.
β₁ = Cov(x, y) / Var(x)
β₀ = ȳ − β₁ · x̄
These two formulas give you the exact best-fit line — guaranteed to minimise the sum of squared residuals.
Try It — The Loss Valley
Here is the calculus as a picture. On the right, the loss L is drawn for every slope β₁ (β₀ follows from Step 1: β₀ = ȳ − β₁x̄). It is a valley. The red line is the tangent — its steepness is ∂L/∂β₁. Setting the derivative to zero means finding the spot where the tangent is flat. Gradient descent finds the same spot by walking downhill; try the different step sizes.
सीधी लाइन का Equation
स्कूल में आपने y = mx + c पढ़ा था। Linear Regression भी यही idea इस्तेमाल करता है,
बस Machine Learning वाले notation के साथ:
Model को fit करने के बाद प्रिया को मिलता है β₀ = −5 (intercept) और
β₁ = 0.115 (slope)। 1 200 sq ft के फ्लैट के लिए:
ŷ = −5 + 0.115 × 1200 = −5 + 138 = 133 lakhs।
Model कहता है: इसे ₹1.33 करोड़ में लिस्ट करो।
Math: सबसे अच्छी लाइन कैसे मिलती है (OLS)
"Best fit" कोई अंदाज़ा नहीं है। Algorithm Sum of Squared Residuals (SSR) को सबसे कम करता है। इसे Residual Sum of Squares (RSS) या Sum of Squared Errors (SSE) भी कहते हैं। Residual का मतलब है असली data point और लाइन के prediction के बीच का फ़ासला।
OLS ऐसे β₀ और β₁ ढूंढता है जिनसे सभी (लाल dashed लाइनों)² का जोड़ सबसे छोटा हो जाए।
Cost Function
हम Loss function L को सबसे कम करना चाहते हैं:
Differential Equations — Minimum ढूंढना
L को सबसे कम करने के लिए, हर parameter के हिसाब से partial derivative लें और उसे zero के बराबर रखें। यहीं पर calculus और Machine Learning मिलते हैं।
∂L/∂β₀ = −2 · Σ(yᵢ − β₀ − β₁xᵢ) = 0आसान करने पर:
Σyᵢ = n·β₀ + β₁·Σxᵢn से भाग दें:
ȳ = β₀ + β₁·x̄ → β₀ = ȳ − β₁·x̄
∂L/∂β₁ = −2 · Σxᵢ(yᵢ − β₀ − β₁xᵢ) = 0आसान करने पर:
Σ(xᵢyᵢ) = β₀·Σxᵢ + β₁·Σxᵢ²
β₁ = Σ(xᵢ − x̄)(yᵢ − ȳ) / Σ(xᵢ − x̄)²यही OLS closed-form solution है। बार-बार दोहराने (iteration) की ज़रूरत नहीं।
β₁ = Cov(x, y) / Var(x)
β₀ = ȳ − β₁ · x̄
ये दो formulas आपको बिल्कुल सही best-fit line देते हैं। यह लाइन sum of squared residuals को पक्का सबसे कम करती है।
खुद करके देखें — Loss Valley
यहाँ calculus को एक तस्वीर की तरह देखिए। दाईं ओर, हर slope β₁ के लिए loss L बनाया गया है (β₀ Step 1 से आता है: β₀ = ȳ − β₁x̄)। यह एक घाटी (valley) जैसा है। लाल लाइन tangent है — इसकी ढलान ∂L/∂β₁ है। Derivative को zero रखने का मतलब है वह जगह ढूंढना जहाँ tangent सपाट हो। Gradient descent भी यही जगह ढूंढता है, बस ढलान पर नीचे चलते-चलते। अलग-अलग step sizes आज़माकर देखिए।
直线的方程
在学校里你学过 y = mx + c。Linear Regression 用的是同一个想法,
只是换成了 Machine Learning 的写法:
训练好 model 以后,Priya 得到 β₀ = −5(intercept)和
β₁ = 0.115(slope)。对于一套 1 200 sq ft 的公寓:
ŷ = −5 + 0.115 × 1200 = −5 + 138 = 133 lakhs。
Model 的答案是:标价 ₹1.33 crore(千万卢比)。
数学:怎样找到最好的直线(OLS)
“最佳拟合”不是靠猜。算法会让 Sum of Squared Residuals(SSR,平方 residual 之和)最小——它也叫 Residual Sum of Squares(RSS)或 Sum of Squared Errors(SSE)。 Residual 就是真实数据点和直线 prediction 之间的差距。
OLS 找到的 β₀ 和 β₁,会让所有(红色虚线)² 的总和尽可能小。
Cost Function
我们想让 Loss function L 最小:
微分方程——找到最小值
要让 L 最小,就对每个参数求 partial derivative, 并让它等于零。这就是微积分和 Machine Learning 相遇的地方。
∂L/∂β₀ = −2 · Σ(yᵢ − β₀ − β₁xᵢ) = 0化简:
Σyᵢ = n·β₀ + β₁·Σxᵢ两边除以 n:
ȳ = β₀ + β₁·x̄ → β₀ = ȳ − β₁·x̄
∂L/∂β₁ = −2 · Σxᵢ(yᵢ − β₀ − β₁xᵢ) = 0化简:
Σ(xᵢyᵢ) = β₀·Σxᵢ + β₁·Σxᵢ²
β₁ = Σ(xᵢ − x̄)(yᵢ − ȳ) / Σ(xᵢ − x̄)²这就是 OLS 的闭式解(closed-form solution)。不需要反复迭代。
β₁ = Cov(x, y) / Var(x)
β₀ = ȳ − β₁ · x̄
这两个公式会给你准确的 best-fit line——保证 平方 residual 之和最小。
动手试试——Loss Valley
这里把微积分画成了一张图。右边画出了每个 slope β₁ 对应的 loss L(β₀ 由第 1 步得到: β₀ = ȳ − β₁x̄)。它像一个山谷。红线是切线——它的陡峭程度就是 ∂L/∂β₁。让 derivative 等于零,就是找到切线变平的那个点。Gradient descent 会一步步往下走,找到同一个 点;试试不同的步长吧。
Squaring residuals serves two purposes: it makes all gaps positive (no cancelling), and it penalises large errors more than small ones (because squaring grows faster than linear). The squared form is also mathematically smooth everywhere, making it easy to differentiate and find a unique minimum.
Numerical Example — Priya's 5 Flats
Let's use a small dataset so the math is visible. Priya takes 5 flats:
| i | Size xᵢ (sq ft) | Price yᵢ (₹L) | xᵢ − x̄ | yᵢ − ȳ | (xᵢ−x̄)(yᵢ−ȳ) | (xᵢ−x̄)² |
|---|---|---|---|---|---|---|
| 1 | 600 | 65 | −400 | −39 | 15 600 | 160 000 |
| 2 | 800 | 85 | −200 | −19 | 3 800 | 40 000 |
| 3 | 1 000 | 105 | 0 | 1 | 0 | 0 |
| 4 | 1 200 | 120 | 200 | 16 | 3 200 | 40 000 |
| 5 | 1 400 | 145 | 400 | 41 | 16 400 | 160 000 |
| Σ | 5 000 | 520 | 0 | 0 | 39 000 | 400 000 |
For the new 1 200 sq ft flat: ŷ = 6.5 + 0.0975 × 1200 = 123.5 lakhs
Try It — OLS Table Builder
Rebuild the table above yourself, one column at a time. Edit any number (or try another dataset) and the whole calculation — means, deviations, β₁, β₀ and the prediction — updates. Press Next to follow the steps.
Residuals को square करने के दो फ़ायदे हैं। पहला, सारे फ़ासले positive हो जाते हैं (कोई एक-दूसरे को cancel नहीं करता)। दूसरा, यह बड़ी errors को छोटी errors से ज़्यादा सज़ा देता है (क्योंकि square, linear से तेज़ी से बढ़ता है)। Squared form गणित में हर जगह smooth भी होता है। इसलिए इसका derivative लेना और एक अकेला (unique) minimum ढूंढना आसान है।
Numerical उदाहरण — प्रिया के 5 फ्लैट
चलिए एक छोटा dataset लेते हैं ताकि math साफ़ दिखे। प्रिया 5 फ्लैट लेती है:
| i | साइज़ xᵢ (sq ft) | कीमत yᵢ (₹L) | xᵢ − x̄ | yᵢ − ȳ | (xᵢ−x̄)(yᵢ−ȳ) | (xᵢ−x̄)² |
|---|---|---|---|---|---|---|
| 1 | 600 | 65 | −400 | −39 | 15 600 | 160 000 |
| 2 | 800 | 85 | −200 | −19 | 3 800 | 40 000 |
| 3 | 1 000 | 105 | 0 | 1 | 0 | 0 |
| 4 | 1 200 | 120 | 200 | 16 | 3 200 | 40 000 |
| 5 | 1 400 | 145 | 400 | 41 | 16 400 | 160 000 |
| Σ | 5 000 | 520 | 0 | 0 | 39 000 | 400 000 |
नए 1 200 sq ft फ्लैट के लिए: ŷ = 6.5 + 0.0975 × 1200 = 123.5 लाख
खुद करके देखें — OLS Table Builder
ऊपर वाली table को खुद बनाइए, एक-एक column करके। कोई भी नंबर बदलें (या कोई दूसरा dataset आज़माएं)। पूरा calculation — means, deviations, β₁, β₀ और prediction — अपने आप update हो जाता है। Steps के साथ चलने के लिए आगे दबाएं।
把 residual 平方有两个作用:它让所有差距都变成正数(不会互相抵消), 而且它对大 error 的惩罚比小 error 更重(因为平方增长得 比线性更快)。平方的形式在每一处都很平滑, 所以很容易求导,也能找到唯一的最小值。
数值例子——Priya 的 5 套公寓
我们用一个小 dataset,这样数学过程看得清楚。Priya 选了 5 套公寓:
| i | 面积 xᵢ(sq ft) | 价格 yᵢ(₹L) | xᵢ − x̄ | yᵢ − ȳ | (xᵢ−x̄)(yᵢ−ȳ) | (xᵢ−x̄)² |
|---|---|---|---|---|---|---|
| 1 | 600 | 65 | −400 | −39 | 15 600 | 160 000 |
| 2 | 800 | 85 | −200 | −19 | 3 800 | 40 000 |
| 3 | 1 000 | 105 | 0 | 1 | 0 | 0 |
| 4 | 1 200 | 120 | 200 | 16 | 3 200 | 40 000 |
| 5 | 1 400 | 145 | 400 | 41 | 16 400 | 160 000 |
| Σ | 5 000 | 520 | 0 | 0 | 39 000 | 400 000 |
对于新的 1 200 sq ft 公寓:ŷ = 6.5 + 0.0975 × 1200 = 123.5 lakh
动手试试——OLS Table Builder
自己把上面的表格重新算一遍,一次算一列。修改任意一个数字(或者换一个 dataset),整个 计算过程——mean、偏差、β₁、β₀ 和 prediction——都会更新。按 下一步 一步步跟着做。
RMSE — Root Mean Squared Error
Now that Priya has a model, she needs to know: how wrong is it, on average? The most common metric for this is RMSE.
Step-by-Step RMSE for Priya's 5 Flats
| i | Actual yᵢ | Predicted ŷᵢ | Residual (yᵢ − ŷᵢ) | (yᵢ − ŷᵢ)² |
|---|---|---|---|---|
| 1 | 65 | 6.5+0.0975×600 = 65.0 | 0.0 | 0.00 |
| 2 | 85 | 6.5+0.0975×800 = 84.5 | 0.5 | 0.25 |
| 3 | 105 | 6.5+0.0975×1000 = 104.0 | 1.0 | 1.00 |
| 4 | 120 | 6.5+0.0975×1200 = 123.5 | −3.5 | 12.25 |
| 5 | 145 | 6.5+0.0975×1400 = 143.0 | 2.0 | 4.00 |
| Σ | 17.50 |
Because errors are squared before averaging, a single large prediction error inflates RMSE far more than several small ones. This is both a feature (large errors are costly in practice) and a sensitivity to outliers. If you want a metric that treats all errors equally, use MAE (Mean Absolute Error).
Try It — Error Metrics Lab
Move flat 4's price with the slider and watch the metrics. As long as all errors are small, RMSE and MAE agree. Make flat 4 an outlier and RMSE shoots up — because squaring gives the one big error most of the weight. Tick refit to also see how an outlier drags the line.
RMSE — Root Mean Squared Error
अब प्रिया के पास एक model है। अब उसे यह जानना है: औसतन यह कितना गलत है? इसके लिए सबसे आम metric है RMSE।
प्रिया के 5 फ्लैट के लिए Step-by-Step RMSE
| i | असली yᵢ | Predicted ŷᵢ | Residual (yᵢ − ŷᵢ) | (yᵢ − ŷᵢ)² |
|---|---|---|---|---|
| 1 | 65 | 6.5+0.0975×600 = 65.0 | 0.0 | 0.00 |
| 2 | 85 | 6.5+0.0975×800 = 84.5 | 0.5 | 0.25 |
| 3 | 105 | 6.5+0.0975×1000 = 104.0 | 1.0 | 1.00 |
| 4 | 120 | 6.5+0.0975×1200 = 123.5 | −3.5 | 12.25 |
| 5 | 145 | 6.5+0.0975×1400 = 143.0 | 2.0 | 4.00 |
| Σ | 17.50 |
औसत निकालने से पहले errors को square किया जाता है। इसलिए एक बड़ी prediction error, कई छोटी errors से कहीं ज़्यादा RMSE बढ़ा देती है। यह एक खूबी भी है (असल में बड़ी errors महंगी पड़ती हैं) और outliers के प्रति संवेदनशीलता भी। अगर आपको ऐसा metric चाहिए जो सभी errors को बराबर माने, तो MAE (Mean Absolute Error) इस्तेमाल करें।
खुद करके देखें — Error Metrics Lab
Slider से फ्लैट 4 की कीमत बदलें और metrics को देखें। जब तक सारी errors छोटी हैं, RMSE और MAE लगभग बराबर रहते हैं। फ्लैट 4 को outlier बना दें, तो RMSE तेज़ी से ऊपर चला जाता है — क्योंकि square करने से उस एक बड़ी error को सबसे ज़्यादा वज़न मिलता है। line को फिर से fit करें पर टिक करें तो यह भी दिखेगा कि एक outlier लाइन को कैसे खींच लेता है।
RMSE——Root Mean Squared Error
现在 Priya 有了一个 model,她需要知道:它平均错多少? 最常用的 metric 就是 RMSE。
一步步计算 Priya 5 套公寓的 RMSE
| i | 真实值 yᵢ | 预测值 ŷᵢ | Residual (yᵢ − ŷᵢ) | (yᵢ − ŷᵢ)² |
|---|---|---|---|---|
| 1 | 65 | 6.5+0.0975×600 = 65.0 | 0.0 | 0.00 |
| 2 | 85 | 6.5+0.0975×800 = 84.5 | 0.5 | 0.25 |
| 3 | 105 | 6.5+0.0975×1000 = 104.0 | 1.0 | 1.00 |
| 4 | 120 | 6.5+0.0975×1200 = 123.5 | −3.5 | 12.25 |
| 5 | 145 | 6.5+0.0975×1400 = 143.0 | 2.0 | 4.00 |
| Σ | 17.50 |
因为 error 在求平均之前先被平方了,所以一个大的 prediction error 让 RMSE 变大的程度,远远超过几个小 error。这既是一个优点 (在实际中,大 error 代价很高),也说明它对 outlier 很敏感。如果你想要 一个平等对待所有 error 的 metric,就用 MAE(Mean Absolute Error)。
动手试试——Error Metrics Lab
用滑块调整第 4 套公寓的价格,观察这些 metric。只要所有 error 都很小,RMSE 和 MAE 就差不多。把 第 4 套公寓变成一个 outlier,RMSE 就会猛涨——因为平方让这一个大 error 占了最大的权重。 勾选 重新 fit 直线,还能看到 outlier 怎样把直线拉偏。
R² — The Coefficient of Determination
RMSE tells you the absolute error in real units. But it does not tell you how good your model is compared to having no model at all. R² answers that question.
After fitting her regression line, the variation that is still unexplained (the residuals) is called SSres (Residual Sum of Squares).
R² measures how much of the original variation the model explained away.
R² = 1 − SS_res/SS_tot. The smaller SS_res is relative to SS_tot, the closer R² is to 1.
Calculating R² for Priya's Data
(65−104)²+(85−104)²+(105−104)²+(120−104)²+(145−104)²
= 1521 + 361 + 1 + 256 + 1681 = 3 820
0 + 0.25 + 1 + 12.25 + 4 = 17.50
The model explains 99.54% of the variance in flat prices. Excellent fit on this small dataset.
Try It — R² Visualizer
Each squared error is drawn as a real square. Left: the orange squares of the "dumb baseline" (always predict ȳ) — their total area is SStot. Right: the red squares left after the regression line — SSres. R² is simply how much of the orange area the line removed. Switch to your line and push the slope too far to see R² go negative.
R² — Coefficient of Determination
RMSE असली units में absolute error बताता है। लेकिन यह नहीं बताता कि बिना किसी model के मुकाबले आपका model कितना अच्छा है। R² इस सवाल का जवाब देता है।
Regression line fit करने के बाद, जो variation अब भी समझाया नहीं गया (यानी residuals), उसे SSres (Residual Sum of Squares) कहते हैं।
R² मापता है कि model ने शुरुआती variation का कितना हिस्सा समझा दिया।
R² = 1 − SS_res/SS_tot। SS_tot के मुकाबले SS_res जितना छोटा होगा, R² उतना ही 1 के करीब होगा।
प्रिया के Data के लिए R² निकालना
(65−104)²+(85−104)²+(105−104)²+(120−104)²+(145−104)²
= 1521 + 361 + 1 + 256 + 1681 = 3 820
0 + 0.25 + 1 + 12.25 + 4 = 17.50
Model फ्लैट की कीमतों के variance का 99.54% समझाता है। इस छोटे dataset पर यह बहुत बढ़िया fit है।
खुद करके देखें — R² Visualizer
हर squared error को एक असली वर्ग (square) की तरह बनाया गया है। बाईं ओर: "बेवकूफ़ baseline" (हमेशा ȳ predict करो) के नारंगी वर्ग — इनका कुल क्षेत्र SStot है। दाईं ओर: regression line के बाद बचे लाल वर्ग — SSres। R² बस यह है कि लाइन ने नारंगी क्षेत्र का कितना हिस्सा हटा दिया। आपकी line पर जाएं और slope को बहुत ज़्यादा बढ़ा दें, तो R² negative होता दिखेगा।
R²——Coefficient of Determination
RMSE 用真实单位告诉你绝对 error。但它不能告诉你, 和完全没有 model 相比,你的 model 好多少。 R² 回答的就是这个问题。
画出 regression line 以后,仍然没有被解释的变化量 (也就是 residual)叫作 SSres(Residual Sum of Squares,残差平方和)。
R² 衡量的是:原来的变化量中,有多少被 model 解释掉了。
R² = 1 − SS_res/SS_tot。SS_res 相对 SS_tot 越小,R² 就越接近 1。
计算 Priya 数据的 R²
(65−104)²+(85−104)²+(105−104)²+(120−104)²+(145−104)²
= 1521 + 361 + 1 + 256 + 1681 = 3 820
0 + 0.25 + 1 + 12.25 + 4 = 17.50
Model 解释了公寓价格 variance 的 99.54%。 在这个小 dataset 上,拟合得非常好。
动手试试——R² Visualizer
每个平方 error 都被画成一个真正的正方形。左边:“笨 baseline”(永远预测 ȳ)的橙色正方形—— 它们的总面积就是 SStot。右边:画出 regression line 后剩下的红色正方形——SSres。 R² 就是:这条线去掉了多少橙色面积。切换到 你的直线,把 slope 推得太远,就能看到 R² 变成负数。
| R² Value | Interpretation | Verdict |
|---|---|---|
| 0.90 – 1.00 | Model explains 90–100% of variance | Excellent |
| 0.70 – 0.90 | Model explains 70–90% of variance | Good |
| 0.50 – 0.70 | Moderate explanatory power | Acceptable |
| 0.00 – 0.50 | Weak model; misses major patterns | Poor |
| Negative | Model is worse than a flat mean baseline | Terrible |
Adding more features to a model never decreases R² — even if those features are pure noise. This means you can get a very high R² just by throwing in hundreds of useless columns. A model with 50 random features will have a higher R² than one with 3 meaningful features, even though it is worse. This is why Adjusted R² was invented.
Adjusted R² — The Honest Version
Adjusted R² corrects for the "adding features always helps" bias in R². It penalises you for adding features that do not genuinely improve the model. It only increases if a new feature adds more than it costs.
How the Penalty Works
(n − 1) / (n − p − 1) is the penalty multiplier.
As p (number of features) grows, the denominator shrinks, making the
multiplier larger. This makes (1 − R²) · penalty larger,
which makes R²_adj smaller.
Numerical Example — Adding a Useless Feature
Priya adds a second feature: the flat owner's lucky number (random noise).
| Model | Features (p) | n | R² | R²_adj | Verdict |
|---|---|---|---|---|---|
| Model A | Size only (p=1) | 5 | 0.9954 | 1 − (1−0.9954)·(4/3) = 1 − 0.0046·1.333 = 0.9939 | Good |
| Model B | Size + Lucky Number (p=2) | 5 | 0.9961 (+0.0007) | 1 − (1−0.9961)·(4/2) = 1 − 0.0039·2.0 = 0.9922 | Worse! |
R² went up slightly (0.9954 → 0.9961) when the lucky number was added — a misleading signal. But Adjusted R² fell (0.9939 → 0.9922), correctly signalling that the extra feature hurt the model more than it helped. Always prefer Adjusted R² when comparing models with different numbers of features.
Try It — The Noise Feature Experiment
Priya's data here has a hidden truth: price depends on size and on the floor number. Add random "lucky number" columns and watch R² creep up anyway, while Adjusted R² falls. Then add the real floor feature and watch both rise. Keep adding noise until p gets close to n to see overfitting.
| R² Value | मतलब | फ़ैसला |
|---|---|---|
| 0.90 – 1.00 | Model 90–100% variance समझाता है | बहुत बढ़िया |
| 0.70 – 0.90 | Model 70–90% variance समझाता है | अच्छा |
| 0.50 – 0.70 | ठीक-ठाक समझाने की ताकत | चलेगा |
| 0.00 – 0.50 | कमज़ोर model; बड़े patterns छूट जाते हैं | खराब |
| Negative | Model एक सपाट mean baseline से भी बुरा है | बहुत खराब |
Model में और features जोड़ने से R² कभी कम नहीं होता — चाहे वे features बिल्कुल noise ही क्यों न हों। मतलब, सैकड़ों बेकार columns डालकर आप बहुत ऊँचा R² पा सकते हैं। 50 random features वाले model का R², 3 काम के features वाले model से ज़्यादा होगा, जबकि वह model असल में बुरा है। इसीलिए Adjusted R² बनाया गया।
Adjusted R² — ईमानदार वाला Version
Adjusted R², R² की "features जोड़ने से हमेशा फ़ायदा होता है" वाली गलती को ठीक करता है। अगर आप ऐसे features जोड़ते हैं जो model को सच में बेहतर नहीं बनाते, तो यह आपको सज़ा देता है। यह तभी बढ़ता है जब नया feature अपनी कीमत से ज़्यादा फ़ायदा दे।
Penalty कैसे काम करती है
(n − 1) / (n − p − 1) penalty multiplier है।
जैसे-जैसे p (features की संख्या) बढ़ता है, नीचे वाला हिस्सा (denominator) छोटा होता जाता है, और
multiplier बड़ा हो जाता है। इससे (1 − R²) · penalty बड़ा होता है,
और R²_adj छोटा हो जाता है।
Numerical उदाहरण — एक बेकार Feature जोड़ना
प्रिया एक दूसरा feature जोड़ती है: फ्लैट के मालिक का lucky number (बस random noise)।
| Model | Features (p) | n | R² | R²_adj | फ़ैसला |
|---|---|---|---|---|---|
| Model A | सिर्फ़ साइज़ (p=1) | 5 | 0.9954 | 1 − (1−0.9954)·(4/3) = 1 − 0.0046·1.333 = 0.9939 | अच्छा |
| Model B | साइज़ + Lucky Number (p=2) | 5 | 0.9961 (+0.0007) | 1 − (1−0.9961)·(4/2) = 1 − 0.0039·2.0 = 0.9922 | बदतर! |
Lucky number जोड़ने पर R² थोड़ा बढ़ गया (0.9954 → 0.9961) — यह एक गुमराह करने वाला संकेत है। लेकिन Adjusted R² गिर गया (0.9939 → 0.9922)। इसने सही बताया कि इस extra feature ने model को फ़ायदे से ज़्यादा नुकसान पहुँचाया। जब अलग-अलग संख्या के features वाले models की तुलना करें, तो हमेशा Adjusted R² को चुनें।
खुद करके देखें — Noise Feature Experiment
यहाँ प्रिया के data में एक छुपा सच है: कीमत साइज़ पर और floor नंबर पर निर्भर करती है। Random "lucky number" columns जोड़ें और देखें कि R² फिर भी धीरे-धीरे बढ़ता है, जबकि Adjusted R² गिरता है। फिर असली floor feature जोड़ें और देखें कि दोनों बढ़ते हैं। Noise जोड़ते रहें जब तक p, n के करीब न पहुँच जाए — तब overfitting दिखेगा।
| R² 值 | 含义 | 结论 |
|---|---|---|
| 0.90 – 1.00 | Model 解释了 90–100% 的 variance | 非常好 |
| 0.70 – 0.90 | Model 解释了 70–90% 的 variance | 好 |
| 0.50 – 0.70 | 解释能力中等 | 可以接受 |
| 0.00 – 0.50 | Model 很弱;漏掉了主要规律 | 差 |
| 负数 | Model 比一条平的 mean baseline 还差 | 非常差 |
给 model 增加更多 feature,R² 永远不会下降——就算这些 feature 全是噪声也一样。这意味着,你只要塞进几百个没用的列, 就能得到很高的 R²。一个有 50 个随机 feature 的 model,它的 R² 会比只有 3 个有意义 feature 的 model 更高,尽管它其实更差。 这就是 Adjusted R² 被发明出来的原因。
Adjusted R²——诚实的版本
Adjusted R² 修正了 R² 的一个偏差:“加 feature 总是有帮助”。 如果你加的 feature 并没有真正改进 model,它就会惩罚你。 只有当新 feature 带来的好处大于它的代价时,它才会上升。
惩罚是怎样起作用的
(n − 1) / (n − p − 1) 是惩罚乘数。
当 p(feature 个数)变大时,分母变小,
乘数就变大。这会让 (1 − R²) · penalty 变大,
于是 R²_adj 变小。
数值例子——加一个没用的 feature
Priya 加了第二个 feature:公寓主人的幸运数字(随机噪声)。
| Model | Feature(p) | n | R² | R²_adj | 结论 |
|---|---|---|---|---|---|
| Model A | 只有面积(p=1) | 5 | 0.9954 | 1 − (1−0.9954)·(4/3) = 1 − 0.0046·1.333 = 0.9939 | 好 |
| Model B | 面积 + 幸运数字(p=2) | 5 | 0.9961 (+0.0007) | 1 − (1−0.9961)·(4/2) = 1 − 0.0039·2.0 = 0.9922 | 更差! |
加入幸运数字后,R² 稍微上升了(0.9954 → 0.9961)—— 这是一个误导人的信号。但 Adjusted R² 下降了(0.9939 → 0.9922),它正确地 告诉我们:这个多出来的 feature 对 model 的伤害大于帮助。 比较 feature 个数不同的 model 时,一定要优先看 Adjusted R²。
动手试试——Noise Feature Experiment
这里 Priya 的数据藏着一个真相:价格取决于面积和楼层。 加几列随机的“幸运数字”,你会看到 R² 照样慢慢上涨,而 Adjusted R² 却在下降。然后加入真正的 floor feature,看看两者一起上升。继续加噪声,直到 p 接近 n,就能看到 overfitting。
Metrics at a Glance
- Same unit as target
- Penalises large errors heavily
- Sensitive to outliers
- Lower is better
- Unitless (0 to 1)
- Easy to communicate
- Never decreases with more features
- Higher is better
- Penalises for extra features
- Best for model comparison
- Can decrease with useless features
- Higher is better
Python Implementation
Manual OLS from Scratch
Metrics एक नज़र में
- Unit वही जो target की है
- बड़ी errors को भारी सज़ा देता है
- Outliers से जल्दी प्रभावित होता है
- जितना कम, उतना अच्छा
- कोई unit नहीं (0 से 1)
- दूसरों को समझाना आसान
- ज़्यादा features से कभी कम नहीं होता
- जितना ज़्यादा, उतना अच्छा
- Extra features पर सज़ा देता है
- Models की तुलना के लिए सबसे अच्छा
- बेकार features से कम हो सकता है
- जितना ज़्यादा, उतना अच्छा
Python Implementation
Manual OLS शुरू से
Metric 一览
- 单位和 target 一样
- 重罚大 error
- 对 outlier 敏感
- 越低越好
- 没有单位(0 到 1)
- 容易向别人解释
- 加更多 feature 也不会下降
- 越高越好
- 对多余的 feature 进行惩罚
- 最适合比较 model
- 加了没用的 feature 会下降
- 越高越好
Python 实现
从零手写 OLS
import math
x = [600, 800, 1000, 1200, 1400] # size (sq ft)
y = [65, 85, 105, 120, 145] # price (lakhs)
n = len(x)
x_bar = sum(x) / n # 1000.0
y_bar = sum(y) / n # 104.0
# OLS coefficients
num = sum((xi - x_bar) * (yi - y_bar) for xi, yi in zip(x, y)) # 39000
denom = sum((xi - x_bar) ** 2 for xi in x) # 400000
beta1 = num / denom # slope = 0.0975
beta0 = y_bar - beta1 * x_bar # intercept = 6.5
print(f"Intercept (β₀): {beta0:.4f}") # 6.5
print(f"Slope (β₁): {beta1:.4f}") # 0.0975
# Predictions
y_pred = [beta0 + beta1 * xi for xi in x]
print("Predictions:", [round(p, 2) for p in y_pred])
# [65.0, 84.5, 104.0, 123.5, 143.0]
Computing RMSE, R², Adjusted R²
RMSE, R², Adjusted R² निकालना
计算 RMSE、R²、Adjusted R²
import math
def rmse(y_true, y_pred):
n = len(y_true)
sse = sum((yt - yp) ** 2 for yt, yp in zip(y_true, y_pred))
return math.sqrt(sse / n)
def r_squared(y_true, y_pred):
y_bar = sum(y_true) / len(y_true)
ss_tot = sum((yt - y_bar) ** 2 for yt in y_true)
ss_res = sum((yt - yp) ** 2 for yt, yp in zip(y_true, y_pred))
return 1 - (ss_res / ss_tot)
def adjusted_r2(y_true, y_pred, p):
n = len(y_true)
r2 = r_squared(y_true, y_pred)
return 1 - (1 - r2) * (n - 1) / (n - p - 1)
y_true = [65, 85, 105, 120, 145]
y_pred = [65.0, 84.5, 104.0, 123.5, 143.0]
print(f"RMSE : {rmse(y_true, y_pred):.4f}") # 1.8708
print(f"R² : {r_squared(y_true, y_pred):.4f}") # 0.9954
print(f"Adjusted R² : {adjusted_r2(y_true, y_pred, p=1):.4f}") # 0.9939
Using scikit-learn
scikit-learn का इस्तेमाल
使用 scikit-learn
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
X = np.array([[600], [800], [1000], [1200], [1400]]) # 2-D for sklearn
y = np.array([65, 85, 105, 120, 145])
model = LinearRegression()
model.fit(X, y)
print(f"Intercept β₀ : {model.intercept_:.4f}") # 6.5
print(f"Slope β₁ : {model.coef_[0]:.4f}") # 0.0975
y_pred = model.predict(X)
mse = mean_squared_error(y, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y, y_pred)
n, p = len(y), X.shape[1]
adj_r2 = 1 - (1 - r2) * (n - 1) / (n - p - 1)
print(f"RMSE : {rmse:.4f}") # 1.8708
print(f"R² : {r2:.4f}") # 0.9954
print(f"Adjusted R² : {adj_r2:.4f}") # 0.9939
# Predict the new flat
new_flat = np.array([[1200]])
print(f"Predicted price for 1200 sq ft: {model.predict(new_flat)[0]:.1f} L")
# 123.5 L
r2_score() only returns plain R². You always need to compute
Adjusted R² manually using the formula above. Remember to track
n (sample size) and p (number of features,
not counting the intercept) carefully.
Assumptions of Linear Regression
Linear Regression is not magic — it comes with four assumptions that must hold for the model and its metrics to be trustworthy.
Try It — Assumption Checker
Pick a dataset. The left plot shows the fit; the right plot shows the residuals vs fitted values — the standard health check. A healthy model gives a shapeless cloud around zero. Each broken assumption leaves its own fingerprint. Press Apply the fix to see the cure.
r2_score() सिर्फ़ साधारण R² देता है। Adjusted R² आपको हमेशा
ऊपर वाले formula से खुद निकालना होगा। ध्यान से
n (sample size) और p (features की संख्या,
intercept को नहीं गिनते) का हिसाब रखें।
Linear Regression की Assumptions
Linear Regression कोई जादू नहीं है। इसके साथ चार assumptions आती हैं। Model और उसके metrics पर भरोसा तभी किया जा सकता है जब ये assumptions सही हों।
खुद करके देखें — Assumption Checker
एक dataset चुनें। बायाँ plot fit दिखाता है; दायाँ plot residuals vs fitted values दिखाता है — यह model की सेहत जाँचने का आम तरीका है। एक सेहतमंद model zero के आसपास बिना किसी आकार का बादल देता है। हर टूटी हुई assumption अपना अलग निशान छोड़ती है। इलाज देखने के लिए fix लगाएँ दबाएं।
r2_score() 只返回普通的 R²。你总是需要用上面的公式
手动计算 Adjusted R²。记得仔细记录
n(样本数量)和 p(feature 个数,
不算 intercept)。
Linear Regression 的 Assumption
Linear Regression 不是魔法——它带有四个 assumption,必须成立, model 和它的 metric 才值得信任。
动手试试——Assumption Checker
选一个 dataset。左边的图显示拟合结果;右边的图显示 residual vs 拟合值——这是 标准的健康检查。健康的 model 会在零附近形成一团没有形状的点。每一种被违反的 assumption 都会留下自己的 “指纹”。按 应用修复 看看解决办法。
Golden Rules
β = (XᵀX)⁻¹Xᵀy),
gradient-descent implementations (used for very large datasets) converge
far faster when features are standardised to mean 0, std 1.
सुनहरे नियम (Golden Rules)
β = (XᵀX)⁻¹Xᵀy),
लेकिन gradient-descent वाले तरीके (जो बहुत बड़े datasets के लिए इस्तेमाल होते हैं) तब
कहीं ज़्यादा तेज़ी से converge करते हैं जब features को standardise करके mean 0, std 1 कर दिया जाए।
黄金法则
β = (XᵀX)⁻¹Xᵀy),
但当 feature 被 standardise 成 mean 0、标准差 1 时,gradient descent 的实现
(用于非常大的 dataset)会收敛得快很多。