Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

The Trace Operator

Populating the interactive namespace from numpy and matplotlib

The Trace Operator

This chapter is very light! I can assure you that you will read it in 1 minute! It is nice after the last two chapters that were quite big! We will see what is the Trace of a matrix. It will be needed for the last chapter on the Principal Component Analysis (PCA).

The Trace Operator

Calculating the trace of a matrix The trace of matrix

The trace is the sum of all values in the diagonal of a square matrix.

A=[298471825]\boldsymbol{A}= \begin{bmatrix} 2 & 9 & 8 \\\\ 4 & 7 & 1 \\\\ 8 & 2 & 5 \end{bmatrix}
Tr(A)=2+7+5=14\mathrm{Tr}(\boldsymbol{A}) = 2 + 7 + 5 = 14

Numpy provides the function trace() to calculate it:

array([[2, 9, 8], [4, 7, 1], [8, 2, 5]])
14

GoodFellow et al. explain that the trace can be used to specify the Frobenius norm of a matrix (see 2.5). The Frobenius norm is the equivalent of the L2L^2 norm for matrices. It is defined by:

∥A∥F=∑i,jAi,j2\left\lVert \boldsymbol{A} \right\rVert_F=\sqrt{\sum_{i,j}A^2_{i,j}}

Take the square of all elements and sum them. Take the square root of the result. This norm can also be calculated with:

∥A∥F=Tr(AAT)\left\lVert \boldsymbol{A} \right\rVert_F=\sqrt{\mathrm{Tr}({\boldsymbol{AA}^T})}

We can check this. The first way to compute the norm can be done with the simple command np.linalg.norm():

17.549928774784245

The Frobenius norm of A\boldsymbol{A} is 17.549928774784245.

With the trace the result is identical:

17.549928774784245

Since the transposition of a matrix doesn’t change the diagonal, the trace of the matrix is equal to the trace of its transpose:

Tr(A)=Tr(AT)\mathrm{Tr}(\boldsymbol{A})=\mathrm{Tr}(\boldsymbol{A}^T)

Trace of a product

Tr(ABC)=Tr(CAB)=Tr(BCA)\mathrm{Tr}(\boldsymbol{ABC}) = \mathrm{Tr}(\boldsymbol{CAB}) = \mathrm{Tr}(\boldsymbol{BCA})

Example 1.

Let’s see an example of this property.

A=[41276]\boldsymbol{A}= \begin{bmatrix} 4 & 12 \\\\ 7 & 6 \end{bmatrix}
B=[1−343]\boldsymbol{B}= \begin{bmatrix} 1 & -3 \\\\ 4 & 3 \end{bmatrix}
C=[6625]\boldsymbol{C}= \begin{bmatrix} 6 & 6 \\\\ 2 & 5 \end{bmatrix}
531
531
531
ABC=[360432180171]\boldsymbol{ABC}= \begin{bmatrix} 360 & 432 \\\\ 180 & 171 \end{bmatrix}
CAB=[49812625933]\boldsymbol{CAB}= \begin{bmatrix} 498 & 126 \\\\ 259 & 33 \end{bmatrix}
BCA=[−63−54393594]\boldsymbol{BCA}= \begin{bmatrix} -63 & -54 \\\\ 393 & 594 \end{bmatrix}
Tr(ABC)=Tr(CAB)=Tr(BCA)=531\mathrm{Tr}(\boldsymbol{ABC}) = \mathrm{Tr}(\boldsymbol{CAB}) = \mathrm{Tr}(\boldsymbol{BCA}) = 531