This commit is contained in:
Morten Hjorth-Jensen
2025-08-31 21:02:56 +02:00
parent 9ddb011a07
commit cd2ce9e8e5
55 changed files with 12364 additions and 3851 deletions
+970 -3
View File
@@ -6,12 +6,12 @@ DATE: September 1-5, 2025
!split
===== Plans for week 36 =====
_Material for the lecture on Monday September 1_
_Material for the lecture on Monday September 1:_
o Linear Regression, ordinary least squares (OLS), Ridge and Lasso and mathematical analysis
o Derivation of Gradient descent and discussion of implementations for
# * "Video of lecture":"https://youtu.be/oHjqjUB36KE"
# * "Whiteboard notes":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesSeptember2.pdf"
_Material for the lab sessions on Tuesday and Wednesday (see at the end of these slides)_
_Material for the lab sessions on Tuesday and Wednesday (see at the end of these slides):_
o Technicalities concerning Ridge and Lasso linear regression.
o Presentation and discussion of the first project
# * "Video of lab session":"https://youtu.be/ZrIdZdZtHe0"
@@ -24,6 +24,971 @@ o Rashcka et al, pages 37-44 and pages 278-283 with focus on linear regression.
===== Material for lecture Monday September 2 =====
!split
===== 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
!bt
\[
\hat{\bm{\theta}} = \left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}.
\]
!et
The _hat_ over $\bm{\theta}$ means we have the optimal parameters after minimization of the cost function.
This means that our best model is defined as
!bt
\[
\tilde{\bm{y}}=\bm{X}\hat{\bm{\theta}} = \bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}.
\]
!et
We now define a matrix
!bt
\[
\bm{A}=\bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T.
\]
!et
We can rewrite
!bt
\[
\tilde{\bm{y}}=\bm{X}\hat{\bm{\theta}} = \bm{A}\bm{y}.
\]
!et
The matrix $\bm{A}$ has the important property that $\bm{A}^2=\bm{A}$. This is the definition of a projection matrix.
We can then interpret our optimal model $\tilde{\bm{y}}$ as being represented by an orthogonal projection of $\bm{y}$ onto a space defined by the column vectors of $\bm{X}$. In our case here the matrix $\bm{A}$ is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix.
!split
===== Residual Error =====
We have defined the residual error as
!bt
\[
\bm{\epsilon}=\bm{y}-\tilde{\bm{y}}=\left[\bm{I}-\bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\right]\bm{y}.
\]
!et
The residual errors are then the projections of $\bm{y}$ onto the orthogonal component of the space defined by the column vectors of $\bm{X}$.
!split
===== Simple case =====
If the matrix $\bm{X}$ is an orthogonal (or unitary in case of complex values) matrix, we have
!bt
\[
\bm{X}^T\bm{X}=\bm{X}\bm{X}^T = \bm{I}.
\]
!et
In this case the matrix $\bm{A}$ becomes
!bt
\[
\bm{A}=\bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T)=\bm{I},
\]
!et
and we have the obvious case
!bt
\[
\bm{\epsilon}=\bm{y}-\tilde{\bm{y}}=0.
\]
!et
This serves also as a useful test of our codes.
!split
===== The singular value decomposition =====
!bblock
The examples we have looked at so far are cases where we normally can
invert the matrix $\bm{X}^T\bm{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.
!eblock
!split
===== Linear Regression Problems =====
One of the typical problems we encounter with linear regression, in particular
when the matrix $\bm{X}$ (our so-called design matrix) is high-dimensional,
are problems with near singular or singular matrices. The column vectors of $\bm{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
!bt
\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*}
!et
The columns of $\bm{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 $\bm{X}^T\bm{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
!bt
\begin{align*}
\bm{X} & = \left[
\begin{array}{rr}
1 & -1
\\
1 & -1
\end{array} \right].
\end{align*}
!et
We see easily that $\mbox{det}(\bm{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 $\bm{X}$ has at least an eigenvalue which is zero.
!split
===== Fixing the singularity =====
If our design matrix $\bm{X}$ which enters the linear regression problem
!bt
\begin{align}
\bm{\theta} & = (\bm{X}^{T} \bm{X})^{-1} \bm{X}^{T} \bm{y},
\end{align}
!et
has linearly dependent column vectors, we will not be able to compute the inverse
of $\bm{X}^T\bm{X}$ and we cannot find the parameters (estimators) $\theta_i$.
The estimators are only well-defined if $(\bm{X}^{T}\bm{X})^{-1}$ exits.
This is more likely to happen when the matrix $\bm{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
!bt
\[
\bm{X}^{T} \bm{X} \rightarrow \bm{X}^{T} \bm{X}+\lambda \bm{I},
\]
!et
where $\bm{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.
!split
===== 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
!bt
\[
{\displaystyle \min_{\bm{\theta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\theta}\right)^T\left(\bm{y}-\bm{X}\bm{\theta}\right)\right\}.
\]
!et
or we can state it as
!bt
\[
{\displaystyle \min_{\bm{\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 \bm{y}-\bm{X}\bm{\theta}\vert\vert_2^2,
\]
!et
where we have used the definition of a norm-2 vector, that is
!bt
\[
\vert\vert \bm{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.
\]
!et
By minimizing the above equation with respect to the parameters
$\bm{\theta}$ we could then obtain an analytical expression for the
parameters $\bm{\theta}$. We can add a regularization parameter $\lambda$ by
defining a new cost function to be optimized, that is
!bt
\[
{\displaystyle \min_{\bm{\theta}\in
{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\theta}\vert\vert_2^2+\lambda\vert\vert \bm{\theta}\vert\vert_2^2
\]
!et
which leads to the Ridge regression minimization problem where we
require that $\vert\vert \bm{\theta}\vert\vert_2^2\le t$, where $t$ is
a finite number larger than zero. By defining
!bt
\[
C(\bm{X},\bm{\theta})=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\theta}\vert\vert_2^2+\lambda\vert\vert \bm{\theta}\vert\vert_1,
\]
!et
we have a new optimization equation
!bt
\[
{\displaystyle \min_{\bm{\theta}\in
{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\theta}\vert\vert_2^2+\lambda\vert\vert \bm{\theta}\vert\vert_1
\]
!et
which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.
Here we have defined the norm-1 as
!bt
\[
\vert\vert \bm{x}\vert\vert_1 = \sum_i \vert x_i\vert.
\]
!et
!split
===== 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
!bt
\[
C(\bm{X},\bm{\theta})=\left\{(\bm{y}-\bm{X}\bm{\theta})^T(\bm{y}-\bm{X}\bm{\theta})\right\}+\lambda\bm{\theta}^T\bm{\theta},
\]
!et
and
taking the derivatives with respect to $\bm{\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
!bt
\[
\hat{\bm{\theta}}_{\mathrm{Ridge}} = \left(\bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y},
\]
!et
with $\bm{I}$ being a $p\times p$ identity matrix with the constraint that
!bt
\[
\sum_{i=0}^{p-1} \theta_i^2 \leq t,
\]
!et
with $t$ a finite positive number.
If we keep the $1/n$ factor, the equation for the optimal $\theta$ changes to
!bt
\[
\hat{\bm{\theta}}_{\mathrm{Ridge}} = \left(\bm{X}^T\bm{X}+n\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}.
\]
!et
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
!bt
\[
\hat{\bm{\theta}}_{\mathrm{OLS}} = \left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y},
\]
!et
which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\bm{X}^T\bm{X}$.
We see that Ridge regression is nothing but the standard OLS with a
modified diagonal term added to $\bm{X}^T\bm{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 $\bm{\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 $\bm{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.
!bc pycod
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()
!ec
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.
!split
===== Basic math of the SVD =====
From standard linear algebra we know that a square matrix $\bm{X}$ can be diagonalized if and only if it is
a so-called "normal matrix":"https://en.wikipedia.org/wiki/Normal_matrix", that is if $\bm{X}\in {\mathbb{R}}^{n\times n}$
we have $\bm{X}\bm{X}^T=\bm{X}^T\bm{X}$ or if $\bm{X}\in {\mathbb{C}}^{n\times n}$ we have $\bm{X}\bm{X}^{\dagger}=\bm{X}^{\dagger}\bm{X}$.
The matrix has then a set of eigenpairs
!bt
\[
(\lambda_1,\bm{u}_1),\dots, (\lambda_n,\bm{u}_n),
!et
and the eigenvalues are given by the diagonal matrix
!bt
\[
\bm{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n).
\]
!et
The matrix $\bm{X}$ can be written in terms of an orthogonal/unitary transformation $\bm{U}$
!bt
\[
\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T,
\]
!et
with $\bm{U}\bm{U}^T=\bm{I}$ or $\bm{U}\bm{U}^{\dagger}=\bm{I}$.
Not all square matrices are diagonalizable. A matrix like the one discussed above
!bt
\[
\bm{X} = \begin{bmatrix}
1& -1 \\
1& -1\\
\end{bmatrix}
\]
!et
is not diagonalizable, it is a so-called "defective matrix":"https://en.wikipedia.org/wiki/Defective_matrix". It is easy to see that the condition
$\bm{X}\bm{X}^T=\bm{X}^T\bm{X}$ is not fulfilled.
!split
===== The SVD, a Fantastic Algorithm =====
However, and this is the strength of the SVD algorithm, any general
matrix $\bm{X}$ can be decomposed in terms of a diagonal matrix and
two orthogonal/unitary matrices. The "Singular Value Decompostion
(SVD) theorem":"https://en.wikipedia.org/wiki/Singular_value_decomposition"
states that a general $m\times n$ matrix $\bm{X}$ can be written in
terms of a diagonal matrix $\bm{\Sigma}$ of dimensionality $m\times n$
and two orthognal matrices $\bm{U}$ and $\bm{V}$, where the first has
dimensionality $m \times m$ and the last dimensionality $n\times n$.
We have then
!bt
\[
\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T
\]
!et
As an example, the above defective matrix can be decomposed as
!bt
\[
\bm{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}=\bm{U}\bm{\Sigma}\bm{V}^T,
\]
!et
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 $\bm{X}$ has dimension
$n\times p$, the matrix is thus decomposed into an $n\times n$
orthogonal matrix $\bm{U}$, a $p\times p$ orthogonal matrix $\bm{V}$
and a diagonal matrix $\bm{\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 $\bm{U}$ are called the left singular vectors while the columns of $\bm{V}$ are the right singular vectors.
!split
===== Economy-size SVD =====
If we assume that $n > p$, then our matrix $\bm{U}$ has dimension $n
\times n$. The last $n-p$ columns of $\bm{U}$ become however
irrelevant in our calculations since they are multiplied with the
zeros in $\bm{\Sigma}$.
The economy-size decomposition removes extra rows or columns of zeros
from the diagonal matrix of singular values, $\bm{\Sigma}$, along with the columns
in either $\bm{U}$ or $\bm{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 $\bm{U}$ and $\bm{\Sigma}$ has dimension $p\times p$.
If $p > n$, then only the first $n$ columns of $\bm{V}$ are computed and $\bm{\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.
!split
===== Codes for the SVD =====
!bc pycod
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)
!ec
The matrix $\bm{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 $\bm{X}^T\bm{X}$ results
in the program terminating due to a singular matrix.
!split
===== 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
!split
===== 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 $\bm{X}$ of dimension $n\times p$
!bt
\[
\bm{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}.
\]
!et
We can SVD decompose our matrix as
!bt
\[
\bm{X}=\bm{U}\bm{\Sigma}\bm{V}^T,
\]
!et
where $\bm{U}$ is an orthogonal matrix of dimension $n\times n$, meaning that $\bm{U}\bm{U}^T=\bm{U}^T\bm{U}=\bm{I}_n$. Here $\bm{I}_n$ is the unit matrix of dimension $n \times n$.
Similarly, $\bm{V}$ is an orthogonal matrix of dimension $p\times p$, meaning that $\bm{V}\bm{V}^T=\bm{V}^T\bm{V}=\bm{I}_p$. Here $\bm{I}_n$ is the unit matrix of dimension $p \times p$.
Finally $\bm{\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
!bt
\[
\sigma_0 > \sigma_1 > \sigma_2 > \dots > \sigma_{p-1} > 0.
\]
!et
All values beyond $p-1$ are all zero.
!split
===== Example Matrix =====
As an example, consider the following $3\times 2$ example for the matrix $\bm{\Sigma}$
!bt
\[
\bm{\Sigma}=
\begin{bmatrix}
2& 0 \\
0 & 1 \\
0 & 0 \\
\end{bmatrix}
\]
!et
The singular values are $\sigma_0=2$ and $\sigma_1=1$. It is common to rewrite the matrix $\bm{\Sigma}$ as
!bt
\[
\bm{\Sigma}=
\begin{bmatrix}
\bm{\tilde{\Sigma}}\\
\bm{0}\\
\end{bmatrix},
\]
!et
where
!bt
\[
\bm{\tilde{\Sigma}}=
\begin{bmatrix}
2& 0 \\
0 & 1 \\
\end{bmatrix},
\]
!et
contains only the singular values. Note also (and we will use this below) that
!bt
\[
\bm{\Sigma}^T\bm{\Sigma}=
\begin{bmatrix}
4& 0 \\
0 & 1 \\
\end{bmatrix},
\]
!et
which is a $2\times 2 $ matrix while
!bt
\[
\bm{\Sigma}\bm{\Sigma}^T=
\begin{bmatrix}
4& 0 & 0\\
0 & 1 & 0\\
0 & 0 & 0\\
\end{bmatrix},
\]
!et
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.
!split
===== Setting up the Matrix to be inverted =====
The matrix that may cause problems for us is $\bm{X}^T\bm{X}$. Using the SVD we can rewrite this matrix as
!bt
\[
\bm{X}^T\bm{X}=\bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T,
\]
!et
and using the orthogonality of the matrix $\bm{U}$ we have
!bt
\[
\bm{X}^T\bm{X}=\bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T.
\]
!et
We define $\bm{\Sigma}^T\bm{\Sigma}=\tilde{\bm{\Sigma}}^2$ which is a diagonal matrix containing only the singular values squared. It has dimensionality $p \times p$.
We can now insert the result for the matrix $\bm{X}^T\bm{X}$ into our equation for ordinary least squares where
!bt
\[
\tilde{y}_{\mathrm{OLS}}=\bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y},
\]
!et
and using our SVD decomposition of $\bm{X}$ we have
!bt
\[
\tilde{y}_{\mathrm{OLS}}=\bm{U}\bm{\Sigma}\bm{V}^T\left(\bm{V}\tilde{\bm{\Sigma}}^{2}(\bm{V}^T\right)^{-1}\bm{V}\bm{\Sigma}^T\bm{U}^T\bm{y},
\]
!et
which gives us, using the orthogonality of the matrix $\bm{V}$,
!bt
\[
\tilde{y}_{\mathrm{OLS}}=\sum_{i=0}^{p-1}\bm{u}_i\bm{u}^T_i\bm{y},
\]
!et
which is not the same as $\tilde{y}_{\mathrm{OLS}}=\bm{U}\bm{U}^T\bm{y}$, which due to the orthogonality of $\bm{U}$ would have given us that the model equals the output.
It means that the ordinary least square model (with the optimal
parameters) $\bm{\tilde{y}}$, corresponds to an orthogonal
transformation of the output (or target) vector $\bm{y}$ by the
vectors of the matrix $\bm{U}$. _Note that the summation ends at_
$p-1$, that is $\bm{\tilde{y}}\ne \bm{y}$. We can thus not use the
orthogonality relation for the matrix $\bm{U}$.
!split
===== Further properties (important for our analyses later) =====
Let us study again $\bm{X}^T\bm{X}$ in terms of our SVD,
!bt
\[
\bm{X}^T\bm{X}=\bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T=\bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T.
\]
!et
If we now multiply from the right with $\bm{V}$ (using the orthogonality of $\bm{V}$) we get
!bt
\[
\left(\bm{X}^T\bm{X}\right)\bm{V}=\bm{V}\bm{\Sigma}^T\bm{\Sigma}.
\]
!et
This means the vectors $\bm{v}_i$ of the orthogonal matrix $\bm{V}$ are the eigenvectors of the matrix $\bm{X}^T\bm{X}$
with eigenvalues given by the singular values squared, that is
!bt
\[
\left(\bm{X}^T\bm{X}\right)\bm{v}_i=\bm{v}_i\sigma_i^2.
\]
!et
Similarly, if we use the SVD decomposition for the matrix $\bm{X}\bm{X}^T$, we have
!bt
\[
\bm{X}\bm{X}^T=\bm{U}\bm{\Sigma}\bm{V}^T\bm{V}\bm{\Sigma}^T\bm{U}^T=\bm{U}\bm{\Sigma}\bm{\Sigma}^T\bm{U}^T.
\]
!et
If we now multiply from the right with $\bm{U}$ (using the orthogonality of $\bm{U}$) we get
!bt
\[
\left(\bm{X}\bm{X}^T\right)\bm{U}=\bm{U}\bm{\Sigma}\bm{\Sigma}^T.
\]
!et
This means the vectors $\bm{u}_i$ of the orthogonal matrix $\bm{U}$ are the eigenvectors of the matrix $\bm{X}\bm{X}^T$
with eigenvalues given by the singular values squared, that is
!bt
\[
\left(\bm{X}\bm{X}^T\right)\bm{u}_i=\bm{u}_i\sigma_i^2.
\]
!et
_Important note_: we have defined our design matrix $\bm{X}$ to be an
$n\times p$ matrix. In most supervised learning cases we have that $n
\ge p$, and quite often we have $n >> p$. For linear algebra based methods like ordinary least squares or Ridge regression, this leads to a matrix $\bm{X}^T\bm{X}$ which is small and thereby easier to handle from a computational point of view (in terms of number of floating point operations).
In our lectures, the number of columns will
always refer to the number of features in our data set, while the
number of rows represents the number of data inputs. Note that in
other texts you may find the opposite notation. This has consequences
for the definition of for example the covariance matrix and its relation to the SVD.
!split
===== Back to 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
!bt
\[
{\displaystyle \min_{\bm{\theta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\theta}\right)^T\left(\bm{y}-\bm{X}\bm{\theta}\right)\right\}.
\]
!et
or we can state it as
!bt
\[
{\displaystyle \min_{\bm{\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 \bm{y}-\bm{X}\bm{\theta}\vert\vert_2^2,
\]
!et
where we have used the definition of a norm-2 vector, that is
!bt
\[
\vert\vert \bm{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.
\]
!et
By minimizing the above equation with respect to the parameters
$\bm{\theta}$ we could then obtain an analytical expression for the
parameters $\bm{\theta}$. We can add a regularization parameter $\lambda$ by
defining a new cost function to be optimized, that is
!bt
\[
{\displaystyle \min_{\bm{\theta}\in
{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\theta}\vert\vert_2^2+\lambda\vert\vert \bm{\theta}\vert\vert_2^2
\]
!et
which leads to the Ridge regression minimization problem where we
require that $\vert\vert \bm{\theta}\vert\vert_2^2\le t$, where $t$ is
a finite number larger than zero. By defining
!bt
\[
C(\bm{X},\bm{\theta})=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\theta}\vert\vert_2^2+\lambda\vert\vert \bm{\theta}\vert\vert_1,
\]
!et
we have a new optimization equation
!bt
\[
{\displaystyle \min_{\bm{\theta}\in
{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\theta}\vert\vert_2^2+\lambda\vert\vert \bm{\theta}\vert\vert_1
\]
!et
which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.
Here we have defined the norm-1 as
!bt
\[
\vert\vert \bm{x}\vert\vert_1 = \sum_i \vert x_i\vert.
\]
!et
Ridge regression, as discussed above, is nothing but the standard OLS with a
modified diagonal term added to $\bm{X}^T\bm{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 $\bm{\theta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.
Using our insights about the SVD of the design matrix $\bm{X}$
We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\bm{U}$ as
!bt
\[
\tilde{\bm{y}}_{\mathrm{OLS}}=\bm{X}\bm{\theta} =\bm{U}\bm{U}^T\bm{y}.
\]
!et
For Ridge regression this becomes
!bt
\[
\tilde{\bm{y}}_{\mathrm{Ridge}}=\bm{X}\bm{\theta}_{\mathrm{Ridge}} = \bm{U\Sigma V^T}\left(\bm{V}\bm{\Sigma}^2\bm{V}^T+\lambda\bm{I} \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\sum_{j=0}^{p-1}\bm{u}_j\bm{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\bm{y},
\]
!et
with the vectors $\bm{u}_j$ being the columns of $\bm{U}$ from the SVD of the matrix $\bm{X}$.
!split
===== Interpreting the Ridge results =====
Since $\lambda \geq 0$, it means that compared to OLS, we have
!bt
\[
\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1.
\]
!et
Ridge regression finds the coordinates of $\bm{y}$ with respect to the
orthonormal basis $\bm{U}$, it then shrinks the coordinates by
$\frac{\sigma_j^2}{\sigma_j^2+\lambda}$. Recall that the SVD has
eigenvalues ordered in a descending way, that is $\sigma_i \geq
\sigma_{i+1}$.
For small eigenvalues $\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.
!split
===== More interpretations =====
For the sake of simplicity, let us assume that the design matrix is orthonormal, that is
!bt
\[
\bm{X}^T\bm{X}=(\bm{X}^T\bm{X})^{-1} =\bm{I}.
\]
!et
In this case the standard OLS results in
!bt
\[
\bm{\theta}^{\mathrm{OLS}} = \bm{X}^T\bm{y}=\sum_{i=0}^{n-1}\bm{u}_i\bm{u}_i^T\bm{y},
\]
!et
and
!bt
\[
\bm{\theta}^{\mathrm{Ridge}} = \left(\bm{I}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}=\left(1+\lambda\right)^{-1}\bm{\theta}^{\mathrm{OLS}},
\]
!et
that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\lambda$, and
the Ridge estimator converges to zero when the hyperparameter goes to
infinity.
We will come back to more interpreations after we have gone through some of the statistical analysis part.
For more discussions of Ridge and Lasso regression, "Wessel van Wieringen's":"https://arxiv.org/abs/1509.09169" article is highly recommended.
Similarly, "Mehta et al's article":"https://arxiv.org/abs/1803.08823" is also recommended.
!split
===== Deriving the Lasso Regression Equations =====
Using the matrix-vector expression for Lasso regression, we have the following _cost_ function
!bt
\[
C(\bm{X},\bm{\theta})=\frac{1}{n}\left\{(\bm{y}-\bm{X}\bm{\theta})^T(\bm{y}-\bm{X}\bm{\theta})\right\}+\lambda\vert\vert\bm{\theta}\vert\vert_1,
\]
!et
Taking the derivative with respect to $\bm{\theta}$ and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)
!bt
\[
\frac{d \vert \theta\vert}{d \theta}=\mathrm{sgn}(\theta)=\left\{\begin{array}{cc} 1 & \theta > 0 \\-1 & \theta < 0, \end{array}\right.
\]
!et
we have that the derivative of the cost function is
!bt
\[
\frac{\partial C(\bm{X},\bm{\theta})}{\partial \bm{\theta}}=-\frac{2}{n}\bm{X}^T(\bm{y}-\bm{X}\bm{\theta})+\lambda sgn(\bm{\theta})=0,
\]
!et
and reordering we have
!bt
\[
\bm{X}^T\bm{X}\bm{\theta}+\frac{n}{2}\lambda sgn(\bm{\theta})=2\bm{X}^T\bm{y}.
\]
!et
We can redefine $\lambda$ to absorb the constant $n/2$ and we rewrite the last equation as
!bt
\[
\bm{X}^T\bm{X}\bm{\theta}+\lambda sgn(\bm{\theta})=2\bm{X}^T\bm{y}.
\]
!et
This equation does not lead to a nice analytical equation as in either Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms.We will discuss how to code the above methods using gardient descent methods.
@@ -270,7 +1235,7 @@ $\frac{\sigma_j^2}{\sigma_j^2+\lambda}$. Recall that the SVD has
eigenvalues ordered in a descending way, that is $\sigma_i \geq
\sigma_{i+1}$.
For small eigenvalues $\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.
For small eigenvalues $\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom.
!split
@@ -777,3 +1742,5 @@ plt.show()
!ec