Linear Regression
What is it?
Linear Regression is a fundamental supervised machine learning algorithm that models a linear relationship between one or more input variables, called features (), and a continuous numerical output, called the target ().
It is widely used to predict continuous real-world quantities such as exam scores, house prices, salaries, temperatures, and sales volumes.
A Motivating Example
Suppose we want to predict a student's final exam score () based on the number of hours they spent studying ():
The input is study hours (), and the target is exam score (). The goal of linear regression is not to pass through every single observed point, but rather to discover a line that best captures the overall trend of the data to make accurate predictions for new, unseen study hours.

Why we need it
Almost every quantitative system in science, engineering, and business seeks to understand how changes in an input produce changes in an output:
- Education Analytics: How much does an extra hour of study boost exam performance?
- Healthcare: How does medication dosage correlate with blood pressure reduction?
- Economics & Finance: How do interest rates impact market returns?
Linear regression is the universal benchmark of predictive modeling because:
- Direct Interpretability: Each learned parameter has clear physical meaning.
- Transparent Mechanics: You can trace exactly how predictions are calculated and why errors occur.
- Foundation of Deep Learning: A single neuron in an artificial neural network is essentially a linear regression unit followed by an activation function!
Explained in detail
1. The Linear Regression Equation
For simple linear regression with one feature, the prediction equation is:
This shares the exact same mathematical structure as the classic slope-intercept equation :
- is the input feature (e.g., study hours).
- (pronounced y-hat) is the model's predicted output.
- (beta-zero) is the y-intercept.
- (beta-one) is the slope (or coefficient).
Understanding the Intercept ()
The intercept is the model's predicted output when the input is zero:
For example, in , the intercept is . When a student studies hours, the model predicts a score of .
Understanding the Slope ()
The slope describes the change in predicted output for a one-unit increase in the input:
If , increasing study time by one hour increases the predicted score by points. Note that this describes the model's learned association, not necessarily a direct causal guarantee.

- (Positive slope): As study hours increase, predicted score increases.
- (Negative slope): As input increases, predicted output decreases (e.g., car age vs. resale value).
- (Zero slope): The input has no linear predictive power over the target; the line is flat.
Statistical Convention: Beta vs. Beta-Hat In statistics, and represent the true (unknown) underlying population parameters. The numbers estimated from sample training data are written with a hat: and .
2. Measuring Prediction Errors: Residuals
Suppose we test an initial, imperfect model:
Let's compare its predictions against our training data:
A residual is the vertical difference between the true observed value and the model's prediction:

- Positive residual (): The actual point lies above the line (the model underpredicted).
- Negative residual (): The actual point lies below the line (the model overpredicted).
- Zero residual (): The line passes directly through the point.
Why Not Simply Sum the Residuals?
If an error is and another is , adding them yields:
Positive and negative residuals cancel out! A total error sum of zero would trick the algorithm into thinking a dreadful model is completely flawless.
3. Cost Functions: RSS and MSE
To prevent positive and negative errors from canceling, we square each residual.
Residual Sum of Squares (RSS)
For residuals :
Mean Squared Error (MSE)
Dividing RSS by the number of training examples gives the average squared penalty, known as the Mean Squared Error (MSE) cost function:
The learning objective of linear regression is to find the parameters and that minimize this cost function:
4. How Does the Model Learn? Gradient Descent
Imagine walking down a misty mountain in dense fog. You cannot see the lowest valley at the bottom. What do you do? At your current position, you feel the slope beneath your feet, take a step in the steepest downhill direction, and repeat until the ground flattens out.

In machine learning optimization:
- The height of the mountain is your cost ().
- Your coordinates on the mountain are your parameters ().
- The negative gradient () tells you which direction leads downhill.
The Update Rule
The general Gradient Descent update rule is:
where is the learning rate (step size).

- too small: Steps are minuscule; training takes thousands of iterations to converge.
- well-chosen: Steps progress smoothly and efficiently toward the minimum.
- too large: Steps overshoot the valley floor, oscillating wildly or even diverging to infinity.
The Gradients for Simple Linear Regression
Applying the calculus chain rule to the MSE cost function yields two partial derivatives:
At each iteration, we update both parameters simultaneously:
5. A Complete Worked Numerical Example
Let's trace one complete update step by hand with a single training point:
- Feature:
- Target:
- Initial guesses: ,
- Learning rate:
Step 1: Compute Prediction
Step 2: Calculate Gradients (for )
Step 3: Update the Intercept ()
Step 4: Update the Slope ()
Resulting Updated Model:
Testing our new model on :
The squared error plummeted from down to !
Interactive Linear Regression: Line of Best Fit & Residuals
Drag data points or adjust the slope (β₁) and intercept (β₀) sliders to minimize the red vertical residuals (eᵢ = yᵢ - ŷᵢ). Watch MSE and R² update in real time.
What to try
- Move the Slope () slider: Watch the line rotate. Notice how the vertical red dashed residuals () stretch when tilts away from the data trend.
- Adjust the Intercept () slider: Shift the baseline height of the line. Watch the live model equation update in the dark instrument panel.
- Click "🎯 Auto-Fit OLS": Instantly compute the exact global minimum of MSE using the closed-form Ordinary Least Squares formula (, ).
- Click "Imperfect (10+10x)": See the exact imperfect baseline model from Section 2 of the notes ().
- Drag any data point: Grab one of the dark circular points on the canvas and drag it up or down to see how an outlier changes the optimal line and inflates the MSE!
Notes & Formula
Simultaneous Updates: When implementing Gradient Descent in code, always calculate both gradients and using the current parameter values before updating either parameter.
The Cancellation Trap: Never minimize raw residuals . Because positive and negative errors cancel out, squaring is strictly required to ensure every mistake is penalized.
Quiz
🧩
Ready to test yourself?
25 questions · explanations shown after
Teach & Solidify
Teach This: Linear Regression
Core Intuition
Linear Regression learns the line ŷ = β₀ + β₁x that minimizes the average squared vertical error (MSE) across all training points.
Key Concepts to Explain
- 1Intercept β₀ is the baseline output when x = 0; slope β₁ is the expected change in ŷ per 1 unit increase in x.
- 2Residual eᵢ = yᵢ - ŷᵢ measures vertical distance between true reality and model prediction.
- 3We square errors (MSE) to prevent positive and negative deviations from canceling out.
- 4Gradient Descent iteratively updates parameters downhill in the direction of the negative gradient.
⚠️ What Most Students Get Confused About
Updating β₀ first and then using the new β₀ to compute the gradient for β₁! In standard Gradient Descent, all gradients must be computed simultaneously from the current parameter state before updating.
Explain Linear Regression in your own words
Imagine you are explaining this idea to a friend or classmate with no math background. Writing it out forces your brain to bridge gaps in your intuition.
Resources & GitHub
Resources & Study Materials
Deepen your understanding with author-prepared study notes, derivation proofs, and curated educational lectures.
Author's complete handwritten and compiled LaTeX reference notes covering formulas, step-by-step updates, and derivations.
Josh Starmer visually breaks down fitting lines, calculating residuals, and understanding R².
Quick formula sheet covering hypothesis, MSE cost function, partial derivatives, and convergence rules.
Mastered this concept?
Tick this box when you feel confident explaining it.
Topic Resources
Was this clear?