Files
FYS-STK4155/doc/pub/week36/ipynb/week36.ipynb
T
2025-09-03 13:40:18 +02:00

239 KiB

Week 36: Linear Regression and Gradient descent

Morten Hjorth-Jensen, Department of Physics, University of Oslo, Norway

Date: September 1-5, 2025

Plans for week 36

Material for the lecture on Monday September 1:

  1. Linear Regression, ordinary least squares (OLS), Ridge and Lasso and mathematical analysis

  2. Derivation of Gradient descent and discussion of implementations for

  3. Video of lecture at https://youtu.be/nVE_FRnGAHw

  4. Whiteboard notes at https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2025/FYSSTKweek36.pdf

Material for the lab sessions on Tuesday and Wednesday (see at the end of these slides):

  1. Technicalities concerning Ridge and Lasso linear regression.

  2. Presentation and discussion of the first project

Reading suggestion:

  1. Goodfellow et al, Deep Learning, introduction to gradient descent, see chapter 4.3 at https://www.deeplearningbook.org/contents/numerical.html

  2. Rashcka et al, pages 37-44 and pages 278-283 with focus on linear regression.

  3. Video on gradient descent at https://www.youtube.com/watch?v=sDv4f4s2SB8

Material for lecture Monday September 2

Mathematical Interpretation of Ordinary Least Squares

What is presented here is a mathematical analysis of various regression algorithms (ordinary least squares, Ridge and Lasso Regression). The analysis is based on an important algorithm in linear algebra, the so-called Singular Value Decomposition (SVD).

We have shown that in ordinary least squares the optimal parameters \theta are given by


\hat{\boldsymbol{\theta}} = \left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.

The hat over \boldsymbol{\theta} means we have the optimal parameters after minimization of the cost function.

This means that our best model is defined as


\tilde{\boldsymbol{y}}=\boldsymbol{X}\hat{\boldsymbol{\theta}} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.

We now define a matrix


\boldsymbol{A}=\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T.

We can rewrite


\tilde{\boldsymbol{y}}=\boldsymbol{X}\hat{\boldsymbol{\theta}} = \boldsymbol{A}\boldsymbol{y}.

The matrix \boldsymbol{A} has the important property that \boldsymbol{A}^2=\boldsymbol{A}. This is the definition of a projection matrix. We can then interpret our optimal model \tilde{\boldsymbol{y}} as being represented by an orthogonal projection of \boldsymbol{y} onto a space defined by the column vectors of \boldsymbol{X}. In our case here the matrix \boldsymbol{A} is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix.

Residual Error

We have defined the residual error as


\boldsymbol{\epsilon}=\boldsymbol{y}-\tilde{\boldsymbol{y}}=\left[\boldsymbol{I}-\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\right]\boldsymbol{y}.

The residual errors are then the projections of \boldsymbol{y} onto the orthogonal component of the space defined by the column vectors of \boldsymbol{X}.

Simple case

If the matrix \boldsymbol{X} is an orthogonal (or unitary in case of complex values) matrix, we have


\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{X}\boldsymbol{X}^T = \boldsymbol{I}.

In this case the matrix \boldsymbol{A} becomes


\boldsymbol{A}=\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T)=\boldsymbol{I},

and we have the obvious case


\boldsymbol{\epsilon}=\boldsymbol{y}-\tilde{\boldsymbol{y}}=0.

This serves also as a useful test of our codes.

The singular value decomposition

The examples we have looked at so far are cases where we normally can invert the matrix \boldsymbol{X}^T\boldsymbol{X}. Using a polynomial expansion where we fit of various functions leads to row vectors of the design matrix which are essentially orthogonal due to the polynomial character of our model. Obtaining the inverse of the design matrix is then often done via a so-called LU, QR or Cholesky decomposition.

As we will also see in the first project, this may however not the be case in general and a standard matrix inversion algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below and in other examples.

There is however a way to circumvent this problem and also gain some insights about the ordinary least squares approach, and later shrinkage methods like Ridge and Lasso regressions.

This is given by the Singular Value Decomposition (SVD) algorithm, perhaps the most powerful linear algebra algorithm. The SVD provides a numerically stable matrix decomposition that is used in a large swath oc applications and the decomposition is always stable numerically.

