2.2.5Linear & Logistic Regression

Normal equation closed-form solution

2,766 words13 min readdifficulty · medium

Overview

The normal equation provides an analytical closed-form solution to linear regression by directly computing the optimal parameters without iterative optimization. Unlike gradient descent, it solves for θ\boldsymbol{\theta} in a single step using matrix calculus.

Figure — Normal equation closed-form solution

Think of it like finding the lowest point in a valley: instead of taking many small steps downhill (gradient descent), we use calculus to jump straight to the bottom in one leap.


The Derivation (From First Principles)

Step 1: Set Up the Cost Function

For linear regression with mm training examples and nn features:

hθ(x)=θTx=θ0+θ1x1++θnxnh_{\boldsymbol{\theta}}(\mathbf{x}) = \boldsymbol{\theta}^T \mathbf{x} = \theta_0 + \theta_1 x_1 + \cdots + \theta_n x_n

The cost function (Mean Squared Error) is:

J(θ)=12mi=1m(hθ(x(i))y(i))2J(\boldsymbol{\theta}) = \frac{1}{2m} \sum_{i=1}^{m} \left( h_{\boldsymbol{\theta}}(\mathbf{x}^{(i)}) - y^{(i)} \right)^2

Why 12m\frac{1}{2m}? The 12\frac{1}{2} cancels with the derivative of the square (makes calculus cleaner), and mm normalizes across different dataset sizes.

Step 2: Vectorize Using Matrix Notation

Let's construct the design matrix X\mathbf{X} (dimensions: m×(n+1)m \times (n+1)):

