Minimize Squared Error: Deriving the OLS Slope and Intercept
Machine LearningModel answerLast 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).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Step-by-step derivation
1. The objective function
The residual at point $i$ is $r_i = y_i - \beta_0 - \beta_1 x_i$. Squaring and averaging:
$$ J(\beta_0, \beta_1) = \frac{1}{n} \sum_{i=1}^{n} \left(y_i - \beta_0 - \beta_1 x_i\right)^2 $$
The $1/n$ scales every value equally, so it has no effect on which $(\beta_0, \beta_1)$ minimizes $J$. The derivation below drops it where convenient and works with the sum of squared errors (SSE) instead.
2. Solving for $\beta_0$
Differentiate with respect to $\beta_0$ (applying the chain rule, the inner derivative is $-1$):
$$ \frac{\partial J}{\partial \beta_0} = -\frac{2}{n} \sum_{i=1}^{n} \left(y_i - \beta_0 - \beta_1 x_i\right) = 0 $$
Expanding the sum:
$$ \sum y_i - n\beta_0 - \beta_1 \sum x_i = 0 $$
Dividing through by $n$:
$$ \boxed{\beta_0 = \bar{y} - \beta_1 \bar{x}} $$
Two immediate consequences worth stating aloud:
- The optimal line always passes through the centroid $(\bar{x}, \bar{y})$.
- Setting this derivative to zero forces the residuals to sum to zero — this holds for any model that includes an intercept.
3. Solving for $\beta_1$
Differentiate with respect to $\beta_1$ (the inner derivative is now $-x_i$):
$$ \frac{\partial J}{\partial \beta_1} = -\frac{2}{n} \sum_{i=1}^{n} x_i \left(y_i - \beta_0 - \beta_1 x_i\right) = 0 $$
Substitute $\beta_0 = \bar{y} - \beta_1 \bar{x}$ to eliminate $\beta_0$:
$$ \sum_{i=1}^{n} x_i \left[\left(y_i - \bar{y}\right) - \beta_1 \left(x_i - \bar{x}\right)\right] = 0 $$
Isolate $\beta_1$:
$$ \beta_1 = \frac{\sum x_i (y_i - \bar{y})}{\sum x_i (x_i - \bar{x})} $$
Centering the numerator and denominator. Because $\sum(y_i - \bar{y}) = 0$, subtracting $\bar{x}$ from the leading $x_i$ in the numerator adds exactly zero:
$$ \sum x_i(y_i - \bar{y}) = \sum (x_i - \bar{x})(y_i - \bar{y}) $$
The same identity applies to the denominator:
$$ \sum x_i(x_i - \bar{x}) = \sum (x_i - \bar{x})^2 $$
So the closed-form slope is:
$$ \boxed{\beta_1 = \frac{\sum_{i=1}^{n}(x_i - \bar{x})(y_i - \bar{y})}{\sum_{i=1}^{n}(x_i - \bar{x})^2}} $$
4. Covariance / variance form
Divide numerator and denominator by the same $n$ (or both by $n-1$; the choice must match):
$$ \boxed{\beta_1 = \frac{\operatorname{Cov}(x, y)}{\operatorname{Var}(x)}}, \qquad \beta_0 = \bar{y} - \beta_1\bar{x} $$
An equivalent way to write this is $\beta_1 = r_{xy} \cdot s_y / s_x$: correlation scaled by the ratio of standard deviations. The slope is in units of $y$ per unit of $x$.
5. Confirming this is a minimum
The Hessian of SSE is:
$$ H = 2 \begin{pmatrix} n & \sum x_i \ \sum x_i & \sum x_i^2 \end{pmatrix} $$
Its determinant is $4\bigl(n \sum x_i^2 - (\sum x_i)^2\bigr) = 4n \sum(x_i - \bar{x})^2$. When $\operatorname{Var}(x) > 0$, the determinant is positive and the top-left entry $2n$ is positive, so $H$ is positive definite. The SSE is strictly convex, and the stationary point is the unique global minimum. Strong candidates mention this check without being prompted.
6. Worked example
Data: $(1, 2),\ (2, 3),\ (3, 5)$.
| quantity | value |
|---|---|
| $\bar{x}$ | $2$ |
| $\bar{y}$ | $10/3 \approx 3.33$ |
| $S_{xy} = \sum(x_i-\bar{x})(y_i-\bar{y})$ | $(-1)(-4/3) + 0 + (1)(5/3) = 3$ |
| $S_{xx} = \sum(x_i-\bar{x})^2$ | $1 + 0 + 1 = 2$ |
| $\beta_1$ | $3/2 = 1.5$ |
| $\beta_0$ | $10/3 - 1.5 \times 2 = 1/3 \approx 0.33$ |
Fitted line: $\hat{y} = 0.33 + 1.5x$.
Predictions: $1.83,\ 3.33,\ 4.83$. Residuals: $+0.17,\ -0.33,\ +0.17$. Their sum is $0.01 \approx 0$ (rounding error), confirming the theory.
7. Edge case: zero input variance
If every $x_i = c$, then $\sum(x_i - \bar{x})^2 = 0$ and the slope formula produces $0/0$.
- The two normal equations become linearly dependent — the $\beta_1$ equation is just $c$ times the $\beta_0$ equation.
- Any $(\beta_0, \beta_1)$ satisfying $\beta_0 + \beta_1 c = \bar{y}$ achieves the same minimum SSE. The slope is not identifiable.
- The Hessian is singular: $J$ is convex but not strictly so.
In practice: the pseudo-inverse returns the minimum-norm solution; Ridge regularization pins $\beta_1 = 0$ and $\beta_0 = \bar{y}$; or simply report that the slope is undefined. Near-zero variance is the continuous version of this problem — the slope variance is $\sigma^2 / \sum(x_i - \bar{x})^2$, which blows up as spread shrinks.
8. Common mistakes
- Missing the chain-rule factor $-x_i$ when differentiating with respect to $\beta_1$.
- Skipping the centering justification. Writing $\sum x_i(y_i - \bar{y}) = \sum(x_i - \bar{x})(y_i - \bar{y})$ requires explicitly noting that $\sum(y_i - \bar{y}) = 0$.
- Mixing normalization conventions — dividing one sum by $n$ and the other by $n-1$ introduces an off-by-$n/(n-1)$ error in $\beta_1$.
- Claiming Gaussian noise is required for OLS. It is not. The derivation above uses no distributional assumption. The Gaussian assumption matters for MLE equivalence and for exact inference (t-tests, F-tests); OLS as an estimator only needs finite variance.
- Never checking the second-order condition. Showing that the stationary point is a minimum — not just a critical point — is part of a complete answer.
Follow-up: MLE agrees with OLS under Gaussian noise
Under $y_i \sim \mathcal{N}(\beta_0 + \beta_1 x_i, \sigma^2)$, the log-likelihood is
$$ \ell = -\frac{n}{2}\log(2\pi\sigma^2) - \frac{1}{2\sigma^2}\sum(y_i - \beta_0 - \beta_1 x_i)^2 $$
For fixed $\sigma^2$, maximizing $\ell$ over $\beta$ is exactly minimizing SSE, so the MLE of $\beta$ equals the OLS solution. The noise MLE is $\hat\sigma^2 = \text{SSE}/n$, which is biased; the unbiased correction divides by $n - 2$ because two parameters were estimated.
Follow-up: when does gradient descent beat the closed form?
For one feature the closed form costs $O(n)$, so there is no reason to prefer gradient descent. In the multivariate case the normal equations cost $O(nd^2 + d^3)$. Prefer iterative methods when $d$ is large (tens of thousands or more), data arrives as a stream, or the loss has no closed form (Lasso, logistic regression, neural networks). When inverting $X^\top X$ is numerically fragile, use QR or SVD factorization rather than explicit inversion.