~/blog

Cost Function in Linear Regression

Jun 25, 20266 min readBy Mohammed Vasim
Machine LearningAIData Science

You've computed two possible slopes — and — and both give different prediction errors. How do you compare them? You need a single number that tells you which set of weights is better. That number is the cost, and the way it changes as you adjust the weights defines the terrain the optimizer must cross.

This terrain is not just any landscape — for linear regression it's a perfect bowl. No local minima, no plateaus, no saddle points. Understanding why it's a bowl is what gives you confidence that every optimization method in this series — OLS, gradient descent — will converge to the same unique best answer.

From Loss to Cost

A loss function measures error for a single sample: .

A cost function averages that loss over all training samples:

This is the Mean Squared Error (MSE). Some textbooks use to cancel the factor of 2 from the derivative — this changes the scale but not the minimizer.

Why MSE and not MAE? MSE is differentiable everywhere. MAE has a non-differentiable kink at zero. Differentiability is what allows gradient descent and the OLS closed form to work.

Anchor dataset: , . True OLS solution: , .

MSE for Three Candidate Models

Hold fixed and vary to see how MSE changes:

(under-estimating the slope):

Predictions:

Residuals:

SSE ≈ 120,000. MSE ≈ 20,000.

(optimal slope):

Predictions:

Residuals:

SSE = 133.3. MSE = 22.2.

(over-estimating the slope):

Predictions:

Residuals:

SSE ≈ 120,000. MSE ≈ 20,000.

The minimum at gives MSE = 22.2. Deviating in either direction increases MSE rapidly — the parabola is steep.

w₁ (slope) MSE 0.05 0.10 0.15 0.20 0.25 0 5k 10k 15k 20k w₁=0.20 MSE=22.2 MSE(w₁) — bowl shape ↓ gradient descent converges here

The Full Loss Surface — 3D View (Both and )

When you free both parameters, the cost function is a paraboloid — a bowl that curves upward in every direction from a single minimum at .

MSE Surface: J(w₀, w₁) minimum w₀=53.33, w₁=0.20 w₀ w₁ MSE contour rings

This shape is guaranteed because MSE is a sum of squares — quadratic in . A quadratic has exactly one minimum for linear regression. That's what makes gradient descent safe here: no local minima to get trapped in.

Why MSE Is Convex — The Key Property

A function is convex if for all .

MSE is quadratic in , so its Hessian is . If has full column rank (no redundant features), is positive definite — meaning the surface curves upward in every direction — and MSE is strictly convex with a unique global minimum.

Practical implication: gradient descent on MSE with linear regression will always converge to the optimal weights, regardless of starting point or step size (as long as the step size is small enough).

Cost Functions for Other Scenarios

NameFormulaWhen to Use
MSE (L2 Loss)Standard regression; penalizes outliers heavily
MAE (L1 Loss)Regression with outliers; robust but not differentiable
Huber LossQuadratic for , linear beyondBest of both: robust + differentiable
RMSESame minimum as MSE; interpretable in original units

Computing MAE and RMSE at the optimal weights:

Residuals:

RMSE and MAE are close here (4.71 vs 4.43, ratio ≈ 1.06) because the residuals are uniform — only two distinct values: 3.3 and 6.7. When a model has a few large outlier-driven errors, this ratio grows significantly.

Plotting the Loss Curve

python
import numpy as np
import matplotlib.pyplot as plt

X = np.array([650, 850, 1100, 1400, 1600, 1900])
y = np.array([180, 220, 280, 340, 370, 430])
w0 = 53.33

w1_values = np.linspace(0.05, 0.35, 100)
mse_values = [np.mean((y - (w0 + w1 * X)) ** 2) for w1 in w1_values]

plt.plot(w1_values, mse_values)
plt.axvline(x=0.20, color='red', linestyle='--', label='Optimal w₁=0.20')
plt.xlabel('w₁ (slope)')
plt.ylabel('MSE')
plt.title('Loss Landscape — MSE vs w₁')
plt.legend()
plt.show()
text
# Output: parabola curve with minimum at w₁=0.20, MSE≈22.2
# Steep rise in both directions confirms unique global minimum

MSE Trace at the Optimal Weights

650180183.3−3.310.9
850220223.3−3.310.9
1100280273.36.744.9
1400340333.36.744.9
1600370373.3−3.310.9
1900430433.3−3.310.9
SSE133.3
MSE22.2

The bowl shape is specific to linear regression with MSE. The moment you wrap the linear output in a sigmoid (logistic regression) or stack it in multiple layers (neural networks), the loss landscape gains saddle points — regions where the gradient is zero but the point is not a minimum. Gradient descent is no longer guaranteed to find the global optimum; it finds a good local one, which in practice is usually sufficient but theoretically weaker.

A common trap is assuming MSE is always the right cost because it's differentiable. MAE is not differentiable at zero, but that doesn't mean you can't minimize it — subgradient methods and coordinate descent handle the kink. The practical choice between them comes down to outlier tolerance. In this series we use MSE because it gives us the clean OLS closed form, but on real data with significant outliers, Huber loss splits the difference: quadratic for small errors, linear for large ones.

Test Your Understanding

  1. For (holding ), compute the MSE manually by listing each residual and squaring it. Verify it's approximately 20,000.

  2. The Hessian of MSE is . For the 1-feature anchor, compute (a 2×2 matrix with the bias column included) and verify it's positive definite.

  3. Why does MSE penalize outliers more than MAE? Sketch two error scenarios — one with uniform small errors, one with one large error — and compare MSE vs MAE for each.

  4. If you use instead of , does the optimal and change? Does the gradient change?

  5. Huber loss transitions from quadratic to linear at . What would the loss curve shape look like as a function of ? Would it still have a unique minimum?

Comments (0)

No comments yet. Be the first to comment!

Leave a comment