Files
FYS-STK4155/doc/LectureNotes/_build/jupyter_execute/week36.ipynb
T
2023-09-03 14:23:01 +02:00

96 KiB

Week 36: Statistical interpretation of Linear Regression and Resampling techniques

Morten Hjorth-Jensen, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

Date: September 4-8, 2023

Plans for week 36

  • Material for the active learning sessions on Tuesday and Wednesday

  • Material for the lecture on Thursday September 7

    • Linear Regression and links with Statistics, Resampling methods

    • Recommended Reading: Goodfellow et al chapter 3 on probability theory, see URL:""

    • See also Murphy, sections 2.4 (Gaussian distributions) and 3.2 (Bayesian Statistics, basis)

Material for the active learning sessions Tuesday and Wednesday

The material here contains a summary from last Week and discussion of SVD, Ridge and Lasso regression with examples

Linear Regression and the SVD

We used the SVD to analyse the matrix to invert in ordinary lineat regression


\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.

Since the matrices here have dimension p\times p, with p corresponding to the singular values, we defined last week the matrix


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

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},

meaning we can write


\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2\boldsymbol{V}^T.

Multiplying from the right with \boldsymbol{V} (using the orthogonality of \boldsymbol{V}) we get


\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{V}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2.

What does it mean?

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


\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{v}_i=\boldsymbol{v}_i\sigma_i^2.

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.

If we now recall the definition of the covariance matrix (not using Bessel's correction) we have


\boldsymbol{C}[\boldsymbol{X}]=\frac{1}{n}\boldsymbol{X}^T\boldsymbol{X},

meaning that every squared non-singular value of \boldsymbol{X} divided by n ( the number of samples) are the eigenvalues of the covariance matrix. Every singular value of \boldsymbol{X} is thus a positive square root of an eigenvalue of \boldsymbol{X}^T\boldsymbol{X}. If the matrix \boldsymbol{X} is self-adjoint, the singular values of \boldsymbol{X} are equal to the absolute value of the eigenvalues of \boldsymbol{X}.

And finally \boldsymbol{X}\boldsymbol{X}^T

For \boldsymbol{X}\boldsymbol{X}^T we found


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

Since the matrices here have dimension n\times n, we have


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

leading to


\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{U}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}\boldsymbol{U}^T.

Multiplying with \boldsymbol{U} from the right gives us the eigenvalue problem


(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U}=\boldsymbol{U}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}.

It means that the eigenvalues of \boldsymbol{X}\boldsymbol{X}^T are again given by the non-zero singular values plus now a series of zeros. The column vectors of \boldsymbol{U} are the eigenvectors of \boldsymbol{X}\boldsymbol{X}^T and measure how much correlations are contained in the rows of \boldsymbol{X}.

Since we will mainly be interested in the correlations among the features of our data (the columns of \boldsymbol{X}, the quantity of interest for us are the non-zero singular values and the column vectors of \boldsymbol{V}.

Code for SVD and Inversion of Matrices

How do we use the SVD to invert a matrix \boldsymbol{X}^\boldsymbol{X} which is singular or near singular? The simple answer is to use the linear algebra function for the computation of the pseudoinverse of a given matrix \boldsymbol{X}, that is

In [1]:
import numpy as np
X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])
Xinv = np.linlag.pinv(X)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [1], in <cell line: 3>()
      1 import numpy as np
      2 X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])
----> 3 Xinv = np.linlag.pinv(X)

File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/numpy/__init__.py:313, in __getattr__(attr)
    310     from .testing import Tester
    311     return Tester
--> 313 raise AttributeError("module {!r} has no attribute "
    314                      "{!r}".format(__name__, attr))

AttributeError: module 'numpy' has no attribute 'linlag'

Let us first look at a matrix which does not causes problems and write our own function where we just use the SVD.

In [2]:
import numpy as np
# SVD inversion
def SVDinv(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)
    print('test U')
    print( (np.transpose(U) @ U - U @np.transpose(U)))
    print('test VT')
    print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))


    D = np.zeros((len(U),len(VT)))
    D = np.diag(s)
    UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)
    return np.matmul(V,np.matmul(invD,UT))


#X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])
# Non-singular square matrix
X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])
print(X)
A = np.transpose(X) @ X
# Brute force inversion
B = np.linalg.inv(A)  # here we could use np.linalg.pinv(A)
C = SVDinv(A)
print(np.abs(B-C))

Inverse of Rectangular 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.

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}})


\boldsymbol{A}_{\mathrm{PI}}= \boldsymbol{V}\boldsymbol{D}_{\mathrm{PI}}\boldsymbol{U}^T,

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.

In [3]:
import numpy as np
# SVD inversion
def SVDinv(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.

Ridge and LASSO Regression

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


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

or we can state it as


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

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


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

From OLS to Ridge and Lasso

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


{\displaystyle \min_{\boldsymbol{\beta}\in
{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^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.

By defining


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

we have a new optimization equation


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

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

Here we have defined the norm-1 as


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

Deriving the Ridge Regression Equations

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


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

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


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

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


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

with t a finite positive number.

Note on Scikit-Learn

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


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

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.

Comparison with OLS

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


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

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

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

SVD analysis

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


\tilde{\boldsymbol{y}}_{\mathrm{OLS}}=\boldsymbol{X}\boldsymbol{\beta}  =\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}.

For Ridge regression this becomes


\tilde{\boldsymbol{y}}_{\mathrm{Ridge}}=\boldsymbol{X}\boldsymbol{\beta}_{\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},

with the vectors \boldsymbol{u}_j being the columns of \boldsymbol{U} from the SVD of the matrix \boldsymbol{X}.

Interpreting the Ridge results

Since \lambda \geq 0, it means that compared to OLS, we have


\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1.

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


\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}.

In this case the standard OLS results in


\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{n-1}\boldsymbol{u}_i\boldsymbol{u}_i^T\boldsymbol{y},

and


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

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 article is highly recommended. Similarly, Mehta et al's article is also recommended.

Deriving the Lasso Regression Equations

Using the matrix-vector expression for Lasso regression, we have the following cost function


C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1,

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.

we have that the derivative of the cost function is


\frac{\partial C(\boldsymbol{X},\boldsymbol{\beta})}{\partial \boldsymbol{\beta}}=-\frac{2}{n}\boldsymbol{X}^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})+\lambda sgn(\boldsymbol{\beta})=0,

and reordering we have


\boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}+\lambda sgn(\boldsymbol{\beta})=\boldsymbol{X}^T\boldsymbol{y}.

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

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)


C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2,

and minimizing we have that


\hat{\beta}_i^{\mathrm{OLS}} = y_i.

Ridge Regression

For Ridge regression our cost function is


C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\beta_i^2,

and minimizing we have that


\hat{\beta}_i^{\mathrm{Ridge}} = \frac{y_i}{1+\lambda}.

Lasso Regression

For Lasso regression our cost function is


C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\vert\beta_i\vert=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\sqrt{\beta_i^2},

and minimizing we have that


-2\sum_{i=0}^{p-1}(y_i-\beta_i)+\lambda \sum_{i=0}^{p-1}\frac{(\beta_i)}{\vert\beta_i\vert}=0,
Warning:
Output truncated. This notebook contains too many cells to display efficiently.