In machine learning it plays a central role in dealing with for example design matrices that may be near singular or singular. Furthermore, as we will see here, the singular values can be related to the covariance matrix (and thereby the correlation matrix) and in turn the variance of a given quantity. It plays also an important role in the principal component analysis where high-dimensional data can be reduced to the statistically relevant features.

Linear Regression Problems

One of the typical problems we encounter with linear regression, in particular when the matrix \boldsymbol{X} (our so-called design matrix) is high-dimensional, are problems with near singular or singular matrices. The column vectors of \boldsymbol{X} may be linearly dependent, normally referred to as super-collinearity.
This means that the matrix may be rank deficient and it is basically impossible to to model the data using linear regression. As an example, consider the matrix


\begin{align*}
\mathbf{X} & =  \left[
\begin{array}{rrr}
1 & -1 & 2
\\
1 & 0 & 1
\\
1 & 2  & -1
\\
1 & 1  & 0
\end{array} \right]
\end{align*}

The columns of \boldsymbol{X} are linearly dependent. We see this easily since the the first column is the row-wise sum of the other two columns. The rank (more correct, the column rank) of a matrix is the dimension of the space spanned by the column vectors. Hence, the rank of \mathbf{X} is equal to the number of linearly independent columns. In this particular case the matrix has rank 2.

