Skip to main content

15  Linear least squares

Lecture 15: Chapter 5: Linear systems of equations

These lecture notes are mainly a record of what we discussed in class. They should not be used as a replacement for attending lectures or reading books. Please let me know if you find any errors or have any questions about the material.

You can use the Hypothesis commenting system available on the right side panel (you can login with your U/Google account). This allows you annotate the notes (private) and leave comments or reply to other people’s comments (public).

I encourage you to download the lecture notes and play around with the Julia code.

15.1 Previously…..

  • Pivoted LU decomposition: at each step choose the largest available pivot, giving \(L\), \(U\) and a permutation matrix \(P\) such that \((PL)U = PA\) with \(PL\) lower triangular; then solve \(Ax = b\) by forwards (\((PL)y = Pb\)) and backwards (\(Ux = y\)) substitution,
  • Without pivoting, the LU decomposition can be unstable: for example \(M(\epsilon) = \begin{pmatrix} -\epsilon & 1 \\ 1 & -1 \end{pmatrix}\) the matrix is well-conditioned but the factors \(L\), \(U\) are not; with pivoting the factors are well-conditioned,
  • The Euclidean norm \(|x|\) and the operator norm \(\|A\| := \max_{x\not=0} \frac{|Ax|}{|x|}\) (so that \(|Ax| \leq \|A\| |x|\)),
  • Condition number \(\kappa(A) := \|A\| \|A^{-1}\|\): if \(Ax = b\) and \(A\tilde x = \tilde b\), then \(\frac{|x - \tilde x|}{|x|} \leq \kappa(A) \frac{|b - \tilde b|}{|b|}\).

15.2 Linear least squares

Let us consider a rectangular linear system of equations: \(A x = b\) where \(A \in \mathbb R^{m\times n}\) with \(m > n\).

Example 15.1 Consider

\[ \begin{align}\nonumber \begin{pmatrix} 1 & 0 \\ 0 & 1 \\ 1 & 1 \end{pmatrix} \begin{pmatrix} x \\ y \end{pmatrix} = \begin{pmatrix} 1 \\ 1 \\ 1 \end{pmatrix}. \end{align} \]

This reads: \(x = y = 1\) and \(x + y = 1\). Therefore there is no solution! We say the matrix equation is overdetermined.

What does Julia think about this?

Code
A = [ 1 0 ; 0 1 ; 1 1 ]
b = [ 1 ; 1 ; 1 ]

A \ b
2-element Vector{Float64}:
 0.6666666666666665
 0.6666666666666667

What does \(x = ( \frac23 , \frac23 )^\top\) have to do with \(A\) and \(b\)?

We can see that

\[ \begin{align}\nonumber \begin{pmatrix} 1 & 0 \\ 0 & 1 \\ 1 & 1 \end{pmatrix} \begin{pmatrix} 2/3 \\ 2/3 \end{pmatrix} = \frac23 \begin{pmatrix} 1 \\ 1 \\ 2 \end{pmatrix}. \end{align} \]

You can show that the residual \(\left|A x -b\right|\) is equal to \(\frac{\sqrt{3}}{3}\) (Exercise 15.1). Could we have chosen \(x\) so the error between \(A x\) and \(b\) was smaller?

\[ \begin{align} |A x - b|^2 &= \left| \begin{pmatrix} 1 & 0 \\ 0 & 1 \\ 1 & 1 \end{pmatrix} \begin{pmatrix} x \\ y \end{pmatrix} - \begin{pmatrix} 1 \\ 1 \\ 1 \end{pmatrix} \right|^2 \nonumber\\ % &= \left| \begin{pmatrix} x-1 \\ y-1 \\ x+y-1 \end{pmatrix} \right|^2 \nonumber\\ % &= (x-1)^2 + (y-1)^2 + (x+y-1)^2. \nonumber \end{align} \]

Intuitively, you can see that, in order to minimise this quantity, we want to make each term equally small: \((x-1)^2 = (y-1)^2 = (x+y-1)^2\). You can achieve this when \(x = y = \frac23\), which is what Julia did!

