2.2.4Linear & Logistic Regression

Cost function (MSE) and gradient descent fitting

3,515 words16 min readdifficulty · medium

Overview

In linear regression, we want to find the best-fit line through our data. But what does "best" mean? We need a way to measure how wrong our predictions are, and then systematically improve them. The Mean Squared Error (MSE) is our measure of wrongness, and gradient descent is our systematic improvement algorithm.

Figure — Cost function (MSE) and gradient descent fitting

We square instead of using absolute values because squared functions are differentiable everywhere, which lets us use calculus to find the minimum efficiently.


Cost Function: Mean Squared Error

J(θ)=12ni=1n(hθ(xi)yi)2J(\theta) = \frac{1}{2n} \sum_{i=1}^{n} (h_\theta(x_i) - y_i)^2

Where:

  • J(θ)J(\theta) = cost function (what we want to minimize)
  • θ\theta = parameters (weights and bias: θ0,θ1,..\theta_0, \theta_1, ..)
  • hθ(xi)=θ0+θ1xih_\theta(x_i) = \theta_0 + \theta_1 x_i for simple linear regression
  • The 12\frac{1}{2} is a convenience factor that cancels when we take derivatives

Derivation from first principles

Why do we need a cost function? We have nn training examples (xi,yi)(x_i, y_i). Our hypothesis makes predictions y^i=hθ(xi)\hat{y}_i = h_\theta(x_i). Each prediction has an error: ei=y^iyie_i = \hat{y}_i - y_i.

Step 1: Measure total error Sum of errors: ei\sum e_i won't work (positive and negative cancel) Sum of absolute errors: ei\sum |e_i| works but isn't differentiable at zero

Step 2: Square the errors Total squared error=i=1nei2=i=1n(hθ(xi)yi)2\text{Total squared error} = \sum_{i=1}^{n} e_i^2 = \sum_{i=1}^{n} (h_\theta(x_i) - y_i)^2

Why this step? Squaring makes all errors positive, penalizes large errors more, and creates a smooth surface we can optimize with calculus.

Step 3: Average to get MSE J(θ)=1ni=1n(hθ(xi)yi)2J(\theta) = \frac{1}{n} \sum_{i=1}^{n} (h_\theta(x_i) - y_i)^2

Why this step? Dividing by nn makes the cost independent of dataset size—10 errors of size 5 should cost the same whether we have 100 or 1000 examples.

Step 4: Add the 12\frac{1}{2} factor J(θ)=12ni=1n(hθ(xi)yi)2J(\theta) = \frac{1}{2n} \sum_{i=1}^{n} (h_\theta(x_i) - y_i)^2

Why this step? When we take the derivative, the power rule brings down a factor of 2 from squaring, which cancels the 12\frac{1}{2}. This makes the gradient cleaner.

  • Outer sum: Accumulates errors across all training examples
  • Inner difference: Prediction minus actual (residual)
  • Square: Penalizes errors quadratically
  • Division by 2n: Normalizes and simplifies derivatives

Gradient Descent: Finding the Minimum

The gradient J(θ)\nabla J(\theta) is a vector pointing in the direction of stepest increase. We go in the opposite direction to descend.

Deriving the Gradient Descent Update Rule

Step 1: Write the update formula (general form) θj:=θjαJ(θ)θj\theta_j := \theta_j - \alpha \frac{\partial J(\theta)}{\partial \theta_j}

Where:

  • :=:= means "update to"
  • α\alpha is the learning rate (step size)
  • J(θ)θj\frac{\partial J(\theta)}{\partial \theta_j} is the partial derivative (slope) with respect to parameter θj\theta_j

Why this form? If the slope is positive (we're on an uphill), the derivative is positive, so we subtract it (go left/down). If the slope is negative (we're on a downhill), we subtract a negative (go right/down).

Step 2: Compute the partial derivative Start with the cost function: J(θ)=12ni=1n(hθ(xi)yi)2J(\theta) = \frac{1}{2n} \sum_{i=1}^{n} (h_\theta(x_i) - y_i)^2