Super-collinearity of an $(n \times p)$-dimensional design matrix \mathbf{X} implies that the inverse of the matrix \boldsymbol{X}^T\boldsymbol{X} (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this


\begin{align*}
\boldsymbol{X} & =  \left[
\begin{array}{rr}
1 & -1
\\
1 & -1
\end{array} \right].
\end{align*}

We see easily that \mbox{det}(\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0. Hence, \mathbf{X} is singular and its inverse is undefined. This is equivalent to saying that the matrix \boldsymbol{X} has at least an eigenvalue which is zero.

Fixing the singularity

If our design matrix \boldsymbol{X} which enters the linear regression problem


\begin{equation}
\boldsymbol{\theta}  =  (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y},
\label{_auto1} \tag{1}
\end{equation}

has linearly dependent column vectors, we will not be able to compute the inverse of \boldsymbol{X}^T\boldsymbol{X} and we cannot find the parameters (estimators) \theta_i. The estimators are only well-defined if (\boldsymbol{X}^{T}\boldsymbol{X})^{-1} exists. This is more likely to happen when the matrix \boldsymbol{X} is high-dimensional. In this case it is likely to encounter a situation where the regression parameters \theta_i cannot be estimated.

A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change


\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I},

where \boldsymbol{I} is the identity matrix. When we discuss Ridge regression this is actually what we end up evaluating. The parameter \lambda is called a hyperparameter. More about this later.

Ridge and LASSO Regression

Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is our optimization problem is


{\displaystyle \min_{\boldsymbol{\theta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta}\right)\right\}.

or we can state it as


{\displaystyle \min_{\boldsymbol{\theta}\in
{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta}\vert\vert_2^2,

where we have used the definition of a norm-2 vector, that is


\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.

By minimizing the above equation with respect to the parameters \boldsymbol{\theta} we could then obtain an analytical expression for the parameters \boldsymbol{\theta}. We can add a regularization parameter \lambda by defining a new cost function to be optimized, that is


{\displaystyle \min_{\boldsymbol{\theta}\in
{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\theta}\vert\vert_2^2

which leads to the Ridge regression minimization problem where we require that \vert\vert \boldsymbol{\theta}\vert\vert_2^2\le t, where t is a finite number larger than zero. By defining


C(\boldsymbol{X},\boldsymbol{\theta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\theta}\vert\vert_1,

we have a new optimization equation


{\displaystyle \min_{\boldsymbol{\theta}\in
{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\theta}\vert\vert_1

which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.

Here we have defined the norm-1 as


\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert.

Deriving the Ridge Regression Equations

Using the matrix-vector expression for Ridge regression and dropping the parameter 1/n in front of the standard means squared error equation, we have


C(\boldsymbol{X},\boldsymbol{\theta})=\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\theta})\right\}+\lambda\boldsymbol{\theta}^T\boldsymbol{\theta},

and taking the derivatives with respect to \boldsymbol{\theta} we obtain then a slightly modified matrix inversion problem which for finite values of \lambda does not suffer from singularity problems. We obtain the optimal parameters


\hat{\boldsymbol{\theta}}_{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},

with \boldsymbol{I} being a p\times p identity matrix with the constraint that


\sum_{i=0}^{p-1} \theta_i^2 \leq t,

with t a finite positive number.

If we keep the 1/n factor, the equation for the optimal \theta changes to


\hat{\boldsymbol{\theta}}_{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+n\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.

In many textbooks the 1/n term is often omitted. Note that a library like Scikit-Learn does not include the 1/n factor in the setup of the cost function.

When we compare this with the ordinary least squares result we have


\hat{\boldsymbol{\theta}}_{\mathrm{OLS}} = \left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},

which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix \boldsymbol{X}^T\boldsymbol{X}.

We see that Ridge regression is nothing but the standard OLS with a modified diagonal term added to \boldsymbol{X}^T\boldsymbol{X}. The consequences, in particular for our discussion of the bias-variance tradeoff are rather interesting. We will see that for specific values of \lambda, we may even reduce the variance of the optimal parameters \boldsymbol{\theta}. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.

When we have discussed the singular value decomposition of the design matrix \boldsymbol{X}, we will in turn perform a more rigorous mathematical discussion of Ridge regression.

The code here is a simple demonstration of how to implement Ridge regression with our own code and compare this with scikit-learn.

In [1]:
%matplotlib inline

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import linear_model

def MSE(y_data,y_model):
    n = np.size(y_model)
    return np.sum((y_data-y_model)**2)/n


# A seed just to ensure that the random numbers are the same for every run.
# Useful for eventual debugging.
np.random.seed(3155)

n = 100
x = np.random.rand(n)
y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)

Maxpolydegree = 20
X = np.zeros((n,Maxpolydegree))
#We include explicitely the intercept column
for degree in range(Maxpolydegree):
    X[:,degree] = x**degree
# We split the data in test and training data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

p = Maxpolydegree
I = np.eye(p,p)
# Decide which values of lambda to use
nlambdas = 6
MSEOwnRidgePredict = np.zeros(nlambdas)
MSERidgePredict = np.zeros(nlambdas)
lambdas = np.logspace(-4, 2, nlambdas)
for i in range(nlambdas):
    lmb = lambdas[i]
    OwnRidgeTheta = np.linalg.pinv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train
    # Note: we include the intercept column and no scaling
    RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
    RegRidge.fit(X_train,y_train)
    # and then make the prediction
    ytildeOwnRidge = X_train @ OwnRidgeTheta
    ypredictOwnRidge = X_test @ OwnRidgeTheta
    ytildeRidge = RegRidge.predict(X_train)
    ypredictRidge = RegRidge.predict(X_test)
    MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)
    MSERidgePredict[i] = MSE(y_test,ypredictRidge)
    print("Theta values for own Ridge implementation")
    print(OwnRidgeTheta)
    print("Theta values for Scikit-Learn Ridge implementation")
    print(RegRidge.coef_)
    print("MSE values for own Ridge implementation")
    print(MSEOwnRidgePredict[i])
    print("MSE values for Scikit-Learn Ridge implementation")
    print(MSERidgePredict[i])

# Now plot the results
plt.figure()
plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'r', label = 'MSE own Ridge Test')
plt.plot(np.log10(lambdas), MSERidgePredict, 'g', label = 'MSE Ridge Test')

plt.xlabel('log10(lambda)')
plt.ylabel('MSE')
plt.legend()
plt.show()

The results here agree when we force Scikit-Learn's Ridge function to include the first column in our design matrix. We see that the results agree very well. Here we have thus explicitely included the intercept column in the design matrix. What happens if we do not include the intercept in our fit? We will discuss this in more detail next week.

Basic math of the SVD

From standard linear algebra we know that a square matrix \boldsymbol{X} can be diagonalized if and only if it is a so-called normal matrix, that is if \boldsymbol{X}\in {\mathbb{R}}^{n\times n} we have \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} or if \boldsymbol{X}\in {\mathbb{C}}^{n\times n} we have \boldsymbol{X}\boldsymbol{X}^{\dagger}=\boldsymbol{X}^{\dagger}\boldsymbol{X}. The matrix has then a set of eigenpairs


(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n),

and the eigenvalues are given by the diagonal matrix


\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n).

