2.2.1Linear & Logistic Regression

Simple linear regression model

2,530 words12 min readdifficulty · medium2 backlinks

Overview

Simple linear regression models the relationship between a single independent variable xx and a dependent variable yy using a straight line. It's the foundation of predictive modeling and the gateway to understanding all supervised learning.

Figure — Simple linear regression model

[!intuition] The Core Idea

Imagine you're predicting house prices. You notice: bigger houses cost more. Simple linear regression draws the "best-fit" straight line through your (size, price) data points. Once you have this line, you predict new prices by reading off the line.

Why a straight line? Because we're modeling a proportional relationship: each extra square foot adds roughly the same amount to the price. The world isn't always linear, but linear models are:

  • Easy to interpret (slope = "price per sq ft")
  • Fast to compute
  • Surprisingly effective for many real phenomena

[!definition] Mathematical Model

The simple linear regression model is:

y=β0+β1x+ϵy = \beta_0 + \beta_1 x + \epsilon

Where:

  • yy dependent variable (target, what we predict)
  • xx = independent variable (feature, predictor)
  • β0\beta_0 = intercept (value of yy when x=0x=0)
  • β1\beta_1 = slope (change in yy per unit change in xx)
  • ϵ\epsilon = error term (random noise, captures what the line mises)

Key assumptions:

  1. Linearity: True relationship is roughly linear
  2. Independence: Observations don't affect each other
  3. Homoscedasticity: Error variance is constant across all xx
  4. Normality: Errors ϵ\epsilon follow N(0,σ2)\mathcal{N}(0, \sigma^2)

[!formula] Deriving the Best-Fit Line (Ordinary Least Squares)

Goal: Find β0,β1\beta_0, \beta_1 that minimize prediction errors.

Step 1: Define the Loss Function

For nn training points (xi,yi)(x_i, y_i), our prediction is y^i=β0+β1xi\hat{y}_i = \beta_0 + \beta_1 x_i.

The residual (error) for point ii is: ei=yiy^ie_i = y_i - \hat{y}_i

We want small errors, so minimize the sum of squared residuals (RSS):

RSS(β0,β1)=i=1n(yiβ0β1xi)2\text{RSS}(\beta_0, \beta_1) = \sum_{i=1}^{n} (y_i - \beta_0 - \beta_1 x_i)^2

Why square the errors?

  1. Squaring makes all errors positive (a 5-5 error is as bad as +5+5)
  2. Squaring penalizes large errors more (outliers hurt)
  3. Squaring makes the math differentiable (we can use calculus)

Step 2: Take Partial Derivatives

To minimize, set RSSβ0=0\frac{\partial \text{RSS}}{\partial \beta_0} = 0 and RSSβ1=0\frac{\partial \text{RSS}}{\partial \beta_1} = 0.

Derivative with respect to β0\beta_0: RSSβ0=β0i=1n(yiβ0β1xi)2\frac{\partial \text{RSS}}{\partial \beta_0} = \frac{\partial}{\partial \beta_0} \sum_{i=1}^{n} (y_i - \beta_0 - \beta_1 x_i)^2

Using chain rule: β0(yiβ0β1xi)2=2(yiβ0β1xi)(1)\frac{\partial}{\partial \beta_0}(y_i - \beta_0 - \beta_1 x_i)^2 = 2(y_i - \beta_0 - \beta_1 x_i) \cdot (-1)

=2i=1n(yiβ0β1xi)=0= -2 \sum_{i=1}^{n} (y_i - \beta_0 - \beta_1 x_i) = 0

Divide by 2-2: i=1n(yiβ0β1xi)=0\sum_{i=1}^{n} (y_i - \beta_0 - \beta_1 x_i) = 0

Expand: i=1nyinβ0β1i=1nxi=0\sum_{i=1}^{n} y_i - n\beta_0 - \beta_1 \sum_{i=1}^{n} x_i = 0

Why this step? Suming all residuals and setting to zero means the line goes through the "center" of the data.

Solve for β0\beta_0: β0=1ni=1nyiβ11ni=1nxi=yˉβ1xˉ\beta_0 = \frac{1}{n}\sum_{i=1}^{n} y_i - \beta_1 \frac{1}{n}\sum_{i=1}^{n} x_i = \bar{y} - \beta_1 \bar{x}

where xˉ=1nxi\bar{x} = \frac{1}{n}\sum x_i and yˉ=1nyi\bar{y} = \frac{1}{n}\sum y_i are the means.