Exercise 15.1 Let \(A\) and \(b\) be as in Example 15.1 and \(x = (\frac23, \frac23)^\top\). Compute the residual \(r := A x - b\), show that \(|r| = \frac{\sqrt3}{3}\), and check that \(r\) is orthogonal to both columns of \(A\) (i.e. \(A^\top r = 0\)).

15.3 Data fitting

There are many situations where we might want to approximately solve \(A x = b\), e.g. statistics:

Example 15.2 (Population of the UK) Here we consider the population of the UK in the years since 1971 (data from the UK Office for National Statistics):

Code
years = 1971:2024
pop = [
    55928000    56096700    56222900    56235600    56225700    56216100    56189900    56178000    56240100    56329700    56357500    56290700    56315700    56409300    56554000    56683800    56804000    56916400    57076500    57237500    57438700    57584500    57713900    57862100    58024800    58164400    58314200    58474900    58684400    58886100    59113000    59365700    59636700    59950400    60413300    60827000    61319100    61823800    62260500    62759500    63285100    63710500    64138200    64618700    65087000    65605800    65964300    66286700    66627500    66739900    66978000    67636100    68526200    69281400
]
r = 1:10:54  
x = years[r]
y = pop[r]
scatter( x, y/1e6 , title="population of UK", xlabel="year", ylabel="/millions", legend=false)

One way of fitting the data exactly would be to consider the polynomial interpolation of the data (see Chapter 3).

In the following, we measure time since 1970 to make the numbers smaller and improve the conditioning of the interpolation problem.

Code
p_interp = fit( r, y/1e6 )
display(p_interp)
scatter( r, y/1e6 , title="population of UK", ylabel="/millions",)
plot!( p_interp , -5 , 60, legend=false, xlabel="years since 1970" )
56.14920446749999 - 0.2674673070833299∙x + 0.04895897833333291∙x2 - 0.002763642499999981∙x3 + 6.807416666666631e-5∙x4 - 5.704166666666641e-7∙x5

You probably have already noticed that this is a bad approximation in this context (e.g. the population before 1970 was not larger than in 1970 and (hopefully) the population will not drop sharply as indicated above). In statistics, this phenomenon is known as overfitting.

It turns out that I did not plot all of the data points and so we can actually measure the testing error (that is the error on the data points that we left out when we came up with our model):

