2.2.2Linear & Logistic Regression

Multiple linear regression

2,460 words11 min readdifficulty · medium1 backlinks

What Is Multiple Linear Regression?

Why multiple features? Real-world phenomena depend on many variables. Single-feature regression ignores confounding factors. Multiple regression captures this complexity if relationships are roughly linear.

Matrix Notation: Why We Need It

Writing y^=β0+β1x1+β2x2+\hat{y} = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \cdots for every prediction is tedious. With mm training examples and nn features, we have mm equations. Matrix form compresses this elegantly.

Step 1: Represent data as matrices

For mm examples, each with nn features: X=[1x1(1)x2(1)xn(1)1x1(2)x2(2)xn(2)1x1(m)x2(m)xn(m)],β=[β0β1βn],y=[y(1)y(2)y(m)]\mathbf{X} = \begin{bmatrix} 1 & x_1^{(1)} & x_2^{(1)} & \cdots & x_n^{(1)} \\ 1 & x_1^{(2)} & x_2^{(2)} & \cdots & x_n^{(2)} \\ \vdots & \vdots & \ddots & \vdots \\ 1 & x_1^{(m)} & x_2^{(m)} & \cdots & x_n^{(m)} \end{bmatrix}, \quad \boldsymbol{\beta} = \begin{bmatrix} \beta_0 \\ \beta_1 \\ \vdots \\ \beta_n \end{bmatrix}, \quad \mathbf{y} = \begin{bmatrix} y^{(1)} \\ y^{(2)} \\ \vdots \\ y^{(m)} \end{bmatrix}

Why the leading1's column? That's the "feature" for β0\beta_0. Makes the intercept just another coefficient in the dot product.

Step 2: Predictions as matrix multiplication

y^=Xβ\hat{\mathbf{y}} = \mathbf{X} \boldsymbol{\beta}

This single equation replaces mm separate prediction formulas. Each row of X\mathbf{X} doted with β\boldsymbol{\beta} gives one prediction.

Figure — Multiple linear regression

Deriving the Optimal Coefficients: The Normal Equation

Goal: Find β\boldsymbol{\beta} that minimizes the mean squared error (MSE): J(β)=1mi=1m(y(i)y^(i))2J(\boldsymbol{\beta}) = \frac{1}{m} \sum_{i=1}^{m} (y^{(i)} - \hat{y}^{(i)})^2

Why this step? We're finding where the cost function's slope is zero—the minimum. The second derivative (Hessian XX\mathbf{X}^\top \mathbf{X}) is positive definite, confirming it's a minimum, not maximum.

When Does the Normal Equation Fail?

Worked Examples

Assumptions of Multiple Linear Regression

For the Normal Equation to give meaningful results, we assume:

  1. Linearity: True relationship is linear (or nearly so)
  2. Independence: Observations are independent (no time-series autocorrelation)
  3. Homoscedasticity: Error variance is constant across all xx values
  4. No perfect multicollinearity: Features aren't exact linear combos of each other
  5. Normality of errors (for inference): Errors N(0,σ2)\sim N(0, \sigma^2) for confidence intervals

What happens if violated?

  • Non-linearity → poor fit, add polynomial features or use non-linear model
  • Multicollinearity → unstable coefficients, high variance
  • Heteroscedasticity → confidence intervals wrong, use weighted least squares

Computational Complexity

Normal Equation: O(n3)O(n^3) for matrix inversion + O(mn2)O(mn^2) for XX\mathbf{X}^\top \mathbf{X}. Dominant cost: inversion.

When to use:

  • Small nn (< 10,000 features): Normal Equation is fast, exact, no hyperparameters
  • Large nn: Use gradient descent (O(kmn)O(kmn) for kk iterations, knk \ll n)
Recall Explain to a 12-Year-Old

Imagine you're guessing how much candy someone will eat at a party. You notice three things matter: how hungry they are, how much they like sweets, and how many friends they're with.

Simple regression is like saying "I'll only look at hunger and ignore everything else." That's silly! Multiple regression is smarter: you make a formula that uses ALL three clues, giving each one a "weight" based on how important it is.

So your formula might be: Candy eaten = 5 + 2×(hunger) + 3×(sweetness love) + 1×(friends nearby). The computer finds the best weights by looking at past parties and figuring out which numbers make the fewest wrong guesses. It's like having a cheat sheet that uses multiple hints instead of just one!

Connections

  • Simple Linear Regression: Multiple regression generalizes to nn features
  • Gradient Descent: Alternative optimization when Normal Equation is expensive
  • Ridge Regression: Adds L2L_2 regularization to handle multicollinearity
  • Polynomial Regression: Multiple regression with x2,x3,x^2, x^3, \ldots as extra features
  • Feature Scaling: Critical preprocessing—keeps coefficients comparable in magnitude
  • R-squared and Adjusted R-squared: Metrics for evaluating fit quality
  • Overfitting: More features → risk of fitting noise, need regularization