The matrix \boldsymbol{X} can be written in terms of an orthogonal/unitary transformation \boldsymbol{U}


\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,

with \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I} or \boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I}.

Not all square matrices are diagonalizable. A matrix like the one discussed above


\boldsymbol{X} = \begin{bmatrix} 
1&  -1 \\
1& -1\\
\end{bmatrix}

is not diagonalizable, it is a so-called defective matrix. It is easy to see that the condition \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} is not fulfilled.

The SVD, a Fantastic Algorithm

However, and this is the strength of the SVD algorithm, any general matrix \boldsymbol{X} can be decomposed in terms of a diagonal matrix and two orthogonal/unitary matrices. The Singular Value Decompostion (SVD) theorem states that a general m\times n matrix \boldsymbol{X} can be written in terms of a diagonal matrix \boldsymbol{\Sigma} of dimensionality m\times n and two orthognal matrices \boldsymbol{U} and \boldsymbol{V}, where the first has dimensionality m \times m and the last dimensionality n\times n. We have then


\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T

As an example, the above defective matrix can be decomposed as


\boldsymbol{X} = \frac{1}{\sqrt{2}}\begin{bmatrix}  1&  1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix}  2&  0 \\ 0& 0\\ \end{bmatrix}    \frac{1}{\sqrt{2}}\begin{bmatrix}  1&  -1 \\ 1& 1\\ \end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,

with eigenvalues \sigma_1=2 and \sigma_2=0. The SVD exits always!

The SVD decomposition (singular values) gives eigenvalues \sigma_i\geq\sigma_{i+1} for all i and for dimensions larger than i=p, the eigenvalues (singular values) are zero.

In the general case, where our design matrix \boldsymbol{X} has dimension n\times p, the matrix is thus decomposed into an n\times n orthogonal matrix \boldsymbol{U}, a p\times p orthogonal matrix \boldsymbol{V} and a diagonal matrix \boldsymbol{\Sigma} with r=\mathrm{min}(n,p) singular values \sigma_i\geq 0 on the main diagonal and zeros filling the rest of the matrix. There are at most p singular values assuming that n > p. In our regression examples for the nuclear masses and the equation of state this is indeed the case, while for the Ising model we have p > n. These are often cases that lead to near singular or singular matrices.

The columns of \boldsymbol{U} are called the left singular vectors while the columns of \boldsymbol{V} are the right singular vectors.

Economy-size SVD

If we assume that n > p, then our matrix \boldsymbol{U} has dimension $n \times n$. The last n-p columns of \boldsymbol{U} become however irrelevant in our calculations since they are multiplied with the zeros in \boldsymbol{\Sigma}.

The economy-size decomposition removes extra rows or columns of zeros from the diagonal matrix of singular values, \boldsymbol{\Sigma}, along with the columns in either \boldsymbol{U} or \boldsymbol{V} that multiply those zeros in the expression. Removing these zeros and columns can improve execution time and reduce storage requirements without compromising the accuracy of the decomposition.

If n > p, we keep only the first p columns of \boldsymbol{U} and \boldsymbol{\Sigma} has dimension p\times p. If p > n, then only the first n columns of \boldsymbol{V} are computed and \boldsymbol{\Sigma} has dimension n\times n. The n=p case is obvious, we retain the full SVD. In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.

Codes for the SVD

