Skip to content
ImagineWorld

Matrix Factorizations

node_idnode-book_mathematics-of-machine-learning_chapter-07-matrix-factorizations
node_typechapter_node
schema_profileworld.chapter_node.v1
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
statusactive
chapter_num7
chapter_titleMatrix Factorizations
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

One of the recurring thoughts in this book is that problem-solving is about finding the best representations of your objects of study. Say linear transformations of a vector space are represented by matrices. Studying one is the same as studying the other, but each perspective comes with its own set of tools. Linear transformations are geometric, while matrices are algebraic sides of the same coin.

This thought can be applied on a smaller scale as well. Recall the LU decomposition from Chapter 6. You can think of this as another view of matrices.

Guess what: It’s not the only one. This chapter is dedicated to the three most important ones:

  • the spectral decomposition,
  • the singular value decomposition,
  • and the QR decomposition.

Buckle up. It’s our most challenging adventure yet.

day-mode Bookmark

So far, we have aspired to develop a geometric view of linear algebra. Vectors are mathematical objects defined by their direction and magnitude. In the spaces of vectors, the concept of distance and orthogonality gives rise to a geometric structure.

Linear transformations, the building blocks of machine learning, are just mappings that distort this structure: rotating, stretching, and skewing the geometry. However, there are types of transformations that preserve some of the structure. In practice, these provide valuable insights, and additionally, they are much easier to work with. In this section, we will take a look at the most important ones, those that we’ll encounter in machine learning.

In machine learning, the most important stage is the Euclidean space ℝn. This is where data is represented and manipulated. There, the entire geometric structure is defined by the inner product

 ∑n ⟨x,y ⟩ = xiyi, i=1

giving rise to the notion of magnitude, direction (in the form of angles), and orthogonality. Because of this, transformations that can be related to the inner product are special. For instance, if ⟨f(x),f(x)⟩ = ⟨x,x⟩ holds for all x ∈ℝn and the linear transformation f : ℝn →ℝn, we know that f leaves the norm invariant. That is, distance in the original and the transformed feature space have the same meaning.

First, we will establish a general relation between images of vectors under a transform and their inner product. This is going to be the foundation for our discussions in this chapter.

Theorem 39. (The adjoint transformation)

Let f : ℝn →ℝn be a linear transformation. Then, there exists a linear transformation f∗ : ℝn →ℝn for which

⟨f(x), y⟩ = ⟨x, f*(y)⟩

(7.1)

holds for all x,y ∈ℝn. f∗ is called the adjoint transformation* of f.

Moreover, if A ∈ℝn×n is the matrix of f in the standard orthonormal basis, then the matrix of f∗ is AT . That is,

⟨Ax, y⟩ = ⟨x, ATy⟩.

(7.2)

Proof. Suppose that A ∈ ℝn×n is the matrix of f in the standard orthonormal basis. For any x = (x1,…,xn) and y = (y1,…,yn), the inner product is defined by

 ∑n ⟨x,y ⟩ = xiyi, i=1

and Ax can be written as

⌊ ⌋ |a11 a12 ... a1n |⌊ ⌋ ⌊ ∑n ⌋ |a a ... a || x1| | ∑ j=1a1jxj| || 21. 2.2 . 2n. |||| x2|| || nj=1a2jxj|| || .. .. .. .. |||| ..|| = || .. || . || ||⌈ .⌉ ⌈ . ⌉ ⌈an1 an2 ... ann ⌉ xn ∑n anjxj j=1

Using this form, we can express ⟨Ax,y⟩ in terms of aij-s, xi-s, and yi-s. For this, we have

 ∑n ∑n ⟨Ax, y⟩ = ( aijxj)yi i=1 j=1 ∑n ∑n = ( aijyi) xj j=1 i=1 ◟--◝◜---◞ T j- th component of A y = ⟨x,AT y⟩.

This shows that the transformation given by f∗ : x→AT x satisfies (7.1) and (7.2), which is what we had to show.

Why is the quantity ⟨Ax,y⟩ that important to us? Because inner products define the geometric structure of a vector space. Recall the equation (2.12), allowing us to fully describe any vector using only the inner products with respect to an orthonormal basis. In addition, ⟨x,x⟩ = ∥x∥2 defines the notion of distance and magnitude. Because of this, (7.1) and (7.2) will be quite useful for us.

As we are about to see, transformations that preserve the inner product are rather special, and these relationships provide us with a way to characterize them both algebraically and geometrically.

Let’s jump straight into the definition.

Definition 26. (Orthogonal transformations)

Let f : ℝn →ℝn be an arbitrary linear transformation. f is called orthogonal if

⟨f(x),f(y)⟩ = ⟨x,y ⟩

holds for all x,y ∈ℝn.

As a consequence, an orthogonal f preserves the norm: ∥f(x)∥2 = ⟨f(x),f(x)⟩ = ⟨x,x⟩ = ∥x∥2. Because the angle enclosed by two vectors is defined by their inner product, see equation (2.9), the property ⟨f(x),f(y)⟩ = ⟨x,y⟩ means that an orthogonal transform also preserves angles.

We can translate the definition to the language of matrices as well. In practice, we are always going to work with matrices, so this characterization is essential.

Theorem 40. (Matrices of orthogonal transformations)

Let f : ℝn → ℝn be a linear transformation and A ∈ ℝn×n be its matrix in the standard orthonormal basis. Then, f is orthogonal if, and only if, AT = A−1.

Proof. As usual, we have to show the implication in both ways.

(a) Suppose that f is orthogonal. Then, (7.2) gives

 T ⟨x, y⟩ = ⟨Ax, Ay ⟩ = ⟨x, A Ay ⟩.

Thus, for any given y,

 T ⟨x,(A A − I)y ⟩ = 0

holds for all x. By letting x = (AT A −I)y, the positive definiteness of the inner product implies that (AT A −I)y = 0 for all y. Thus, AT A = I, which means that AT is the inverse of A.

(b) If AT = A−1, we have

⟨Ax, Ay ⟩ = ⟨x,AT Ay ⟩ −1 = ⟨x,A Ay ⟩ = ⟨x,y ⟩,

showing that f is orthogonal.

The fact that AT = A−1 has a profound implication regarding the columns of A. If you think back to the definition of matrix multiplication in Section 4.1.2, the element in the i-th row and j-th column of AB is the inner product of the i-th row of A and the j-th column of B.

To be more precise, if the i-th column is denoted by ai = (a1,i,a2,i,…,an,i), then we have

AT A = (⟨ai,aj⟩)n = I, i,j=1