For simple linear regression, hθ(xi)=θ0+θ1xih_\theta(x_i) = \theta_0 + \theta_1 x_i.

Take the derivative with respect to θj\theta_j: J(θ)θj=θj[12ni=1n(hθ(xi)yi)2]\frac{\partial J(\theta)}{\partial \theta_j} = \frac{\partial}{\partial \theta_j} \left[ \frac{1}{2n} \sum_{i=1}^{n} (h_\theta(x_i) - y_i)^2 \right]

Why this step? We need to know how much a small change in θj\theta_j changes the cost.

Step 3: Apply chain rule =12ni=1nθj(hθ(xi)yi)2= \frac{1}{2n} \sum_{i=1}^{n} \frac{\partial}{\partial \theta_j} (h_\theta(x_i) - y_i)^2

=12ni=1n2(hθ(xi)yi)θj(hθ(xi)yi)= \frac{1}{2n} \sum_{i=1}^{n} 2(h_\theta(x_i) - y_i) \cdot \frac{\partial}{\partial \theta_j}(h_\theta(x_i) - y_i)

Why this step? Chain rule: derivative of u2u^2 is 2uu2u \cdot u'. Here u=hθ(xi)yiu = h_\theta(x_i) - y_i.

The 2 cancels with 12\frac{1}{2}: =1ni=1n(hθ(xi)yi)hθ(xi)θj= \frac{1}{n} \sum_{i=1}^{n} (h_\theta(x_i) - y_i) \cdot \frac{\partial h_\theta(x_i)}{\partial \theta_j}

Step 4: Compute hθ(xi)θj\frac{\partial h_\theta(x_i)}{\partial \theta_j}

For θ0\theta_0 (bias/intercept): θ0(θ0+θ1xi)=1\frac{\partial}{\partial \theta_0}(\theta_0 + \theta_1 x_i) = 1

For θ1\theta_1 (slope): θ1(θ0+θ1xi)=xi\frac{\partial}{\partial \theta_1}(\theta_0 + \theta_1 x_i) = x_i

In general, for θj\theta_j: hθ(xi)θj=xi(j)\frac{\partial h_\theta(x_i)}{\partial \theta_j} = x_i^{(j)} where xi(j)x_i^{(j)} is the jj-th feature of example ii (with xi(0)=1x_i^{(0)} = 1 for the bias term).

Step 5: Final gradient J(θ)θj=1ni=1n(hθ(xi)yi)xi(j)\frac{\partial J(\theta)}{\partial \theta_j} = \frac{1}{n} \sum_{i=1}^{n} (h_\theta(x_i) - y_i) \cdot x_i^{(j)}

Update all parameters simultaneously:

  • θ0:=θ0α1ni=1n(hθ(xi)yi)\theta_0 := \theta_0 - \alpha \frac{1}{n} \sum_{i=1}^{n} (h_\theta(x_i) - y_i)
  • θ1:=θ1α1ni=1n(hθ(xi)yi)xi\theta_1 := \theta_1 - \alpha \frac{1}{n} \sum_{i=1}^{n} (h_\theta(x_i) - y_i) \cdot x_i

Simultaneous means: compute all new values using the old θ\theta values, then update all at once.


The Learning Rate α\alpha

Too small: Convergence is slow (many iterations needed) Too large: We overshoot the minimum and may diverge (cost increases) Just right: Fast convergence to the minimum

Typical values: 0.001,0.01,0.1,10.001, 0.01, 0.1, 1. Often found by trial and error or adaptive methods.

The gradient tells you the direction; α\alpha tells you how far to go.


Worked Examples

Goal: Fit y=θ0+θ1xy = \theta_0 + \theta_1 x using gradient descent.

Initialize: θ0=0,θ1=0\theta_0 = 0, \theta_1 = 0, learning rate α=0.1\alpha = 0.1