Code
scatter( pop'/1e6 , title="population of UK", label="testing data", xlabel="years since 1970", ylabel="/millions",color="red")

println( "training error: ",  norm( p_interp.(r) - y/1e6 ) )
println( "testing error: ",  norm( p_interp.(1:54) - pop'/1e6 ) )

scatter!( r, y/1e6 , title="population of UK", label="training data", xlabel="years since 1970", ylabel="/millions",color="blue")
plot!( p_interp, -5, 60, label="model" )
training error: 6.355287432313019e-14
testing error: 3.947571417338935

Here, we can see that indeed the “model” does not capture the correct behaviour outside the training data (i.e. the data points we used in order to derive the model in the first place).

Instead it may be useful to “fit” the data using a low degree polynomial, for example. In order to do this, we set up an (overdetermined) linear system of equations \(A x \approx b\) and try to minimise the error in this approximation. First suppose that the data can be described by the linear function \(y \approx p(t) = c_1 + c_2 t\) where \(p\) is the population at time \(t\). Suppose we have the data points \((t_1,y_1),\dots,(t_m,y_m)\) and notice that we want

\[ \begin{align}\nonumber y = \begin{pmatrix} y_1 \\ y_2 \\ \vdots \\ y_m \end{pmatrix} % &\approx \begin{pmatrix} p(t_1) \\ p(t_2) \\ \vdots \\ p(t_m) \end{pmatrix} % = \begin{pmatrix} 1 & t_1 \\ 1 & t_2 \\ \vdots & \vdots \\ 1 & t_m \end{pmatrix} \begin{pmatrix} c_1 \\ c_2 \end{pmatrix}. \end{align} \]

In order to solve this equation approximately, we may again use the A \ b operator as we did in Example 15.1:

Code
n = 1
V = r.^(0:n)'
p = Polynomial( V \ (y/1e6) )

scatter( pop'/1e6 , title="population of UK", label="testing data", xlabel="years since 1970", ylabel="/millions",color="red")
println( "training error: ",  norm( p.(r) - y/1e6 ) )
println( "testing error: ",  norm( p.(1:54) - pop'/1e6 ) )
scatter!( r, y/1e6 , title="population of UK", label="training data",color="blue")
plot!( p, -5, 60, label="model" )
training error: 3.206666526918118
testing error: 10.088011997522381

We can see that the testing error for this model is actually worse than the polynomial interpolation! The model is too simple to capture what is actually happening. We can add complexity to the model by choosing a higher degree polynomial: \(p(t) = c_1 + c_2 t + c_3 t^2\) and so we want

\[ \begin{align}\nonumber y % &\approx \begin{pmatrix} p(t_1) \\ p(t_2) \\ \vdots \\ p(t_m) \end{pmatrix} % = \begin{pmatrix} 1 & t_1 & t_1^2\\ 1 & t_2 & t_2^2\\ \vdots & \vdots & \vdots \\ 1 & t_m & t_m^2 \end{pmatrix} \begin{pmatrix} c_1 \\ c_2 \\ c_3 \end{pmatrix}. \end{align} \]

Doing this indeed reduces the testing error:

Code
n = 2
V = r.^(0:n)'
p = Polynomial( V \ (y/1e6) )

scatter( 1:54, pop'/1e6 , title="population of UK", label="testing data", xlabel="years since 1970", ylabel="/millions",color="red")

println( "training error: ",  norm( p.(r) - y/1e6 ) )
println( "testing error: ",  norm( p.(1:54) - pop'/1e6 ) )

scatter!( r, y/1e6 , title="population of UK", label="training data", xlabel="years since 1970", ylabel="/millions",color="blue")
plot!( p, -5, 60, label="model" )
training error: 0.7000921851544214
testing error: 2.4978049313214417

This is known as linear least squares (because we are minimising \(|A x-b|^2\)). The choice of polynomials is somewhat arbitrary: we still get an overdetermined linear system of equations if we instead took \(p(t) = c_1 + c_2 t + c_3 t^3 + c_4 \cos t\):

Code
# Different basis functions:

f(t) = 1; g(t) = t; h(t) = t^3; j(t) = cos(t)
A = [f.(r) g.(r) h.(r) j.(r)]
c = A \ (y/1e6) 

p′(x) = c[1] * f(x) + c[2] * g(x) + c[3] * h(x) + c[4] * j(x)

scatter( 1:54, pop'/1e6 , title="population of UK", label="testing data", xlabel="years since 1970", ylabel="/millions",color="red")

println( "training error: ",  norm( p′.(r) - y/1e6 ) )
println( "testing error: ",  norm( p′.(1:54) - pop'/1e6 ) )

scatter!( r, y/1e6 , label="training data", xlabel="years since 1970", ylabel="/millions",color="blue")
plot!( p′, -5, 60, label="model" )
training error: 0.5283726651045577
testing error: 3.3411811246054257

15.4 The normal equations

Theorem 15.1 Suppose \(x\) solves the normal equations \(A^\top Ax = A^\top b\). Then, \(x\) minimises the error \(|Ax - b|\).

Proof. Suppose that \(x\) solves the normal equations and \(\delta x \in \mathbb R^{n}\). Notice that \(|u+v|^2 = |u|^2 + 2 v^\top u + |v|^2\) and so we have

\[ \begin{align} |A(x+\delta x) - b|^2 &= |(Ax-b) + A\delta x|^2 \nonumber\\ % &= |Ax-b|^2 + 2(\delta x)^\top A^\top (Ax - b) + |A\delta x|^2 \nonumber\\ % &= |Ax-b|^2 + |A\delta x|^2 \nonumber\\ % &\geq |Ax-b|^2. \nonumber \end{align} \]

That is, \(x\) is a minimiser of the function \(y \mapsto |Ay - b|\).

Remark 15.1. Where do the normal equations come from? Since \(|Ax-b|^2 = (Ax-b)^\top (Ax-b)\), you can show that the derivative with respect to \(x_k\) is (Exercise 15.2)

\[ \begin{align}\nonumber \frac{\partial} {\partial x_k} \left( \sum_{i=1}^m (Ax-b)_i (Ax-b)_i \right) % &= 2\sum_{i=1}^m A_{ik} (Ax - b)_i % = 2 \big( A^\top(Ax - b) \big)_k. \end{align} \]

Therefore, the critical points of the function \(y \mapsto |Ay-b|^2\) satisfy \(A^\top(Ay - b) = 0\).

Exercise 15.2 Fill in the details in Remark 15.1: for \(A \in \mathbb R^{m\times n}\) and \(b \in \mathbb R^m\), show that \(\frac{\partial}{\partial x_k} |Ax - b|^2 = 2\big(A^\top(Ax - b)\big)_k\).

Therefore, in order to solve the linear least squares problem, we could solve \(A^\top A x = A^\top b\) which is now a square matrix equation that we have seen how to deal with (i.e. (P)LU decomposition + forwards and backwards substitution). The problem is that “\(\kappa(A^\top A) = \kappa(A)^2\)” (one can define the condition number of a rectangular matrix but we haven’t seen the definition; see Exercise 15.6 for the square case) and so, whenever \(A\) is moderately ill-conditioned, the normal equations are much worse conditioned than the original problem (if \(\kappa(A) \approx 10^8\), we expect to lose all 16 digits).

15.5 QR factorisation

Instead: the built-in function in Julia uses the so-called QR factorisation which plays the role of the LU decomposition but for solving overdetermined systems of equations. We may return to this in the last week of semester; here we only see the very basics:

Suppose that \(A \in \mathbb R^{m \times n}\) is such that \(A = QR\) with \(Q \in \mathbb R^{m\times n}\) with orthonormal columns (i.e. \(Q^{T} Q = I\)) and \(R \in \mathbb R^{n\times n}\) upper triangular. If one has such a decomposition, then

\[ \begin{align}\nonumber A^\top A x = (QR)^\top (QR) x % = R^\top Q^\top Q R x % = R^\top R x \end{align} \]

and

\[ \begin{align}\nonumber A^\top b = (QR)^\top b = R^\top Q^\top b. \end{align} \]

It turns out that if \(A\) has linearly independent columns, then \(R^\top\) is invertible and \(A^\top Ax = A^\top b\) is equivalent to \(R x = Q^\top b\). Solving this system is possible by backwards substitution.

Exercise 15.3 Suppose \(A \in \mathbb R^{m\times n}\) (\(m \geq n\)) has linearly independent columns and \(A = QR\) as above. Show that \(R\) is invertible and that \(A^\top Ax = A^\top b\) if and only if \(Rx = Q^\top b\).

15.6 Next time….

  • QR factorisation
  • Singular value decomposition (SVD)
TipTO-DO
  • Exercises throughout the notes,
  • (Sign-up to office hours if you like)

15.7 Extra exercises

Exercise 15.4 Use the normal equations to find the straight line \(p(t) = c_1 + c_2 t\) which best fits (in the least squares sense) the data \((0,1)\), \((1,3)\), \((2,4)\), \((3,4)\). Compute the residual and check that it is orthogonal to the columns of \(A\). Check your answer using A \ b in Julia.

Exercise 15.5 Let \(A \in \mathbb R^{m\times n}\). Show that \(A^\top A\) is invertible if and only if \(A\) has linearly independent columns. Deduce that, in this case, the least squares problem \(\min_{x} |Ax - b|\) has a unique solution.

Exercise 15.6 Let \(A \in \mathbb R^{n\times n}\) be invertible.

  1. Show that \(\|A^\top A\| = \|A\|^2\),
  2. Show that \(\|A^\top \| = \|A\|\),
  3. Deduce that \(\kappa(A^\top A) = \kappa(A)^2\) and check this numerically in Julia for a matrix of your choice (using cond).
Timer
00:00
min