X=[1x1(1)x2(1)xn(1)1x1(2)x2(2)xn(2)1x1(m)x2(m)xn(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}

Why the column of 1's? That's the x0=1x_0 = 1 feature that multiplies θ0\theta_0 (the intercept/bias term).

The parameter vector θR(n+1)\boldsymbol{\theta} \in \mathbb{R}^{(n+1)} and target vector yRm\mathbf{y} \in \mathbb{R}^m:

θ=[θ0θ1θn],y=[y(1)y(2)y(m)]\boldsymbol{\theta} = \begin{bmatrix} \theta_0 \\ \theta_1 \\ \vdots \\ \theta_n \end{bmatrix}, \quad \mathbf{y} = \begin{bmatrix} y^{(1)} \\ y^{(2)} \\ \vdots \\ y^{(m)} \end{bmatrix}

Now all predictions in one shot: Xθ\mathbf{X}\boldsymbol{\theta} gives a vector of mm predictions.

The cost function becomes:

J(θ)=12m(Xθy)T(Xθy)J(\boldsymbol{\theta}) = \frac{1}{2m} (\mathbf{X}\boldsymbol{\theta} - \mathbf{y})^T (\mathbf{X}\boldsymbol{\theta} - \mathbf{y})

Why this form? The squared error sum (hy)2\sum (h - y)^2 is exactly the dot product of the error vector with itself: eTe\mathbf{e}^T \mathbf{e}.

Step 3: Take the Gradient and Set to Zero

To minimize JJ, we need θJ=0\nabla_{\boldsymbol{\theta}} J = \mathbf{0}.

Expanding the quadratic:

J(θ)=12m(θTXTXθ2θTXTy+yTy)J(\boldsymbol{\theta}) = \frac{1}{2m} \left( \boldsymbol{\theta}^T \mathbf{X}^T \mathbf{X} \boldsymbol{\theta} - 2\boldsymbol{\theta}^T \mathbf{X}^T \mathbf{y} + \mathbf{y}^T \mathbf{y} \right)

Why this expansion? We use (ab)T(ab)=aTa2aTb+bTb(a-b)^T(a-b) = a^Ta - 2a^Tb + b^Tb with a=Xθa = \mathbf{X}\boldsymbol{\theta} and b=yb = \mathbf{y}.

Taking the gradient with respect to θ\boldsymbol{\theta} (using matrix calculus rules):

θJ=1m(XTXθXTy)\nabla_{\boldsymbol{\theta}} J = \frac{1}{m} \left( \mathbf{X}^T \mathbf{X} \boldsymbol{\theta} - \mathbf{X}^T \mathbf{y} \right)

Why these terms?

  • θ(θTAθ)=2Aθ\nabla_{\boldsymbol{\theta}} (\boldsymbol{\theta}^T \mathbf{A} \boldsymbol{\theta}) = 2\mathbf{A}\boldsymbol{\theta} when A\mathbf{A} is symmetric
  • θ(θTb)=b\nabla_{\boldsymbol{\theta}} (\boldsymbol{\theta}^T \mathbf{b}) = \mathbf{b}
  • Constants vanish

Setting the gradient to zero:

XTXθXTy=0\mathbf{X}^T \mathbf{X} \boldsymbol{\theta} - \mathbf{X}^T \mathbf{y} = \mathbf{0}

Step 4: Solve for θ\boldsymbol{\theta}

Why is it called "normal"? In linear algebra, "normal" means perpendicular. At the optimum, the residual vector (Xθy)(\mathbf{X}\boldsymbol{\theta} - \mathbf{y}) is orthogonal (normal) to the column space of X\mathbf{X}. This is the least squares solution.

Important caveat on the pseudoinverse: When X\mathbf{X} has full column rank (i.e., XTX\mathbf{X}^T \mathbf{X} is invertible), the matrix (XTX)1XT(\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T equals the Moore-Penrose pseudoinverse X+\mathbf{X}^+, giving the unique least squares solution. When X\mathbf{X} is rank-deficient (singular XTX\mathbf{X}^T \mathbf{X}), this formula breaks down, and the pseudoinverse must be computed via a more general method such as SVD (Singular Value Decomposition). In that case there are infinitely many least squares solutions, and X+\mathbf{X}^+ returns the one with minimum norm.


Worked Examples

Step 1: Construct X\mathbf{X} and y\mathbf{y}

X=[111213],y=[245]\mathbf{X} = \begin{bmatrix} 1 & 1 \\ 1 & 2 \\ 1 & 3 \end{bmatrix}, \quad \mathbf{y} = \begin{bmatrix} 2 \\ 4 \\ 5 \end{bmatrix}

Why this structure? First column is all 1's for θ0\theta_0, second column is the xx values.

Step 2: Compute XTX\mathbf{X}^T \mathbf{X}

XTX=[111123][111213]=[36614]\mathbf{X}^T \mathbf{X} = \begin{bmatrix} 1 & 1 & 1 \\ 1 & 2 & 3 \end{bmatrix} \begin{bmatrix} 1 & 1 \\ 1 & 2 \\ 1 & 3 \end{bmatrix} = \begin{bmatrix} 3 & 6 \\ 6 & 14 \end{bmatrix}

Why this multiplication? Each element (i,j)(i,j) is the dot product of row ii from XT\mathbf{X}^T with column jj from X\mathbf{X}.

Step 3: Compute XTy\mathbf{X}^T \mathbf{y}

XTy=[111123][245]=[1125]\mathbf{X}^T \mathbf{y} = \begin{bmatrix} 1 & 1 & 1 \\ 1 & 2 & 3 \end{bmatrix} \begin{bmatrix} 2 \\ 4 \\ 5 \end{bmatrix} = \begin{bmatrix} 11 \\ 25 \end{bmatrix}

Step 4: Invert XTX\mathbf{X}^T \mathbf{X}

For a 2×2 matrix [abcd]\begin{bmatrix} a & b \\ c & d \end{bmatrix}, the inverse is 1adbc[dbca]\frac{1}{ad-bc}\begin{bmatrix} d & -b \\ -c & a \end{bmatrix}.

(XTX)1=131466[14663]=16[14663]=[7/3111/2](\mathbf{X}^T \mathbf{X})^{-1} = \frac{1}{3 \cdot 14 - 6 \cdot 6} \begin{bmatrix} 14 & -6 \\ -6 & 3 \end{bmatrix} = \frac{1}{6} \begin{bmatrix} 14 & -6 \\ -6 & 3 \end{bmatrix} = \begin{bmatrix} 7/3 & -1 \\ -1 & 1/2 \end{bmatrix}

Why compute the determinant? It's 3(14)6(6)=4236=63(14) - 6(6) = 42 - 36 = 6, which ensures the matrix is invertible.

Step 5: Compute θ\boldsymbol{\theta}

θ=[7/3111/2][1125]=[77/32511+25/2]=[2/33/2]\boldsymbol{\theta} = \begin{bmatrix} 7/3 & -1 \\ -1 & 1/2 \end{bmatrix} \begin{bmatrix} 11 \\ 25 \end{bmatrix} = \begin{bmatrix} 77/3 - 25 \\ -11 + 25/2 \end{bmatrix} = \begin{bmatrix} 2/3 \\ 3/2 \end{bmatrix}

Result: θ0=2/30.67\theta_0 = 2/3 \approx 0.67, θ1=3/2=1.5\theta_1 = 3/2 = 1.5

The fitted line is y=0.67+1.5xy = 0.67 + 1.5x.


x1x_1 x2x_2 yy
1 3 7
2 4 10
3 5 13

Step 1: Design matrix

X=[113124135],y=[71013]\mathbf{X} = \begin{bmatrix} 1 & 1 & 3 \\ 1 & 2 & 4 \\ 1 & 3 & 5 \end{bmatrix}, \quad \mathbf{y} = \begin{bmatrix} 7 \\ 10 \\ 13 \end{bmatrix}

Why three columns? Column 0 is for θ0\theta_0, column 1 for θ1\theta_1 (feature x1x_1), column 2 for θ2\theta_2 (feature x2x_2).

Step 2: XTX\mathbf{X}^T \mathbf{X}

XTX=[361261426122650]\mathbf{X}^T \mathbf{X} = \begin{bmatrix} 3 & 6 & 12 \\ 6 & 14 & 26 \\ 12 & 26 & 50 \end{bmatrix}

Step 3: XTy\mathbf{X}^T \mathbf{y}

XTy=[3066126]\mathbf{X}^T \mathbf{y} = \begin{bmatrix} 30 \\ 66 \\ 126 \end{bmatrix}

Why these numbers? Row 1: 7+10+13=307 + 10 + 13 = 30. Row 2: 1(7)+2(10)+3(13)=7+20+39=661(7) + 2(10) + 3(13) = 7 + 20 + 39 = 66. Row 3: 3(7)+4(10)+5(13)=21+40+65=1263(7) + 4(10) + 5(13) = 21 + 40 + 65 = 126.

Step 4: STOP — check invertibility first!

Look carefully at the feature columns: notice that x2=x1+2x_2 = x_1 + 2 for every row. This means column 2 of X\mathbf{X} equals column 1 plus 2×2 \times (column of 1's):

col2=col1+2col0\text{col}_2 = \text{col}_1 + 2\cdot\text{col}_0

The columns are linearly dependent, so X\mathbf{X} is rank-deficient (rank=2<3\text{rank} = 2 < 3). Therefore XTX\mathbf{X}^T \mathbf{X} is singular — its determinant is 00 and it cannot be inverted. The plain normal equation formula does not apply here.

Why this matters: Because the features are redundant, there is no unique θ\boldsymbol{\theta}. There are infinitely many exact solutions.

Step 5: Solve correctly. The relationship is exactly linear (y=2+2x1+x2y = 2 + 2x_1 + x_2 is one valid fit), so a perfect (zero-error) fit exists. For example:

θ=[221]{2+2(1)+1(3)=72+2(2)+1(4)=102+2(3)+1(5)=13\boldsymbol{\theta} = \begin{bmatrix} 2 \\ 2 \\ 1 \end{bmatrix} \Rightarrow \begin{cases} 2 + 2(1) + 1(3) = 7 \checkmark \\ 2 + 2(2) + 1(4) = 10 \checkmark \\ 2 + 2(3) + 1(5) = 13 \checkmark \end{cases}

But because x2=x1+2x_2 = x_1 + 2, we can trade weight between the parameters. Another exact solution:

θ=[031]0+3(1)+1(3)=6\boldsymbol{\theta}' = \begin{bmatrix} 0 \\ 3 \\ 1 \end{bmatrix} \Rightarrow 0 + 3(1) + 1(3) = 6 \ldots

wait — let's keep the constraint honest. Any θ=(θ0,θ1,θ2)\boldsymbol{\theta} = (\theta_0, \theta_1, \theta_2) satisfying θ0+3θ1+(consistent shift)\theta_0 + 3\theta_1 + \text{(consistent shift)} that reproduces the targets works. The clean way to see it: substitute x2=x1+2x_2 = x_1 + 2 into the model:

h=θ0+θ1x1+θ2(x1+2)=(θ0+2θ2)+(θ1+θ2)x1h = \theta_0 + \theta_1 x_1 + \theta_2 (x_1 + 2) = (\theta_0 + 2\theta_2) + (\theta_1 + \theta_2) x_1

Only the combinations (θ0+2θ2)(\theta_0 + 2\theta_2) and (θ1+θ2)(\theta_1 + \theta_2) are determined; the individual values are free. The data requires (θ0+2θ2)=4(\theta_0 + 2\theta_2) = 4 and (θ1+θ2)=3(\theta_1 + \theta_2) = 3 (matching y=4+3x1y = 4 + 3x_1), giving infinitely many θ\boldsymbol{\theta}.

The correct tool: Use the SVD-based pseudoinverse (X+\mathbf{X}^+), which returns the minimum-norm solution among these infinitely many, or remove the redundant feature x2x_2 and solve a well-posed 2-parameter problem.

Lesson: Always check the rank of X\mathbf{X} before blindly inverting XTX\mathbf{X}^T \mathbf{X}.


When to Use (and When Not to Use)

When to use normal equation:

  • n10,000n \leq 10{,}000 features (matrix inversion is tractable)
  • Small to medium datasets (m<100,000m < 100{,}000)
  • Need exact solution without tuning hyperparameters
  • No regularization needed

When to use gradient descent:

  • n>10,000n > 10{,}000 (e.g., image features, text features)
  • Very large mm (big data scenarios)
  • Online learning (data arrives in streams)
  • Need regularization (Lasso/Ridge) or other constraints

The mistake: Applying the normal equation when XTX\mathbf{X}^T \mathbf{X} is singular (non-invertible)—exactly what happens in Example 2 above.

Why it feels right: The formula looks simple—just plug in your data!

What goes wrong:

  • When nmn \geq m (more features than examples): system is under-determined
  • When features are linearly dependent (multicollinearity): rank(X)<n+1\text{rank}(\mathbf{X}) < n+1
  • Example: including both "price in dollars" and "price in cents" as separate features

The fix:

  1. Remove redundant features (check correlation matrix / rank)
  2. Use regularization (Ridge regression adds λI\lambda \mathbf{I} to make XTX+λI\mathbf{X}^T \mathbf{X} + \lambda \mathbf{I} invertible)
  3. Use the SVD-based pseudoinverse (numpy's pinv or lstsq handles singular matrices gracefully and returns the minimum-norm solution)
  4. Collect more data if m<nm < n

The mistake: Computing the normal equation without feature normalization.

Why it feels right: The normal equation is analytical—scaling shouldn't matter mathematically.

What actually happens:

  • Numerical instability in matrix inversion when features have vastly different scales
  • XTX\mathbf{X}^T \mathbf{X} becomes ill-conditioned (small changes cause huge errors)
  • Example: feature 1 is "age" (20-80), feature 2 is "income" (20,000-200,000)

The fix: Standardize features: xj:=xjμjσjx_j := \frac{x_j - \mu_j}{\sigma_j} before applying the normal equation.


Implementation Considerations

Instead of explicitly computing (XTX)1(\mathbf{X}^T \mathbf{X})^{-1}, use:

  1. QR decomposition: X=QR\mathbf{X} = \mathbf{Q}\mathbf{R}, then solve Rθ=QTy\mathbf{R}\boldsymbol{\theta} = \mathbf{Q}^T \mathbf{y}
  2. SVD (Singular Value Decomposition): Handles near-singular and rank-deficient matrices robustly (and defines the true pseudoinverse)
  3. Cholesky decomposition: Faster for positive definite XTX\mathbf{X}^T \mathbf{X}

Why? Direct matrix inversion is numerically unstable and computationally expensive. These methods avoid inversion while solving the same system.

import numpy as np
 
# Bad: explicit inversion (fails if X^T X is singular)
theta_bad = np.linalg.inv(X.T @ X) @ X.T @ y
 
# Good: use solve (uses LU decomposition internally)
theta_good = np.linalg.solve(X.T @ X, X.T @ y)
 
# Best: use lstsq (uses SVD, handles singular/rank-deficient matrices)
theta_best = np.linalg.lstsq(X, y, rcond=None)[0]

Recall Feynman Explanation (Explain to a 12-year-old)

Imagine you're trying to draw the best straight line through some points on a graph. You could guess a line, measure how far each point is from it, adjust a little bit, and keep doing this until you can't improve anymore (that's gradient descent—lots of little adjustments).

But there's a clever shortcut! Using math, you can calculate the PERFECT line in one go without any guessing. It's like having a magic formula that looks at ALL your points at once and figures out exactly where the line should be.

The "normal equation" is that magic formula. You organize all your data points into a special grid (matrix), do some multiplying and dividing with these grids, and out pops the answer—the exact best line!

The catch? This magic formula gets really slow when you have TONS of data or LOTS of different measurements (features). For small problems, it's the fastest way. For huge problems, you're better off with the "guess-and-adjust" method. And watch out: if two of your measurements are secretly the same thing in disguise (like measuring height in inches AND in centimeters), the magic formula gets confused and can't give one answer—there are infinitely many! You have to throw away the duplicate first.


"The Transpose Times, Inverse Times, Transpose Y"

θ=(XTX)1XTy\boldsymbol{\theta} = (\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T \mathbf{y}

Or think: "X-Transpose-X gets inverted, then X-Transpose-y gets inserted"

Visual: (XtX)1Xty(XtX)^{-1} \cdot Xt \cdot y → the "sandwiched inverse" pattern.


Connections

  • Linear Regression Fundamentals — the problem this solves
  • Gradient Descent — the iterative alternative
  • Ridge Regression — adds λI\lambda \mathbf{I} to handle non-invertibility
  • Moore-Penrose Pseudoinverse — generalized inverse for singular matrices (via SVD)
  • QR Decomposition — numerically stable way to solve least squares
  • Feature Scaling — preprocessing to avoid numerical issues
  • Polynomial Regression — still uses normal equation with transformed features
  • Underdetermined vs Overdetermined Systems — when unique solutions exist

#flashcards/

Concept Map

is a

has

found where

solves

contrasts with

uses

uses

vectorized via

has

derived into

yields

computes

Linear Regression

Quadratic Optimization

Unique Minimum

Gradient equals Zero

Normal Equation

Gradient Descent

Iterative Steps

Matrix Calculus

Cost Function MSE

Design Matrix X

Column of 1's for intercept

Optimal theta

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, is note ka core idea bahut simple hai. Jab hum linear regression karte hain, toh humara goal hota hai woh best-fit line dhundhna jo error ko minimum kare. Ab error ko minimize karne ke do tareeke hain — ek toh gradient descent, jisme hum thode-thode steps le kar dheere-dheere neeche valley ke bottom tak jaate hain. Lekin normal equation ek shortcut deta hai — ye ek hi baar mein, ek single formula se seedha optimal parameters θ\boldsymbol{\theta} nikaal deta hai. Iska matlab hai koi iteration nahi, koi learning rate tune karne ka jhanjhat nahi, bas ek matrix calculation aur kaam khatam.

Ye kaam isliye karta hai kyunki linear regression ka cost function ek quadratic (bowl-shaped) function hota hai — ek katore jaisa. Aur katore ke sabse neeche wale point pe slope zero hoti hai. Toh agar hum gradient ko zero set kar dein aur solve karein, toh humein seedha wahi lowest point mil jaata hai jahan error minimum hai. Isi ko algebra mein solve karke woh famous formula banta hai: θ=(XTX)1XTy\boldsymbol{\theta} = (\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T \mathbf{y}. Yahan X\mathbf{X} hamara design matrix hai jisme sab features rakhe hain, aur woh 1's ka column intercept (bias) term ke liye hota hai.

Ab ye why-matters kyun hai? Kyunki jab tumhara dataset chhota ya medium size ka ho aur features zyada na hon, tab normal equation gradient descent se kaafi tez aur accurate hota hai — no tuning, no guessing. Lekin ek dhyan dene wali baat — jab features bahut zyada ho jaate hain, tab (XTX)1(\mathbf{X}^T \mathbf{X})^{-1} ka inverse nikaalna computationally mehenga ho jaata hai, aur tab gradient descent better rehta hai. Toh ye samajhna zaroori hai ki dono methods kab-kab use hote hain — ye concept tumhare machine learning foundation ko strong banata hai.

Go deeper — visual, from zero

Test yourself — Linear & Logistic Regression

Connections