Iteration 1:

  1. Compute predictions:

    • hθ(1)=0+0(1)=0h_\theta(1) = 0 + 0(1) = 0
    • hθ(2)=0+0(2)=0h_\theta(2) = 0 + 0(2) = 0
    • hθ(3)=0+0(3)=0h_\theta(3) = 0 + 0(3) = 0
  2. Compute errors (residuals):

    • e1=02=2e_1 = 0 - 2 = -2
    • e2=04=4e_2 = 0 - 4 = -4
    • e3=05=5e_3 = 0 - 5 = -5
  3. Compute cost: J(θ)=123[(2)2+(4)2+(5)2]=16[4+16+25]=456=7.5J(\theta) = \frac{1}{2\cdot 3}[(-2)^2 + (-4)^2 + (-5)^2] = \frac{1}{6}[4 + 16 + 25] = \frac{45}{6} = 7.5

  4. Compute gradients: Jθ0=13[(2)(1)+(4)(1)+(5)(1)]=113=3.67\frac{\partial J}{\partial \theta_0} = \frac{1}{3}[(-2)(1) + (-4)(1) + (-5)(1)] = \frac{-11}{3} = -3.67 Why this step? Each error is multiplied by x(0)=1x^{(0)} = 1 for the bias term.

    Jθ1=13[(2)(1)+(4)(2)+(5)(3)]=253=8.33\frac{\partial J}{\partial \theta_1} = \frac{1}{3}[(-2)(1) + (-4)(2) + (-5)(3)] = \frac{-25}{3} = -8.33

    Why this step? Each error is multiplied by the corresponding xix_i value.

  5. Update parameters: θ0:=00.1(3.67)=0.367\theta_0 := 0 - 0.1(-3.67) = 0.367 θ1:=00.1(8.33)=0.833\theta_1 := 0 - 0.1(-8.33) = 0.833

    Why this step? We move in the direction opposite to the gradient (downhill).

Iteration 2 (using new θ\theta):

  1. Predictions:

    • hθ(1)=0.367+0.833(1)=1.2h_\theta(1) = 0.367 + 0.833(1) = 1.2
    • hθ(2)=0.367+0.833(2)=2.033h_\theta(2) = 0.367 + 0.833(2) = 2.033
    • hθ(3)=0.367+0.833(3)=2.866h_\theta(3) = 0.367 + 0.833(3) = 2.866
  2. Errors:

    • e1=1.22=0.8e_1 = 1.2 - 2= -0.8
    • e2=2.0334=1.967e_2 = 2.033 - 4 = -1.967
    • e3=2.8665=2.134e_3 = 2.866 - 5 = -2.134
  3. Cost: J(θ)=16[0.64+3.87+4.55]=1.51J(\theta) = \frac{1}{6}[0.64 + 3.87 + 4.55] = 1.51

    Why this step? Cost decreased from 7.5 to 1.51—we're moving downhill!

Continue until cost stops decreasing significantly (convergence).


Step 1: Compute prediction and error

  • hθ(2)=12=2h_\theta(2) = 1 \cdot 2 = 2
  • Error: e=25=3e = 2 - 5 = -3

Step 2: Compute cost J(θ1)=121(3)2=4.5J(\theta_1) = \frac{1}{2 \cdot 1}(-3)^2 = 4.5

Step 3: Compute gradient Jθ1=11[(3)(2)]=6\frac{\partial J}{\partial \theta_1} = \frac{1}{1}[(-3)(2)] = -6

Why is it negative? Our prediction (2) is less than the actual (5). The error is negative. When multiplied by x=2x = 2, we get -6. This negative gradient tells us: increase θ1\theta_1 to make better predictions.

Step 4: Update (with α=0.1\alpha = 0.1) θ1:=10.1(6)=1+0.6=1.6\theta_1 := 1 - 0.1(-6) = 1 + 0.6 = 1.6

Why this step? Subtracting a negative gradient means adding, so θ1\theta_1 increases, which will increase our predictions (moving from 2 toward 5).

