Least squares as a quadratic program
The same least-squares problem as in linear algebra — until you add realistic constraints and it becomes a QP.
- Write least squares as a convex optimization problem
- Add constraints and recognise the result as a quadratic program
- Read a solution where constraints are active
The least-squares lesson solved
\[\min_{\mathbf{x}} \; \|A\mathbf{x} - \mathbf{b}\|_2^2\]with the normal equations. Geometrically, it projects \(\mathbf{b}\) onto the column space of \(A\) — least_squares.py says exactly this in its docstring, and draws it:
The objective is a convex quadratic — its Hessian \(2A^{\mathsf{T}}A\) is positive semidefinite — so least squares is already a convex problem. It just happens to have a closed-form answer.
Mixing paint
The colour-mixing script gives the problem a body. Each column of \(A\) is a base paint colour, \(\mathbf{b}\) is the colour you want, and \(\mathbf{x}\) is how much of each paint to use. In CVXPY it reads almost like the maths:
x = cp.Variable(num_base_colors)
cost = cp.sum_squares(A @ x - b)
constraints = [
x >= 0, # non-negative amounts of paint
cp.sum(x) <= 1, # total paint at most 1
x <= 0.5, # no more than 0.5 of any colour
]
prob = cp.Problem(cp.Minimize(cost), constraints)
prob.solve()
With the constraints, this is a quadratic program (QP): a convex quadratic objective over a set cut out by linear inequalities. There is no closed form any more, but QPs are among the fastest problems to solve reliably.
What the constraints cost
Running the script (seed 42) is instructive:
| Mixing amounts \(\mathbf{x}\) | Colour error \(|A\mathbf{x} - \mathbf{b}|\) | |
|---|---|---|
| Unconstrained | \((0.21,\; 5.17,\; -5.85)\) | essentially 0 |
| Constrained | \((0,\; 0.5,\; 0.5)\) | 0.303 |
With three base colours in a three-dimensional colour space, \(A\) is square and invertible, so the unconstrained problem has an exact solution — that needs 5.2 units of one paint and minus 5.9 of another. Mathematically perfect, physically absurd.
The constrained answer is worse by 0.303 but real. Read it closely: two paints sit exactly at their 0.5 cap, the first is at its floor of 0, and the total is exactly
- Several constraints are active — the solution is pressed against the walls of the feasible region. That is typical of constrained optimization, and it is exactly what will happen to the car’s acceleration limit in the MPC lessons.
Try it yourself. Remove only the x <= 0.5 constraint and re-solve: which constraints are active now, and does the error improve? Then add a fourth base colour, making \(A\) a 3×4 matrix — the unconstrained problem now has infinitely many exact solutions. Which one does np.linalg.lstsq return?