KatInterview

Minimize Squared Error: Deriving the OLS Slope and Intercept

Machine LearningModel answer
MediumModel answerMachine Learninglinear-regressioncalculusOLS

Last updated

Derive the closed-form least-squares estimators for a simple linear model by minimizing MSE, and reason through what breaks when input variance is zero.

Minimize Squared Error: Deriving the OLS Slope and Intercept

You have $n$ data points $(x_i, y_i)$. You model the relationship as

$$ y_i = \beta_0 + \beta_1 x_i + \epsilon_i $$

where each $\epsilon_i$ is drawn independently from a Gaussian distribution with mean $0$ and variance $\sigma^2$.

What you need to do

Part 1 — Write down the objective. Define the Mean Squared Error $J(\beta_0, \beta_1)$ that measures how well the line fits the data.

Part 2 — Solve for the optimal parameters. Take partial derivatives of $J$ with respect to $\beta_0$ and $\beta_1$, set them to zero, and solve for the values that minimize $J$. Show every algebraic step.

Part 3 — Restate the slope in statistical terms. Re-express your formula for $\beta_1$ using the covariance of $x$ and $y$ and the variance of $x$.

Requirements

  • Walk through the calculus step by step — don't skip to the answer.
  • You may assume $n > 1$ and that the $x_i$ values are not all the same.

Worked example to check your answer

For the three points $(1, 2),\ (2, 3),\ (3, 5)$:

  • $\bar{x} = 2$, $\quad \bar{y} \approx 3.33$
  • $\beta_1$ is the slope of the line with the smallest total squared vertical distance to these points.

Compute $\beta_0$ and $\beta_1$ explicitly and verify that the residuals sum to zero.

Edge case to address

What happens to your formula if every $x_i$ is the same value? Why does this cause a problem, and how should it be handled in practice?

Hints

Hint 1

Start by writing out the squared residual for a single point, then sum over all n points. Notice that dividing by n doesn't change where the minimum is, so you can treat MSE and SSE interchangeably when differentiating.

Hint 2

After you set ∂J/∂β₀ = 0, you'll get a clean expression for β₀ in terms of the two sample means. Substitute that expression into the ∂J/∂β₁ = 0 equation before you try to isolate β₁ — it makes the algebra much shorter.

Hint 3

To go from the raw sum formula to the Cov/Var form, notice that subtracting x̄ from the leading xᵢ in the numerator costs nothing because ∑(yᵢ − ȳ) = 0. The same trick applies to the denominator. Once both sums are centered, dividing numerator and denominator by n gives you exactly Cov(x,y)/Var(x).