Verification:

  • New prediction: hθ(2)=1.62=3.2h_\theta(2) = 1.6 \cdot 2 = 3.2 (closer to 5 ✓)
  • New cost: J=12(3.25)2=1.62J = \frac{1}{2}(3.2 - 5)^2 = 1.62 (less than 4.5 ✓)

Common Mistakes

Why it feels right: It seems logical to use the most recent value.

Why it's wrong: The gradient was computed assuming both parameters at their old values. Using a partially updated value corrupts the gradient direction.

Fix: Compute all gradients first, then update all parameters at once.

# Wrong
theta_0 = theta_0 - alpha * grad_0
theta_1 = theta_1 - alpha * grad_1  # Uses NEW theta_0 indirectly
 
# Right
temp_0 = theta_0 - alpha * grad_0
temp_1 = theta_1 - alpha * grad_1
theta_0 = temp_0
theta_1 = temp_1

Why it feels right: The derivation shows a sum, so just use the sum.

Why it's wrong: Without dividing by nn, your effective learning rate scales with dataset size. Adding more data would require shrinking α\alpha, making it non-transferable.

Fix: Always divide by nn: θj:=θjα1ni=1n(hθ(xi)yi)xi(j)\theta_j := \theta_j - \alpha \frac{1}{n} \sum_{i=1}^{n} (h_\theta(x_i) - y_i) \cdot x_i^{(j)}


Why it feels right: Seems like it would be faster than using all data.

Actually: This is stochastic gradient descent (SGD), not batch gradient descent. It's not wrong per se, but it's a different algorithm with different properties:

  • Batch GD: Uses all data, stable convergence, slower per iteration
  • SGD: Uses one point, noisy updates, faster per iteration, may not converge exactly

Both are valid; just know which you're using!


Why it happens: You're overshooting the minimum. Each update jumps to the opposite side of the valley.

Fix:

  1. Reduce α\alpha (try dividing by 10)
  2. Monitor cost per iteration—it should decrease monotonically in batch GD
  3. Use learning rate schedules or adaptive methods (Adam, RMSprop)

Visual: If plotting cost vs. iteration shows a jagged upward trend, α\alpha is too large.


Convergence Criteria

In practice, monitor the cost function. If it stops decreasing meaningfully, you've converged.


Batch vs. Stochastic vs. Mini-Batch

Method Update Uses Pros Cons
Batch GD All nn examples Stable, exact gradient Slow for large nn
Stochastic GD 1 random example Fast, online learning Noisy, may not converge exactly
Mini-batch GD bb examples (e.g., 32) Balanced speed/stability One more hyperparameter

Batch GD (what we derived): θj:=θjα1ni=1n(hθ(xi)yi)xi(j)\theta_j := \theta_j - \alpha \frac{1}{n} \sum_{i=1}^{n} (h_\theta(x_i) - y_i) x_i^{(j)}

Stochastic GD: θj:=θjα(hθ(xi)yi)xi(j)for a random i\theta_j := \theta_j - \alpha (h_\theta(x_i) - y_i) x_i^{(j)} \quad \text{for a random } i

Mini-batch GD: θj:=θjα1bibatch(hθ(xi)yi)xi(j)\theta_j := \theta_j - \alpha \frac{1}{b} \sum_{i \in \text{batch}} (h_\theta(x_i) - y_i) x_i^{(j)}


Feature Scaling Impact

Solution: Normalize features to similar scales (e.g., mean 0, std 1): xj(i):=xj(i)μjσjx_j^{(i)} := \frac{x_j^{(i)} - \mu_j}{\sigma_j}

This makes the cost function more circular/spherical, allowing gradient descent to converge faster with larger learning rates.


Recall Explain to a 12-year-old

Imagine you're trying to draw the best line through some dots on a graph. How do you know if your line is good? You measure how far each dot is from your line (that's the error). Then you add up all these errors—but you square them first so big mistakes count more than small ones. That total is your "cost." The smaller the cost, the better your line.

