Skip to main content

Linear Regression

Linear Regression - Best Fit Line

From Intuition to Implementation

In the previous modules, you learned:
  1. ML is about finding patterns in data
  2. We measure β€œwrongness” with a loss function
  3. Gradient descent minimizes the loss
Now let’s put it all together into a complete, professional algorithm.

The Real-World Setup

Your boss asks: β€œCan you predict how much revenue we’ll make based on our advertising spend?” You have historical data:
Question: If we spend 100konTV,100k on TV, 40k on Radio, and $30k on Newspaper, what revenue can we expect?
House Price Prediction with Linear Regression

The Linear Regression Model

We assume revenue is a weighted combination of ad spends: revenue=w0+w1β‹…TV+w2β‹…Radio+w3β‹…Newspaper\text{revenue} = w_0 + w_1 \cdot \text{TV} + w_2 \cdot \text{Radio} + w_3 \cdot \text{Newspaper} Or in matrix notation (see Matrix Operations): y^=Xβ‹…w\hat{y} = X \cdot w Where:
  • XX is our feature matrix (with a column of 1s for the bias term)
  • ww is our weight vector
  • y^\hat{y} is our predictions

Step-by-Step Implementation

Step 1: Prepare the Data

Step 2: Define the Model

Step 3: Define the Loss Function

Step 4: Compute the Gradient

Step 5: Gradient Descent

Step 6: Train the Model


Using scikit-learn (The Professional Way)

In practice, we use libraries that handle all the details β€” the normal equation, numerical stability, edge cases. Understanding the math (above) is for your brain; scikit-learn is for your production code.

Interpreting the Results

The coefficients tell a story:
Insights:
  • Every 1kspentonβˆ—βˆ—Radioβˆ—βˆ—returnsΒ 1k spent on **Radio** returns ~188 in revenue (best ROI!)
  • Every 1konβˆ—βˆ—TVβˆ—βˆ—returnsΒ 1k on **TV** returns ~46
  • Newspaper ads have almost no impact
Business decision: Shift budget from newspaper to radio!

The Closed-Form Solution

For linear regression, there’s actually a formula that gives the optimal weights directly, without gradient descent: w=(XTX)βˆ’1XTyw = (X^T X)^{-1} X^T y This is called the Normal Equation. It comes from calculus - setting the gradient to zero and solving. Think of it as the β€œjust give me the answer” approach versus gradient descent’s β€œlet me walk there step by step.”
When to use which?In practice, scikit-learn’s LinearRegression automatically picks the best solver for your data size. You rarely need to worry about this choice β€” but understanding it helps you debug slow training times.

Real-World Example: House Price Prediction

Let’s build a proper house price predictor using real data:

Common Pitfalls and Solutions

Pitfall 1: Features on Different Scales

Pitfall 2: Multicollinearity

When features are highly correlated, coefficients become unstable. Imagine trying to figure out whether it’s the coffee or the sugar making your drink sweet β€” when they always appear together, it’s hard to tell who deserves the credit.

Pitfall 3: Overfitting

When the model memorizes training data but fails on new data. This is like studying only the practice exam and then bombing the real test because the questions are slightly different.
Practical rule of thumb: Linear regression rarely overfits unless you have far more features than samples. If you have 50 features and 100 rows, consider Ridge or Lasso regression (Module 13) to keep things under control.

The Complete Linear Regression Workflow


Key Takeaways

Linear = Weighted Sum

y = w0 + w1x1 + w2x2 + …

MSE Loss

Measures average squared error

Scale Your Features

Normalize for better training

Evaluate on Test Data

Always hold out some data

πŸš€ Mini Projects

Project 1

Build a salary prediction model

Project 2

Real estate price predictor with feature engineering

Project 3

Model comparison and selection pipeline

What’s Next?

Linear regression predicts continuous numbers. But what if you want to predict categories?
  • Is this email spam or not spam?
  • Will this customer churn or stay?
  • Is this tumor malignant or benign?
That’s classification - the subject of our next module!

Continue to Module 4: Classification

Learn to predict categories with logistic regression and beyond

πŸ”— Math β†’ ML Connection Summary

Where the math you learned powers linear regression:Bottom line: Linear regression is the intersection of all three math courses. Master this, and neural networks become β€œjust deeper linear regression with nonlinearities.”
Want to understand the theory? Here’s what’s happening under the hood:

Why Gradient Descent Works

The MSE loss is convex (bowl-shaped), meaning:
  • There’s exactly one minimum
  • Gradient descent is guaranteed to find it
  • Step size (learning rate) affects speed but not destination
L(w)=1nβˆ‘i=1n(yiβˆ’wTxi)2L(w) = \frac{1}{n}\sum_{i=1}^{n}(y_i - \mathbf{w}^T\mathbf{x}_i)^2Taking the gradient: βˆ‡wL=βˆ’2nXT(yβˆ’Xw)\nabla_w L = -\frac{2}{n}X^T(y - X\mathbf{w})Setting to zero gives the normal equation: wβˆ—=(XTX)βˆ’1XTy\mathbf{w}^* = (X^TX)^{-1}X^Ty

The Statistical Interpretation

Under the assumption that errors are normally distributed: y=wTx+Ο΅,ϡ∼N(0,Οƒ2)y = \mathbf{w}^T\mathbf{x} + \epsilon, \quad \epsilon \sim \mathcal{N}(0, \sigma^2)Maximum Likelihood Estimation (MLE) of w\mathbf{w} is equivalent to minimizing MSE!

Regularization from a Bayesian View

  • Ridge Regression (L2): Assumes weights have Gaussian prior w∼N(0,Ο„2I)\mathbf{w} \sim \mathcal{N}(0, \tau^2I)
  • Lasso (L1): Assumes weights have Laplacian prior β†’ promotes sparsity
This connection between regularization and Bayesian priors is why regularization prevents overfitting!