#flashcards/ai-ml

What is the matrix form of multiple linear regression predictions? :: y^=Xβ\hat{\mathbf{y}} = \mathbf{X} \boldsymbol{\beta}, where X\mathbf{X} is the design matrix (with leading 1's for intercept), β\boldsymbol{\beta} is the coefficient vector.

What is the Normal Equation for multiple linear regression?
β=(XX)1Xy\boldsymbol{\beta} = (\mathbf{X}^\top \mathbf{X})^{-1} \mathbf{X}^\top \mathbf{y}. Derived by setting the gradient of MSE to zero.
Why do we add a column of 1's to the feature matrix X\mathbf{X}?
To represent the intercept term β0\beta_0 as part of the matrix multiplication Xβ\mathbf{X}\boldsymbol{\beta}. The 1's act as the "feature" for the bias term.
When is XX\mathbf{X}^\top \mathbf{X} non-invertible?
When (1) m<nm < n (fewer examples than features), or (2) perfect multicollinearity exists (one feature is an exact linear combination of others).
What are two alternatives when the Normal Equation fails?
(1) Use gradient descent instead (doesn't require inversion), (2) Add regularization like Ridge regression (XX+λI\mathbf{X}^\top \mathbf{X} + \lambda \mathbf{I}).
What does a negative coefficient βi\beta_i mean in multiple linear regression?
For every1-unit increase in feature xix_i, the predicted target y^\hat{y} decreases by βi|\beta_i| units, holding all other features constant.
What is multicollinearity?
When features are highly correlated with each other (e.g., x32x1+x2x_3 \approx 2x_1 + x_2). Causes unstable coefficient estimates and inflated variance.
Why is the Normal Equation O(n3)O(n^3) complexity?
Matrix inversion (XX)1(\mathbf{X}^\top \mathbf{X})^{-1} is O(n3)O(n^3) for an n×nn \times n matrix. This dominates the cost.
When should you use gradient descent over the Normal Equation?
When nn is large (> 10,000 features). Gradient descent is O(kmn)O(kmn) for kk iterations, avoiding the O(n3)O(n^3) inversion cost.
What does "holding other features constant" mean in coefficient interpretation?
The coefficient βi\beta_i measures the isolated effect of xix_i on y^\hat{y}, as if all other features are frozen. Multiple regression disentangles each feature's contribution.

Concept Map

combined linearly

predicts

fits

uses

weight each

compressed by

prediction

leading 1s column

error minimized by

solved via

derives

Multiple features

Multiple Linear Regression

Continuous target y

Hyperplane in n-dim

Coefficients + intercept

Matrix notation

y-hat = X beta

Encodes intercept

Mean Squared Error

Normal Equation

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, yaha core idea bahut simple hai. Pehle humne ek single feature se prediction kiya tha, jaise sirf ghar ke size se price predict karna. Lekin real world mein cheezein itni simple nahi hoti — ghar ka price sirf size pe nahi, balki bedrooms, location, age, sab pe depend karta hai. Toh Multiple Linear Regression basically yahi karta hai: kai saare features ko ek saath use karke prediction banata hai, aur har feature ko ek weight (coefficient) deta hai jo batata hai ki wo feature kitna important hai. 2D mein jaise hum ek line fit karte the, ab high dimensions mein hum ek "hyperplane" fit kar rahe hain — concept wahi hai, bas dimensions zyada ho gaye.

Ab matrix notation kyun important hai? Socho tumhare paas hazaaron training examples hain, har ek ke liye alag-alag equation likhna practically impossible hai. Isliye hum saara data matrices mein pack kar dete hain — X matrix mein saare features, beta vector mein saare weights. Phir sirf ek chhota sa equation y = X·beta se saari predictions ek saath ho jaati hain. Wo jo leading 1's ka column dikhta hai na, wo intercept (β₀) ke liye hai, taaki bias bhi baaki coefficients ki tarah hi dot product mein aa jaaye. Ye trick calculations ko super clean aur fast bana deti hai, especially jab computer pe implement karna ho.

Aur sabse mast part hai Normal Equation. Hum error (MSE) ko minimize karna chahte hain, matlab prediction aur actual value ke beech ka gap kam se kam ho. Toh calculus use karke gradient nikaalte hain, usse zero pe set karte hain, aur seedha ek formula mil jaata hai jo optimal beta de deta hai — bina koi iterations ya guessing ke, one shot mein! Ye matter isliye karta hai kyunki ye foundation hai — machine learning ke bade models bhi isi linear algebra aur optimization ki soch pe khade hain. Ek baar ye intuition clear ho gayi toh aage neural networks tak sab samajhne mein aasaani hogi.

Go deeper — visual, from zero

Test yourself — Linear & Logistic Regression

Connections