In [2]:
import numpy as np
# SVD inversion
def SVD(A):
    ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).
    SVD is numerically more stable than the inversion algorithms provided by
    numpy and scipy.linalg at the cost of being slower.
    '''
    U, S, VT = np.linalg.svd(A,full_matrices=True)
    print('test U')
    print( (np.transpose(U) @ U - U @np.transpose(U)))
    print('test VT')
    print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))
    print(U)
    print(S)
    print(VT)

    D = np.zeros((len(U),len(VT)))
    for i in range(0,len(VT)):
        D[i,i]=S[i]
    return U @ D @ VT


X = np.array([ [1.0,-1.0], [1.0,-1.0]])
#X = np.array([[1, 2], [3, 4], [5, 6]])

print(X)
C = SVD(X)
# Print the difference between the original matrix and the SVD one
print(C-X)

The matrix \boldsymbol{X} has columns that are linearly dependent. The first column is the row-wise sum of the other two columns. The rank of a matrix (the column rank) is the dimension of space spanned by the column vectors. The rank of the matrix is the number of linearly independent columns, in this case just 2. We see this from the singular values when running the above code. Running the standard inversion algorithm for matrix inversion with \boldsymbol{X}^T\boldsymbol{X} results in the program terminating due to a singular matrix.

Note about SVD Calculations

The U, S, and V matrices returned from the svd() function cannot be multiplied directly.

As you can see from the code, the S vector must be converted into a diagonal matrix. This may cause a problem as the size of the matrices do not fit the rules of matrix multiplication, where the number of columns in a matrix must match the number of rows in the subsequent matrix.

If you wish to include the zero singular values, you will need to resize the matrices and set up a diagonal matrix as done in the above example

Mathematics of the SVD and implications

Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies.

Our starting point is our design matrix \boldsymbol{X} of dimension n\times p


\boldsymbol{X}=\begin{bmatrix}
x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\
x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\
x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\
\dots & \dots & \dots & \dots \dots & \dots \\
x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\
x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\
\end{bmatrix}.

We can SVD decompose our matrix as


\boldsymbol{X}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,

where \boldsymbol{U} is an orthogonal matrix of dimension n\times n, meaning that \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{U}^T\boldsymbol{U}=\boldsymbol{I}_n. Here \boldsymbol{I}_n is the unit matrix of dimension n \times n.

Similarly, \boldsymbol{V} is an orthogonal matrix of dimension p\times p, meaning that \boldsymbol{V}\boldsymbol{V}^T=\boldsymbol{V}^T\boldsymbol{V}=\boldsymbol{I}_p. Here \boldsymbol{I}_n is the unit matrix of dimension p \times p.

Finally \boldsymbol{\Sigma} contains the singular values \sigma_i. This matrix has dimension n\times p and the singular values \sigma_i are all positive. The non-zero values are ordered in descending order, that is


\sigma_0 > \sigma_1 > \sigma_2 > \dots > \sigma_{p-1} > 0.

All values beyond p-1 are all zero.

Example Matrix

As an example, consider the following 3\times 2 example for the matrix \boldsymbol{\Sigma}


\boldsymbol{\Sigma}=
\begin{bmatrix}
2& 0 \\
0 & 1 \\
0 & 0 \\
\end{bmatrix}

The singular values are \sigma_0=2 and \sigma_1=1. It is common to rewrite the matrix \boldsymbol{\Sigma} as


\boldsymbol{\Sigma}=
\begin{bmatrix}
\boldsymbol{\tilde{\Sigma}}\\
\boldsymbol{0}\\
\end{bmatrix},

where


\boldsymbol{\tilde{\Sigma}}=
\begin{bmatrix}
2& 0 \\
0 & 1 \\
\end{bmatrix},

contains only the singular values. Note also (and we will use this below) that


\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}=
\begin{bmatrix}
4& 0 \\
0 & 1 \\
\end{bmatrix},

which is a 2\times 2 matrix while


\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T=
\begin{bmatrix}
4& 0 & 0\\
0 & 1 & 0\\
0 & 0 & 0\\
\end{bmatrix},

is a 3\times 3 matrix. The last row and column of this last matrix contain only zeros. This will have important consequences for our SVD decomposition of the design matrix.

Setting up the Matrix to be inverted

The matrix that may cause problems for us is \boldsymbol{X}^T\boldsymbol{X}. Using the SVD we can rewrite this matrix as


\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,
Warning:
Output truncated. This notebook contains too many cells to display efficiently.