that is,

 ( |{ ⟨a ,a ⟩ = 1 if i = j, i j |( 0 otherwise.

In other words, the columns of A form an orthonormal system. This fact should not come as a surprise since orthogonal transformations preserve magnitude and orthogonality, and the columns of A are the images of the standard orthonormal basis e1,…,en.

In machine learning, performing an orthogonal transformation on our features is equivalent to looking at them from another perspective, without distortion. You might know it already, but this is what Principal Component Analysis (PCA) is doing.

day-mode Bookmark

7.2 Self-adjoint transformations and the spectral decomposition theorem

Section titled “7.2 Self-adjoint transformations and the spectral decomposition theorem”

Besides orthogonal transformations, there is another important class: transformations whose adjoints are themselves. Bear with me a bit, and we’ll see an example soon.

Definition 27. (Self-adjoint transformations)

Let f : ℝn →ℝn be a linear transformation. f is self-adjoint if f∗ = f, that is,

⟨f(x), y⟩ = ⟨x, f(y)⟩

(7.3)

holds for all x,y ∈ℝn.

As always, we are going to translate this into the language of matrices. If A is the matrix of f in the standard orthonormal basis, we know that AT is the matrix of the adjoint. For self-adjoint transformations, it implies that AT = A. Matrices such as these are called symmetric, and they have a lot of pleasant properties.

For us, the most important one is that symmetric matrices can be diagonalized! (That is,they can be transformed into a diagonal matrix with a check reference) The following theorem makes this precise.

Theorem 41. (Spectral decomposition of real symmetric matrices)

Let A ∈ ℝn×n be a real symmetric matrix. Then, A has exactly n real eigenvalues λ1 ≥⋅⋅⋅≥λn, and the corresponding eigenvectors u1,…,un can be selected such that they form an orthonormal basis.

Moreover, if we let Λ = diag(λ1,…,λn) and U be the orthogonal matrix whose columns are u1,…,un, then

A = UΛUT

(7.4)

holds.

Note that the eigenvalues λ1 ≥⋅⋅⋅≥λn are not necessarily distinct from each other.

Proof. (Sketch) Since the proof is pretty involved, we are better off getting to know the main ideas behind it, without all the mathematical details.

The main steps are the following.

  1. If the matrix A is symmetric, all of its eigenvalues are real.
  2. Using this, it can be shown that an orthonormal basis can be formed from the eigenvectors of A.
  3. Writing the matrix of the transformation x → Ax in this orthonormal basis yields a diagonal matrix. Hence, a change of basis yields (7.4).

Showing that the eigenvalues are real requires some complex number magic (which is beyond the scope of this chapter). The tough part is the second step. Once that has been done, moving to the third one is straightforward, as we have seen when talking about eigenspaces and their bases (Section 6.3).

We still don’t have a hands-on way to diagonalize matrices, but this theorem gets us one step closer: at least we know it is possible for symmetric matrices. This is an important stepping stone, as we’ll be able to reduce the general case to the symmetric one.

The requirement for a matrix to be symmetric seems like a very special one. However, in practice, we can symmetrize matrices in several different ways. For any matrix A ∈ℝn×m, the products AAT and AT A will be symmetric. For square matrices, the average A+AT- 2 also works. So, symmetric matrices are more common than you think.

The orthogonal matrix U and the corresponding orthonormal basis {u1,…,un} that diagonalizes a symmetric matrix A has a special property that is going to be very important in machine learning for the principal component analysis of data samples.

Before looking at the next theorem, we introduce the argmax notation. Recall that the expression maxx∈Af(x) denotes the maximum value of the function over the set A. Often, we would like to know where that maximum is attained, which is defined by the argmax:

 ∗ x = argmaxx ∈Af (x), f(x∗) = max f(x). x∈A

Now, let’s see the fundamentals of PCA!

Theorem 42.

Let A ∈ ℝn×n be a real symmetric matrix and let λ1 ≥ ⋅⋅⋅ ≥ λn be its real eigenvalues in decreasing order. Moreover, let U ∈ ℝn×n be the orthogonal matrix that diagonalizes A, with the corresponding orthonormal basis {u1,…,un}.

Then,

 T arg m∥axx∥=1 x Ax = u1,

and

 max xT Ax = λ1. ∥x∥=1

Proof. Since {u1,…,un} is an orthonormal basis, any x can be expressed as a linear combination of them:

 n ∑ x = xiui, xi ∈ ℝ. i=1

Thus, since the ui are eigenvectors of A,

 ∑n ∑n ∑n Ax = A( xiui) = xiAui = xiλiui. i=1 i=1 i=1

Plugging it back into xT Ax, we have

 T ∑n T ∑n x Ax = ( xjuj) A ( xiui) j=1 i=1 ∑n ∑n = ( xjuTj )A ( xiui) j=1 i=1 ∑n ∑n = ( xjuTj )( xiλiui) j=1 i=1

 ∑n T = xixjλiuj ui. i,j=1

Since the ui-s form an orthonormal basis,

 (| T {1 if i = j, uj ui = ⟨ui,uj⟩ = | (0 otherwise.

In other words, ujT ui vanishes when i≠j. Continuing the above calculation with this observation,

When

, the sum

is a weighted average of the eigenvalues

. So,

from which xT Ax ≤ λ1 follows. (Recall that we can assume without loss in generality that the eigenvalues are decreasing.) On the other hand, by plugging in x = u1, we can see that u1T Au1 = λ1, so the maximum is indeed attained. From these two, the theorem follows.

Remark 6.

In other words, Theorem 42 gives that the function x→xT Ax assumes its maximum value at u1, and that maximum value is u1T Au1 = λ1. The quantity xT Ax seems quite mysterious as well, so let’s clarify this a bit. If we think in terms of features, the vectors u1,…,un can be thought of as mixtures of the “old” features e1,…,en. When we have actual observations (that is, data), we can use the above process to diagonalize the covariance matrix. So, if A denotes this covariance matrix, u1T Au1 is the variance of the new feature u1.

Thus, this theorem says that u1 is the unique feature that maximizes the variance. So, among all the possible choices for new features, u1 conveys the most information about the data.

At this point, we don’t have all the tools to see, but in connection to the principal component analysis, this says that the first principal vector is the one that maximizes variance.

Theorem 42 is just a special case of the following general theorem.

Theorem 43.

Let A ∈ ℝn×n be a real symmetric matrix, let λ1 ≥ ⋅⋅⋅ ≥ λn be its real eigenvalues in decreasing order. Moreover, let U ∈ ℝn×n be the orthogonal matrix that diagonalizes A, with the corresponding orthonormal basis {u1,…,un}.

Then, for all k = 1,…,n, we have

u = argmax{xT Ax : ∥x∥ = 1,x ⊥ {u ,...,u }}, k 1 k−1

and

λ max {xT Ax : ∥x∥ = 1,x ⊥ {u ,...,u }}. k 1 k− 1

(Sometimes, when the conditions are too complicated, we write max{f(x) : x ∈A} instead of maxx∈Af(x).)

Proof. The proof is almost identical to the previous one. Since x is required to be orthogonal to u1,…,uk−1, it can be expressed as

 n ∑ x = xiui. i=k

Following the calculations in the proof of the previous theorem, we have

 ∑n xTAx = x2iλi ≤ λk. i=k

On the other hand, similar to before, ukT Auk = λk, so the theorem follows.

day-mode Bookmark

So, we can diagonalize any real symmetric matrix with an orthogonal transformation. That’s great, but what if our matrix is not symmetric? After all, this is a rather special case.

How can we do the same for a general matrix? We’ll use a very strong tool, straight from the mathematician’s toolkit: wishful thinking. We pretend to have the solution, then reverse engineer it. To be specific, let A ∈ℝn×m be any real matrix. (It might not be square.) Since A is not symmetric, we have to relax our wishes for factoring it into the form UΛUT . The most straightforward way is to assume that the orthogonal matrices to the left and to the right are not each other’s transposes.

Thus, we are looking for orthogonal matrices U ∈ℝn×n and V ∈ℝm×m such that

A = U ΣV T

holds for some diagonal Σ ∈ℝn×m. (A non-square matrix Σ = (σi,j)i,j=1n,m is diagonal if σi,j is 0 when i≠j.)

You might be wondering about the notational switch from Λ to Σ. This is because Σ will not necessarily contain eigenvalues, but singular values. We’ll explain soon.

Here comes the reverse-engineering part. First, as we discussed earlier, AAT and AT A are symmetric matrices. Second, we can simplify them by using the orthogonality of U and V , obtaining

 T T T AA = (UΣV )(VΣU ) 2 T = U Σ U .

Similarly, we have AT A = V Σ2V T . Good news: We can actually find U and V by applying the spectral decomposition theorem (Theorem 41) to AAT and AT A, respectively. Thus, the factorization A = UΣV T is valid! This form is called the singular value decomposition (SVD), one of the pinnacle achievements of linear algebra.

Of course, we are not done yet; we just know where to look. Let’s make this mathematically precise!

Theorem 44. (Singular value decomposition)

Let A ∈ℝn×m be an arbitrary matrix. Then, there exists a diagonal matrix Σ ∈ℝn×m and orthogonal matrices U ∈ℝn×n and V ∈ℝm×m, such that

A = U ΣV T.

What is a non-square diagonal matrix? Let me give you two examples, and you’ll immediately get the gist:

⌊ ⌋ ⌊ ⌋ 1 0 1 0 0 ||0 2|| , ||0 2 0|| . ⌈ ⌉ ⌈ ⌉ 0 0

We can always write rectangular matrices M ∈ℝn×m in the forms

 ⌊ ⌋ M1 m×m (n−m)×m M = ⌈ ⌉ , M1 ∈ ℝ , M2 ∈ ℝ M2

if m<n, and

 [ ] n×n n×(m−n) M = M1 M2 , M1 ∈ ℝ , M2 ∈ ℝ

otherwise. Now, let’s see the proof of the singular value decomposition!

Proof. (Sketch.) To illustrate the main ideas of the proof, we assume that 1) A is square, and 2) A is invertible; that is, 0 is not an eigenvalue of A,

Since AT A ∈ ℝm×m is a real symmetric matrix, we can apply the spectral decomposition theorem to obtain a diagonal Σ ∈ ℝm×m and orthogonal V ∈ℝm×m such that

 T 2 T A A = V Σ V

holds. (Recall that the eigenvalues of a symmetric matrix are nonnegative, thus we can write the eigenvalues of AT A in the form Σ2.)

As A is invertible, AT A is invertible as well; thus, 0 is not an eigenvalue of AT A. As a consequence, ΣA−1 is well defined. Now, by defining U := AV ΣA−1, the orthogonality of V gives that

 T −1 T U ΣV = (AV Σ )ΣV T = AV V = A,

Thus, we are almost finished. The only thing left to show is that U is indeed orthogonal, that is, UT U = I. Here we go:

U TU = (AV Σ− 1)TAV Σ−1 −1 T T −1 = Σ V A◟◝◜A◞ V Σ =VΣ2VT = Σ−1(V TV )Σ2(V TV)Σ −1 = Σ−1Σ2 Σ− 1 = I,

With that, have the singular value decomposition for the special case of square and invertible A.

To keep the complexity bearable, we won’t work the rest of the details out; I’ll leave that to you as an exercise. You have all the tools by now.

Let’s take a moment to appreciate the power of the singular value decomposition. The columns of U and V are orthogonal matrices, which are rather special transformations. As they leave the inner products and the norm invariant, the structure of the underlying vector spaces is preserved. The diagonal Σ is also special, as it is just a stretching in the direction of the bases. It is very surprising that any linear transformation is the composition of these three special ones.

Besides mapping out the fine structure of linear transformations, SVD offers a lot more. For instance, it generalizes the notion of eigenvectors, a concept that was defined only for square matrices. With this, we have

AV = U Σ,

which we can take a look at column-wise. Here, Σ is diagonal, but its number of elements depends on the smaller one of n or m.

So, if ui is the i-th column of U, and vi is the i-th column of V , the identity AV = UΣ is translated to

Av = σ u , 0 ≤ i ≤ min (n,m ). i ii

This closely resembles the definition of eigenvalue-eigenvector pairs, except that instead of one vector, we have two. The ui and vi are the so-called left and right singular vectors, while the scalars σi = √λ- i are called singular values.

To sum up, orthogonal transformations give us the singular value decomposition, but is that all? Are there any other special transformations and matrix decompositions? You bet there is.

Enter orthogonal projections.

day-mode Bookmark

Linear transformations are essentially manipulations of data, revealing other (hopefully more useful) representations. Intuitively, we think about them as one-to-one mappings, faithfully preserving all the “information” from the input.

This is often not the case, to such an extent that sometimes a lossy compression of the data is highly beneficial. To give you a concrete example, consider a dataset with a million features, out of which only a couple hundred are useful. What we can do is identify the important features and throw away the rest, obtaining a representation that is more compact, thus easier to work with.

This notion is formalized by the concept of orthogonal projections. We already met them upon our first encounter with the inner products (see (2.7)).

Projections also play a fundamental role in the Gram-Schmidt process (Theorem 13), used to orthogonalize an arbitrary basis. Because we are already somewhat familiar with orthogonal projections, a formal definition is due.

Definition 28. (Projections and orthogonal projections)

Let V be an arbitrary inner product space and P : V → V be a linear transformation. P is a projection if P2 = P.

A projection P is orthogonal if the subspaces kerP and imP are orthogonal to each other. (That is, for every pair of x ∈ kerP and y ∈ imP, we have ⟨x,y⟩ = 0.)

Let’s revisit the examples we have seen so far to get a grip on the definition!

Example 1. The simplest one is the orthogonal projection to a single vector. That is, if u ∈ℝn is an arbitrary vector, the transformation

proju(x) = ⟨x,u⟩-u ⟨u,u ⟩

is the orthogonal projection to (the subspace spanned by) u. (We talked about this when discussing the geometric interpretation of inner products in Section 2.2.3, where this definition was deduced from a geometric intuition.) Applying this transformation repeatedly, we get

 ⟨x,u⟩ ⟨⟨u,u⟩u,-u⟩ proju(proju (x )) = ⟨u,u ⟩ u ⟨x,u⟩ -⟨u,u⟩⟨u,-u⟩ = ⟨u,u ⟩ u = ⟨x,u-⟩u ⟨u,u ⟩ = proj (x). u

Thus, faithfully to its name,

is indeed a projection. To see that it is orthogonal, let’s examine its kernel and image! Since the value of

is a scalar multiple of

, its image is

im (proj) = span(u). u

Its kernel, the set of vectors mapped to 0 by proju, is also easy to find, as ⟨⟨xu,,uu⟩⟩u = 0 can only happen if ⟨x,u⟩ = 0, that is, if x ⊥u.

In other words,

ker(proju) = span (u)⊥,

where span(u)⊥ denotes the orthogonal complement (Definition 13) of span(u). This means that proju is indeed an orthogonal projection.

We can also describe

in terms of matrices. By writing out

component-wise, we have

 ⌊ ⌋ | ⟨x,u⟩u1| ⟨x,u⟩ 1 | ⟨x,u⟩u2| proju(x) = -----u = ----2|| . || , ⟨u, u⟩ ∥u ∥ |⌈ .. |⌉ ⟨x,u⟩u n

where u = (u1,…,un). This looks like some kind of matrix multiplication! As we saw earlier, multiplying a matrix and a vector can be described in terms of rowwise dot products. (See (3.3).)

So, according to this interpretation of matrix multiplication, we have

L(U,V ) = {f : U → V | f is linear}

(7.5)

Note that the scaling with ∥u∥2 can be incorporated into the “matrix” product by writing

 T T uu---= -u--⋅ u--, ∥u∥2 ∥u ∥ ∥u∥

The matrix uuT ∈ℝn×n, obtained from the product of the vector u ∈ℝn(×1) and its transpose uT ∈ℝ1×n, is a rather special one. They are called rank-1 projection matrices, and they frequently appear in mathematics.

(In general, the matrix uvT is called the outer product of the vectors u and v. We won’t use this extensively, but it appears frequently throughout linear algebra.)

Example 2. As we saw when introducing the Gram-Schmidt orthogonalization process (Theorem 13), the previous example can be generalized by projecting to multiple vectors. If u1,…,uk ∈ℝn is a set of linearly independent and pairwise orthogonal vectors, then the linear transformation

 ∑k ⟨x, ui⟩ proju1,...,uk(x) = -------ui i=1 ⟨ui,ui⟩

is an orthogonal projection onto the subspace span(u1,…,uk). This is easy to see, and I recommend the reader to do this as an exercise. (This can be found in the problems section as well.)

From (7.5), we can determine the matrix form of proju1,…,uk as well:

 ∑k T proj (x) = ( uiu-i) x. u1,...,uk i=1 ∥ui∥2 ◟----◝◜---◞ ∈ℝn×n

This is good to know, as projection matrices are often needed in the implementation of certain algorithms.

7.4.1 Properties of orthogonal projections

Section titled “7.4.1 Properties of orthogonal projections”

Now that we have seen a few examples, it is time to discuss orthogonal projections in more general terms. There are lots of reasons why these special transformations are useful, and we’ll explore them in this section. First, let’s start with the most important one: orthogonal projections also enable the decomposition of vectors in terms of a given subspace plus an orthogonal vector.

Theorem 45.

Let V be an inner product space and P : V → V be a projection. Then, V = kerP + imP; that is, every vector x ∈V can be written as

x = x + x , x ∈ ker P, x ∈ im P. ker im ker im

If P is an orthogonal projection, then xim ⊥xker.

Proof. Every x can be written as

x = (x − Px )+ Px.

Since P is idempotent, that is, P2 = P, we have

P (x − P x) = Px − P (Px) = Px − P x = 0,

that is, x −Px ∈ kerP. By definition, Px ∈ imP, so V = kerV + imV , which proves our main proposition.

If P is an orthogonal projection, then again, by definition, xim ⊥xker, which is what we had to show.

In addition, orthogonal projections are self-adjoint. This might not sound like a big deal, but self-adjointness leads to several very pleasant properties.

Theorem 46.

Let V be an inner product space and P : V →V be an orthogonal projection. Then, P is self-adjoint.

Proof. According to the definition (27), all we need to show is that

⟨Px, y⟩ = ⟨x, Py⟩

holds for any x,y ∈V . In the previous result, we have seen that x and y can be written as

x = xker P + xim P, xker P ∈ ker P, xim P ∈ im P

y = yker P + yim P, yker P ∈ ker P, yim P ∈ im P

Since P2 = P, we have

⟨P x,y⟩ = ⟨PxkerP + Pxim P,ykerP + yim P⟩ = ⟨xim P,ykerP + yim P⟩ = ⟨x ,y ⟩+ ⟨x ,y ⟩ ◟-im-P◝◜kerP◞ im P im P =0 = ⟨xim P,yimP ⟩.

Similarly, it can be shown that ⟨x,Py⟩ = ⟨xim P ,yim P ⟩. These two identities imply ⟨Px,y⟩ = ⟨x,Py⟩, which is what we had to show.

One straightforward consequence of self-adjointness is that the kernel of orthogonal projections is the orthogonal complement of its image.

Theorem 47. Let V be an inner product space and P : V → V be an orthogonal projection. Then,

 ⊥ ker P = (im P ) .

Proof. To prove the equality of these two sets, we need to show that (a) kerP ⊆ (imP)⊥, and (b) (imP)⊥⊆ kerP.

(a) Let x ∈ kerP; that is, suppose that Px = 0. We need to show that for any y ∈ imP, we have ⟨x,y⟩ = 0. For this, let y0 ∈V such that Py0 = y. (This is guaranteed to exist, since we took y from the image of P.) Then,

⟨x,y ⟩ = ⟨x,P y0⟩ = ⟨P x,y0⟩ = ⟨0,y0⟩ = 0,

where P is self-adjoint. Thus, x ∈ (imP)⊥ also holds, implying kerP ⊆ (imP)⊥.

(b) Now, let x ∈ (imP)⊥. Then, for any y ∈V , we have ⟨x,Py⟩ = 0. However,

⟨Px,y ⟩ = ⟨x,P y⟩ = 0.

Especially, with the choice y = Px, we have ⟨Px,Px⟩ = 0. Due to the positive definiteness of the inner product, this implies that Px = 0, that is, x ∈ kerP.

Summing up all of the above, if P is an orthogonal projection of the inner product space V , then

V = im P + (im P )⊥.

Do you recall that when we first encountered the concept of orthogonal complements (Definition 13), we proved that V = S + S⊥ for any finite-dimensional inner product space V and its subspace S? We did this with the use of a special orthogonal projection. We are getting close to seeing the general pattern here.

Because the kernel of an orthogonal projection P is an orthogonal complement of the image, the transformation I −P is an orthogonal projection as well, with the roles of image and kernel reversed.

Theorem 48.

Let V be an inner product space and P : V →V be an orthogonal projection. Then, I −P is an orthogonal projection as well, and

ker(I − P ) = im P, im (I − P ) = ker P.

The proof is so simple that this is left as an exercise for the reader.

One more thing to mention. If the image spaces of two orthogonal projections match, then the projections themselves are equal. This is a very strong uniqueness property, as if you think about it, this is not true for other classes of linear transformations.

Theorem 49. (Uniqueness of orthogonal projections)

Let V be an inner product space and P,Q : V → V be two orthogonal projections. If imP = imQ, then P = Q.

Proof. Because of kerP = (imP)⊥, the equality of the image spaces also imply that kerP = kerQ.

Since V = kerP + imP, every x ∈V can be decomposed as

x = xkerP + xim P, xkerP ∈ kerP, xim P ∈ im P.

This decomposition and the equality of the kernel and image spaces give that

Px = P xkerP + P ximP = xim P.

With an identical argument, we have Qx = xim P , thus Px = Qx on all vectors x ∈V . This proves P = Q.

In other words, given a subspace, there can be only one orthogonal projection to it. But is there any at all? Yes, and in the next section, we will see that it can be described in geometric terms.

7.4.2 Orthogonal projections are the optimal projections

Section titled “7.4.2 Orthogonal projections are the optimal projections”

Orthogonal projections have an extremely pleasant and mathematically useful property. In some sense, if P : V →V is an orthogonal projection, Px provides the optimal approximation of x among all vectors in imP. To make this precise, we can state the following.

Theorem 50. (Construction of orthogonal transformations)

Let V be a finite-dimensional inner product space and S ⊆V its subspace. Then, the transformation P : V →V , defined by

P : x → argmyi∈nS ∥x − y∥

is an orthogonal projection to S.

In other words, since orthogonal projections to a given subspace are unique (as implied by Theorem 49), Px is the closest vector to x in the subspace S. Thus, we can denote this as PS, emphasizing the uniqueness.

Besides having an explicit way to describe orthogonal projections, there is one extra benefit. Recall that previously, we showed that

V = im P + (im P)⊥

holds. Since for any subspace S an orthogonal projection PS exists whose image set is S, it also follows that V = S + S⊥. Although we saw this earlier when talking about orthogonal complements (Definition 13), it is interesting to see a proof that doesn’t require the construction of an orthonormal basis in S.

Interestingly, this is the point where mathematical analysis and linear algebra intersect. We don’t have the tools for it yet, but using the concept of convergence, the above theorems can be generalized to infinite-dimensional spaces. Infinite-dimensional spaces are not particularly relevant to machine learning in practice, yet they provide a beautiful mathematical framework for the study of functions. Who knows, one day these advanced tools may provide a significant breakthrough in machine learning.

day-mode Bookmark

In the last chapter, we reached the singular value decomposition, one of the pinnacle results of linear algebra. We laid out the theoretical groundwork to get us to this point.

However, one thing is missing: computing the singular value decomposition in practice. Without this, we can’t reap all the rewards this powerful tool offers. In this section, we’ll develop two methods for this purpose. One offers a deep insight into the behavior of eigenvectors, but it doesn’t work in practice. The other offers excellent performance, but it is hard to understand what is happening behind the formulas. Let’s start with the first one, illuminating how the eigenvectors determine the effects of a linear transformation!

7.5.1 Power iteration for calculating the eigenvectors of real symmetric matrices

Section titled “7.5.1 Power iteration for calculating the eigenvectors of real symmetric matrices”

If you recall, we discovered the singular value decomposition by tracing the problem back to the spectral decomposition of symmetric matrices. In turn, we can obtain the spectral decomposition by finding an orthonormal basis from the eigenvectors of our matrix. The plan is the following: first, we define a procedure that finds an orthonormal set of eigenvectors for symmetric matrices. Then, use this to compute the singular value decomposition for arbitrary matrices.

A naive way would be to find the eigenvalues by solving the polynomial equation det(A−λI) = 0 for λ, then compute the corresponding eigenvectors by solving the linear equations (A −λI)x = 0.

However, there are problems with this approach. For an n ×n matrix, the characteristic polynomial p(λ) = det(A−λI) is a polynomial of degree n. Even if we could effectively evaluate det(A −λI) for any lambda, there are serious issues. Unfortunately, unlike for the quadratic equation ax2 + bx + c = 0, there are no formulas for finding the solutions when n>4. (It is not that mathematicians were just not clever enough to find them. No such formula exists.)

How can we find an alternative approach? Once again, we use the wishful thinking approach that worked so well before. Let’s pretend that we know the eigenvalues, play around with them, and see if this gives us some useful insight.

For the sake of simplicity, assume that A is a small symmetric 2 × 2 matrix, say with eigenvalues λ1 = 4 and λ2 = 2. Since A is symmetric, we can even find a set of corresponding eigenvectors u1,u2 such that u1 and u2 form an orthonormal basis. (That is, both have a unit norm and they are orthogonal to each other.) This is guaranteed by the spectral decomposition theorem (Theorem 41).

Thus, any x ∈ℝ2 can be written as x = x1u1 + x2u2 for some nonzero scalars x1,x2. What happens if we apply the transformation A to our vector x? Because ui is eigenvectors, we have

Ax = A (x1u1 + x2u2 ) = x1Au1 + x2Au2 = x1λ1u1 + x2λ2u2 = 4x1u1 + 2x2u2.

By applying A one more time, we obtain

 2 2 2 A x = x1λ1u1 + x2λ2u2 2 2 = 4x1u1 + 2 x2u2.

A pattern starts to emerge. In general, the k-th iteration of A yields

Akx = x1 λk1u1 + x2λk2u2 = 4kx1u1 + 2kx2u2.

By taking an inquisitive look at Akx, we can note that the contribution of u1 is much more significant than u2. Why? Because the coefficient x1λ1k = 4kx1 grows faster than x2λ2k = 2kx2, regardless of the value of x1 and x2. In technical terms, we say that λ1 dominates λ2.

Now, by scaling things down with λ1k, we can extract the eigenvector u1! That is,

Akx- λ2- k λk = x1u1 + x2(λ1 ) u2 1 = x1u1 + (something very small)k.

If we let k grow infinitely, the contribution of u2 to Akkx- λ1 vanishes. If you are familiar with the concept of limits, you could write

limk → ∞ (A_k x - λ_k 1) = x1u1.

(7.6)

Remark 7. (A primer on limits)

If you are not familiar with limits, here is a quick explanation. The identity

 Akx lim --k- = x1u1 k→ ∞ λ1

means that as k grows, the quantity Akx- λk1 gets closer and closer to x1u1, until the difference between them is infinitesimal. In practice, this means that we can approximate x1u1 by Akx- λk1 by selecting a very large k.

Equation (7.6) is great news for us! All we have to do is repeatedly apply the transformation A to identify the eigenvector for the dominant eigenvalue λ1. There is one small caveat, though: we have to know the value of λ1. We’ll deal with this later, but first, let’s record this milestone in the form of a theorem.

Theorem 51.

Finding the eigenvector for the dominant eigenvalue with power iteration.

Let A ∈ℝn×n be a real symmetric matrix. Suppose that:

(a) The eigenvalues of A are λ1>…>λn (that is, λ1 is the dominant eigenvalue).

(b) The corresponding eigenvectors u1,…,un form an orthonormal basis.

Let x ∈ℝn be a vector such that when written as the linear combination x = ∑ i=1nxiui, the coefficient x1 ∈ℝ is nonzero. Then,

limk → ∞ (A_k x - λ_k 1) = x1u1.

(7.7)

Before we jump into the proof, some explanations are in order. Recall that if A is symmetric, the spectral decomposition theorem (Theorem 41) guarantees that it can be diagonalized with a similarity transformation. In its proof (sketch), we mentioned that a symmetric matrix has:

  • Real eigenvalues
  • An orthonormal basis from its eigenvectors

Thus, the assumptions (a) and (b) are guaranteed, except for one caveat: the eigenvalues are not necessarily distinct. However, this rarely causes problems in practice. There are multiple reasons for this, but most importantly, matrices with repeated eigenvalues are so rare that they form a zero-probability set. (We’ll learn about probability later in the book. For now, we can assume that randomly picking a matrix with repeated eigenvalues is impossible.) Thus, stumbling upon one is highly unlikely.

Proof. Because uk is the eigenvector for the eigenvalue λk, we have

Akx = ∑i=1n xiλikui. (7.8)

Thus,

 n Akx- ∑ λi-k λk = x1u1 + xi(λ1) ui. 1 i=2

Since λ1 is the dominant eigenvalue, ∥λi∕λ1∥>1 for i = 2,…,n, so (λi∕λ1)k → 0 as k →∞. Hence,

 Akx- kli→m∞ λk = x1u1. 1

This is what we had to show.

Now, let’s fix the small issue that requires us to know

. Since

is the largest eigenvalue, the previous theorem shows that

equals

plus some term that is much smaller, at least compared to this dominant term. We can extract this quantity by taking the supremum norm

. (Recall that for any

, the supremum norm is defined by

. Keep in mind that the

-s are the coefficients of

in the original basis of our vector space, which is not necessarily our eigenvector basis

.)

By factoring out jλ1jk from Akx, we have

 ∑n ∥Akx ∥∞ = |λ1|k∥x1u1 + xi(λi)kui∥∞. i=2 λ1

Intuitively speaking, the remainder term ∑ i=2nxi(λi λ1)kui is small, thus we can approximate the norm as

∥Akx ∥∞ ≈ |λ1 |k∥x1u1∥ ∞.

In other words, instead of scaling with

, we can scale with

.

So, we are ready to describe our general eigenvector-finding procedure fully. First, we initialize a vector x0 randomly, then we define the recursive sequence

 Axk −1 xk = ----------, k = 1,2,... ∥Axk −1∥∞

Using the linearity of A, we can see that, in fact,

 k xk = --A--x0--, ∥Akx0 ∥∞

but scaling has an additional side benefit, as we don’t have to use large numbers at any computational step. With this, (51) implies that

 --Akx0--- lki→m∞ xk = kl→im∞ ∥Akx0 ∥∞ = u1.

That is, we can extract the eigenvector for the dominant eigenvalue without actually knowing the eigenvalue itself.

Let’s put the power iteration method into practice! The input of our power_iteration function is a square matrix A, and we expect the output to be an eigenvector corresponding to the dominant eigenvalue.

Since this is an iterative process, we should define a condition that defines when the process should terminate. If the consecutive members of the sequence {xk}k=1∞ are sufficiently close together, we arrived at a solution. That is, if, say,

∥xk+1 − xk∥2 <1× 10−10,

we can stop and return the current value. However, this might never happen. For those cases, we define a cutoff point, say, k = 100,000, when we terminate the computation, even if there is no convergence.

To give us a bit more control, we can also manually define the initialization vector x_init.

import numpy as np
def power_iteration(
A: np.ndarray,
n_max_steps: int = 100000,
convergence_threshold: float = 1e-10,
x_init: np.ndarray = None,
normalize: bool = False
):
"""
Performs the power iteration method to find an approximation of the dominant eigenvector
of a square matrix.
Parameters
----------
A : np.ndarray
A square matrix whose dominant eigenvector is to be computed.
n_max_steps : int, optional
The maximum number of iterations to perform. Default is 100000.
convergence_threshold : float, optional
The convergence threshold for the difference between successive approximations.
Default is 1e-10.
x_init : np.ndarray, optional
The initial guess for the eigenvector. If None, a random vector is used.
Default is None.
normalize : bool, optional
If True, the resulting vector is normalized to unit length. Default is False.
Returns
-------
np.ndarray
The approximate dominant eigenvector of the matrix ‘A‘.
Raises
------
ValueError
If the input matrix ‘A‘ is not square.
"""
n, m = A.shape
# checking the validity of the input
if n != m:
raise ValueError("the matrix A must be square
# reshaping or defining the initial vector
if x_init is not None:
x = x_init.reshape(-1, 1)
else:
x = np.random.normal(size=(n, 1))
# performing the iteration
for step in range(n_max_steps):
x_transformed = A @ x # applying the transform
x_new = x_transformed / np.linalg.norm(x_transformed, ord=np.inf) # scaling the result
# quantifying the difference between the new and old vector
diff = np.linalg.norm(x - x_new)
x = x_new
# stopping the iteration in case of convergence
if diff < convergence_threshold:
break
# normalizing the result if required
if normalize:
return x / np.linalg.norm(x)
return x

To test the method, we should use an input for which the correct output is easy to calculate by hand. Our usual recurring example

 ⌊ ⌋ 2 1 A = ⌈ ⌉ . 1 2

should be perfect, as we already know a lot about it.

Previously, we have seen in Section 6.2.2 that its eigenvalues are λ1 = 3 and λ2 = 1, with corresponding eigenvectors u1 = (1,1) and u2 = (−1,1).

Let’s see if our function correctly recovers (a scalar multiple of) u1 = (1,1)!

A = np.array([[2, 1], [1, 2]])
u_1 = power_iteration(A, normalize=True)
u_1
array([[0.70710678],
      [0.70710678]])

Success! To recover the eigenvalue, we can simply apply the linear transformation and compute the proportions.

A @ u_1 / u_1
array([[3.],
      [3.]])

The result is 3, as expected.

7.5.3 Power iteration for the rest of the eigenvectors

Section titled “7.5.3 Power iteration for the rest of the eigenvectors”

Can we modify the power iteration algorithm to recover the other eigenvalues as well? In theory, yes. In practice, no. Let me elaborate!

To get a grip on how to generalize the idea, let’s take another look at the equation (7.8), saying that

 ∑n Akx = xiλkiui. i=1

One of the conditions for  k Aλxk- 1 to converge was that x should have a nonzero component of the eigenvector u1, that is, x1≠0.

What if x1 = 0? In that case, we have

Akx = x2λk2u2 + ⋅⋅⋅+ xnλk2un,

with x2λ2ku2 becoming the dominant term.

Thus, we have

Akx ∑n λi k --k-= x2u2 + xi( --) uk λ 2 i=3 λ2 = x u + (something very small), 2 2 k

implying that

 Akx lim --k-= x2u2. k→∞ λ 2

Let’s make this mathematically precise in the following theorem.

Theorem 52. (Generalized power iteration)

Let A ∈ℝn×n be a real symmetric matrix. Suppose that:

(a) The eigenvalues of A are λ1>…>λn (that is, λ1 is the dominant eigenvalue).

(b) The corresponding eigenvectors u1,…,un form an orthonormal basis.

Let

be a vector such that, when written as a linear combination of the basis

, its first nonzero component is along

for some

(that is,

).

Then,

 k lim A--x = xlul k→ ∞ λkl

holds.

The proof looks just like what we have seen a few times already. The question is, how can we eliminate the u1,…,ul−1 components from any vector? The answer is simple: orthogonal projections (Section 7.4).

For the sake of simplicity, let’s take a look at extracting the second dominant eigenvector with power iteration. Recall that the transformation

proj (x) = ⟨x, u ⟩u u1 1 1

describes the orthogonal projection of any x to u1.

In concrete terms, if x = ∑ i=1nxiui, then

 ∑n proju (x) = proju ( xiui) 1 1 i=1 ∑n = xiproj (ui) i=1 u1 = x1u1.

This is the exact opposite of what we are looking for! However, at this point, we can see that I − proju1 is going to be suitable for our purposes. This is still an orthogonal projection. Moreover, we have

 ∑n ∑n (I − proju1)( xiui) = xiui, i=1 i=2

That is, I − proju1 eliminates the u1 component of x. Thus, if we initialize the power iteration with x∗ = (I − proju1)(x), the sequence --Akx∗-- ∥Akx∗∥∞ will converge to u2, the second dominant eigenvector.

How do we compute (I − proj )(x) u1 in practice? Recall that in the standard orthonormal basis, the matrix of proju1 can be written as:

proju1 = u1uT1.

(Keep in mind that the

vectors form an orthonormal basis, so ∥u1∥ = 1 .) Thus, the matrix of

is:

I − u1uT1,

which we can easily compute.

For a general vector u, this is how we can do this in NumPy.

def get_orthogonal_complement_projection(u: np.ndarray):
"""
Compute the projection matrix onto the orthogonal complement of the vector u.
This function returns a projection matrix P such that for any vector v,
P @ v is the projection of v onto the subspace orthogonal to u.
Parameters
----------
u : np.ndarray
A 1D or 2D array representing the vector u. It will be reshaped to a column vector.
Returns
-------
np.ndarray
The projection matrix onto the orthogonal complement of u. This matrix
has shape (n, n), where n is the length of u.
"""
u = u.reshape(-1, 1)
n, _ = u.shape
return np.eye(n) - u @ u.T / np.linalg.norm(u, ord=2)**2

So, the procedure to find all the eigenvectors is the following.

  1. Initialize a random and use the power iteration to find .
  2. Project to the orthogonal complement of the subspace spanned by , thus obtaining x (2) := (I − proju1)(x(1)), which we use as the initial vector of the second round of power iteration, yielding the second dominant eigenvector .
  3. Project to the orthogonal complement of the subspace spanned by and , thus obtaining x(3) = (I − proju2)(x(2)) (1) = (I − proju1,u2)(x ), which we use as the initial vector of the third round of power iteration, yielding the third dominant eigenvector .
  4. Project to…

You get the pattern. To implement this in practice, we add the find_eigenvectors function.

def find_eigenvectors(A: np.ndarray, x_init: np.ndarray):
"""
Find the eigenvectors of the matrix A using the power iteration method.
This function computes the eigenvectors of the matrix A by iteratively
applying the power iteration method and projecting out previously found
eigenvectors to find orthogonal eigenvectors.
Parameters
----------
A : np.ndarray
A square matrix of shape (n, n) for which eigenvectors are to be computed.
x_init : np.ndarray
A 1D array representing the initial vector used for the power iteration.
Returns
-------
List[np.ndarray]
A list of eigenvectors, each represented as a 1D numpy array of length n.
"""
n, _ = A.shape
eigenvectors = []
for _ in range(n):
ev = power_iteration(A, x_init=x_init)
proj = get_orthogonal_complement_projection(ev)
x_init = proj @ x_init
x_init = x_init / np.linalg.norm(x_init, ord=np.inf)
eigenvectors.append(ev)
return eigenvectors

Let’s test find_eigenvectors out on our old friend

 ⌊ ⌋ 2 1 A = ⌈ ⌉! 1 2

A = np.array([[2.0, 1.0], [1.0, 2.0]])
x_init = np.random.rand(2, 1)
find_eigenvectors(A, x_init)
[array([[1.],
       [1.]]),
 array([[ 1.],
       [-1.]])]

The result is as we expected. (Don’t be surprised that the eigenvectors are not normalized, as we haven’t explicitly done so in the find_eigenvectors function.)

We are ready to actually diagonalize symmetric matrices. Recall that the diagonalizing orthogonal matrix U can be obtained by vertically stacking the eigenvectors one by one.

def diagonalize_symmetric_matrix(A: np.ndarray, x_init: np.ndarray):
"""
Diagonalize a symmetric matrix A using its eigenvectors.
Parameters
----------
A : np.ndarray
A symmetric matrix of shape (n, n) to be diagonalized. The matrix should
be square and symmetric.
x_init : np.ndarray
A 1D array representing the initial guess for the power iteration.
Returns
-------
Tuple[np.ndarray, np.ndarray] containing:
- U : np.ndarray
A matrix of shape (n, n) whose columns are the normalized eigenvectors
of A.
- np.ndarray
A diagonal matrix (n, n) of the eigenvalues of A, computed as U @ A @ U.T.
"""
eigenvectors = find_eigenvectors(A, x_init)
U = np.hstack(eigenvectors) / np.linalg.norm(np.hstack(eigenvectors), axis=0, ord=2)
return U, U @ A @ U.T
diagonalize_symmetric_matrix(A, x_init)
(array([[ 0.70710678,  0.70710678],
       [ 0.70710678, -0.70710678]]),
 array([[ 3.00000000e+00, -3.57590301e-11],
       [-3.57589164e-11,  1.00000000e+00]]))

Awesome!

What’s the problem? Unfortunately, power iteration is numerically unstable. For n ×n matrices, where n can be in the millions, this is a serious issue.

Why did we talk so much about power iteration, then? Besides being the simplest, it offers a deep insight into how linear transformations work.

The identity

 ∑n Ax = xiλiui, i=1

where λi and ui are eigenvalue-eigenvector pairs of the symmetric matrix A, reflecting how eigenvectors and eigenvalues determine the behavior of the transformation.

If the power iteration is not usable in practice, how can we compute the eigenvalues? We will see this in the next section.

day-mode Bookmark

The algorithm used in practice to compute the eigenvalues is the so-called QR algorithm, proposed independently by John G. R. Francis and the Soviet mathematician Vera Kublanovskaya. This is where all of the lessons we have learned in linear algebra converge. Describing the QR algorithm is very simple, as it is the iteration of a matrix decomposition and a multiplication step.

However, understanding why it works is a different question. Behind the scenes, the QR algorithm combines many tools we have learned earlier. To start, let’s revisit the good old Gram-Schmidt orthogonalization process.

If you recall, we encountered the Gram-Schmidt orthogonalization process (Theorem 13) when introducing the concept of orthogonal bases.

In essence, this algorithm takes an arbitrary basis v1,…,vn and turns it into an orthonormal one e1,…,en, such that e1,…,ek spans the same subspace as v1,…,vk for all 1 ≤k ≤n. Since we last met this, we have gained a lot of perspective on linear algebra, so we are ready to see the bigger picture.

With the orthogonal projections defined by

 ∑k ⟨x,ei⟩ proje1,...,ek(x) = ------ei, i=1 ⟨ei,ei⟩

we can describe the Gram-Schmidt process recursively as

e1 = v1, ek = vk − proje1,...,ek−1(vk),

where the ek vectors are normalized after.

By expanding this and writing out ek explicitly, we have

e1 = v1 e2 = v2 − ⟨v2,e1⟩e1 ⟨e1,e1⟩ .. . ⟨vn, e1⟩ ⟨vn, en−1⟩ en = vn − ⟨e-,e-⟩e1 − ⋅⋅⋅− ⟨e----,e---⟩en−1. 1 1 n− 1 n−1

A pattern is starting to emerge. By arranging the e1,…,en terms on one side, we obtain

v1 = e1 ⟨v2,e1⟩ v2 = ⟨e-,e-⟩e1 + e2 1 1 ... vn = ⟨vn,e1⟩e1 + ⋅⋅⋅ + -⟨vn,en−1⟩-en−1 + en. ⟨e1,e1⟩ ⟨en−1,en−1⟩

This is starting to resemble some kind of matrix multiplication! Recall that matrix multiplication can be viewed as taking the linear combination of columns. (Check (4.2) if you are uncertain about this.)

By horizontally concatenating the column vectors vk to form the matrix A and similarly defining the vector Q from the ek-s, we obtain that

A = Q∗R ∗

for some upper triangular R, defined by the coefficients of ek in vk according to the Gram-Schmidt orthogonalization. To be more precise, define

 ⌊ ⌋ ⌊ ⌋ A = ||v ... v || , Q ∗ = || e ... e || , ⌈ 1 n⌉ ⌈ 1 n⌉

and

 ⌊ ⟨v2,e1⟩ ⟨vn,e1⟩⌋ |1 ⟨e1,e1⟩ ... ⟨e1,e1⟩| ||0 1 ... ⟨vn,e2⟩|| R ∗ = |. . ⟨e2,.e2⟩|. ||.. .. ... .. || ⌈ .. ⌉ 0 0 . 1

The result A = Q∗R∗ is almost what we call the QR factorization. The columns of Q∗ are orthogonal (but not orthonormal), while R∗ is upper triangular. We can easily orthonormalize Q∗ by factoring out the norms columnwise, thus obtaining

 ⌊ ⌋ ∥e ∥ √⟨v2,e1⟩-- ... √⟨vn,e1⟩- ⌊ ⌋ | 1 ⟨e1,e1⟩ ⟨e1,e1⟩| | | || 0 ∥e2∥ ... √⟨vn,e2⟩|| Q = |⌈ e1-- ... en-|⌉ , R = || ⟨e2,e2⟩|| . ∥e1∥ ∥en∥ || ... ... ... ... || ⌈ . ⌉ 0 0 .. ∥en∥

It is easy to see that A = QR still holds. This result is called the QR decomposition, and we have just proved the following theorem.

Theorem 53. (QR decomposition)

Let A ∈ ℝn×n be an invertible matrix. Then, there exists an orthogonal matrix Q ∈ℝn×n and an upper triangular matrix R ∈ℝn×n such that

A = QR

holds.

As we are about to see, the QR decomposition is an extremely useful and versatile tool (like all other matrix decompositions are). Before we move forward to discuss how it can be used to compute the eigenvalues in practice, let’s put what we have seen so far into code!

The QR decomposition algorithm is essentially Gram-Schmidt orthogonalization, where we explicitly memorize some coefficients and form a matrix from them. (Recall our earlier implementation in Section 3.1.2 if you feel overwhelmed.)

def projection_coeff(x: np.ndarray, to: np.ndarray):
"""
Compute the scalar coefficient for the projection of vector x onto vector to.
Parameters
----------
x : np.ndarray
A 1D array representing the vector onto which the projection is computed.
to : np.ndarray
A 1D array representing the vector onto which x is being projected.
Returns
-------
float
The scalar coefficient representing the projection of x onto to.
"""
return np.dot(x, to)/np.dot(to, to)
from typing import List
def projection(x: np.ndarray, to: List[np.ndarray], return_coeffs: bool = True):
"""
Computes the orthogonal projection of a vector \`x\` onto the subspace
spanned by a set of vectors \`to\`.
Parameters
----------
x : np.ndarray
A 1D array representing the vector to be projected onto the subspace.
to : List[np.ndarray]
A list of 1D arrays, each representing a vector spanning the subspace
onto which \`x\` is projected.
return_coeffs : bool, optional, default=True
If True, the function returns the list of projection coefficients.
If False, only the projected vector is returned.
Returns
-------
Tuple[np.ndarray, List[float]] or np.ndarray
- If \`return_coeffs\` is True, returns a tuple where the first element
is the projected vector and
the second element is a list of the projection coefficients
for each vector in \`to\`.
- If \`return_coeffs\` is False, returns only the projected vector.
"""
p_x = np.zeros_like(x)
coeffs = []
for e in to:
coeff = projection_coeff(x, e)
coeffs.append(coeff)
p_x += coeff*e
if return_coeffs:
return p_x, coeffs
else:
return p_x

Now we can put these together to obtain the QR factorization of an arbitrary square matrix. (Surprisingly, this works for non-square matrices as well, but we won’t be concerned with this.)

def QR(A: np.ndarray):
"""
Computes the QR decomposition of matrix A using the Gram-Schmidt
orthogonalization process.
Parameters
----------
A : np.ndarray
A 2D array of shape (n, m) representing the matrix to be decomposed.
The matrix A should have full column rank for a valid QR decomposition.
Returns
-------
Tuple[np.ndarray, np.ndarray]
- Q : np.ndarray
An orthogonal matrix of shape (n, m), whose columns are orthonormal.
- R : np.ndarray
An upper triangular matrix of shape (m, m), representing the coefficients of the
linear combinations of the columns of A.
"""
n, m = A.shape
A_columns = [A[:, i] for i in range(A.shape[1])]
Q_columns, R_columns = [], []
Q_columns.append(A_columns[0])
R_columns.append([1] + (m-1)*[0])
for i, a in enumerate(A_columns[1:]):
p, coeffs = projection(a, Q_columns, return_coeffs=True)
next_q = a - p
next_r = coeffs + [1] + max(0, m - i - 2)*[0]
Q_columns.append(next_q)
R_columns.append(next_r)
# assembling Q and R from its columns
Q, R = np.array(Q_columns).T, np.array(R_columns).T
# normalizing Q’s columns
Q_norms = np.linalg.norm(Q, axis=0)
Q = Q/Q_norms
R = np.diag(Q_norms) @ R
return Q, R

Let’s try it out on a random 3 × 3 matrix.

A = np.random.rand(3, 3)
Q, R = QR(A)

There are three things to check: (a) A = QR, (b) Q is an orthogonal matrix, and (c) R is upper triangular.

np.allclose(A, Q @ R)
True
np.allclose(Q.T @ Q, np.eye(3))
True
np.allclose(R, np.triu(R))
True

Success! There is only one more question left. How does this help us in calculating the eigenvalues? Let’s see that now.

Surprisingly, we can discover the eigenvalues of a matrix A by a simple iterative process. First, we find the QR decomposition

A = Q R , 1 1

and define the matrix A1 by

A1 = R1Q1,

That is, we simply reverse the order of Q and R. Then, we start it all over and find the QR decomposition of A1, and so on, defining the sequence

L(U,V ) = {f : U → V | f is linear}

(7.9)

In the long run, the diagonal elements of Ak will get closer and closer to the eigenvalues of A. This is called the QR algorithm, which is so simple that I didn’t believe it when I first saw it.

With all of our tools, we can implement the QR algorithm in a few lines.

def QR_algorithm(A: np.ndarray, n_iter: int = 1000):
"""
Computes the QR algorithm to find the eigenvalues of a matrix A.
Parameters
----------
A : np.ndarray
A square matrix of shape (n, n) for which the eigenvalues are to be computed.
n_iter : int, optional, default=1000
The number of iterations to run the QR algorithm.
More iterations may lead to more accurate results,
but the algorithm typically converges quickly.
Returns
-------
np.ndarray
A matrix that has converged, where the diagonal elements are the eigenvalues of the
original matrix A.
The off-diagonal elements should be close to zero.
"""
for _ in range(n_iter):
Q, R = QR(A)
A = R @ Q
return A

Let’s test it right away.

A = np.array([[2.0, 1.0], [1.0, 2.0]])
QR_algorithm(A)
array([[3.00000000e+00, 2.39107046e-16],
      [0.00000000e+00, 1.00000000e+00]])

We are almost at the state of the art. Unfortunately, the vanilla QR algorithm has some issues, as it can fail to converge. A simple example is given by the matrix

 ⌊ ⌋ A = ⌈0 1⌉ . 1 0

A = np.array([[0.0, 1.0], [1.0, 0.0]])
QR_algorithm(A)
array([[0., 1.],
      [1., 0.]])

In practice, we can solve this with the introduction of shifts:

L(U,V ) = {f : U → V | f is linear}

(7.10)

where αk is some scalar. There are multiple approaches to defining the shifts themselves (Rayleigh quotient shift, Wilkinson shift, etc.), but the details lie much deeper than our study.

day-mode Bookmark

I told you that climbing the peak is not easy: so far, this was our hardest chapter yet. However, the tools we’ve learned are at the pinnacle of linear algebra. We started by studying two special transformations: the self-adjoint and orthogonal ones. The former ones gave the spectral decomposition theorem, while the latter ones gave the singular value decomposition.

Undoubtedly, the SVD is one of the most important results in linear algebra, stating that every rectangular matrix A can be written in the form

A = U ΣV T,

where U ∈ℝn×n, Σ ∈ℝn×m, and V ∈ℝm×m are rather special: Σ is diagonal, while U and V are orthogonal.

When viewing A as a linear transformation, the singular value decomposition tells us that it can be written as the composition of two distance-preserving transformations (the orthogonal ones) and a simple scaling. That’s quite a characterization!

Speaking of singular values and eigenvalues, how do we find them in practice? Definitely not by solving the polynomial equation

det(A − λI ) = 0,

which is a computationally painful problem.

We’ve seen two actual methods for the task. One is the complicated, slow, unstable, but illuminating algorithm of power iteration, yielding eigenvectors for the dominant eigenvalue of a real and symmetric matrix A via the limit

 Akx0 lk→im∞ ∥Akx--∥-- = u1. 0 ∞

Although power iteration gives us valuable insight into the structure of such matrices, the real deal is the QR algorithm (unrelated to QR codes), originating from the vectorized version of the Gram-Schmidt algorithm. The QR algorithm is hard to intuitively understand, but despite its mystery, it provides a blazing-fast method for computing the eigenvalues in practice.

What’s next? Now that we are at the peak, it’s time to relax a bit and enjoy the beautiful view. The next chapter does just that.

You see, one of the most beautiful and useful topics in linear algebra is the connection between matrices and graphs. Because from the right perspective, a matrix is a graph, and we can utilize this relationship to study the structure of both. Let’s see!

day-mode Bookmark

Problem 1. Let u1,…,uk ∈ℝn be a set of linearly independent and pairwise orthogonal vectors. Show that the linear transformation

 ∑k ⟨x, ui⟩ proju1,...,uk(x) = ⟨u-,u-⟩ui i=1 i i

is an orthogonal projection.

Problem 2. Let u1,…,uk ∈ℝn be a set of linearly independent vectors, and define the linear transformation

 ∑k ⟨x,ui⟩- fakeproju1,...,uk(x ) = ⟨ui,ui⟩ui. i=1

Is this a projection? (Hint: Study the special case k = 2 and ℝ3. You can visualize this if needed.)

Problem 3. Let V be an inner product space and P : V →V be an orthogonal projection. Show that I −P is an orthogonal projection as well, and

ker(I − P ) = im P, im (I − P ) = ker P

holds.

Problem 4. Let A,B ∈ℝn×n be two square matrix that are written in the block matrix form

 ⌊ ⌋ ⌊ ⌋ A1,1 A1,2 B1,1 B1,2 A = ||A A ||, B = ||B B ||, ⌈ 2,1 2,2⌉ ⌈ 2,1 2,2⌉

where A1,1,B1,1 ∈ℝk×k, A1,2,B1,2 ∈ℝk×l, A2,1,B2,1 ∈ℝl×k, and A2,2,B2,2 ∈ℝl×l.

Show that

 ⌊ ⌋ A1,1B1,1 + A1,2B2,1 A1,1B1,2 + A1,2B2,2 || || AB = ⌈A2,1B1,1 + A2,2B2,1 A2,1B1,2 + A2,2B2,2⌉ .

Problem 5. Let A ∈ℝ2×2 be the square matrix defined by

 ⌊ ⌋ A = ⌈1 1⌉ . 1 0

(a) Show that the two eigenvalues of A are

 − 1 λ1 = φ, λ2 = − φ ,

where φ = 1+√5 --2-- is the golden ratio.

(b) Show that the eigenvectors of λ1 and λ2 are

 ⌊ ⌋ ⌊ −1⌋ f = ⌈φ ⌉, f = ⌈− φ ⌉ , 1 1 2 1

and show that they are orthogonal; that is, ⟨f1,f2⟩ = 0.

(c) Let U be the matrix formed by the eigenvectors of A, defined by

 ⌊ ⌋ φ − φ−1 U = ⌈ ⌉ . 1 1

Show that

 ⌊ ⌋ 1 φ −1 U −1 = √1-⌈ ⌉ . 5 − 1 φ

(d) Show that

 − 1 A = UΛU ,

where

 ⌊ ⌋ ⌊ ⌋ λ1 0 φ 0 Λ = ⌈ ⌉ = ⌈ −1⌉ . 0 λ2 0 − φ

(e) Were you wondering the purpose of all these mundane computations? Here comes the punchline. First, show that

 ⌊ ⌋ ⌊ ⌋ n An = ⌈1 1⌉ = ⌈Fn+1 Fn ⌉ , 1 0 Fn Fn−1

where Fn is the n-th Fibonacci number, defined by the recursive sequence

F0 = 0, F1 = 1, Fn = Fn−1 + Fn−2.

Consequently, show that A = UΛU−1 implies that