Material for lab sessions sessions Tuesday and Wednesday
+
Mathematical Interpretation of Ordinary Least Squares
-
The material here contains a summary of the lecture on Monday and discussion of SVD, Ridge and Lasso regression with examples
+
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
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.
+
where the tilde-matrix \( \tilde{\boldsymbol{\Sigma}} \) is a matrix of dimension \( p\times p \) containing only the singular values \( \sigma_i \), that is
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} \).
This means the vectors \( \boldsymbol{v}_i \) of the orthogonal matrix \( \boldsymbol{V} \)
-are the eigenvectors of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) with eigenvalues
-given by the singular values squared, that is
-
+
If the matrix \( \boldsymbol{X} \) is an orthogonal (or unitary in case of complex values) matrix, we have
In other words, each non-zero singular value of \( \boldsymbol{X} \) is a positive
-square root of an eigenvalue of \( \boldsymbol{X}^T\boldsymbol{X} \). It means also that
-the columns of \( \boldsymbol{V} \) are the eigenvectors of
-\( \boldsymbol{X}^T\boldsymbol{X} \). Since we have ordered the singular values of
-\( \boldsymbol{X} \) in a descending order, it means that the column vectors
-\( \boldsymbol{v}_i \) are hierarchically ordered by how much correlation they
-encode from the columns of \( \boldsymbol{X} \).
-
+
In this case the matrix \( \boldsymbol{A} \) becomes
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
+
+
+
+
+
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.
+
-
where we have used the definition of a norm-2 vector, that is
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.
+
By minimizing the above equation with respect to the parameters
-\( \boldsymbol{\beta} \) we could then obtain an analytical expression for the
-parameters \( \boldsymbol{\beta} \). We can add a regularization parameter \( \lambda \) by
-defining a new cost function to be optimized, that is
+
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
+
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.
which leads to the Ridge regression minimization problem where we
-require that \( \vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t \), where \( t \) is
-a finite number larger than zero. We do not include such a constraints in the discussions here.
+
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
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.
+
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
+
Fixing the singularity
+
If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem
and
-taking the derivatives with respect to \( \boldsymbol{\beta} \) 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
+
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} \) exits.
+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
with \( \boldsymbol{I} \) being a \( p\times p \) identity matrix with the constraint that
-
-$$
-\sum_{i=0}^{p-1} \beta_i^2 \leq t,
-$$
-
-
with \( t \) a finite positive number.
+
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.
Note well that a library like Scikit-Learn does not include the \( 1/n \) factor in the expression for the mean-squared error. If you include it, the optimal parameter \( \beta \) becomes
+
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
+
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
+
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
+
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
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
+
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
which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \).
@@ -182,7 +295,106 @@ $$
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{\beta} \). These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.
+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.
+
+
+
+
+
+
+
+
+
importnumpyasnp
+importpandasaspd
+importmatplotlib.pyplotasplt
+fromsklearn.model_selectionimport train_test_split
+fromsklearnimport linear_model
+
+defMSE(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 inrange(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 inrange(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.
@@ -210,7 +422,7 @@ even reduce the variance of the optimal parameters \( \boldsymbol{\beta} \). The
Using our insights about the SVD of the design matrix \( \boldsymbol{X} \)
-We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as
+
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
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.
+
Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the
-orthonormal basis \( \boldsymbol{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} \).
+
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
-
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.
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.
@@ -212,7 +323,7 @@ eigenvalues ordered in a descending way, that is \( \sigma_i \geq
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.
+
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} \).
-
We will come back to more interpreations after we have gone through some of the statistical analysis part.
+
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.
importnumpyasnp
+# SVD inversion
+defSVD(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)
-
Taking the derivative with respect to \( \boldsymbol{\beta} \) and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicity)
-$$
-\frac{d \vert \beta\vert}{d \beta}=\mathrm{sgn}(\beta)=\left\{\begin{array}{cc} 1 & \beta > 0 \\-1 & \beta < 0, \end{array}\right.
-$$
+ D = np.zeros((len(U),len(VT)))
+ for i inrange(0,len(VT)):
+ D[i,i]=S[i]
+ return U @ D @ VT
-
we have that the derivative of the cost function is
-$$
-\boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}+\lambda sgn(\boldsymbol{\beta})=\boldsymbol{X}^T\boldsymbol{y}.
-$$
+print(X)
+C = SVD(X)
+# Print the difference between the original matrix and the SVD one
+print(C-X)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
This equation does not lead to a nice analytical equation as in Ridge regression or ordinary least squares. We have absorbed the factor \( 2/n \) in a redefinition of the parameter \( \lambda \). We will solve this type of problems using libraries like scikit-learn and using our own gradient descent code in project 1.
+
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.
+
Simple example to illustrate Ordinary Least Squares, Ridge and Lasso Regression
+
Note about SVD Calculations
-
Let us assume that our design matrix is given by unit (identity) matrix, that is a square diagonal matrix with ones only along the
-diagonal. In this case we have an equal number of rows and columns \( n=p \).
+
The \( U \), \( S \), and \( V \) matrices returned from the svd() function
+cannot be multiplied directly.
-
Our model approximation is just \( \tilde{\boldsymbol{y}}=\boldsymbol{\beta} \) and the mean squared error and thereby the cost function for ordinary least sqquares (OLS) is then (we drop the term \( 1/n \))
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
+
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
Plotting these results shows clearly that Lasso regression suppresses (sets to zero) values of \( \beta_i \) for specific values of \( \lambda \). Ridge regression reduces on the other hand the values of \( \beta_i \) as function of \( \lambda \).
+
contains only the singular values. Note also (and we will use this below) that
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.
+
meaning that we have two features and two unknown parameters \( \beta_0 \) and \( \beta_1 \) to be determined either by ordinary least squares, Ridge or Lasso regression.
+
We define \( \boldsymbol{\Sigma}^T\boldsymbol{\Sigma}=\tilde{\boldsymbol{\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 \( \boldsymbol{X}^T\boldsymbol{X} \) into our equation for ordinary least squares where
which is not the same as \( \tilde{y}_{\mathrm{OLS}}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y} \), which due to the orthogonality of \( \boldsymbol{U} \) would have given us that the model equals the output.
+
+
It means that the ordinary least square model (with the optimal
+parameters) \( \boldsymbol{\tilde{y}} \), corresponds to an orthogonal
+transformation of the output (or target) vector \( \boldsymbol{y} \) by the
+vectors of the matrix \( \boldsymbol{U} \). Note that the summation ends at
+\( p-1 \), that is \( \boldsymbol{\tilde{y}}\ne \boldsymbol{y} \). We can thus not use the
+orthogonality relation for the matrix \( \boldsymbol{U} \).
+
The code which implements this simpler case is presented after the discussion of Ridge and Lasso.
+
This means the vectors \( \boldsymbol{v}_i \) of the orthogonal matrix \( \boldsymbol{V} \) are the eigenvectors of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \)
+with eigenvalues given by the singular values squared, that is
+
This means the vectors \( \boldsymbol{u}_i \) of the orthogonal matrix \( \boldsymbol{U} \) are the eigenvectors of the matrix \( \boldsymbol{X}\boldsymbol{X}^T \)
+with eigenvalues given by the singular values squared, that is
+
Important note: we have defined our design matrix \( \boldsymbol{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 \( \boldsymbol{X}^T\boldsymbol{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.
+
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
+
There is normally a constraint on the value of \( \vert\vert \boldsymbol{\beta}\vert\vert_2 \) via the parameter \( \lambda \).
-Let us for simplicity assume that \( \beta_0^2+\beta_1^2=1 \) as constraint. This will allow us to find an expression for the optimal values of \( \beta \) and \( \lambda \).
+
where we have used the definition of a norm-2 vector, that is
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
-
To see this, let us write the cost function for Ridge regression.
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
+
Ridge regression, as discussed above, 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.
+
+
+
Using our insights about the SVD of the design matrix \( \boldsymbol{X} \)
+We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as
+
and taking the derivative with respect to \( \beta_0 \) we get
-$$
-\beta_0=\frac{8}{4+\lambda},
-$$
+
Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the
+orthonormal basis \( \boldsymbol{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} \).
+
-
and for \( \beta_1 \) we obtain
-$$
-\beta_1=\frac{2}{1+\lambda},
-$$
-
-
Using the constraint for \( \beta_0^2+\beta_1^2=1 \) we can constrain \( \lambda \) by solving
which gives \( \lambda=4.571 \) and \( \beta_0=0.933 \) and \( \beta_1=0.359 \).
+
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 Lasso we need now, keeping a constraint on \( \vert\beta_0\vert+\vert\beta_1\vert=1 \), to take the derivative of the absolute values of \( \beta_0 \)
-and \( \beta_1 \). This gives us the following derivatives of the cost function
-
We have now four cases to solve besides the trivial cases \( \beta_0 \) and/or \( \beta_1 \) are zero, namely
-
-
\( \beta_0 > 0 \) and \( \beta_1 > 0 \),
-
\( \beta_0 > 0 \) and \( \beta_1 < 0 \),
-
\( \beta_0 < 0 \) and \( \beta_1 > 0 \),
-
\( \beta_0 < 0 \) and \( \beta_1 < 0 \).
-
+
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.
Taking the derivative with respect to \( \boldsymbol{\theta} \) and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)
Using the constraint on \( \beta_0 \) and \( \beta_1 \) we can then find the optimal value of \( \lambda \) for the different cases. We leave this as an exercise to you.
+
we have that the derivative of the cost function is
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.
Material for lab sessions sessions Tuesday and Wednesday
-
Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of \( \lambda \), meaning that we need to perform a search in order to find the optimal values.
-
-
First we study and compare the OLS and Ridge results. The next code compares all three methods.
-
-
-
-
-
-
-
-
-
importos
-importnumpyasnp
-importpandasaspd
-importmatplotlib.pyplotasplt
-
-defR2(y_data, y_model):
- return1- np.sum((y_data - y_model) **2) / np.sum((y_data - np.mean(y_data)) **2)
-defMSE(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.
-
-X = np.array( [ [ 2, 0], [0, 1], [0,0]])
-y = np.array( [4, 2, 3])
-
-
-# matrix inversion to find beta
-OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y
-print(OLSbeta)
-# and then make the prediction
-ytildeOLS = X @ OLSbeta
-print("Training MSE for OLS")
-print(MSE(y,ytildeOLS))
-ypredictOLS = X @ OLSbeta
-
-# Repeat now for Ridge regression and various values of the regularization parameter
-I = np.eye(2,2)
-# Decide which values of lambda to use
-nlambdas =100
-MSEPredict = np.zeros(nlambdas)
-lambdas = np.logspace(-4, 4, nlambdas)
-for i inrange(nlambdas):
- lmb = lambdas[i]
- Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y
-# print(Ridgebeta)
- # and then make the prediction
- ypredictRidge = X @ Ridgebeta
- MSEPredict[i] = MSE(y,ypredictRidge)
-# print(MSEPredict[i])
- # Now plot the results
-plt.figure()
-plt.plot(np.log10(lambdas), MSEPredict, 'r--', label ='MSE Ridge Train')
-plt.xlabel('log10(lambda)')
-plt.ylabel('MSE')
-plt.legend()
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
We see here that we reach a plateau. What is actually happening?
+
The material here contains a summary of the lecture on Monday and discussion of SVD, Ridge and Lasso regression with examples
where the tilde-matrix \( \tilde{\boldsymbol{\Sigma}} \) is a matrix of dimension \( p\times p \) containing only the singular values \( \sigma_i \), that is
+$$
+\tilde{\boldsymbol{\Sigma}}=\begin{bmatrix} \sigma_0 & 0 & 0 & \dots & 0 & 0 \\
+ 0 & \sigma_1 & 0 & \dots & 0 & 0 \\
+ 0 & 0 & \sigma_2 & \dots & 0 & 0 \\
+ 0 & 0 & 0 & \dots & \sigma_{p-2} & 0 \\
+ 0 & 0 & 0 & \dots & 0 & \sigma_{p-1} \\
+\end{bmatrix},
+$$
-# A seed just to ensure that the random numbers are the same for every run.
-# Useful for eventual debugging.
+
meaning we can write
+$$
+\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2\boldsymbol{V}^T.
+$$
-X = np.array( [ [ 2, 0], [0, 1], [0,0]])
-y = np.array( [4, 2, 3])
-
-
-# matrix inversion to find beta
-OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y
-print(OLSbeta)
-# and then make the prediction
-ytildeOLS = X @ OLSbeta
-print("Training MSE for OLS")
-print(MSE(y,ytildeOLS))
-ypredictOLS = X @ OLSbeta
-
-# Repeat now for Ridge regression and various values of the regularization parameter
-I = np.eye(2,2)
-# Decide which values of lambda to use
-nlambdas =100
-MSERidgePredict = np.zeros(nlambdas)
-MSELassoPredict = np.zeros(nlambdas)
-lambdas = np.logspace(-4, 4, nlambdas)
-for i inrange(nlambdas):
- lmb = lambdas[i]
- Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y
- print(Ridgebeta)
- # and then make the prediction
- ypredictRidge = X @ Ridgebeta
- MSERidgePredict[i] = MSE(y,ypredictRidge)
- RegLasso = linear_model.Lasso(lmb,fit_intercept=False)
- RegLasso.fit(X,y)
- ypredictLasso = RegLasso.predict(X)
- print(RegLasso.coef_)
- MSELassoPredict[i] = MSE(y,ypredictLasso)
-# Now plot the results
-plt.figure()
-plt.plot(np.log10(lambdas), MSERidgePredict, 'r--', label ='MSE Ridge Train')
-plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label ='MSE Lasso Train')
-plt.xlabel('log10(lambda)')
-plt.ylabel('MSE')
-plt.legend()
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
Multiplying from the right with \( \boldsymbol{V} \) (using the orthogonality of \( \boldsymbol{V} \)) we get
This means the vectors \( \boldsymbol{v}_i \) of the orthogonal matrix \( \boldsymbol{V} \)
+are the eigenvectors of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) with eigenvalues
+given by the singular values squared, that is
+
-
-
-
-
-
-
-
importos
-importnumpyasnp
-importpandasaspd
-importmatplotlib.pyplotasplt
-fromsklearn.model_selectionimport train_test_split
-fromsklearnimport linear_model
+$$
+\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{v}_i=\boldsymbol{v}_i\sigma_i^2.
+$$
-defR2(y_data, y_model):
- return1- np.sum((y_data - y_model) **2) / np.sum((y_data - np.mean(y_data)) **2)
-defMSE(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)
-
-x = np.random.rand(100)
-y =2.0+5*x*x+0.1*np.random.randn(100)
-
-# number of features p (here degree of polynomial
-p =3
-# The design matrix now as function of a given polynomial
-X = np.zeros((len(x),p))
-X[:,0] =1.0
-X[:,1] = x
-X[:,2] = x*x
-# 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)
-
-# matrix inversion to find beta
-OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train
-print(OLSbeta)
-# and then make the prediction
-ytildeOLS = X_train @ OLSbeta
-print("Training MSE for OLS")
-print(MSE(y_train,ytildeOLS))
-ypredictOLS = X_test @ OLSbeta
-print("Test MSE OLS")
-print(MSE(y_test,ypredictOLS))
-
-# Repeat now for Lasso and Ridge regression and various values of the regularization parameter
-I = np.eye(p,p)
-# Decide which values of lambda to use
-nlambdas =100
-MSEPredict = np.zeros(nlambdas)
-MSETrain = np.zeros(nlambdas)
-MSELassoPredict = np.zeros(nlambdas)
-MSELassoTrain = np.zeros(nlambdas)
-lambdas = np.logspace(-4, 4, nlambdas)
-for i inrange(nlambdas):
- lmb = lambdas[i]
- Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train
- # include lasso using Scikit-Learn
- RegLasso = linear_model.Lasso(lmb,fit_intercept=False)
- RegLasso.fit(X_train,y_train)
- # and then make the prediction
- ytildeRidge = X_train @ Ridgebeta
- ypredictRidge = X_test @ Ridgebeta
- ytildeLasso = RegLasso.predict(X_train)
- ypredictLasso = RegLasso.predict(X_test)
- MSEPredict[i] = MSE(y_test,ypredictRidge)
- MSETrain[i] = MSE(y_train,ytildeRidge)
- MSELassoPredict[i] = MSE(y_test,ypredictLasso)
- MSELassoTrain[i] = MSE(y_train,ytildeLasso)
-
-# Now plot the results
-plt.figure()
-plt.plot(np.log10(lambdas), MSETrain, label ='MSE Ridge train')
-plt.plot(np.log10(lambdas), MSEPredict, 'r--', label ='MSE Ridge Test')
-plt.plot(np.log10(lambdas), MSELassoTrain, label ='MSE Lasso train')
-plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label ='MSE Lasso Test')
-
-plt.xlabel('log10(lambda)')
-plt.ylabel('MSE')
-plt.legend()
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
In other words, each non-zero singular value of \( \boldsymbol{X} \) is a positive
+square root of an eigenvalue of \( \boldsymbol{X}^T\boldsymbol{X} \). It means also that
+the columns of \( \boldsymbol{V} \) are the eigenvectors of
+\( \boldsymbol{X}^T\boldsymbol{X} \). Since we have ordered the singular values of
+\( \boldsymbol{X} \) in a descending order, it means that the column vectors
+\( \boldsymbol{v}_i \) are hierarchically ordered by how much correlation they
+encode from the columns of \( \boldsymbol{X} \).
+
+
Note that these are also the eigenvectors and eigenvalues of the
+Hessian matrix.
+
Although our matrix to invert \( \boldsymbol{X}^T\boldsymbol{X} \) is a square matrix, our matrix may be singular.
-
-
The pseudoinverse is the generalization of the matrix inverse for square matrices to
-rectangular matrices where the number of rows and columns are not equal.
+
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
-
-
It is also called the the Moore-Penrose Inverse after two independent discoverers of the method or the Generalized Inverse.
-It is used for the calculation of the inverse for singular or near singular matrices and for rectangular matrices.
-
-
-
Using the SVD we can obtain the pseudoinverse of a matrix \( \boldsymbol{A} \) (labeled here as \( \boldsymbol{A}_{\mathrm{PI}} \))
where \( \boldsymbol{D}_{\mathrm{PI}} \) can be calculated by creating a diagonal matrix from \( \boldsymbol{\Sigma} \) where we only keep the singular values (the non-zero values). The following code computes the pseudoinvers of the matrix based on the SVD.
importnumpyasnp
-# SVD inversion
-defSVDinv(A):
- U, s, VT = np.linalg.svd(A)
- # reciprocals of singular values of s
- d =1.0/ s
- # create m x n D matrix
- D = np.zeros(A.shape)
- # populate D with n x n diagonal matrix
- D[:A.shape[1], :A.shape[1]] = np.diag(d)
- UT = np.transpose(U)
- V = np.transpose(VT)
- return np.matmul(V,np.matmul(D.T,UT))
-
-
-A = np.array([ [0.3, 0.4], [0.5, 0.6], [0.7, 0.8],[0.9, 1.0]])
-print(A)
-# Brute force inversion of super-collinear matrix
-B = np.linalg.pinv(A)
-print(B)
-# Compare our own algorithm with pinv
-C = SVDinv(A)
-print(np.abs(C-B))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
As you can see from this example, our own decomposition based on the SVD agrees with the pseudoinverse algorithm provided by Numpy.
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
+
By minimizing the above equation with respect to the parameters
+\( \boldsymbol{\beta} \) we could then obtain an analytical expression for the
+parameters \( \boldsymbol{\beta} \). We can add a regularization parameter \( \lambda \) by
+defining a new cost function to be optimized, that is
where we have used the definition of a norm-2 vector, that is
+
which leads to the Ridge regression minimization problem where we
+require that \( \vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t \), where \( t \) is
+a finite number larger than zero. We do not include such a constraints in the discussions here.
+
By minimizing the above equation with respect to the parameters
-\( \boldsymbol{\beta} \) we could then obtain an analytical expression for the
-parameters \( \boldsymbol{\beta} \). We can add a regularization parameter \( \lambda \) by
-defining a new cost function to be optimized, that is
+
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
and
+taking the derivatives with respect to \( \boldsymbol{\beta} \) 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
which leads to the Ridge regression minimization problem where we
-require that \( \vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t \), where \( t \) is
-a finite number larger than zero. We do not include such a constraints in the discussions here.
-
-
-
By defining
+
with \( \boldsymbol{I} \) being a \( p\times p \) identity matrix with the constraint that
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
+
Note well that a library like Scikit-Learn does not include the \( 1/n \) factor in the expression for the mean-squared error. If you include it, the optimal parameter \( \beta \) becomes
and
-taking the derivatives with respect to \( \boldsymbol{\beta} \) 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
-
Note well that a library like Scikit-Learn does not include the \( 1/n \) factor in the expression for the mean-squared error. If you include it, the optimal parameter \( \beta \) becomes
-
+
Comparison with OLS
+
When we compare this with the ordinary least squares result we have
In our codes where we compare our own codes with Scikit-Learn, we do thus not include the \( 1/n \) factor in the cost function.
+
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{\beta} \). These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.
+
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{\beta} \). 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 \( \boldsymbol{X} \)
+We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as
Using our insights about the SVD of the design matrix \( \boldsymbol{X} \)
-We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as
+
Since \( \lambda \geq 0 \), it means that compared to OLS, we have
Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the
+orthonormal basis \( \boldsymbol{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} \).
with the vectors \( \boldsymbol{u}_j \) being the columns of \( \boldsymbol{U} \) from the SVD of the matrix \( \boldsymbol{X} \).
+
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.
Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the
-orthonormal basis \( \boldsymbol{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} \).
+
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.
-
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.
+
We will come back to more interpreations after we have gone through some of the statistical analysis part.
Taking the derivative with respect to \( \boldsymbol{\beta} \) and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicity)
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.
-
This equation does not lead to a nice analytical equation as in Ridge regression or ordinary least squares. We have absorbed the factor \( 2/n \) in a redefinition of the parameter \( \lambda \). We will solve this type of problems using libraries like scikit-learn and using our own gradient descent code in project 1.
Simple example to illustrate Ordinary Least Squares, Ridge and Lasso Regression
-
Using the matrix-vector expression for Lasso regression, we have the following cost function
+
Let us assume that our design matrix is given by unit (identity) matrix, that is a square diagonal matrix with ones only along the
+diagonal. In this case we have an equal number of rows and columns \( n=p \).
+
+
Our model approximation is just \( \tilde{\boldsymbol{y}}=\boldsymbol{\beta} \) and the mean squared error and thereby the cost function for ordinary least sqquares (OLS) is then (we drop the term \( 1/n \))
Taking the derivative with respect to \( \boldsymbol{\beta} \) and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicity)
This equation does not lead to a nice analytical equation as in Ridge regression or ordinary least squares. We have absorbed the factor \( 2/n \) in a redefinition of the parameter \( \lambda \). We will solve this type of problems using libraries like scikit-learn.
Simple example to illustrate Ordinary Least Squares, Ridge and Lasso Regression
+
Ridge Regression
-
Let us assume that our design matrix is given by unit (identity) matrix, that is a square diagonal matrix with ones only along the
-diagonal. In this case we have an equal number of rows and columns \( n=p \).
-
-
-
Our model approximation is just \( \tilde{\boldsymbol{y}}=\boldsymbol{\beta} \) and the mean squared error and thereby the cost function for ordinary least sqquares (OLS) is then (we drop the term \( 1/n \))
Plotting these results shows clearly that Lasso regression suppresses (sets to zero) values of \( \beta_i \) for specific values of \( \lambda \). Ridge regression reduces on the other hand the values of \( \beta_i \) as function of \( \lambda \).
Plotting these results shows clearly that Lasso regression suppresses (sets to zero) values of \( \beta_i \) for specific values of \( \lambda \). Ridge regression reduces on the other hand the values of \( \beta_i \) as function of \( \lambda \).
+
meaning that we have two features and two unknown parameters \( \beta_0 \) and \( \beta_1 \) to be determined either by ordinary least squares, Ridge or Lasso regression.
meaning that we have two features and two unknown parameters \( \beta_0 \) and \( \beta_1 \) to be determined either by ordinary least squares, Ridge or Lasso regression.
+
The code which implements this simpler case is presented after the discussion of Ridge and Lasso.
The code which implements this simpler case is presented after the discussion of Ridge and Lasso.
+
There is normally a constraint on the value of \( \vert\vert \boldsymbol{\beta}\vert\vert_2 \) via the parameter \( \lambda \).
+Let us for simplicity assume that \( \beta_0^2+\beta_1^2=1 \) as constraint. This will allow us to find an expression for the optimal values of \( \beta \) and \( \lambda \).
+
+
+
To see this, let us write the cost function for Ridge regression.
There is normally a constraint on the value of \( \vert\vert \boldsymbol{\beta}\vert\vert_2 \) via the parameter \( \lambda \).
-Let us for simplicity assume that \( \beta_0^2+\beta_1^2=1 \) as constraint. This will allow us to find an expression for the optimal values of \( \beta \) and \( \lambda \).
-
+
and taking the derivative with respect to \( \beta_0 \) we get
+$$
+\beta_0=\frac{8}{4+\lambda},
+$$
-
To see this, let us write the cost function for Ridge regression.
+
and for \( \beta_1 \) we obtain
+$$
+\beta_1=\frac{2}{1+\lambda},
+$$
+
+
Using the constraint for \( \beta_0^2+\beta_1^2=1 \) we can constrain \( \lambda \) by solving
We define the MSE without the \( 1/n \) factor and have then, using that
+
For Lasso we need now, keeping a constraint on \( \vert\beta_0\vert+\vert\beta_1\vert=1 \), to take the derivative of the absolute values of \( \beta_0 \)
+and \( \beta_1 \). This gives us the following derivatives of the cost function
+
For Lasso we need now, keeping a constraint on \( \vert\beta_0\vert+\vert\beta_1\vert=1 \), to take the derivative of the absolute values of \( \beta_0 \)
-and \( \beta_1 \). This gives us the following derivatives of the cost function
-
We have now four cases to solve besides the trivial cases \( \beta_0 \) and/or \( \beta_1 \) are zero, namely
-
-
\( \beta_0 > 0 \) and \( \beta_1 > 0 \),
-
\( \beta_0 > 0 \) and \( \beta_1 < 0 \),
-
\( \beta_0 < 0 \) and \( \beta_1 > 0 \),
-
\( \beta_0 < 0 \) and \( \beta_1 < 0 \).
-
+
which yields
+
+$$
+\beta_0=\frac{16+\lambda}{8},
+$$
+
+
and
+$$
+\beta_1=\frac{4+\lambda}{2}.
+$$
+
+
Using the constraint on \( \beta_0 \) and \( \beta_1 \) we can then find the optimal value of \( \lambda \) for the different cases. We leave this as an exercise to you.
Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of \( \lambda \), meaning that we need to perform a search in order to find the optimal values.
-
and
-$$
--2(2-\beta_1)+\lambda=0.
-$$
+
First we study and compare the OLS and Ridge results. The next code compares all three methods.
Using the constraint on \( \beta_0 \) and \( \beta_1 \) we can then find the optimal value of \( \lambda \) for the different cases. We leave this as an exercise to you.
+
+# A seed just to ensure that the random numbers are the same for every run.
+# Useful for eventual debugging.
+
+X = np.array( [ [ 2, 0], [0, 1], [0,0]])
+y = np.array( [4, 2, 3])
+
+
+# matrix inversion to find beta
+OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y
+print(OLSbeta)
+# and then make the prediction
+ytildeOLS = X @ OLSbeta
+print("Training MSE for OLS")
+print(MSE(y,ytildeOLS))
+ypredictOLS = X @ OLSbeta
+
+# Repeat now for Ridge regression and various values of the regularization parameter
+I = np.eye(2,2)
+# Decide which values of lambda to use
+nlambdas =100
+MSEPredict = np.zeros(nlambdas)
+lambdas = np.logspace(-4, 4, nlambdas)
+for i inrange(nlambdas):
+ lmb = lambdas[i]
+ Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y
+# print(Ridgebeta)
+ # and then make the prediction
+ ypredictRidge = X @ Ridgebeta
+ MSEPredict[i] = MSE(y,ypredictRidge)
+# print(MSEPredict[i])
+ # Now plot the results
+plt.figure()
+plt.plot(np.log10(lambdas), MSEPredict, 'r--', label ='MSE Ridge Train')
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
We see here that we reach a plateau. What is actually happening?
Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of \( \lambda \), meaning that we need to perform a search in order to find the optimal values.
-
-
First we study and compare the OLS and Ridge results. The next code compares all three methods.
+
With Lasso Regression
@@ -280,6 +264,7 @@ MathJax.Hub.Config({
importnumpyasnpimportpandasaspdimportmatplotlib.pyplotasplt
+fromsklearnimport linear_model
defR2(y_data, y_model):
return1- np.sum((y_data - y_model) **2) / np.sum((y_data - np.mean(y_data)) **2)
@@ -308,19 +293,25 @@ ypredictOLS = X = np.eye(2,2)
# Decide which values of lambda to use
nlambdas =100
-MSEPredict = np.zeros(nlambdas)
+MSERidgePredict = np.zeros(nlambdas)
+MSELassoPredict = np.zeros(nlambdas)
lambdas = np.logspace(-4, 4, nlambdas)
for i inrange(nlambdas):
lmb = lambdas[i]
Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y
-# print(Ridgebeta)
+ print(Ridgebeta)
# and then make the prediction
ypredictRidge = X @ Ridgebeta
- MSEPredict[i] = MSE(y,ypredictRidge)
-# print(MSEPredict[i])
- # Now plot the results
+ MSERidgePredict[i] = MSE(y,ypredictRidge)
+ RegLasso = linear_model.Lasso(lmb,fit_intercept=False)
+ RegLasso.fit(X,y)
+ ypredictLasso = RegLasso.predict(X)
+ print(RegLasso.coef_)
+ MSELassoPredict[i] = MSE(y,ypredictLasso)
+# Now plot the results
plt.figure()
-plt.plot(np.log10(lambdas), MSEPredict, 'r--', label ='MSE Ridge Train')
+plt.plot(np.log10(lambdas), MSERidgePredict, 'r--', label ='MSE Ridge Train')
+plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label ='MSE Lasso Train')
plt.xlabel('log10(lambda)')
plt.ylabel('MSE')
plt.legend()
@@ -340,7 +331,6 @@ plt.show()
-
We see here that we reach a plateau. What is actually happening?
Rashcka et al, pages 37-44 and pages 278-283 with focus on linear regression.
+
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
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.
+
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
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
+
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
+
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
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} \) exits.
+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
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
+
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
+
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
+
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
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
+
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
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.
+
+
+
+
+
+
+
+
+
importnumpyasnp
+importpandasaspd
+importmatplotlib.pyplotasplt
+fromsklearn.model_selectionimport train_test_split
+fromsklearnimport linear_model
+
+defMSE(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 inrange(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 inrange(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
+
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
+
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
+
+
+
+
+
+
+
+
+
importnumpyasnp
+# SVD inversion
+defSVD(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 inrange(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 \)
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
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
We define \( \boldsymbol{\Sigma}^T\boldsymbol{\Sigma}=\tilde{\boldsymbol{\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 \( \boldsymbol{X}^T\boldsymbol{X} \) into our equation for ordinary least squares where
which is not the same as \( \tilde{y}_{\mathrm{OLS}}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y} \), which due to the orthogonality of \( \boldsymbol{U} \) would have given us that the model equals the output.
+
+
It means that the ordinary least square model (with the optimal
+parameters) \( \boldsymbol{\tilde{y}} \), corresponds to an orthogonal
+transformation of the output (or target) vector \( \boldsymbol{y} \) by the
+vectors of the matrix \( \boldsymbol{U} \). Note that the summation ends at
+\( p-1 \), that is \( \boldsymbol{\tilde{y}}\ne \boldsymbol{y} \). We can thus not use the
+orthogonality relation for the matrix \( \boldsymbol{U} \).
+
+
+
+
+
Further properties (important for our analyses later)
+
+
Let us study again \( \boldsymbol{X}^T\boldsymbol{X} \) in terms of our SVD,
This means the vectors \( \boldsymbol{v}_i \) of the orthogonal matrix \( \boldsymbol{V} \) are the eigenvectors of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \)
+with eigenvalues given by the singular values squared, that is
+
This means the vectors \( \boldsymbol{u}_i \) of the orthogonal matrix \( \boldsymbol{U} \) are the eigenvectors of the matrix \( \boldsymbol{X}\boldsymbol{X}^T \)
+with eigenvalues given by the singular values squared, that is
+
Important note: we have defined our design matrix \( \boldsymbol{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 \( \boldsymbol{X}^T\boldsymbol{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.
+
+
+
+
+
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
+
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
+
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
+
Ridge regression, as discussed above, 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.
+
+
+
Using our insights about the SVD of the design matrix \( \boldsymbol{X} \)
+We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as
+
Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the
+orthonormal basis \( \boldsymbol{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.
+
+
+
+
More interpretations
+
+
For the sake of simplicity, let us assume that the design matrix is orthonormal, that is
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.
Taking the derivative with respect to \( \boldsymbol{\theta} \) and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)
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.
+
+
Material for lab sessions sessions Tuesday and Wednesday
@@ -487,7 +1554,7 @@ 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.
Rashcka et al, pages 37-44 and pages 278-283 with focus on linear regression.
+
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
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.
+
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
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
+
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
+
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
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} \) exits.
+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
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
+
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
+
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
+
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
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
+
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
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.
+
+
+
+
+
+
+
+
+
importnumpyasnp
+importpandasaspd
+importmatplotlib.pyplotasplt
+fromsklearn.model_selectionimport train_test_split
+fromsklearnimport linear_model
+
+defMSE(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 inrange(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 inrange(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
+
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
+
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
+
+
+
+
+
+
+
+
+
importnumpyasnp
+# SVD inversion
+defSVD(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 inrange(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 \)
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
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
We define \( \boldsymbol{\Sigma}^T\boldsymbol{\Sigma}=\tilde{\boldsymbol{\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 \( \boldsymbol{X}^T\boldsymbol{X} \) into our equation for ordinary least squares where
which is not the same as \( \tilde{y}_{\mathrm{OLS}}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y} \), which due to the orthogonality of \( \boldsymbol{U} \) would have given us that the model equals the output.
+
+
It means that the ordinary least square model (with the optimal
+parameters) \( \boldsymbol{\tilde{y}} \), corresponds to an orthogonal
+transformation of the output (or target) vector \( \boldsymbol{y} \) by the
+vectors of the matrix \( \boldsymbol{U} \). Note that the summation ends at
+\( p-1 \), that is \( \boldsymbol{\tilde{y}}\ne \boldsymbol{y} \). We can thus not use the
+orthogonality relation for the matrix \( \boldsymbol{U} \).
+
+
+
+
Further properties (important for our analyses later)
+
+
Let us study again \( \boldsymbol{X}^T\boldsymbol{X} \) in terms of our SVD,
This means the vectors \( \boldsymbol{v}_i \) of the orthogonal matrix \( \boldsymbol{V} \) are the eigenvectors of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \)
+with eigenvalues given by the singular values squared, that is
+
This means the vectors \( \boldsymbol{u}_i \) of the orthogonal matrix \( \boldsymbol{U} \) are the eigenvectors of the matrix \( \boldsymbol{X}\boldsymbol{X}^T \)
+with eigenvalues given by the singular values squared, that is
+
Important note: we have defined our design matrix \( \boldsymbol{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 \( \boldsymbol{X}^T\boldsymbol{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.
+
+
+
+
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
+
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
+
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
+
Ridge regression, as discussed above, 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.
+
+
+
Using our insights about the SVD of the design matrix \( \boldsymbol{X} \)
+We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as
+
Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the
+orthonormal basis \( \boldsymbol{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.
+
+
+
More interpretations
+
+
For the sake of simplicity, let us assume that the design matrix is orthonormal, that is
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.
Taking the derivative with respect to \( \boldsymbol{\theta} \) and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)
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.
+
Material for lab sessions sessions Tuesday and Wednesday
@@ -378,7 +1381,7 @@ 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.
Rashcka et al, pages 37-44 and pages 278-283 with focus on linear regression.
+
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
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.
+
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
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
+
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
+
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
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} \) exits.
+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
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
+
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
+
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
+
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
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
+
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
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.
+
+
+
+
+
+
+
+
+
importnumpyasnp
+importpandasaspd
+importmatplotlib.pyplotasplt
+fromsklearn.model_selectionimport train_test_split
+fromsklearnimport linear_model
+
+defMSE(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 inrange(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 inrange(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
+
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
+
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
+
+
+
+
+
+
+
+
+
importnumpyasnp
+# SVD inversion
+defSVD(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 inrange(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 \)
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
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
We define \( \boldsymbol{\Sigma}^T\boldsymbol{\Sigma}=\tilde{\boldsymbol{\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 \( \boldsymbol{X}^T\boldsymbol{X} \) into our equation for ordinary least squares where
which is not the same as \( \tilde{y}_{\mathrm{OLS}}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y} \), which due to the orthogonality of \( \boldsymbol{U} \) would have given us that the model equals the output.
+
+
It means that the ordinary least square model (with the optimal
+parameters) \( \boldsymbol{\tilde{y}} \), corresponds to an orthogonal
+transformation of the output (or target) vector \( \boldsymbol{y} \) by the
+vectors of the matrix \( \boldsymbol{U} \). Note that the summation ends at
+\( p-1 \), that is \( \boldsymbol{\tilde{y}}\ne \boldsymbol{y} \). We can thus not use the
+orthogonality relation for the matrix \( \boldsymbol{U} \).
+
+
+
+
Further properties (important for our analyses later)
+
+
Let us study again \( \boldsymbol{X}^T\boldsymbol{X} \) in terms of our SVD,
This means the vectors \( \boldsymbol{v}_i \) of the orthogonal matrix \( \boldsymbol{V} \) are the eigenvectors of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \)
+with eigenvalues given by the singular values squared, that is
+
This means the vectors \( \boldsymbol{u}_i \) of the orthogonal matrix \( \boldsymbol{U} \) are the eigenvectors of the matrix \( \boldsymbol{X}\boldsymbol{X}^T \)
+with eigenvalues given by the singular values squared, that is
+
Important note: we have defined our design matrix \( \boldsymbol{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 \( \boldsymbol{X}^T\boldsymbol{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.
+
+
+
+
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
+
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
+
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
+
Ridge regression, as discussed above, 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.
+
+
+
Using our insights about the SVD of the design matrix \( \boldsymbol{X} \)
+We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as
+
Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the
+orthonormal basis \( \boldsymbol{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.
+
+
+
More interpretations
+
+
For the sake of simplicity, let us assume that the design matrix is orthonormal, that is
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.
Taking the derivative with respect to \( \boldsymbol{\theta} \) and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)
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.
+
Material for lab sessions sessions Tuesday and Wednesday
@@ -455,7 +1458,7 @@ 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.
More interpretations
diff --git a/doc/pub/week36/ipynb/ipynb-week36-src.tar.gz b/doc/pub/week36/ipynb/ipynb-week36-src.tar.gz
index 224acf905..b7e70f108 100644
Binary files a/doc/pub/week36/ipynb/ipynb-week36-src.tar.gz and b/doc/pub/week36/ipynb/ipynb-week36-src.tar.gz differ
diff --git a/doc/pub/week36/ipynb/week36.ipynb b/doc/pub/week36/ipynb/week36.ipynb
index f90acdd48..10dde77a6 100644
--- a/doc/pub/week36/ipynb/week36.ipynb
+++ b/doc/pub/week36/ipynb/week36.ipynb
@@ -2,7 +2,7 @@
"cells": [
{
"cell_type": "markdown",
- "id": "654ab862",
+ "id": "621499f3",
"metadata": {
"editable": true
},
@@ -14,7 +14,7 @@
},
{
"cell_type": "markdown",
- "id": "27bc19f6",
+ "id": "9850803f",
"metadata": {
"editable": true
},
@@ -27,38 +27,35 @@
},
{
"cell_type": "markdown",
- "id": "0e9af352",
+ "id": "1946c95d",
"metadata": {
"editable": true
},
"source": [
"## Plans for week 36\n",
"\n",
- "* Material for the lecture on Monday September 2\n",
+ "**Material for the lecture on Monday September 1:**\n",
+ "1. Linear Regression, ordinary least squares (OLS), Ridge and Lasso and mathematical analysis\n",
"\n",
- "a. Linear Regression, ordinary least squares (OLS), Ridge and Lasso and mathematical analysis\n",
- "\n",
- "b. Derivation of Gradient descent and discussion of implementations for\n",
+ "2. Derivation of Gradient descent and discussion of implementations for\n",
"\n",
"\n",
"\n",
- "* Material for the active learning sessions on Tuesday and Wednesday (see at the end of this slides)\n",
+ "**Material for the lab sessions on Tuesday and Wednesday (see at the end of these slides):**\n",
+ "1. Technicalities concerning Ridge and Lasso linear regression.\n",
"\n",
- " * Technicalities concerning Ridge and Lasso linear regression.\n",
- "\n",
- " * Presentation and discussion of the first project\n",
+ "2. Presentation and discussion of the first project\n",
"\n",
"\n",
- "* Reading suggestion:\n",
+ "**Reading suggestion:**\n",
+ "1. Goodfellow et al, Deep Learning, introduction to gradient descent, see chapter 4.3 at \n",
"\n",
- "a. Goodfellow et al, Deep Learning, introduction to gradient descent, see chapter 4.3 at \n",
- "\n",
- "b. Rashcka et al, pages 37-44 and pages 278-283 with focus on linear regression."
+ "2. Rashcka et al, pages 37-44 and pages 278-283 with focus on linear regression."
]
},
{
"cell_type": "markdown",
- "id": "8bd2183c",
+ "id": "68f1bb41",
"metadata": {
"editable": true
},
@@ -68,31 +65,1509 @@
},
{
"cell_type": "markdown",
- "id": "513f1331",
+ "id": "cf4c7ef3",
"metadata": {
"editable": true
},
"source": [
- "## Material for lab sessions sessions Tuesday and Wednesday\n",
+ "## Mathematical Interpretation of Ordinary Least Squares\n",
"\n",
- "The material here contains a summary of the lecture on Monday and discussion of SVD, Ridge and Lasso regression with examples"
+ "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). \n",
+ "\n",
+ "We have shown that in ordinary least squares the optimal parameters $\\theta$ are given by"
]
},
{
"cell_type": "markdown",
- "id": "ad197236",
+ "id": "91bd955c",
"metadata": {
"editable": true
},
"source": [
- "## Linear Regression and the SVD\n",
- "\n",
- "We used the SVD to analyse the matrix to invert in ordinary lineat regression"
+ "$$\n",
+ "\\hat{\\boldsymbol{\\theta}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
]
},
{
"cell_type": "markdown",
- "id": "47b9ddee",
+ "id": "fe6b5c23",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "The **hat** over $\\boldsymbol{\\theta}$ means we have the optimal parameters after minimization of the cost function.\n",
+ "\n",
+ "This means that our best model is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ab6c256a",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}=\\boldsymbol{X}\\hat{\\boldsymbol{\\theta}} = \\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "28ebdefd",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "We now define a matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e8a4ed80",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "18cbc7f5",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "We can rewrite"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ca9c127d",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}=\\boldsymbol{X}\\hat{\\boldsymbol{\\theta}} = \\boldsymbol{A}\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9ac3aac4",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "The matrix $\\boldsymbol{A}$ has the important property that $\\boldsymbol{A}^2=\\boldsymbol{A}$. This is the definition of a projection matrix.\n",
+ "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."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "689c9ad2",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Residual Error\n",
+ "\n",
+ "We have defined the residual error as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b7d5c970",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\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}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7ba1e34f",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "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}$."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8c81fa1b",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Simple case\n",
+ "\n",
+ "If the matrix $\\boldsymbol{X}$ is an orthogonal (or unitary in case of complex values) matrix, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "317142c4",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{X}\\boldsymbol{X}^T = \\boldsymbol{I}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2104cfb3",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "In this case the matrix $\\boldsymbol{A}$ becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2545dd7a",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T)=\\boldsymbol{I},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e483ff85",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "and we have the obvious case"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ec1217d8",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\epsilon}=\\boldsymbol{y}-\\tilde{\\boldsymbol{y}}=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a4294197",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "This serves also as a useful test of our codes."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "523bedff",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## The singular value decomposition\n",
+ "\n",
+ "The examples we have looked at so far are cases where we normally can\n",
+ "invert the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$. Using a polynomial expansion where we fit of various functions leads to\n",
+ "row vectors of the design matrix which are essentially orthogonal due\n",
+ "to the polynomial character of our model. Obtaining the inverse of the\n",
+ "design matrix is then often done via a so-called LU, QR or Cholesky\n",
+ "decomposition.\n",
+ "\n",
+ "As we will also see in the first project, \n",
+ "this may\n",
+ "however not the be case in general and a standard matrix inversion\n",
+ "algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below and in other examples.\n",
+ "\n",
+ "There is however a way to circumvent this problem and also\n",
+ "gain some insights about the ordinary least squares approach, and\n",
+ "later shrinkage methods like Ridge and Lasso regressions.\n",
+ "\n",
+ "This is given by the **Singular Value Decomposition** (SVD) algorithm,\n",
+ "perhaps the most powerful linear algebra algorithm. The SVD provides\n",
+ "a numerically stable matrix decomposition that is used in a large\n",
+ "swath oc applications and the decomposition is always stable\n",
+ "numerically.\n",
+ "\n",
+ "In machine learning it plays a central role in dealing with for\n",
+ "example design matrices that may be near singular or singular.\n",
+ "Furthermore, as we will see here, the singular values can be related\n",
+ "to the covariance matrix (and thereby the correlation matrix) and in\n",
+ "turn the variance of a given quantity. It plays also an important role\n",
+ "in the principal component analysis where high-dimensional data can be\n",
+ "reduced to the statistically relevant features."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7a63895f",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Linear Regression Problems\n",
+ "\n",
+ "One of the typical problems we encounter with linear regression, in particular \n",
+ "when the matrix $\\boldsymbol{X}$ (our so-called design matrix) is high-dimensional, \n",
+ "are problems with near singular or singular matrices. The column vectors of $\\boldsymbol{X}$ \n",
+ "may be linearly dependent, normally referred to as super-collinearity. \n",
+ "This means that the matrix may be rank deficient and it is basically impossible to \n",
+ "to model the data using linear regression. As an example, consider the matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5be6cc00",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\mathbf{X} & = \\left[\n",
+ "\\begin{array}{rrr}\n",
+ "1 & -1 & 2\n",
+ "\\\\\n",
+ "1 & 0 & 1\n",
+ "\\\\\n",
+ "1 & 2 & -1\n",
+ "\\\\\n",
+ "1 & 1 & 0\n",
+ "\\end{array} \\right]\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f0e55e26",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "The columns of $\\boldsymbol{X}$ are linearly dependent. We see this easily since the \n",
+ "the first column is the row-wise sum of the other two columns. The rank (more correct,\n",
+ "the column rank) of a matrix is the dimension of the space spanned by the\n",
+ "column vectors. Hence, the rank of $\\mathbf{X}$ is equal to the number\n",
+ "of linearly independent columns. In this particular case the matrix has rank 2.\n",
+ "\n",
+ "Super-collinearity of an $(n \\times p)$-dimensional design matrix $\\mathbf{X}$ implies\n",
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b0c93e43",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\boldsymbol{X} & = \\left[\n",
+ "\\begin{array}{rr}\n",
+ "1 & -1\n",
+ "\\\\\n",
+ "1 & -1\n",
+ "\\end{array} \\right].\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3639c924",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "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.\n",
+ "This is equivalent to saying that the matrix $\\boldsymbol{X}$ has at least an eigenvalue which is zero."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8d3ba757",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Fixing the singularity\n",
+ "\n",
+ "If our design matrix $\\boldsymbol{X}$ which enters the linear regression problem"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "81f9ca59",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "\n",
+ "\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\boldsymbol{\\theta} = (\\boldsymbol{X}^{T} \\boldsymbol{X})^{-1} \\boldsymbol{X}^{T} \\boldsymbol{y},\n",
+ "\\label{_auto1} \\tag{1}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "195027ed",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "has linearly dependent column vectors, we will not be able to compute the inverse\n",
+ "of $\\boldsymbol{X}^T\\boldsymbol{X}$ and we cannot find the parameters (estimators) $\\theta_i$. \n",
+ "The estimators are only well-defined if $(\\boldsymbol{X}^{T}\\boldsymbol{X})^{-1}$ exits. \n",
+ "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 \n",
+ "the regression parameters $\\theta_i$ cannot be estimated.\n",
+ "\n",
+ "A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e5fd03fb",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^{T} \\boldsymbol{X} \\rightarrow \\boldsymbol{X}^{T} \\boldsymbol{X}+\\lambda \\boldsymbol{I},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b0f9d6d0",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "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."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "332cc7e8",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Ridge and LASSO Regression\n",
+ "\n",
+ "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 \n",
+ "our optimization problem is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b78869a4",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "{\\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\\}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "848010ab",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "or we can state it as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e7abce99",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\theta}\\in\n",
+ "{\\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,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "16f05d95",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "where we have used the definition of a norm-2 vector, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "432f4790",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "954ac1c9",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "By minimizing the above equation with respect to the parameters\n",
+ "$\\boldsymbol{\\theta}$ we could then obtain an analytical expression for the\n",
+ "parameters $\\boldsymbol{\\theta}$. We can add a regularization parameter $\\lambda$ by\n",
+ "defining a new cost function to be optimized, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "02ba7398",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\theta}\\in\n",
+ "{\\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\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "505fa97e",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "which leads to the Ridge regression minimization problem where we\n",
+ "require that $\\vert\\vert \\boldsymbol{\\theta}\\vert\\vert_2^2\\le t$, where $t$ is\n",
+ "a finite number larger than zero. By defining"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d02ee785",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "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,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ecaded7f",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "we have a new optimization equation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f3eaed8e",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\theta}\\in\n",
+ "{\\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\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "343a5abf",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n",
+ "\n",
+ "Here we have defined the norm-1 as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "156ce8b1",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ff820f30",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Deriving the Ridge Regression Equations\n",
+ "\n",
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "28020db4",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "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},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1a8a4b70",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "and \n",
+ "taking the derivatives with respect to $\\boldsymbol{\\theta}$ we obtain then\n",
+ "a slightly modified matrix inversion problem which for finite values\n",
+ "of $\\lambda$ does not suffer from singularity problems. We obtain\n",
+ "the optimal parameters"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "389554f4",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\theta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b4f76602",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "dd9756e8",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\sum_{i=0}^{p-1} \\theta_i^2 \\leq t,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3ed04a92",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "with $t$ a finite positive number. \n",
+ "\n",
+ "If we keep the $1/n$ factor, the equation for the optimal $\\theta$ changes to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "be9f2cbc",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\theta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+n\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2c78b184",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "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.\n",
+ "\n",
+ "When we compare this with the ordinary least squares result we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a433cf4b",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\theta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "721b72cf",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$.\n",
+ "\n",
+ "We see that Ridge regression is nothing but the standard OLS with a\n",
+ "modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The consequences, in\n",
+ "particular for our discussion of the bias-variance tradeoff are rather\n",
+ "interesting. We will see that for specific values of $\\lambda$, we may\n",
+ "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.\n",
+ "\n",
+ "When we have discussed the singular value decomposition of the design\n",
+ "matrix $\\boldsymbol{X}$, we will in turn perform a more rigorous mathematical\n",
+ "discussion of Ridge regression.\n",
+ "\n",
+ "The code here is a simple demonstration of how to implement Ridge regression with our own code and compare this with scikit-learn."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "b957a32b",
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn import linear_model\n",
+ "\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
+ "\n",
+ "\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "np.random.seed(3155)\n",
+ "\n",
+ "n = 100\n",
+ "x = np.random.rand(n)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)\n",
+ "\n",
+ "Maxpolydegree = 20\n",
+ "X = np.zeros((n,Maxpolydegree))\n",
+ "#We include explicitely the intercept column\n",
+ "for degree in range(Maxpolydegree):\n",
+ " X[:,degree] = x**degree\n",
+ "# We split the data in test and training data\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
+ "\n",
+ "p = Maxpolydegree\n",
+ "I = np.eye(p,p)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 6\n",
+ "MSEOwnRidgePredict = np.zeros(nlambdas)\n",
+ "MSERidgePredict = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 2, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " OwnRidgeTheta = np.linalg.pinv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n",
+ " # Note: we include the intercept column and no scaling\n",
+ " RegRidge = linear_model.Ridge(lmb,fit_intercept=False)\n",
+ " RegRidge.fit(X_train,y_train)\n",
+ " # and then make the prediction\n",
+ " ytildeOwnRidge = X_train @ OwnRidgeTheta\n",
+ " ypredictOwnRidge = X_test @ OwnRidgeTheta\n",
+ " ytildeRidge = RegRidge.predict(X_train)\n",
+ " ypredictRidge = RegRidge.predict(X_test)\n",
+ " MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)\n",
+ " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n",
+ " print(\"Theta values for own Ridge implementation\")\n",
+ " print(OwnRidgeTheta)\n",
+ " print(\"Theta values for Scikit-Learn Ridge implementation\")\n",
+ " print(RegRidge.coef_)\n",
+ " print(\"MSE values for own Ridge implementation\")\n",
+ " print(MSEOwnRidgePredict[i])\n",
+ " print(\"MSE values for Scikit-Learn Ridge implementation\")\n",
+ " print(MSERidgePredict[i])\n",
+ "\n",
+ "# Now plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'r', label = 'MSE own Ridge Test')\n",
+ "plt.plot(np.log10(lambdas), MSERidgePredict, 'g', label = 'MSE Ridge Test')\n",
+ "\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8607d736",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "The results here agree when we force **Scikit-Learn**'s Ridge function to include the first column in our design matrix.\n",
+ "We see that the results agree very well. Here we have thus explicitely included the intercept column in the design matrix.\n",
+ "What happens if we do not include the intercept in our fit? We will discuss this in more detail next week."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0118b1d0",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Basic math of the SVD\n",
+ "\n",
+ "From standard linear algebra we know that a square matrix $\\boldsymbol{X}$ can be diagonalized if and only if it is \n",
+ "a so-called [normal matrix](https://en.wikipedia.org/wiki/Normal_matrix), that is if $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$\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}$.\n",
+ "The matrix has then a set of eigenpairs"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7328ad62",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "(\\lambda_1,\\boldsymbol{u}_1),\\dots, (\\lambda_n,\\boldsymbol{u}_n),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "110d74ec",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "and the eigenvalues are given by the diagonal matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "43775b2f",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}=\\mathrm{Diag}(\\lambda_1, \\dots,\\lambda_n).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5d9d7e09",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "The matrix $\\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\\boldsymbol{U}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "94ef14bf",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b9208f23",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "with $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ or $\\boldsymbol{U}\\boldsymbol{U}^{\\dagger}=\\boldsymbol{I}$.\n",
+ "\n",
+ "Not all square matrices are diagonalizable. A matrix like the one discussed above"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c2c30a84",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\begin{bmatrix} \n",
+ "1& -1 \\\\\n",
+ "1& -1\\\\\n",
+ "\\end{bmatrix}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "48697e16",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "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\n",
+ "$\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ is not fulfilled."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "80422083",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## The SVD, a Fantastic Algorithm\n",
+ "\n",
+ "However, and this is the strength of the SVD algorithm, any general\n",
+ "matrix $\\boldsymbol{X}$ can be decomposed in terms of a diagonal matrix and\n",
+ "two orthogonal/unitary matrices. The [Singular Value Decompostion\n",
+ "(SVD) theorem](https://en.wikipedia.org/wiki/Singular_value_decomposition)\n",
+ "states that a general $m\\times n$ matrix $\\boldsymbol{X}$ can be written in\n",
+ "terms of a diagonal matrix $\\boldsymbol{\\Sigma}$ of dimensionality $m\\times n$\n",
+ "and two orthognal matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$, where the first has\n",
+ "dimensionality $m \\times m$ and the last dimensionality $n\\times n$.\n",
+ "We have then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "34c18fb1",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ad87f938",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "As an example, the above defective matrix can be decomposed as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c3fae543",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\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,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ed2a3b1e",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "with eigenvalues $\\sigma_1=2$ and $\\sigma_2=0$. \n",
+ "The SVD exits always! \n",
+ "\n",
+ "The SVD\n",
+ "decomposition (singular values) gives eigenvalues \n",
+ "$\\sigma_i\\geq\\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=p$, the\n",
+ "eigenvalues (singular values) are zero.\n",
+ "\n",
+ "In the general case, where our design matrix $\\boldsymbol{X}$ has dimension\n",
+ "$n\\times p$, the matrix is thus decomposed into an $n\\times n$\n",
+ "orthogonal matrix $\\boldsymbol{U}$, a $p\\times p$ orthogonal matrix $\\boldsymbol{V}$\n",
+ "and a diagonal matrix $\\boldsymbol{\\Sigma}$ with $r=\\mathrm{min}(n,p)$\n",
+ "singular values $\\sigma_i\\geq 0$ on the main diagonal and zeros filling\n",
+ "the rest of the matrix. There are at most $p$ singular values\n",
+ "assuming that $n > p$. In our regression examples for the nuclear\n",
+ "masses and the equation of state this is indeed the case, while for\n",
+ "the Ising model we have $p > n$. These are often cases that lead to\n",
+ "near singular or singular matrices.\n",
+ "\n",
+ "The columns of $\\boldsymbol{U}$ are called the left singular vectors while the columns of $\\boldsymbol{V}$ are the right singular vectors."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c91325a5",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Economy-size SVD\n",
+ "\n",
+ "If we assume that $n > p$, then our matrix $\\boldsymbol{U}$ has dimension $n\n",
+ "\\times n$. The last $n-p$ columns of $\\boldsymbol{U}$ become however\n",
+ "irrelevant in our calculations since they are multiplied with the\n",
+ "zeros in $\\boldsymbol{\\Sigma}$.\n",
+ "\n",
+ "The economy-size decomposition removes extra rows or columns of zeros\n",
+ "from the diagonal matrix of singular values, $\\boldsymbol{\\Sigma}$, along with the columns\n",
+ "in either $\\boldsymbol{U}$ or $\\boldsymbol{V}$ that multiply those zeros in the expression. \n",
+ "Removing these zeros and columns can improve execution time\n",
+ "and reduce storage requirements without compromising the accuracy of\n",
+ "the decomposition.\n",
+ "\n",
+ "If $n > p$, we keep only the first $p$ columns of $\\boldsymbol{U}$ and $\\boldsymbol{\\Sigma}$ has dimension $p\\times p$. \n",
+ "If $p > n$, then only the first $n$ columns of $\\boldsymbol{V}$ are computed and $\\boldsymbol{\\Sigma}$ has dimension $n\\times n$.\n",
+ "The $n=p$ case is obvious, we retain the full SVD. \n",
+ "In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "349d7a8f",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Codes for the SVD"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "214c48ce",
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "# SVD inversion\n",
+ "def SVD(A):\n",
+ " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n",
+ " SVD is numerically more stable than the inversion algorithms provided by\n",
+ " numpy and scipy.linalg at the cost of being slower.\n",
+ " '''\n",
+ " U, S, VT = np.linalg.svd(A,full_matrices=True)\n",
+ " print('test U')\n",
+ " print( (np.transpose(U) @ U - U @np.transpose(U)))\n",
+ " print('test VT')\n",
+ " print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n",
+ " print(U)\n",
+ " print(S)\n",
+ " print(VT)\n",
+ "\n",
+ " D = np.zeros((len(U),len(VT)))\n",
+ " for i in range(0,len(VT)):\n",
+ " D[i,i]=S[i]\n",
+ " return U @ D @ VT\n",
+ "\n",
+ "\n",
+ "X = np.array([ [1.0,-1.0], [1.0,-1.0]])\n",
+ "#X = np.array([[1, 2], [3, 4], [5, 6]])\n",
+ "\n",
+ "print(X)\n",
+ "C = SVD(X)\n",
+ "# Print the difference between the original matrix and the SVD one\n",
+ "print(C-X)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ff572ce1",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "The matrix $\\boldsymbol{X}$ has columns that are linearly dependent. The first\n",
+ "column is the row-wise sum of the other two columns. The rank of a\n",
+ "matrix (the column rank) is the dimension of space spanned by the\n",
+ "column vectors. The rank of the matrix is the number of linearly\n",
+ "independent columns, in this case just $2$. We see this from the\n",
+ "singular values when running the above code. Running the standard\n",
+ "inversion algorithm for matrix inversion with $\\boldsymbol{X}^T\\boldsymbol{X}$ results\n",
+ "in the program terminating due to a singular matrix."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "32e06c3b",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Note about SVD Calculations\n",
+ "\n",
+ "The $U$, $S$, and $V$ matrices returned from the **svd()** function\n",
+ "cannot be multiplied directly.\n",
+ "\n",
+ "As you can see from the code, the $S$ vector must be converted into a\n",
+ "diagonal matrix. This may cause a problem as the size of the matrices\n",
+ "do not fit the rules of matrix multiplication, where the number of\n",
+ "columns in a matrix must match the number of rows in the subsequent\n",
+ "matrix.\n",
+ "\n",
+ "If you wish to include the zero singular values, you will need to\n",
+ "resize the matrices and set up a diagonal matrix as done in the above\n",
+ "example"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b32e6b97",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Mathematics of the SVD and implications\n",
+ "\n",
+ "Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies.\n",
+ "\n",
+ "Our starting point is our design matrix $\\boldsymbol{X}$ of dimension $n\\times p$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "69354b1a",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}\n",
+ "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
+ "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
+ "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
+ "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
+ "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
+ "\\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1f873fcd",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "We can SVD decompose our matrix as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "22ebe1ab",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a0dc0d9f",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "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$.\n",
+ "\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$.\n",
+ "\n",
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "168c1b66",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\sigma_0 > \\sigma_1 > \\sigma_2 > \\dots > \\sigma_{p-1} > 0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "50cb9802",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "All values beyond $p-1$ are all zero."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1ec29252",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Example Matrix\n",
+ "\n",
+ "As an example, consider the following $3\\times 2$ example for the matrix $\\boldsymbol{\\Sigma}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a568112a",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}=\n",
+ "\\begin{bmatrix}\n",
+ "2& 0 \\\\\n",
+ "0 & 1 \\\\\n",
+ "0 & 0 \\\\\n",
+ "\\end{bmatrix}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a20d59ba",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "The singular values are $\\sigma_0=2$ and $\\sigma_1=1$. It is common to rewrite the matrix $\\boldsymbol{\\Sigma}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cb8f997e",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}=\n",
+ "\\begin{bmatrix}\n",
+ "\\boldsymbol{\\tilde{\\Sigma}}\\\\\n",
+ "\\boldsymbol{0}\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fcb8b9af",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "where"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "07c3b63d",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\tilde{\\Sigma}}=\n",
+ "\\begin{bmatrix}\n",
+ "2& 0 \\\\\n",
+ "0 & 1 \\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7e51e38a",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "contains only the singular values. Note also (and we will use this below) that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0e25f153",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}=\n",
+ "\\begin{bmatrix}\n",
+ "4& 0 \\\\\n",
+ "0 & 1 \\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b5e93a92",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "which is a $2\\times 2 $ matrix while"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b6645d1b",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T=\n",
+ "\\begin{bmatrix}\n",
+ "4& 0 & 0\\\\\n",
+ "0 & 1 & 0\\\\\n",
+ "0 & 0 & 0\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "443712ff",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "is a $3\\times 3 $ matrix. The last row and column of this last matrix\n",
+ "contain only zeros. This will have important consequences for our SVD\n",
+ "decomposition of the design matrix."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4eef9305",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Setting up the Matrix to be inverted\n",
+ "\n",
+ "The matrix that may cause problems for us is $\\boldsymbol{X}^T\\boldsymbol{X}$. Using the SVD we can rewrite this matrix as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "156cfa45",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9118545b",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "and using the orthogonality of the matrix $\\boldsymbol{U}$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fba158e1",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5322f74b",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "We define $\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}=\\tilde{\\boldsymbol{\\Sigma}}^2$ which is a diagonal matrix containing only the singular values squared. It has dimensionality $p \\times p$.\n",
+ "\n",
+ "We can now insert the result for the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ into our equation for ordinary least squares where"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a4d49735",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "67c3cfb9",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "and using our SVD decomposition of $\\boldsymbol{X}$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "48a0f5d7",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\left(\\boldsymbol{V}\\tilde{\\boldsymbol{\\Sigma}}^{2}(\\boldsymbol{V}^T\\right)^{-1}\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8a837224",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "which gives us, using the orthogonality of the matrix $\\boldsymbol{V}$,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8cb7a1f5",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\tilde{y}_{\\mathrm{OLS}}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_i\\boldsymbol{u}^T_i\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "73000cf9",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "which is not the same as $\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}$, which due to the orthogonality of $\\boldsymbol{U}$ would have given us that the model equals the output.\n",
+ "\n",
+ "It means that the ordinary least square model (with the optimal\n",
+ "parameters) $\\boldsymbol{\\tilde{y}}$, corresponds to an orthogonal\n",
+ "transformation of the output (or target) vector $\\boldsymbol{y}$ by the\n",
+ "vectors of the matrix $\\boldsymbol{U}$. **Note that the summation ends at**\n",
+ "$p-1$, that is $\\boldsymbol{\\tilde{y}}\\ne \\boldsymbol{y}$. We can thus not use the\n",
+ "orthogonality relation for the matrix $\\boldsymbol{U}$."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "99fd315b",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Further properties (important for our analyses later)\n",
+ "\n",
+ "Let us study again $\\boldsymbol{X}^T\\boldsymbol{X}$ in terms of our SVD,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2c90ca3c",
"metadata": {
"editable": true
},
@@ -104,7 +1579,648 @@
},
{
"cell_type": "markdown",
- "id": "c68bd4a2",
+ "id": "55edce1b",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "If we now multiply from the right with $\\boldsymbol{V}$ (using the orthogonality of $\\boldsymbol{V}$) we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8914bdba",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{V}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2764a6a3",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "This means the vectors $\\boldsymbol{v}_i$ of the orthogonal matrix $\\boldsymbol{V}$ are the eigenvectors of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$\n",
+ "with eigenvalues given by the singular values squared, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "eb958b83",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{v}_i=\\boldsymbol{v}_i\\sigma_i^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4c9a382e",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "Similarly, if we use the SVD decomposition for the matrix $\\boldsymbol{X}\\boldsymbol{X}^T$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "85b639fc",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "22b5186f",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "If we now multiply from the right with $\\boldsymbol{U}$ (using the orthogonality of $\\boldsymbol{U}$) we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8c769dd3",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}\\boldsymbol{X}^T\\right)\\boldsymbol{U}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "07c98da1",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "This means the vectors $\\boldsymbol{u}_i$ of the orthogonal matrix $\\boldsymbol{U}$ are the eigenvectors of the matrix $\\boldsymbol{X}\\boldsymbol{X}^T$\n",
+ "with eigenvalues given by the singular values squared, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b72b4794",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}\\boldsymbol{X}^T\\right)\\boldsymbol{u}_i=\\boldsymbol{u}_i\\sigma_i^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ca243c34",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "**Important note**: we have defined our design matrix $\\boldsymbol{X}$ to be an\n",
+ "$n\\times p$ matrix. In most supervised learning cases we have that $n\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 $\\boldsymbol{X}^T\\boldsymbol{X}$ which is small and thereby easier to handle from a computational point of view (in terms of number of floating point operations).\n",
+ "\n",
+ "In our lectures, the number of columns will\n",
+ "always refer to the number of features in our data set, while the\n",
+ "number of rows represents the number of data inputs. Note that in\n",
+ "other texts you may find the opposite notation. This has consequences\n",
+ "for the definition of for example the covariance matrix and its relation to the SVD."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a32f8cb4",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Back to Ridge and LASSO Regression\n",
+ "\n",
+ "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 \n",
+ "our optimization problem is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "36a5761e",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "{\\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\\}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "78a25fba",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "or we can state it as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "dc3fc392",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\theta}\\in\n",
+ "{\\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,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "776a6b1b",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "where we have used the definition of a norm-2 vector, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d5e49536",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5114d169",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "By minimizing the above equation with respect to the parameters\n",
+ "$\\boldsymbol{\\theta}$ we could then obtain an analytical expression for the\n",
+ "parameters $\\boldsymbol{\\theta}$. We can add a regularization parameter $\\lambda$ by\n",
+ "defining a new cost function to be optimized, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4b46be4a",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\theta}\\in\n",
+ "{\\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\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2548fc2e",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "which leads to the Ridge regression minimization problem where we\n",
+ "require that $\\vert\\vert \\boldsymbol{\\theta}\\vert\\vert_2^2\\le t$, where $t$ is\n",
+ "a finite number larger than zero. By defining"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f10e0754",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "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,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "24e5a851",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "we have a new optimization equation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "abadd06e",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\theta}\\in\n",
+ "{\\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\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b310538d",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n",
+ "\n",
+ "Here we have defined the norm-1 as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "993d85b7",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "90863588",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "Ridge regression, as discussed above, is nothing but the standard OLS with a\n",
+ "modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The consequences, in\n",
+ "particular for our discussion of the bias-variance tradeoff are rather\n",
+ "interesting. We will see that for specific values of $\\lambda$, we may\n",
+ "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.\n",
+ "\n",
+ "Using our insights about the SVD of the design matrix $\\boldsymbol{X}$ \n",
+ "We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9961c60f",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}_{\\mathrm{OLS}}=\\boldsymbol{X}\\boldsymbol{\\theta} =\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e0baa289",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "For Ridge regression this becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9ae92883",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}_{\\mathrm{Ridge}}=\\boldsymbol{X}\\boldsymbol{\\theta}_{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{\\Sigma}^2\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "253eb07f",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$ from the SVD of the matrix $\\boldsymbol{X}$."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4a4694a8",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Interpreting the Ridge results\n",
+ "\n",
+ "Since $\\lambda \\geq 0$, it means that compared to OLS, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d8ba62af",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7a152478",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n",
+ "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n",
+ "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n",
+ "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n",
+ "\\sigma_{i+1}$.\n",
+ "\n",
+ "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."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2dad5d0d",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## More interpretations\n",
+ "\n",
+ "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4d51dc36",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fb0636bb",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "In this case the standard OLS results in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3e787280",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\theta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{n-1}\\boldsymbol{u}_i\\boldsymbol{u}_i^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c4c794e7",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2d780f46",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\theta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\theta}^{\\mathrm{OLS}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "27f0b04d",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n",
+ "the Ridge estimator converges to zero when the hyperparameter goes to\n",
+ "infinity.\n",
+ "\n",
+ "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n",
+ "\n",
+ "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n",
+ "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e6736c46",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Deriving the Lasso Regression Equations\n",
+ "\n",
+ "Using the matrix-vector expression for Lasso regression, we have the following **cost** function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d30ef5ac",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\theta})=\\frac{1}{n}\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\theta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\theta})\\right\\}+\\lambda\\vert\\vert\\boldsymbol{\\theta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d9e09aac",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "Taking the derivative with respect to $\\boldsymbol{\\theta}$ and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "936a99a1",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\frac{d \\vert \\theta\\vert}{d \\theta}=\\mathrm{sgn}(\\theta)=\\left\\{\\begin{array}{cc} 1 & \\theta > 0 \\\\-1 & \\theta < 0, \\end{array}\\right.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "acd780b1",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "we have that the derivative of the cost function is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ee8c183a",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{X},\\boldsymbol{\\theta})}{\\partial \\boldsymbol{\\theta}}=-\\frac{2}{n}\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\theta})+\\lambda sgn(\\boldsymbol{\\theta})=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "aab1f387",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "and reordering we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "56a08fe6",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\theta}+\\frac{n}{2}\\lambda sgn(\\boldsymbol{\\theta})=2\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3a7376bf",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "We can redefine $\\lambda$ to absorb the constant $n/2$ and we rewrite the last equation as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "030fc2c9",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\theta}+\\lambda sgn(\\boldsymbol{\\theta})=2\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1146c162",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "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."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d58c9fcc",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Material for lab sessions sessions Tuesday and Wednesday\n",
+ "\n",
+ "The material here contains a summary of the lecture on Monday and discussion of SVD, Ridge and Lasso regression with examples"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0fb1040e",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Linear Regression and the SVD\n",
+ "\n",
+ "We used the SVD to analyse the matrix to invert in ordinary lineat regression"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "db25930c",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4a546ba3",
"metadata": {
"editable": true
},
@@ -114,7 +2230,7 @@
},
{
"cell_type": "markdown",
- "id": "90436ad2",
+ "id": "c6de0dc0",
"metadata": {
"editable": true
},
@@ -126,7 +2242,7 @@
},
{
"cell_type": "markdown",
- "id": "1f67366e",
+ "id": "fe5dcdab",
"metadata": {
"editable": true
},
@@ -136,7 +2252,7 @@
},
{
"cell_type": "markdown",
- "id": "ae1866df",
+ "id": "2a51b2e5",
"metadata": {
"editable": true
},
@@ -153,7 +2269,7 @@
},
{
"cell_type": "markdown",
- "id": "de4b618c",
+ "id": "bcb630ab",
"metadata": {
"editable": true
},
@@ -163,7 +2279,7 @@
},
{
"cell_type": "markdown",
- "id": "b1b26f26",
+ "id": "c8e959be",
"metadata": {
"editable": true
},
@@ -175,7 +2291,7 @@
},
{
"cell_type": "markdown",
- "id": "dfd9e09f",
+ "id": "3c833fb9",
"metadata": {
"editable": true
},
@@ -185,7 +2301,7 @@
},
{
"cell_type": "markdown",
- "id": "2d875472",
+ "id": "f26ce824",
"metadata": {
"editable": true
},
@@ -197,7 +2313,7 @@
},
{
"cell_type": "markdown",
- "id": "a2dd73e0",
+ "id": "a53e6221",
"metadata": {
"editable": true
},
@@ -211,7 +2327,7 @@
},
{
"cell_type": "markdown",
- "id": "c1bfb958",
+ "id": "92dfaee8",
"metadata": {
"editable": true
},
@@ -223,7 +2339,7 @@
},
{
"cell_type": "markdown",
- "id": "35f471a5",
+ "id": "5900606b",
"metadata": {
"editable": true
},
@@ -242,7 +2358,7 @@
},
{
"cell_type": "markdown",
- "id": "83252299",
+ "id": "96866dd5",
"metadata": {
"editable": true
},
@@ -255,7 +2371,7 @@
},
{
"cell_type": "markdown",
- "id": "4a8521ba",
+ "id": "2de2dd52",
"metadata": {
"editable": true
},
@@ -267,7 +2383,7 @@
},
{
"cell_type": "markdown",
- "id": "33246dbe",
+ "id": "85c82be2",
"metadata": {
"editable": true
},
@@ -277,7 +2393,7 @@
},
{
"cell_type": "markdown",
- "id": "9e05b84b",
+ "id": "c9bd13b0",
"metadata": {
"editable": true
},
@@ -290,7 +2406,7 @@
},
{
"cell_type": "markdown",
- "id": "386f7592",
+ "id": "00a53089",
"metadata": {
"editable": true
},
@@ -300,7 +2416,7 @@
},
{
"cell_type": "markdown",
- "id": "305c74c8",
+ "id": "9156ea65",
"metadata": {
"editable": true
},
@@ -312,7 +2428,7 @@
},
{
"cell_type": "markdown",
- "id": "6c3eed08",
+ "id": "5de72fba",
"metadata": {
"editable": true
},
@@ -327,7 +2443,7 @@
},
{
"cell_type": "markdown",
- "id": "d61c3bb7",
+ "id": "b842e373",
"metadata": {
"editable": true
},
@@ -340,7 +2456,7 @@
},
{
"cell_type": "markdown",
- "id": "4b0e2714",
+ "id": "f0fe85a5",
"metadata": {
"editable": true
},
@@ -354,7 +2470,7 @@
},
{
"cell_type": "markdown",
- "id": "b3987610",
+ "id": "a96485c6",
"metadata": {
"editable": true
},
@@ -366,7 +2482,7 @@
},
{
"cell_type": "markdown",
- "id": "d1957b4b",
+ "id": "845dac57",
"metadata": {
"editable": true
},
@@ -376,7 +2492,7 @@
},
{
"cell_type": "markdown",
- "id": "bb514910",
+ "id": "feb1287c",
"metadata": {
"editable": true
},
@@ -389,7 +2505,7 @@
},
{
"cell_type": "markdown",
- "id": "a2630434",
+ "id": "cde81855",
"metadata": {
"editable": true
},
@@ -401,7 +2517,7 @@
},
{
"cell_type": "markdown",
- "id": "f83f49fb",
+ "id": "426999dd",
"metadata": {
"editable": true
},
@@ -413,7 +2529,7 @@
},
{
"cell_type": "markdown",
- "id": "b8fbce65",
+ "id": "b023d5ec",
"metadata": {
"editable": true
},
@@ -425,7 +2541,7 @@
},
{
"cell_type": "markdown",
- "id": "ab835024",
+ "id": "8c88df1d",
"metadata": {
"editable": true
},
@@ -437,7 +2553,7 @@
},
{
"cell_type": "markdown",
- "id": "59f9c302",
+ "id": "7b538bea",
"metadata": {
"editable": true
},
@@ -451,7 +2567,7 @@
},
{
"cell_type": "markdown",
- "id": "60ebd5bc",
+ "id": "48b626f8",
"metadata": {
"editable": true
},
@@ -463,7 +2579,7 @@
},
{
"cell_type": "markdown",
- "id": "362ea5fa",
+ "id": "de641451",
"metadata": {
"editable": true
},
@@ -473,7 +2589,7 @@
},
{
"cell_type": "markdown",
- "id": "61d34847",
+ "id": "a42a620b",
"metadata": {
"editable": true
},
@@ -485,7 +2601,7 @@
},
{
"cell_type": "markdown",
- "id": "d25b4c25",
+ "id": "f3f3ca34",
"metadata": {
"editable": true
},
@@ -495,7 +2611,7 @@
},
{
"cell_type": "markdown",
- "id": "0d0a0404",
+ "id": "9ae449cb",
"metadata": {
"editable": true
},
@@ -507,7 +2623,7 @@
},
{
"cell_type": "markdown",
- "id": "7712fb05",
+ "id": "d0788dec",
"metadata": {
"editable": true
},
@@ -519,7 +2635,7 @@
},
{
"cell_type": "markdown",
- "id": "064a101a",
+ "id": "f6ce16ec",
"metadata": {
"editable": true
},
@@ -529,7 +2645,7 @@
},
{
"cell_type": "markdown",
- "id": "1bd71d29",
+ "id": "aef8a956",
"metadata": {
"editable": true
},
@@ -540,7 +2656,7 @@
},
{
"cell_type": "markdown",
- "id": "92e51db6",
+ "id": "ce797210",
"metadata": {
"editable": true
},
@@ -552,7 +2668,7 @@
},
{
"cell_type": "markdown",
- "id": "68683057",
+ "id": "bce49278",
"metadata": {
"editable": true
},
@@ -568,7 +2684,7 @@
},
{
"cell_type": "markdown",
- "id": "18240326",
+ "id": "2560c4b3",
"metadata": {
"editable": true
},
@@ -581,7 +2697,7 @@
},
{
"cell_type": "markdown",
- "id": "37ab6fb0",
+ "id": "f4cba9b6",
"metadata": {
"editable": true
},
@@ -593,7 +2709,7 @@
},
{
"cell_type": "markdown",
- "id": "39a960dd",
+ "id": "de2a1df1",
"metadata": {
"editable": true
},
@@ -603,7 +2719,7 @@
},
{
"cell_type": "markdown",
- "id": "f4f6a309",
+ "id": "25fbea25",
"metadata": {
"editable": true
},
@@ -615,7 +2731,7 @@
},
{
"cell_type": "markdown",
- "id": "940a96a0",
+ "id": "2250909a",
"metadata": {
"editable": true
},
@@ -625,7 +2741,7 @@
},
{
"cell_type": "markdown",
- "id": "cf9d0724",
+ "id": "f5f1ec38",
"metadata": {
"editable": true
},
@@ -637,7 +2753,7 @@
},
{
"cell_type": "markdown",
- "id": "a6a5c44c",
+ "id": "353a033b",
"metadata": {
"editable": true
},
@@ -649,7 +2765,7 @@
},
{
"cell_type": "markdown",
- "id": "e9894a9f",
+ "id": "aaff0699",
"metadata": {
"editable": true
},
@@ -660,12 +2776,12 @@
"eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n",
"\\sigma_{i+1}$.\n",
"\n",
- "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."
]
},
{
"cell_type": "markdown",
- "id": "fbffece4",
+ "id": "9086c7ed",
"metadata": {
"editable": true
},
@@ -677,7 +2793,7 @@
},
{
"cell_type": "markdown",
- "id": "381fe4a6",
+ "id": "ed4ff265",
"metadata": {
"editable": true
},
@@ -689,7 +2805,7 @@
},
{
"cell_type": "markdown",
- "id": "6786abf3",
+ "id": "00d299f4",
"metadata": {
"editable": true
},
@@ -699,7 +2815,7 @@
},
{
"cell_type": "markdown",
- "id": "5d8f3546",
+ "id": "ebe5d9d8",
"metadata": {
"editable": true
},
@@ -711,7 +2827,7 @@
},
{
"cell_type": "markdown",
- "id": "2507d9e7",
+ "id": "c6edfc6a",
"metadata": {
"editable": true
},
@@ -721,7 +2837,7 @@
},
{
"cell_type": "markdown",
- "id": "945284de",
+ "id": "e0b4814d",
"metadata": {
"editable": true
},
@@ -733,7 +2849,7 @@
},
{
"cell_type": "markdown",
- "id": "61991d06",
+ "id": "27682ade",
"metadata": {
"editable": true
},
@@ -750,7 +2866,7 @@
},
{
"cell_type": "markdown",
- "id": "a5730190",
+ "id": "77a93e3d",
"metadata": {
"editable": true
},
@@ -762,7 +2878,7 @@
},
{
"cell_type": "markdown",
- "id": "1b9baf1a",
+ "id": "2b5f205f",
"metadata": {
"editable": true
},
@@ -774,7 +2890,7 @@
},
{
"cell_type": "markdown",
- "id": "865388f2",
+ "id": "e3b126e5",
"metadata": {
"editable": true
},
@@ -784,7 +2900,7 @@
},
{
"cell_type": "markdown",
- "id": "db158717",
+ "id": "da358f73",
"metadata": {
"editable": true
},
@@ -796,7 +2912,7 @@
},
{
"cell_type": "markdown",
- "id": "e26695ac",
+ "id": "0f2e27fe",
"metadata": {
"editable": true
},
@@ -806,7 +2922,7 @@
},
{
"cell_type": "markdown",
- "id": "67a5ca74",
+ "id": "5a90b8b0",
"metadata": {
"editable": true
},
@@ -818,7 +2934,7 @@
},
{
"cell_type": "markdown",
- "id": "2bed7a2b",
+ "id": "ee51ab14",
"metadata": {
"editable": true
},
@@ -828,7 +2944,7 @@
},
{
"cell_type": "markdown",
- "id": "1bdbbaca",
+ "id": "2a6710db",
"metadata": {
"editable": true
},
@@ -840,7 +2956,7 @@
},
{
"cell_type": "markdown",
- "id": "8c12039f",
+ "id": "e1f59642",
"metadata": {
"editable": true
},
@@ -850,7 +2966,7 @@
},
{
"cell_type": "markdown",
- "id": "ef20a9b4",
+ "id": "7ce86400",
"metadata": {
"editable": true
},
@@ -865,7 +2981,7 @@
},
{
"cell_type": "markdown",
- "id": "ff638cc0",
+ "id": "98b73725",
"metadata": {
"editable": true
},
@@ -877,7 +2993,7 @@
},
{
"cell_type": "markdown",
- "id": "3311b61b",
+ "id": "59ec5543",
"metadata": {
"editable": true
},
@@ -887,7 +3003,7 @@
},
{
"cell_type": "markdown",
- "id": "1e40ccd2",
+ "id": "0b602027",
"metadata": {
"editable": true
},
@@ -899,7 +3015,7 @@
},
{
"cell_type": "markdown",
- "id": "fac9dff2",
+ "id": "4deb54d0",
"metadata": {
"editable": true
},
@@ -911,7 +3027,7 @@
},
{
"cell_type": "markdown",
- "id": "5134e6ba",
+ "id": "1bb3b75c",
"metadata": {
"editable": true
},
@@ -923,7 +3039,7 @@
},
{
"cell_type": "markdown",
- "id": "a6907400",
+ "id": "ec06de57",
"metadata": {
"editable": true
},
@@ -933,7 +3049,7 @@
},
{
"cell_type": "markdown",
- "id": "8f47d69d",
+ "id": "443a4c51",
"metadata": {
"editable": true
},
@@ -945,7 +3061,7 @@
},
{
"cell_type": "markdown",
- "id": "c2fe94eb",
+ "id": "2caa2792",
"metadata": {
"editable": true
},
@@ -957,7 +3073,7 @@
},
{
"cell_type": "markdown",
- "id": "0e383b22",
+ "id": "fdab0d9e",
"metadata": {
"editable": true
},
@@ -969,7 +3085,7 @@
},
{
"cell_type": "markdown",
- "id": "217a5190",
+ "id": "9bf9979d",
"metadata": {
"editable": true
},
@@ -979,7 +3095,7 @@
},
{
"cell_type": "markdown",
- "id": "af831ebf",
+ "id": "69a9abf7",
"metadata": {
"editable": true
},
@@ -991,7 +3107,7 @@
},
{
"cell_type": "markdown",
- "id": "d63c47e3",
+ "id": "08351598",
"metadata": {
"editable": true
},
@@ -1001,7 +3117,7 @@
},
{
"cell_type": "markdown",
- "id": "c8432613",
+ "id": "8cd66c38",
"metadata": {
"editable": true
},
@@ -1015,7 +3131,7 @@
},
{
"cell_type": "markdown",
- "id": "40be7059",
+ "id": "4887c632",
"metadata": {
"editable": true
},
@@ -1025,7 +3141,7 @@
},
{
"cell_type": "markdown",
- "id": "ae35aa35",
+ "id": "a4660170",
"metadata": {
"editable": true
},
@@ -1037,7 +3153,7 @@
},
{
"cell_type": "markdown",
- "id": "b9e6d414",
+ "id": "1b0fea4a",
"metadata": {
"editable": true
},
@@ -1049,7 +3165,7 @@
},
{
"cell_type": "markdown",
- "id": "8488396a",
+ "id": "26ac6cb7",
"metadata": {
"editable": true
},
@@ -1059,7 +3175,7 @@
},
{
"cell_type": "markdown",
- "id": "1cd26957",
+ "id": "2eab96bb",
"metadata": {
"editable": true
},
@@ -1071,7 +3187,7 @@
},
{
"cell_type": "markdown",
- "id": "15f3283b",
+ "id": "683837ff",
"metadata": {
"editable": true
},
@@ -1081,7 +3197,7 @@
},
{
"cell_type": "markdown",
- "id": "59e9eeb6",
+ "id": "35faa9c3",
"metadata": {
"editable": true
},
@@ -1093,7 +3209,7 @@
},
{
"cell_type": "markdown",
- "id": "6082802f",
+ "id": "1d9e928d",
"metadata": {
"editable": true
},
@@ -1105,7 +3221,7 @@
},
{
"cell_type": "markdown",
- "id": "35ecd677",
+ "id": "a6c85dfa",
"metadata": {
"editable": true
},
@@ -1115,7 +3231,7 @@
},
{
"cell_type": "markdown",
- "id": "be994264",
+ "id": "707c9ba6",
"metadata": {
"editable": true
},
@@ -1127,7 +3243,7 @@
},
{
"cell_type": "markdown",
- "id": "fe94745b",
+ "id": "a262ea3d",
"metadata": {
"editable": true
},
@@ -1137,7 +3253,7 @@
},
{
"cell_type": "markdown",
- "id": "5b49cedd",
+ "id": "a86375ed",
"metadata": {
"editable": true
},
@@ -1149,7 +3265,7 @@
},
{
"cell_type": "markdown",
- "id": "a806f154",
+ "id": "0cf34409",
"metadata": {
"editable": true
},
@@ -1161,7 +3277,7 @@
},
{
"cell_type": "markdown",
- "id": "aefa84ec",
+ "id": "2b27c3be",
"metadata": {
"editable": true
},
@@ -1171,7 +3287,7 @@
},
{
"cell_type": "markdown",
- "id": "f01d6040",
+ "id": "a6f53a04",
"metadata": {
"editable": true
},
@@ -1183,7 +3299,7 @@
},
{
"cell_type": "markdown",
- "id": "25ae26b8",
+ "id": "b8b440e5",
"metadata": {
"editable": true
},
@@ -1196,7 +3312,7 @@
},
{
"cell_type": "markdown",
- "id": "0db0770b",
+ "id": "67fd1c0d",
"metadata": {
"editable": true
},
@@ -1208,7 +3324,7 @@
},
{
"cell_type": "markdown",
- "id": "4296d66b",
+ "id": "3cdbca60",
"metadata": {
"editable": true
},
@@ -1220,7 +3336,7 @@
},
{
"cell_type": "markdown",
- "id": "167a1b00",
+ "id": "ae419827",
"metadata": {
"editable": true
},
@@ -1232,7 +3348,7 @@
},
{
"cell_type": "markdown",
- "id": "ae480e8f",
+ "id": "6a690852",
"metadata": {
"editable": true
},
@@ -1242,7 +3358,7 @@
},
{
"cell_type": "markdown",
- "id": "d787a1dc",
+ "id": "24417171",
"metadata": {
"editable": true
},
@@ -1254,7 +3370,7 @@
},
{
"cell_type": "markdown",
- "id": "47cd33a8",
+ "id": "1a4ff44b",
"metadata": {
"editable": true
},
@@ -1264,7 +3380,7 @@
},
{
"cell_type": "markdown",
- "id": "bd43b981",
+ "id": "7f1dc0b6",
"metadata": {
"editable": true
},
@@ -1276,7 +3392,7 @@
},
{
"cell_type": "markdown",
- "id": "05f0108c",
+ "id": "c90156c1",
"metadata": {
"editable": true
},
@@ -1286,7 +3402,7 @@
},
{
"cell_type": "markdown",
- "id": "f74d5dc6",
+ "id": "9fa725ef",
"metadata": {
"editable": true
},
@@ -1298,7 +3414,7 @@
},
{
"cell_type": "markdown",
- "id": "68cdb6be",
+ "id": "1d2b029c",
"metadata": {
"editable": true
},
@@ -1308,7 +3424,7 @@
},
{
"cell_type": "markdown",
- "id": "5d7d1f9f",
+ "id": "271db328",
"metadata": {
"editable": true
},
@@ -1321,7 +3437,7 @@
},
{
"cell_type": "markdown",
- "id": "a33af366",
+ "id": "d8b5b4f6",
"metadata": {
"editable": true
},
@@ -1333,7 +3449,7 @@
},
{
"cell_type": "markdown",
- "id": "510d9216",
+ "id": "1232b642",
"metadata": {
"editable": true
},
@@ -1345,7 +3461,7 @@
},
{
"cell_type": "markdown",
- "id": "4c6cf088",
+ "id": "fc401cbb",
"metadata": {
"editable": true
},
@@ -1355,7 +3471,7 @@
},
{
"cell_type": "markdown",
- "id": "af73ab41",
+ "id": "53c50332",
"metadata": {
"editable": true
},
@@ -1367,7 +3483,7 @@
},
{
"cell_type": "markdown",
- "id": "0616ec01",
+ "id": "50a046d9",
"metadata": {
"editable": true
},
@@ -1384,7 +3500,7 @@
},
{
"cell_type": "markdown",
- "id": "b7330fcf",
+ "id": "7ad94202",
"metadata": {
"editable": true
},
@@ -1396,7 +3512,7 @@
},
{
"cell_type": "markdown",
- "id": "99d7b150",
+ "id": "24acdcc1",
"metadata": {
"editable": true
},
@@ -1408,7 +3524,7 @@
},
{
"cell_type": "markdown",
- "id": "0803ea8a",
+ "id": "c3327ee1",
"metadata": {
"editable": true
},
@@ -1418,7 +3534,7 @@
},
{
"cell_type": "markdown",
- "id": "dac7d432",
+ "id": "fe60589e",
"metadata": {
"editable": true
},
@@ -1430,7 +3546,7 @@
},
{
"cell_type": "markdown",
- "id": "cb7d543c",
+ "id": "5a662c04",
"metadata": {
"editable": true
},
@@ -1440,7 +3556,7 @@
},
{
"cell_type": "markdown",
- "id": "0a73761e",
+ "id": "f1b6531c",
"metadata": {
"editable": true
},
@@ -1452,7 +3568,7 @@
},
{
"cell_type": "markdown",
- "id": "ff21f10e",
+ "id": "29464730",
"metadata": {
"editable": true
},
@@ -1462,7 +3578,7 @@
},
{
"cell_type": "markdown",
- "id": "2b1b8d20",
+ "id": "c998bd2a",
"metadata": {
"editable": true
},
@@ -1474,7 +3590,7 @@
},
{
"cell_type": "markdown",
- "id": "c449fb5e",
+ "id": "ab2ebc84",
"metadata": {
"editable": true
},
@@ -1484,7 +3600,7 @@
},
{
"cell_type": "markdown",
- "id": "96af3eda",
+ "id": "2dc43348",
"metadata": {
"editable": true
},
@@ -1498,16 +3614,14 @@
},
{
"cell_type": "code",
- "execution_count": 1,
- "id": "c8a3087a",
+ "execution_count": 3,
+ "id": "20f9c9f3",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
- "%matplotlib inline\n",
- "\n",
"import os\n",
"import numpy as np\n",
"import pandas as pd\n",
@@ -1561,7 +3675,7 @@
},
{
"cell_type": "markdown",
- "id": "e5510a2c",
+ "id": "5f6a1a60",
"metadata": {
"editable": true
},
@@ -1571,7 +3685,7 @@
},
{
"cell_type": "markdown",
- "id": "8d959d30",
+ "id": "885d9cc9",
"metadata": {
"editable": true
},
@@ -1581,8 +3695,8 @@
},
{
"cell_type": "code",
- "execution_count": 2,
- "id": "1d1473e5",
+ "execution_count": 4,
+ "id": "76f8b826",
"metadata": {
"collapsed": false,
"editable": true
@@ -1649,7 +3763,7 @@
},
{
"cell_type": "markdown",
- "id": "b9861ae2",
+ "id": "b3da2bd5",
"metadata": {
"editable": true
},
@@ -1659,8 +3773,8 @@
},
{
"cell_type": "code",
- "execution_count": 3,
- "id": "7cc52080",
+ "execution_count": 5,
+ "id": "4504fbc8",
"metadata": {
"collapsed": false,
"editable": true
diff --git a/doc/src/week36/week36.do.txt b/doc/src/week36/week36.do.txt
index 39af66146..581192358 100644
--- a/doc/src/week36/week36.do.txt
+++ b/doc/src/week36/week36.do.txt
@@ -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
+
+