Now, how do you find the best line? You start with a random line. Then you look at which way you should tilt it to make the cost smaller—like rolling a ball downhill. You tilt it a little bit in that direction. Then you check again and tilt more. You keep doing this over and over until your line is so good that tilting it any more doesn't help. That's gradient descent—it's like teaching your line to walk downhill until it reaches the bottom of a valley, where the cost is lowest.

The "learning rate" is how big your steps are. Too big and you'll jump over the valley. Too small and you'll take forever to get there.


  • Measure: Compute J(θ)J(\theta) = how wrong you are
  • Squared: Errors are squared (big mistakes hurt more)
  • Errors: Difference between prediction and actual
  • Go: Move parameters in a direction
  • Downhill: Opposite of gradient (stepest descent)

Or think: "Mean Squared Errors Guide Descent"


Connections

  • 2.2.03-Hypothesis-representation-in-linear-regression — The hypothesis hθ(x)h_\theta(x) is what we're optimizing
  • 2.2.05-Normal-equation — Closed-form alternative to gradient descent
  • 2.06-Feature-scaling-and-normalization — Makes gradient descent converge faster
  • 2.3.02-Logistic-cost-function — Different cost function for classification
  • 2.4.01-Gradient-descent-for-neural-networks — Backpropagation extends this idea
  • 3.1.02-Convex-optimization — MSE is convex, guaranteing global minimum
  • 4.2.01-Stochastic-gradient-descent — Faster variant for large datasets
  • 4.2.03-Learning-rate-schedules — Adaptive strategies for α\alpha

#flashcards/ai-ml

What is the Mean Squared Error (MSE) cost function for linear regression? :: J(θ)=12ni=1n(hθ(xi)yi)2J(\theta) = \frac{1}{2n} \sum_{i=1}^{n} (h_\theta(x_i) - y_i)^2, where hθ(xi)h_\theta(x_i) is the prediction and yiy_i is the actual value. The 12n\frac{1}{2n} normalizes by dataset size and simplifies derivatives.

Why do we square the errors in MSE instead of using absolute values?
Squaring makes all errors positive, penalizes large errors more heavily (quadratic penalty), and creates a smooth, differentiable cost surface. Absolute values have a non-differentiable point at zero, making optimization harder.

What is the gradient descent update rule for a parameter θj\theta_j? :: θj:=θjαJ(θ)θj\theta_j := \theta_j - \alpha \frac{\partial J(\theta)}{\partial \theta_j}, where α\alpha is the learning rate and the partial derivative is the gradient (slope) of the cost function with respect to that parameter.

What is the gradient of MSE with respect to parameter θj\theta_j in linear regression?
J(θ)θj=1ni=1n(hθ(xi)yi)xi(j)\frac{\partial J(\theta)}{\partial \theta_j} = \frac{1}{n} \sum_{i=1}^{n} (h_\theta(x_i) - y_i) \cdot x_i^{(j)}, where xi(j)x_i^{(j)} is the jj-th feature of example ii (with xi(0)=1x_i^{(0)} = 1 for bias).
What is the learning rate α\alpha in gradient descent?
The learning rate is a hyperparameter controlling the step size in the direction opposite to the gradient. Too small means slow convergence; too large risks overshooting and divergence. Typical values: 0.001 to 1.
Why must gradient descent updates be simultaneous for all parameters?
Because the gradient is computed assuming all parameters are at their current (old) values. Updating one parameter first and then using that new value for the next update corrupts the gradient direction. Compute all new values, then update all at once.
What happens if the learning rate is too large in gradient descent?
The cost may increase or oscillate instead of decreasing. You overshoot the minimum, jumping from one side of the valley to the other without settling at the bottom.
What is the difference between batch, stochastic, and mini-batch gradient descent?
Batch GD uses all nn examples per update (stable, slow for large nn). Stochastic GD uses 1 random example (fast, noisy). Mini-batch GD uses bb examples (balanced). All minimize the same cost but with different update strategies.
What is a common convergence criterion for gradient descent?
Stop when the change in cost is smaller than a threshold: J(t)J(t1)<ϵ|J^{(t)} - J^{(t-1)}| < \epsilon (e.g., ϵ=106\epsilon = 10^{-6}), or when the gradient norm is near zero, or after a maximum number of iterations.
Why does feature scaling help gradient descent converge faster?
When features have very different ranges, the cost function becomes elongated (narrow valley). Gradient descent zigzags slowly. Scaling features to similar ranges (e.g., mean 0, std 1) makes the cost surface more circular, allowing faster, more direct convergence.
Derive the gradient Jθj\frac{\partial J}{\partial \theta_j} from the MSE cost function.
Start with J(θ)=12n(hθ(xi)yi)2J(\theta) = \frac{1}{2n} \sum (h_\theta(x_i) - y_i)^2. Apply chain rule: Jθj=12n2(hθ(xi)yi)hθ(xi)θj\frac{\partial J}{\partial \theta_j} = \frac{1}{2n} \sum 2(h_\theta(x_i) - y_i) \frac{\partial h_\theta(x_i)}{\partial \theta_j}. The 2 cancels 12\frac{1}{2}. Since hθ(xi)=θjxi(j)h_\theta(x_i) = \sum \theta_j x_i^{(j)}, we have hθθj=xi(j)\frac{\partial h_\theta}{\partial \theta_j} = x_i^{(j)}. Result: 1n(hθ(xi)yi)xi(j)\frac{1}{n} \sum (h_\theta(x_i) - y_i) x_i^{(j)}.

