Cost function (MSE) and gradient descent fitting
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.

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
Where:
- = cost function (what we want to minimize)
- = parameters (weights and bias: )
- for simple linear regression
- The is a convenience factor that cancels when we take derivatives
Derivation from first principles
Why do we need a cost function? We have training examples . Our hypothesis makes predictions . Each prediction has an error: .
Step 1: Measure total error Sum of errors: won't work (positive and negative cancel) Sum of absolute errors: works but isn't differentiable at zero
Step 2: Square the errors
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
Why this step? Dividing by 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 factor
Why this step? When we take the derivative, the power rule brings down a factor of 2 from squaring, which cancels the . 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 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)
Where:
- means "update to"
- is the learning rate (step size)
- is the partial derivative (slope) with respect to parameter
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:
For simple linear regression, .
Take the derivative with respect to :
Why this step? We need to know how much a small change in changes the cost.
Step 3: Apply chain rule
Why this step? Chain rule: derivative of is . Here .
The 2 cancels with :
Step 4: Compute
For (bias/intercept):
For (slope):
In general, for : where is the -th feature of example (with for the bias term).
Step 5: Final gradient
Update all parameters simultaneously:
Simultaneous means: compute all new values using the old values, then update all at once.
The Learning Rate
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: . Often found by trial and error or adaptive methods.
The gradient tells you the direction; tells you how far to go.
Worked Examples
Goal: Fit using gradient descent.
Initialize: , learning rate
Iteration 1:
-
Compute predictions:
-
Compute errors (residuals):
-
Compute cost:
-
Compute gradients: Why this step? Each error is multiplied by for the bias term.
Why this step? Each error is multiplied by the corresponding value.
-
Update parameters:
Why this step? We move in the direction opposite to the gradient (downhill).
Iteration 2 (using new ):
-
Predictions:
-
Errors:
-
Cost:
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
- Error:
Step 2: Compute cost
Step 3: Compute gradient
Why is it negative? Our prediction (2) is less than the actual (5). The error is negative. When multiplied by , we get -6. This negative gradient tells us: increase to make better predictions.
Step 4: Update (with )
Why this step? Subtracting a negative gradient means adding, so increases, which will increase our predictions (moving from 2 toward 5).
Verification:
- New prediction: (closer to 5 ✓)
- New cost: (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_1Why it feels right: The derivation shows a sum, so just use the sum.
Why it's wrong: Without dividing by , your effective learning rate scales with dataset size. Adding more data would require shrinking , making it non-transferable.
Fix: Always divide by :
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:
- Reduce (try dividing by 10)
- Monitor cost per iteration—it should decrease monotonically in batch GD
- Use learning rate schedules or adaptive methods (Adam, RMSprop)
Visual: If plotting cost vs. iteration shows a jagged upward trend, 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 examples | Stable, exact gradient | Slow for large |
| Stochastic GD | 1 random example | Fast, online learning | Noisy, may not converge exactly |
| Mini-batch GD | examples (e.g., 32) | Balanced speed/stability | One more hyperparameter |
Batch GD (what we derived):
Stochastic GD:
Mini-batch GD:
Feature Scaling Impact
Solution: Normalize features to similar scales (e.g., mean 0, std 1):
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 = 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 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
#flashcards/ai-ml
What is the Mean Squared Error (MSE) cost function for linear regression? :: , where is the prediction and is the actual value. The normalizes by dataset size and simplifies derivatives.
Why do we square the errors in MSE instead of using absolute values?
What is the gradient descent update rule for a parameter ? :: , where 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 in linear regression?
What is the learning rate in gradient descent?
Why must gradient descent updates be simultaneous for all parameters?
What happens if the learning rate is too large in gradient descent?
What is the difference between batch, stochastic, and mini-batch gradient descent?
What is a common convergence criterion for gradient descent?
Why does feature scaling help gradient descent converge faster?
Derive the gradient from the MSE cost function.
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 (), we effectively add to , moving it in the direction that reduces cost.
Concept Map
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.