{"course":{"slug":"maths-you-need","title":"The Maths You Actually Need","url":"https://addaly.com/learn/maths-you-need","level":"intermediate","track":"deep"},"lesson":{"slug":"least-squares-and-the-normal-equations","title":"The best fit, and what \"best\" was defined to mean","url":"https://addaly.com/learn/maths-you-need/least-squares-and-the-normal-equations","position":15,"of":76,"minutes":9,"answer":"Least squares finds the point in the space your model can reach that is closest to the data, and it does so by making the residual perpendicular to everything the model can represent.","keyIdea":"Least squares finds the point in the space your model can reach that is closest to the data, and it does so by making the residual perpendicular to everything the model can represent."},"body":{"format":"markdown","text":"## The problem with no exact answer\n\nYou have 500 houses, four features each, and one price. You want `X w = y`, where X is 500×4 and w is the four coefficients you are looking for. There are 500 equations and 4 unknowns. Unless the data is astonishingly obliging, no `w` satisfies all 500. There is no exact answer.\n\nSo you settle for the closest one, and the definition of \"closest\" is a choice. Least squares chooses to minimise the sum of squared residuals:\n\n```\nminimise  ||X w - y||^2  =  sum over rows of (prediction - actual)^2\n```\n\nThat is a decision, not a law. Choosing squares rather than absolute values means one house that is ₹50 lakh out counts as much as a hundred houses ₹5 lakh out, because 50² = 2,500 and 100 × 5² = 2,500. Whether that is right depends on whether one big mistake is as bad as a hundred small ones for your purpose. Frequently it is not, and that is the argument for absolute-error regression instead.\n\n## The geometry, which makes the formula obvious\n\nHere is the picture worth carrying. `X w`, as w varies over all possibilities, traces out the column space of X: a 4-dimensional flat surface sitting inside 500-dimensional space. Your target `y` is a point in that 500-dimensional space, and almost certainly not on the surface.\n\nThe closest point on a flat surface to an outside point is found by dropping a perpendicular. So the best `Xw` is the **projection** of y onto the column space, and the residual `y − Xw` must be perpendicular to that surface, which means perpendicular to every column of X:\n\n```\nX^T (y - X w) = 0\n```\n\nRearrange:\n\n```\nX^T X w = X^T y            <- the normal equations\nw = (X^T X)^-1 X^T y       <- the closed form\n```\n\nThat is the whole derivation, and it comes from one geometric fact: the error must be orthogonal to everything the model could have produced. The word \"normal\" in \"normal equations\" means perpendicular, not typical.\n\n## Worked, small\n\nFit `y = w x` through three points (1, 2), (2, 4.1), (3, 5.8), no intercept.\n\n```\nX = [1; 2; 3]        y = [2; 4.1; 5.8]\nX^T X = 1 + 4 + 9 = 14\nX^T y = 1*2 + 2*4.1 + 3*5.8 = 2 + 8.2 + 17.4 = 27.6\nw = 27.6 / 14 = 1.971\n```\n\nPredictions: 1.971, 3.943, 5.914. Residuals: +0.029, +0.157, −0.114. Their dot product with the column `[1, 2, 3]` is `0.029 + 0.314 − 0.343 = 0`, up to rounding. The residual is perpendicular to the column space. The geometry is not a metaphor.\n\n## What to run in practice\n\nDo not code the closed form. Use `np.linalg.lstsq`, which solves it via QR decomposition or SVD, is numerically far better behaved, and works even when `X^T X` is singular:\n\n```python\nimport numpy as np\nw, residuals, rank, sv = np.linalg.lstsq(X, y, rcond=None)\n```\n\nNote what it returns alongside the answer: the rank of X and its singular values. Those tell you whether your features were linearly dependent, which is the failure the closed form hides.\n\n## Reading R-squared without being fooled\n\nThe standard summary statistic is\n\n```\nR^2 = 1 - (sum of squared residuals) / (sum of squared deviations from the mean of y)\n```\n\nIt says what fraction of the variance in y your model accounts for, compared with predicting the mean every time. R² = 0 means you did no better than the mean; R² = 1 means perfect fit.\n\nTwo honest warnings. First, R² never decreases when you add a feature, even a column of random numbers, so comparing models by R² always favours the bigger one. Adjusted R² penalises this, imperfectly. Second, R² is computed on the data you fitted; the only version worth quoting is computed on data the model has not seen.\n\n## The assumptions you have quietly made\n\nLeast squares always returns an answer, so it is worth naming what has to be true for the answer to be meaningful.\n\n- **Linearity.** You have assumed y is a straight-line function of the features. Fit a line through a curve and you get a line, with no complaint from the arithmetic.\n- **Independent errors.** With time-series data, consecutive residuals are usually correlated, and the coefficient standard errors will be too small: your significance tests become overconfident.\n- **Roughly constant error size.** If the errors grow with the prediction, as they do for prices and counts, the fit is dominated by the large end. Taking logs of the target often fixes this in one line.\n- **No influential outliers.** Squaring makes a single wild point capable of dragging the whole fit. Always plot residuals against predictions; the plot shows all four of these problems and takes ten seconds.\n\n## The rule to keep\n\nLeast squares projects your data onto what your model can represent, and calls the perpendicular distance the error. If your model cannot represent the truth, the projection is still computed, still optimal, and still wrong: optimality is relative to a model class you chose."},"check":{"question":"A least-squares fit gives the residual vector r. Which statement about r is guaranteed by the way the solution was derived?","options":[{"text":"The residuals sum to exactly zero.","correct":false,"tempting":"True only when the model includes an intercept column; with no intercept the residuals need not sum to zero at all."},{"text":"The dot product of r with every column of X is zero, because the solution is defined as the point whose residual is perpendicular to the column space.","correct":true},{"text":"The residuals are normally distributed, since least squares assumes normal errors.","correct":false,"tempting":"Normality is an assumption used for confidence intervals and tests, not something the fitting procedure produces or guarantees."},{"text":"The residuals are all smaller in magnitude than they would be under any other coefficient vector.","correct":false,"tempting":"Least squares minimises the sum of squares, not every individual residual; another fit can beat it on any particular point."}]},"prev":{"slug":"determinants-and-volume","title":"The determinant, and what it says about collapse","url":"https://addaly.com/learn/maths-you-need/determinants-and-volume"},"next":{"slug":"rank-and-low-rank","title":"Rank, and why a huge matrix can be two small ones","url":"https://addaly.com/learn/maths-you-need/rank-and-low-rank"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'The best fit, and what \"best\" was defined to mean', in The Maths You Actually Need. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/maths-you-need/least-squares-and-the-normal-equations (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"The best fit, and what “best” was defined to mean","courseTitle":"The Maths You Actually Need","module":{"index":2,"slug":"matrices-and-layers","title":"Matrices, and what a layer really does"},"answer":null,"keyIdea":"Least squares finds the point in the space your model can reach that is closest to the data, and it does so by making the residual perpendicular to everything the model can represent.","hero":{"kind":"plate","image":"https://addaly.com/art/modules/maths-you-need/matrices-and-layers.webp","alt":"Three blocks of cells joined by arrows: a narrow column, a large square grid and a single tall bar.","caption":"A column of values entering a grid of weights and leaving as a shorter column, in that order: the shape change is what a layer does, and the grid’s rank decides whether two small matrices could stand in for it."},"blocks":[{"t":"h2","id":"the-problem-with-no-exact-answer","runs":[{"text":"The problem with no exact answer"}]},{"t":"p","runs":[{"text":"You have 500 houses, four features each, and one price. You want "},{"text":"X w = y","code":true},{"text":", where X is 500×4 and w is the four coefficients you are looking for. There are 500 equations and 4 unknowns. Unless the data is astonishingly obliging, no "},{"text":"w","code":true},{"text":" satisfies all 500. There is no exact answer."}]},{"t":"p","runs":[{"text":"So you settle for the closest one, and the definition of “closest” is a choice. Least squares chooses to minimise the sum of squared residuals:"}]},{"t":"code","lang":"","label":"Text","text":"minimise  ||X w - y||^2  =  sum over rows of (prediction - actual)^2"},{"t":"p","runs":[{"text":"That is a decision, not a law. Choosing squares rather than absolute values means one house that is ₹50 lakh out counts as much as a hundred houses ₹5 lakh out, because 50² = 2,500 and 100 × 5² = 2,500. Whether that is right depends on whether one big mistake is as bad as a hundred small ones for your purpose. Frequently it is not, and that is the argument for absolute-error regression instead."}]},{"t":"h2","id":"the-geometry-which-makes-the-formula-obvious","runs":[{"text":"The geometry, which makes the formula obvious"}]},{"t":"p","runs":[{"text":"Here is the picture worth carrying. "},{"text":"X w","code":true},{"text":", as w varies over all possibilities, traces out the column space of X: a 4-dimensional flat surface sitting inside 500-dimensional space. Your target "},{"text":"y","code":true},{"text":" is a point in that 500-dimensional space, and almost certainly not on the surface."}]},{"t":"p","runs":[{"text":"The closest point on a flat surface to an outside point is found by dropping a perpendicular. So the best "},{"text":"Xw","code":true},{"text":" is the "},{"text":"projection","b":true},{"text":" of y onto the column space, and the residual "},{"text":"y − Xw","code":true},{"text":" must be perpendicular to that surface, which means perpendicular to every column of X:"}]},{"t":"code","lang":"","label":"Text","text":"X^T (y - X w) = 0"},{"t":"p","runs":[{"text":"Rearrange:"}]},{"t":"code","lang":"","label":"Text","text":"X^T X w = X^T y            <- the normal equations\nw = (X^T X)^-1 X^T y       <- the closed form"},{"t":"p","runs":[{"text":"That is the whole derivation, and it comes from one geometric fact: the error must be orthogonal to everything the model could have produced. The word “normal” in “normal equations” means perpendicular, not typical."}]},{"t":"h2","id":"worked-small","runs":[{"text":"Worked, small"}]},{"t":"p","runs":[{"text":"Fit "},{"text":"y = w x","code":true},{"text":" through three points (1, 2), (2, 4.1), (3, 5.8), no intercept."}]},{"t":"code","lang":"","label":"Text","text":"X = [1; 2; 3]        y = [2; 4.1; 5.8]\nX^T X = 1 + 4 + 9 = 14\nX^T y = 1*2 + 2*4.1 + 3*5.8 = 2 + 8.2 + 17.4 = 27.6\nw = 27.6 / 14 = 1.971"},{"t":"p","runs":[{"text":"Predictions: 1.971, 3.943, 5.914. Residuals: +0.029, +0.157, −0.114. Their dot product with the column "},{"text":"[1, 2, 3]","code":true},{"text":" is "},{"text":"0.029 + 0.314 − 0.343 = 0","code":true},{"text":", up to rounding. The residual is perpendicular to the column space. The geometry is not a metaphor."}]},{"t":"h2","id":"what-to-run-in-practice","runs":[{"text":"What to run in practice"}]},{"t":"p","runs":[{"text":"Do not code the closed form. Use "},{"text":"np.linalg.lstsq","code":true},{"text":", which solves it via QR decomposition or SVD, is numerically far better behaved, and works even when "},{"text":"X^T X","code":true},{"text":" is singular:"}]},{"t":"code","lang":"python","label":"Python","text":"import numpy as np\nw, residuals, rank, sv = np.linalg.lstsq(X, y, rcond=None)"},{"t":"p","runs":[{"text":"Note what it returns alongside the answer: the rank of X and its singular values. Those tell you whether your features were linearly dependent, which is the failure the closed form hides."}]},{"t":"h2","id":"reading-r-squared-without-being-fooled","runs":[{"text":"Reading R-squared without being fooled"}]},{"t":"p","runs":[{"text":"The standard summary statistic is"}]},{"t":"code","lang":"","label":"Text","text":"R^2 = 1 - (sum of squared residuals) / (sum of squared deviations from the mean of y)"},{"t":"p","runs":[{"text":"It says what fraction of the variance in y your model accounts for, compared with predicting the mean every time. R² = 0 means you did no better than the mean; R² = 1 means perfect fit."}]},{"t":"p","runs":[{"text":"Two honest warnings. First, R² never decreases when you add a feature, even a column of random numbers, so comparing models by R² always favours the bigger one. Adjusted R² penalises this, imperfectly. Second, R² is computed on the data you fitted; the only version worth quoting is computed on data the model has not seen."}]},{"t":"h2","id":"the-assumptions-you-have-quietly-made","runs":[{"text":"The assumptions you have quietly made"}]},{"t":"p","runs":[{"text":"Least squares always returns an answer, so it is worth naming what has to be true for the answer to be meaningful."}]},{"t":"ul","items":[[{"text":"Linearity.","b":true},{"text":" You have assumed y is a straight-line function of the features. Fit a line through a curve and you get a line, with no complaint from the arithmetic."}],[{"text":"Independent errors.","b":true},{"text":" With time-series data, consecutive residuals are usually correlated, and the coefficient standard errors will be too small: your significance tests become overconfident."}],[{"text":"Roughly constant error size.","b":true},{"text":" If the errors grow with the prediction, as they do for prices and counts, the fit is dominated by the large end. Taking logs of the target often fixes this in one line."}],[{"text":"No influential outliers.","b":true},{"text":" Squaring makes a single wild point capable of dragging the whole fit. Always plot residuals against predictions; the plot shows all four of these problems and takes ten seconds."}]]},{"t":"h2","id":"the-rule-to-keep","runs":[{"text":"The rule to keep"}]},{"t":"p","runs":[{"text":"Least squares projects your data onto what your model can represent, and calls the perpendicular distance the error. If your model cannot represent the truth, the projection is still computed, still optimal, and still wrong: optimality is relative to a model class you chose."}]}],"check":{"question":[{"text":"A least-squares fit gives the residual vector r. Which statement about r is guaranteed by the way the solution was derived?"}],"options":[{"text":[{"text":"The residuals sum to exactly zero."}],"correct":false,"tempting":[{"text":"True only when the model includes an intercept column; with no intercept the residuals need not sum to zero at all."}]},{"text":[{"text":"The dot product of r with every column of X is zero, because the solution is defined as the point whose residual is perpendicular to the column space."}],"correct":true,"tempting":null},{"text":[{"text":"The residuals are normally distributed, since least squares assumes normal errors."}],"correct":false,"tempting":[{"text":"Normality is an assumption used for confidence intervals and tests, not something the fitting procedure produces or guarantees."}]},{"text":[{"text":"The residuals are all smaller in magnitude than they would be under any other coefficient vector."}],"correct":false,"tempting":[{"text":"Least squares minimises the sum of squares, not every individual residual; another fit can beat it on any particular point."}]}],"order":[3,0,1,2],"why":null},"prev":{"slug":"determinants-and-volume","title":"The determinant, and what it says about collapse","minutes":8},"next":{"slug":"rank-and-low-rank","title":"Rank, and why a huge matrix can be two small ones","minutes":9}}}