What does a negative gradient mean in gradient descent? :: A negative gradient means the cost decreases as the parameter increases, so we should increase the parameter. Since we subtract the gradient (θ:=θαnegative value\theta := \theta - \alpha \cdot \text{negative value}), we effectively add to θ\theta, moving it in the direction that reduces cost.

Concept Map

difference

sum cancels out

square errors

penalizes big errors

differentiable everywhere

average over n

add one half factor

generates

define

enables calculus

used by

updates

Predictions vs actual

Residual errors

Need better measure

Squared errors

MSE cost J theta

Smooth surface

Size independent cost

Cleaner gradient

Hypothesis h theta x

Parameters theta

Gradient descent

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho yaar, linear regression mein hum best-fit line dhoondte hain, lekin "best" ka matlab kya hai? Yahi problem MSE solve karta hai. Har prediction aur actual value ke beech jo error hota hai, usko hum square karke sum karte hain. Square isliye karte hain kyunki big mistakes ko zyada penalty milti hai (quadratic penalty), positive aur negative errors cancel nahi hote, aur function smooth ho jaata hai jise hum calculus se easily minimize kar sakte hain. Simple bolein toh MSE ek "wrongness meter" hai jo batata hai ki hamari line kitni galat predictions de rahi hai.

Ab MSE toh bata deta hai ki galat kitne ho, lekin usko sahi kaise karein? Yahaan aata hai gradient descent. Socho tum blindfold hoke ek pahaadi (cost function surface) pe khade ho aur sabse neeche wali valley tak pahunchna chahte ho. Tum feel karte ho ki kaunsi direction sabse zyada neeche slope kar rahi hai (yeh gradient hai), phir us direction mein ek chhota step lete ho (parameters update karte ho), aur yeh baar-baar repeat karte ho jab tak aur neeche na ja sako. Learning rate (alpha) tumhare step ki size decide karta hai — bahut bada toh tum valley cross kar jaoge, bahut chhota toh time zyada lagega.

Yeh cheez isliye important hai kyunki yahi poori machine learning ki foundation hai. MSE + gradient descent ka combo sirf linear regression tak seemit nahi hai — neural networks tak, sab jagah yahi core idea kaam karta hai: pehle apni galti measure karo, phir systematically usko kam karte jao. Agar tumne yeh intuition solid kar li, toh aage ke advanced topics tumhe bilkul natural lagenge, bas formula thoda complex ho jaayega but soch wahi rahegi.

Go deeper — visual, from zero

Test yourself — Linear & Logistic Regression

Connections