Least squares objective
Quick answer
Ordinary least squares (OLS) chooses the coefficients of a linear prediction rule to minimize the sum of squared residuals on the training rows. A residual is observed target minus predicted target. Squaring prevents cancellation of positive and negative errors and makes large deviations count more. For a fixed nonempty dataset, minimizing mean squared error (MSE) gives the same minimizer as minimizing sum of squared errors (SSE). All code examples run locally in Python 3.13.5; library examples use scikit-learn 1.8.0 or NumPy 2.3.5. ByteMind package execution is unverified.
Compare two candidate lines
x = [0, 1, 2, 3]y = [1, 4, 5, 8]for b, w in [(0, 2), (1, 2)]: errors = [v - (b + w*t) for t, v in zip(x, y)] print(errors, sum(e*e for e in errors))Expected output:
[1, 2, 1, 2] 10[0, 1, 0, 1] 2The second line has lower SSE, but comparing only two candidates does not establish optimality.
How it works
For n paired observations, let e_i = y_i - yhat_i. SSE = sum(e_i**2), MSE = SSE/n. For a line yhat = b + wx, b and w are parameters. The derivative of SSE with respect to b is -2sum(e_i); its derivative with respect to w is -2sum(x_ie_i). At an unconstrained OLS optimum both vanish. In matrix form the objective is ||y - A beta||², with A the design matrix (rows are observations; columns are features plus a column of ones when using an intercept). The objective is convex in beta; a minimizer need not be unique if columns are dependent. Squaring changes the influence of large residuals: an error of 4 contributes 16, not twice the contribution of an error of 2. SSE has squared target units; RMSE restores the target units. The objective describes in-sample fit, not a promise about unseen rows.
Squared error versus cancellation
from sklearn.metrics import mean_squared_errory = [3, 7, 5]p = [1, 9, 5]print(sum(a-b for a,b in zip(y,p)))print(round(mean_squared_error(y,p), 6))Expected output:
02.666667Signed errors cancel but mean squared error remains positive.
Common mistakes
Do not sum signed residuals as a loss: [3,-3] sums to zero but SSE is 18. Also do not choose parameters using test loss; reserve it for evaluation after selection.
Practice and next steps
For observed [3, 7] and predictions [4, 5], calculate the two residuals, SSE and MSE. Then compare with predictions [2, 8]. Complete the chapter knowledge check and coding exercise. Next: Simple regression by hand.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Least squares objective — knowledge check
Apply least squares objective to small regression fixtures.
What does OLS minimize?
Observed 8, predicted 5: what is the residual?
Residuals 2 and -2 give which SSE?
For a fixed nonempty dataset, which objective shares the OLS minimizer?
Does low training SSE prove good generalization?