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

[!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:
Where:
- dependent variable (target, what we predict)
- = independent variable (feature, predictor)
- = intercept (value of when )
- = slope (change in per unit change in )
- = error term (random noise, captures what the line mises)
Key assumptions:
- Linearity: True relationship is roughly linear
- Independence: Observations don't affect each other
- Homoscedasticity: Error variance is constant across all
- Normality: Errors follow
[!formula] Deriving the Best-Fit Line (Ordinary Least Squares)
Goal: Find that minimize prediction errors.
Step 1: Define the Loss Function
For training points , our prediction is .
The residual (error) for point is:
We want small errors, so minimize the sum of squared residuals (RSS):
Why square the errors?
- Squaring makes all errors positive (a error is as bad as )
- Squaring penalizes large errors more (outliers hurt)
- Squaring makes the math differentiable (we can use calculus)
Step 2: Take Partial Derivatives
To minimize, set and .
Derivative with respect to :
Using chain rule:
Divide by :
Expand:
Why this step? Suming all residuals and setting to zero means the line goes through the "center" of the data.
Solve for :
where and are the means.
Derivative with respect to :
Substitute :
Why this step? We're centering the data around its mean, which simplifies to covariance and variance.
Note: , and
Solve for :
In terms of statistics:
Final OLS formulas:
[!example] Worked Example 1: House Prices
Data: 5 houses with size (100s of sq ft) and price (1000s of $)
| (size) | (price) |
|---|---|
| 10 | 250 |
| 15 | 350 |
| 20 | 450 |
| 25 | 550 |
| 30 | 650 |
Step 1: Calculate means
Step 2: Calculate slope
| 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 |
Why this value? Each100 sq ft increase raises price by $20k. Makes intuitive sense!
Step 3: Calculate intercept
Final model:
Interpretation: A house with 0 sq ft (doesn't exist!) would cost 20k.
Prediction: For a 200 sq ft house ():
[!example] Worked Example 2: Study Hours vs Exam Score
Data: 4 students
| Study Hours () | Score () |
|---|---|
| 2 | 50 |
| 4 | 65 |
| 6 | 80 |
| 8 | 95 |
Step 1: ,
Step 2:
Step 3:
Model:
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)
where TSS (Total Sum of Squares) = measures total variance in .
Derivation of meaning:
- RSS = unexplained variance (what the model missed)
- TSS = total variance in data
- = fraction unexplained
- = fraction explained (between 0 and 1)
Why this metric? means "85% of variance in is explained by ". Higher is better.
2. Root Mean Squared Error (RMSE)
Why this metric? RMSE is in the same units as . If predicting price in dollars, RMSE is in dollars. "On average, predictions are off by ."
[!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 works for any !
The fix: Linearity might break outside your data range. Huge houses have different price dynamics (luxury market). Only interpolate within observed 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 .
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
- 2.1-Introduction-to-Regression: Broader context
- 2.2.02-Multiple-Linear-Regression: Extension to multiple features
- 2.3-Gradient-Descent-for-Linear-Regression: Iterative optimization approach
- 2.5-Assumptions-and-Diagnostics: Checking model validity
- 3.1-Logistic-Regression-Model: Extension to classification
- 4.2-Overfitting-vs-Underfitting: Bias-variance in linear models
- 1.3-Loss-Functions: RSS is a specific loss function
#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 + ε?
What does Ordinary Least Squares (OLS) minimize?
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 β₀?
Why do we square residuals in OLS?
What does R² measure?
What does RMSE measure and why use it?
What are the four key assumptions of simple linear regression?
Why is extrapolation beyond the data range dangerous?
What is a confounding variable and why does it matter?
How do outliers affect linear regression?
How can you check if linearity assumption holds?
What does the slope β₁ =20 mean in a house price model?
In the modelŷ = 35 + 7.5x for study hours vs score, what does the intercept mean?
Concept Map
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!