Derivative with respect to β1\beta_1: RSSβ1=2i=1n(yiβ0β1xi)xi=0\frac{\partial \text{RSS}}{\partial \beta_1} = -2 \sum_{i=1}^{n} (y_i - \beta_0 - \beta_1 x_i) \cdot x_i = 0

i=1nxi(yiβ0β1xi)=0\sum_{i=1}^{n} x_i(y_i - \beta_0 - \beta_1 x_i) = 0

Substitute β0=yˉβ1xˉ\beta_0 = \bar{y} - \beta_1 \bar{x}: i=1nxi[yi(yˉβ1xˉ)β1xi]=0\sum_{i=1}^{n} x_i[y_i - (\bar{y} - \beta_1 \bar{x}) - \beta_1 x_i] = 0

i=1nxi(yiyˉ)β1i=1nxi(xixˉ)=0\sum_{i=1}^{n} x_i(y_i - \bar{y}) - \beta_1 \sum_{i=1}^{n} x_i(x_i - \bar{x}) = 0

Why this step? We're centering the data around its mean, which simplifies to covariance and variance.

Note: xixˉ=ˉxi=nxˉ2\sum x_i \bar{x} = \bar \sum x_i = n\bar{x}^2, and xiyixiyˉ=xi(yiyˉ)\sum x_i y_i - \sum x_i \bar{y} = \sum x_i(y_i - \bar{y})

Solve for β1\beta_1: β1=i=1n(xixˉ)(yiyˉ)i=1n(xixˉ)2\beta_1 = \frac{\sum_{i=1}^{n} (x_i - \bar{x})(y_i - \bar{y})}{\sum_{i=1}^{n} (x_i - \bar{x})^2}

In terms of statistics: β1=Cov(x,y)Var(x)=sxysx2\beta_1 = \frac{\text{Cov}(x,y)}{\text{Var}(x)} = \frac{s_{xy}}{s_x^2}

Final OLS formulas: β1=i=1n(xixˉ)(yiyˉ)i=1n(xixˉ)2\boxed{\beta_1 = \frac{\sum_{i=1}^{n} (x_i - \bar{x})(y_i - \bar{y})}{\sum_{i=1}^{n} (x_i - \bar{x})^2}}

β0=yˉβ1xˉ\boxed{\beta_0 = \bar{y} - \beta_1 \bar{x}}

[!example] Worked Example 1: House Prices

Data: 5 houses with size (100s of sq ft) and price (1000s of $)

xx (size) yy (price)
10 250
15 350
20 450
25 550
30 650

Step 1: Calculate means xˉ=10+15+20+25+305=20\bar{x} = \frac{10+15+20+25+30}{5} = 20 yˉ=250+350+450+550+6505=450\bar{y} = \frac{250+350+450+550+650}{5} = 450

Step 2: Calculate slope β1\beta_1

xix_i yiy_i xixˉx_i - \bar{x} yiyˉy_i - \bar{y} (xixˉ)(yiyˉ)(x_i-\bar{x})(y_i-\bar{y}) (xixˉ)2(x_i-\bar{x})^2
10 250 -10 -200 2000 100
15 350 -5 -100 500 25
20 450 0 0 0
25 550 5 100 500 25
30 650 10 2000 100
Sum 5000 250

β1=5000250=20\beta_1 = \frac{5000}{250} = 20

Why this value? Each100 sq ft increase raises price by $20k. Makes intuitive sense!

Step 3: Calculate intercept β0\beta_0 β0=45020×20=450400=50\beta_0 = 450 - 20 \times 20 = 450 - 400 = 50

Final model: y^=50+20x\hat{y} = 50 + 20x

