Last time¶
Intro to Krylov/GMRES
Matrix norms and conditioning
Today¶
Least squares problems
Geometry of the SVD
using LinearAlgebra
using Plots
default(linewidth=4, legendfontsize=12)
function vander(x, k=nothing)
if isnothing(k)
k = length(x)
end
m = length(x)
V = ones(m, k)
for j in 2:k
V[:, j] = V[:, j-1] .* x
end
V
end
function gram_schmidt_classical(A)
m, n = size(A)
Q = zeros(m, n)
R = zeros(n, n)
for j in 1:n
v = A[:,j]
R[1:j-1,j] = Q[:,1:j-1]' * v
v -= Q[:,1:j-1] * R[1:j-1,j]
R[j,j] = norm(v)
Q[:,j] = v / R[j,j]
end
Q, R
end
function qr_householder(A)
m, n = size(A)
R = copy(A)
V = [] # list of reflectors
for j in 1:n
v = copy(R[j:end, j])
v[1] += sign(v[1]) * norm(v) # <---
v = normalize(v)
R[j:end,j:end] -= 2 * v * v' * R[j:end,j:end]
push!(V, v)
end
V, R
end
function qr_chol(A)
R = cholesky(A' * A).U
Q = A / R
Q, R
end
function qr_chol2(A)
Q, R = qr_chol(A)
Q, R1 = qr_chol(Q)
Q, R1 * R
end
qr_chol2 (generic function with 1 method)Condition numbers for matrices¶
We may have informally referred to a matrix as “ill-conditioned” when the columns are nearly linearly dependent, but let’s make this concept for precise. Recall the definition of (relative) condition number:
We understood this definition for scalar problems, but it also makes sense when the inputs and/or outputs are vectors (or matrices, etc.) and absolute value is replaced by vector (or matrix) norms. Consider matrix-vector multiplication, for which .
There are two problems here:
I wrote but my formula depends on .
What is that beastie?
Matrix norms induced by vector norms¶
Vector norms are built into the linear space (and defined in term of the inner product). Matrix norms are induced by vector norms, according to
This equation makes sense for non-square matrices -- the vector norms of the input and output spaces may differ.
Due to linearity, all that matters is direction of , so it could equivalently be written
The formula makes sense, but still depends on .¶
Consider the matrix
What is the norm of this matrix?
What is the condition number when ?
What is the condition number when ?
Condition number of the matrix¶
The condition number of matrix-vector multiplication depends on the vector. The condition number of the matrix is the worst case (maximum) of the condition number for any vector, i.e.,
If is invertible, then we can rephrase as
Evidently multiplying by a matrix is just as ill-conditioned of an operation as solving a linear system using that matrix.
Least squares and the normal equations¶
A least squares problem takes the form: given an matrix (), find such that
is minimized. If is square and full rank, then this minimizer will satisfy , but that is not the case in general because is not in the range of . The residual must be orthogonal to the range of .
Is this the same as saying ?
If , is it the same as ?
We showed that is an orthogonal projector onto the range of . If ,
So if is in the range of , we can solve . If not, we need only orthogonally project into the range of .
The Professional’s Way: QR (Householder)¶
Solve .
QR factorization costs operations and is done once per matrix .
Computing costs (using the elementary reflectors, which are stable and lower storage than naive storage of ).
Solving with costs operations. Total cost per right hand side is thus .
This method is stable and accurate.
The 737 MAX Way: Cholesky/Normal Equations¶
fast, unregulated, and dangerous¶
The mathematically equivalent form are called the normal equations. The solution process involves factoring the symmetric and positive definite matrix .
Computing costs flops, exploiting symmetry.
Factoring costs flops. The total factorization cost is thus .
Computing costs .
Solving with costs .
Solving with costs . Total cost per right hand side is thus .
The product is ill-conditioned: and can reduce the accuracy of a least squares solution.
The Prepper’s Way: Singular Value Decomposition¶
where and have orthonormal columns and is diagonal with nonnegative entries. The entries of are called singular values and this decomposition is the singular value decomposition (SVD). It may remind you of an eigenvalue decomposition , but
the SVD exists for all matrices (including non-square and deficient matrices)
have orthogonal columns (while can be arbitrarily ill-conditioned). Indeed, if a matrix is symmetric and positive definite (all positive eigenvalues), then and . Computing an SVD requires a somewhat complicated iterative algorithm, but a crude estimate of the cost is . Note that this is similar to the cost of when , but much more expensive for square matrices. Solving with the SVD involves
Compute at a cost of .
Solve with the diagonal matrix at a cost of .
Apply at a cost of . The total cost per right hand side is thus .
SVD gives the unique minimum norm solution when is rank deficient¶
Demo: Geometry of the Singular Value Decomposition¶
default(aspect_ratio=:equal)
function peanut()
theta = LinRange(0, 2*pi, 50)
r = 1 .+ .4*sin.(3*theta) + .6*sin.(2*theta)
r' .* [cos.(theta) sin.(theta)]'
end
function circle()
theta = LinRange(0, 2*pi, 50)
[cos.(theta) sin.(theta)]'
end
function Aplot(A)
"Plot a transformation from X to Y"
X = peanut()
Y = A * X
p = scatter(X[1,:], X[2,:], label="in")
scatter!(p, Y[1,:], Y[2,:], label="out")
X = circle()
Y = A * X
q = scatter(X[1,:], X[2,:], label="in")
scatter!(q, Y[1,:], Y[2,:], label="out")
plot(p, q, layout=2)
endAplot (generic function with 1 method)Aplot(1.5*I)Diagonal matrices¶
Perhaps the simplest transformation is a scalar multiple of the identity.
Aplot([.4 0; 0 1.1])The diagonal entries can be different sizes.
Aplot([2 0; 0 .5])The circles becomes an ellipse that is aligned with the coordinate axes
Givens Rotation (as example of orthogonal matrix)¶
We can rotate the input using a matrix, parametrized by . Its transpose rotates in the opposite direction.
function givens(theta)
s = sin(theta)
c = cos(theta)
[c -s; s c]
end
G = givens(pi/2)
Aplot(G)Aplot(G')Reflection¶
We’ve previously seen that reflectors have the form where is a normalized vector. Reflectors satisfy and , thus .
function reflect(theta)
v = [cos(theta), sin(theta)]
I - 2 * v * v'
end
Aplot(reflect(0.3))Singular Value Decomposition¶
The SVD is where and have orthonormal columns and is diagonal with nonnegative entries. It exists for any matrix (non-square, singular, etc.). If we think of orthogonal matrices as reflections/rotations, this says any matrix can be represented as reflect/rotate, diagonally scale, and reflect/rotate again.
Let’s try a random symmetric matrix.
A = randn(2, 2)
#A += A' # make symmetric
@show det(A) # Positive means orientation is preserved
Aplot(A)det(A) = -1.0746714389805787
U, S, V = svd(A)
@show S
@show norm(U * diagm(S) * V' - A) # Should be zero
@show det(U), det(V)
Aplot(V) # Rotate/reflect in preparation for scaling]S = [2.6065410498109953, 0.4122979145325583]
norm(U * diagm(S) * V' - A) = 6.080941944488118e-16
(det(U), det(V)) = (-1.0, 1.0000000000000002)
What visual features indicate that this is a symmetric matrix?
Is the orthogonal matrix a reflection or rotation?
Does this change when the determinant is positive versus negative (rerun the cell above as needed).
Parts of the SVD¶
Aplot(diagm(S)) # scale along axesAplot(U) # rotate/reflect backPutting it together¶
Aplot(U * diagm(S) * V')Observations¶
The circle always maps to an ellipse
The and factors may reflect even when
What makes a matrix ill-conditioned?¶
A = [10 5; .9 .5]
@show cond(A)
svdvals(A)cond(A) = 252.116033572376
2-element Vector{Float64}:
11.22755613596245
0.0445332888070338m = 100
x = LinRange(-1, 1, m)
A = vander(x, 20)
@show cond(A)
svdvals(A)cond(A) = 7.206778416853811e6
20-element Vector{Float64}:
11.510601491136654
8.993572449917352
5.907360126610745
3.6029154831946064
1.9769729310318853
1.098310376576986
0.5392322016751737
0.2820042230178553
0.12425066006852684
0.06183086124622112
0.024242929146349384
0.011556331531623212
0.003964435582121844
0.0018189836735690052
0.0005298822985647027
0.00023487660987952337
5.4870893944525604e-5
2.3566694052620285e-5
3.8286365250847765e-6
1.597190981232044e-6Orthogonal transformations don’t affect singular values (or conditioning)¶
A = [3 0; 0 .5]
Q, _R = qr(randn(2,2))
B = Q * A * Q'
U, S, V = svd(randn(2,2))
@show S
@show S[1] / S[end]
Aplot(diagm(S))S = [1.0729677922517786, 0.0804276181075547]
S[1] / S[end] = 13.340787872356412