diff --git a/doc/pub/week35/html/._week35-bs000.html b/doc/pub/week35/html/._week35-bs000.html index a463d20ef..3b671f811 100644 --- a/doc/pub/week35/html/._week35-bs000.html +++ b/doc/pub/week35/html/._week35-bs000.html @@ -38,11 +38,11 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Why Linear Regression (aka Ordinary Least Squares and family), ' - 'repeat from last week', + ('For exercise sessions: Why Linear Regression (aka Ordinary ' + 'Least Squares and family), repeat from last week', 2, None, - 'why-linear-regression-aka-ordinary-least-squares-and-family-repeat-from-last-week'), + 'for-exercise-sessions-why-linear-regression-aka-ordinary-least-squares-and-family-repeat-from-last-week'), ('The equations for ordinary least squares', 2, None, @@ -144,11 +144,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'linear-regression-code-intercept-handling-first'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Monday, August 26', 2, None, @@ -284,7 +279,7 @@ MathJax.Hub.Config({
@@ -410,7 +403,7 @@ MathJax.Hub.Config({@@ -400,7 +395,7 @@ MathJax.Hub.Config({
-
We need first a reminder from last week about linear regression.
@@ -404,7 +397,7 @@ Similarly, Mehta et al
- -
The Boston housing -data set was originally a part of UCI Machine Learning Repository -and has been removed now. The data set is now included in Scikit-Learn's -library. There are 506 samples and 13 feature (predictor) variables -in this data set. The objective is to predict the value of prices of -the house using the features (predictors) listed here. -
- -The features/predictors are
-diff --git a/doc/pub/week35/html/._week35-bs040.html b/doc/pub/week35/html/._week35-bs040.html index 79084da05..8619d07cd 100644 --- a/doc/pub/week35/html/._week35-bs040.html +++ b/doc/pub/week35/html/._week35-bs040.html @@ -38,11 +38,11 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Why Linear Regression (aka Ordinary Least Squares and family), ' - 'repeat from last week', + ('For exercise sessions: Why Linear Regression (aka Ordinary ' + 'Least Squares and family), repeat from last week', 2, None, - 'why-linear-regression-aka-ordinary-least-squares-and-family-repeat-from-last-week'), + 'for-exercise-sessions-why-linear-regression-aka-ordinary-least-squares-and-family-repeat-from-last-week'), ('The equations for ordinary least squares', 2, None, @@ -144,11 +144,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'linear-regression-code-intercept-handling-first'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Monday, August 26', 2, None, @@ -284,7 +279,7 @@ MathJax.Hub.Config({ @@ -367,346 +360,37 @@ MathJax.Hub.Config({
-
We start by importing the libraries
+import numpy as np
-import matplotlib.pyplot as plt
+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).
-import pandas as pd
-import seaborn as sns
-
-We have shown that in ordinary least squares the optimal parameters \( \beta \) are given by
-and load the Boston Housing DataSet from Scikit-Learn
+$$ +\hat{\boldsymbol{\beta}} = \left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +$$ +The hat over \( \boldsymbol{\beta} \) means we have the optimal parameters after minimization of the cost function.
- -from sklearn.datasets import load_boston
+This means that our best model is defined as
-boston_dataset = load_boston()
+$$
+\tilde{\boldsymbol{y}}=\boldsymbol{X}\hat{\boldsymbol{\beta}} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
+$$
-# boston_dataset is a dictionary
-# let's check what it contains
-boston_dataset.keys()
-
-We now define a matrix
+$$ +\boldsymbol{A}=\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T. +$$ -Then we invoke Pandas
- - -boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)
-boston.head()
-boston['MEDV'] = boston_dataset.target
-
-and preprocess the data
- - -# check for missing values in all the columns
-boston.isnull().sum()
-
-We can then visualize the data
- - -# set the size of the figure
-sns.set(rc={'figure.figsize':(11.7,8.27)})
-
-# plot a histogram showing the distribution of the target values
-sns.distplot(boston['MEDV'], bins=30)
-plt.show()
-
-It is now useful to look at the correlation matrix
- - -# compute the pair wise correlation for all columns
-correlation_matrix = boston.corr().round(2)
-# use the heatmap function from seaborn to plot the correlation matrix
-# annot = True to print the values inside the square
-sns.heatmap(data=correlation_matrix, annot=True)
-
-From the above coorelation plot we can see that MEDV is strongly correlated to LSTAT and RM. We see also that RAD and TAX are stronly correlated, but we don't include this in our features together to avoid multi-colinearity
- - - -plt.figure(figsize=(20, 5))
-
-features = ['LSTAT', 'RM']
-target = boston['MEDV']
-
-for i, col in enumerate(features):
- plt.subplot(1, len(features) , i+1)
- x = boston[col]
- y = target
- plt.scatter(x, y, marker='o')
- plt.title(col)
- plt.xlabel(col)
- plt.ylabel('MEDV')
-
-Now we start training our model
- - -X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])
-Y = boston['MEDV']
-
-We split the data into training and test sets
- - - -from sklearn.model_selection import train_test_split
-
-# splits the training and test data set in 80% : 20%
-# assign random_state to any value.This ensures consistency.
-X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=5)
-print(X_train.shape)
-print(X_test.shape)
-print(Y_train.shape)
-print(Y_test.shape)
-
-Then we use the linear regression functionality from Scikit-Learn
- - -from sklearn.linear_model import LinearRegression
-from sklearn.metrics import mean_squared_error, r2_score
-
-lin_model = LinearRegression()
-lin_model.fit(X_train, Y_train)
-
-# model evaluation for training set
-
-y_train_predict = lin_model.predict(X_train)
-rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict)))
-r2 = r2_score(Y_train, y_train_predict)
-
-print("The model performance for training set")
-print("--------------------------------------")
-print('RMSE is {}'.format(rmse))
-print('R2 score is {}'.format(r2))
-print("\n")
-
-# model evaluation for testing set
-
-y_test_predict = lin_model.predict(X_test)
-# root mean square error of the model
-rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict)))
-
-# r-squared score of the model
-r2 = r2_score(Y_test, y_test_predict)
-
-print("The model performance for testing set")
-print("--------------------------------------")
-print('RMSE is {}'.format(rmse))
-print('R2 score is {}'.format(r2))
-
-# plotting the y_test vs y_pred
-# ideally should have been a straight line
-plt.scatter(Y_test, y_test_predict)
-plt.show()
-
-We can rewrite
+$$ +\tilde{\boldsymbol{y}}=\boldsymbol{X}\hat{\boldsymbol{\beta}} = \boldsymbol{A}\boldsymbol{y}. +$$ +The matrix \( \boldsymbol{A} \) has the important property that \( \boldsymbol{A}^2=\boldsymbol{A} \). This is the definition of a projection matrix. +We can then interpret our optimal model \( \tilde{\boldsymbol{y}} \) as being represented by an orthogonal projection of \( \boldsymbol{y} \) onto a space defined by the column vectors of \( \boldsymbol{X} \). In our case here the matrix \( \boldsymbol{A} \) is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix. +
@@ -733,7 +417,7 @@ plt.show()
-
We have defined the residual error as
+$$ +\boldsymbol{\epsilon}=\boldsymbol{y}-\tilde{\boldsymbol{y}}=\left[\boldsymbol{I}-\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\right]\boldsymbol{y}. +$$ + +The residual errors are then the projections of \( \boldsymbol{y} \) onto the orthogonal component of the space defined by the column vectors of \( \boldsymbol{X} \).
@@ -394,7 +394,7 @@ MathJax.Hub.Config({
-
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 \( \beta \) are given by
+If the matrix \( \boldsymbol{X} \) is an orthogonal (or unitary in case of complex values) matrix, we have
$$ -\hat{\boldsymbol{\beta}} = \left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{X}\boldsymbol{X}^T = \boldsymbol{I}. $$ -The hat over \( \boldsymbol{\beta} \) means we have the optimal parameters after minimization of the cost function.
- -This means that our best model is defined as
- +In this case the matrix \( \boldsymbol{A} \) becomes
$$ -\tilde{\boldsymbol{y}}=\boldsymbol{X}\hat{\boldsymbol{\beta}} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +\boldsymbol{A}=\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T)=\boldsymbol{I}, $$ -We now define a matrix
+and we have the obvious case
$$ -\boldsymbol{A}=\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T. +\boldsymbol{\epsilon}=\boldsymbol{y}-\tilde{\boldsymbol{y}}=0. $$ -We can rewrite
-$$ -\tilde{\boldsymbol{y}}=\boldsymbol{X}\hat{\boldsymbol{\beta}} = \boldsymbol{A}\boldsymbol{y}. -$$ - -The matrix \( \boldsymbol{A} \) has the important property that \( \boldsymbol{A}^2=\boldsymbol{A} \). This is the definition of a projection matrix. -We can then interpret our optimal model \( \tilde{\boldsymbol{y}} \) as being represented by an orthogonal projection of \( \boldsymbol{y} \) onto a space defined by the column vectors of \( \boldsymbol{X} \). In our case here the matrix \( \boldsymbol{A} \) is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix. -
+This serves also as a useful test of our codes.
@@ -424,7 +405,7 @@ We can then interpret our optimal model \( \tilde{\boldsymbol{y}} \) as being re
-
We have defined the residual error as
-$$ -\boldsymbol{\epsilon}=\boldsymbol{y}-\tilde{\boldsymbol{y}}=\left[\boldsymbol{I}-\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\right]\boldsymbol{y}. -$$ +The 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. +
+ +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. +
+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} \).
@@ -401,7 +429,7 @@ $$
-
If the matrix \( \boldsymbol{X} \) is an orthogonal (or unitary in case of complex values) matrix, we have
+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 +
$$ -\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{X}\boldsymbol{X}^T = \boldsymbol{I}. +\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*} $$ -In this case the matrix \( \boldsymbol{A} \) becomes
+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 +
$$ -\boldsymbol{A}=\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T)=\boldsymbol{I}, +\begin{align*} +\boldsymbol{X} & = \left[ +\begin{array}{rr} +1 & -1 +\\ +1 & -1 +\end{array} \right]. +\end{align*} $$ -and we have the obvious case
-$$ -\boldsymbol{\epsilon}=\boldsymbol{y}-\tilde{\boldsymbol{y}}=0. -$$ - -This serves also as a useful test of our codes.
+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. +
@@ -412,7 +434,7 @@ $$
-
If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem
+$$ +\begin{align} +\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y}, +\tag{1} +\end{align} +$$ -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. +
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) \( \beta_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 \( \beta_i \) cannot be estimated.
-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. -
- -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. -
-A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change
+$$ +\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I}, +$$ +where \( \boldsymbol{I} \) is the identity matrix. When we discuss Ridge regression this is actually what we end up evaluating. The parameter \( \lambda \) is called a hyperparameter. More about this later.
@@ -436,7 +409,7 @@ reduced to the statistically relevant features.
-
One of the typical problems we encounter with linear regression, in particular -when the matrix \( \boldsymbol{X} \) (our so-called design matrix) is high-dimensional, -are problems with near singular or singular matrices. The column vectors of \( \boldsymbol{X} \) -may be linearly dependent, normally referred to as super-collinearity. -This means that the matrix may be rank deficient and it is basically impossible to -to model the data using linear regression. As an example, consider the matrix -
-$$ -\begin{align*} -\mathbf{X} & = \left[ -\begin{array}{rrr} -1 & -1 & 2 -\\ -1 & 0 & 1 -\\ -1 & 2 & -1 -\\ -1 & 1 & 0 -\end{array} \right] -\end{align*} -$$ - -The columns of \( \boldsymbol{X} \) are linearly dependent. We see this easily since the -the first column is the row-wise sum of the other two columns. The rank (more correct, -the column rank) of a matrix is the dimension of the space spanned by the -column vectors. Hence, the rank of \( \mathbf{X} \) is equal to the number -of linearly independent columns. In this particular case the matrix has rank 2. +
From standard linear algebra we know that a square matrix \( \boldsymbol{X} \) can be diagonalized if and only 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
-Super-collinearity of an \( (n \times p) \)-dimensional design matrix \( \mathbf{X} \) implies -that the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this -
$$ -\begin{align*} -\boldsymbol{X} & = \left[ -\begin{array}{rr} -1 & -1 -\\ -1 & -1 -\end{array} \right]. -\end{align*} +(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n), $$ -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. +
and the eigenvalues are given by the diagonal matrix
+$$ +\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). +$$ + +The matrix \( \boldsymbol{X} \) can be written in terms of an orthogonal/unitary transformation \( \boldsymbol{U} \)
+$$ +\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, +$$ + +with \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I} \) or \( \boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I} \).
+ +Not all square matrices are diagonalizable. A matrix like the one discussed above
+$$ +\boldsymbol{X} = \begin{bmatrix} +1& -1 \\ +1& -1\\ +\end{bmatrix} +$$ + +is not diagonalizable, it is a so-called defective matrix. It is easy to see that the condition +\( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) is not fulfilled.
@@ -441,7 +421,7 @@ This is equivalent to saying that the matrix \( \boldsymbol{X} \) has at least a
-
If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem
-$$ -\begin{align} -\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y}, -\tag{1} -\end{align} -$$ - -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) \( \beta_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 \( \beta_i \) cannot be estimated. +
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
-A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change
-$$ -\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I}, +$$ +\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T $$ -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.
+As an example, the above defective matrix can be decomposed as
+ +$$ +\boldsymbol{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, +$$ + +with eigenvalues \( \sigma_1=2 \) and \( \sigma_2=0 \). +The SVD exits always! +
+ +The SVD +decomposition (singular values) gives eigenvalues +\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=p \), the +eigenvalues (singular values) are zero. +
+ +In the general case, where our design matrix \( \boldsymbol{X} \) has dimension +\( n\times p \), the matrix is thus decomposed into an \( n\times n \) +orthogonal matrix \( \boldsymbol{U} \), a \( p\times p \) orthogonal matrix \( \boldsymbol{V} \) +and a diagonal matrix \( \boldsymbol{\Sigma} \) with \( r=\mathrm{min}(n,p) \) +singular values \( \sigma_i\geq 0 \) on the main diagonal and zeros filling +the rest of the matrix. There are at most \( p \) singular values +assuming that \( n > p \). In our regression examples for the nuclear +masses and the equation of state this is indeed the case, while for +the Ising model we have \( p > n \). These are often cases that lead to +near singular or singular matrices. +
+ +The columns of \( \boldsymbol{U} \) are called the left singular vectors while the columns of \( \boldsymbol{V} \) are the right singular vectors.
@@ -416,7 +432,7 @@ $$
-
From standard linear algebra we know that a square matrix \( \boldsymbol{X} \) can be diagonalized if and only 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 +
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} \).
-$$ -(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n), -$$ +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. +
-and the eigenvalues are given by the diagonal matrix
-$$ -\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). -$$ - -The matrix \( \boldsymbol{X} \) can be written in terms of an orthogonal/unitary transformation \( \boldsymbol{U} \)
-$$ -\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, -$$ - -with \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I} \) or \( \boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I} \).
- -Not all square matrices are diagonalizable. A matrix like the one discussed above
-$$ -\boldsymbol{X} = \begin{bmatrix} -1& -1 \\ -1& -1\\ -\end{bmatrix} -$$ - -is not diagonalizable, it is a so-called defective matrix. It is easy to see that the condition -\( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) is not fulfilled. +
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.
@@ -428,7 +407,7 @@ $$
-
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 + + +
import numpy as np
+# SVD inversion
+def SVD(A):
+ ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).
+ SVD is numerically more stable than the inversion algorithms provided by
+ numpy and scipy.linalg at the cost of being slower.
+ '''
+ U, S, VT = np.linalg.svd(A,full_matrices=True)
+ print('test U')
+ print( (np.transpose(U) @ U - U @np.transpose(U)))
+ print('test VT')
+ print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))
+ print(U)
+ print(S)
+ print(VT)
+
+ D = np.zeros((len(U),len(VT)))
+ for i in range(0,len(VT)):
+ D[i,i]=S[i]
+ return U @ D @ VT
+
+
+X = np.array([ [1.0,-1.0], [1.0,-1.0]])
+#X = np.array([[1, 2], [3, 4], [5, 6]])
+
+print(X)
+C = SVD(X)
+# Print the difference between the original matrix and the SVD one
+print(C-X)
+
+The matrix \( \boldsymbol{X} \) has columns that are linearly dependent. The first +column is the row-wise sum of the other two columns. The rank of a +matrix (the column rank) is the dimension of space spanned by the +column vectors. The rank of the matrix is the number of linearly +independent columns, in this case just \( 2 \). We see this from the +singular values when running the above code. Running the standard +inversion algorithm for matrix inversion with \( \boldsymbol{X}^T\boldsymbol{X} \) results +in the program terminating due to a singular matrix.
-$$ -\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T -$$ - -As an example, the above defective matrix can be decomposed as
- -$$ -\boldsymbol{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, -$$ - -with eigenvalues \( \sigma_1=2 \) and \( \sigma_2=0 \). -The SVD exits always! -
- -The SVD -decomposition (singular values) gives eigenvalues -\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=p \), the -eigenvalues (singular values) are zero. -
- -In the general case, where our design matrix \( \boldsymbol{X} \) has dimension -\( n\times p \), the matrix is thus decomposed into an \( n\times n \) -orthogonal matrix \( \boldsymbol{U} \), a \( p\times p \) orthogonal matrix \( \boldsymbol{V} \) -and a diagonal matrix \( \boldsymbol{\Sigma} \) with \( r=\mathrm{min}(n,p) \) -singular values \( \sigma_i\geq 0 \) on the main diagonal and zeros filling -the rest of the matrix. There are at most \( p \) singular values -assuming that \( n > p \). In our regression examples for the nuclear -masses and the equation of state this is indeed the case, while for -the Ising model we have \( p > n \). These are often cases that lead to -near singular or singular matrices. -
- -The columns of \( \boldsymbol{U} \) are called the left singular vectors while the columns of \( \boldsymbol{V} \) are the right singular vectors.
-diff --git a/doc/pub/week35/html/._week35-bs050.html b/doc/pub/week35/html/._week35-bs050.html index 973ba3d53..3a252eb47 100644 --- a/doc/pub/week35/html/._week35-bs050.html +++ b/doc/pub/week35/html/._week35-bs050.html @@ -38,11 +38,11 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Why Linear Regression (aka Ordinary Least Squares and family), ' - 'repeat from last week', + ('For exercise sessions: Why Linear Regression (aka Ordinary ' + 'Least Squares and family), repeat from last week', 2, None, - 'why-linear-regression-aka-ordinary-least-squares-and-family-repeat-from-last-week'), + 'for-exercise-sessions-why-linear-regression-aka-ordinary-least-squares-and-family-repeat-from-last-week'), ('The equations for ordinary least squares', 2, None, @@ -144,11 +144,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'linear-regression-code-intercept-handling-first'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Monday, August 26', 2, None, @@ -284,7 +279,7 @@ MathJax.Hub.Config({ @@ -367,26 +360,22 @@ MathJax.Hub.Config({
-
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 \( U \), \( S \), and \( V \) matrices returned from the svd() function +cannot be multiplied directly.
-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. +
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 \( 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. +
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
@@ -414,7 +403,7 @@ In general the economy-size SVD leads to less FLOPS and still conserving the des
-
Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies.
- -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)
+Our starting point is our design matrix \( \boldsymbol{X} \) of dimension \( n\times p \)
+$$
+\boldsymbol{X}=\begin{bmatrix}
+x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\
+x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\
+x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\
+\dots & \dots & \dots & \dots \dots & \dots \\
+x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\
+x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\
+\end{bmatrix}.
+$$
- D = np.zeros((len(U),len(VT)))
- for i in range(0,len(VT)):
- D[i,i]=S[i]
- return U @ D @ VT
+We can SVD decompose our matrix as
+$$
+\boldsymbol{X}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,
+$$
+where \( \boldsymbol{U} \) is an orthogonal matrix of dimension \( n\times n \), meaning that \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{U}^T\boldsymbol{U}=\boldsymbol{I}_n \). Here \( \boldsymbol{I}_n \) is the unit matrix of dimension \( n \times n \).
-X = np.array([ [1.0,-1.0], [1.0,-1.0]])
-#X = np.array([[1, 2], [3, 4], [5, 6]])
+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 \).
-print(X)
-C = SVD(X)
-# Print the difference between the original matrix and the SVD one
-print(C-X)
-
-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
-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. -
+$$ +\sigma_0 > \sigma_1 > \sigma_2 > \dots > \sigma_{p-1} > 0. +$$ + +All values beyond \( p-1 \) are all zero.
@@ -455,7 +418,7 @@ in the program terminating due to a singular matrix.
-
The \( U \), \( S \), and \( V \) matrices returned from the svd() function -cannot be multiplied directly. -
+As an example, consider the following \( 3\times 2 \) example for the matrix \( \boldsymbol{\Sigma} \)
-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. -
+$$ +\boldsymbol{\Sigma}= +\begin{bmatrix} +2& 0 \\ +0 & 1 \\ +0 & 0 \\ +\end{bmatrix} +$$ -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 +
The singular values are \( \sigma_0=2 \) and \( \sigma_1=1 \). It is common to rewrite the matrix \( \boldsymbol{\Sigma} \) as
+ +$$ +\boldsymbol{\Sigma}= +\begin{bmatrix} +\boldsymbol{\tilde{\Sigma}}\\ +\boldsymbol{0}\\ +\end{bmatrix}, +$$ + +where
+$$ +\boldsymbol{\tilde{\Sigma}}= +\begin{bmatrix} +2& 0 \\ +0 & 1 \\ +\end{bmatrix}, +$$ + +contains only the singular values. Note also (and we will use this below) that
+ +$$ +\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}= +\begin{bmatrix} +4& 0 \\ +0 & 1 \\ +\end{bmatrix}, +$$ + +which is a \( 2\times 2 \) matrix while
+$$ +\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T= +\begin{bmatrix} +4& 0 & 0\\ +0 & 1 & 0\\ +0 & 0 & 0\\ +\end{bmatrix}, +$$ + +is a \( 3\times 3 \) matrix. The last row and column of this last matrix +contain only zeros. This will have important consequences for our SVD +decomposition of the design matrix.
@@ -410,7 +442,7 @@ example
-
Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies.
- -Our starting point is our design matrix \( \boldsymbol{X} \) of dimension \( n\times p \)
-$$ -\boldsymbol{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}. -$$ - -We can SVD decompose our matrix as
-$$ -\boldsymbol{X}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, -$$ - -where \( \boldsymbol{U} \) is an orthogonal matrix of dimension \( n\times n \), meaning that \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{U}^T\boldsymbol{U}=\boldsymbol{I}_n \). Here \( \boldsymbol{I}_n \) is the unit matrix of dimension \( n \times n \).
- -Similarly, \( \boldsymbol{V} \) is an orthogonal matrix of dimension \( p\times p \), meaning that \( \boldsymbol{V}\boldsymbol{V}^T=\boldsymbol{V}^T\boldsymbol{V}=\boldsymbol{I}_p \). Here \( \boldsymbol{I}_n \) is the unit matrix of dimension \( p \times p \).
- -Finally \( \boldsymbol{\Sigma} \) contains the singular values \( \sigma_i \). This matrix has dimension \( n\times p \) and the singular values \( \sigma_i \) are all positive. The non-zero values are ordered in descending order, that is
+The matrix that may cause problems for us is \( \boldsymbol{X}^T\boldsymbol{X} \). Using the SVD we can rewrite this matrix as
$$ -\sigma_0 > \sigma_1 > \sigma_2 > \dots > \sigma_{p-1} > 0. +\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, $$ -All values beyond \( p-1 \) are all zero.
+and using the orthogonality of the matrix \( \boldsymbol{U} \) we have
+ +$$ +\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T. +$$ + +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
+ +$$ +\tilde{y}_{\mathrm{OLS}}=\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}, +$$ + +and using our SVD decomposition of \( \boldsymbol{X} \) we have
+ +$$ +\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}, +$$ + +which gives us, using the orthogonality of the matrix \( \boldsymbol{V} \),
+ +$$ +\tilde{y}_{\mathrm{OLS}}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_i\boldsymbol{u}^T_i\boldsymbol{y}, +$$ + +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} \). This can already be +when we multiply the matrices \( \boldsymbol{\Sigma}^T\boldsymbol{U}^T \). +
@@ -425,7 +428,7 @@ $$
-
As an example, consider the following \( 3\times 2 \) example for the matrix \( \boldsymbol{\Sigma} \)
+Let us study again \( \boldsymbol{X}^T\boldsymbol{X} \) in terms of our SVD,
$$ -\boldsymbol{\Sigma}= -\begin{bmatrix} -2& 0 \\ -0 & 1 \\ -0 & 0 \\ -\end{bmatrix} +\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. $$ -The singular values are \( \sigma_0=2 \) and \( \sigma_1=1 \). It is common to rewrite the matrix \( \boldsymbol{\Sigma} \) as
- +If we now multiply from the right with \( \boldsymbol{V} \) (using the orthogonality of \( \boldsymbol{V} \)) we get
$$ -\boldsymbol{\Sigma}= -\begin{bmatrix} -\boldsymbol{\tilde{\Sigma}}\\ -\boldsymbol{0}\\ -\end{bmatrix}, +\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{V}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}. $$ -where
+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 +
$$ -\boldsymbol{\tilde{\Sigma}}= -\begin{bmatrix} -2& 0 \\ -0 & 1 \\ -\end{bmatrix}, +\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{v}_i=\boldsymbol{v}_i\sigma_i^2. $$ -contains only the singular values. Note also (and we will use this below) that
- +Similarly, if we use the SVD decomposition for the matrix \( \boldsymbol{X}\boldsymbol{X}^T \), we have
$$ -\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}= -\begin{bmatrix} -4& 0 \\ -0 & 1 \\ -\end{bmatrix}, +\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. $$ -which is a \( 2\times 2 \) matrix while
+If we now multiply from the right with \( \boldsymbol{U} \) (using the orthogonality of \( \boldsymbol{U} \)) we get
$$ -\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T= -\begin{bmatrix} -4& 0 & 0\\ -0 & 1 & 0\\ -0 & 0 & 0\\ -\end{bmatrix}, +\left(\boldsymbol{X}\boldsymbol{X}^T\right)\boldsymbol{U}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T. $$ -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. +
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 +
+$$ +\left(\boldsymbol{X}\boldsymbol{X}^T\right)\boldsymbol{u}_i=\boldsymbol{u}_i\sigma_i^2. +$$ + +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.
@@ -449,7 +433,7 @@ decomposition of the design matrix.
-
The matrix that may cause problems for us is \( \boldsymbol{X}^T\boldsymbol{X} \). Using the SVD we can rewrite this matrix as
+Before we move on to a discussion of Ridge and Lasso regression, we want to show an important example of the above.
+ +We have already noted that the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) in ordinary +least squares is proportional to the second derivative of the cost +function, that is we have +
$$ -\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, +\frac{\partial^2 C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}\partial \boldsymbol{\beta}^T} =\frac{2}{n}\boldsymbol{X}^T\boldsymbol{X}. $$ -and using the orthogonality of the matrix \( \boldsymbol{U} \) we have
+This quantity defines was what is called the Hessian matrix (the second derivative of a function we want to optimize).
+ +The Hessian matrix plays an important role and is defined in this course as
$$ -\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T. +\boldsymbol{H}=\boldsymbol{X}^T\boldsymbol{X}. $$ -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
- -$$ -\tilde{y}_{\mathrm{OLS}}=\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}, -$$ - -and using our SVD decomposition of \( \boldsymbol{X} \) we have
- -$$ -\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}, -$$ - -which gives us, using the orthogonality of the matrix \( \boldsymbol{V} \),
- -$$ -\tilde{y}_{\mathrm{OLS}}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_i\boldsymbol{u}^T_i\boldsymbol{y}, -$$ - -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} \). This can already be -when we multiply the matrices \( \boldsymbol{\Sigma}^T\boldsymbol{U}^T \). +
The Hessian matrix for ordinary least squares is also proportional to +the covariance matrix. This means also that we can use the SVD to find +the eigenvalues of the covariance matrix and the Hessian matrix in +terms of the singular values. Let us develop these arguments, as they will play an important role in our machine learning studies.
@@ -435,7 +412,7 @@ when we multiply the matrices \( \boldsymbol{\Sigma}^T\boldsymbol{U}^T \).
-
Let us study again \( \boldsymbol{X}^T\boldsymbol{X} \) in terms of our SVD,
-$$ -\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. -$$ - -If we now multiply 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}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}. -$$ - -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. -$$ - -Similarly, if we use the SVD decomposition for the matrix \( \boldsymbol{X}\boldsymbol{X}^T \), we have
-$$ -\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. -$$ - -If we now multiply from the right with \( \boldsymbol{U} \) (using the orthogonality of \( \boldsymbol{U} \)) we get
-$$ -\left(\boldsymbol{X}\boldsymbol{X}^T\right)\boldsymbol{U}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T. -$$ - -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 -
-$$ -\left(\boldsymbol{X}\boldsymbol{X}^T\right)\boldsymbol{u}_i=\boldsymbol{u}_i\sigma_i^2. -$$ - -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). +
Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about +the definition of the covariance and the correlation function. These are quantities that play a central role in machine learning methods.
-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. +
Suppose we have defined two vectors +\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as +
+$$ +\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\ + \end{bmatrix}, +$$ + +where for example
+$$ +\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). +$$ + +With this definition and recalling that the variance is defined as
+$$ +\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, +$$ + +we can rewrite the covariance matrix as
+$$ +\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\ + \end{bmatrix}. +$$ + +Note: we have used \( 1/n \) in the above definitions of the sample variance and covariance. We assume then that we can calculate the exact mean value. +What you will find in essentially all statistics texts are equations +with a factor \( 1/(n-1) \). This is called Bessel's correction. This +method corrects the bias in the estimation of the population variance +and covariance. It also partially corrects the bias in the estimation +of the population standard deviation. If you use a library like +Scikit-Learn or nunmpy's function to calculate the covariance, this +quantity will be computed with a factor \( 1/(n-1) \).
@@ -440,7 +427,7 @@ for the definition of for example the covariance matrix and its relation to the
-
Before we move on to a discussion of Ridge and Lasso regression, we want to show an important example of the above.
- -We have already noted that the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) in ordinary -least squares is proportional to the second derivative of the cost -function, that is we have +
The covariance takes values between zero and infinity and may thus +lead to problems with loss of numerical precision for particularly +large values. It is common to scale the covariance matrix by +introducing instead the correlation matrix defined via the so-called +correlation function
$$ -\frac{\partial^2 C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}\partial \boldsymbol{\beta}^T} =\frac{2}{n}\boldsymbol{X}^T\boldsymbol{X}. +\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. $$ -This quantity defines was what is called the Hessian matrix (the second derivative of a function we want to optimize).
- -The Hessian matrix plays an important role and is defined in this course as
- -$$ -\boldsymbol{H}=\boldsymbol{X}^T\boldsymbol{X}. -$$ - -The Hessian matrix for ordinary least squares is also proportional to -the covariance matrix. This means also that we can use the SVD to find -the eigenvalues of the covariance matrix and the Hessian matrix in -terms of the singular values. Let us develop these arguments, as they will play an important role in our machine learning studies. +
The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] +\in [-1,1] \). This avoids eventual problems with too large values. We +can then define the correlation matrix for the two vectors \( \boldsymbol{x} \) +and \( \boldsymbol{y} \) as
+$$ +\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\ + \end{bmatrix}, +$$ + +In the above example this is the function we constructed using pandas.
+
-
Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about -the definition of the covariance and the correlation function. These are quantities that play a central role in machine learning methods. +
In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression +we defined the design/feature matrix \( \boldsymbol{X} \) as
-Suppose we have defined two vectors -\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as +$$ +\boldsymbol{X}=\begin{bmatrix} +x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ +x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ +x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ +\dots & \dots & \dots & \dots \dots & \dots \\ +x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ +x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ +\end{bmatrix}, +$$ + +
with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the +entries \( n \) being the row elements. +We can rewrite the design/feature matrix in terms of its column vectors as
$$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\ - \end{bmatrix}, +\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix}, $$ -where for example
+with a given vector
$$ -\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). +\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. $$ -With this definition and recalling that the variance is defined as
-$$ -\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, -$$ - -we can rewrite the covariance matrix as
-$$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\ - \end{bmatrix}. -$$ - -Note: we have used \( 1/n \) in the above definitions of the sample variance and covariance. We assume then that we can calculate the exact mean value. -What you will find in essentially all statistics texts are equations -with a factor \( 1/(n-1) \). This is called Bessel's correction. This -method corrects the bias in the estimation of the population variance -and covariance. It also partially corrects the bias in the estimation -of the population standard deviation. If you use a library like -Scikit-Learn or nunmpy's function to calculate the covariance, this -quantity will be computed with a factor \( 1/(n-1) \). +
With these definitions, we can now rewrite our \( 2\times 2 \) +correlation/covariance matrix in terms of a moe general design/feature +matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \) +covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \)
+$$ +\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix} +\mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ +\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ +\mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_1] & \mathrm{var}[\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & \mathrm{var}[\boldsymbol{x}_{p-1}]\\ +\end{bmatrix}, +$$ + +and the correlation matrix
+$$ +\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix} +1 & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ +\mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_0] & 1 & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ +\mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & 1\\ +\end{bmatrix}, +$$ + +diff --git a/doc/pub/week35/html/._week35-bs059.html b/doc/pub/week35/html/._week35-bs059.html index e22920fc3..c471e93ce 100644 --- a/doc/pub/week35/html/._week35-bs059.html +++ b/doc/pub/week35/html/._week35-bs059.html @@ -38,11 +38,11 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Why Linear Regression (aka Ordinary Least Squares and family), ' - 'repeat from last week', + ('For exercise sessions: Why Linear Regression (aka Ordinary ' + 'Least Squares and family), repeat from last week', 2, None, - 'why-linear-regression-aka-ordinary-least-squares-and-family-repeat-from-last-week'), + 'for-exercise-sessions-why-linear-regression-aka-ordinary-least-squares-and-family-repeat-from-last-week'), ('The equations for ordinary least squares', 2, None, @@ -144,11 +144,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'linear-regression-code-intercept-handling-first'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Monday, August 26', 2, None, @@ -284,7 +279,7 @@ MathJax.Hub.Config({ @@ -367,32 +360,61 @@ MathJax.Hub.Config({
-
The covariance takes values between zero and infinity and may thus -lead to problems with loss of numerical precision for particularly -large values. It is common to scale the covariance matrix by -introducing instead the correlation matrix defined via the so-called -correlation function +
The Numpy function np.cov calculates the covariance elements using +the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have +the exact mean values. The following simple function uses the +np.vstack function which takes each vector of dimension \( 1\times n \) +and produces a \( 2\times n \) matrix \( \boldsymbol{W} \)
+Note that this assumes you have the features as the rows, and the inputs as columns, that is
$$ -\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. -$$ - -The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] -\in [-1,1] \). This avoids eventual problems with too large values. We -can then define the correlation matrix for the two vectors \( \boldsymbol{x} \) -and \( \boldsymbol{y} \) as -
- -$$ -\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\ +\boldsymbol{W} = \begin{bmatrix} x_0 & x_1 & x_2 & \dots & x_{n-2} & x_{n-1} \\ + y_0 & y_1 & y_2 & \dots & y_{n-2} & y_{n-1} \\ \end{bmatrix}, $$ -In the above example this is the function we constructed using pandas.
+which in turn is converted into into the \( 2\times 2 \) covariance matrix +\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate +the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy +function np.mean(x). We can also extract the eigenvalues of the +covariance matrix through the np.linalg.eig() function. +
+ + + +# Importing various packages
+import numpy as np
+n = 100
+x = np.random.normal(size=n)
+print(np.mean(x))
+y = 4+3*x+np.random.normal(size=n)
+print(np.mean(y))
+W = np.vstack((x, y))
+C = np.cov(W)
+print(C)
+
+@@ -419,7 +441,7 @@ $$
-
In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression -we defined the design/feature matrix \( \boldsymbol{X} \) as +
The previous example can be converted into the correlation matrix by +simply scaling the matrix elements with the variances. We should also +subtract the mean values for each column. This leads to the following +code which sets up the correlations matrix for the previous example in +a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors).
-$$ -\boldsymbol{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}, -$$ -with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the -entries \( n \) being the row elements. -We can rewrite the design/feature matrix in terms of its column vectors as -
-$$ -\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix}, -$$ + +import numpy as np
+n = 100
+# define two vectors
+x = np.random.random(size=n)
+y = 4+3*x+np.random.normal(size=n)
+#scaling the x and y vectors
+x = x - np.mean(x)
+y = y - np.mean(y)
+variance_x = np.sum(x@x)/n
+variance_y = np.sum(y@y)/n
+print(variance_x)
+print(variance_y)
+cov_xy = np.sum(x@y)/n
+cov_xx = np.sum(x@x)/n
+cov_yy = np.sum(y@y)/n
+C = np.zeros((2,2))
+C[0,0]= cov_xx/variance_x
+C[1,1]= cov_yy/variance_y
+C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
+C[1,0]= C[0,1]
+print(C)
+
+with a given vector
-$$ -\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. -$$ - -With these definitions, we can now rewrite our \( 2\times 2 \) -correlation/covariance matrix in terms of a moe general design/feature -matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \) -covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \) +
We see that the matrix elements along the diagonal are one as they +should be and that the matrix is symmetric. Furthermore, diagonalizing +this matrix we easily see that it is a positive definite matrix.
-$$ -\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix} -\mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ -\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ -\mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_1] & \mathrm{var}[\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & \mathrm{var}[\boldsymbol{x}_{p-1}]\\ -\end{bmatrix}, -$$ - -and the correlation matrix
-$$ -\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix} -1 & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ -\mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_0] & 1 & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ -\mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & 1\\ -\end{bmatrix}, -$$ - +The above procedure with numpy can be made more compact if we use pandas.
@@ -452,7 +444,7 @@ $$
-
The Numpy function np.cov calculates the covariance elements using -the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have -the exact mean values. The following simple function uses the -np.vstack function which takes each vector of dimension \( 1\times n \) -and produces a \( 2\times n \) matrix \( \boldsymbol{W} \) -
- -Note that this assumes you have the features as the rows, and the inputs as columns, that is
-$$ -\boldsymbol{W} = \begin{bmatrix} x_0 & x_1 & x_2 & \dots & x_{n-2} & x_{n-1} \\ - y_0 & y_1 & y_2 & \dots & y_{n-2} & y_{n-1} \\ - \end{bmatrix}, -$$ - -which in turn is converted into into the \( 2\times 2 \) covariance matrix -\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate -the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy -function np.mean(x). We can also extract the eigenvalues of the -covariance matrix through the np.linalg.eig() function. -
+We whow here how we can set up the correlation matrix using pandas, as done in this simple code
# Importing various packages
-import numpy as np
-n = 100
+ import numpy as np
+import pandas as pd
+n = 10
x = np.random.normal(size=n)
-print(np.mean(x))
+x = x - np.mean(x)
y = 4+3*x+np.random.normal(size=n)
-print(np.mean(y))
-W = np.vstack((x, y))
-C = np.cov(W)
-print(C)
+y = y - np.mean(y)
+# Note that we transpose the matrix in order to stay with our ordering n x p
+X = (np.vstack((x, y))).T
+print(X)
+Xpd = pd.DataFrame(X)
+print(Xpd)
+correlation_matrix = Xpd.corr()
+print(correlation_matrix)
We expand this model to the Franke function discussed above.
@@ -448,7 +426,7 @@ C = np.c
-
The previous example can be converted into the correlation matrix by -simply scaling the matrix elements with the variances. We should also -subtract the mean values for each column. This leads to the following -code which sets up the correlations matrix for the previous example in -a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors). -
+import numpy as np
-n = 100
-# define two vectors
-x = np.random.random(size=n)
-y = 4+3*x+np.random.normal(size=n)
-#scaling the x and y vectors
-x = x - np.mean(x)
-y = y - np.mean(y)
-variance_x = np.sum(x@x)/n
-variance_y = np.sum(y@y)/n
-print(variance_x)
-print(variance_y)
-cov_xy = np.sum(x@y)/n
-cov_xx = np.sum(x@x)/n
-cov_yy = np.sum(y@y)/n
-C = np.zeros((2,2))
-C[0,0]= cov_xx/variance_x
-C[1,1]= cov_yy/variance_y
-C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
-C[1,0]= C[0,1]
-print(C)
+ # Common imports
+import numpy as np
+import pandas as pd
+
+
+def FrankeFunction(x,y):
+ term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
+ term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
+ term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
+ term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
+ return term1 + term2 + term3 + term4
+
+
+def create_X(x, y, n ):
+ if len(x.shape) > 1:
+ x = np.ravel(x)
+ y = np.ravel(y)
+
+ N = len(x)
+ l = int((n+1)*(n+2)/2) # Number of elements in beta
+ X = np.ones((N,l))
+
+ for i in range(1,n+1):
+ q = int((i)*(i+1)/2)
+ for k in range(i+1):
+ X[:,q+k] = (x**(i-k))*(y**k)
+
+ return X
+
+
+# Making meshgrid of datapoints and compute Franke's function
+n = 4
+N = 100
+x = np.sort(np.random.uniform(0, 1, N))
+y = np.sort(np.random.uniform(0, 1, N))
+z = FrankeFunction(x, y)
+X = create_X(x, y, n=n)
+
+Xpd = pd.DataFrame(X)
+# subtract the mean values and set up the covariance matrix
+Xpd = Xpd - Xpd.mean()
+covariance_matrix = Xpd.cov()
+print(covariance_matrix)
We see that the matrix elements along the diagonal are one as they -should be and that the matrix is symmetric. Furthermore, diagonalizing -this matrix we easily see that it is a positive definite matrix. +
We note here that the covariance is zero for the first rows and +columns since all matrix elements in the design matrix were set to one +(we are fitting the function in terms of a polynomial of degree \( n \)).
-The above procedure with numpy can be made more compact if we use pandas.
+This means that the variance for these elements will be zero and will +cause problems when we set up the correlation matrix. We can simply +drop these elements and construct a correlation +matrix without these elements. +
@@ -450,8 +462,6 @@ this matrix we easily see that it is a positive definite matrix.
-
We whow here how we can set up the correlation matrix using pandas, as done in this simple code
+We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as
+$$ +\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}]. +$$ - -import numpy as np
-import pandas as pd
-n = 10
-x = np.random.normal(size=n)
-x = x - np.mean(x)
-y = 4+3*x+np.random.normal(size=n)
-y = y - np.mean(y)
-# Note that we transpose the matrix in order to stay with our ordering n x p
-X = (np.vstack((x, y))).T
-print(X)
-Xpd = pd.DataFrame(X)
-print(Xpd)
-correlation_matrix = Xpd.corr()
-print(correlation_matrix)
-
-To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \)
+$$ +\boldsymbol{X}=\begin{bmatrix} +x_{00} & x_{01}\\ +x_{10} & x_{11}\\ +\end{bmatrix}=\begin{bmatrix} +\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\ +\end{bmatrix}. +$$ -We expand this model to the Franke function discussed above.
+If we then compute the expectation value (note the \( 1/n \) factor instead of \( 1/(n-1) \))
+$$ +\mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}=\frac{1}{n}\begin{bmatrix} +x_{00}^2+x_{10}^2 & x_{00}x_{01}+x_{10}x_{11}\\ +x_{01}x_{00}+x_{11}x_{10} & x_{01}^2+x_{11}^2\\ +\end{bmatrix}, +$$ + +which is just
+$$ +\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]=\begin{bmatrix} \mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] \\ + \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\ + \end{bmatrix}, +$$ + +where we wrote $$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ to indicate that this is the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \).
+ +It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \).
@@ -431,9 +419,6 @@ correlation_matrix = Xpd70
We saw earlier that Since the matrices here have dimension \( p\times p \), with \( p \) corresponding to the singular values, we defined earlier the 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 meaning we can write Multiplying from the right with \( \boldsymbol{V} \) (using the orthogonality of \( \boldsymbol{V} \)) we get We note here that the covariance is zero for the first rows and
-columns since all matrix elements in the design matrix were set to one
-(we are fitting the function in terms of a polynomial of degree \( n \)).
- This means that the variance for these elements will be zero and will
-cause problems when we set up the correlation matrix. We can simply
-drop these elements and construct a correlation
-matrix without these elements.
-
@@ -467,8 +416,6 @@ matrix without these elements.
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
+ We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 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. Note also that the Hessian matrix we are discussing here is from a cost function defined by the mean squared error only.
+ If we now recall the definition of the covariance matrix (not using
+Bessel's correction) we have
+ If we then compute the expectation value (note the \( 1/n \) factor instead of \( 1/(n-1) \)) which is just where we wrote $$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ to indicate that this is the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \). It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). 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} \).
+
@@ -424,8 +421,6 @@ $$
We saw earlier that Since the matrices here have dimension \( p\times p \), with \( p \) corresponding to the singular values, we defined earlier the 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 For \( \boldsymbol{X}\boldsymbol{X}^T \) we found meaning we can write Since the matrices here have dimension \( n\times n \), we have Multiplying from the right with \( \boldsymbol{V} \) (using the orthogonality of \( \boldsymbol{V} \)) we get leading to Multiplying with \( \boldsymbol{U} \) from the right gives us the eigenvalue problem 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} \).
+
@@ -421,8 +414,6 @@ $$
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
+ 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
+ or we can state it as where we have used the definition of a norm-2 vector, that 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
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. Note also that the Hessian matrix we are discussing here is from a cost function defined by the mean squared error only.
- If we now recall the definition of the covariance matrix (not using
-Bessel's correction) we have
+ 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. By defining
we have a new optimization equation which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. Here we have defined the norm-1 as 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} \).
-
@@ -426,8 +433,6 @@ absolute value of the eigenvalues of \( \boldsymbol{X} \).
For \( \boldsymbol{X}\boldsymbol{X}^T \) we found 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 Since the matrices here have dimension \( n\times n \), 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
+ leading to with \( \boldsymbol{I} \) being a \( p\times p \) identity matrix with the constraint that Multiplying with \( \boldsymbol{U} \) from the right gives us the eigenvalue problem with \( t \) a finite positive number. If we keep the \( 1/n \) factor, the equation for the optimal \( \beta \) changes to 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} \).
+ 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{\beta} \). These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.
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} \).
+ 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
For Ridge regression this becomes with the vectors \( \boldsymbol{u}_j \) being the columns of \( \boldsymbol{U} \) from the SVD of the matrix \( \boldsymbol{X} \).
@@ -419,8 +440,6 @@ values and the column vectors of \( \boldsymbol{V} \).
Since \( \lambda \geq 0 \), it means that compared to OLS, we have 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
- or we can state it as where we have used the definition of a norm-2 vector, that 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
+ 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} \).
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. By defining
- we have a new optimization equation which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. Here we have defined the norm-1 as 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.
@@ -438,8 +394,6 @@ $$
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 For the sake of simplicity, let us assume that the design matrix is orthonormal, that is 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
- In this case the standard OLS results in with \( \boldsymbol{I} \) being a \( p\times p \) identity matrix with the constraint that and with \( t \) a finite positive number. If we keep the \( 1/n \) factor, the equation for the optimal \( \beta \) changes to 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{\beta} \). These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.
+ 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.
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
+ 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.
For Ridge regression this becomes with the vectors \( \boldsymbol{u}_j \) being the columns of \( \boldsymbol{U} \) from the SVD of the matrix \( \boldsymbol{X} \).
@@ -445,8 +406,6 @@ $$
Since \( \lambda \geq 0 \), it means that compared to OLS, we have Using the matrix-vector expression for Lasso regression, we have the following cost function 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} \).
- 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 simplicty) 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 have that the derivative of the cost function is and reordering we have We can redefine \( \lambda \) to absorb the constant \( n/2 \) and we rewrite the last equation as 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 using for example the Python package CVXOPT. We will discuss this later.
@@ -399,9 +406,6 @@ eigenvalues ordered in a descending way, that is \( \sigma_i \geq
Correlation Matrix with Pandas and the Franke function
+Linking with the SVD
+# Common imports
-import numpy as np
-import pandas as pd
+
-Rewriting the Covariance and/or Correlation Matrix
+What does it mean?
+
+Linking with the SVD
+And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
-What does it mean?
+Ridge and LASSO Regression
-And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
+Deriving the Ridge Regression Equations
-Ridge and LASSO Regression
+Interpreting the Ridge results
+
+Deriving the Ridge Regression Equations
+More interpretations
-Interpreting the Ridge results
+Deriving the Lasso Regression Equations
-
We need first a reminder from last week about linear regression.
@@ -1917,377 +1919,6 @@ regression next week.The Boston housing -data set was originally a part of UCI Machine Learning Repository -and has been removed now. The data set is now included in Scikit-Learn's -library. There are 506 samples and 13 feature (predictor) variables -in this data set. The objective is to predict the value of prices of -the house using the features (predictors) listed here. -
- -The features/predictors are
-We start by importing the libraries
- - -import numpy as np
-import matplotlib.pyplot as plt
-
-import pandas as pd
-import seaborn as sns
-
-and load the Boston Housing DataSet from Scikit-Learn
- - - -from sklearn.datasets import load_boston
-
-boston_dataset = load_boston()
-
-# boston_dataset is a dictionary
-# let's check what it contains
-boston_dataset.keys()
-
-Then we invoke Pandas
- - -boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)
-boston.head()
-boston['MEDV'] = boston_dataset.target
-
-and preprocess the data
- - -# check for missing values in all the columns
-boston.isnull().sum()
-
-We can then visualize the data
- - -# set the size of the figure
-sns.set(rc={'figure.figsize':(11.7,8.27)})
-
-# plot a histogram showing the distribution of the target values
-sns.distplot(boston['MEDV'], bins=30)
-plt.show()
-
-It is now useful to look at the correlation matrix
- - -# compute the pair wise correlation for all columns
-correlation_matrix = boston.corr().round(2)
-# use the heatmap function from seaborn to plot the correlation matrix
-# annot = True to print the values inside the square
-sns.heatmap(data=correlation_matrix, annot=True)
-
-From the above coorelation plot we can see that MEDV is strongly correlated to LSTAT and RM. We see also that RAD and TAX are stronly correlated, but we don't include this in our features together to avoid multi-colinearity
- - - -plt.figure(figsize=(20, 5))
-
-features = ['LSTAT', 'RM']
-target = boston['MEDV']
-
-for i, col in enumerate(features):
- plt.subplot(1, len(features) , i+1)
- x = boston[col]
- y = target
- plt.scatter(x, y, marker='o')
- plt.title(col)
- plt.xlabel(col)
- plt.ylabel('MEDV')
-
-Now we start training our model
- - -X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])
-Y = boston['MEDV']
-
-We split the data into training and test sets
- - - -from sklearn.model_selection import train_test_split
-
-# splits the training and test data set in 80% : 20%
-# assign random_state to any value.This ensures consistency.
-X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=5)
-print(X_train.shape)
-print(X_test.shape)
-print(Y_train.shape)
-print(Y_test.shape)
-
-Then we use the linear regression functionality from Scikit-Learn
- - -from sklearn.linear_model import LinearRegression
-from sklearn.metrics import mean_squared_error, r2_score
-
-lin_model = LinearRegression()
-lin_model.fit(X_train, Y_train)
-
-# model evaluation for training set
-
-y_train_predict = lin_model.predict(X_train)
-rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict)))
-r2 = r2_score(Y_train, y_train_predict)
-
-print("The model performance for training set")
-print("--------------------------------------")
-print('RMSE is {}'.format(rmse))
-print('R2 score is {}'.format(r2))
-print("\n")
-
-# model evaluation for testing set
-
-y_test_predict = lin_model.predict(X_test)
-# root mean square error of the model
-rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict)))
-
-# r-squared score of the model
-r2 = r2_score(Y_test, y_test_predict)
-
-print("The model performance for testing set")
-print("--------------------------------------")
-print('RMSE is {}'.format(rmse))
-print('R2 score is {}'.format(r2))
-
-# plotting the y_test vs y_pred
-# ideally should have been a straight line
-plt.scatter(Y_test, y_test_predict)
-plt.show()
-
-We need first a reminder from last week about linear regression.
@@ -1882,375 +1879,6 @@ intercept. This becomes more important when we discuss Ridge and Lasso regression next week. - -The Boston housing -data set was originally a part of UCI Machine Learning Repository -and has been removed now. The data set is now included in Scikit-Learn's -library. There are 506 samples and 13 feature (predictor) variables -in this data set. The objective is to predict the value of prices of -the house using the features (predictors) listed here. -
- -The features/predictors are
-We start by importing the libraries
- - -import numpy as np
-import matplotlib.pyplot as plt
-
-import pandas as pd
-import seaborn as sns
-
-and load the Boston Housing DataSet from Scikit-Learn
- - - -from sklearn.datasets import load_boston
-
-boston_dataset = load_boston()
-
-# boston_dataset is a dictionary
-# let's check what it contains
-boston_dataset.keys()
-
-Then we invoke Pandas
- - -boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)
-boston.head()
-boston['MEDV'] = boston_dataset.target
-
-and preprocess the data
- - -# check for missing values in all the columns
-boston.isnull().sum()
-
-We can then visualize the data
- - -# set the size of the figure
-sns.set(rc={'figure.figsize':(11.7,8.27)})
-
-# plot a histogram showing the distribution of the target values
-sns.distplot(boston['MEDV'], bins=30)
-plt.show()
-
-It is now useful to look at the correlation matrix
- - -# compute the pair wise correlation for all columns
-correlation_matrix = boston.corr().round(2)
-# use the heatmap function from seaborn to plot the correlation matrix
-# annot = True to print the values inside the square
-sns.heatmap(data=correlation_matrix, annot=True)
-
-From the above coorelation plot we can see that MEDV is strongly correlated to LSTAT and RM. We see also that RAD and TAX are stronly correlated, but we don't include this in our features together to avoid multi-colinearity
- - - -plt.figure(figsize=(20, 5))
-
-features = ['LSTAT', 'RM']
-target = boston['MEDV']
-
-for i, col in enumerate(features):
- plt.subplot(1, len(features) , i+1)
- x = boston[col]
- y = target
- plt.scatter(x, y, marker='o')
- plt.title(col)
- plt.xlabel(col)
- plt.ylabel('MEDV')
-
-Now we start training our model
- - -X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])
-Y = boston['MEDV']
-
-We split the data into training and test sets
- - - -from sklearn.model_selection import train_test_split
-
-# splits the training and test data set in 80% : 20%
-# assign random_state to any value.This ensures consistency.
-X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=5)
-print(X_train.shape)
-print(X_test.shape)
-print(Y_train.shape)
-print(Y_test.shape)
-
-Then we use the linear regression functionality from Scikit-Learn
- - -from sklearn.linear_model import LinearRegression
-from sklearn.metrics import mean_squared_error, r2_score
-
-lin_model = LinearRegression()
-lin_model.fit(X_train, Y_train)
-
-# model evaluation for training set
-
-y_train_predict = lin_model.predict(X_train)
-rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict)))
-r2 = r2_score(Y_train, y_train_predict)
-
-print("The model performance for training set")
-print("--------------------------------------")
-print('RMSE is {}'.format(rmse))
-print('R2 score is {}'.format(r2))
-print("\n")
-
-# model evaluation for testing set
-
-y_test_predict = lin_model.predict(X_test)
-# root mean square error of the model
-rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict)))
-
-# r-squared score of the model
-r2 = r2_score(Y_test, y_test_predict)
-
-print("The model performance for testing set")
-print("--------------------------------------")
-print('RMSE is {}'.format(rmse))
-print('R2 score is {}'.format(r2))
-
-# plotting the y_test vs y_pred
-# ideally should have been a straight line
-plt.scatter(Y_test, y_test_predict)
-plt.show()
-
-We need first a reminder from last week about linear regression.
@@ -1959,375 +1956,6 @@ intercept. This becomes more important when we discuss Ridge and Lasso regression next week. - -The Boston housing -data set was originally a part of UCI Machine Learning Repository -and has been removed now. The data set is now included in Scikit-Learn's -library. There are 506 samples and 13 feature (predictor) variables -in this data set. The objective is to predict the value of prices of -the house using the features (predictors) listed here. -
- -The features/predictors are
-We start by importing the libraries
- - -import numpy as np
-import matplotlib.pyplot as plt
-
-import pandas as pd
-import seaborn as sns
-
-and load the Boston Housing DataSet from Scikit-Learn
- - - -from sklearn.datasets import load_boston
-
-boston_dataset = load_boston()
-
-# boston_dataset is a dictionary
-# let's check what it contains
-boston_dataset.keys()
-
-Then we invoke Pandas
- - -boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)
-boston.head()
-boston['MEDV'] = boston_dataset.target
-
-and preprocess the data
- - -# check for missing values in all the columns
-boston.isnull().sum()
-
-We can then visualize the data
- - -# set the size of the figure
-sns.set(rc={'figure.figsize':(11.7,8.27)})
-
-# plot a histogram showing the distribution of the target values
-sns.distplot(boston['MEDV'], bins=30)
-plt.show()
-
-It is now useful to look at the correlation matrix
- - -# compute the pair wise correlation for all columns
-correlation_matrix = boston.corr().round(2)
-# use the heatmap function from seaborn to plot the correlation matrix
-# annot = True to print the values inside the square
-sns.heatmap(data=correlation_matrix, annot=True)
-
-From the above coorelation plot we can see that MEDV is strongly correlated to LSTAT and RM. We see also that RAD and TAX are stronly correlated, but we don't include this in our features together to avoid multi-colinearity
- - - -plt.figure(figsize=(20, 5))
-
-features = ['LSTAT', 'RM']
-target = boston['MEDV']
-
-for i, col in enumerate(features):
- plt.subplot(1, len(features) , i+1)
- x = boston[col]
- y = target
- plt.scatter(x, y, marker='o')
- plt.title(col)
- plt.xlabel(col)
- plt.ylabel('MEDV')
-
-Now we start training our model
- - -X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])
-Y = boston['MEDV']
-
-We split the data into training and test sets
- - - -from sklearn.model_selection import train_test_split
-
-# splits the training and test data set in 80% : 20%
-# assign random_state to any value.This ensures consistency.
-X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=5)
-print(X_train.shape)
-print(X_test.shape)
-print(Y_train.shape)
-print(Y_test.shape)
-
-Then we use the linear regression functionality from Scikit-Learn
- - -from sklearn.linear_model import LinearRegression
-from sklearn.metrics import mean_squared_error, r2_score
-
-lin_model = LinearRegression()
-lin_model.fit(X_train, Y_train)
-
-# model evaluation for training set
-
-y_train_predict = lin_model.predict(X_train)
-rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict)))
-r2 = r2_score(Y_train, y_train_predict)
-
-print("The model performance for training set")
-print("--------------------------------------")
-print('RMSE is {}'.format(rmse))
-print('R2 score is {}'.format(r2))
-print("\n")
-
-# model evaluation for testing set
-
-y_test_predict = lin_model.predict(X_test)
-# root mean square error of the model
-rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict)))
-
-# r-squared score of the model
-r2 = r2_score(Y_test, y_test_predict)
-
-print("The model performance for testing set")
-print("--------------------------------------")
-print('RMSE is {}'.format(rmse))
-print('R2 score is {}'.format(r2))
-
-# plotting the y_test vs y_pred
-# ideally should have been a straight line
-plt.scatter(Y_test, y_test_predict)
-plt.show()
-
-