Interpretation: A house with 0 sq ft (doesn't exist!) would cost 50k(maybelandvalue?).Each100sqftadds50k (maybe land value?). Each 100 sq ft adds 20k.

Prediction: For a 200 sq ft house (x=22x=22): y^=50+20(22)=490 thousand dollars\hat{y} = 50 + 20(22) = 490 \text{ thousand dollars}

[!example] Worked Example 2: Study Hours vs Exam Score

Data: 4 students

Study Hours (xx) Score (yy)
2 50
4 65
6 80
8 95

Step 1: xˉ=5\bar{x} = 5, yˉ=72.5\bar{y} = 72.5

Step 2:

(xixˉ)(yiyˉ)=(3)(22.5)+(1)(7.5)+(1)(7.5)+(3)(22.5)\sum(x_i-\bar{x})(y_i-\bar{y}) = (-3)(-22.5) + (-1)(-7.5) + (1)(7.5) + (3)(22.5) =67.5+7.5+67.5=150= 67.5 + 7.5 + 67.5 = 150

(xixˉ)2=9+1+1+9=20\sum(x_i-\bar{x})^2 = 9 + 1 + 1 + 9 = 20

β1=15020=7.5\beta_1 = \frac{150}{20} = 7.5

Step 3: β0=72.57.5(5)=35\beta_0 = 72.5 - 7.5(5) = 35

Model: y^=35+7.5x\hat{y} = 35 + 7.5x

Meaning: Each extra study hour adds 7.5 points. With 0 hours, base score is 35 (prior knowledge?).

[!formula] Model Evaluation Metrics

1. R-squared (Coefficient of Determination)

R2=1RSSTSS=1(yiy^i)2(yiyˉ)2R^2 = 1 - \frac{\text{RSS}}{\text{TSS}} = 1 - \frac{\sum(y_i - \hat{y}_i)^2}{\sum(y_i - \bar{y})^2}

where TSS (Total Sum of Squares) = (yiyˉ)2\sum(y_i - \bar{y})^2 measures total variance in yy.

Derivation of meaning:

  • RSS = unexplained variance (what the model missed)
  • TSS = total variance in data
  • RSSTS\frac{\text{RSS}}{\text{TS}} = fraction unexplained
  • R2R^2 = fraction explained (between 0 and 1)

Why this metric? R2=0.85R^2 = 0.85 means "85% of variance in yy is explained by xx". Higher is better.

2. Root Mean Squared Error (RMSE)

RMSE=1ni=1n(yiy^i)2\text{RMSE} = \sqrt{\frac{1}{n}\sum_{i=1}^{n}(y_i - \hat{y}_i)^2}

Why this metric? RMSE is in the same units as yy. If predicting price in dollars, RMSE is in dollars. "On average, predictions are off by ±RMSE±\text{RMSE}."

[!mistake] Common Pitfalls

Mistake 1: Extrapolation Beyond Data Range

Wrong thinking: "My model works for houses1000-3000 sq ft, so I'll predict a10,000 sq ft mansion."

Why it feels right: The formula y^=β0+β1x\hat{y} = \beta_0 + \beta_1 x works for any xx!

The fix: Linearity might break outside your data range. Huge houses have different price dynamics (luxury market). Only interpolate within observed xx range.

Mistake 2: Correlation≠ Causation

Wrong thinking: "Ice cream sales and drowning deaths are correlated and fit a linear model, so ice cream causes drowning!"

Why it feels right: The math is valid; the regression line exists.

The fix: Regression finds association, not causation. Both are caused by a confounding variable (summer heat). Need controlled experiments or causal inference methods to claim causation.

Mistake 3: Ignoring Outliers

Wrong thinking: "One data point is way off, but I'll include it anyway."

Why it feels right: More data is better, right?

The fix: Outliers distort the line (squared errors amplify their influence). Investigate outliers: data entry errors? Or legitimate extreme cases? Consider robust regression methods or remove after justification.

Mistake 4: Assuming Linearity Without Checking

Wrong thinking: "I fit a line, so the relationship is linear."

Why it feels right: You get a line no matter what; OLS always returns β0,β1\beta_0, \beta_1.

The fix: Plot residuals vs fitted values. Random scatter = good. Patterns (curve, funel shape) = violated assumptions. Transform data (log, sqrt) or use polynomial/nonlinear regression.

[!recall]- Explain Like I'm 12

Imagine you're trying to guess how tall your friends are by looking at their shoe size.

You notice: bigger shoes usually mean taller person. So you draw a straight line on graph paper where you've ploted everyone's (shoe size, height).

Now when a new kid with size 7 shoes shows up, you find7 on your line and read off their predicted height!

Simple linear regression is just finding the BEST line through your dots. "Best" means the line that's closest to all dots at once (smallest mistakes on average).

The slope tells you "how many inches taller per shoe size", and the intercept is where the line crosses the height axis (though baby with size 0 shoes wouldn't actually be that height—the line is just a model!).

[!mnemonic] SLOPE

Sum of (x - mean)(y - mean)
Less
Over
Product of (x - mean)²
Equals beta₁

Intercept: "y-bar minus beta times x-bar" (sounds like "why bother? Beat times X!")

Connections


#flashcards/ai-ml

What is simple linear regression modeling? :: A method to model the relationship between a single independent variable x and dependent variable y using a straight line equation y = β₀ + β₁x + ε

What are the parameters in y = β₀ + β₁x + ε?
β₀ is the intercept (y-value when x=0), β₁ is the slope (change in y per unit x), ε is the random error term
What does Ordinary Least Squares (OLS) minimize?
The sum of squared residuals RSS = Σ(yᵢ - ŷᵢ)², where residuals are the differences between actual and predicted values

Derive the OLS formula for β₁ from first principles :: Take ∂RSS/∂β₁ = 0, substitute β₀ = ȳ - β₁x̄, solve to get β₁ = Σ(xᵢ-x̄)(yᵢ-ȳ) / Σ(xᵢ-x̄)² = Cov(x,y)/Var(x)

What is the OLS formula for the intercept β₀?
β₀ = ȳ - β₁x̄, ensuring the regression line passes through the point (x̄, ȳ)
Why do we square residuals in OLS?
(1) Makes all errors positive, (2) Penalizes large errors more heavily, (3) Makes the loss function differentiable for calculus-based optimization
What does R² measure?
The coefficient of determination: R² = 1 - RSS/TSS, representing the proportion of variance in y explained by x (ranges 0 to 1)
What does RMSE measure and why use it?
Root Mean Squared Error = √(Σ(yᵢ-ŷᵢ)²/n), gives average prediction error in the same units as y, making it interpretable
What are the four key assumptions of simple linear regression?
(1) Linearity: true relationship is linear, (2) Independence: observations don't affect each other, (3) Homoscedasticity: constant error variance, (4) Normality: errors follow N(0,σ²)
Why is extrapolation beyond the data range dangerous?
The linear relationship may not hold outside observed x values; different dynamics may apply (e.g., luxury market for large houses)
What is a confounding variable and why does it matter?
A variable that influences both x and y, creating spurious correlation (e.g., heat causes both ice cream sales and drowning); regression shows association, not causation
How do outliers affect linear regression?
Squared errors amplify outlier influence, distorting the fitted line; investigate whether they're errors or legitimate extreme cases before deciding to remove
How can you check if linearity assumption holds?
Plot residuals vs fitted values; random scatter indicates good fit, patterns (curves, funnels) indicate violated assumptions requiring transformation or nonlinear models
What does the slope β₁ =20 mean in a house price model?
Each one-unit increase in x (e.g., 100 sq ft) increases predicted y (price) by 20 units (e.g., $20k)
In the modelŷ = 35 + 7.5x for study hours vs score, what does the intercept mean?
With 0 study hours, the baseline predicted score is 35 (possibly representing prior knowledge or guessing ability)

Concept Map

models

predictor of

contains

contains

contains

requires

assumed Normal

fit by

minimizes

sums squared

equals y minus prediction

solved via

yields

yields

Simple Linear Regression

Independent variable x

Dependent variable y

y = b0 + b1 x + e

Intercept b0

Slope b1

Error term e

Assumptions

Ordinary Least Squares

Sum of Squared Residuals

Residual e_i

Partial Derivatives = 0

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Simple linear regression ek basic lekin powerful technique hai jisme hum ek straight line use karte hain do variables ke bech relationship dhoondhne ke liye. Socho tumhare pas kuch houses hain aur tum dekhna chahte ho ki size aur price mein kya connection hai. Toh tum sabhi (size, price) points ko graph pe plot karo aur phir ek line draw karo jo sabse pass se in points se guzre. Yahi line tumhara model hai!

Is line ko mathematically likhte hain: y = β₀ + β₁x + ε. Yahaan β₁ slope hai jo bata hai ki "x mein 1 unit badha toh y mein kitna badhega", aur β₀ intercept hai jo starting point hai (jab x zero ho). Epsilon (ε) wo random error hai jo har real-world situation mein hota hai kyunki perfect prediction kabhi possible nahi.

Sabse best line dhoondhne ke liye hum Ordinary Least Squares (OLS) method use karte hain. Iska matlab hai ki hum un β₀ aur β₁ values ko dhondh rahe hain jo sabhi prediction errors ko minimum kare. "Error" matlab actual value minus predicted value. Inn errors ko square karke sum karte hain (taki negative aur positive cancel na ho), aur phir calculus use karke wo values nikalte hain jo is sum ko minimum banaye. Formula ata hai: β₁ = Σ(xᵢ-x̄)(yᵢ-ȳ) / Σ(xᵢ-x̄)², jo basically kehta hai "x aur y ke beech covariance ko x ke variance se divide karo."

Yeh technique machine learning ka foundation hai.Isse hum predictions bana sakte hain (naye house ki price), trends samajh sakte hain (har100 sq ft pe kitna paisa badhta hai), aur data-driven decisions le sakte hain. Lekin dhyan rakho: model sirf utna hi accurate hai jitna tumhara data clean aur assumptions valid hain!

Go deeper — visual, from zero

Test yourself — Linear & Logistic Regression

Connections