Use symbolic linear algebraLesson 36 of 48 · 9 min
Fit a small line exactly
Solve a least-squares problem and verify the residual’s orthogonality condition.
Maths refresher: Residuals and squared error
A residual is observed minus fitted. Least squares minimises the total of their squares rather than requiring each residual to vanish.
If three points do not lie exactly on one line, a two-parameter line generally leaves nonzero residuals.
An overdetermined linear system may have no exact solution. Least squares chooses coefficients that minimise the sum of squared residuals. For independent columns, the normal equations set A transpose times the residual to zero.
Use an exact, invented three-point example to keep the geometry inspectable. The coefficient order is intercept then slope. The fitted values need not equal every observation, but the residual vector should be orthogonal to each design column.
The normal-equation solve here is an educational exact calculation. For floating-point data, QR or SVD approaches usually provide better numerical behaviour. A fitted line does not itself establish causation, measurement quality or predictive uncertainty; those require a separate data and model analysis.
Must every residual be zero at a least-squares solution?
Write a prediction (optional)
Exact fit to invented observations
Select Run Python with the code unchanged.
Your saved draft is open. To use the published code, select Restore example in Tools. Use Recover draft to bring back your code.
Tools
About Python
Python and the course packages can load while you read. Each run starts with fresh user variables; imported modules stay loaded. Stop replaces the worker. Runtime details ↗
Ctrl+Enter or ⌘+Enter runs Python.
Execution error
Technical error details
Your result
Python text output
Compare with the worked example
Executed from the published Python during the site build. Your own run appears above. Build environment ↗
Worked text output
Intercept and slope: Matrix([[7/6], [1/2]]) Observed minus fitted: Matrix([[-1/6], [1/3], [-1/6]]) Orthogonality check: Matrix([[0], [0]]) Squared error: 1/6
Read the starter result
The Observed minus fitted residual can be nonzero while the Orthogonality check is zero. Squared error adds the squared residuals and measures the mismatch at the invented observations.
Edit and compare
On the b line replace sp.Matrix([1,2,2]) with sp.Matrix([1,2,3]). Select Run Python and compare Observed minus fitted and Squared error with the first run. Can the fitted line now pass through every invented point?
Scope. Invented inputs and exact normal equations are used. Statistical uncertainty and robust numerical fitting are outside this small derivation.
Try a fresh case
What does a zero establish in this full-column-rank example?
Need a hint?
Hint 1
Separate an algebraic check from a scientific claim.
Hint 2
The condition refers to the chosen design matrix and objective.