diff --git a/doc/BookChapters/chapter1.do.txt b/doc/BookChapters/chapter1.do.txt
index 5c3670c10..029b8a4a0 100644
--- a/doc/BookChapters/chapter1.do.txt
+++ b/doc/BookChapters/chapter1.do.txt
@@ -1,7 +1,5 @@
======= Linear Regression =======
-"Video of Lecture":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h20/forelesningsvideoer/LectureAug21.mp4?vrtx=view-as-webpage"
-
===== Introduction =====
@@ -9,7 +7,7 @@
-Our emphasis throughout this series of lectures (small change)
+Our emphasis throughout this series of lectures
is on understanding the mathematical aspects of
different algorithms used in the fields of data analysis and machine learning.
diff --git a/doc/BookChapters/chapter3.do.txt b/doc/BookChapters/chapter3.do.txt
index 5c1b8e90a..0ebd9707c 100644
--- a/doc/BookChapters/chapter3.do.txt
+++ b/doc/BookChapters/chapter3.do.txt
@@ -1,28 +1,120 @@
======= Ridge and Lasso Regression =======
-"Video of Lecture":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember10.mp4?vrtx=view-as-webpage"
+
+
+===== Mathematical Interpretation of Ordinary Least Squares =====
+
+What is presented here is a mathematical analysis of various regression algorithms (ordinary least squares, Ridge and Lasso Regression). The analysis is based on an important algorithm in linear algebra, the so-called Singular Value Decomposition (SVD).
+
+
+We have shown that in ordinary least squares the optimal parameters $\beta$ are given by
+
+!bt
+\[
+\hat{\bm{\beta}} = \left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}.
+\]
+!et
+
+The _hat_ over $\bm{\beta}$ means we have the optimal parameters after minimization of the cost function.
+
+This means that our best model is defined as
+
+!bt
+\[
+\tilde{\bm{y}}=\bm{X}\hat{\bm{\beta}} = \bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}.
+\]
+!et
+
+We now define a matrix
+!bt
+\[
+\bm{A}=\bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T.
+\]
+!et
+
+We can rewrite
+!bt
+\[
+\tilde{\bm{y}}=\bm{X}\hat{\bm{\beta}} = \bm{A}\bm{y}.
+\]
+!et
+
+The matrix $\bm{A}$ has the important property that $\bm{A}^2=\bm{A}$. This is the definition of a projection matrix.
+We can then interpret our optimal model $\tilde{\bm{y}}$ as being represented by an orthogonal projection of $\bm{y}$ onto a space defined by the column vectors of $\bm{X}$. In our case here the matrix $\bm{A}$ is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix.
+
+
+
+
+We have defined the residual error as
+!bt
+\[
+\bm{\epsilon}=\bm{y}-\tilde{\bm{y}}=\left[\bm{I}-\bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\right]\bm{y}.
+\]
+!et
+
+The residual errors are then the projections of $\bm{y}$ onto the orthogonal component of the space defined by the column vectors of $\bm{X}$.
+
+
+If the matrix $\bm{X}$ is an orthogonal (or unitary in case of complex values) matrix, we have
+
+!bt
+\[
+\bm{X}^T\bm{X}=\bm{X}\bm{X}^T = \bm{I}.
+\]
+!et
+
+In this case the matrix $\bm{A}$ becomes
+!bt
+\[
+\bm{A}=\bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T)=\bm{I},
+\]
+!et
+and we have the obvious case
+!bt
+\[
+\bm{\epsilon}=\bm{y}-\tilde{\bm{y}}=0.
+\]
+!et
+
+This serves also as a useful test of our codes.
+
+
===== The singular value decomposition =====
+
The examples we have looked at so far are cases where we normally can
-invert the matrix $\bm{X}^T\bm{X}$. Using a polynomial expansion as we
-did both for the masses and the fitting of the equation of state,
-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.
+invert the matrix $\bm{X}^T\bm{X}$. Using a polynomial expansion where we fit of various functions leads to
+row vectors of the design matrix which are essentially orthogonal due
+to the polynomial character of our model. Obtaining the inverse of the
+design matrix is then often done via a so-called LU, QR or Cholesky
+decomposition.
-
-This may
+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 partially circumvent this problem and also gain some insights about the ordinary least squares approach, and later shrinkage methods like Ridge and Lasso regressions.
+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.
-This is given by the _Singular Value Decomposition_ algorithm, perhaps
-the most powerful linear algebra algorithm. Let us look at a
-different example where we may have problems with the standard matrix
-inversion algorithm. Thereafter we dive into the math of the SVD.
@@ -69,6 +161,7 @@ We see easily that $\mbox{det}(\bm{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \tim
This is equivalent to saying that the matrix $\bm{X}$ has at least an eigenvalue which is zero.
+
If our design matrix $\bm{X}$ which enters the linear regression problem
!bt
\begin{align}
@@ -92,6 +185,8 @@ where $\bm{I}$ is the identity matrix. When we discuss _Ridge_ regression this
+===== Basic math of the SVD =====
+
From standard linear algebra we know that a square matrix $\bm{X}$ can be diagonalized if and only it is
a so-called "normal matrix":"https://en.wikipedia.org/wiki/Normal_matrix", that is if $\bm{X}\in {\mathbb{R}}^{n\times n}$
@@ -130,7 +225,6 @@ $\bm{X}\bm{X}^T=\bm{X}^T\bm{X}$ is not fulfilled.
-===== The SVD, a Fantastic Algorithm =====
However, and this is the strength of the SVD algorithm, any general
@@ -178,7 +272,6 @@ near singular or singular matrices.
The columns of $\bm{U}$ are called the left singular vectors while the columns of $\bm{V}$ are the right singular vectors.
-===== Economy-size SVD =====
If we assume that $n > p$, then our matrix $\bm{U}$ has dimension $n
\times n$. The last $n-p$ columns of $\bm{U}$ become however
@@ -197,41 +290,39 @@ If $p > n$, then only the first $n$ columns of $\bm{V}$ are computed and $\bm{\S
The $n=p$ case is obvious, we retain the full SVD.
In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.
+!split
+===== Codes for the SVD =====
!bc pycod
import numpy as np
# SVD inversion
-def SVDinv(A):
+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)
-# print('test U')
-# print( (np.transpose(U) @ U - U @np.transpose(U)))
-# print('test VT')
-# print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))
+ 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(S)
print(VT)
D = np.zeros((len(U),len(VT)))
for i in range(0,len(VT)):
- D[i,i]=s[i]
- UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)
- return np.matmul(V,np.matmul(invD,UT))
+ D[i,i]=S[i]
+ return U @ D @ VT
-X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])
+X = np.array([ [1.0,-1.0], [1.0,-1.0]])
+#X = np.array([[1, 2], [3, 4], [5, 6]])
+
print(X)
-A = np.transpose(X) @ X
-print(A)
-# Brute force inversion of super-collinear matrix
-#B = np.linalg.inv(A)
-#print(B)
-C = SVDinv(A)
-print(C)
-
+C = SVD(X)
+# Print the difference between the original matrix and the SVD one
+print(C-X)
!ec
The matrix $\bm{X}$ has columns that are linearly dependent. The first
@@ -245,76 +336,720 @@ in the program terminating due to a singular matrix.
+The $U$, $S$, and $V$ matrices returned from the _svd()_ function
+cannot be multiplied directly.
-There are several interesting mathematical properties which will be
-relevant when we are going to discuss the differences between say
-ordinary least squares (OLS) and _Ridge_ regression.
+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.
-We have from OLS that the parameters of the linear approximation are given by
+If you wish to include the zero singular values, you will need to
+resize the matrices and set up a diagonal matrix as done in the above
+example
+
+
+
+
+
+===== Mathematics of the SVD and implications =====
+
+Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies.
+
+Our starting point is our design matrix $\bm{X}$ of dimension $n\times p$
!bt
\[
-\bm{\tilde{y}} = \bm{X}\bm{\beta} = \bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}.
+\bm{X}=\begin{bmatrix}
+x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\
+x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\
+x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\
+\dots & \dots & \dots & \dots \dots & \dots \\
+x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\
+x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\
+\end{bmatrix}.
\]
!et
-The matrix to invert can be rewritten in terms of our SVD decomposition as
+We can SVD decompose our matrix as
+!bt
+\[
+\bm{X}=\bm{U}\bm{\Sigma}\bm{V}^T,
+\]
+!et
+where $\bm{U}$ is an orthogonal matrix of dimension $n\times n$, meaning that $\bm{U}\bm{U}^T=\bm{U}^T\bm{U}=\bm{I}_n$. Here $\bm{I}_n$ is the unit matrix of dimension $n \times n$.
+
+Similarly, $\bm{V}$ is an orthogonal matrix of dimension $p\times p$, meaning that $\bm{V}\bm{V}^T=\bm{V}^T\bm{V}=\bm{I}_p$. Here $\bm{I}_n$ is the unit matrix of dimension $p \times p$.
+
+Finally $\bm{\Sigma}$ contains the singular values $\sigma_i$. This matrix has dimension $n\times p$ and the singular values $\sigma_i$ are all positive. The non-zero values are ordered in descending order, that is
!bt
\[
-\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T.
+\sigma_0 > \sigma_1 > \sigma_2 > \dots > \sigma_{p-1} > 0.
\]
!et
-Using the orthogonality properties of $\bm{U}$ we have
+
+All values beyond $p-1$ are all zero.
+
+
+As an example, consider the following $3\times 2$ example for the matrix $\bm{\Sigma}$
!bt
\[
-\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T = \bm{V}\bm{D}\bm{V}^T,
+\bm{\Sigma}=
+\begin{bmatrix}
+2& 0 \\
+0 & 1 \\
+0 & 0 \\
+\end{bmatrix}
\]
!et
-with $\bm{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared.
-This means that
+The singular values are $\sigma_0=2$ and $\sigma_1=1$. It is common to rewrite the matrix $\bm{\Sigma}$ as
+
!bt
\[
-(\bm{X}^T\bm{X})\bm{V} = \bm{V}\bm{D},
+\bm{\Sigma}=
+\begin{bmatrix}
+\bm{\tilde{\Sigma}}\\
+\bm{0}\\
+\end{bmatrix},
\]
!et
-that is the eigenvectors of $(\bm{X}^T\bm{X})$ are given by the columns of the right singular matrix of $\bm{X}$ and the eigenvalues are the squared singular values. It is easy to show (show this) that
+
+where
!bt
\[
-(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D},
+\bm{\tilde{\Sigma}}=
+\begin{bmatrix}
+2& 0 \\
+0 & 1 \\
+\end{bmatrix},
\]
!et
-that is, the eigenvectors of $(\bm{X}\bm{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same.
+contains only the singular values. Note also (and we will use this below) that
-Going back to our OLS equation we have
!bt
\[
-\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y}.
+\bm{\Sigma}^T\bm{\Sigma}=
+\begin{bmatrix}
+4& 0 \\
+0 & 1 \\
+\end{bmatrix},
+\]
+!et
+which is a $2\times 2 $ matrix while
+!bt
+\[
+\bm{\Sigma}\bm{\Sigma}^T=
+\begin{bmatrix}
+4& 0 & 0\\
+0 & 1 & 0\\
+0 & 0 & 0\\
+\end{bmatrix},
\]
!et
-We will come back to this expression when we discuss Ridge regression.
-
-$$ \tilde{y}^{OLS}=\bm{X}\hat{\beta}^{OLS}=\sum_{j=1}^p \bm{u}_j\bm{u}_j^T\bm{y}$$ and for Ridge we have
-
-$$ \tilde{y}^{Ridge}=\bm{X}\hat{\beta}^{Ridge}=\sum_{j=1}^p \bm{u}_j\frac{\sigma_j^2}{\sigma_j^2+\lambda}\bm{u}_j^T\bm{y}$$ .
-
-It is indeed the economy-sized SVD, note the summation runs up tp $$p$$ only and not $$n$$.
-
-Here we have that $$\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T$$, with $$\Sigma$$ being an $$ n\times p$$ matrix and $$\bm{V}$$ being a $$ p\times p$$ matrix. We also have assumed here that $$ n > p$$.
+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.
+The matrix that may cause problems for us is $\bm{X}^T\bm{X}$. Using the SVD we can rewrite this matrix as
+
+!bt
+\[
+\bm{X}^T\bm{X}=\bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T,
+\]
+!et
+and using the orthogonality of the matrix $\bm{U}$ we have
+
+!bt
+\[
+\bm{X}^T\bm{X}=\bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T.
+\]
+!et
+We define $\bm{\Sigma}^T\bm{\Sigma}=\tilde{\bm{\Sigma}}^2$ which is a diagonal matrix containing only the singular values squared. It has dimensionality $p \times p$.
+
+This means, using the orthogonality of $\bm{V}$, that we get
+
+!bt
+\[
+\bm{X}^T\bm{X}=\tilde{\bm{\Sigma}}^2.
+\]
+!et
+
+We can now insert the result for the matrix $\bm{X}^T\bm{X}$ into our equation for ordinary least squares where
+
+!bt
+\[
+\tilde{y}_{\mathrm{OLS}}=\bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y},
+\]
+!et
+and using our SVD decomposition of $\bm{X}$ we have
+
+!bt
+\[
+\tilde{y}_{\mathrm{OLS}}=\bm{U}\bm{\Sigma}\bm{V}^T\tilde{\bm{\Sigma}}^{-2}\bm{V}\bm{\Sigma}^T\bm{U}^T\bm{y},
+\]
+!et
+which gives us, using the orthogonality of the matrices $\bm{U}$ and $\bm{V}$,
+
+!bt
+\[
+\tilde{y}_{\mathrm{OLS}}=\bm{U}\bm{U}^T\bm{y}=\sum_{i=0}^{p-1}\bm{u}_i\bm{u}^T_j\bm{y},
+\]
+!et
+
+Note here that when we perform the multiplication of the various matrices, the orthogonal vectors of the matrix $\bm{U}$
+!bt
+\[
+\bm{U}=[\bm{u}_0,\bm{u}_1,\dots,\bm{u}_{n-1}],
+\]
+!et
+that belong to $i>p-1$, result in only zeros when we perform the multiplications. This means that the sum above has non-zero elements only up to $i=p-1$. This corresponds also to the number of singular values (these are all non-zero).
+
+It means that the ordinary least square model (with the optimal parameters) $\bm{\tilde{y}}$, corresponds to an orthogonal transformation of the output (or target) vector $\bm{y}$ by the vectors of the matrix $\bm{U}$.
+===== Further properties (important for our analyses later) =====
+
+Let us study again $\bm{X}^T\bm{X}$ in terms of our SVD,
+!bt
+\[
+\bm{X}^T\bm{X}=\bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T=\bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T.
+\]
+!et
+
+If we now multiply from the right with $\bm{V}$ (using the orthogonality of $\bm{V}$) we get
+!bt
+\[
+\left(\bm{X}^T\bm{X}\right)\bm{V}=\bm{V}\bm{\Sigma}^T\bm{\Sigma}.
+\]
+!et
+This means the vectors $\bm{v}_i$ of the orthogonal matrix $\bm{V}$ are the eigenvectors of the matrix $\bm{X}^T\bm{X}$
+with eigenvalues given by the singular values squared, that is
+!bt
+\[
+\left(\bm{X}^T\bm{X}\right)\bm{v}_i=\bm{v}_i\sigma_i^2.
+\]
+!et
+
+Similarly, if we use the SVD decomposition for the matrix $\bm{X}\bm{X}^T$, we have
+!bt
+\[
+\bm{X}\bm{X}^T=\bm{U}\bm{\Sigma}\bm{V}^T\bm{V}\bm{\Sigma}^T\bm{U}^T=\bm{U}\bm{\Sigma}\bm{\Sigma}^T\bm{U}^T.
+\]
+!et
+
+If we now multiply from the right with $\bm{U}$ (using the orthogonality of $\bm{U}$) we get
+!bt
+\[
+\left(\bm{X}\bm{X}^T\right)\bm{U}=\bm{U}\bm{\Sigma}\bm{\Sigma}^T.
+\]
+!et
+This means the vectors $\bm{u}_i$ of the orthogonal matrix $\bm{U}$ are the eigenvectors of the matrix $\bm{X}\bm{X}^T$
+with eigenvalues given by the singular values squared, that is
+!bt
+\[
+\left(\bm{X}\bm{X}^T\right)\bm{u}_i=\bm{u}_i\sigma_i^2.
+\]
+!et
+
+_Important note_: we have defined our design matrix $\bm{X}$ to be an
+$n\times p$ matrix. In most supervised learning cases we have that $n
+\ge p$, and quite often we have $n >> p$. For linear algebra based methods like ordinary least squares or Ridge regression, this leads to a matrix $\bm{X}^T\bm{X}$ which is small and thereby easier to handle from a computational point of view (in terms of number of floating point operations).
+
+In our lectures, the number of columns will
+always refer to the number of features in our data set, while the
+number of rows represents the number of data inputs. Note that in
+other texts you may find the opposite notation. This has consequences
+for the definition of for example the covariance matrix and its relation to the SVD.
+
+
+===== Meet the Covariance Matrix =====
+
+
+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 $\bm{X}^T\bm{X}$ in ordinary
+least squares is proportional to the second derivative of the cost
+function, that is we have
+
+!bt
+\[
+\frac{\partial^2 C(\bm{\beta})}{\partial \bm{\beta}^T\partial \bm{\beta}} =\frac{2}{n}\bm{X}^T\bm{X}.
+\]
+!et
+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
+
+!bt
+\[
+\bm{H}=\bm{X}^T\bm{X}.
+\]
+!et
+
+
+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.
+
+
+
+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.
+
+Suppose we have defined two vectors
+$\hat{x}$ and $\hat{y}$ with $n$ elements each. The covariance matrix $\bm{C}$ is defined as
+!bt
+\[
+\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{cov}[\bm{x},\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\
+ \mathrm{cov}[\bm{y},\bm{x}] & \mathrm{cov}[\bm{y},\bm{y}] \\
+ \end{bmatrix},
+\]
+!et
+where for example
+!bt
+\[
+\mathrm{cov}[\bm{x},\bm{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}).
+\]
+!et
+With this definition and recalling that the variance is defined as
+!bt
+\[
+\mathrm{var}[\bm{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2,
+\]
+!et
+we can rewrite the covariance matrix as
+!bt
+\[
+\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{var}[\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\
+ \mathrm{cov}[\bm{x},\bm{y}] & \mathrm{var}[\bm{y}] \\
+ \end{bmatrix}.
+\]
+!et
+
+_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":"https://mathworld.wolfram.com/BesselsCorrection.html". 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 calculate the covariance, this
+quantity will be computed with a factor $1/(n-1)$.
+
+
+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
+
+!bt
+\[
+\mathrm{corr}[\bm{x},\bm{y}]=\frac{\mathrm{cov}[\bm{x},\bm{y}]}{\sqrt{\mathrm{var}[\bm{x}] \mathrm{var}[\bm{y}]}}.
+\]
+!et
+
+The correlation function is then given by values $\mathrm{corr}[\bm{x},\bm{y}]
+\in [-1,1]$. This avoids eventual problems with too large values. We
+can then define the correlation matrix for the two vectors $\bm{x}$
+and $\bm{y}$ as
+
+!bt
+\[
+\bm{K}[\bm{x},\bm{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\bm{x},\bm{y}] \\
+ \mathrm{corr}[\bm{y},\bm{x}] & 1 \\
+ \end{bmatrix},
+\]
+!et
+
+In the above example this is the function we constructed using _pandas_.
+
+
+
+In our derivation of the various regression algorithms like _Ordinary Least Squares_ or _Ridge regression_
+we defined the design/feature matrix $\bm{X}$ as
+
+!bt
+\[
+\bm{X}=\begin{bmatrix}
+x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\
+x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\
+x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\
+\dots & \dots & \dots & \dots \dots & \dots \\
+x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\
+x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\
+\end{bmatrix},
+\]
+!et
+with $\bm{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
+!bt
+\[
+\bm{X}=\begin{bmatrix} \bm{x}_0 & \bm{x}_1 & \bm{x}_2 & \dots & \dots & \bm{x}_{p-1}\end{bmatrix},
+\]
+!et
+with a given vector
+!bt
+\[
+\bm{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}.
+\]
+!et
+
+With these definitions, we can now rewrite our $2\times 2$
+correlation/covariance matrix in terms of a moe general design/feature
+matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$. This leads to a $p\times p$
+covariance matrix for the vectors $\bm{x}_i$ with $i=0,1,\dots,p-1$
+
+!bt
+\[
+\bm{C}[\bm{x}] = \begin{bmatrix}
+\mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] & \mathrm{cov}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_0,\bm{x}_{p-1}]\\
+\mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] & \mathrm{cov}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_1,\bm{x}_{p-1}]\\
+\mathrm{cov}[\bm{x}_2,\bm{x}_0] & \mathrm{cov}[\bm{x}_2,\bm{x}_1] & \mathrm{var}[\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_2,\bm{x}_{p-1}]\\
+\dots & \dots & \dots & \dots & \dots & \dots \\
+\dots & \dots & \dots & \dots & \dots & \dots \\
+\mathrm{cov}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & \mathrm{var}[\bm{x}_{p-1}]\\
+\end{bmatrix},
+\]
+!et
+and the correlation matrix
+!bt
+\[
+\bm{K}[\bm{x}] = \begin{bmatrix}
+1 & \mathrm{corr}[\bm{x}_0,\bm{x}_1] & \mathrm{corr}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_0,\bm{x}_{p-1}]\\
+\mathrm{corr}[\bm{x}_1,\bm{x}_0] & 1 & \mathrm{corr}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_1,\bm{x}_{p-1}]\\
+\mathrm{corr}[\bm{x}_2,\bm{x}_0] & \mathrm{corr}[\bm{x}_2,\bm{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\bm{x}_2,\bm{x}_{p-1}]\\
+\dots & \dots & \dots & \dots & \dots & \dots \\
+\dots & \dots & \dots & \dots & \dots & \dots \\
+\mathrm{corr}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & 1\\
+\end{bmatrix},
+\]
+!et
+
+
+
+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 $\bm{W}$
+
+Note that this assumes you have the features as the rows, and the inputs as columns, that is
+!bt
+\[
+\bm{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},
+\]
+!et
+
+which in turn is converted into into the $2\times 2$ covariance matrix
+$\bm{C}$ via the Numpy function _np.cov()_. We note that we can also calculate
+the mean value of each set of samples $\bm{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.
+
+!bc pycod
+# 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)
+!ec
+
+
+
+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).
+
+!bc pycod
+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)
+!ec
+
+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.
+
+The above procedure with _numpy_ can be made more compact if we use _pandas_.
+
+
+
+We whow here how we can set up the correlation matrix using _pandas_, as done in this simple code
+!bc pycod
+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)
+!ec
+
+
+We expand this model to the Franke function discussed earlier.
+
+
+!bc pycod
+# 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)
+!ec
+
+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.
+
+
+
+We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\bm{X}$ as
+!bt
+\[
+\bm{C}[\bm{x}] = \frac{1}{n}\bm{X}^T\bm{X}= \mathbb{E}[\bm{X}^T\bm{X}].
+\]
+!et
+
+To see this let us simply look at a design matrix $\bm{X}\in {\mathbb{R}}^{2\times 2}$
+!bt
+\[
+\bm{X}=\begin{bmatrix}
+x_{00} & x_{01}\\
+x_{10} & x_{11}\\
+\end{bmatrix}=\begin{bmatrix}
+\bm{x}_{0} & \bm{x}_{1}\\
+\end{bmatrix}.
+\]
+!et
+
+If we then compute the expectation value (note the $1/n$ factor instead of $1/(n-1)$)
+!bt
+\[
+\mathbb{E}[\bm{X}^T\bm{X}] = \frac{1}{n}\bm{X}^T\bm{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},
+\]
+!et
+which is just
+!bt
+\[
+\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]=\begin{bmatrix} \mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] \\
+ \mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] \\
+ \end{bmatrix},
+\]
+!et
+where we wrote $$\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]$$ to indicate that this is the covariance of the vectors $\bm{x}$ of the design/feature matrix $\bm{X}$.
+
+It is easy to generalize this to a matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$.
+
+
+
+===== Linking with the SVD =====
+
+We saw earlier that
+!bt
+\[
+\bm{X}^T\bm{X}=\bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T=\bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T.
+\]
+!et
+Since the matrices here have dimension $p\times p$, with $p$ corresponding to the singular values, we defined earlier the matrix
+!bt
+\[
+\bm{\Sigma}^T\bm{\Sigma} = \begin{bmatrix} \tilde{\bm{\Sigma}} & \bm{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\bm{\Sigma}} \\ \bm{0}\\ \end{bmatrix},
+\]
+!et
+where the tilde-matrix $\tilde{\bm{\Sigma}}$ is a matrix of dimension $p\times p$ containing only the singular values $\sigma_i$, that is
+
+!bt
+\[
+\tilde{\bm{\Sigma}}=\begin{bmatrix} \sigma_0 & 0 & 0 & \dots & 0 & 0 \\
+ 0 & \sigma_1 & 0 & \dots & 0 & 0 \\
+ 0 & 0 & \sigma_2 & \dots & 0 & 0 \\
+ 0 & 0 & 0 & \dots & \sigma_{p-2} & 0 \\
+ 0 & 0 & 0 & \dots & 0 & \sigma_{p-1} \\
+\end{bmatrix},
+\]
+!et
+meaning we can write
+!bt
+\[
+\bm{X}^T\bm{X}=\bm{V}\tilde{\bm{\Sigma}}^2\bm{V}^T.
+\]
+!et
+Multiplying from the right with $\bm{V}$ (using the orthogonality of $\bm{V}$) we get
+!bt
+\[
+\left(\bm{X}^T\bm{X}\right)\bm{V}=\bm{V}\tilde{\bm{\Sigma}}^2.
+\]
+!et
+
+
+This means the vectors $\bm{v}_i$ of the orthogonal matrix $\bm{V}$
+are the eigenvectors of the matrix $\bm{X}^T\bm{X}$ with eigenvalues
+given by the singular values squared, that is
+
+!bt
+\[
+\left(\bm{X}^T\bm{X}\right)\bm{v}_i=\bm{v}_i\sigma_i^2.
+\]
+!et
+
+In other words, each non-zero singular value of $\bm{X}$ is a positive
+square root of an eigenvalue of $\bm{X}^T\bm{X}$. It means also that
+the columns of $\bm{V}$ are the eigenvectors of
+$\bm{X}^T\bm{X}$. Since we have ordered the singular values of
+$\bm{X}$ in a descending order, it means that the column vectors
+$\bm{v}_i$ are hierarchically ordered by how much correlation they
+encode from the columns of $\bm{X}$.
+
+
+Note that these are also the eigenvectors and eigenvalues of the
+Hessian matrix.
+
+If we now recall the definition of the covariance matrix (not using
+Bessel's correction) we have
+
+
+!bt
+\[
+\bm{C}[\bm{X}]=\frac{1}{n}\bm{X}^T\bm{X},
+\]
+!et
+
+meaning that every squared non-singular value of $\bm{X}$ divided by $n$ (
+the number of samples) are the eigenvalues of the covariance
+matrix. Every singular value of $\bm{X}$ is thus a positive square
+root of an eigenvalue of $\bm{X}^T\bm{X}$. If the matrix $\bm{X}$ is
+self-adjoint, the singular values of $\bm{X}$ are equal to the
+absolute value of the eigenvalues of $\bm{X}$.
+
+
+For $\bm{X}\bm{X}^T$ we found
+
+!bt
+\[
+\bm{X}\bm{X}^T=\bm{U}\bm{\Sigma}\bm{V}^T\bm{V}\bm{\Sigma}^T\bm{U}^T=\bm{U}\bm{\Sigma}^T\bm{\Sigma}\bm{U}^T.
+\]
+!et
+Since the matrices here have dimension $n\times n$, we have
+!bt
+\[
+\bm{\Sigma}\bm{\Sigma}^T = \begin{bmatrix} \tilde{\bm{\Sigma}} \\ \bm{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\bm{\Sigma}} \bm{0}\\ \end{bmatrix}=\begin{bmatrix} \tilde{\bm{\Sigma}} & \bm{0} \\ \bm{0} & \bm{0}\\ \end{bmatrix},
+\]
+!et
+leading to
+!bt
+\[
+\bm{X}\bm{X}^T=\bm{U}\begin{bmatrix} \tilde{\bm{\Sigma}} & \bm{0} \\ \bm{0} & \bm{0}\\ \end{bmatrix}\bm{U}^T.
+\]
+!et
+
+Multiplying with $\bm{U}$ from the right gives us the eigenvalue problem
+!bt
+\[
+(\bm{X}\bm{X}^T)\bm{U}=\bm{U}\begin{bmatrix} \tilde{\bm{\Sigma}} & \bm{0} \\ \bm{0} & \bm{0}\\ \end{bmatrix}.
+\]
+!et
+
+It means that the eigenvalues of $\bm{X}\bm{X}^T$ are again given by
+the non-zero singular values plus now a series of zeros. The column
+vectors of $\bm{U}$ are the eigenvectors of $\bm{X}\bm{X}^T$ and
+measure how much correlations are contained in the rows of $\bm{X}$.
+
+Since we will mainly be interested in the correlations among the features
+of our data (the columns of $\bm{X}$, the quantity of interest for us are the non-zero singular
+values and the column vectors of $\bm{V}$.
===== Ridge and LASSO Regression =====
-"Video of Lecture":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember11.mp4?vrtx=view-as-webpage"
-
Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is
our optimization problem is
!bt
@@ -376,21 +1111,21 @@ Here we have defined the norm-1 as
-Using the matrix-vector expression for Ridge regression,
+Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have
!bt
\[
-C(\bm{X},\bm{\beta})=\frac{1}{n}\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\bm{\beta}^T\bm{\beta},
+C(\bm{X},\bm{\beta})=\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\bm{\beta}^T\bm{\beta},
\]
!et
-
-by taking the derivatives with respect to $\bm{\beta}$ we obtain then
+and
+taking the derivatives with respect to $\bm{\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
!bt
\[
-\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y},
+\hat{\bm{\beta}}_{\mathrm{Ridge}} = \left(\bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y},
\]
!et
@@ -404,22 +1139,26 @@ with $\bm{I}$ being a $p\times p$ identity matrix with the constraint that
with $t$ a finite positive number.
-We see that Ridge regression is nothing but the standard
-OLS with a modified diagonal term added to $\bm{X}^T\bm{X}$. The
-consequences, in particular for our discussion of the bias-variance tradeoff
-are rather interesting.
-
-Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had
+When we compare this with the ordinary least squares result we have
!bt
\[
-(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D}.
+\hat{\bm{\beta}}_{\mathrm{OLS}} = \left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y},
\]
!et
+which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\bm{X}^T\bm{X}$.
-We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\bm{U}$ as
+
+We see that Ridge regression is nothing but the standard OLS with a
+modified diagonal term added to $\bm{X}^T\bm{X}$. The consequences, in
+particular for our discussion of the bias-variance tradeoff are rather
+interesting. We will see that for specific values of $\lambda$, we may
+even reduce the variance of the optimal parameters $\bm{\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.
+
+Using our insights about the SVD of the design matrix $\bm{X}$
+We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\bm{U}$ as
!bt
\[
-\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y}
+\tilde{\bm{y}}_{\mathrm{OLS}}=\bm{X}\bm{\beta} =\bm{U}\bm{U}^T\bm{y}.
\]
!et
@@ -428,11 +1167,11 @@ For Ridge regression this becomes
!bt
\[
-\bm{X}\bm{\beta}^{\mathrm{Ridge}} = \bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T+\lambda\bm{I} \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\sum_{j=0}^{p-1}\bm{u}_j\bm{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\bm{y},
+\tilde{\bm{y}}_{\mathrm{Ridge}}=\bm{X}\bm{\beta}_{\mathrm{Ridge}} = \bm{U\Sigma V^T}\left(\bm{V}\bm{\Sigma}^2\bm{V}^T+\lambda\bm{I} \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\sum_{j=0}^{p-1}\bm{u}_j\bm{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\bm{y},
\]
!et
-with the vectors $\bm{u}_j$ being the columns of $\bm{U}$.
+with the vectors $\bm{u}_j$ being the columns of $\bm{U}$ from the SVD of the matrix $\bm{X}$.
Since $\lambda \geq 0$, it means that compared to OLS, we have
@@ -449,9 +1188,7 @@ $\frac{\sigma_j^2}{\sigma_j^2+\lambda}$. Recall that the SVD has
eigenvalues ordered in a descending way, that is $\sigma_i \geq
\sigma_{i+1}$.
-For small eigenvalues $\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom.
-Actually, calculating the variance of $\bm{X}\bm{v}_j$ shows that this quantity is equal to $\sigma_j^2/n$.
-With a parameter $\lambda$ we can thus shrink the role of specific parameters.
+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.
@@ -488,361 +1225,1356 @@ For more discussions of Ridge and Lasso regression, "Wessel van Wieringen's":"ht
Similarly, "Mehta et al's article":"https://arxiv.org/abs/1803.08823" is also recommended.
-
-===== A better understanding of regularization =====
-
-The parameter $\lambda$ that we have introduced in the Ridge (and
-Lasso as well) regression is often called a regularization parameter
-or shrinkage parameter. It is common to call it a hyperparameter. What does it mean mathemtically?
-
-Here we will first look at how to analyze the difference between the
-standard OLS equations and the Ridge expressions in terms of a linear
-algebra analysis using the SVD algorithm. Thereafter, we will link
-(see the material on the bias-variance tradeoff below) these
-observation to the statisical analysis of the results. In particular
-we consider how the variance of the parameters $\bm{\beta}$ is
-affected by changing the parameter $\lambda$.
-
-
-We have our design matrix
- $\bm{X}\in {\mathbb{R}}^{n\times p}$. With the SVD we decompose it as
-
-!bt
-\[
-\bm{X} = \bm{U\Sigma V^T},
-\]
-!et
-
-with $\bm{U}\in {\mathbb{R}}^{n\times n}$, $\bm{\Sigma}\in {\mathbb{R}}^{n\times p}$
-and $\bm{V}\in {\mathbb{R}}^{p\times p}$.
-
-The matrices $\bm{U}$ and $\bm{V}$ are unitary/orthonormal matrices, that is in case the matrices are real we have $\bm{U}^T\bm{U}=\bm{U}\bm{U}^T=\bm{I}$ and $\bm{V}^T\bm{V}=\bm{V}\bm{V}^T=\bm{I}$.
-
-
-
-===== Introducing the Covariance and Correlation functions =====
-
-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
-
-Suppose we have defined two vectors
-$\bm{x}$ and $\bm{y}$ with $n$ elements each. The covariance matrix $\bm{C}$ is defined as
-!bt
-\[
-\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{cov}[\bm{x},\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\
- \mathrm{cov}[\bm{y},\bm{x}] & \mathrm{cov}[\bm{y},\bm{y}] \\
- \end{bmatrix},
-\]
-!et
-where for example
-!bt
-\[
-\mathrm{cov}[\bm{x},\bm{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}).
-\]
-!et
-With this definition and recalling that the variance is defined as
-!bt
-\[
-\mathrm{var}[\bm{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2,
-\]
-!et
-we can rewrite the covariance matrix as
-!bt
-\[
-\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{var}[\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\
- \mathrm{cov}[\bm{x},\bm{y}] & \mathrm{var}[\bm{y}] \\
- \end{bmatrix}.
-\]
-!et
-
-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
+Using the matrix-vector expression for Lasso regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have the following _cost_ function
!bt
\[
-\mathrm{corr}[\bm{x},\bm{y}]=\frac{\mathrm{cov}[\bm{x},\bm{y}]}{\sqrt{\mathrm{var}[\bm{x}] \mathrm{var}[\bm{y}]}}.
+C(\bm{X},\bm{\beta})=\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\vert\vert\bm{\beta}\vert\vert_1,
\]
!et
-The correlation function is then given by values $\mathrm{corr}[\bm{x},\bm{y}]
-\in [-1,1]$. This avoids eventual problems with too large values. We
-can then define the correlation matrix for the two vectors $\bm{x}$
-and $\bm{y}$ as
+Taking the derivative with respect to $\bm{\beta}$ and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)
+!bt
+\[
+\frac{d \vert \beta\vert}{d \bm{\beta}}=\mathrm{sgn}(\bm{\beta})=\left\{\begin{array}{cc} 1 & \beta > 0 \\ 0 & \beta =0\\-1 & \beta < 0, \end{array}\right.
+\]
+!et
+we have that the derivative of the cost function is
!bt
\[
-\bm{K}[\bm{x},\bm{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\bm{x},\bm{y}] \\
- \mathrm{corr}[\bm{y},\bm{x}] & 1 \\
- \end{bmatrix},
+\frac{\partial C(\bm{X},\bm{\beta})}{\partial \bm{\beta}}=-2\bm{X}^T(\bm{y}-\bm{X}\bm{\beta})+\lambda sgn(\bm{\beta})=0,
\]
!et
-
-In the above example this is the function we constructed using _pandas_.
-
-
-
-In our derivation of the various regression algorithms like _Ordinary Least Squares_ or _Ridge regression_
-we defined the design/feature matrix $\bm{X}$ as
-
+and reordering we have
!bt
\[
-\bm{X}=\begin{bmatrix}
-x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\
-x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\
-x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\
-\dots & \dots & \dots & \dots \dots & \dots \\
-x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\
-x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\
-\end{bmatrix},
-\]
-!et
-with $\bm{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
-!bt
-\[
-\bm{X}=\begin{bmatrix} \bm{x}_0 & \bm{x}_1 & \bm{x}_2 & \dots & \dots & \bm{x}_{p-1}\end{bmatrix},
-\]
-!et
-with a given vector
-!bt
-\[
-\bm{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}.
+\bm{X}^T\bm{X}\bm{\beta})+\lambda sgn(\bm{\beta})=2\bm{X}^T(\bm{y}.
\]
!et
+This equation does not lead to a nice analytical equation as in either Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms using for example the Python package "CVXOPT":"https://cvxopt.org/". We will discuss this later.
-With these definitions, we can now rewrite our $2\times 2$
-correaltion/covariance matrix in terms of a moe general design/feature
-matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$. This leads to a $p\times p$
-covariance matrix for the vectors $\bm{x}_i$ with $i=0,1,\dots,p-1$
-
-!bt
-\[
-\bm{C}[\bm{x}] = \begin{bmatrix}
-\mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] & \mathrm{cov}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_0,\bm{x}_{p-1}]\\
-\mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] & \mathrm{cov}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_1,\bm{x}_{p-1}]\\
-\mathrm{cov}[\bm{x}_2,\bm{x}_0] & \mathrm{cov}[\bm{x}_2,\bm{x}_1] & \mathrm{var}[\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_2,\bm{x}_{p-1}]\\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\mathrm{cov}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & \mathrm{var}[\bm{x}_{p-1}]\\
-\end{bmatrix},
-\]
-!et
-and the correlation matrix
-!bt
-\[
-\bm{K}[\bm{x}] = \begin{bmatrix}
-1 & \mathrm{corr}[\bm{x}_0,\bm{x}_1] & \mathrm{corr}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_0,\bm{x}_{p-1}]\\
-\mathrm{corr}[\bm{x}_1,\bm{x}_0] & 1 & \mathrm{corr}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_1,\bm{x}_{p-1}]\\
-\mathrm{corr}[\bm{x}_2,\bm{x}_0] & \mathrm{corr}[\bm{x}_2,\bm{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\bm{x}_2,\bm{x}_{p-1}]\\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\mathrm{corr}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & 1\\
-\end{bmatrix},
-\]
-!et
-
-
-
-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 $\bm{W}$
-
-
-!bt
-\[
-\bm{W} = \begin{bmatrix} x_0 & y_0 \\
- x_1 & y_1 \\
- x_2 & y_2\\
- \dots & \dots \\
- x_{n-2} & y_{n-2}\\
- x_{n-1} & y_{n-1} &
- \end{bmatrix},
-\]
-!et
-
-which in turn is converted into into the $2\times 2$ covariance matrix
-$\bm{C}$ via the Numpy function _np.cov()_. We note that we can also calculate
-the mean value of each set of samples $\bm{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.
+===== Code for SVD and Inversion of Matrices =====
+How do we use the SVD to invert a matrix $\bm{X}^\bm{X}$ which is singular or near singular?
+The simple answer is to use the linear algebra function for pseudoinvers, that is
!bc pycod
-# 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)
+Ainv = np.linlag.pinv(A)
!ec
-
-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).
+Let us first look at a matrix which does not causes problems and write our own function where we just use the SVD.
!bc pycod
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)
-!ec
-
-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.
-
-The above procedure with _numpy_ can be made more compact if we use _pandas_.
+# SVD inversion
+def SVDinv(A):
+ ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).
+ SVD is numerically more stable than the inversion algorithms provided by
+ numpy and scipy.linalg at the cost of being slower.
+ '''
+ U, s, VT = np.linalg.svd(A)
+ print('test U')
+ print( (np.transpose(U) @ U - U @np.transpose(U)))
+ print('test VT')
+ print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))
-We whow here how we can set up the correlation matrix using _pandas_, as done in this simple code
-!bc pycod
-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)
-X = (np.vstack((x, y))).T
+ D = np.zeros((len(U),len(VT)))
+ D = np.diag(s)
+ UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)
+ return np.matmul(V,np.matmul(invD,UT))
+
+
+#X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])
+# Non-singular square matrix
+X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])
print(X)
-Xpd = pd.DataFrame(X)
-print(Xpd)
-correlation_matrix = Xpd.corr()
-print(correlation_matrix)
+A = np.transpose(X) @ X
+# Brute force inversion
+B = np.linalg.inv(A) # here we could use np.linalg.pinv(A)
+C = SVDinv(A)
+print(np.abs(B-C))
+
!ec
-We expand this model to the Franke function discussed above.
+Although our matrix to invert $\bm{X}^T\bm{X}$ is a square matrix, our matrix may be singular.
+
+The pseudoinverse is the generalization of the matrix inverse for square matrices to
+rectangular matrices where the number of rows and columns are not equal.
+
+It is also called the the Moore-Penrose Inverse after two independent discoverers of the method or the Generalized Inverse.
+It is used for the calculation of the inverse for singular or near singular matrices and for rectangular matrices.
+
+Using the SVD we can obtain the pseudoinverse of a matrix $\bm{A}$ (labeled here as $\bm{A}_{\mathrm{PI}}$
+!bt
+\[
+\bm{A}_{\mathrm{PI}}= \bm{V}\bm{D}_{\mathrm{PI}}\bm{U}^T,
+\]
+!et
+where $\bm{D}_{\mathrm{PI}}$ can be calculated by creating a diagonal matrix from $\bm{Sigma}$ where we only keep the singular values (the non-zero values). The following code computes the pseudoinvers of the matrix based on the SVD.
+
+
+!bc pycod
+import numpy as np
+# SVD inversion
+def SVDinv(A):
+ U, s, VT = np.linalg.svd(A)
+ # reciprocals of singular values of s
+ d = 1.0 / s
+ # create m x n D matrix
+ D = np.zeros(A.shape)
+ # populate D with n x n diagonal matrix
+ D[:A.shape[1], :A.shape[1]] = np.diag(d)
+ UT = np.transpose(U)
+ V = np.transpose(VT)
+ return np.matmul(V,np.matmul(D.T,UT))
+
+
+A = np.array([ [0.3, 0.4], [0.5, 0.6], [0.7, 0.8],[0.9, 1.0]])
+print(A)
+# Brute force inversion of super-collinear matrix
+B = np.linalg.pinv(A)
+print(B)
+# Compare our own algorithm with pinv
+C = SVDinv(A)
+print(np.abs(C-B))
+
+!ec
+As you can see from this example, our own decomposition based on the SVD agrees the pseudoinverse algorithm provided by _Numpy_.
+
+
+
+===== Deriving the Ridge Regression Equations =====
+
+Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is
+our optimization problem is
+!bt
+\[
+{\displaystyle \min_{\bm{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}.
+\]
+!et
+or we can state it as
+!bt
+\[
+{\displaystyle \min_{\bm{\beta}\in
+{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2,
+\]
+!et
+where we have used the definition of a norm-2 vector, that is
+!bt
+\[
+\vert\vert \bm{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.
+\]
+!et
+
+
+
+By minimizing the above equation with respect to the parameters
+$\bm{\beta}$ we could then obtain an analytical expression for the
+parameters $\bm{\beta}$. We can add a regularization parameter $\lambda$ by
+defining a new cost function to be optimized, that is
+
+!bt
+\[
+{\displaystyle \min_{\bm{\beta}\in
+{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_2^2
+\]
+!et
+
+which leads to the Ridge regression minimization problem where we
+require that $\vert\vert \bm{\beta}\vert\vert_2^2\le t$, where $t$ is
+a finite number larger than zero. By defining
+
+!bt
+\[
+C(\bm{X},\bm{\beta})=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1,
+\]
+!et
+
+we have a new optimization equation
+!bt
+\[
+{\displaystyle \min_{\bm{\beta}\in
+{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1
+\]
+!et
+which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.
+
+Here we have defined the norm-1 as
+!bt
+\[
+\vert\vert \bm{x}\vert\vert_1 = \sum_i \vert x_i\vert.
+\]
+!et
+
+
+
+
+
+Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have
+
+!bt
+\[
+C(\bm{X},\bm{\beta})=\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\bm{\beta}^T\bm{\beta},
+\]
+!et
+and
+taking the derivatives with respect to $\bm{\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
+!bt
+\[
+\hat{\bm{\beta}}_{\mathrm{Ridge}} = \left(\bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y},
+\]
+!et
+
+with $\bm{I}$ being a $p\times p$ identity matrix with the constraint that
+
+!bt
+\[
+\sum_{i=0}^{p-1} \beta_i^2 \leq t,
+\]
+!et
+
+with $t$ a finite positive number.
+
+When we compare this with the ordinary least squares result we have
+!bt
+\[
+\hat{\bm{\beta}}_{\mathrm{OLS}} = \left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y},
+\]
+!et
+which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\bm{X}^T\bm{X}$.
+
+
+We see that Ridge regression is nothing but the standard OLS with a
+modified diagonal term added to $\bm{X}^T\bm{X}$. The consequences, in
+particular for our discussion of the bias-variance tradeoff are rather
+interesting. We will see that for specific values of $\lambda$, we may
+even reduce the variance of the optimal parameters $\bm{\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.
+
+
+
+Using our insights about the SVD of the design matrix $\bm{X}$
+We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\bm{U}$ as
+!bt
+\[
+\tilde{\bm{y}}_{\mathrm{OLS}}=\bm{X}\bm{\beta} =\bm{U}\bm{U}^T\bm{y}.
+\]
+!et
+
+
+For Ridge regression this becomes
+
+!bt
+\[
+\tilde{\bm{y}}_{\mathrm{Ridge}}=\bm{X}\bm{\beta}_{\mathrm{Ridge}} = \bm{U\Sigma V^T}\left(\bm{V}\bm{\Sigma}^2\bm{V}^T+\lambda\bm{I} \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\sum_{j=0}^{p-1}\bm{u}_j\bm{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\bm{y},
+\]
+!et
+
+with the vectors $\bm{u}_j$ being the columns of $\bm{U}$ from the SVD of the matrix $\bm{X}$.
+
+
+
+Since $\lambda \geq 0$, it means that compared to OLS, we have
+
+!bt
+\[
+\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1.
+\]
+!et
+
+Ridge regression finds the coordinates of $\bm{y}$ with respect to the
+orthonormal basis $\bm{U}$, it then shrinks the coordinates by
+$\frac{\sigma_j^2}{\sigma_j^2+\lambda}$. Recall that the SVD has
+eigenvalues ordered in a descending way, that is $\sigma_i \geq
+\sigma_{i+1}$.
+
+For small eigenvalues $\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.
+
+
+
+For the sake of simplicity, let us assume that the design matrix is orthonormal, that is
+
+!bt
+\[
+\bm{X}^T\bm{X}=(\bm{X}^T\bm{X})^{-1} =\bm{I}.
+\]
+!et
+
+In this case the standard OLS results in
+!bt
+\[
+\bm{\beta}^{\mathrm{OLS}} = \bm{X}^T\bm{y}=\sum_{i=0}^{p-1}\bm{u}_j\bm{u}_j^T\bm{y},
+\]
+!et
+
+and
+
+!bt
+\[
+\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{I}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}=\left(1+\lambda\right)^{-1}\bm{\beta}^{\mathrm{OLS}},
+\]
+!et
+
+that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\lambda$, and
+the Ridge estimator converges to zero when the hyperparameter goes to
+infinity.
+
+We will come back to more interpreations after we have gone through some of the statistical analysis part.
+
+
+
+Using the matrix-vector expression for Lasso regression and dropping the parameter $1/n$ in front of the standard mean squared error equation, we have the following _cost_ function
+
+!bt
+\[
+C(\bm{X},\bm{\beta})=\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\vert\vert\bm{\beta}\vert\vert_1,
+\]
+!et
+
+Taking the derivative with respect to $\bm{\beta}$ and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)
+!bt
+\[
+\frac{d \vert \beta\vert}{d \bm{\beta}}=\mathrm{sgn}(\bm{\beta})=\left\{\begin{array}{cc} 1 & \beta > 0 \\ 0 & \beta =0\\-1 & \beta < 0, \end{array}\right.
+\]
+!et
+we have that the derivative of the cost function is
+
+!bt
+\[
+\frac{\partial C(\bm{X},\bm{\beta})}{\partial \bm{\beta}}=-2\bm{X}^T(\bm{y}-\bm{X}\bm{\beta})+\lambda sgn(\bm{\beta})=0,
+\]
+!et
+and reordering we have
+!bt
+\[
+\bm{X}^T\bm{X}\bm{\beta}+\lambda sgn(\bm{\beta})=2\bm{X}^T\bm{y}.
+\]
+!et
+This equation does not lead to a nice analytical equation as in 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":"https://cvxopt.org/". We will discuss this later.
+
+
+
+
+
+Let us assume that our design matrix is given by unit (identity) matrix, that is a square diagonal matrix with ones only along the
+diagonal. In this case we have an equal number of rows and columns $n=p$.
+
+Our model approximation is just $\tilde{\bm{y}}=\bm{\beta}$ and the mean squared error and thereby the cost function for ordinary least sqquares (OLS) is then (we drop the term $1/n$)
+!bt
+\[
+C(\bm{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2,
+\]
+!et
+and minimizing we have that
+!bt
+\[
+\hat{\beta}_i^{\mathrm{OLS}} = y_i.
+\]
+!et
+
+
+For Ridge regression our cost function is
+!bt
+\[
+C(\bm{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\beta_i^2,
+\]
+!et
+and minimizing we have that
+!bt
+\[
+\hat{\beta}_i^{\mathrm{Ridge}} = \frac{y_i}{1+\lambda}.
+\]
+!et
+
+
+For Lasso regression our cost function is
+!bt
+\[
+C(\bm{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\vert\beta_i\vert=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\sqrt{\beta_i^2},
+\]
+!et
+and minimizing we have that
+!bt
+\[
+-2\sum_{i=0}^{p-1}(y_i-\beta_i)+\lambda \sum_{i=0}^{p-1}\frac{(\beta_i)}{\vert\beta_i\vert}=0,
+\]
+!et
+which leads to
+!bt
+\[
+\hat{\bm{\beta}}_i^{\mathrm{Lasso}} = \left\{\begin{array}{ccc}y_i-\frac{\lambda}{2} &\mathrm{if} & y_i> \frac{\lambda}{2}\\
+ y_i+\frac{\lambda}{2} &\mathrm{if} & y_i< -\frac{\lambda}{2}\\
+ 0 &\mathrm{if} & \vert y_i\vert\le \frac{\lambda}{2}\end{array}\right.\\.
+\]
+!et
+
+Plotting these results ("figure in handwritten notes for week 36":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2021/NotesSeptember9.pdf") shows clearly that Lasso regression suppresses (sets to zero) values of $\beta_i$ for specific values of $\lambda$. Ridge regression reduces on the other hand the values of $\beta_i$ as function of $\lambda$.
+
+
+As another examples,
+let us assume we have a data set with outputs/targets given by the vector
+
+!bt
+\[
+\bm{y}=\begin{bmatrix}4 \\ 2 \\3\end{bmatrix},
+\]
+!et
+and our inputs as a $3\times 2$ design matrix
+!bt
+\[
+\bm{X}=\begin{bmatrix}2 & 0\\ 0 & 1 \\ 0 & 0\end{bmatrix},
+\]
+!et
+meaning that we have two features and two unknown parameters $\beta_0$ and $\beta_1$ to be determined either by ordinary least squares, Ridge or Lasso regression.
+
+
+For ordinary least squares (OLS) we know that the optimal solution is
+
+!bt
+\[
+\hat{\bm{\beta}}^{\mathrm{OLS}}=\left( \bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}.
+\]
+!et
+Inserting the above values we obtain that
+
+!bt
+\[
+\hat{\bm{\beta}}^{\mathrm{OLS}}=\begin{bmatrix}2 \\ 2\end{bmatrix},
+\]
+!et
+
+The code which implements this simpler case is presented after the discussion of Ridge and Lasso.
+
+
+For Ridge regression we have
+
+!bt
+\[
+\hat{\bm{\beta}}^{\mathrm{Ridge}}=\left( \bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}.
+\]
+!et
+Inserting the above values we obtain that
+
+!bt
+\[
+\hat{\bm{\beta}}^{\mathrm{Ridge}}=\begin{bmatrix}\frac{8}{4+\lambda} \\ \frac{2}{1+\lambda}\end{bmatrix},
+\]
+!et
+
+There is normally a constraint on the value of $\vert\vert \bm{\beta}\vert\vert_2$ via the parameter $\lambda$.
+Let us for simplicity assume that $\beta_0^2+\beta_1^2=1$ as constraint. This will allow us to find an expression for the optimal values of $\beta$ and $\lambda$.
+
+To see this, let us write the cost function for Ridge regression.
+
+
+
+We define the MSE without the $1/n$ factor and have then, using that
+!bt
+\[
+\bm{X}\bm{\beta}=\begin{bmatrix} 2\beta_0 \\ \beta_1 \\0 \end{bmatrix},
+\]
+!et
+
+!bt
+\[
+C(\bm{\beta})=(4-2\beta_0)^2+(2-\beta_1)^2+\lambda(\beta_0^2+\beta_1^2),
+\]
+!et
+and taking the derivative with respect to $\beta_0$ we get
+!bt
+\[
+\beta_0=\frac{8}{4+\lambda},
+\]
+!et
+and for $\beta_1$ we obtain
+!bt
+\[
+\beta_1=\frac{2}{1+\lambda},
+\]
+!et
+
+Using the constraint for $\beta_0^2+\beta_1^2=1$ we can constrain $\lambda$ by solving
+!bt
+\[
+\left(\frac{8}{4+\lambda}\right)^2+\left(\frac{2}{1+\lambda}\right)^2=1,
+\]
+!et
+which gives $\lambda=4.571$ and $\beta_0=0.933$ and $\beta_1=0.359$.
+
+
+For Lasso we need now, keeping a constraint on $\vert\beta_0\vert+\vert\beta_1\vert=1$, to take the derivative of the absolute values of $\beta_0$
+and $\beta_1$. This gives us the following derivatives of the cost function
+!bt
+\[
+C(\bm{\beta})=(4-2\beta_0)^2+(2-\beta_1)^2+\lambda(\vert\beta_0\vert+\vert\beta_1\vert),
+\]
+!et
+
+!bt
+\[
+\frac{\partial C(\bm{\beta})}{\partial \beta_0}=-4(4-2\beta_0)+\lambda\mathrm{sgn}(\beta_0)=0,
+\]
+!et
+and
+!bt
+\[
+\frac{\partial C(\bm{\beta})}{\partial \beta_1}=-2(2-\beta_1)+\lambda\mathrm{sgn}(\beta_1)=0.
+\]
+!et
+We have now four cases to solve besides the trivial cases $\beta_0$ and/or $\beta_1$ are zero, namely
+o $\beta_0 > 0$ and $\beta_1 > 0$,
+o $\beta_0 > 0$ and $\beta_1 < 0$,
+o $\beta_0 < 0$ and $\beta_1 > 0$,
+o $\beta_0 < 0$ and $\beta_1 < 0$.
+
+
+If we consider the first case, we have then
+!bt
+\[
+-4(4-2\beta_0)+\lambda=0,
+\]
+!et
+and
+!bt
+\[
+-2(2-\beta_1)+\lambda=0.
+\]
+!et
+which yields
+
+!bt
+\[
+\beta_0=\frac{16+\lambda}{8},
+\]
+!et
+and
+!bt
+\[
+\beta_1=\frac{4+\lambda}{2}.
+\]
+!et
+
+Using the constraint on $\beta_0$ and $\beta_1$ we can then find the optimal value of $\lambda$ for the different cases. We leave this as an exercise to you.
+
+
+Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of $\lambda$, meaning that we need to perform a search in order to find the optimal values.
+
+First we study and compare the OLS and Ridge results. The next code compares all three methods.
+
+
+!bc pycod
+import os
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+
+# A seed just to ensure that the random numbers are the same for every run.
+# Useful for eventual debugging.
+
+X = np.array( [ [ 2, 0], [0, 1], [0,0]])
+y = np.array( [4, 2, 3])
+
+
+# matrix inversion to find beta
+OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y
+print(OLSbeta)
+# and then make the prediction
+ytildeOLS = X @ OLSbeta
+print("Training MSE for OLS")
+print(MSE(y,ytildeOLS))
+ypredictOLS = X @ OLSbeta
+
+# Repeat now for Ridge regression and various values of the regularization parameter
+I = np.eye(2,2)
+# Decide which values of lambda to use
+nlambdas = 100
+MSEPredict = np.zeros(nlambdas)
+lambdas = np.logspace(-4, 4, nlambdas)
+for i in range(nlambdas):
+ lmb = lambdas[i]
+ Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y
+# print(Ridgebeta)
+ # and then make the prediction
+ ypredictRidge = X @ Ridgebeta
+ MSEPredict[i] = MSE(y,ypredictRidge)
+# print(MSEPredict[i])
+ # Now plot the results
+plt.figure()
+plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Train')
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
+
+!ec
+
+We see here that we reach a plateau. What is actually happening?
!bc pycod
-# Common imports
+import os
import numpy as np
import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn import linear_model
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
-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
+# A seed just to ensure that the random numbers are the same for every run.
+# Useful for eventual debugging.
+
+X = np.array( [ [ 2, 0], [0, 1], [0,0]])
+y = np.array( [4, 2, 3])
-def create_X(x, y, n ):
- if len(x.shape) > 1:
- x = np.ravel(x)
- y = np.ravel(y)
+# matrix inversion to find beta
+OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y
+print(OLSbeta)
+# and then make the prediction
+ytildeOLS = X @ OLSbeta
+print("Training MSE for OLS")
+print(MSE(y,ytildeOLS))
+ypredictOLS = X @ OLSbeta
- N = len(x)
- l = int((n+1)*(n+2)/2) # Number of elements in beta
- X = np.ones((N,l))
+# Repeat now for Ridge regression and various values of the regularization parameter
+I = np.eye(2,2)
+# Decide which values of lambda to use
+nlambdas = 100
+MSERidgePredict = np.zeros(nlambdas)
+MSELassoPredict = np.zeros(nlambdas)
+lambdas = np.logspace(-4, 4, nlambdas)
+for i in range(nlambdas):
+ lmb = lambdas[i]
+ Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y
+ print(Ridgebeta)
+ # and then make the prediction
+ ypredictRidge = X @ Ridgebeta
+ MSERidgePredict[i] = MSE(y,ypredictRidge)
+ RegLasso = linear_model.Lasso(lmb)
+ RegLasso.fit(X,y)
+ ypredictLasso = RegLasso.predict(X)
+ print(RegLasso.coef_)
+ MSELassoPredict[i] = MSE(y,ypredictLasso)
+# Now plot the results
+plt.figure()
+plt.plot(np.log10(lambdas), MSERidgePredict, 'r--', label = 'MSE Ridge Train')
+plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Train')
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
- 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)
!ec
-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.
+Another Example, now with a polynomial fit.
+
+!bc pycod
+import os
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.model_selection import train_test_split
+from sklearn import linear_model
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+
+# A seed just to ensure that the random numbers are the same for every run.
+# Useful for eventual debugging.
+np.random.seed(3155)
+
+x = np.random.rand(100)
+y = 2.0+5*x*x+0.1*np.random.randn(100)
+
+# number of features p (here degree of polynomial
+p = 3
+# The design matrix now as function of a given polynomial
+X = np.zeros((len(x),p))
+X[:,0] = 1.0
+X[:,1] = x
+X[:,2] = x*x
+# We split the data in test and training data
+X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
+
+# matrix inversion to find beta
+OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train
+print(OLSbeta)
+# and then make the prediction
+ytildeOLS = X_train @ OLSbeta
+print("Training MSE for OLS")
+print(MSE(y_train,ytildeOLS))
+ypredictOLS = X_test @ OLSbeta
+print("Test MSE OLS")
+print(MSE(y_test,ypredictOLS))
+
+# Repeat now for Lasso and Ridge regression and various values of the regularization parameter
+I = np.eye(p,p)
+# Decide which values of lambda to use
+nlambdas = 100
+MSEPredict = np.zeros(nlambdas)
+MSETrain = np.zeros(nlambdas)
+MSELassoPredict = np.zeros(nlambdas)
+MSELassoTrain = np.zeros(nlambdas)
+lambdas = np.logspace(-4, 4, nlambdas)
+for i in range(nlambdas):
+ lmb = lambdas[i]
+ Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train
+ # include lasso using Scikit-Learn
+ RegLasso = linear_model.Lasso(lmb)
+ RegLasso.fit(X_train,y_train)
+ # and then make the prediction
+ ytildeRidge = X_train @ Ridgebeta
+ ypredictRidge = X_test @ Ridgebeta
+ ytildeLasso = RegLasso.predict(X_train)
+ ypredictLasso = RegLasso.predict(X_test)
+ MSEPredict[i] = MSE(y_test,ypredictRidge)
+ MSETrain[i] = MSE(y_train,ytildeRidge)
+ MSELassoPredict[i] = MSE(y_test,ypredictLasso)
+ MSELassoTrain[i] = MSE(y_train,ytildeLasso)
+
+# Now plot the results
+plt.figure()
+plt.plot(np.log10(lambdas), MSETrain, label = 'MSE Ridge train')
+plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Test')
+plt.plot(np.log10(lambdas), MSELassoTrain, label = 'MSE Lasso train')
+plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Test')
+
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
+
+!ec
+
+
+===== Linking the regression analysis with a statistical interpretation =====
+
+We will now couple the discussions of ordinary least squares, Ridge
+and Lasso regression with a statistical interpretation, that is we
+move from a linear algebra analysis to a statistical analysis. In
+particular, we will focus on what the regularization terms can result
+in. We will amongst other things show that the regularization
+parameter can reduce considerably the variance of the parameters
+$\beta$.
+
+
+The
+advantage of doing linear regression is that we actually end up with
+analytical expressions for several statistical quantities.
+Standard least squares and Ridge regression allow us to
+derive quantities like the variance and other expectation values in a
+rather straightforward way.
+
+
+It is assumed that $\varepsilon_i
+\sim \mathcal{N}(0, \sigma^2)$ and the $\varepsilon_{i}$ are
+independent, i.e.:
+!bt
+\begin{align*}
+\mbox{Cov}(\varepsilon_{i_1},
+\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if}
+& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right.
+\end{align*}
+!et
+The randomness of $\varepsilon_i$ implies that
+$\mathbf{y}_i$ is also a random variable. In particular,
+$\mathbf{y}_i$ is normally distributed, because $\varepsilon_i \sim
+\mathcal{N}(0, \sigma^2)$ and $\mathbf{X}_{i,\ast} \, \bm{\beta}$ is a
+non-random scalar. To specify the parameters of the distribution of
+$\mathbf{y}_i$ we need to calculate its first two moments.
+
+Recall that $\bm{X}$ is a matrix of dimensionality $n\times p$. The
+notation above $\mathbf{X}_{i,\ast}$ means that we are looking at the
+row number $i$ and perform a sum over all values $p$.
-
-We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\bm{X}$ as
+The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off)
+that there exists a function $f(\bm{x})$ and a normal distributed error $\bm{\varepsilon}\sim \mathcal{N}(0, \sigma^2)$
+which describe our data
!bt
\[
-\bm{C}[\bm{x}] = \frac{1}{n}\bm{X}^T\bm{X}= \mathbb{E}[\bm{X}^T\bm{X}].
+\bm{y} = f(\bm{x})+\bm{\varepsilon}
\]
!et
-To see this let us simply look at a design matrix $\bm{X}\in {\mathbb{R}}^{2\times 2}$
+We approximate this function with our model from the solution of the linear regression equations, that is our
+function $f$ is approximated by $\bm{\tilde{y}}$ where we want to minimize $(\bm{y}-\bm{\tilde{y}})^2$, our MSE, with
!bt
\[
-\bm{X}=\begin{bmatrix}
-x_{00} & x_{01}\\
-x_{10} & x_{11}\\
-\end{bmatrix}=\begin{bmatrix}
-\bm{x}_{0} & \bm{x}_{1}\\
-\end{bmatrix}.
+\bm{\tilde{y}} = \bm{X}\bm{\beta}.
\]
!et
-If we then compute the expectation value
+
+We can calculate the expectation value of $\bm{y}$ for a given element $i$
+!bt
+\begin{align*}
+\mathbb{E}(y_i) & =
+\mathbb{E}(\mathbf{X}_{i, \ast} \, \bm{\beta}) + \mathbb{E}(\varepsilon_i)
+\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta,
+\end{align*}
+!et
+while
+its variance is
+!bt
+\begin{align*} \mbox{Var}(y_i) & = \mathbb{E} \{ [y_i
+- \mathbb{E}(y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( y_i^2 ) -
+[\mathbb{E}(y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \,
+\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \bm{\beta})^2 \\ &
+= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \bm{\beta})^2 + 2 \varepsilon_i
+\mathbf{X}_{i, \ast} \, \bm{\beta} + \varepsilon_i^2 ] - ( \mathbf{X}_{i,
+\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \bm{\beta})^2 + 2
+\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \bm{\beta} +
+\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \bm{\beta})^2
+\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \,
+\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2.
+\end{align*}
+!et
+Hence, $y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \bm{\beta}, \sigma^2)$, that is $\bm{y}$ follows a normal distribution with
+mean value $\bm{X}\bm{\beta}$ and variance $\sigma^2$ (not be confused with the singular values of the SVD).
+
+
+With the OLS expressions for the parameters $\bm{\beta}$ we can evaluate the expectation value
!bt
\[
-\mathbb{E}[\bm{X}^T\bm{X}] = \frac{1}{n}\bm{X}^T\bm{X}=\begin{bmatrix}
-x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\
-x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\
-\end{bmatrix},
+\mathbb{E}(\bm{\beta}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\bm{\beta}=\bm{\beta}.
\]
!et
-which is just
+This means that the estimator of the regression parameters is unbiased.
+
+We can also calculate the variance
+
+The variance of $\bm{\beta}$ is
+!bt
+\begin{eqnarray*}
+\mbox{Var}(\bm{\beta}) & = & \mathbb{E} \{ [\bm{\beta} - \mathbb{E}(\bm{\beta})] [\bm{\beta} - \mathbb{E}(\bm{\beta})]^{T} \}
+\\
+& = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \bm{\beta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \bm{\beta}]^{T} \}
+\\
+% & = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}]^{T} \} - \bm{\beta} \, \bm{\beta}^{T}
+% \\
+% & = & \mathbb{E} \{ (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} \, \mathbf{Y}^{T} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} \} - \bm{\beta} \, \bm{\beta}^{T}
+% \\
+& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \mathbb{E} \{ \mathbf{Y} \, \mathbf{Y}^{T} \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \bm{\beta} \, \bm{\beta}^{T}
+\\
+& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \bm{\beta} \, \bm{\beta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \bm{\beta} \, \bm{\beta}^{T}
+% \\
+% & = & (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \bm{\beta} \, \bm{\beta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1}
+% \\
+% & & + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \bm{\beta} \bm{\beta}^T
+\\
+& = & \bm{\beta} \, \bm{\beta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \bm{\beta} \, \bm{\beta}^{T}
+\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1},
+\end{eqnarray*}
+!et
+
+where we have used that $\mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) =
+\mathbf{X} \, \bm{\beta} \, \bm{\beta}^{T} \, \mathbf{X}^{T} +
+\sigma^2 \, \mathbf{I}_{nn}$. From $\mbox{Var}(\bm{\beta}) = \sigma^2
+\, (\mathbf{X}^{T} \mathbf{X})^{-1}$, one obtains an estimate of the
+variance of the estimate of the $j$-th regression coefficient:
+$\bm{\sigma}^2 (\bm{\beta}_j ) = \bm{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} $. This may be used to
+construct a confidence interval for the estimates.
+
+
+In a similar way, we can obtain analytical expressions for say the
+expectation values of the parameters $\bm{\beta}$ and their variance
+when we employ Ridge regression, allowing us again to define a confidence interval.
+
+It is rather straightforward to show that
!bt
\[
-\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]=\begin{bmatrix} \mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] \\
- \mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] \\
- \end{bmatrix},
+\mathbb{E} \big[ \bm{\beta}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\bm{\beta}^{\mathrm{OLS}}.
\]
!et
-where we wrote $$\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]$$ to indicate that this the covariance of the vectors $\bm{x}$ of the design/feature matrix $\bm{X}$.
+We see clearly that
+$\mathbb{E} \big[ \bm{\beta}^{\mathrm{Ridge}} \big] \not= \bm{\beta}^{\mathrm{OLS}}$ for any $\lambda > 0$. We say then that the ridge estimator is biased.
-It is easy to generalize this to a matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$.
+We can also compute the variance as
+
+!bt
+\[
+\mbox{Var}[\bm{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T},
+\]
+!et
+and it is easy to see that if the parameter $\lambda$ goes to infinity then the variance of Ridge parameters $\bm{\beta}$ goes to zero.
+
+With this, we can compute the difference
+
+!bt
+\[
+\mbox{Var}[\bm{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\bm{\beta}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}.
+\]
+!et
+The difference is non-negative definite since each component of the
+matrix product is non-negative definite.
+This means the variance we obtain with the standard OLS will always for $\lambda > 0$ be larger than the variance of $\bm{\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below.
+
+
+
+===== Deriving OLS from a probability distribution =====
+
+Our basic assumption when we derived the OLS equations was to assume
+that our output is determined by a given continuous function
+$f(\bm{x})$ and a random noise $\bm{\epsilon}$ given by the normal
+distribution with zero mean value and an undetermined variance
+$\sigma^2$.
+
+We found above that the outputs $\bm{y}$ have a mean value given by
+$\bm{X}\hat{\bm{\beta}}$ and variance $\sigma^2$. Since the entries to
+the design matrix are not stochastic variables, we can assume that the
+probability distribution of our targets is also a normal distribution
+but now with mean value $\bm{X}\hat{\bm{\beta}}$. This means that a
+single output $y_i$ is given by the Gaussian distribution
+
+!bt
+\[
+y_i\sim \mathcal{N}(\bm{X}_{i,*}\bm{\beta}, \sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}.
+\]
+!et
+
+
+We assume now that the various $y_i$ values are stochastically distributed according to the above Gaussian distribution.
+We define this distribution as
+!bt
+\[
+p(y_i, \bm{X}\vert\bm{\beta})=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]},
+\]
+!et
+which reads as finding the likelihood of an event $y_i$ with the input variables $\bm{X}$ given the parameters (to be determined) $\bm{\beta}$.
+
+Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event $\bm{y}$ as the product of the single events, that is we have
+
+!bt
+\[
+p(\bm{y},\bm{X}\vert\bm{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\bm{X}\vert\bm{\beta}).
+\]
+!et
+
+We will write this in a more compact form reserving $\bm{D}$ for the domain of events, including the ouputs (targets) and the inputs. That is
+in case we have a simple one-dimensional input and output case
+!bt
+\[
+\bm{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})].
+\]
+!et
+In the more general case the various inputs should be replaced by the possible features represented by the input data set $\bm{X}$.
+We can now rewrite the above probability as
+!bt
+\[
+p(\bm{D}\vert\bm{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}.
+\]
+!et
+
+It is a conditional probability (see below) and reads as the likelihood of a domain of events $\bm{D}$ given a set of parameters $\bm{\beta}$.
+
+
+In statistics, maximum likelihood estimation (MLE) is a method of
+estimating the parameters of an assumed probability distribution,
+given some observed data. This is achieved by maximizing a likelihood
+function so that, under the assumed statistical model, the observed
+data is the most probable.
+
+
+We will assume here that our events are given by the above Gaussian
+distribution and we will determine the optimal parameters $\beta$ by
+maximizing the above PDF. However, computing the derivatives of a
+product function is cumbersome and can easily lead to overflow and/or
+underflowproblems, with potentials for loss of numerical precision.
+
+
+In practice, it is more convenient to maximize the logarithm of the
+PDF because it is a monotonically increasing function of the argument.
+Alternatively, and this will be our option, we will minimize the
+negative of the logarithm since this is a monotonically decreasing
+function.
+
+Note also that maximization/minimization of the logarithm of the PDF
+is equivalent to the maximization/minimization of the function itself.
+
+
+
+
+We could now define a new cost function to minimize, namely the negative logarithm of the above PDF
+
+!bt
+\[
+C(\bm{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\bm{X}\vert\bm{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\bm{X}\vert\bm{\beta})},
+\]
+!et
+which becomes
+!bt
+\[
+C(\bm{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}.
+\]
+!et
+
+Taking the derivative of the *new* cost function with respect to the parameters $\beta$ we recognize our familiar OLS equation, namely
+
+!bt
+\[
+\bm{X}^T\left(\bm{y}-\bm{X}\bm{\beta}\right) =0,
+\]
+!et
+which leads to the well-known OLS equation for the optimal paramters $\beta$
+!bt
+\[
+\hat{\bm{\beta}}^{\mathrm{OLS}}=\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}!
+\]
+!et
+
+
+Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics.
+
+
+A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry.
+Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics.
+
+Assume we have two domains of events $X=[x_0,x_1,\dots,x_{n-1}]$ and $Y=[y_0,y_1,\dots,y_{n-1}]$.
+
+We define also the likelihood for $X$ and $Y$ as $p(X)$ and $p(Y)$ respectively.
+The likelihood of a specific event $x_i$ (or $y_i$) is then written as $p(X=x_i)$ or just $p(x_i)=p_i$.
+
+!bblock Union of events is given by
+!bt
+\[
+p(X \cup Y)= p(X)+p(Y)-p(X \cap Y).
+\]
+!et
+!eblock
+
+
+!bblock The product rule (aka joint probability) is given by
+!bt
+\[
+p(X \cup Y)= p(X,Y)= p(X\vert Y)p(Y)=p(Y\vert X)p(X),
+\]
+!et
+where we read $p(X\vert Y)$ as the likelihood of obtaining $X$ given $Y$.
+!eblock
+
+If we have independent events then $p(X,Y)=p(X)p(Y)$.
+
+
+
+The marginal probability is defined in terms of only one of the set of variables $X,Y$. For a discrete probability we have
+!bblock
+!bt
+\[
+p(X)=\sum_{i=0}^{n-1}p(X,Y=y_i)=\sum_{i=0}^{n-1}p(X\vert Y=y_i)p(Y=y_i)=\sum_{i=0}^{n-1}p(X\vert y_i)p(y_i).
+\]
+!et
+!eblock
+
+
+
+The conditional probability, if $p(Y) > 0$, is
+!bblock
+!bt
+\[
+p(X\vert Y)= \frac{p(X,Y)}{p(Y)}=\frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}.
+\]
+!et
+!eblock
+
+
+
+If we combine the conditional probability with the marginal probability and the standard product rule, we have
+!bt
+\[
+p(X\vert Y)= \frac{p(X,Y)}{p(Y)},
+\]
+!et
+which we can rewrite as
+
+!bt
+\[
+p(X\vert Y)= \frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}=\frac{p(Y\vert X)p(X)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)},
+\]
+!et
+which is Bayes' theorem. It allows us to evaluate the uncertainty in in $X$ after we have observed $Y$. We can easily interchange $X$ with $Y$.
+
+
+The quantity $p(Y\vert X)$ on the right-hand side of the theorem is
+evaluated for the observed data $Y$ and can be viewed as a function of
+the parameter space represented by $X$. This function is not
+necesseraly normalized and is normally called the likelihood function.
+
+The function $p(X)$ on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution.
+
+Let us try to illustrate Bayes' theorem through an example.
+
+
+Let us suppose that you are undergoing a series of mammography scans in
+order to rule out possible breast cancer cases. We define the
+sensitivity for a positive event by the variable $X$. It takes binary
+values with $X=1$ representing a positive event and $X=0$ being a
+negative event. We reserve $Y$ as a classification parameter for
+either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing).
+
+We let $Y=1$ represent the the case of having breast cancer and $Y=0$ as not.
+
+Let us assume that if you have breast cancer, the test will be positive with a probability of $0.8$, that is we have
+
+!bt
+\[
+p(X=1\vert Y=1) =0.8.
+\]
+!et
+
+This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of $80\%$ for having cancer.
+It is however not correct, as the following Bayesian analysis shows.
+
+
+If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number.
+Let us assume that the prior probability in the population as a whole is
+
+!bt
+\[
+p(Y=1) =0.004.
+\]
+!et
+
+We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have
+!bt
+\[
+p(X=1\vert Y=0) =0.1.
+\]
+!et
+
+Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute
+
+!bt
+\[
+p(Y=1\vert X=1)=\frac{p(X=1\vert Y=1)p(Y=1)}{p(X=1\vert Y=1)p(Y=1)+p(X=1\vert Y=0)p(Y=0)}=\frac{0.8\times 0.004}{0.8\times 0.004+0.1\times 0.996}=0.031.
+\]
+!et
+That is, in case of a positive test, there is only a $3\%$ chance of having breast cancer!
+
+
+
+===== Bayes' Theorem and Ridge and Lasso Regression =====
+
+Hitherto we have discussed Ridge and Lasso regression in terms of a
+linear analysis. This may to many of you feel rather technical and
+perhaps not that intuitive. The question is whether we can develop a
+more intuitive way of understanding what Ridge and Lasso express.
+
+Before we proceed let us perform a Ridge, Lasso and OLS analysis of a polynomial fit.
+
+
+We will play around with a study of the values for the optimal
+parameters $\bm{\beta}$ using OLS, Ridge and Lasso regression. For
+OLS, you will notice as function of the noise and polynomial degree,
+that the parameters $\beta$ will fluctuate from order to order in the
+polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS.
+
+For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one.
+
+!bc pycod
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.model_selection import train_test_split
+from sklearn import linear_model
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+# Make data set.
+n = 10000
+x = np.random.rand(n)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
+
+Maxpolydegree = 5
+X = np.zeros((len(x),Maxpolydegree))
+X[:,0] = 1.0
+
+for polydegree in range(1, Maxpolydegree):
+ for degree in range(polydegree):
+ X[:,degree] = x**(degree)
+
+
+# We split the data in test and training data
+X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
+
+# matrix inversion to find beta
+OLSbeta = np.linalg.pinv(X_train.T @ X_train) @ X_train.T @ y_train
+print(OLSbeta)
+ypredictOLS = X_test @ OLSbeta
+print("Test MSE OLS")
+print(MSE(y_test,ypredictOLS))
+# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn
+# Decide which values of lambda to use
+nlambdas = 4
+MSERidgePredict = np.zeros(nlambdas)
+MSELassoPredict = np.zeros(nlambdas)
+lambdas = np.logspace(-3, 1, nlambdas)
+for i in range(nlambdas):
+ lmb = lambdas[i]
+ # Make the fit using Ridge and Lasso
+ RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
+ RegRidge.fit(X_train,y_train)
+ RegLasso = linear_model.Lasso(lmb,fit_intercept=False)
+ RegLasso.fit(X_train,y_train)
+ # and then make the prediction
+ ypredictRidge = RegRidge.predict(X_test)
+ ypredictLasso = RegLasso.predict(X_test)
+ # Compute the MSE and print it
+ MSERidgePredict[i] = MSE(y_test,ypredictRidge)
+ MSELassoPredict[i] = MSE(y_test,ypredictLasso)
+ print(lmb,RegRidge.coef_)
+ print(lmb,RegLasso.coef_)
+# Now plot the results
+plt.figure()
+plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')
+plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
+
+
+!ec
+
+How can we understand this?
+
+
+
+Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression.
+
+For ordinary least squares we postulated that the maximum likelihood for the doamin of events $\bm{D}$ (one-dimensional case)
+!bt
+\[
+\bm{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})],
+\]
+!et
+is given by
+!bt
+\[
+p(\bm{D}\vert\bm{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}.
+\]
+!et
+
+In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set $\bm{\beta}$ given a domain of events $\bm{D}$? That is, how can we define the posterior probability
+
+!bt
+\[
+p(\bm{\beta}\vert\bm{D}).
+\]
+!et
+
+Bayes' theorem comes to our rescue here since (omitting the normalization constant)
+!bt
+\[
+p(\bm{\beta}\vert\bm{D})\propto p(\bm{D}\vert\bm{\beta})p(\bm{\beta}).
+\]
+!et
+
+We have a model for $p(\bm{D}\vert\bm{\beta})$ but need one for the _prior_ $p(\bm{\beta}$!
+
+
+
+With the posterior probability defined by a likelihood which we have
+already modeled and an unknown prior, we are now ready to make
+additional models for the prior.
+
+We can, based on our discussions of the variance of $\bm{\beta}$ and the mean value, assume that the prior for the values $\bm{\beta}$ is given by a Gaussian with mean value zero and variance $\tau^2$, that is
+
+!bt
+\[
+p(\bm{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}.
+\]
+!et
+
+Our posterior probability becomes then (omitting the normalization factor which is just a constant)
+!bt
+\[
+p(\bm{\beta\vert\bm{D})}=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}.
+\]
+!et
+
+
+We can now optimize this quantity with respect to $\bm{\beta}$. As we
+did for OLS, this is most conveniently done by taking the negative
+logarithm of the posterior probability. Doing so and leaving out the
+constants terms that do not depend on $\beta$, we have
+
+
+!bt
+\[
+C(\bm{\beta})=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{2\tau^2}\vert\vert\bm{\beta}\vert\vert_2^2,
+\]
+!et
+and replacing $1/2\tau^2$ with $\lambda$ we have
+
+!bt
+\[
+C(\bm{\beta})=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\bm{\beta}\vert\vert_2^2,
+\]
+!et
+which is our Ridge cost function! Nice, isn't it?
+
+
+To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution ("Laplace in this case":"https://en.wikipedia.org/wiki/Laplace_distribution") with zero mean value, that is
+
+!bt
+\[
+p(\bm{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}.
+\]
+!et
+
+Our posterior probability becomes then (omitting the normalization factor which is just a constant)
+!bt
+\[
+p(\bm{\beta}\vert\bm{D})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}.
+\]
+!et
+
+
+Taking the negative
+logarithm of the posterior probability and leaving out the
+constants terms that do not depend on $\beta$, we have
+
+
+!bt
+\[
+C(\bm{\beta}=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{\tau}\vert\vert\bm{\beta}\vert\vert_1,
+\]
+!et
+and replacing $1/\tau$ with $\lambda$ we have
+
+!bt
+\[
+C(\bm{\beta}=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\bm{\beta}\vert\vert_1,
+\]
+!et
+which is our Lasso cost function!
-===== Linking with SVD =====
diff --git a/doc/LectureNotes/_build/.doctrees/chapter2.doctree b/doc/LectureNotes/_build/.doctrees/chapter2.doctree
index 545f752d2..f7c32732c 100644
Binary files a/doc/LectureNotes/_build/.doctrees/chapter2.doctree and b/doc/LectureNotes/_build/.doctrees/chapter2.doctree differ
diff --git a/doc/LectureNotes/_build/.doctrees/chapter3.doctree b/doc/LectureNotes/_build/.doctrees/chapter3.doctree
index 05a4fe75e..ceb0eabba 100644
Binary files a/doc/LectureNotes/_build/.doctrees/chapter3.doctree and b/doc/LectureNotes/_build/.doctrees/chapter3.doctree differ
diff --git a/doc/LectureNotes/_build/.doctrees/environment.pickle b/doc/LectureNotes/_build/.doctrees/environment.pickle
index 141148dec..434f41d71 100644
Binary files a/doc/LectureNotes/_build/.doctrees/environment.pickle and b/doc/LectureNotes/_build/.doctrees/environment.pickle differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter3_25_2.png b/doc/LectureNotes/_build/html/_images/chapter3_25_2.png
new file mode 100644
index 000000000..98e9e3a97
Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter3_25_2.png differ
diff --git a/doc/LectureNotes/_build/html/_sources/chapter2.ipynb b/doc/LectureNotes/_build/html/_sources/chapter2.ipynb
index d7f8222d5..1c18a18a0 100644
--- a/doc/LectureNotes/_build/html/_sources/chapter2.ipynb
+++ b/doc/LectureNotes/_build/html/_sources/chapter2.ipynb
@@ -4,66 +4,3340 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "# Resampling Methods\n",
- "\n",
- "## Introduction\n",
- "\n",
- "Resampling methods are an indispensable tool in modern\n",
- "statistics. They involve repeatedly drawing samples from a training\n",
- "set and refitting a model of interest on each sample in order to\n",
- "obtain additional information about the fitted model. For example, in\n",
- "order to estimate the variability of a linear regression fit, we can\n",
- "repeatedly draw different samples from the training data, fit a linear\n",
- "regression to each new sample, and then examine the extent to which\n",
- "the resulting fits differ. Such an approach may allow us to obtain\n",
- "information that would not be available from fitting the model only\n",
- "once using the original training sample.\n",
- "\n",
- "Two resampling methods are often used in Machine Learning analyses,\n",
- "1. The **bootstrap method**\n",
- "\n",
- "2. and **Cross-Validation**\n",
- "\n",
- "In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular\n",
- "cross-validation and the bootstrap method. \n",
+ "# Ridge and Lasso Regression\n",
"\n",
"\n",
- "Resampling approaches can be computationally expensive, because they\n",
- "involve fitting the same statistical method multiple times using\n",
- "different subsets of the training data. However, due to recent\n",
- "advances in computing power, the computational requirements of\n",
- "resampling methods generally are not prohibitive. In this chapter, we\n",
- "discuss two of the most commonly used resampling methods,\n",
- "cross-validation and the bootstrap. Both methods are important tools\n",
- "in the practical application of many statistical learning\n",
- "procedures. For example, cross-validation can be used to estimate the\n",
- "test error associated with a given statistical learning method in\n",
- "order to evaluate its performance, or to select the appropriate level\n",
- "of flexibility. The process of evaluating a model’s performance is\n",
- "known as model assessment, whereas the process of selecting the proper\n",
- "level of flexibility for a model is known as model selection. The\n",
- "bootstrap is widely used.\n",
+ "\n",
+ "## Mathematical Interpretation of Ordinary Least Squares\n",
+ "\n",
+ "What is presented here is a mathematical analysis of various regression algorithms (ordinary least squares, Ridge and Lasso Regression). The analysis is based on an important algorithm in linear algebra, the so-called Singular Value Decomposition (SVD). \n",
"\n",
"\n",
- "* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods\n",
+ "We have shown that in ordinary least squares the optimal parameters $\\beta$ are given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The **hat** over $\\boldsymbol{\\beta}$ means we have the optimal parameters after minimization of the cost function.\n",
"\n",
- "* The results can be analysed with the same statistical tools as we would use analysing experimental data.\n",
- "\n",
- "* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n",
- "\n",
- "## Reminder on Statistics\n",
+ "This means that our best model is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}=\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}} = \\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We now define a matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can rewrite"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}=\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}} = \\boldsymbol{A}\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The matrix $\\boldsymbol{A}$ has the important property that $\\boldsymbol{A}^2=\\boldsymbol{A}$. This is the definition of a projection matrix.\n",
+ "We can then interpret our optimal model $\\tilde{\\boldsymbol{y}}$ as being represented by an orthogonal projection of $\\boldsymbol{y}$ onto a space defined by the column vectors of $\\boldsymbol{X}$. In our case here the matrix $\\boldsymbol{A}$ is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix.\n",
"\n",
"\n",
- "* As in other experiments, many numerical experiments have two classes of errors:\n",
- "\n",
- " * Statistical errors\n",
- "\n",
- " * Systematical errors\n",
"\n",
"\n",
- "* Statistical errors can be estimated using standard tools from statistics\n",
+ "We have defined the residual error as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\epsilon}=\\boldsymbol{y}-\\tilde{\\boldsymbol{y}}=\\left[\\boldsymbol{I}-\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\right]\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The residual errors are then the projections of $\\boldsymbol{y}$ onto the orthogonal component of the space defined by the column vectors of $\\boldsymbol{X}$.\n",
+ "\n",
+ "\n",
+ "If the matrix $\\boldsymbol{X}$ is an orthogonal (or unitary in case of complex values) matrix, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{X}\\boldsymbol{X}^T = \\boldsymbol{I}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this case the matrix $\\boldsymbol{A}$ becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T)=\\boldsymbol{I},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and we have the obvious case"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\epsilon}=\\boldsymbol{y}-\\tilde{\\boldsymbol{y}}=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This serves also as a useful test of our codes. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## The singular value decomposition\n",
+ "\n",
+ "\n",
+ "The examples we have looked at so far are cases where we normally can\n",
+ "invert the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$. Using a polynomial expansion where we fit of various functions leads to\n",
+ "row vectors of the design matrix which are essentially orthogonal due\n",
+ "to the polynomial character of our model. Obtaining the inverse of the\n",
+ "design matrix is then often done via a so-called LU, QR or Cholesky\n",
+ "decomposition.\n",
+ "\n",
+ "\n",
+ "As we will also see in the first project, \n",
+ "this may\n",
+ "however not the be case in general and a standard matrix inversion\n",
+ "algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.\n",
+ "\n",
+ "There is however a way to circumvent this problem and also\n",
+ "gain some insights about the ordinary least squares approach, and\n",
+ "later shrinkage methods like Ridge and Lasso regressions.\n",
+ "\n",
+ "This is given by the **Singular Value Decomposition** (SVD) algorithm,\n",
+ "perhaps the most powerful linear algebra algorithm. The SVD provides\n",
+ "a numerically stable matrix decomposition that is used in a large\n",
+ "swath oc applications and the decomposition is always stable\n",
+ "numerically.\n",
+ "\n",
+ "In machine learning it plays a central role in dealing with for\n",
+ "example design matrices that may be near singular or singular.\n",
+ "Furthermore, as we will see here, the singular values can be related\n",
+ "to the covariance matrix (and thereby the correlation matrix) and in\n",
+ "turn the variance of a given quantity. It plays also an important role\n",
+ "in the principal component analysis where high-dimensional data can be\n",
+ "reduced to the statistically relevant features.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "One of the typical problems we encounter with linear regression, in particular \n",
+ "when the matrix $\\boldsymbol{X}$ (our so-called design matrix) is high-dimensional, \n",
+ "are problems with near singular or singular matrices. The column vectors of $\\boldsymbol{X}$ \n",
+ "may be linearly dependent, normally referred to as super-collinearity. \n",
+ "This means that the matrix may be rank deficient and it is basically impossible to \n",
+ "to model the data using linear regression. As an example, consider the matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\mathbf{X} & = \\left[\n",
+ "\\begin{array}{rrr}\n",
+ "1 & -1 & 2\n",
+ "\\\\\n",
+ "1 & 0 & 1\n",
+ "\\\\\n",
+ "1 & 2 & -1\n",
+ "\\\\\n",
+ "1 & 1 & 0\n",
+ "\\end{array} \\right]\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The columns of $\\boldsymbol{X}$ are linearly dependent. We see this easily since the \n",
+ "the first column is the row-wise sum of the other two columns. The rank (more correct,\n",
+ "the column rank) of a matrix is the dimension of the space spanned by the\n",
+ "column vectors. Hence, the rank of $\\mathbf{X}$ is equal to the number\n",
+ "of linearly independent columns. In this particular case the matrix has rank 2.\n",
+ "\n",
+ "Super-collinearity of an $(n \\times p)$-dimensional design matrix $\\mathbf{X}$ implies\n",
+ "that the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\boldsymbol{X} & = \\left[\n",
+ "\\begin{array}{rr}\n",
+ "1 & -1\n",
+ "\\\\\n",
+ "1 & -1\n",
+ "\\end{array} \\right].\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see easily that $\\mbox{det}(\\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \\times (-1) - 1 \\times (-1) = 0$. Hence, $\\mathbf{X}$ is singular and its inverse is undefined.\n",
+ "This is equivalent to saying that the matrix $\\boldsymbol{X}$ has at least an eigenvalue which is zero.\n",
+ "\n",
+ "\n",
+ "\n",
+ "If our design matrix $\\boldsymbol{X}$ which enters the linear regression problem"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "
\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\boldsymbol{\\beta} = (\\boldsymbol{X}^{T} \\boldsymbol{X})^{-1} \\boldsymbol{X}^{T} \\boldsymbol{y},\n",
+ "\\label{_auto1} \\tag{1}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "has linearly dependent column vectors, we will not be able to compute the inverse\n",
+ "of $\\boldsymbol{X}^T\\boldsymbol{X}$ and we cannot find the parameters (estimators) $\\beta_i$. \n",
+ "The estimators are only well-defined if $(\\boldsymbol{X}^{T}\\boldsymbol{X})^{-1}$ exits. \n",
+ "This is more likely to happen when the matrix $\\boldsymbol{X}$ is high-dimensional. In this case it is likely to encounter a situation where \n",
+ "the regression parameters $\\beta_i$ cannot be estimated.\n",
+ "\n",
+ "A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^{T} \\boldsymbol{X} \\rightarrow \\boldsymbol{X}^{T} \\boldsymbol{X}+\\lambda \\boldsymbol{I},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\boldsymbol{I}$ is the identity matrix. When we discuss **Ridge** regression this is actually what we end up evaluating. The parameter $\\lambda$ is called a hyperparameter. More about this later. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Basic math of the SVD\n",
+ "\n",
+ "\n",
+ "From standard linear algebra we know that a square matrix $\\boldsymbol{X}$ can be diagonalized if and only it is \n",
+ "a so-called [normal matrix](https://en.wikipedia.org/wiki/Normal_matrix), that is if $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$\n",
+ "we have $\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ or if $\\boldsymbol{X}\\in {\\mathbb{C}}^{n\\times n}$ we have $\\boldsymbol{X}\\boldsymbol{X}^{\\dagger}=\\boldsymbol{X}^{\\dagger}\\boldsymbol{X}$.\n",
+ "The matrix has then a set of eigenpairs"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "(\\lambda_1,\\boldsymbol{u}_1),\\dots, (\\lambda_n,\\boldsymbol{u}_n),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and the eigenvalues are given by the diagonal matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}=\\mathrm{Diag}(\\lambda_1, \\dots,\\lambda_n).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The matrix $\\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\\boldsymbol{U}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ or $\\boldsymbol{U}\\boldsymbol{U}^{\\dagger}=\\boldsymbol{I}$.\n",
+ "\n",
+ "Not all square matrices are diagonalizable. A matrix like the one discussed above"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\begin{bmatrix} \n",
+ "1& -1 \\\\\n",
+ "1& -1\\\\\n",
+ "\\end{bmatrix}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "is not diagonalizable, it is a so-called [defective matrix](https://en.wikipedia.org/wiki/Defective_matrix). It is easy to see that the condition\n",
+ "$\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ is not fulfilled. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "However, and this is the strength of the SVD algorithm, any general\n",
+ "matrix $\\boldsymbol{X}$ can be decomposed in terms of a diagonal matrix and\n",
+ "two orthogonal/unitary matrices. The [Singular Value Decompostion\n",
+ "(SVD) theorem](https://en.wikipedia.org/wiki/Singular_value_decomposition)\n",
+ "states that a general $m\\times n$ matrix $\\boldsymbol{X}$ can be written in\n",
+ "terms of a diagonal matrix $\\boldsymbol{\\Sigma}$ of dimensionality $m\\times n$\n",
+ "and two orthognal matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$, where the first has\n",
+ "dimensionality $m \\times m$ and the last dimensionality $n\\times n$.\n",
+ "We have then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As an example, the above defective matrix can be decomposed as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& 1 \\\\ 1& -1\\\\ \\end{bmatrix} \\begin{bmatrix} 2& 0 \\\\ 0& 0\\\\ \\end{bmatrix} \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& -1 \\\\ 1& 1\\\\ \\end{bmatrix}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with eigenvalues $\\sigma_1=2$ and $\\sigma_2=0$. \n",
+ "The SVD exits always! \n",
+ "\n",
+ "The SVD\n",
+ "decomposition (singular values) gives eigenvalues \n",
+ "$\\sigma_i\\geq\\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=p$, the\n",
+ "eigenvalues (singular values) are zero.\n",
+ "\n",
+ "In the general case, where our design matrix $\\boldsymbol{X}$ has dimension\n",
+ "$n\\times p$, the matrix is thus decomposed into an $n\\times n$\n",
+ "orthogonal matrix $\\boldsymbol{U}$, a $p\\times p$ orthogonal matrix $\\boldsymbol{V}$\n",
+ "and a diagonal matrix $\\boldsymbol{\\Sigma}$ with $r=\\mathrm{min}(n,p)$\n",
+ "singular values $\\sigma_i\\geq 0$ on the main diagonal and zeros filling\n",
+ "the rest of the matrix. There are at most $p$ singular values\n",
+ "assuming that $n > p$. In our regression examples for the nuclear\n",
+ "masses and the equation of state this is indeed the case, while for\n",
+ "the Ising model we have $p > n$. These are often cases that lead to\n",
+ "near singular or singular matrices.\n",
+ "\n",
+ "The columns of $\\boldsymbol{U}$ are called the left singular vectors while the columns of $\\boldsymbol{V}$ are the right singular vectors.\n",
+ "\n",
+ "\n",
+ "If we assume that $n > p$, then our matrix $\\boldsymbol{U}$ has dimension $n\n",
+ "\\times n$. The last $n-p$ columns of $\\boldsymbol{U}$ become however\n",
+ "irrelevant in our calculations since they are multiplied with the\n",
+ "zeros in $\\boldsymbol{\\Sigma}$.\n",
+ "\n",
+ "The economy-size decomposition removes extra rows or columns of zeros\n",
+ "from the diagonal matrix of singular values, $\\boldsymbol{\\Sigma}$, along with the columns\n",
+ "in either $\\boldsymbol{U}$ or $\\boldsymbol{V}$ that multiply those zeros in the expression. \n",
+ "Removing these zeros and columns can improve execution time\n",
+ "and reduce storage requirements without compromising the accuracy of\n",
+ "the decomposition.\n",
+ "\n",
+ "If $n > p$, we keep only the first $p$ columns of $\\boldsymbol{U}$ and $\\boldsymbol{\\Sigma}$ has dimension $p\\times p$. \n",
+ "If $p > n$, then only the first $n$ columns of $\\boldsymbol{V}$ are computed and $\\boldsymbol{\\Sigma}$ has dimension $n\\times n$.\n",
+ "The $n=p$ case is obvious, we retain the full SVD. \n",
+ "In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.\n",
+ "\n",
+ "## Codes for the SVD"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "# SVD inversion\n",
+ "def SVD(A):\n",
+ " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n",
+ " SVD is numerically more stable than the inversion algorithms provided by\n",
+ " numpy and scipy.linalg at the cost of being slower.\n",
+ " '''\n",
+ " U, S, VT = np.linalg.svd(A,full_matrices=True)\n",
+ " print('test U')\n",
+ " print( (np.transpose(U) @ U - U @np.transpose(U)))\n",
+ " print('test VT')\n",
+ " print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n",
+ " print(U)\n",
+ " print(S)\n",
+ " print(VT)\n",
+ "\n",
+ " D = np.zeros((len(U),len(VT)))\n",
+ " for i in range(0,len(VT)):\n",
+ " D[i,i]=S[i]\n",
+ " return U @ D @ VT\n",
+ "\n",
+ "\n",
+ "X = np.array([ [1.0,-1.0], [1.0,-1.0]])\n",
+ "#X = np.array([[1, 2], [3, 4], [5, 6]])\n",
+ "\n",
+ "print(X)\n",
+ "C = SVD(X)\n",
+ "# Print the difference between the original matrix and the SVD one\n",
+ "print(C-X)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The matrix $\\boldsymbol{X}$ has columns that are linearly dependent. The first\n",
+ "column is the row-wise sum of the other two columns. The rank of a\n",
+ "matrix (the column rank) is the dimension of space spanned by the\n",
+ "column vectors. The rank of the matrix is the number of linearly\n",
+ "independent columns, in this case just $2$. We see this from the\n",
+ "singular values when running the above code. Running the standard\n",
+ "inversion algorithm for matrix inversion with $\\boldsymbol{X}^T\\boldsymbol{X}$ results\n",
+ "in the program terminating due to a singular matrix.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The $U$, $S$, and $V$ matrices returned from the **svd()** function\n",
+ "cannot be multiplied directly.\n",
+ "\n",
+ "As you can see from the code, the $S$ vector must be converted into a\n",
+ "diagonal matrix. This may cause a problem as the size of the matrices\n",
+ "do not fit the rules of matrix multiplication, where the number of\n",
+ "columns in a matrix must match the number of rows in the subsequent\n",
+ "matrix.\n",
+ "\n",
+ "If you wish to include the zero singular values, you will need to\n",
+ "resize the matrices and set up a diagonal matrix as done in the above\n",
+ "example\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Mathematics of the SVD and implications\n",
+ "\n",
+ "Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies.\n",
+ "\n",
+ "Our starting point is our design matrix $\\boldsymbol{X}$ of dimension $n\\times p$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}\n",
+ "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
+ "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
+ "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
+ "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
+ "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
+ "\\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can SVD decompose our matrix as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\boldsymbol{U}$ is an orthogonal matrix of dimension $n\\times n$, meaning that $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{U}^T\\boldsymbol{U}=\\boldsymbol{I}_n$. Here $\\boldsymbol{I}_n$ is the unit matrix of dimension $n \\times n$.\n",
+ "\n",
+ "Similarly, $\\boldsymbol{V}$ is an orthogonal matrix of dimension $p\\times p$, meaning that $\\boldsymbol{V}\\boldsymbol{V}^T=\\boldsymbol{V}^T\\boldsymbol{V}=\\boldsymbol{I}_p$. Here $\\boldsymbol{I}_n$ is the unit matrix of dimension $p \\times p$.\n",
+ "\n",
+ "Finally $\\boldsymbol{\\Sigma}$ contains the singular values $\\sigma_i$. This matrix has dimension $n\\times p$ and the singular values $\\sigma_i$ are all positive. The non-zero values are ordered in descending order, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma_0 > \\sigma_1 > \\sigma_2 > \\dots > \\sigma_{p-1} > 0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "All values beyond $p-1$ are all zero.\n",
+ "\n",
+ "\n",
+ "As an example, consider the following $3\\times 2$ example for the matrix $\\boldsymbol{\\Sigma}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}=\n",
+ "\\begin{bmatrix}\n",
+ "2& 0 \\\\\n",
+ "0 & 1 \\\\\n",
+ "0 & 0 \\\\\n",
+ "\\end{bmatrix}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The singular values are $\\sigma_0=2$ and $\\sigma_1=1$. It is common to rewrite the matrix $\\boldsymbol{\\Sigma}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}=\n",
+ "\\begin{bmatrix}\n",
+ "\\boldsymbol{\\tilde{\\Sigma}}\\\\\n",
+ "\\boldsymbol{0}\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\tilde{\\Sigma}}=\n",
+ "\\begin{bmatrix}\n",
+ "2& 0 \\\\\n",
+ "0 & 1 \\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "contains only the singular values. Note also (and we will use this below) that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}=\n",
+ "\\begin{bmatrix}\n",
+ "4& 0 \\\\\n",
+ "0 & 1 \\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is a $2\\times 2 $ matrix while"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T=\n",
+ "\\begin{bmatrix}\n",
+ "4& 0 & 0\\\\\n",
+ "0 & 1 & 0\\\\\n",
+ "0 & 0 & 0\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "is a $3\\times 3 $ matrix. The last row and column of this last matrix\n",
+ "contain only zeros. This will have important consequences for our SVD\n",
+ "decomposition of the design matrix.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The matrix that may cause problems for us is $\\boldsymbol{X}^T\\boldsymbol{X}$. Using the SVD we can rewrite this matrix as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and using the orthogonality of the matrix $\\boldsymbol{U}$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We define $\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}=\\tilde{\\boldsymbol{\\Sigma}}^2$ which is a diagonal matrix containing only the singular values squared. It has dimensionality $p \\times p$.\n",
+ "\n",
+ "This means, using the orthogonality of $\\boldsymbol{V}$, that we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\tilde{\\boldsymbol{\\Sigma}}^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can now insert the result for the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ into our equation for ordinary least squares where"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and using our SVD decomposition of $\\boldsymbol{X}$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\tilde{\\boldsymbol{\\Sigma}}^{-2}\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which gives us, using the orthogonality of the matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_i\\boldsymbol{u}^T_j\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note here that when we perform the multiplication of the various matrices, the orthogonal vectors of the matrix $\\boldsymbol{U}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{U}=[\\boldsymbol{u}_0,\\boldsymbol{u}_1,\\dots,\\boldsymbol{u}_{n-1}],\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "that belong to $i>p-1$, result in only zeros when we perform the multiplications. This means that the sum above has non-zero elements only up to $i=p-1$. This corresponds also to the number of singular values (these are all non-zero).\n",
+ "\n",
+ "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}$.\n",
+ "\n",
+ "\n",
+ "## Further properties (important for our analyses later)\n",
+ "\n",
+ "Let us study again $\\boldsymbol{X}^T\\boldsymbol{X}$ in terms of our SVD,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we now multiply from the right with $\\boldsymbol{V}$ (using the orthogonality of $\\boldsymbol{V}$) we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{V}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This means the vectors $\\boldsymbol{v}_i$ of the orthogonal matrix $\\boldsymbol{V}$ are the eigenvectors of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$\n",
+ "with eigenvalues given by the singular values squared, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{v}_i=\\boldsymbol{v}_i\\sigma_i^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Similarly, if we use the SVD decomposition for the matrix $\\boldsymbol{X}\\boldsymbol{X}^T$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we now multiply from the right with $\\boldsymbol{U}$ (using the orthogonality of $\\boldsymbol{U}$) we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}\\boldsymbol{X}^T\\right)\\boldsymbol{U}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This means the vectors $\\boldsymbol{u}_i$ of the orthogonal matrix $\\boldsymbol{U}$ are the eigenvectors of the matrix $\\boldsymbol{X}\\boldsymbol{X}^T$\n",
+ "with eigenvalues given by the singular values squared, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}\\boldsymbol{X}^T\\right)\\boldsymbol{u}_i=\\boldsymbol{u}_i\\sigma_i^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Important note**: we have defined our design matrix $\\boldsymbol{X}$ to be an\n",
+ "$n\\times p$ matrix. In most supervised learning cases we have that $n\n",
+ "\\ge p$, and quite often we have $n >> p$. For linear algebra based methods like ordinary least squares or Ridge regression, this leads to a matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ which is small and thereby easier to handle from a computational point of view (in terms of number of floating point operations).\n",
+ "\n",
+ "In our lectures, the number of columns will\n",
+ "always refer to the number of features in our data set, while the\n",
+ "number of rows represents the number of data inputs. Note that in\n",
+ "other texts you may find the opposite notation. This has consequences\n",
+ "for the definition of for example the covariance matrix and its relation to the SVD.\n",
+ "\n",
+ "\n",
+ "## Meet the Covariance Matrix\n",
+ "\n",
+ "\n",
+ "Before we move on to a discussion of Ridge and Lasso regression, we want to show an important example of the above.\n",
+ "\n",
+ "We have already noted that the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ in ordinary\n",
+ "least squares is proportional to the second derivative of the cost\n",
+ "function, that is we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial^2 C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}^T\\partial \\boldsymbol{\\beta}} =\\frac{2}{n}\\boldsymbol{X}^T\\boldsymbol{X}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This quantity defines was what is called the Hessian matrix (the second derivative of a function we want to optimize).\n",
+ "\n",
+ "The Hessian matrix plays an important role and is defined in this course as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{H}=\\boldsymbol{X}^T\\boldsymbol{X}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The Hessian matrix for ordinary least squares is also proportional to\n",
+ "the covariance matrix. This means also that we can use the SVD to find\n",
+ "the eigenvalues of the covariance matrix and the Hessian matrix in\n",
+ "terms of the singular values. Let us develop these arguments, as they will play an important role in our machine learning studies.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about\n",
+ "the definition of the covariance and the correlation function. These are quantities that play a central role in machine learning methods.\n",
+ "\n",
+ "Suppose we have defined two vectors\n",
+ "$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
+ " \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where for example"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With this definition and recalling that the variance is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we can rewrite the covariance matrix as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
+ " \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n",
+ " \\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**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. \n",
+ "What you will find in essentially all statistics texts are equations\n",
+ "with a factor $1/(n-1)$. This is called [Bessel's correction](https://mathworld.wolfram.com/BesselsCorrection.html). This\n",
+ "method corrects the bias in the estimation of the population variance\n",
+ "and covariance. It also partially corrects the bias in the estimation\n",
+ "of the population standard deviation. If you use a library like\n",
+ "**Scikit-Learn** or **nunmpy's** function calculate the covariance, this\n",
+ "quantity will be computed with a factor $1/(n-1)$.\n",
+ "\n",
+ "\n",
+ "The covariance takes values between zero and infinity and may thus\n",
+ "lead to problems with loss of numerical precision for particularly\n",
+ "large values. It is common to scale the covariance matrix by\n",
+ "introducing instead the correlation matrix defined via the so-called\n",
+ "correlation function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]=\\frac{\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}]}{\\sqrt{\\mathrm{var}[\\boldsymbol{x}] \\mathrm{var}[\\boldsymbol{y}]}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The correlation function is then given by values $\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]\n",
+ "\\in [-1,1]$. This avoids eventual problems with too large values. We\n",
+ "can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n",
+ "and $\\boldsymbol{y}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
+ " \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the above example this is the function we constructed using **pandas**.\n",
+ "\n",
+ "\n",
+ "\n",
+ "In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**\n",
+ "we defined the design/feature matrix $\\boldsymbol{X}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}\n",
+ "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
+ "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
+ "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
+ "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
+ "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ refering to the column numbers and the\n",
+ "entries $n$ being the row elements.\n",
+ "We can rewrite the design/feature matrix in terms of its column vectors as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with a given vector"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{x}_i^T = \\begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \\dots & \\dots x_{n-1,i}\\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With these definitions, we can now rewrite our $2\\times 2$\n",
+ "correlation/covariance matrix in terms of a moe general design/feature\n",
+ "matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$\n",
+ "covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i=0,1,\\dots,p-1$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
+ "\\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}]\\\\\n",
+ "\\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}]\\\\\n",
+ "\\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}]\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\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}]\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and the correlation matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
+ "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}]\\\\\n",
+ "\\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}]\\\\\n",
+ "\\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}]\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\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\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The Numpy function **np.cov** calculates the covariance elements using\n",
+ "the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n",
+ "the exact mean values. The following simple function uses the\n",
+ "**np.vstack** function which takes each vector of dimension $1\\times n$\n",
+ "and produces a $2\\times n$ matrix $\\boldsymbol{W}$\n",
+ "\n",
+ "Note that this assumes you have the features as the rows, and the inputs as columns, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{W} = \\begin{bmatrix} x_0 & x_1 & x_2 & \\dots & x_{n-2} & x_{n-1} \\\\\n",
+ " y_0 & y_1 & y_2 & \\dots & y_{n-2} & y_{n-1} \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which in turn is converted into into the $2\\times 2$ covariance matrix\n",
+ "$\\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate\n",
+ "the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n",
+ "function **np.mean(x)**. We can also extract the eigenvalues of the\n",
+ "covariance matrix through the **np.linalg.eig()** function."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Importing various packages\n",
+ "import numpy as np\n",
+ "n = 100\n",
+ "x = np.random.normal(size=n)\n",
+ "print(np.mean(x))\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "print(np.mean(y))\n",
+ "W = np.vstack((x, y))\n",
+ "C = np.cov(W)\n",
+ "print(C)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The previous example can be converted into the correlation matrix by\n",
+ "simply scaling the matrix elements with the variances. We should also\n",
+ "subtract the mean values for each column. This leads to the following\n",
+ "code which sets up the correlations matrix for the previous example in\n",
+ "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)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "n = 100\n",
+ "# define two vectors \n",
+ "x = np.random.random(size=n)\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "#scaling the x and y vectors \n",
+ "x = x - np.mean(x)\n",
+ "y = y - np.mean(y)\n",
+ "variance_x = np.sum(x@x)/n\n",
+ "variance_y = np.sum(y@y)/n\n",
+ "print(variance_x)\n",
+ "print(variance_y)\n",
+ "cov_xy = np.sum(x@y)/n\n",
+ "cov_xx = np.sum(x@x)/n\n",
+ "cov_yy = np.sum(y@y)/n\n",
+ "C = np.zeros((2,2))\n",
+ "C[0,0]= cov_xx/variance_x\n",
+ "C[1,1]= cov_yy/variance_y\n",
+ "C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n",
+ "C[1,0]= C[0,1]\n",
+ "print(C)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see that the matrix elements along the diagonal are one as they\n",
+ "should be and that the matrix is symmetric. Furthermore, diagonalizing\n",
+ "this matrix we easily see that it is a positive definite matrix.\n",
+ "\n",
+ "The above procedure with **numpy** can be made more compact if we use **pandas**.\n",
+ "\n",
+ "\n",
+ "\n",
+ "We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "n = 10\n",
+ "x = np.random.normal(size=n)\n",
+ "x = x - np.mean(x)\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "y = y - np.mean(y)\n",
+ "# Note that we transpose the matrix in order to stay with our ordering n x p\n",
+ "X = (np.vstack((x, y))).T\n",
+ "print(X)\n",
+ "Xpd = pd.DataFrame(X)\n",
+ "print(Xpd)\n",
+ "correlation_matrix = Xpd.corr()\n",
+ "print(correlation_matrix)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We expand this model to the Franke function discussed earlier."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Common imports\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "\n",
+ "\n",
+ "def FrankeFunction(x,y):\n",
+ "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
+ "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
+ "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
+ "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
+ "\treturn term1 + term2 + term3 + term4\n",
+ "\n",
+ "\n",
+ "def create_X(x, y, n ):\n",
+ "\tif len(x.shape) > 1:\n",
+ "\t\tx = np.ravel(x)\n",
+ "\t\ty = np.ravel(y)\n",
+ "\n",
+ "\tN = len(x)\n",
+ "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n",
+ "\tX = np.ones((N,l))\n",
+ "\n",
+ "\tfor i in range(1,n+1):\n",
+ "\t\tq = int((i)*(i+1)/2)\n",
+ "\t\tfor k in range(i+1):\n",
+ "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n",
+ "\n",
+ "\treturn X\n",
+ "\n",
+ "\n",
+ "# Making meshgrid of datapoints and compute Franke's function\n",
+ "n = 4\n",
+ "N = 100\n",
+ "x = np.sort(np.random.uniform(0, 1, N))\n",
+ "y = np.sort(np.random.uniform(0, 1, N))\n",
+ "z = FrankeFunction(x, y)\n",
+ "X = create_X(x, y, n=n) \n",
+ "\n",
+ "Xpd = pd.DataFrame(X)\n",
+ "# subtract the mean values and set up the covariance matrix\n",
+ "Xpd = Xpd - Xpd.mean()\n",
+ "covariance_matrix = Xpd.cov()\n",
+ "print(covariance_matrix)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We note here that the covariance is zero for the first rows and\n",
+ "columns since all matrix elements in the design matrix were set to one\n",
+ "(we are fitting the function in terms of a polynomial of degree $n$).\n",
+ "\n",
+ "This means that the variance for these elements will be zero and will\n",
+ "cause problems when we set up the correlation matrix. We can simply\n",
+ "drop these elements and construct a correlation\n",
+ "matrix without these elements. \n",
+ "\n",
+ "\n",
+ "\n",
+ "We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\\boldsymbol{X}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}\n",
+ "x_{00} & x_{01}\\\\\n",
+ "x_{10} & x_{11}\\\\\n",
+ "\\end{bmatrix}=\\begin{bmatrix}\n",
+ "\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n",
+ "\\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we then compute the expectation value (note the $1/n$ factor instead of $1/(n-1)$)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}=\\frac{1}{n}\\begin{bmatrix}\n",
+ "x_{00}^2+x_{10}^2 & x_{00}x_{01}+x_{10}x_{11}\\\\\n",
+ "x_{01}x_{00}+x_{11}x_{10} & x_{01}^2+x_{11}^2\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is just"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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] \\\\\n",
+ " \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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}$.\n",
+ "\n",
+ "It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Linking with the SVD\n",
+ "\n",
+ "We saw earlier that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Since the matrices here have dimension $p\\times p$, with $p$ corresponding to the singular values, we defined earlier the matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma} = \\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0}\\\\ \\end{bmatrix}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\\\ \\boldsymbol{0}\\\\ \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where the tilde-matrix $\\tilde{\\boldsymbol{\\Sigma}}$ is a matrix of dimension $p\\times p$ containing only the singular values $\\sigma_i$, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{\\Sigma}}=\\begin{bmatrix} \\sigma_0 & 0 & 0 & \\dots & 0 & 0 \\\\\n",
+ " 0 & \\sigma_1 & 0 & \\dots & 0 & 0 \\\\\n",
+ "\t\t\t\t 0 & 0 & \\sigma_2 & \\dots & 0 & 0 \\\\\n",
+ "\t\t\t\t 0 & 0 & 0 & \\dots & \\sigma_{p-2} & 0 \\\\\n",
+ "\t\t\t\t 0 & 0 & 0 & \\dots & 0 & \\sigma_{p-1} \\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "meaning we can write"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\tilde{\\boldsymbol{\\Sigma}}^2\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Multiplying from the right with $\\boldsymbol{V}$ (using the orthogonality of $\\boldsymbol{V}$) we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{V}=\\boldsymbol{V}\\tilde{\\boldsymbol{\\Sigma}}^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This means the vectors $\\boldsymbol{v}_i$ of the orthogonal matrix $\\boldsymbol{V}$\n",
+ "are the eigenvectors of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ with eigenvalues\n",
+ "given by the singular values squared, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{v}_i=\\boldsymbol{v}_i\\sigma_i^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In other words, each non-zero singular value of $\\boldsymbol{X}$ is a positive\n",
+ "square root of an eigenvalue of $\\boldsymbol{X}^T\\boldsymbol{X}$. It means also that\n",
+ "the columns of $\\boldsymbol{V}$ are the eigenvectors of\n",
+ "$\\boldsymbol{X}^T\\boldsymbol{X}$. Since we have ordered the singular values of\n",
+ "$\\boldsymbol{X}$ in a descending order, it means that the column vectors\n",
+ "$\\boldsymbol{v}_i$ are hierarchically ordered by how much correlation they\n",
+ "encode from the columns of $\\boldsymbol{X}$. \n",
+ "\n",
+ "\n",
+ "Note that these are also the eigenvectors and eigenvalues of the\n",
+ "Hessian matrix.\n",
+ "\n",
+ "If we now recall the definition of the covariance matrix (not using\n",
+ "Bessel's correction) we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{X}]=\\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "meaning that every squared non-singular value of $\\boldsymbol{X}$ divided by $n$ (\n",
+ "the number of samples) are the eigenvalues of the covariance\n",
+ "matrix. Every singular value of $\\boldsymbol{X}$ is thus a positive square\n",
+ "root of an eigenvalue of $\\boldsymbol{X}^T\\boldsymbol{X}$. If the matrix $\\boldsymbol{X}$ is\n",
+ "self-adjoint, the singular values of $\\boldsymbol{X}$ are equal to the\n",
+ "absolute value of the eigenvalues of $\\boldsymbol{X}$.\n",
+ "\n",
+ "\n",
+ "For $\\boldsymbol{X}\\boldsymbol{X}^T$ we found"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{U}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Since the matrices here have dimension $n\\times n$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T = \\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\\\ \\boldsymbol{0}\\\\ \\end{bmatrix}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\boldsymbol{0}\\\\ \\end{bmatrix}=\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "leading to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix}\\boldsymbol{U}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Multiplying with $\\boldsymbol{U}$ from the right gives us the eigenvalue problem"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U}=\\boldsymbol{U}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It means that the eigenvalues of $\\boldsymbol{X}\\boldsymbol{X}^T$ are again given by\n",
+ "the non-zero singular values plus now a series of zeros. The column\n",
+ "vectors of $\\boldsymbol{U}$ are the eigenvectors of $\\boldsymbol{X}\\boldsymbol{X}^T$ and\n",
+ "measure how much correlations are contained in the rows of $\\boldsymbol{X}$.\n",
+ "\n",
+ "Since we will mainly be interested in the correlations among the features\n",
+ "of our data (the columns of $\\boldsymbol{X}$, the quantity of interest for us are the non-zero singular\n",
+ "values and the column vectors of $\\boldsymbol{V}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Ridge and LASSO Regression\n",
+ "\n",
+ "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n",
+ "our optimization problem is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or we can state it as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have used the definition of a norm-2 vector, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "By minimizing the above equation with respect to the parameters\n",
+ "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n",
+ "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n",
+ "defining a new cost function to be optimized, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to the Ridge regression minimization problem where we\n",
+ "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n",
+ "a finite number larger than zero. By defining"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have a new optimization equation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n",
+ "\n",
+ "Here we have defined the norm-1 as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and \n",
+ "taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n",
+ "a slightly modified matrix inversion problem which for finite values\n",
+ "of $\\lambda$ does not suffer from singularity problems. We obtain\n",
+ "the optimal parameters"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $t$ a finite positive number. \n",
+ "\n",
+ "When we compare this with the ordinary least squares result we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$.\n",
+ "\n",
+ "\n",
+ "We see that Ridge regression is nothing but the standard OLS with a\n",
+ "modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The consequences, in\n",
+ "particular for our discussion of the bias-variance tradeoff are rather\n",
+ "interesting. We will see that for specific values of $\\lambda$, we may\n",
+ "even reduce the variance of the optimal parameters $\\boldsymbol{\\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.\n",
+ "\n",
+ "Using our insights about the SVD of the design matrix $\\boldsymbol{X}$ \n",
+ "We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}_{\\mathrm{OLS}}=\\boldsymbol{X}\\boldsymbol{\\beta} =\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For Ridge regression this becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}_{\\mathrm{Ridge}}=\\boldsymbol{X}\\boldsymbol{\\beta}_{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{\\Sigma}^2\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$ from the SVD of the matrix $\\boldsymbol{X}$. \n",
+ "\n",
+ "\n",
+ "Since $\\lambda \\geq 0$, it means that compared to OLS, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n",
+ "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n",
+ "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n",
+ "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n",
+ "\\sigma_{i+1}$.\n",
+ "\n",
+ "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.\n",
+ "\n",
+ "\n",
+ "\n",
+ "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this case the standard OLS results in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n",
+ "the Ridge estimator converges to zero when the hyperparameter goes to\n",
+ "infinity.\n",
+ "\n",
+ "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n",
+ "\n",
+ "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n",
+ "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\n",
+ "\n",
+ "\n",
+ "Using the matrix-vector expression for Lasso regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have the following **cost** function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{d \\vert \\beta\\vert}{d \\boldsymbol{\\beta}}=\\mathrm{sgn}(\\boldsymbol{\\beta})=\\left\\{\\begin{array}{cc} 1 & \\beta > 0 \\\\ 0 & \\beta =0\\\\-1 & \\beta < 0, \\end{array}\\right.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have that the derivative of the cost function is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{X},\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}=-2\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})+\\lambda sgn(\\boldsymbol{\\beta})=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and reordering we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta})+\\lambda sgn(\\boldsymbol{\\beta})=2\\boldsymbol{X}^T(\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This equation does not lead to a nice analytical equation as in either Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms using for example the Python package [CVXOPT](https://cvxopt.org/). We will discuss this later. \n",
+ "\n",
+ "## Code for SVD and Inversion of Matrices\n",
+ "\n",
+ "How do we use the SVD to invert a matrix $\\boldsymbol{X}^\\boldsymbol{X}$ which is singular or near singular?\n",
+ "The simple answer is to use the linear algebra function for pseudoinvers, that is"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "Ainv = np.linlag.pinv(A)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let us first look at a matrix which does not causes problems and write our own function where we just use the SVD."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "# SVD inversion\n",
+ "def SVDinv(A):\n",
+ " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n",
+ " SVD is numerically more stable than the inversion algorithms provided by\n",
+ " numpy and scipy.linalg at the cost of being slower.\n",
+ " '''\n",
+ " U, s, VT = np.linalg.svd(A)\n",
+ " print('test U')\n",
+ " print( (np.transpose(U) @ U - U @np.transpose(U)))\n",
+ " print('test VT')\n",
+ " print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n",
+ "\n",
+ "\n",
+ " D = np.zeros((len(U),len(VT)))\n",
+ " D = np.diag(s)\n",
+ " UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)\n",
+ " return np.matmul(V,np.matmul(invD,UT))\n",
+ "\n",
+ "\n",
+ "#X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])\n",
+ "# Non-singular square matrix\n",
+ "X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])\n",
+ "print(X)\n",
+ "A = np.transpose(X) @ X\n",
+ "# Brute force inversion\n",
+ "B = np.linalg.inv(A) # here we could use np.linalg.pinv(A)\n",
+ "C = SVDinv(A)\n",
+ "print(np.abs(B-C))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Although our matrix to invert $\\boldsymbol{X}^T\\boldsymbol{X}$ is a square matrix, our matrix may be singular. \n",
+ "\n",
+ "The pseudoinverse is the generalization of the matrix inverse for square matrices to\n",
+ "rectangular matrices where the number of rows and columns are not equal.\n",
+ "\n",
+ "It is also called the the Moore-Penrose Inverse after two independent discoverers of the method or the Generalized Inverse.\n",
+ "It is used for the calculation of the inverse for singular or near singular matrices and for rectangular matrices.\n",
+ "\n",
+ "Using the SVD we can obtain the pseudoinverse of a matrix $\\boldsymbol{A}$ (labeled here as $\\boldsymbol{A}_{\\mathrm{PI}}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}_{\\mathrm{PI}}= \\boldsymbol{V}\\boldsymbol{D}_{\\mathrm{PI}}\\boldsymbol{U}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\boldsymbol{D}_{\\mathrm{PI}}$ can be calculated by creating a diagonal matrix from $\\boldsymbol{Sigma}$ where we only keep the singular values (the non-zero values). The following code computes the pseudoinvers of the matrix based on the SVD."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "# SVD inversion\n",
+ "def SVDinv(A):\n",
+ " U, s, VT = np.linalg.svd(A)\n",
+ " # reciprocals of singular values of s\n",
+ " d = 1.0 / s\n",
+ " # create m x n D matrix\n",
+ " D = np.zeros(A.shape)\n",
+ " # populate D with n x n diagonal matrix\n",
+ " D[:A.shape[1], :A.shape[1]] = np.diag(d)\n",
+ " UT = np.transpose(U)\n",
+ " V = np.transpose(VT)\n",
+ " return np.matmul(V,np.matmul(D.T,UT))\n",
+ "\n",
+ "\n",
+ "A = np.array([ [0.3, 0.4], [0.5, 0.6], [0.7, 0.8],[0.9, 1.0]])\n",
+ "print(A)\n",
+ "# Brute force inversion of super-collinear matrix\n",
+ "B = np.linalg.pinv(A)\n",
+ "print(B)\n",
+ "# Compare our own algorithm with pinv\n",
+ "C = SVDinv(A)\n",
+ "print(np.abs(C-B))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see from this example, our own decomposition based on the SVD agrees the pseudoinverse algorithm provided by **Numpy**.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Deriving the Ridge Regression Equations\n",
+ "\n",
+ "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n",
+ "our optimization problem is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or we can state it as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have used the definition of a norm-2 vector, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "By minimizing the above equation with respect to the parameters\n",
+ "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n",
+ "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n",
+ "defining a new cost function to be optimized, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to the Ridge regression minimization problem where we\n",
+ "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n",
+ "a finite number larger than zero. By defining"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have a new optimization equation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n",
+ "\n",
+ "Here we have defined the norm-1 as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and \n",
+ "taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n",
+ "a slightly modified matrix inversion problem which for finite values\n",
+ "of $\\lambda$ does not suffer from singularity problems. We obtain\n",
+ "the optimal parameters"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $t$ a finite positive number. \n",
+ "\n",
+ "When we compare this with the ordinary least squares result we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$.\n",
+ "\n",
+ "\n",
+ "We see that Ridge regression is nothing but the standard OLS with a\n",
+ "modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The consequences, in\n",
+ "particular for our discussion of the bias-variance tradeoff are rather\n",
+ "interesting. We will see that for specific values of $\\lambda$, we may\n",
+ "even reduce the variance of the optimal parameters $\\boldsymbol{\\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Using our insights about the SVD of the design matrix $\\boldsymbol{X}$ \n",
+ "We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}_{\\mathrm{OLS}}=\\boldsymbol{X}\\boldsymbol{\\beta} =\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For Ridge regression this becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}_{\\mathrm{Ridge}}=\\boldsymbol{X}\\boldsymbol{\\beta}_{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{\\Sigma}^2\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$ from the SVD of the matrix $\\boldsymbol{X}$. \n",
+ "\n",
+ "\n",
+ "\n",
+ "Since $\\lambda \\geq 0$, it means that compared to OLS, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n",
+ "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n",
+ "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n",
+ "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n",
+ "\\sigma_{i+1}$.\n",
+ "\n",
+ "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.\n",
+ "\n",
+ "\n",
+ "\n",
+ "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this case the standard OLS results in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n",
+ "the Ridge estimator converges to zero when the hyperparameter goes to\n",
+ "infinity.\n",
+ "\n",
+ "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n",
+ "\n",
+ "\n",
+ "\n",
+ "Using the matrix-vector expression for Lasso regression and dropping the parameter $1/n$ in front of the standard mean squared error equation, we have the following **cost** function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{d \\vert \\beta\\vert}{d \\boldsymbol{\\beta}}=\\mathrm{sgn}(\\boldsymbol{\\beta})=\\left\\{\\begin{array}{cc} 1 & \\beta > 0 \\\\ 0 & \\beta =0\\\\-1 & \\beta < 0, \\end{array}\\right.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have that the derivative of the cost function is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{X},\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}=-2\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})+\\lambda sgn(\\boldsymbol{\\beta})=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and reordering we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta}+\\lambda sgn(\\boldsymbol{\\beta})=2\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This equation does not lead to a nice analytical equation as in 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](https://cvxopt.org/). We will discuss this later. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Let us assume that our design matrix is given by unit (identity) matrix, that is a square diagonal matrix with ones only along the\n",
+ "diagonal. In this case we have an equal number of rows and columns $n=p$.\n",
+ "\n",
+ "Our model approximation is just $\\tilde{\\boldsymbol{y}}=\\boldsymbol{\\beta}$ and the mean squared error and thereby the cost function for ordinary least sqquares (OLS) is then (we drop the term $1/n$)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and minimizing we have that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\beta}_i^{\\mathrm{OLS}} = y_i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For Ridge regression our cost function is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\beta_i^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and minimizing we have that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\beta}_i^{\\mathrm{Ridge}} = \\frac{y_i}{1+\\lambda}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For Lasso regression our cost function is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\vert\\beta_i\\vert=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\sqrt{\\beta_i^2},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and minimizing we have that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "-2\\sum_{i=0}^{p-1}(y_i-\\beta_i)+\\lambda \\sum_{i=0}^{p-1}\\frac{(\\beta_i)}{\\vert\\beta_i\\vert}=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_i^{\\mathrm{Lasso}} = \\left\\{\\begin{array}{ccc}y_i-\\frac{\\lambda}{2} &\\mathrm{if} & y_i> \\frac{\\lambda}{2}\\\\\n",
+ " y_i+\\frac{\\lambda}{2} &\\mathrm{if} & y_i< -\\frac{\\lambda}{2}\\\\\n",
+ "\t\t\t\t\t\t\t 0 &\\mathrm{if} & \\vert y_i\\vert\\le \\frac{\\lambda}{2}\\end{array}\\right.\\\\.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Plotting these results ([figure in handwritten notes for week 36](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2021/NotesSeptember9.pdf)) shows clearly that Lasso regression suppresses (sets to zero) values of $\\beta_i$ for specific values of $\\lambda$. Ridge regression reduces on the other hand the values of $\\beta_i$ as function of $\\lambda$.\n",
+ "\n",
+ "\n",
+ "As another examples, \n",
+ "let us assume we have a data set with outputs/targets given by the vector"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{y}=\\begin{bmatrix}4 \\\\ 2 \\\\3\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and our inputs as a $3\\times 2$ design matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}2 & 0\\\\ 0 & 1 \\\\ 0 & 0\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "meaning that we have two features and two unknown parameters $\\beta_0$ and $\\beta_1$ to be determined either by ordinary least squares, Ridge or Lasso regression.\n",
+ "\n",
+ "\n",
+ "For ordinary least squares (OLS) we know that the optimal solution is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\left( \\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Inserting the above values we obtain that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\begin{bmatrix}2 \\\\ 2\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The code which implements this simpler case is presented after the discussion of Ridge and Lasso.\n",
+ "\n",
+ "\n",
+ "For Ridge regression we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}}=\\left( \\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Inserting the above values we obtain that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}}=\\begin{bmatrix}\\frac{8}{4+\\lambda} \\\\ \\frac{2}{1+\\lambda}\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "There is normally a constraint on the value of $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2$ via the parameter $\\lambda$.\n",
+ "Let us for simplicity assume that $\\beta_0^2+\\beta_1^2=1$ as constraint. This will allow us to find an expression for the optimal values of $\\beta$ and $\\lambda$.\n",
+ "\n",
+ "To see this, let us write the cost function for Ridge regression. \n",
+ "\n",
+ "\n",
+ "\n",
+ "We define the MSE without the $1/n$ factor and have then, using that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}\\boldsymbol{\\beta}=\\begin{bmatrix} 2\\beta_0 \\\\ \\beta_1 \\\\0 \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=(4-2\\beta_0)^2+(2-\\beta_1)^2+\\lambda(\\beta_0^2+\\beta_1^2),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and taking the derivative with respect to $\\beta_0$ we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_0=\\frac{8}{4+\\lambda},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and for $\\beta_1$ we obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_1=\\frac{2}{1+\\lambda},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using the constraint for $\\beta_0^2+\\beta_1^2=1$ we can constrain $\\lambda$ by solving"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\frac{8}{4+\\lambda}\\right)^2+\\left(\\frac{2}{1+\\lambda}\\right)^2=1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which gives $\\lambda=4.571$ and $\\beta_0=0.933$ and $\\beta_1=0.359$.\n",
+ "\n",
+ "\n",
+ "For Lasso we need now, keeping a constraint on $\\vert\\beta_0\\vert+\\vert\\beta_1\\vert=1$, to take the derivative of the absolute values of $\\beta_0$\n",
+ "and $\\beta_1$. This gives us the following derivatives of the cost function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=(4-2\\beta_0)^2+(2-\\beta_1)^2+\\lambda(\\vert\\beta_0\\vert+\\vert\\beta_1\\vert),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_0}=-4(4-2\\beta_0)+\\lambda\\mathrm{sgn}(\\beta_0)=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_1}=-2(2-\\beta_1)+\\lambda\\mathrm{sgn}(\\beta_1)=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We have now four cases to solve besides the trivial cases $\\beta_0$ and/or $\\beta_1$ are zero, namely\n",
+ "1. $\\beta_0 > 0$ and $\\beta_1 > 0$,\n",
+ "\n",
+ "2. $\\beta_0 > 0$ and $\\beta_1 < 0$,\n",
+ "\n",
+ "3. $\\beta_0 < 0$ and $\\beta_1 > 0$,\n",
+ "\n",
+ "4. $\\beta_0 < 0$ and $\\beta_1 < 0$.\n",
+ "\n",
+ "If we consider the first case, we have then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "-4(4-2\\beta_0)+\\lambda=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "-2(2-\\beta_1)+\\lambda=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which yields"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_0=\\frac{16+\\lambda}{8},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_1=\\frac{4+\\lambda}{2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using the constraint on $\\beta_0$ and $\\beta_1$ we can then find the optimal value of $\\lambda$ for the different cases. We leave this as an exercise to you.\n",
+ "\n",
+ "\n",
+ "Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of $\\lambda$, meaning that we need to perform a search in order to find the optimal values.\n",
+ "\n",
+ "First we study and compare the OLS and Ridge results. The next code compares all three methods."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "def R2(y_data, y_model):\n",
+ " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
+ "\n",
+ "\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "\n",
+ "X = np.array( [ [ 2, 0], [0, 1], [0,0]])\n",
+ "y = np.array( [4, 2, 3])\n",
+ "\n",
+ "\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y\n",
+ "print(OLSbeta)\n",
+ "# and then make the prediction\n",
+ "ytildeOLS = X @ OLSbeta\n",
+ "print(\"Training MSE for OLS\")\n",
+ "print(MSE(y,ytildeOLS))\n",
+ "ypredictOLS = X @ OLSbeta\n",
+ "\n",
+ "# Repeat now for Ridge regression and various values of the regularization parameter\n",
+ "I = np.eye(2,2)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 100\n",
+ "MSEPredict = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 4, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y\n",
+ "# print(Ridgebeta)\n",
+ " # and then make the prediction\n",
+ " ypredictRidge = X @ Ridgebeta\n",
+ " MSEPredict[i] = MSE(y,ypredictRidge)\n",
+ "# print(MSEPredict[i])\n",
+ " # Now plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Train')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see here that we reach a plateau. What is actually happening?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn import linear_model\n",
+ "\n",
+ "def R2(y_data, y_model):\n",
+ " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
+ "\n",
+ "\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "\n",
+ "X = np.array( [ [ 2, 0], [0, 1], [0,0]])\n",
+ "y = np.array( [4, 2, 3])\n",
+ "\n",
+ "\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y\n",
+ "print(OLSbeta)\n",
+ "# and then make the prediction\n",
+ "ytildeOLS = X @ OLSbeta\n",
+ "print(\"Training MSE for OLS\")\n",
+ "print(MSE(y,ytildeOLS))\n",
+ "ypredictOLS = X @ OLSbeta\n",
+ "\n",
+ "# Repeat now for Ridge regression and various values of the regularization parameter\n",
+ "I = np.eye(2,2)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 100\n",
+ "MSERidgePredict = np.zeros(nlambdas)\n",
+ "MSELassoPredict = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 4, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y\n",
+ " print(Ridgebeta)\n",
+ " # and then make the prediction\n",
+ " ypredictRidge = X @ Ridgebeta\n",
+ " MSERidgePredict[i] = MSE(y,ypredictRidge)\n",
+ " RegLasso = linear_model.Lasso(lmb)\n",
+ " RegLasso.fit(X,y)\n",
+ " ypredictLasso = RegLasso.predict(X)\n",
+ " print(RegLasso.coef_)\n",
+ " MSELassoPredict[i] = MSE(y,ypredictLasso)\n",
+ "# Now plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSERidgePredict, 'r--', label = 'MSE Ridge Train')\n",
+ "plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Train')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Another Example, now with a polynomial fit."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn import linear_model\n",
+ "\n",
+ "def R2(y_data, y_model):\n",
+ " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
+ "\n",
+ "\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "np.random.seed(3155)\n",
+ "\n",
+ "x = np.random.rand(100)\n",
+ "y = 2.0+5*x*x+0.1*np.random.randn(100)\n",
+ "\n",
+ "# number of features p (here degree of polynomial\n",
+ "p = 3\n",
+ "# The design matrix now as function of a given polynomial\n",
+ "X = np.zeros((len(x),p))\n",
+ "X[:,0] = 1.0\n",
+ "X[:,1] = x\n",
+ "X[:,2] = x*x\n",
+ "# We split the data in test and training data\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
+ "\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n",
+ "print(OLSbeta)\n",
+ "# and then make the prediction\n",
+ "ytildeOLS = X_train @ OLSbeta\n",
+ "print(\"Training MSE for OLS\")\n",
+ "print(MSE(y_train,ytildeOLS))\n",
+ "ypredictOLS = X_test @ OLSbeta\n",
+ "print(\"Test MSE OLS\")\n",
+ "print(MSE(y_test,ypredictOLS))\n",
+ "\n",
+ "# Repeat now for Lasso and Ridge regression and various values of the regularization parameter\n",
+ "I = np.eye(p,p)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 100\n",
+ "MSEPredict = np.zeros(nlambdas)\n",
+ "MSETrain = np.zeros(nlambdas)\n",
+ "MSELassoPredict = np.zeros(nlambdas)\n",
+ "MSELassoTrain = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 4, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n",
+ " # include lasso using Scikit-Learn\n",
+ " RegLasso = linear_model.Lasso(lmb)\n",
+ " RegLasso.fit(X_train,y_train)\n",
+ " # and then make the prediction\n",
+ " ytildeRidge = X_train @ Ridgebeta\n",
+ " ypredictRidge = X_test @ Ridgebeta\n",
+ " ytildeLasso = RegLasso.predict(X_train)\n",
+ " ypredictLasso = RegLasso.predict(X_test)\n",
+ " MSEPredict[i] = MSE(y_test,ypredictRidge)\n",
+ " MSETrain[i] = MSE(y_train,ytildeRidge)\n",
+ " MSELassoPredict[i] = MSE(y_test,ypredictLasso)\n",
+ " MSELassoTrain[i] = MSE(y_train,ytildeLasso)\n",
+ "\n",
+ "# Now plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSETrain, label = 'MSE Ridge train')\n",
+ "plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Test')\n",
+ "plt.plot(np.log10(lambdas), MSELassoTrain, label = 'MSE Lasso train')\n",
+ "plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Test')\n",
+ "\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Linking the regression analysis with a statistical interpretation\n",
+ "\n",
+ "We will now couple the discussions of ordinary least squares, Ridge\n",
+ "and Lasso regression with a statistical interpretation, that is we\n",
+ "move from a linear algebra analysis to a statistical analysis. In\n",
+ "particular, we will focus on what the regularization terms can result\n",
+ "in. We will amongst other things show that the regularization\n",
+ "parameter can reduce considerably the variance of the parameters\n",
+ "$\\beta$.\n",
"\n",
- "* Systematical errors are method specific and must be treated differently from case to case. \n",
"\n",
"The\n",
"advantage of doing linear regression is that we actually end up with\n",
@@ -107,6 +3381,7 @@
"row number $i$ and perform a sum over all values $p$.\n",
"\n",
"\n",
+ "\n",
"The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off)\n",
"that there exists a function $f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim \\mathcal{N}(0, \\sigma^2)$\n",
"which describe our data"
@@ -254,8 +3529,7 @@
"\\sigma^2 \\, \\mathbf{I}_{nn}$. From $\\mbox{Var}(\\boldsymbol{\\beta}) = \\sigma^2\n",
"\\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}$, one obtains an estimate of the\n",
"variance of the estimate of the $j$-th regression coefficient:\n",
- "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 \\sqrt{\n",
- "[(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} }$. This may be used to\n",
+ "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 [(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} $. This may be used to\n",
"construct a confidence interval for the estimates.\n",
"\n",
"\n",
@@ -322,48 +3596,20 @@
"\n",
"\n",
"\n",
- "## Resampling methods\n",
+ "## Deriving OLS from a probability distribution\n",
"\n",
- "With all these analytical equations for both the OLS and Ridge\n",
- "regression, we will now outline how to assess a given model. This will\n",
- "lead us to a discussion of the so-called bias-variance tradeoff (see\n",
- "below) and so-called resampling methods.\n",
+ "Our basic assumption when we derived the OLS equations was to assume\n",
+ "that our output is determined by a given continuous function\n",
+ "$f(\\boldsymbol{x})$ and a random noise $\\boldsymbol{\\epsilon}$ given by the normal\n",
+ "distribution with zero mean value and an undetermined variance\n",
+ "$\\sigma^2$.\n",
"\n",
- "One of the quantities we have discussed as a way to measure errors is\n",
- "the mean-squared error (MSE), mainly used for fitting of continuous\n",
- "functions. Another choice is the absolute error.\n",
- "\n",
- "In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,\n",
- "we discuss the\n",
- "1. prediction error or simply the **test error** $\\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the \n",
- "\n",
- "2. training error $\\mathrm{Err_{Train}}$, which is the average loss over the training data.\n",
- "\n",
- "As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.\n",
- "For a certain level of complexity the test error will reach minimum, before starting to increase again. The\n",
- "training error reaches a saturation.\n",
- "\n",
- "\n",
- "\n",
- "Two famous\n",
- "resampling methods are the **independent bootstrap** and **the jackknife**. \n",
- "\n",
- "The jackknife is a special case of the independent bootstrap. Still, the jackknife was made\n",
- "popular prior to the independent bootstrap. And as the popularity of\n",
- "the independent bootstrap soared, new variants, such as **the dependent bootstrap**.\n",
- "\n",
- "The Jackknife and independent bootstrap work for\n",
- "independent, identically distributed random variables.\n",
- "If these conditions are not\n",
- "satisfied, the methods will fail. Yet, it should be said that if the data are\n",
- "independent, identically distributed, and we only want to estimate the\n",
- "variance of $\\overline{X}$ (which often is the case), then there is no\n",
- "need for bootstrapping. \n",
- "\n",
- "\n",
- "The Jackknife works by making many replicas of the estimator $\\widehat{\\theta}$. \n",
- "The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\\boldsymbol{x} = (x_1,x_2,\\cdots,X_n)$. \n",
- "Let $\\boldsymbol{x}_i$ denote the vector"
+ "We found above that the outputs $\\boldsymbol{y}$ have a mean value given by\n",
+ "$\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$ and variance $\\sigma^2$. Since the entries to\n",
+ "the design matrix are not stochastic variables, we can assume that the\n",
+ "probability distribution of our targets is also a normal distribution\n",
+ "but now with mean value $\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$. This means that a\n",
+ "single output $y_i$ is given by the Gaussian distribution"
]
},
{
@@ -371,7 +3617,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{x}_i = (x_1,x_2,\\cdots,x_{i-1},x_{i+1},\\cdots,x_n),\n",
+ "y_i\\sim \\mathcal{N}(\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta}, \\sigma^2)=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
"$$"
]
},
@@ -379,229 +3625,8 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "which equals the vector $\\boldsymbol{x}$ with the exception that observation\n",
- "number $i$ is left out. Using this notation, define\n",
- "$\\widehat{\\theta}_i$ to be the estimator\n",
- "$\\widehat{\\theta}$ computed using $\\vec{X}_i$."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "from numpy import *\n",
- "from numpy.random import randint, randn\n",
- "from time import time\n",
- "\n",
- "def jackknife(data, stat):\n",
- " n = len(data);t = zeros(n); inds = arange(n); t0 = time()\n",
- " ## 'jackknifing' by leaving out an observation for each i \n",
- " for i in range(n):\n",
- " t[i] = stat(delete(data,i) )\n",
- "\n",
- " # analysis \n",
- " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Jackknife Statistics :\")\n",
- " print(\"original bias std. error\")\n",
- " print(\"%8g %14g %15g\" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))\n",
- "\n",
- " return t\n",
- "\n",
- "\n",
- "# Returns mean of data samples \n",
- "def stat(data):\n",
- " return mean(data)\n",
- "\n",
- "\n",
- "mu, sigma = 100, 15\n",
- "datapoints = 10000\n",
- "x = mu + sigma*random.randn(datapoints)\n",
- "# jackknife returns the data sample \n",
- "t = jackknife(x, stat)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Bootstrap\n",
- "\n",
- "Bootstrapping is a nonparametric approach to statistical inference\n",
- "that substitutes computation for more traditional distributional\n",
- "assumptions and asymptotic results. Bootstrapping offers a number of\n",
- "advantages: \n",
- "1. The bootstrap is quite general, although there are some cases in which it fails. \n",
- "\n",
- "2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. \n",
- "\n",
- "3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. \n",
- "\n",
- "4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).\n",
- "\n",
- "Since $\\widehat{\\theta} = \\widehat{\\theta}(\\boldsymbol{X})$ is a function of random variables,\n",
- "$\\widehat{\\theta}$ itself must be a random variable. Thus it has\n",
- "a pdf, call this function $p(\\boldsymbol{t})$. The aim of the bootstrap is to\n",
- "estimate $p(\\boldsymbol{t})$ by the relative frequency of\n",
- "$\\widehat{\\theta}$. You can think of this as using a histogram\n",
- "in the place of $p(\\boldsymbol{t})$. If the relative frequency closely\n",
- "resembles $p(\\vec{t})$, then using numerics, it is straight forward to\n",
- "estimate all the interesting parameters of $p(\\boldsymbol{t})$ using point\n",
- "estimators. \n",
- "\n",
- "\n",
- "\n",
- "In the case that $\\widehat{\\theta}$ has\n",
- "more than one component, and the components are independent, we use the\n",
- "same estimator on each component separately. If the probability\n",
- "density function of $X_i$, $p(x)$, had been known, then it would have\n",
- "been straight forward to do this by: \n",
- "1. Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \\cdots, X_n^*)$. \n",
- "\n",
- "2. Then using these numbers, we could compute a replica of $\\widehat{\\theta}$ called $\\widehat{\\theta}^*$. \n",
- "\n",
- "By repeated use of (1) and (2), many\n",
- "estimates of $\\widehat{\\theta}$ could have been obtained. The\n",
- "idea is to use the relative frequency of $\\widehat{\\theta}^*$\n",
- "(think of a histogram) as an estimate of $p(\\boldsymbol{t})$.\n",
- "\n",
- "\n",
- "But\n",
- "unless there is enough information available about the process that\n",
- "generated $X_1,X_2,\\cdots,X_n$, $p(x)$ is in general\n",
- "unknown. Therefore, [Efron in 1979](https://projecteuclid.org/euclid.aos/1176344552) asked the\n",
- "question: What if we replace $p(x)$ by the relative frequency\n",
- "of the observation $X_i$; if we draw observations in accordance with\n",
- "the relative frequency of the observations, will we obtain the same\n",
- "result in some asymptotic sense? The answer is yes.\n",
- "\n",
- "\n",
- "Instead of generating the histogram for the relative\n",
- "frequency of the observation $X_i$, just draw the values\n",
- "$(X_1^*,X_2^*,\\cdots,X_n^*)$ with replacement from the vector\n",
- "$\\boldsymbol{X}$. \n",
- "\n",
- "\n",
- "The independent bootstrap works like this: \n",
- "\n",
- "1. Draw with replacement $n$ numbers for the observed variables $\\boldsymbol{x} = (x_1,x_2,\\cdots,x_n)$. \n",
- "\n",
- "2. Define a vector $\\boldsymbol{x}^*$ containing the values which were drawn from $\\boldsymbol{x}$. \n",
- "\n",
- "3. Using the vector $\\boldsymbol{x}^*$ compute $\\widehat{\\theta}^*$ by evaluating $\\widehat \\theta$ under the observations $\\boldsymbol{x}^*$. \n",
- "\n",
- "4. Repeat this process $k$ times. \n",
- "\n",
- "When you are done, you can draw a histogram of the relative frequency\n",
- "of $\\widehat \\theta^*$. This is your estimate of the probability\n",
- "distribution $p(t)$. Using this probability distribution you can\n",
- "estimate any statistics thereof. In principle you never draw the\n",
- "histogram of the relative frequency of $\\widehat{\\theta}^*$. Instead\n",
- "you use the estimators corresponding to the statistic of interest. For\n",
- "example, if you are interested in estimating the variance of $\\widehat\n",
- "\\theta$, apply the etsimator $\\widehat \\sigma^2$ to the values\n",
- "$\\widehat \\theta ^*$.\n",
- "\n",
- "\n",
- "\n",
- "The following code starts with a Gaussian distribution with mean value\n",
- "$\\mu =100$ and variance $\\sigma=15$. We use this to generate the data\n",
- "used in the bootstrap analysis. The bootstrap analysis returns a data\n",
- "set after a given number of bootstrap operations (as many as we have\n",
- "data points). This data set consists of estimated mean values for each\n",
- "bootstrap operation. The histogram generated by the bootstrap method\n",
- "shows that the distribution for these mean values is also a Gaussian,\n",
- "centered around the mean value $\\mu=100$ but with standard deviation\n",
- "$\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in\n",
- "this case the same as the number of original data points). The value\n",
- "of the standard deviation is what we expect from the central limit\n",
- "theorem."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "%matplotlib inline\n",
- "\n",
- "from numpy import *\n",
- "from numpy.random import randint, randn\n",
- "from time import time\n",
- "import matplotlib.mlab as mlab\n",
- "import matplotlib.pyplot as plt\n",
- "\n",
- "# Returns mean of bootstrap samples \n",
- "def stat(data):\n",
- " return mean(data)\n",
- "\n",
- "# Bootstrap algorithm\n",
- "def bootstrap(data, statistic, R):\n",
- " t = zeros(R); n = len(data); inds = arange(n); t0 = time()\n",
- " # non-parametric bootstrap \n",
- " for i in range(R):\n",
- " t[i] = statistic(data[randint(0,n,n)])\n",
- "\n",
- " # analysis \n",
- " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Bootstrap Statistics :\")\n",
- " print(\"original bias std. error\")\n",
- " print(\"%8g %8g %14g %15g\" % (statistic(data), std(data),mean(t),std(t)))\n",
- " return t\n",
- "\n",
- "\n",
- "mu, sigma = 100, 15\n",
- "datapoints = 10000\n",
- "x = mu + sigma*random.randn(datapoints)\n",
- "# bootstrap returns the data sample \n",
- "t = bootstrap(x, stat, datapoints)\n",
- "# the histogram of the bootstrapped data \n",
- "n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)\n",
- "\n",
- "# add a 'best fit' line \n",
- "y = mlab.normpdf( binsboot, mean(t), std(t))\n",
- "lt = plt.plot(binsboot, y, 'r--', linewidth=1)\n",
- "plt.xlabel('Smarts')\n",
- "plt.ylabel('Probability')\n",
- "plt.axis([99.5, 100.6, 0, 3.0])\n",
- "plt.grid(True)\n",
- "\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Various steps in cross-validation\n",
- "\n",
- "When the repetitive splitting of the data set is done randomly,\n",
- "samples may accidently end up in a fast majority of the splits in\n",
- "either training or test set. Such samples may have an unbalanced\n",
- "influence on either model building or prediction evaluation. To avoid\n",
- "this $k$-fold cross-validation structures the data splitting. The\n",
- "samples are divided into $k$ more or less equally sized exhaustive and\n",
- "mutually exclusive subsets. In turn (at each split) one of these\n",
- "subsets plays the role of the test set while the union of the\n",
- "remaining subsets constitutes the training set. Such a splitting\n",
- "warrants a balanced representation of each sample in both training and\n",
- "test set over the splits. Still the division into the $k$ subsets\n",
- "involves a degree of randomness. This may be fully excluded when\n",
- "choosing $k=n$. This particular case is referred to as leave-one-out\n",
- "cross-validation (LOOCV). \n",
- "\n",
- "\n",
- "* Define a range of interest for the penalty parameter.\n",
- "\n",
- "* Divide the data set into training and test set comprising samples $\\{1, \\ldots, n\\} \\setminus i$ and $\\{ i \\}$, respectively.\n",
- "\n",
- "* Fit the linear regression model by means of ridge estimation for each $\\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\\boldsymbol{\\sigma}_{-i}^2(\\lambda)$, as"
+ "We assume now that the various $y_i$ values are stochastically distributed according to the above Gaussian distribution. \n",
+ "We define this distribution as"
]
},
{
@@ -609,11 +3634,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\begin{align*}\n",
- "\\boldsymbol{\\beta}_{-i}(\\lambda) & = ( \\boldsymbol{X}_{-i, \\ast}^{T}\n",
- "\\boldsymbol{X}_{-i, \\ast} + \\lambda \\boldsymbol{I}_{pp})^{-1}\n",
- "\\boldsymbol{X}_{-i, \\ast}^{T} \\boldsymbol{y}_{-i}\n",
- "\\end{align*}\n",
+ "p(y_i, \\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]},\n",
"$$"
]
},
@@ -621,11 +3642,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "* Evaluate the prediction performance of these models on the test set by $\\log\\{L[y_i, \\boldsymbol{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}$. Or, by the prediction error $|y_i - \\boldsymbol{X}_{i, \\ast} \\boldsymbol{\\beta}_{-i}(\\lambda)|$, the relative error, the error squared or the R2 score function.\n",
+ "which reads as finding the likelihood of an event $y_i$ with the input variables $\\boldsymbol{X}$ given the parameters (to be determined) $\\boldsymbol{\\beta}$.\n",
"\n",
- "* Repeat the first three steps such that each sample plays the role of the test set once.\n",
- "\n",
- "* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as"
+ "Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event $\\boldsymbol{y}$ as the product of the single events, that is we have"
]
},
{
@@ -633,9 +3652,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\begin{align*}\n",
- "\\frac{1}{n} \\sum_{i = 1}^n \\log\\{L[y_i, \\mathbf{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}.\n",
- "\\end{align*}\n",
+ "p(\\boldsymbol{y},\\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}=\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta}).\n",
"$$"
]
},
@@ -643,26 +3660,360 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "For the various values of $k$\n",
- "\n",
- "1. shuffle the dataset randomly.\n",
- "\n",
- "2. Split the dataset into $k$ groups.\n",
- "\n",
- "3. For each unique group:\n",
- "\n",
- "a. Decide which group to use as set for test data\n",
- "\n",
- "b. Take the remaining groups as a training data set\n",
- "\n",
- "c. Fit a model on the training set and evaluate it on the test set\n",
- "\n",
- "d. Retain the evaluation score and discard the model\n",
+ "We will write this in a more compact form reserving $\\boldsymbol{D}$ for the domain of events, including the ouputs (targets) and the inputs. That is\n",
+ "in case we have a simple one-dimensional input and output case"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})].\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the more general case the various inputs should be replaced by the possible features represented by the input data set $\\boldsymbol{X}$. \n",
+ "We can now rewrite the above probability as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It is a conditional probability (see below) and reads as the likelihood of a domain of events $\\boldsymbol{D}$ given a set of parameters $\\boldsymbol{\\beta}$.\n",
"\n",
"\n",
- "5. Summarize the model using the sample of model evaluation scores\n",
+ "In statistics, maximum likelihood estimation (MLE) is a method of\n",
+ "estimating the parameters of an assumed probability distribution,\n",
+ "given some observed data. This is achieved by maximizing a likelihood\n",
+ "function so that, under the assumed statistical model, the observed\n",
+ "data is the most probable. \n",
"\n",
- "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial."
+ "\n",
+ "We will assume here that our events are given by the above Gaussian\n",
+ "distribution and we will determine the optimal parameters $\\beta$ by\n",
+ "maximizing the above PDF. However, computing the derivatives of a\n",
+ "product function is cumbersome and can easily lead to overflow and/or\n",
+ "underflowproblems, with potentials for loss of numerical precision.\n",
+ "\n",
+ "\n",
+ "In practice, it is more convenient to maximize the logarithm of the\n",
+ "PDF because it is a monotonically increasing function of the argument.\n",
+ "Alternatively, and this will be our option, we will minimize the\n",
+ "negative of the logarithm since this is a monotonically decreasing\n",
+ "function.\n",
+ "\n",
+ "Note also that maximization/minimization of the logarithm of the PDF\n",
+ "is equivalent to the maximization/minimization of the function itself.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "We could now define a new cost function to minimize, namely the negative logarithm of the above PDF"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta}=-\\log{\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})}=-\\sum_{i=0}^{n-1}\\log{p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta}=\\frac{n}{2}\\log{2\\pi\\sigma^2}+\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Taking the derivative of the *new* cost function with respect to the parameters $\\beta$ we recognize our familiar OLS equation, namely"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right) =0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to the well-known OLS equation for the optimal paramters $\\beta$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}!\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics. \n",
+ "\n",
+ "\n",
+ "A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry.\n",
+ "Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics.\n",
+ "\n",
+ "Assume we have two domains of events $X=[x_0,x_1,\\dots,x_{n-1}]$ and $Y=[y_0,y_1,\\dots,y_{n-1}]$.\n",
+ "\n",
+ "We define also the likelihood for $X$ and $Y$ as $p(X)$ and $p(Y)$ respectively.\n",
+ "The likelihood of a specific event $x_i$ (or $y_i$) is then written as $p(X=x_i)$ or just $p(x_i)=p_i$. \n",
+ "\n",
+ "**Union of events is given by.**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X \\cup Y)= p(X)+p(Y)-p(X \\cap Y).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**The product rule (aka joint probability) is given by.**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X \\cup Y)= p(X,Y)= p(X\\vert Y)p(Y)=p(Y\\vert X)p(X),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we read $p(X\\vert Y)$ as the likelihood of obtaining $X$ given $Y$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "If we have independent events then $p(X,Y)=p(X)p(Y)$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The marginal probability is defined in terms of only one of the set of variables $X,Y$. For a discrete probability we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X)=\\sum_{i=0}^{n-1}p(X,Y=y_i)=\\sum_{i=0}^{n-1}p(X\\vert Y=y_i)p(Y=y_i)=\\sum_{i=0}^{n-1}p(X\\vert y_i)p(y_i).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The conditional probability, if $p(Y) > 0$, is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)}=\\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we combine the conditional probability with the marginal probability and the standard product rule, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which we can rewrite as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X\\vert Y)= \\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}=\\frac{p(Y\\vert X)p(X)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is Bayes' theorem. It allows us to evaluate the uncertainty in in $X$ after we have observed $Y$. We can easily interchange $X$ with $Y$. \n",
+ "\n",
+ "\n",
+ "The quantity $p(Y\\vert X)$ on the right-hand side of the theorem is\n",
+ "evaluated for the observed data $Y$ and can be viewed as a function of\n",
+ "the parameter space represented by $X$. This function is not\n",
+ "necesseraly normalized and is normally called the likelihood function.\n",
+ "\n",
+ "The function $p(X)$ on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution.\n",
+ "\n",
+ "Let us try to illustrate Bayes' theorem through an example.\n",
+ "\n",
+ "\n",
+ "Let us suppose that you are undergoing a series of mammography scans in\n",
+ "order to rule out possible breast cancer cases. We define the\n",
+ "sensitivity for a positive event by the variable $X$. It takes binary\n",
+ "values with $X=1$ representing a positive event and $X=0$ being a\n",
+ "negative event. We reserve $Y$ as a classification parameter for\n",
+ "either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing).\n",
+ "\n",
+ "We let $Y=1$ represent the the case of having breast cancer and $Y=0$ as not.\n",
+ "\n",
+ "Let us assume that if you have breast cancer, the test will be positive with a probability of $0.8$, that is we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X=1\\vert Y=1) =0.8.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of $80\\%$ for having cancer.\n",
+ "It is however not correct, as the following Bayesian analysis shows.\n",
+ "\n",
+ "\n",
+ "If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number.\n",
+ "Let us assume that the prior probability in the population as a whole is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(Y=1) =0.004.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X=1\\vert Y=0) =0.1.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(Y=1\\vert X=1)=\\frac{p(X=1\\vert Y=1)p(Y=1)}{p(X=1\\vert Y=1)p(Y=1)+p(X=1\\vert Y=0)p(Y=0)}=\\frac{0.8\\times 0.004}{0.8\\times 0.004+0.1\\times 0.996}=0.031.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "That is, in case of a positive test, there is only a $3\\%$ chance of having breast cancer!\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Bayes' Theorem and Ridge and Lasso Regression\n",
+ "\n",
+ "Hitherto we have discussed Ridge and Lasso regression in terms of a\n",
+ "linear analysis. This may to many of you feel rather technical and\n",
+ "perhaps not that intuitive. The question is whether we can develop a\n",
+ "more intuitive way of understanding what Ridge and Lasso express.\n",
+ "\n",
+ "Before we proceed let us perform a Ridge, Lasso and OLS analysis of a polynomial fit. \n",
+ "\n",
+ "\n",
+ "We will play around with a study of the values for the optimal\n",
+ "parameters $\\boldsymbol{\\beta}$ using OLS, Ridge and Lasso regression. For\n",
+ "OLS, you will notice as function of the noise and polynomial degree,\n",
+ "that the parameters $\\beta$ will fluctuate from order to order in the\n",
+ "polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS.\n",
+ "\n",
+ "For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one."
]
},
{
@@ -676,674 +4027,289 @@
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
- "from sklearn.model_selection import KFold\n",
- "from sklearn.linear_model import Ridge\n",
- "from sklearn.model_selection import cross_val_score\n",
- "from sklearn.preprocessing import PolynomialFeatures\n",
- "\n",
- "# A seed just to ensure that the random numbers are the same for every run.\n",
- "# Useful for eventual debugging.\n",
- "np.random.seed(3155)\n",
- "\n",
- "# Generate the data.\n",
- "nsamples = 100\n",
- "x = np.random.randn(nsamples)\n",
- "y = 3*x**2 + np.random.randn(nsamples)\n",
- "\n",
- "## Cross-validation on Ridge regression using KFold only\n",
- "\n",
- "# Decide degree on polynomial to fit\n",
- "poly = PolynomialFeatures(degree = 6)\n",
- "\n",
- "# Decide which values of lambda to use\n",
- "nlambdas = 500\n",
- "lambdas = np.logspace(-3, 5, nlambdas)\n",
- "\n",
- "# Initialize a KFold instance\n",
- "k = 5\n",
- "kfold = KFold(n_splits = k)\n",
- "\n",
- "# Perform the cross-validation to estimate MSE\n",
- "scores_KFold = np.zeros((nlambdas, k))\n",
- "\n",
- "i = 0\n",
- "for lmb in lambdas:\n",
- " ridge = Ridge(alpha = lmb)\n",
- " j = 0\n",
- " for train_inds, test_inds in kfold.split(x):\n",
- " xtrain = x[train_inds]\n",
- " ytrain = y[train_inds]\n",
- "\n",
- " xtest = x[test_inds]\n",
- " ytest = y[test_inds]\n",
- "\n",
- " Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n",
- " ridge.fit(Xtrain, ytrain[:, np.newaxis])\n",
- "\n",
- " Xtest = poly.fit_transform(xtest[:, np.newaxis])\n",
- " ypred = ridge.predict(Xtest)\n",
- "\n",
- " scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n",
- "\n",
- " j += 1\n",
- " i += 1\n",
- "\n",
- "\n",
- "estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n",
- "\n",
- "## Cross-validation using cross_val_score from sklearn along with KFold\n",
- "\n",
- "# kfold is an instance initialized above as:\n",
- "# kfold = KFold(n_splits = k)\n",
- "\n",
- "estimated_mse_sklearn = np.zeros(nlambdas)\n",
- "i = 0\n",
- "for lmb in lambdas:\n",
- " ridge = Ridge(alpha = lmb)\n",
- "\n",
- " X = poly.fit_transform(x[:, np.newaxis])\n",
- " estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n",
- "\n",
- " # cross_val_score return an array containing the estimated negative mse for every fold.\n",
- " # we have to the the mean of every array in order to get an estimate of the mse of the model\n",
- " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n",
- "\n",
- " i += 1\n",
- "\n",
- "## Plot and compare the slightly different ways to perform cross-validation\n",
- "\n",
- "plt.figure()\n",
- "\n",
- "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n",
- "plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n",
- "\n",
- "plt.xlabel('log10(lambda)')\n",
- "plt.ylabel('mse')\n",
- "\n",
- "plt.legend()\n",
- "\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## The bias-variance tradeoff\n",
- "\n",
- "\n",
- "We will discuss the bias-variance tradeoff in the context of\n",
- "continuous predictions such as regression. However, many of the\n",
- "intuitions and ideas discussed here also carry over to classification\n",
- "tasks. Consider a dataset $\\mathcal{L}$ consisting of the data\n",
- "$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$. \n",
- "\n",
- "Let us assume that the true data is generated from a noisy model"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "where $\\epsilon$ is normally distributed with mean zero and standard deviation $\\sigma^2$.\n",
- "\n",
- "In our derivation of the ordinary least squares method we defined then\n",
- "an approximation to the function $f$ in terms of the parameters\n",
- "$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n",
- "that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$. \n",
- "\n",
- "Thereafter we found the parameters $\\boldsymbol{\\beta}$ by optimizing the means squared error via the so-called cost function"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We can rewrite this as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\frac{1}{n}\\sum_i(f_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\sigma^2.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The three terms represent the square of the bias of the learning\n",
- "method, which can be thought of as the error caused by the simplifying\n",
- "assumptions built into the method. The second term represents the\n",
- "variance of the chosen model and finally the last terms is variance of\n",
- "the error $\\boldsymbol{\\epsilon}$.\n",
- "\n",
- "To derive this equation, we need to recall that the variance of $\\boldsymbol{y}$ and $\\boldsymbol{\\epsilon}$ are both equal to $\\sigma^2$. The mean value of $\\boldsymbol{\\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\\boldsymbol{\\tilde{y}}$.\n",
- "We use a more compact notation in terms of the expectation value"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}})^2\\right],\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "and adding and subtracting $\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]$ we get"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}}+\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right],\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which, using the abovementioned expectation values can be rewritten as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right]+\\mathrm{Var}\\left[\\boldsymbol{\\tilde{y}}\\right]+\\sigma^2,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "that is the rewriting in terms of the so-called bias, the variance of the model $\\boldsymbol{\\tilde{y}}$ and the variance of $\\boldsymbol{\\epsilon}$."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "import matplotlib.pyplot as plt\n",
- "import numpy as np\n",
- "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
- "from sklearn.preprocessing import PolynomialFeatures\n",
"from sklearn.model_selection import train_test_split\n",
- "from sklearn.pipeline import make_pipeline\n",
- "from sklearn.utils import resample\n",
+ "from sklearn import linear_model\n",
"\n",
- "np.random.seed(2018)\n",
- "\n",
- "n = 500\n",
- "n_boostraps = 100\n",
- "degree = 18 # A quite high value, just to show.\n",
- "noise = 0.1\n",
+ "def R2(y_data, y_model):\n",
+ " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
"\n",
"# Make data set.\n",
- "x = np.linspace(-1, 3, n).reshape(-1, 1)\n",
- "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)\n",
+ "n = 10000\n",
+ "x = np.random.rand(n)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n",
"\n",
- "# Hold out some test data that is never used in training.\n",
- "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
- "\n",
- "# Combine x transformation and model into one operation.\n",
- "# Not neccesary, but convenient.\n",
- "model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
- "\n",
- "# The following (m x n_bootstraps) matrix holds the column vectors y_pred\n",
- "# for each bootstrap iteration.\n",
- "y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
- "for i in range(n_boostraps):\n",
- " x_, y_ = resample(x_train, y_train)\n",
- "\n",
- " # Evaluate the new model on the same test data each time.\n",
- " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
- "\n",
- "# Note: Expectations and variances taken w.r.t. different training\n",
- "# data sets, hence the axis=1. Subsequent means are taken across the test data\n",
- "# set in order to obtain a total value, but before this we have error/bias/variance\n",
- "# calculated per data point in the test set.\n",
- "# Note 2: The use of keepdims=True is important in the calculation of bias as this \n",
- "# maintains the column vector form. Dropping this yields very unexpected results.\n",
- "error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
- "bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
- "variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
- "print('Error:', error)\n",
- "print('Bias^2:', bias)\n",
- "print('Var:', variance)\n",
- "print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))\n",
- "\n",
- "plt.plot(x[::5, :], y[::5, :], label='f(x)')\n",
- "plt.scatter(x_test, y_test, label='Data points')\n",
- "plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')\n",
- "plt.legend()\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "import matplotlib.pyplot as plt\n",
- "import numpy as np\n",
- "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
- "from sklearn.preprocessing import PolynomialFeatures\n",
- "from sklearn.model_selection import train_test_split\n",
- "from sklearn.pipeline import make_pipeline\n",
- "from sklearn.utils import resample\n",
- "\n",
- "np.random.seed(2018)\n",
- "\n",
- "n = 40\n",
- "n_boostraps = 100\n",
- "maxdegree = 14\n",
- "\n",
- "\n",
- "# Make data set.\n",
- "x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
- "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
- "error = np.zeros(maxdegree)\n",
- "bias = np.zeros(maxdegree)\n",
- "variance = np.zeros(maxdegree)\n",
- "polydegree = np.zeros(maxdegree)\n",
- "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
- "\n",
- "for degree in range(maxdegree):\n",
- " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
- " y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
- " for i in range(n_boostraps):\n",
- " x_, y_ = resample(x_train, y_train)\n",
- " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
- "\n",
- " polydegree[degree] = degree\n",
- " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
- " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
- " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
- " print('Polynomial degree:', degree)\n",
- " print('Error:', error[degree])\n",
- " print('Bias^2:', bias[degree])\n",
- " print('Var:', variance[degree])\n",
- " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n",
- "\n",
- "plt.plot(polydegree, error, label='Error')\n",
- "plt.plot(polydegree, bias, label='bias')\n",
- "plt.plot(polydegree, variance, label='Variance')\n",
- "plt.legend()\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The bias-variance tradeoff summarizes the fundamental tension in\n",
- "machine learning, particularly supervised learning, between the\n",
- "complexity of a model and the amount of training data needed to train\n",
- "it. Since data is often limited, in practice it is often useful to\n",
- "use a less-complex model with higher bias, that is a model whose asymptotic\n",
- "performance is worse than another model because it is easier to\n",
- "train and less sensitive to sampling noise arising from having a\n",
- "finite-sized training dataset (smaller variance). \n",
- "\n",
- "\n",
- "\n",
- "The above equations tell us that in\n",
- "order to minimize the expected test error, we need to select a\n",
- "statistical learning method that simultaneously achieves low variance\n",
- "and low bias. Note that variance is inherently a nonnegative quantity,\n",
- "and squared bias is also nonnegative. Hence, we see that the expected\n",
- "test MSE can never lie below $Var(\\epsilon)$, the irreducible error.\n",
- "\n",
- "\n",
- "What do we mean by the variance and bias of a statistical learning\n",
- "method? The variance refers to the amount by which our model would change if we\n",
- "estimated it using a different training data set. Since the training\n",
- "data are used to fit the statistical learning method, different\n",
- "training data sets will result in a different estimate. But ideally the\n",
- "estimate for our model should not vary too much between training\n",
- "sets. However, if a method has high variance then small changes in\n",
- "the training data can result in large changes in the model. In general, more\n",
- "flexible statistical methods have higher variance.\n",
- "\n",
- "\n",
- "You may also find this recent [article](https://www.pnas.org/content/116/32/15849) of interest."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "\"\"\"\n",
- "============================\n",
- "Underfitting vs. Overfitting\n",
- "============================\n",
- "\n",
- "This example demonstrates the problems of underfitting and overfitting and\n",
- "how we can use linear regression with polynomial features to approximate\n",
- "nonlinear functions. The plot shows the function that we want to approximate,\n",
- "which is a part of the cosine function. In addition, the samples from the\n",
- "real function and the approximations of different models are displayed. The\n",
- "models have polynomial features of different degrees. We can see that a\n",
- "linear function (polynomial with degree 1) is not sufficient to fit the\n",
- "training samples. This is called **underfitting**. A polynomial of degree 4\n",
- "approximates the true function almost perfectly. However, for higher degrees\n",
- "the model will **overfit** the training data, i.e. it learns the noise of the\n",
- "training data.\n",
- "We evaluate quantitatively **overfitting** / **underfitting** by using\n",
- "cross-validation. We calculate the mean squared error (MSE) on the validation\n",
- "set, the higher, the less likely the model generalizes correctly from the\n",
- "training data.\n",
- "\"\"\"\n",
- "\n",
- "print(__doc__)\n",
- "\n",
- "import numpy as np\n",
- "import matplotlib.pyplot as plt\n",
- "from sklearn.pipeline import Pipeline\n",
- "from sklearn.preprocessing import PolynomialFeatures\n",
- "from sklearn.linear_model import LinearRegression\n",
- "from sklearn.model_selection import cross_val_score\n",
- "\n",
- "\n",
- "def true_fun(X):\n",
- " return np.cos(1.5 * np.pi * X)\n",
- "\n",
- "np.random.seed(0)\n",
- "\n",
- "n_samples = 30\n",
- "degrees = [1, 4, 15]\n",
- "\n",
- "X = np.sort(np.random.rand(n_samples))\n",
- "y = true_fun(X) + np.random.randn(n_samples) * 0.1\n",
- "\n",
- "plt.figure(figsize=(14, 5))\n",
- "for i in range(len(degrees)):\n",
- " ax = plt.subplot(1, len(degrees), i + 1)\n",
- " plt.setp(ax, xticks=(), yticks=())\n",
- "\n",
- " polynomial_features = PolynomialFeatures(degree=degrees[i],\n",
- " include_bias=False)\n",
- " linear_regression = LinearRegression()\n",
- " pipeline = Pipeline([(\"polynomial_features\", polynomial_features),\n",
- " (\"linear_regression\", linear_regression)])\n",
- " pipeline.fit(X[:, np.newaxis], y)\n",
- "\n",
- " # Evaluate the models using crossvalidation\n",
- " scores = cross_val_score(pipeline, X[:, np.newaxis], y,\n",
- " scoring=\"neg_mean_squared_error\", cv=10)\n",
- "\n",
- " X_test = np.linspace(0, 1, 100)\n",
- " plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label=\"Model\")\n",
- " plt.plot(X_test, true_fun(X_test), label=\"True function\")\n",
- " plt.scatter(X, y, edgecolor='b', s=20, label=\"Samples\")\n",
- " plt.xlabel(\"x\")\n",
- " plt.ylabel(\"y\")\n",
- " plt.xlim((0, 1))\n",
- " plt.ylim((-2, 2))\n",
- " plt.legend(loc=\"best\")\n",
- " plt.title(\"Degree {}\\nMSE = {:.2e}(+/- {:.2e})\".format(\n",
- " degrees[i], -scores.mean(), scores.std()))\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "# Common imports\n",
- "import os\n",
- "import numpy as np\n",
- "import pandas as pd\n",
- "import matplotlib.pyplot as plt\n",
- "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
- "from sklearn.model_selection import train_test_split\n",
- "from sklearn.utils import resample\n",
- "from sklearn.metrics import mean_squared_error\n",
- "# Where to save the figures and data files\n",
- "PROJECT_ROOT_DIR = \"Results\"\n",
- "FIGURE_ID = \"Results/FigureFiles\"\n",
- "DATA_ID = \"DataFiles/\"\n",
- "\n",
- "if not os.path.exists(PROJECT_ROOT_DIR):\n",
- " os.mkdir(PROJECT_ROOT_DIR)\n",
- "\n",
- "if not os.path.exists(FIGURE_ID):\n",
- " os.makedirs(FIGURE_ID)\n",
- "\n",
- "if not os.path.exists(DATA_ID):\n",
- " os.makedirs(DATA_ID)\n",
- "\n",
- "def image_path(fig_id):\n",
- " return os.path.join(FIGURE_ID, fig_id)\n",
- "\n",
- "def data_path(dat_id):\n",
- " return os.path.join(DATA_ID, dat_id)\n",
- "\n",
- "def save_fig(fig_id):\n",
- " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
- "\n",
- "infile = open(data_path(\"EoS.csv\"),'r')\n",
- "\n",
- "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
- "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
- "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
- "EoS = EoS.dropna()\n",
- "Energies = EoS['Energy']\n",
- "Density = EoS['Density']\n",
- "# The design matrix now as function of various polytrops\n",
- "\n",
- "Maxpolydegree = 30\n",
- "X = np.zeros((len(Density),Maxpolydegree))\n",
+ "Maxpolydegree = 5\n",
+ "X = np.zeros((len(x),Maxpolydegree))\n",
"X[:,0] = 1.0\n",
- "testerror = np.zeros(Maxpolydegree)\n",
- "trainingerror = np.zeros(Maxpolydegree)\n",
- "polynomial = np.zeros(Maxpolydegree)\n",
- "\n",
- "trials = 100\n",
- "for polydegree in range(1, Maxpolydegree):\n",
- " polynomial[polydegree] = polydegree\n",
- " for degree in range(polydegree):\n",
- " X[:,degree] = Density**(degree/3.0)\n",
- "\n",
- "# loop over trials in order to estimate the expectation value of the MSE\n",
- " testerror[polydegree] = 0.0\n",
- " trainingerror[polydegree] = 0.0\n",
- " for samples in range(trials):\n",
- " x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n",
- " model = LinearRegression(fit_intercept=True).fit(x_train, y_train)\n",
- " ypred = model.predict(x_train)\n",
- " ytilde = model.predict(x_test)\n",
- " testerror[polydegree] += mean_squared_error(y_test, ytilde)\n",
- " trainingerror[polydegree] += mean_squared_error(y_train, ypred) \n",
- "\n",
- " testerror[polydegree] /= trials\n",
- " trainingerror[polydegree] /= trials\n",
- " print(\"Degree of polynomial: %3d\"% polynomial[polydegree])\n",
- " print(\"Mean squared error on training data: %.8f\" % trainingerror[polydegree])\n",
- " print(\"Mean squared error on test data: %.8f\" % testerror[polydegree])\n",
- "\n",
- "plt.plot(polynomial, np.log10(trainingerror), label='Training Error')\n",
- "plt.plot(polynomial, np.log10(testerror), label='Test Error')\n",
- "plt.xlabel('Polynomial degree')\n",
- "plt.ylabel('log10[MSE]')\n",
- "plt.legend()\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "# Common imports\n",
- "import os\n",
- "import numpy as np\n",
- "import pandas as pd\n",
- "import matplotlib.pyplot as plt\n",
- "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
- "from sklearn.metrics import mean_squared_error\n",
- "from sklearn.model_selection import KFold\n",
- "from sklearn.model_selection import cross_val_score\n",
- "\n",
- "\n",
- "# Where to save the figures and data files\n",
- "PROJECT_ROOT_DIR = \"Results\"\n",
- "FIGURE_ID = \"Results/FigureFiles\"\n",
- "DATA_ID = \"DataFiles/\"\n",
- "\n",
- "if not os.path.exists(PROJECT_ROOT_DIR):\n",
- " os.mkdir(PROJECT_ROOT_DIR)\n",
- "\n",
- "if not os.path.exists(FIGURE_ID):\n",
- " os.makedirs(FIGURE_ID)\n",
- "\n",
- "if not os.path.exists(DATA_ID):\n",
- " os.makedirs(DATA_ID)\n",
- "\n",
- "def image_path(fig_id):\n",
- " return os.path.join(FIGURE_ID, fig_id)\n",
- "\n",
- "def data_path(dat_id):\n",
- " return os.path.join(DATA_ID, dat_id)\n",
- "\n",
- "def save_fig(fig_id):\n",
- " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
- "\n",
- "infile = open(data_path(\"EoS.csv\"),'r')\n",
- "\n",
- "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
- "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
- "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
- "EoS = EoS.dropna()\n",
- "Energies = EoS['Energy']\n",
- "Density = EoS['Density']\n",
- "# The design matrix now as function of various polytrops\n",
- "\n",
- "Maxpolydegree = 30\n",
- "X = np.zeros((len(Density),Maxpolydegree))\n",
- "X[:,0] = 1.0\n",
- "estimated_mse_sklearn = np.zeros(Maxpolydegree)\n",
- "polynomial = np.zeros(Maxpolydegree)\n",
- "k =5\n",
- "kfold = KFold(n_splits = k)\n",
"\n",
"for polydegree in range(1, Maxpolydegree):\n",
- " polynomial[polydegree] = polydegree\n",
" for degree in range(polydegree):\n",
- " X[:,degree] = Density**(degree/3.0)\n",
- " OLS = LinearRegression()\n",
- "# loop over trials in order to estimate the expectation value of the MSE\n",
- " estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)\n",
- "#[:, np.newaxis]\n",
- " estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)\n",
+ " X[:,degree] = x**(degree)\n",
"\n",
- "plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')\n",
- "plt.xlabel('Polynomial degree')\n",
- "plt.ylabel('log10[MSE]')\n",
- "plt.legend()\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "import numpy as np\n",
- "import matplotlib.pyplot as plt\n",
- "from sklearn.model_selection import KFold\n",
- "from sklearn.linear_model import Ridge\n",
- "from sklearn.model_selection import cross_val_score\n",
- "from sklearn.preprocessing import PolynomialFeatures\n",
"\n",
- "# A seed just to ensure that the random numbers are the same for every run.\n",
- "np.random.seed(3155)\n",
- "# Generate the data.\n",
- "n = 100\n",
- "x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
- "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
- "# Decide degree on polynomial to fit\n",
- "poly = PolynomialFeatures(degree = 10)\n",
+ "# We split the data in test and training data\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
"\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.pinv(X_train.T @ X_train) @ X_train.T @ y_train\n",
+ "print(OLSbeta)\n",
+ "ypredictOLS = X_test @ OLSbeta\n",
+ "print(\"Test MSE OLS\")\n",
+ "print(MSE(y_test,ypredictOLS))\n",
+ "# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn\n",
"# Decide which values of lambda to use\n",
- "nlambdas = 500\n",
- "lambdas = np.logspace(-3, 5, nlambdas)\n",
- "# Initialize a KFold instance\n",
- "k = 5\n",
- "kfold = KFold(n_splits = k)\n",
- "estimated_mse_sklearn = np.zeros(nlambdas)\n",
- "i = 0\n",
- "for lmb in lambdas:\n",
- " ridge = Ridge(alpha = lmb)\n",
- " estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)\n",
- " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n",
- " i += 1\n",
+ "nlambdas = 4\n",
+ "MSERidgePredict = np.zeros(nlambdas)\n",
+ "MSELassoPredict = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-3, 1, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " # Make the fit using Ridge and Lasso\n",
+ " RegRidge = linear_model.Ridge(lmb,fit_intercept=False)\n",
+ " RegRidge.fit(X_train,y_train)\n",
+ " RegLasso = linear_model.Lasso(lmb,fit_intercept=False)\n",
+ " RegLasso.fit(X_train,y_train)\n",
+ " # and then make the prediction\n",
+ " ypredictRidge = RegRidge.predict(X_test)\n",
+ " ypredictLasso = RegLasso.predict(X_test)\n",
+ " # Compute the MSE and print it\n",
+ " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n",
+ " MSELassoPredict[i] = MSE(y_test,ypredictLasso)\n",
+ " print(lmb,RegRidge.coef_)\n",
+ " print(lmb,RegLasso.coef_)\n",
+ "# Now plot the results\n",
"plt.figure()\n",
- "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n",
+ "plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')\n",
+ "plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')\n",
"plt.xlabel('log10(lambda)')\n",
"plt.ylabel('MSE')\n",
"plt.legend()\n",
"plt.show()"
]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "How can we understand this? \n",
+ "\n",
+ "\n",
+ "\n",
+ "Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression. \n",
+ "\n",
+ "For ordinary least squares we postulated that the maximum likelihood for the doamin of events $\\boldsymbol{D}$ (one-dimensional case)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})],\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "is given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set $\\boldsymbol{\\beta}$ given a domain of events $\\boldsymbol{D}$? That is, how can we define the posterior probability"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Bayes' theorem comes to our rescue here since (omitting the normalization constant)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})\\propto p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})p(\\boldsymbol{\\beta}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We have a model for $p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})$ but need one for the **prior** $p(\\boldsymbol{\\beta}$! \n",
+ "\n",
+ "\n",
+ "\n",
+ "With the posterior probability defined by a likelihood which we have\n",
+ "already modeled and an unknown prior, we are now ready to make\n",
+ "additional models for the prior.\n",
+ "\n",
+ "We can, based on our discussions of the variance of $\\boldsymbol{\\beta}$ and the mean value, assume that the prior for the values $\\boldsymbol{\\beta}$ is given by a Gaussian with mean value zero and variance $\\tau^2$, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Our posterior probability becomes then (omitting the normalization factor which is just a constant)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta\\vert\\boldsymbol{D})}=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can now optimize this quantity with respect to $\\boldsymbol{\\beta}$. As we\n",
+ "did for OLS, this is most conveniently done by taking the negative\n",
+ "logarithm of the posterior probability. Doing so and leaving out the\n",
+ "constants terms that do not depend on $\\beta$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{2\\tau^2}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and replacing $1/2\\tau^2$ with $\\lambda$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is our Ridge cost function! Nice, isn't it?\n",
+ "\n",
+ "\n",
+ "To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution ([Laplace in this case](https://en.wikipedia.org/wiki/Laplace_distribution)) with zero mean value, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Our posterior probability becomes then (omitting the normalization factor which is just a constant)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Taking the negative\n",
+ "logarithm of the posterior probability and leaving out the\n",
+ "constants terms that do not depend on $\\beta$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{\\tau}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and replacing $1/\\tau$ with $\\lambda$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is our Lasso cost function!"
+ ]
}
],
"metadata": {},
diff --git a/doc/LectureNotes/_build/html/_sources/chapter3.ipynb b/doc/LectureNotes/_build/html/_sources/chapter3.ipynb
index 5ede9f687..d7f8222d5 100644
--- a/doc/LectureNotes/_build/html/_sources/chapter3.ipynb
+++ b/doc/LectureNotes/_build/html/_sources/chapter3.ipynb
@@ -4,40 +4,78 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "# Ridge and Lasso Regression\n",
+ "# Resampling Methods\n",
"\n",
- "[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember10.mp4?vrtx=view-as-webpage)\n",
+ "## Introduction\n",
+ "\n",
+ "Resampling methods are an indispensable tool in modern\n",
+ "statistics. They involve repeatedly drawing samples from a training\n",
+ "set and refitting a model of interest on each sample in order to\n",
+ "obtain additional information about the fitted model. For example, in\n",
+ "order to estimate the variability of a linear regression fit, we can\n",
+ "repeatedly draw different samples from the training data, fit a linear\n",
+ "regression to each new sample, and then examine the extent to which\n",
+ "the resulting fits differ. Such an approach may allow us to obtain\n",
+ "information that would not be available from fitting the model only\n",
+ "once using the original training sample.\n",
+ "\n",
+ "Two resampling methods are often used in Machine Learning analyses,\n",
+ "1. The **bootstrap method**\n",
+ "\n",
+ "2. and **Cross-Validation**\n",
+ "\n",
+ "In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular\n",
+ "cross-validation and the bootstrap method. \n",
"\n",
"\n",
- "## The singular value decomposition\n",
- "\n",
- "The examples we have looked at so far are cases where we normally can\n",
- "invert the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$. Using a polynomial expansion as we\n",
- "did both for the masses and the fitting of the equation of state,\n",
- "leads to row vectors of the design matrix which are essentially\n",
- "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. \n",
+ "Resampling approaches can be computationally expensive, because they\n",
+ "involve fitting the same statistical method multiple times using\n",
+ "different subsets of the training data. However, due to recent\n",
+ "advances in computing power, the computational requirements of\n",
+ "resampling methods generally are not prohibitive. In this chapter, we\n",
+ "discuss two of the most commonly used resampling methods,\n",
+ "cross-validation and the bootstrap. Both methods are important tools\n",
+ "in the practical application of many statistical learning\n",
+ "procedures. For example, cross-validation can be used to estimate the\n",
+ "test error associated with a given statistical learning method in\n",
+ "order to evaluate its performance, or to select the appropriate level\n",
+ "of flexibility. The process of evaluating a model’s performance is\n",
+ "known as model assessment, whereas the process of selecting the proper\n",
+ "level of flexibility for a model is known as model selection. The\n",
+ "bootstrap is widely used.\n",
"\n",
"\n",
+ "* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods\n",
"\n",
- "This may\n",
- "however not the be case in general and a standard matrix inversion\n",
- "algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.\n",
+ "* The results can be analysed with the same statistical tools as we would use analysing experimental data.\n",
"\n",
- "There is however a way to partially circumvent this problem and also gain some insights about the ordinary least squares approach, and later shrinkage methods like Ridge and Lasso regressions. \n",
+ "* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n",
"\n",
- "This is given by the **Singular Value Decomposition** algorithm, perhaps\n",
- "the most powerful linear algebra algorithm. Let us look at a\n",
- "different example where we may have problems with the standard matrix\n",
- "inversion algorithm. Thereafter we dive into the math of the SVD.\n",
+ "## Reminder on Statistics\n",
"\n",
"\n",
+ "* As in other experiments, many numerical experiments have two classes of errors:\n",
"\n",
- "One of the typical problems we encounter with linear regression, in particular \n",
- "when the matrix $\\boldsymbol{X}$ (our so-called design matrix) is high-dimensional, \n",
- "are problems with near singular or singular matrices. The column vectors of $\\boldsymbol{X}$ \n",
- "may be linearly dependent, normally referred to as super-collinearity. \n",
- "This means that the matrix may be rank deficient and it is basically impossible to \n",
- "to model the data using linear regression. As an example, consider the matrix"
+ " * Statistical errors\n",
+ "\n",
+ " * Systematical errors\n",
+ "\n",
+ "\n",
+ "* Statistical errors can be estimated using standard tools from statistics\n",
+ "\n",
+ "* Systematical errors are method specific and must be treated differently from case to case. \n",
+ "\n",
+ "The\n",
+ "advantage of doing linear regression is that we actually end up with\n",
+ "analytical expressions for several statistical quantities. \n",
+ "Standard least squares and Ridge regression allow us to\n",
+ "derive quantities like the variance and other expectation values in a\n",
+ "rather straightforward way.\n",
+ "\n",
+ "\n",
+ "It is assumed that $\\varepsilon_i\n",
+ "\\sim \\mathcal{N}(0, \\sigma^2)$ and the $\\varepsilon_{i}$ are\n",
+ "independent, i.e.:"
]
},
{
@@ -45,17 +83,10 @@
"metadata": {},
"source": [
"$$\n",
- "\\begin{align*}\n",
- "\\mathbf{X} & = \\left[\n",
- "\\begin{array}{rrr}\n",
- "1 & -1 & 2\n",
- "\\\\\n",
- "1 & 0 & 1\n",
- "\\\\\n",
- "1 & 2 & -1\n",
- "\\\\\n",
- "1 & 1 & 0\n",
- "\\end{array} \\right]\n",
+ "\\begin{align*} \n",
+ "\\mbox{Cov}(\\varepsilon_{i_1},\n",
+ "\\varepsilon_{i_2}) & = \\left\\{ \\begin{array}{lcc} \\sigma^2 & \\mbox{if}\n",
+ "& i_1 = i_2, \\\\ 0 & \\mbox{if} & i_1 \\not= i_2. \\end{array} \\right.\n",
"\\end{align*}\n",
"$$"
]
@@ -64,14 +95,21 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The columns of $\\boldsymbol{X}$ are linearly dependent. We see this easily since the \n",
- "the first column is the row-wise sum of the other two columns. The rank (more correct,\n",
- "the column rank) of a matrix is the dimension of the space spanned by the\n",
- "column vectors. Hence, the rank of $\\mathbf{X}$ is equal to the number\n",
- "of linearly independent columns. In this particular case the matrix has rank 2.\n",
+ "The randomness of $\\varepsilon_i$ implies that\n",
+ "$\\mathbf{y}_i$ is also a random variable. In particular,\n",
+ "$\\mathbf{y}_i$ is normally distributed, because $\\varepsilon_i \\sim\n",
+ "\\mathcal{N}(0, \\sigma^2)$ and $\\mathbf{X}_{i,\\ast} \\, \\boldsymbol{\\beta}$ is a\n",
+ "non-random scalar. To specify the parameters of the distribution of\n",
+ "$\\mathbf{y}_i$ we need to calculate its first two moments. \n",
"\n",
- "Super-collinearity of an $(n \\times p)$-dimensional design matrix $\\mathbf{X}$ implies\n",
- "that the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this"
+ "Recall that $\\boldsymbol{X}$ is a matrix of dimensionality $n\\times p$. The\n",
+ "notation above $\\mathbf{X}_{i,\\ast}$ means that we are looking at the\n",
+ "row number $i$ and perform a sum over all values $p$.\n",
+ "\n",
+ "\n",
+ "The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off)\n",
+ "that there exists a function $f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim \\mathcal{N}(0, \\sigma^2)$\n",
+ "which describe our data"
]
},
{
@@ -79,13 +117,43 @@
"metadata": {},
"source": [
"$$\n",
- "\\begin{align*}\n",
- "\\boldsymbol{X} & = \\left[\n",
- "\\begin{array}{rr}\n",
- "1 & -1\n",
- "\\\\\n",
- "1 & -1\n",
- "\\end{array} \\right].\n",
+ "\\boldsymbol{y} = f(\\boldsymbol{x})+\\boldsymbol{\\varepsilon}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We approximate this function with our model from the solution of the linear regression equations, that is our\n",
+ "function $f$ is approximated by $\\boldsymbol{\\tilde{y}}$ where we want to minimize $(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2$, our MSE, with"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can calculate the expectation value of $\\boldsymbol{y}$ for a given element $i$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*} \n",
+ "\\mathbb{E}(y_i) & =\n",
+ "\\mathbb{E}(\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}) + \\mathbb{E}(\\varepsilon_i)\n",
+ "\\, \\, \\, = \\, \\, \\, \\mathbf{X}_{i, \\ast} \\, \\beta, \n",
"\\end{align*}\n",
"$$"
]
@@ -94,39 +162,8 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "We see easily that $\\mbox{det}(\\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \\times (-1) - 1 \\times (-1) = 0$. Hence, $\\mathbf{X}$ is singular and its inverse is undefined.\n",
- "This is equivalent to saying that the matrix $\\boldsymbol{X}$ has at least an eigenvalue which is zero.\n",
- "\n",
- "\n",
- "If our design matrix $\\boldsymbol{X}$ which enters the linear regression problem"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "
\n",
- "\n",
- "$$\n",
- "\\begin{equation}\n",
- "\\boldsymbol{\\beta} = (\\boldsymbol{X}^{T} \\boldsymbol{X})^{-1} \\boldsymbol{X}^{T} \\boldsymbol{y},\n",
- "\\label{_auto1} \\tag{1}\n",
- "\\end{equation}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "has linearly dependent column vectors, we will not be able to compute the inverse\n",
- "of $\\boldsymbol{X}^T\\boldsymbol{X}$ and we cannot find the parameters (estimators) $\\beta_i$. \n",
- "The estimators are only well-defined if $(\\boldsymbol{X}^{T}\\boldsymbol{X})^{-1}$ exits. \n",
- "This is more likely to happen when the matrix $\\boldsymbol{X}$ is high-dimensional. In this case it is likely to encounter a situation where \n",
- "the regression parameters $\\beta_i$ cannot be estimated.\n",
- "\n",
- "A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change"
+ "while\n",
+ "its variance is"
]
},
{
@@ -134,7 +171,18 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X}^{T} \\boldsymbol{X} \\rightarrow \\boldsymbol{X}^{T} \\boldsymbol{X}+\\lambda \\boldsymbol{I},\n",
+ "\\begin{align*} \\mbox{Var}(y_i) & = \\mathbb{E} \\{ [y_i\n",
+ "- \\mathbb{E}(y_i)]^2 \\} \\, \\, \\, = \\, \\, \\, \\mathbb{E} ( y_i^2 ) -\n",
+ "[\\mathbb{E}(y_i)]^2 \\\\ & = \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\,\n",
+ "\\beta + \\varepsilon_i )^2] - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \\\\ &\n",
+ "= \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2 \\varepsilon_i\n",
+ "\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} + \\varepsilon_i^2 ] - ( \\mathbf{X}_{i,\n",
+ "\\ast} \\, \\beta)^2 \\\\ & = ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2\n",
+ "\\mathbb{E}(\\varepsilon_i) \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} +\n",
+ "\\mathbb{E}(\\varepsilon_i^2 ) - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \n",
+ "\\\\ & = \\mathbb{E}(\\varepsilon_i^2 ) \\, \\, \\, = \\, \\, \\,\n",
+ "\\mbox{Var}(\\varepsilon_i) \\, \\, \\, = \\, \\, \\, \\sigma^2. \n",
+ "\\end{align*}\n",
"$$"
]
},
@@ -142,16 +190,11 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "where $\\boldsymbol{I}$ is the identity matrix. When we discuss **Ridge** regression this is actually what we end up evaluating. The parameter $\\lambda$ is called a hyperparameter. More about this later. \n",
+ "Hence, $y_i \\sim \\mathcal{N}( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}, \\sigma^2)$, that is $\\boldsymbol{y}$ follows a normal distribution with \n",
+ "mean value $\\boldsymbol{X}\\boldsymbol{\\beta}$ and variance $\\sigma^2$ (not be confused with the singular values of the SVD). \n",
"\n",
"\n",
- "\n",
- "\n",
- "\n",
- "From standard linear algebra we know that a square matrix $\\boldsymbol{X}$ can be diagonalized if and only it is \n",
- "a so-called [normal matrix](https://en.wikipedia.org/wiki/Normal_matrix), that is if $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$\n",
- "we have $\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ or if $\\boldsymbol{X}\\in {\\mathbb{C}}^{n\\times n}$ we have $\\boldsymbol{X}\\boldsymbol{X}^{\\dagger}=\\boldsymbol{X}^{\\dagger}\\boldsymbol{X}$.\n",
- "The matrix has then a set of eigenpairs"
+ "With the OLS expressions for the parameters $\\boldsymbol{\\beta}$ we can evaluate the expectation value"
]
},
{
@@ -159,7 +202,7 @@
"metadata": {},
"source": [
"$$\n",
- "(\\lambda_1,\\boldsymbol{u}_1),\\dots, (\\lambda_n,\\boldsymbol{u}_n),\n",
+ "\\mathbb{E}(\\boldsymbol{\\beta}) = \\mathbb{E}[ (\\mathbf{X}^{\\top} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbb{E}[ \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\mathbf{X}^{T}\\mathbf{X}\\boldsymbol{\\beta}=\\boldsymbol{\\beta}.\n",
"$$"
]
},
@@ -167,7 +210,11 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "and the eigenvalues are given by the diagonal matrix"
+ "This means that the estimator of the regression parameters is unbiased.\n",
+ "\n",
+ "We can also calculate the variance\n",
+ "\n",
+ "The variance of $\\boldsymbol{\\beta}$ is"
]
},
{
@@ -175,7 +222,26 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{\\Sigma}=\\mathrm{Diag}(\\lambda_1, \\dots,\\lambda_n).\n",
+ "\\begin{eqnarray*}\n",
+ "\\mbox{Var}(\\boldsymbol{\\beta}) & = & \\mathbb{E} \\{ [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})] [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})]^{T} \\}\n",
+ "\\\\\n",
+ "& = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} - \\boldsymbol{\\beta}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} - \\boldsymbol{\\beta}]^{T} \\}\n",
+ "\\\\\n",
+ "% & = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y}]^{T} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "% \\\\\n",
+ "% & = & \\mathbb{E} \\{ (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} \\, \\mathbf{Y}^{T} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "% \\\\\n",
+ "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\mathbb{E} \\{ \\mathbf{Y} \\, \\mathbf{Y}^{T} \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "\\\\\n",
+ "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\{ \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} + \\sigma^2 \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "% \\\\\n",
+ "% & = & (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^T \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T % \\mathbf{X})^{-1}\n",
+ "% \\\\\n",
+ "% & & + \\, \\, \\sigma^2 \\, (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\boldsymbol{\\beta}^T\n",
+ "\\\\\n",
+ "& = & \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} + \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "\\, \\, \\, = \\, \\, \\, \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1},\n",
+ "\\end{eqnarray*}\n",
"$$"
]
},
@@ -183,7 +249,21 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The matrix $\\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\\boldsymbol{U}$"
+ "where we have used that $\\mathbb{E} (\\mathbf{Y} \\mathbf{Y}^{T}) =\n",
+ "\\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} +\n",
+ "\\sigma^2 \\, \\mathbf{I}_{nn}$. From $\\mbox{Var}(\\boldsymbol{\\beta}) = \\sigma^2\n",
+ "\\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}$, one obtains an estimate of the\n",
+ "variance of the estimate of the $j$-th regression coefficient:\n",
+ "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 \\sqrt{\n",
+ "[(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} }$. This may be used to\n",
+ "construct a confidence interval for the estimates.\n",
+ "\n",
+ "\n",
+ "In a similar way, we can obtain analytical expressions for say the\n",
+ "expectation values of the parameters $\\boldsymbol{\\beta}$ and their variance\n",
+ "when we employ Ridge regression, allowing us again to define a confidence interval. \n",
+ "\n",
+ "It is rather straightforward to show that"
]
},
{
@@ -191,7 +271,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "\\mathbb{E} \\big[ \\boldsymbol{\\beta}^{\\mathrm{Ridge}} \\big]=(\\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I}_{pp})^{-1} (\\mathbf{X}^{\\top} \\mathbf{X})\\boldsymbol{\\beta}^{\\mathrm{OLS}}.\n",
"$$"
]
},
@@ -199,9 +279,10 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "with $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ or $\\boldsymbol{U}\\boldsymbol{U}^{\\dagger}=\\boldsymbol{I}$.\n",
+ "We see clearly that \n",
+ "$\\mathbb{E} \\big[ \\boldsymbol{\\beta}^{\\mathrm{Ridge}} \\big] \\not= \\boldsymbol{\\beta}^{\\mathrm{OLS}}$ for any $\\lambda > 0$. We say then that the ridge estimator is biased.\n",
"\n",
- "Not all square matrices are diagonalizable. A matrix like the one discussed above"
+ "We can also compute the variance as"
]
},
{
@@ -209,10 +290,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X} = \\begin{bmatrix} \n",
- "1& -1 \\\\\n",
- "1& -1\\\\\n",
- "\\end{bmatrix}\n",
+ "\\mbox{Var}[\\boldsymbol{\\beta}^{\\mathrm{Ridge}}]=\\sigma^2[ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1} \\mathbf{X}^{T} \\mathbf{X} \\{ [ \\mathbf{X}^{\\top} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T},\n",
"$$"
]
},
@@ -220,23 +298,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "is not diagonalizable, it is a so-called [defective matrix](https://en.wikipedia.org/wiki/Defective_matrix). It is easy to see that the condition\n",
- "$\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ is not fulfilled. \n",
+ "and it is easy to see that if the parameter $\\lambda$ goes to infinity then the variance of Ridge parameters $\\boldsymbol{\\beta}$ goes to zero. \n",
"\n",
- "\n",
- "\n",
- "## The SVD, a Fantastic Algorithm\n",
- "\n",
- "\n",
- "However, and this is the strength of the SVD algorithm, any general\n",
- "matrix $\\boldsymbol{X}$ can be decomposed in terms of a diagonal matrix and\n",
- "two orthogonal/unitary matrices. The [Singular Value Decompostion\n",
- "(SVD) theorem](https://en.wikipedia.org/wiki/Singular_value_decomposition)\n",
- "states that a general $m\\times n$ matrix $\\boldsymbol{X}$ can be written in\n",
- "terms of a diagonal matrix $\\boldsymbol{\\Sigma}$ of dimensionality $m\\times n$\n",
- "and two orthognal matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$, where the first has\n",
- "dimensionality $m \\times m$ and the last dimensionality $n\\times n$.\n",
- "We have then"
+ "With this, we can compute the difference"
]
},
{
@@ -244,7 +308,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\n",
+ "\\mbox{Var}[\\boldsymbol{\\beta}^{\\mathrm{OLS}}]-\\mbox{Var}(\\boldsymbol{\\beta}^{\\mathrm{Ridge}})=\\sigma^2 [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}[ 2\\lambda\\mathbf{I} + \\lambda^2 (\\mathbf{X}^{T} \\mathbf{X})^{-1} ] \\{ [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T}.\n",
"$$"
]
},
@@ -252,7 +316,54 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "As an example, the above defective matrix can be decomposed as"
+ "The difference is non-negative definite since each component of the\n",
+ "matrix product is non-negative definite. \n",
+ "This means the variance we obtain with the standard OLS will always for $\\lambda > 0$ be larger than the variance of $\\boldsymbol{\\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. \n",
+ "\n",
+ "\n",
+ "\n",
+ "## Resampling methods\n",
+ "\n",
+ "With all these analytical equations for both the OLS and Ridge\n",
+ "regression, we will now outline how to assess a given model. This will\n",
+ "lead us to a discussion of the so-called bias-variance tradeoff (see\n",
+ "below) and so-called resampling methods.\n",
+ "\n",
+ "One of the quantities we have discussed as a way to measure errors is\n",
+ "the mean-squared error (MSE), mainly used for fitting of continuous\n",
+ "functions. Another choice is the absolute error.\n",
+ "\n",
+ "In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,\n",
+ "we discuss the\n",
+ "1. prediction error or simply the **test error** $\\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the \n",
+ "\n",
+ "2. training error $\\mathrm{Err_{Train}}$, which is the average loss over the training data.\n",
+ "\n",
+ "As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.\n",
+ "For a certain level of complexity the test error will reach minimum, before starting to increase again. The\n",
+ "training error reaches a saturation.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Two famous\n",
+ "resampling methods are the **independent bootstrap** and **the jackknife**. \n",
+ "\n",
+ "The jackknife is a special case of the independent bootstrap. Still, the jackknife was made\n",
+ "popular prior to the independent bootstrap. And as the popularity of\n",
+ "the independent bootstrap soared, new variants, such as **the dependent bootstrap**.\n",
+ "\n",
+ "The Jackknife and independent bootstrap work for\n",
+ "independent, identically distributed random variables.\n",
+ "If these conditions are not\n",
+ "satisfied, the methods will fail. Yet, it should be said that if the data are\n",
+ "independent, identically distributed, and we only want to estimate the\n",
+ "variance of $\\overline{X}$ (which often is the case), then there is no\n",
+ "need for bootstrapping. \n",
+ "\n",
+ "\n",
+ "The Jackknife works by making many replicas of the estimator $\\widehat{\\theta}$. \n",
+ "The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\\boldsymbol{x} = (x_1,x_2,\\cdots,X_n)$. \n",
+ "Let $\\boldsymbol{x}_i$ denote the vector"
]
},
{
@@ -260,7 +371,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X} = \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& 1 \\\\ 1& -1\\\\ \\end{bmatrix} \\begin{bmatrix} 2& 0 \\\\ 0& 0\\\\ \\end{bmatrix} \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& -1 \\\\ 1& 1\\\\ \\end{bmatrix}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "\\boldsymbol{x}_i = (x_1,x_2,\\cdots,x_{i-1},x_{i+1},\\cdots,x_n),\n",
"$$"
]
},
@@ -268,45 +379,290 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "with eigenvalues $\\sigma_1=2$ and $\\sigma_2=0$. \n",
- "The SVD exits always! \n",
+ "which equals the vector $\\boldsymbol{x}$ with the exception that observation\n",
+ "number $i$ is left out. Using this notation, define\n",
+ "$\\widehat{\\theta}_i$ to be the estimator\n",
+ "$\\widehat{\\theta}$ computed using $\\vec{X}_i$."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from numpy import *\n",
+ "from numpy.random import randint, randn\n",
+ "from time import time\n",
"\n",
- "The SVD\n",
- "decomposition (singular values) gives eigenvalues \n",
- "$\\sigma_i\\geq\\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=p$, the\n",
- "eigenvalues (singular values) are zero.\n",
+ "def jackknife(data, stat):\n",
+ " n = len(data);t = zeros(n); inds = arange(n); t0 = time()\n",
+ " ## 'jackknifing' by leaving out an observation for each i \n",
+ " for i in range(n):\n",
+ " t[i] = stat(delete(data,i) )\n",
"\n",
- "In the general case, where our design matrix $\\boldsymbol{X}$ has dimension\n",
- "$n\\times p$, the matrix is thus decomposed into an $n\\times n$\n",
- "orthogonal matrix $\\boldsymbol{U}$, a $p\\times p$ orthogonal matrix $\\boldsymbol{V}$\n",
- "and a diagonal matrix $\\boldsymbol{\\Sigma}$ with $r=\\mathrm{min}(n,p)$\n",
- "singular values $\\sigma_i\\geq 0$ on the main diagonal and zeros filling\n",
- "the rest of the matrix. There are at most $p$ singular values\n",
- "assuming that $n > p$. In our regression examples for the nuclear\n",
- "masses and the equation of state this is indeed the case, while for\n",
- "the Ising model we have $p > n$. These are often cases that lead to\n",
- "near singular or singular matrices.\n",
+ " # analysis \n",
+ " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Jackknife Statistics :\")\n",
+ " print(\"original bias std. error\")\n",
+ " print(\"%8g %14g %15g\" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))\n",
"\n",
- "The columns of $\\boldsymbol{U}$ are called the left singular vectors while the columns of $\\boldsymbol{V}$ are the right singular vectors.\n",
+ " return t\n",
"\n",
- "## Economy-size SVD\n",
"\n",
- "If we assume that $n > p$, then our matrix $\\boldsymbol{U}$ has dimension $n\n",
- "\\times n$. The last $n-p$ columns of $\\boldsymbol{U}$ become however\n",
- "irrelevant in our calculations since they are multiplied with the\n",
- "zeros in $\\boldsymbol{\\Sigma}$.\n",
+ "# Returns mean of data samples \n",
+ "def stat(data):\n",
+ " return mean(data)\n",
"\n",
- "The economy-size decomposition removes extra rows or columns of zeros\n",
- "from the diagonal matrix of singular values, $\\boldsymbol{\\Sigma}$, along with the columns\n",
- "in either $\\boldsymbol{U}$ or $\\boldsymbol{V}$ that multiply those zeros in the expression. \n",
- "Removing these zeros and columns can improve execution time\n",
- "and reduce storage requirements without compromising the accuracy of\n",
- "the decomposition.\n",
"\n",
- "If $n > p$, we keep only the first $p$ columns of $\\boldsymbol{U}$ and $\\boldsymbol{\\Sigma}$ has dimension $p\\times p$. \n",
- "If $p > n$, then only the first $n$ columns of $\\boldsymbol{V}$ are computed and $\\boldsymbol{\\Sigma}$ has dimension $n\\times n$.\n",
- "The $n=p$ case is obvious, we retain the full SVD. \n",
- "In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy."
+ "mu, sigma = 100, 15\n",
+ "datapoints = 10000\n",
+ "x = mu + sigma*random.randn(datapoints)\n",
+ "# jackknife returns the data sample \n",
+ "t = jackknife(x, stat)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Bootstrap\n",
+ "\n",
+ "Bootstrapping is a nonparametric approach to statistical inference\n",
+ "that substitutes computation for more traditional distributional\n",
+ "assumptions and asymptotic results. Bootstrapping offers a number of\n",
+ "advantages: \n",
+ "1. The bootstrap is quite general, although there are some cases in which it fails. \n",
+ "\n",
+ "2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. \n",
+ "\n",
+ "3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. \n",
+ "\n",
+ "4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).\n",
+ "\n",
+ "Since $\\widehat{\\theta} = \\widehat{\\theta}(\\boldsymbol{X})$ is a function of random variables,\n",
+ "$\\widehat{\\theta}$ itself must be a random variable. Thus it has\n",
+ "a pdf, call this function $p(\\boldsymbol{t})$. The aim of the bootstrap is to\n",
+ "estimate $p(\\boldsymbol{t})$ by the relative frequency of\n",
+ "$\\widehat{\\theta}$. You can think of this as using a histogram\n",
+ "in the place of $p(\\boldsymbol{t})$. If the relative frequency closely\n",
+ "resembles $p(\\vec{t})$, then using numerics, it is straight forward to\n",
+ "estimate all the interesting parameters of $p(\\boldsymbol{t})$ using point\n",
+ "estimators. \n",
+ "\n",
+ "\n",
+ "\n",
+ "In the case that $\\widehat{\\theta}$ has\n",
+ "more than one component, and the components are independent, we use the\n",
+ "same estimator on each component separately. If the probability\n",
+ "density function of $X_i$, $p(x)$, had been known, then it would have\n",
+ "been straight forward to do this by: \n",
+ "1. Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \\cdots, X_n^*)$. \n",
+ "\n",
+ "2. Then using these numbers, we could compute a replica of $\\widehat{\\theta}$ called $\\widehat{\\theta}^*$. \n",
+ "\n",
+ "By repeated use of (1) and (2), many\n",
+ "estimates of $\\widehat{\\theta}$ could have been obtained. The\n",
+ "idea is to use the relative frequency of $\\widehat{\\theta}^*$\n",
+ "(think of a histogram) as an estimate of $p(\\boldsymbol{t})$.\n",
+ "\n",
+ "\n",
+ "But\n",
+ "unless there is enough information available about the process that\n",
+ "generated $X_1,X_2,\\cdots,X_n$, $p(x)$ is in general\n",
+ "unknown. Therefore, [Efron in 1979](https://projecteuclid.org/euclid.aos/1176344552) asked the\n",
+ "question: What if we replace $p(x)$ by the relative frequency\n",
+ "of the observation $X_i$; if we draw observations in accordance with\n",
+ "the relative frequency of the observations, will we obtain the same\n",
+ "result in some asymptotic sense? The answer is yes.\n",
+ "\n",
+ "\n",
+ "Instead of generating the histogram for the relative\n",
+ "frequency of the observation $X_i$, just draw the values\n",
+ "$(X_1^*,X_2^*,\\cdots,X_n^*)$ with replacement from the vector\n",
+ "$\\boldsymbol{X}$. \n",
+ "\n",
+ "\n",
+ "The independent bootstrap works like this: \n",
+ "\n",
+ "1. Draw with replacement $n$ numbers for the observed variables $\\boldsymbol{x} = (x_1,x_2,\\cdots,x_n)$. \n",
+ "\n",
+ "2. Define a vector $\\boldsymbol{x}^*$ containing the values which were drawn from $\\boldsymbol{x}$. \n",
+ "\n",
+ "3. Using the vector $\\boldsymbol{x}^*$ compute $\\widehat{\\theta}^*$ by evaluating $\\widehat \\theta$ under the observations $\\boldsymbol{x}^*$. \n",
+ "\n",
+ "4. Repeat this process $k$ times. \n",
+ "\n",
+ "When you are done, you can draw a histogram of the relative frequency\n",
+ "of $\\widehat \\theta^*$. This is your estimate of the probability\n",
+ "distribution $p(t)$. Using this probability distribution you can\n",
+ "estimate any statistics thereof. In principle you never draw the\n",
+ "histogram of the relative frequency of $\\widehat{\\theta}^*$. Instead\n",
+ "you use the estimators corresponding to the statistic of interest. For\n",
+ "example, if you are interested in estimating the variance of $\\widehat\n",
+ "\\theta$, apply the etsimator $\\widehat \\sigma^2$ to the values\n",
+ "$\\widehat \\theta ^*$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The following code starts with a Gaussian distribution with mean value\n",
+ "$\\mu =100$ and variance $\\sigma=15$. We use this to generate the data\n",
+ "used in the bootstrap analysis. The bootstrap analysis returns a data\n",
+ "set after a given number of bootstrap operations (as many as we have\n",
+ "data points). This data set consists of estimated mean values for each\n",
+ "bootstrap operation. The histogram generated by the bootstrap method\n",
+ "shows that the distribution for these mean values is also a Gaussian,\n",
+ "centered around the mean value $\\mu=100$ but with standard deviation\n",
+ "$\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in\n",
+ "this case the same as the number of original data points). The value\n",
+ "of the standard deviation is what we expect from the central limit\n",
+ "theorem."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "from numpy import *\n",
+ "from numpy.random import randint, randn\n",
+ "from time import time\n",
+ "import matplotlib.mlab as mlab\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "# Returns mean of bootstrap samples \n",
+ "def stat(data):\n",
+ " return mean(data)\n",
+ "\n",
+ "# Bootstrap algorithm\n",
+ "def bootstrap(data, statistic, R):\n",
+ " t = zeros(R); n = len(data); inds = arange(n); t0 = time()\n",
+ " # non-parametric bootstrap \n",
+ " for i in range(R):\n",
+ " t[i] = statistic(data[randint(0,n,n)])\n",
+ "\n",
+ " # analysis \n",
+ " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Bootstrap Statistics :\")\n",
+ " print(\"original bias std. error\")\n",
+ " print(\"%8g %8g %14g %15g\" % (statistic(data), std(data),mean(t),std(t)))\n",
+ " return t\n",
+ "\n",
+ "\n",
+ "mu, sigma = 100, 15\n",
+ "datapoints = 10000\n",
+ "x = mu + sigma*random.randn(datapoints)\n",
+ "# bootstrap returns the data sample \n",
+ "t = bootstrap(x, stat, datapoints)\n",
+ "# the histogram of the bootstrapped data \n",
+ "n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)\n",
+ "\n",
+ "# add a 'best fit' line \n",
+ "y = mlab.normpdf( binsboot, mean(t), std(t))\n",
+ "lt = plt.plot(binsboot, y, 'r--', linewidth=1)\n",
+ "plt.xlabel('Smarts')\n",
+ "plt.ylabel('Probability')\n",
+ "plt.axis([99.5, 100.6, 0, 3.0])\n",
+ "plt.grid(True)\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Various steps in cross-validation\n",
+ "\n",
+ "When the repetitive splitting of the data set is done randomly,\n",
+ "samples may accidently end up in a fast majority of the splits in\n",
+ "either training or test set. Such samples may have an unbalanced\n",
+ "influence on either model building or prediction evaluation. To avoid\n",
+ "this $k$-fold cross-validation structures the data splitting. The\n",
+ "samples are divided into $k$ more or less equally sized exhaustive and\n",
+ "mutually exclusive subsets. In turn (at each split) one of these\n",
+ "subsets plays the role of the test set while the union of the\n",
+ "remaining subsets constitutes the training set. Such a splitting\n",
+ "warrants a balanced representation of each sample in both training and\n",
+ "test set over the splits. Still the division into the $k$ subsets\n",
+ "involves a degree of randomness. This may be fully excluded when\n",
+ "choosing $k=n$. This particular case is referred to as leave-one-out\n",
+ "cross-validation (LOOCV). \n",
+ "\n",
+ "\n",
+ "* Define a range of interest for the penalty parameter.\n",
+ "\n",
+ "* Divide the data set into training and test set comprising samples $\\{1, \\ldots, n\\} \\setminus i$ and $\\{ i \\}$, respectively.\n",
+ "\n",
+ "* Fit the linear regression model by means of ridge estimation for each $\\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\\boldsymbol{\\sigma}_{-i}^2(\\lambda)$, as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\boldsymbol{\\beta}_{-i}(\\lambda) & = ( \\boldsymbol{X}_{-i, \\ast}^{T}\n",
+ "\\boldsymbol{X}_{-i, \\ast} + \\lambda \\boldsymbol{I}_{pp})^{-1}\n",
+ "\\boldsymbol{X}_{-i, \\ast}^{T} \\boldsymbol{y}_{-i}\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "* Evaluate the prediction performance of these models on the test set by $\\log\\{L[y_i, \\boldsymbol{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}$. Or, by the prediction error $|y_i - \\boldsymbol{X}_{i, \\ast} \\boldsymbol{\\beta}_{-i}(\\lambda)|$, the relative error, the error squared or the R2 score function.\n",
+ "\n",
+ "* Repeat the first three steps such that each sample plays the role of the test set once.\n",
+ "\n",
+ "* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\frac{1}{n} \\sum_{i = 1}^n \\log\\{L[y_i, \\mathbf{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}.\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For the various values of $k$\n",
+ "\n",
+ "1. shuffle the dataset randomly.\n",
+ "\n",
+ "2. Split the dataset into $k$ groups.\n",
+ "\n",
+ "3. For each unique group:\n",
+ "\n",
+ "a. Decide which group to use as set for test data\n",
+ "\n",
+ "b. Take the remaining groups as a training data set\n",
+ "\n",
+ "c. Fit a model on the training set and evaluate it on the test set\n",
+ "\n",
+ "d. Retain the evaluation score and discard the model\n",
+ "\n",
+ "\n",
+ "5. Summarize the model using the sample of model evaluation scores\n",
+ "\n",
+ "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial."
]
},
{
@@ -319,60 +675,110 @@
"outputs": [],
"source": [
"import numpy as np\n",
- "# SVD inversion\n",
- "def SVDinv(A):\n",
- " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n",
- " SVD is numerically more stable than the inversion algorithms provided by\n",
- " numpy and scipy.linalg at the cost of being slower.\n",
- " '''\n",
- " U, s, VT = np.linalg.svd(A)\n",
- "# print('test U')\n",
- "# print( (np.transpose(U) @ U - U @np.transpose(U)))\n",
- "# print('test VT')\n",
- "# print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n",
- " print(U)\n",
- " print(s)\n",
- " print(VT)\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import KFold\n",
+ "from sklearn.linear_model import Ridge\n",
+ "from sklearn.model_selection import cross_val_score\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
"\n",
- " D = np.zeros((len(U),len(VT)))\n",
- " for i in range(0,len(VT)):\n",
- " D[i,i]=s[i]\n",
- " UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)\n",
- " return np.matmul(V,np.matmul(invD,UT))\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "np.random.seed(3155)\n",
+ "\n",
+ "# Generate the data.\n",
+ "nsamples = 100\n",
+ "x = np.random.randn(nsamples)\n",
+ "y = 3*x**2 + np.random.randn(nsamples)\n",
+ "\n",
+ "## Cross-validation on Ridge regression using KFold only\n",
+ "\n",
+ "# Decide degree on polynomial to fit\n",
+ "poly = PolynomialFeatures(degree = 6)\n",
+ "\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 500\n",
+ "lambdas = np.logspace(-3, 5, nlambdas)\n",
+ "\n",
+ "# Initialize a KFold instance\n",
+ "k = 5\n",
+ "kfold = KFold(n_splits = k)\n",
+ "\n",
+ "# Perform the cross-validation to estimate MSE\n",
+ "scores_KFold = np.zeros((nlambdas, k))\n",
+ "\n",
+ "i = 0\n",
+ "for lmb in lambdas:\n",
+ " ridge = Ridge(alpha = lmb)\n",
+ " j = 0\n",
+ " for train_inds, test_inds in kfold.split(x):\n",
+ " xtrain = x[train_inds]\n",
+ " ytrain = y[train_inds]\n",
+ "\n",
+ " xtest = x[test_inds]\n",
+ " ytest = y[test_inds]\n",
+ "\n",
+ " Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n",
+ " ridge.fit(Xtrain, ytrain[:, np.newaxis])\n",
+ "\n",
+ " Xtest = poly.fit_transform(xtest[:, np.newaxis])\n",
+ " ypred = ridge.predict(Xtest)\n",
+ "\n",
+ " scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n",
+ "\n",
+ " j += 1\n",
+ " i += 1\n",
"\n",
"\n",
- "X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])\n",
- "print(X)\n",
- "A = np.transpose(X) @ X\n",
- "print(A)\n",
- "# Brute force inversion of super-collinear matrix\n",
- "#B = np.linalg.inv(A)\n",
- "#print(B)\n",
- "C = SVDinv(A)\n",
- "print(C)"
+ "estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n",
+ "\n",
+ "## Cross-validation using cross_val_score from sklearn along with KFold\n",
+ "\n",
+ "# kfold is an instance initialized above as:\n",
+ "# kfold = KFold(n_splits = k)\n",
+ "\n",
+ "estimated_mse_sklearn = np.zeros(nlambdas)\n",
+ "i = 0\n",
+ "for lmb in lambdas:\n",
+ " ridge = Ridge(alpha = lmb)\n",
+ "\n",
+ " X = poly.fit_transform(x[:, np.newaxis])\n",
+ " estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n",
+ "\n",
+ " # cross_val_score return an array containing the estimated negative mse for every fold.\n",
+ " # we have to the the mean of every array in order to get an estimate of the mse of the model\n",
+ " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n",
+ "\n",
+ " i += 1\n",
+ "\n",
+ "## Plot and compare the slightly different ways to perform cross-validation\n",
+ "\n",
+ "plt.figure()\n",
+ "\n",
+ "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n",
+ "plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n",
+ "\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('mse')\n",
+ "\n",
+ "plt.legend()\n",
+ "\n",
+ "plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "The matrix $\\boldsymbol{X}$ has columns that are linearly dependent. The first\n",
- "column is the row-wise sum of the other two columns. The rank of a\n",
- "matrix (the column rank) is the dimension of space spanned by the\n",
- "column vectors. The rank of the matrix is the number of linearly\n",
- "independent columns, in this case just $2$. We see this from the\n",
- "singular values when running the above code. Running the standard\n",
- "inversion algorithm for matrix inversion with $\\boldsymbol{X}^T\\boldsymbol{X}$ results\n",
- "in the program terminating due to a singular matrix.\n",
+ "## The bias-variance tradeoff\n",
"\n",
"\n",
+ "We will discuss the bias-variance tradeoff in the context of\n",
+ "continuous predictions such as regression. However, many of the\n",
+ "intuitions and ideas discussed here also carry over to classification\n",
+ "tasks. Consider a dataset $\\mathcal{L}$ consisting of the data\n",
+ "$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$. \n",
"\n",
- "\n",
- "There are several interesting mathematical properties which will be\n",
- "relevant when we are going to discuss the differences between say\n",
- "ordinary least squares (OLS) and **Ridge** regression.\n",
- "\n",
- "We have from OLS that the parameters of the linear approximation are given by"
+ "Let us assume that the true data is generated from a noisy model"
]
},
{
@@ -380,7 +786,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}\n",
"$$"
]
},
@@ -388,7 +794,14 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The matrix to invert can be rewritten in terms of our SVD decomposition as"
+ "where $\\epsilon$ is normally distributed with mean zero and standard deviation $\\sigma^2$.\n",
+ "\n",
+ "In our derivation of the ordinary least squares method we defined then\n",
+ "an approximation to the function $f$ in terms of the parameters\n",
+ "$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n",
+ "that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$. \n",
+ "\n",
+ "Thereafter we found the parameters $\\boldsymbol{\\beta}$ by optimizing the means squared error via the so-called cost function"
]
},
{
@@ -396,7 +809,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X}^T\\boldsymbol{X} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n",
"$$"
]
},
@@ -404,7 +817,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Using the orthogonality properties of $\\boldsymbol{U}$ we have"
+ "We can rewrite this as"
]
},
{
@@ -412,7 +825,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X}^T\\boldsymbol{X} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T = \\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T,\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\frac{1}{n}\\sum_i(f_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\sigma^2.\n",
"$$"
]
},
@@ -420,9 +833,14 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "with $\\boldsymbol{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared. \n",
+ "The three terms represent the square of the bias of the learning\n",
+ "method, which can be thought of as the error caused by the simplifying\n",
+ "assumptions built into the method. The second term represents the\n",
+ "variance of the chosen model and finally the last terms is variance of\n",
+ "the error $\\boldsymbol{\\epsilon}$.\n",
"\n",
- "This means that"
+ "To derive this equation, we need to recall that the variance of $\\boldsymbol{y}$ and $\\boldsymbol{\\epsilon}$ are both equal to $\\sigma^2$. The mean value of $\\boldsymbol{\\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\\boldsymbol{\\tilde{y}}$.\n",
+ "We use a more compact notation in terms of the expectation value"
]
},
{
@@ -430,7 +848,7 @@
"metadata": {},
"source": [
"$$\n",
- "(\\boldsymbol{X}^T\\boldsymbol{X})\\boldsymbol{V} = \\boldsymbol{V}\\boldsymbol{D},\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}})^2\\right],\n",
"$$"
]
},
@@ -438,7 +856,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "that is the eigenvectors of $(\\boldsymbol{X}^T\\boldsymbol{X})$ are given by the columns of the right singular matrix of $\\boldsymbol{X}$ and the eigenvalues are the squared singular values. It is easy to show (show this) that"
+ "and adding and subtracting $\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]$ we get"
]
},
{
@@ -446,7 +864,7 @@
"metadata": {},
"source": [
"$$\n",
- "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U} = \\boldsymbol{U}\\boldsymbol{D},\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}}+\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right],\n",
"$$"
]
},
@@ -454,9 +872,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "that is, the eigenvectors of $(\\boldsymbol{X}\\boldsymbol{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same. \n",
- "\n",
- "Going back to our OLS equation we have"
+ "which, using the abovementioned expectation values can be rewritten as"
]
},
{
@@ -464,7 +880,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right]+\\mathrm{Var}\\left[\\boldsymbol{\\tilde{y}}\\right]+\\sigma^2,\n",
"$$"
]
},
@@ -472,642 +888,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "We will come back to this expression when we discuss Ridge regression. \n",
- "\n",
- "\n",
- "$$ \\tilde{y}^{OLS}=\\boldsymbol{X}\\hat{\\beta}^{OLS}=\\sum_{j=1}^p \\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y}$$ and for Ridge we have \n",
- "\n",
- "$$ \\tilde{y}^{Ridge}=\\boldsymbol{X}\\hat{\\beta}^{Ridge}=\\sum_{j=1}^p \\boldsymbol{u}_j\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{u}_j^T\\boldsymbol{y}$$ . \n",
- "\n",
- "It is indeed the economy-sized SVD, note the summation runs up tp $$p$$ only and not $$n$$. \n",
- "\n",
- "Here we have that $$\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T$$, with $$\\Sigma$$ being an $$ n\\times p$$ matrix and $$\\boldsymbol{V}$$ being a $$ p\\times p$$ matrix. We also have assumed here that $$ n > p$$. \n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "## Ridge and LASSO Regression\n",
- "\n",
- "[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember11.mp4?vrtx=view-as-webpage)\n",
- "\n",
- "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n",
- "our optimization problem is"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "or we can state it as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
- "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "where we have used the definition of a norm-2 vector, that is"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "By minimizing the above equation with respect to the parameters\n",
- "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n",
- "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n",
- "defining a new cost function to be optimized, that is"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
- "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which leads to the Ridge regression minimization problem where we\n",
- "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n",
- "a finite number larger than zero. By defining"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "we have a new optimization equation"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
- "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n",
- "\n",
- "Here we have defined the norm-1 as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Using the matrix-vector expression for Ridge regression,"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "by taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n",
- "a slightly modified matrix inversion problem which for finite values\n",
- "of $\\lambda$ does not suffer from singularity problems. We obtain"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with $t$ a finite positive number. \n",
- "\n",
- "We see that Ridge regression is nothing but the standard\n",
- "OLS with a modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The\n",
- "consequences, in particular for our discussion of the bias-variance tradeoff \n",
- "are rather interesting.\n",
- "\n",
- "Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U} = \\boldsymbol{U}\\boldsymbol{D}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "For Ridge regression this becomes"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$. \n",
- "\n",
- "\n",
- "Since $\\lambda \\geq 0$, it means that compared to OLS, we have"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n",
- "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n",
- "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n",
- "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n",
- "\\sigma_{i+1}$.\n",
- "\n",
- "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom.\n",
- "Actually, calculating the variance of $\\boldsymbol{X}\\boldsymbol{v}_j$ shows that this quantity is equal to $\\sigma_j^2/n$.\n",
- "With a parameter $\\lambda$ we can thus shrink the role of specific parameters. \n",
- "\n",
- "\n",
- "\n",
- "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In this case the standard OLS results in"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "and"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n",
- "the Ridge estimator converges to zero when the hyperparameter goes to\n",
- "infinity.\n",
- "\n",
- "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n",
- "\n",
- "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n",
- "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\n",
- "\n",
- "\n",
- "\n",
- "## A better understanding of regularization\n",
- "\n",
- "The parameter $\\lambda$ that we have introduced in the Ridge (and\n",
- "Lasso as well) regression is often called a regularization parameter\n",
- "or shrinkage parameter. It is common to call it a hyperparameter. What does it mean mathemtically?\n",
- "\n",
- "Here we will first look at how to analyze the difference between the\n",
- "standard OLS equations and the Ridge expressions in terms of a linear\n",
- "algebra analysis using the SVD algorithm. Thereafter, we will link\n",
- "(see the material on the bias-variance tradeoff below) these\n",
- "observation to the statisical analysis of the results. In particular\n",
- "we consider how the variance of the parameters $\\boldsymbol{\\beta}$ is\n",
- "affected by changing the parameter $\\lambda$.\n",
- "\n",
- "\n",
- "We have our design matrix\n",
- " $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. With the SVD we decompose it as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X} = \\boldsymbol{U\\Sigma V^T},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with $\\boldsymbol{U}\\in {\\mathbb{R}}^{n\\times n}$, $\\boldsymbol{\\Sigma}\\in {\\mathbb{R}}^{n\\times p}$\n",
- "and $\\boldsymbol{V}\\in {\\mathbb{R}}^{p\\times p}$.\n",
- "\n",
- "The matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$ are unitary/orthonormal matrices, that is in case the matrices are real we have $\\boldsymbol{U}^T\\boldsymbol{U}=\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ and $\\boldsymbol{V}^T\\boldsymbol{V}=\\boldsymbol{V}\\boldsymbol{V}^T=\\boldsymbol{I}$.\n",
- "\n",
- "\n",
- "\n",
- "## Introducing the Covariance and Correlation functions\n",
- "\n",
- "Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about\n",
- "the definition of the covariance and the correlation function. These are quantities \n",
- "\n",
- "Suppose we have defined two vectors\n",
- "$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
- " \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "where for example"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "With this definition and recalling that the variance is defined as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "we can rewrite the covariance matrix as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
- " \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n",
- " \\end{bmatrix}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The covariance takes values between zero and infinity and may thus\n",
- "lead to problems with loss of numerical precision for particularly\n",
- "large values. It is common to scale the covariance matrix by\n",
- "introducing instead the correlation matrix defined via the so-called\n",
- "correlation function"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]=\\frac{\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}]}{\\sqrt{\\mathrm{var}[\\boldsymbol{x}] \\mathrm{var}[\\boldsymbol{y}]}}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The correlation function is then given by values $\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]\n",
- "\\in [-1,1]$. This avoids eventual problems with too large values. We\n",
- "can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n",
- "and $\\boldsymbol{y}$ as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
- " \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In the above example this is the function we constructed using **pandas**.\n",
- "\n",
- "\n",
- "\n",
- "In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**\n",
- "we defined the design/feature matrix $\\boldsymbol{X}$ as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}=\\begin{bmatrix}\n",
- "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
- "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
- "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
- "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
- "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
- "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ refering to the column numbers and the\n",
- "entries $n$ being the row elements.\n",
- "We can rewrite the design/feature matrix in terms of its column vectors as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with a given vector"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{x}_i^T = \\begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \\dots & \\dots x_{n-1,i}\\end{bmatrix}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "With these definitions, we can now rewrite our $2\\times 2$\n",
- "correaltion/covariance matrix in terms of a moe general design/feature\n",
- "matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$\n",
- "covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i=0,1,\\dots,p-1$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
- "\\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}]\\\\\n",
- "\\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}]\\\\\n",
- "\\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}]\\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\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}]\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "and the correlation matrix"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
- "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}]\\\\\n",
- "\\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}]\\\\\n",
- "\\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}]\\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\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\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The Numpy function **np.cov** calculates the covariance elements using\n",
- "the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n",
- "the exact mean values. The following simple function uses the\n",
- "**np.vstack** function which takes each vector of dimension $1\\times n$\n",
- "and produces a $2\\times n$ matrix $\\boldsymbol{W}$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{W} = \\begin{bmatrix} x_0 & y_0 \\\\\n",
- " x_1 & y_1 \\\\\n",
- " x_2 & y_2\\\\\n",
- " \\dots & \\dots \\\\\n",
- " x_{n-2} & y_{n-2}\\\\\n",
- " x_{n-1} & y_{n-1} & \n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which in turn is converted into into the $2\\times 2$ covariance matrix\n",
- "$\\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate\n",
- "the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n",
- "function **np.mean(x)**. We can also extract the eigenvalues of the\n",
- "covariance matrix through the **np.linalg.eig()** function."
+ "that is the rewriting in terms of the so-called bias, the variance of the model $\\boldsymbol{\\tilde{y}}$ and the variance of $\\boldsymbol{\\epsilon}$."
]
},
{
@@ -1119,27 +900,60 @@
},
"outputs": [],
"source": [
- "# Importing various packages\n",
+ "import matplotlib.pyplot as plt\n",
"import numpy as np\n",
- "n = 100\n",
- "x = np.random.normal(size=n)\n",
- "print(np.mean(x))\n",
- "y = 4+3*x+np.random.normal(size=n)\n",
- "print(np.mean(y))\n",
- "W = np.vstack((x, y))\n",
- "C = np.cov(W)\n",
- "print(C)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The previous example can be converted into the correlation matrix by\n",
- "simply scaling the matrix elements with the variances. We should also\n",
- "subtract the mean values for each column. This leads to the following\n",
- "code which sets up the correlations matrix for the previous example in\n",
- "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)."
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.pipeline import make_pipeline\n",
+ "from sklearn.utils import resample\n",
+ "\n",
+ "np.random.seed(2018)\n",
+ "\n",
+ "n = 500\n",
+ "n_boostraps = 100\n",
+ "degree = 18 # A quite high value, just to show.\n",
+ "noise = 0.1\n",
+ "\n",
+ "# Make data set.\n",
+ "x = np.linspace(-1, 3, n).reshape(-1, 1)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)\n",
+ "\n",
+ "# Hold out some test data that is never used in training.\n",
+ "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
+ "\n",
+ "# Combine x transformation and model into one operation.\n",
+ "# Not neccesary, but convenient.\n",
+ "model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
+ "\n",
+ "# The following (m x n_bootstraps) matrix holds the column vectors y_pred\n",
+ "# for each bootstrap iteration.\n",
+ "y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
+ "for i in range(n_boostraps):\n",
+ " x_, y_ = resample(x_train, y_train)\n",
+ "\n",
+ " # Evaluate the new model on the same test data each time.\n",
+ " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
+ "\n",
+ "# Note: Expectations and variances taken w.r.t. different training\n",
+ "# data sets, hence the axis=1. Subsequent means are taken across the test data\n",
+ "# set in order to obtain a total value, but before this we have error/bias/variance\n",
+ "# calculated per data point in the test set.\n",
+ "# Note 2: The use of keepdims=True is important in the calculation of bias as this \n",
+ "# maintains the column vector form. Dropping this yields very unexpected results.\n",
+ "error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
+ "bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
+ "variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
+ "print('Error:', error)\n",
+ "print('Bias^2:', bias)\n",
+ "print('Var:', variance)\n",
+ "print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))\n",
+ "\n",
+ "plt.plot(x[::5, :], y[::5, :], label='f(x)')\n",
+ "plt.scatter(x_test, y_test, label='Data points')\n",
+ "plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')\n",
+ "plt.legend()\n",
+ "plt.show()"
]
},
{
@@ -1151,41 +965,89 @@
},
"outputs": [],
"source": [
+ "import matplotlib.pyplot as plt\n",
"import numpy as np\n",
- "n = 100\n",
- "# define two vectors \n",
- "x = np.random.random(size=n)\n",
- "y = 4+3*x+np.random.normal(size=n)\n",
- "#scaling the x and y vectors \n",
- "x = x - np.mean(x)\n",
- "y = y - np.mean(y)\n",
- "variance_x = np.sum(x@x)/n\n",
- "variance_y = np.sum(y@y)/n\n",
- "print(variance_x)\n",
- "print(variance_y)\n",
- "cov_xy = np.sum(x@y)/n\n",
- "cov_xx = np.sum(x@x)/n\n",
- "cov_yy = np.sum(y@y)/n\n",
- "C = np.zeros((2,2))\n",
- "C[0,0]= cov_xx/variance_x\n",
- "C[1,1]= cov_yy/variance_y\n",
- "C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n",
- "C[1,0]= C[0,1]\n",
- "print(C)"
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.pipeline import make_pipeline\n",
+ "from sklearn.utils import resample\n",
+ "\n",
+ "np.random.seed(2018)\n",
+ "\n",
+ "n = 40\n",
+ "n_boostraps = 100\n",
+ "maxdegree = 14\n",
+ "\n",
+ "\n",
+ "# Make data set.\n",
+ "x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
+ "error = np.zeros(maxdegree)\n",
+ "bias = np.zeros(maxdegree)\n",
+ "variance = np.zeros(maxdegree)\n",
+ "polydegree = np.zeros(maxdegree)\n",
+ "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
+ "\n",
+ "for degree in range(maxdegree):\n",
+ " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
+ " y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
+ " for i in range(n_boostraps):\n",
+ " x_, y_ = resample(x_train, y_train)\n",
+ " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
+ "\n",
+ " polydegree[degree] = degree\n",
+ " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
+ " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
+ " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
+ " print('Polynomial degree:', degree)\n",
+ " print('Error:', error[degree])\n",
+ " print('Bias^2:', bias[degree])\n",
+ " print('Var:', variance[degree])\n",
+ " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n",
+ "\n",
+ "plt.plot(polydegree, error, label='Error')\n",
+ "plt.plot(polydegree, bias, label='bias')\n",
+ "plt.plot(polydegree, variance, label='Variance')\n",
+ "plt.legend()\n",
+ "plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "We see that the matrix elements along the diagonal are one as they\n",
- "should be and that the matrix is symmetric. Furthermore, diagonalizing\n",
- "this matrix we easily see that it is a positive definite matrix.\n",
- "\n",
- "The above procedure with **numpy** can be made more compact if we use **pandas**.\n",
+ "The bias-variance tradeoff summarizes the fundamental tension in\n",
+ "machine learning, particularly supervised learning, between the\n",
+ "complexity of a model and the amount of training data needed to train\n",
+ "it. Since data is often limited, in practice it is often useful to\n",
+ "use a less-complex model with higher bias, that is a model whose asymptotic\n",
+ "performance is worse than another model because it is easier to\n",
+ "train and less sensitive to sampling noise arising from having a\n",
+ "finite-sized training dataset (smaller variance). \n",
"\n",
"\n",
- "We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code"
+ "\n",
+ "The above equations tell us that in\n",
+ "order to minimize the expected test error, we need to select a\n",
+ "statistical learning method that simultaneously achieves low variance\n",
+ "and low bias. Note that variance is inherently a nonnegative quantity,\n",
+ "and squared bias is also nonnegative. Hence, we see that the expected\n",
+ "test MSE can never lie below $Var(\\epsilon)$, the irreducible error.\n",
+ "\n",
+ "\n",
+ "What do we mean by the variance and bias of a statistical learning\n",
+ "method? The variance refers to the amount by which our model would change if we\n",
+ "estimated it using a different training data set. Since the training\n",
+ "data are used to fit the statistical learning method, different\n",
+ "training data sets will result in a different estimate. But ideally the\n",
+ "estimate for our model should not vary too much between training\n",
+ "sets. However, if a method has high variance then small changes in\n",
+ "the training data can result in large changes in the model. In general, more\n",
+ "flexible statistical methods have higher variance.\n",
+ "\n",
+ "\n",
+ "You may also find this recent [article](https://www.pnas.org/content/116/32/15849) of interest."
]
},
{
@@ -1197,26 +1059,77 @@
},
"outputs": [],
"source": [
+ "\"\"\"\n",
+ "============================\n",
+ "Underfitting vs. Overfitting\n",
+ "============================\n",
+ "\n",
+ "This example demonstrates the problems of underfitting and overfitting and\n",
+ "how we can use linear regression with polynomial features to approximate\n",
+ "nonlinear functions. The plot shows the function that we want to approximate,\n",
+ "which is a part of the cosine function. In addition, the samples from the\n",
+ "real function and the approximations of different models are displayed. The\n",
+ "models have polynomial features of different degrees. We can see that a\n",
+ "linear function (polynomial with degree 1) is not sufficient to fit the\n",
+ "training samples. This is called **underfitting**. A polynomial of degree 4\n",
+ "approximates the true function almost perfectly. However, for higher degrees\n",
+ "the model will **overfit** the training data, i.e. it learns the noise of the\n",
+ "training data.\n",
+ "We evaluate quantitatively **overfitting** / **underfitting** by using\n",
+ "cross-validation. We calculate the mean squared error (MSE) on the validation\n",
+ "set, the higher, the less likely the model generalizes correctly from the\n",
+ "training data.\n",
+ "\"\"\"\n",
+ "\n",
+ "print(__doc__)\n",
+ "\n",
"import numpy as np\n",
- "import pandas as pd\n",
- "n = 10\n",
- "x = np.random.normal(size=n)\n",
- "x = x - np.mean(x)\n",
- "y = 4+3*x+np.random.normal(size=n)\n",
- "y = y - np.mean(y)\n",
- "X = (np.vstack((x, y))).T\n",
- "print(X)\n",
- "Xpd = pd.DataFrame(X)\n",
- "print(Xpd)\n",
- "correlation_matrix = Xpd.corr()\n",
- "print(correlation_matrix)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We expand this model to the Franke function discussed above."
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.pipeline import Pipeline\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "from sklearn.linear_model import LinearRegression\n",
+ "from sklearn.model_selection import cross_val_score\n",
+ "\n",
+ "\n",
+ "def true_fun(X):\n",
+ " return np.cos(1.5 * np.pi * X)\n",
+ "\n",
+ "np.random.seed(0)\n",
+ "\n",
+ "n_samples = 30\n",
+ "degrees = [1, 4, 15]\n",
+ "\n",
+ "X = np.sort(np.random.rand(n_samples))\n",
+ "y = true_fun(X) + np.random.randn(n_samples) * 0.1\n",
+ "\n",
+ "plt.figure(figsize=(14, 5))\n",
+ "for i in range(len(degrees)):\n",
+ " ax = plt.subplot(1, len(degrees), i + 1)\n",
+ " plt.setp(ax, xticks=(), yticks=())\n",
+ "\n",
+ " polynomial_features = PolynomialFeatures(degree=degrees[i],\n",
+ " include_bias=False)\n",
+ " linear_regression = LinearRegression()\n",
+ " pipeline = Pipeline([(\"polynomial_features\", polynomial_features),\n",
+ " (\"linear_regression\", linear_regression)])\n",
+ " pipeline.fit(X[:, np.newaxis], y)\n",
+ "\n",
+ " # Evaluate the models using crossvalidation\n",
+ " scores = cross_val_score(pipeline, X[:, np.newaxis], y,\n",
+ " scoring=\"neg_mean_squared_error\", cv=10)\n",
+ "\n",
+ " X_test = np.linspace(0, 1, 100)\n",
+ " plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label=\"Model\")\n",
+ " plt.plot(X_test, true_fun(X_test), label=\"True function\")\n",
+ " plt.scatter(X, y, edgecolor='b', s=20, label=\"Samples\")\n",
+ " plt.xlabel(\"x\")\n",
+ " plt.ylabel(\"y\")\n",
+ " plt.xlim((0, 1))\n",
+ " plt.ylim((-2, 2))\n",
+ " plt.legend(loc=\"best\")\n",
+ " plt.title(\"Degree {}\\nMSE = {:.2e}(+/- {:.2e})\".format(\n",
+ " degrees[i], -scores.mean(), scores.std()))\n",
+ "plt.show()"
]
},
{
@@ -1229,146 +1142,207 @@
"outputs": [],
"source": [
"# Common imports\n",
+ "import os\n",
"import numpy as np\n",
"import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.utils import resample\n",
+ "from sklearn.metrics import mean_squared_error\n",
+ "# Where to save the figures and data files\n",
+ "PROJECT_ROOT_DIR = \"Results\"\n",
+ "FIGURE_ID = \"Results/FigureFiles\"\n",
+ "DATA_ID = \"DataFiles/\"\n",
"\n",
+ "if not os.path.exists(PROJECT_ROOT_DIR):\n",
+ " os.mkdir(PROJECT_ROOT_DIR)\n",
"\n",
- "def FrankeFunction(x,y):\n",
- "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
- "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
- "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
- "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
- "\treturn term1 + term2 + term3 + term4\n",
+ "if not os.path.exists(FIGURE_ID):\n",
+ " os.makedirs(FIGURE_ID)\n",
"\n",
+ "if not os.path.exists(DATA_ID):\n",
+ " os.makedirs(DATA_ID)\n",
"\n",
- "def create_X(x, y, n ):\n",
- "\tif len(x.shape) > 1:\n",
- "\t\tx = np.ravel(x)\n",
- "\t\ty = np.ravel(y)\n",
+ "def image_path(fig_id):\n",
+ " return os.path.join(FIGURE_ID, fig_id)\n",
"\n",
- "\tN = len(x)\n",
- "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n",
- "\tX = np.ones((N,l))\n",
+ "def data_path(dat_id):\n",
+ " return os.path.join(DATA_ID, dat_id)\n",
"\n",
- "\tfor i in range(1,n+1):\n",
- "\t\tq = int((i)*(i+1)/2)\n",
- "\t\tfor k in range(i+1):\n",
- "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n",
+ "def save_fig(fig_id):\n",
+ " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
"\n",
- "\treturn X\n",
+ "infile = open(data_path(\"EoS.csv\"),'r')\n",
"\n",
+ "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
+ "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
+ "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
+ "EoS = EoS.dropna()\n",
+ "Energies = EoS['Energy']\n",
+ "Density = EoS['Density']\n",
+ "# The design matrix now as function of various polytrops\n",
"\n",
- "# Making meshgrid of datapoints and compute Franke's function\n",
- "n = 4\n",
- "N = 100\n",
- "x = np.sort(np.random.uniform(0, 1, N))\n",
- "y = np.sort(np.random.uniform(0, 1, N))\n",
- "z = FrankeFunction(x, y)\n",
- "X = create_X(x, y, n=n) \n",
+ "Maxpolydegree = 30\n",
+ "X = np.zeros((len(Density),Maxpolydegree))\n",
+ "X[:,0] = 1.0\n",
+ "testerror = np.zeros(Maxpolydegree)\n",
+ "trainingerror = np.zeros(Maxpolydegree)\n",
+ "polynomial = np.zeros(Maxpolydegree)\n",
"\n",
- "Xpd = pd.DataFrame(X)\n",
- "# subtract the mean values and set up the covariance matrix\n",
- "Xpd = Xpd - Xpd.mean()\n",
- "covariance_matrix = Xpd.cov()\n",
- "print(covariance_matrix)"
+ "trials = 100\n",
+ "for polydegree in range(1, Maxpolydegree):\n",
+ " polynomial[polydegree] = polydegree\n",
+ " for degree in range(polydegree):\n",
+ " X[:,degree] = Density**(degree/3.0)\n",
+ "\n",
+ "# loop over trials in order to estimate the expectation value of the MSE\n",
+ " testerror[polydegree] = 0.0\n",
+ " trainingerror[polydegree] = 0.0\n",
+ " for samples in range(trials):\n",
+ " x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n",
+ " model = LinearRegression(fit_intercept=True).fit(x_train, y_train)\n",
+ " ypred = model.predict(x_train)\n",
+ " ytilde = model.predict(x_test)\n",
+ " testerror[polydegree] += mean_squared_error(y_test, ytilde)\n",
+ " trainingerror[polydegree] += mean_squared_error(y_train, ypred) \n",
+ "\n",
+ " testerror[polydegree] /= trials\n",
+ " trainingerror[polydegree] /= trials\n",
+ " print(\"Degree of polynomial: %3d\"% polynomial[polydegree])\n",
+ " print(\"Mean squared error on training data: %.8f\" % trainingerror[polydegree])\n",
+ " print(\"Mean squared error on test data: %.8f\" % testerror[polydegree])\n",
+ "\n",
+ "plt.plot(polynomial, np.log10(trainingerror), label='Training Error')\n",
+ "plt.plot(polynomial, np.log10(testerror), label='Test Error')\n",
+ "plt.xlabel('Polynomial degree')\n",
+ "plt.ylabel('log10[MSE]')\n",
+ "plt.legend()\n",
+ "plt.show()"
]
},
{
- "cell_type": "markdown",
- "metadata": {},
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
"source": [
- "We note here that the covariance is zero for the first rows and\n",
- "columns since all matrix elements in the design matrix were set to one\n",
- "(we are fitting the function in terms of a polynomial of degree $n$).\n",
- "\n",
- "This means that the variance for these elements will be zero and will\n",
- "cause problems when we set up the correlation matrix. We can simply\n",
- "drop these elements and construct a correlation\n",
- "matrix without these elements. \n",
+ "# Common imports\n",
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.metrics import mean_squared_error\n",
+ "from sklearn.model_selection import KFold\n",
+ "from sklearn.model_selection import cross_val_score\n",
"\n",
"\n",
+ "# Where to save the figures and data files\n",
+ "PROJECT_ROOT_DIR = \"Results\"\n",
+ "FIGURE_ID = \"Results/FigureFiles\"\n",
+ "DATA_ID = \"DataFiles/\"\n",
"\n",
+ "if not os.path.exists(PROJECT_ROOT_DIR):\n",
+ " os.mkdir(PROJECT_ROOT_DIR)\n",
"\n",
- "We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\\boldsymbol{X}$ as"
+ "if not os.path.exists(FIGURE_ID):\n",
+ " os.makedirs(FIGURE_ID)\n",
+ "\n",
+ "if not os.path.exists(DATA_ID):\n",
+ " os.makedirs(DATA_ID)\n",
+ "\n",
+ "def image_path(fig_id):\n",
+ " return os.path.join(FIGURE_ID, fig_id)\n",
+ "\n",
+ "def data_path(dat_id):\n",
+ " return os.path.join(DATA_ID, dat_id)\n",
+ "\n",
+ "def save_fig(fig_id):\n",
+ " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
+ "\n",
+ "infile = open(data_path(\"EoS.csv\"),'r')\n",
+ "\n",
+ "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
+ "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
+ "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
+ "EoS = EoS.dropna()\n",
+ "Energies = EoS['Energy']\n",
+ "Density = EoS['Density']\n",
+ "# The design matrix now as function of various polytrops\n",
+ "\n",
+ "Maxpolydegree = 30\n",
+ "X = np.zeros((len(Density),Maxpolydegree))\n",
+ "X[:,0] = 1.0\n",
+ "estimated_mse_sklearn = np.zeros(Maxpolydegree)\n",
+ "polynomial = np.zeros(Maxpolydegree)\n",
+ "k =5\n",
+ "kfold = KFold(n_splits = k)\n",
+ "\n",
+ "for polydegree in range(1, Maxpolydegree):\n",
+ " polynomial[polydegree] = polydegree\n",
+ " for degree in range(polydegree):\n",
+ " X[:,degree] = Density**(degree/3.0)\n",
+ " OLS = LinearRegression()\n",
+ "# loop over trials in order to estimate the expectation value of the MSE\n",
+ " estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)\n",
+ "#[:, np.newaxis]\n",
+ " estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)\n",
+ "\n",
+ "plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')\n",
+ "plt.xlabel('Polynomial degree')\n",
+ "plt.ylabel('log10[MSE]')\n",
+ "plt.legend()\n",
+ "plt.show()"
]
},
{
- "cell_type": "markdown",
- "metadata": {},
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
"source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}=\\begin{bmatrix}\n",
- "x_{00} & x_{01}\\\\\n",
- "x_{10} & x_{11}\\\\\n",
- "\\end{bmatrix}=\\begin{bmatrix}\n",
- "\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n",
- "\\end{bmatrix}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "If we then compute the expectation value"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}=\\begin{bmatrix}\n",
- "x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\\\\n",
- "x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which is just"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\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] \\\\\n",
- " \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "where we wrote $$\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]$$ to indicate that this the covariance of the vectors $\\boldsymbol{x}$ of the design/feature matrix $\\boldsymbol{X}$.\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import KFold\n",
+ "from sklearn.linear_model import Ridge\n",
+ "from sklearn.model_selection import cross_val_score\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
"\n",
- "It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$.\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "np.random.seed(3155)\n",
+ "# Generate the data.\n",
+ "n = 100\n",
+ "x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
+ "# Decide degree on polynomial to fit\n",
+ "poly = PolynomialFeatures(degree = 10)\n",
"\n",
- "\n",
- "## Linking with SVD"
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 500\n",
+ "lambdas = np.logspace(-3, 5, nlambdas)\n",
+ "# Initialize a KFold instance\n",
+ "k = 5\n",
+ "kfold = KFold(n_splits = k)\n",
+ "estimated_mse_sklearn = np.zeros(nlambdas)\n",
+ "i = 0\n",
+ "for lmb in lambdas:\n",
+ " ridge = Ridge(alpha = lmb)\n",
+ " estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)\n",
+ " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n",
+ " i += 1\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
]
}
],
diff --git a/doc/LectureNotes/_build/html/chapter2.html b/doc/LectureNotes/_build/html/chapter2.html
index 21ac40195..258b482f4 100644
--- a/doc/LectureNotes/_build/html/chapter2.html
+++ b/doc/LectureNotes/_build/html/chapter2.html
@@ -5,7 +5,7 @@
- 4. Resampling Methods — Applied Data Analysis and Machine Learning
+ 4. Ridge and Lasso Regression — Applied Data Analysis and Machine Learning
@@ -54,7 +54,7 @@
-
+
@@ -144,12 +144,12 @@
- 4. Resampling Methods
+ 4. Ridge and Lasso Regression
- 5. Ridge and Lasso Regression
+ 5. Resampling Methods
@@ -285,35 +285,73 @@
@@ -327,60 +365,1694 @@
-
-
4. Resampling Methods
-
-
4.1. Introduction
-
Resampling methods are an indispensable tool in modern
-statistics. They involve repeatedly drawing samples from a training
-set and refitting a model of interest on each sample in order to
-obtain additional information about the fitted model. For example, in
-order to estimate the variability of a linear regression fit, we can
-repeatedly draw different samples from the training data, fit a linear
-regression to each new sample, and then examine the extent to which
-the resulting fits differ. Such an approach may allow us to obtain
-information that would not be available from fitting the model only
-once using the original training sample.
-
Two resampling methods are often used in Machine Learning analyses,
-
-The bootstrap method
-and Cross-Validation
-
-
In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular
-cross-validation and the bootstrap method.
-
Resampling approaches can be computationally expensive, because they
-involve fitting the same statistical method multiple times using
-different subsets of the training data. However, due to recent
-advances in computing power, the computational requirements of
-resampling methods generally are not prohibitive. In this chapter, we
-discuss two of the most commonly used resampling methods,
-cross-validation and the bootstrap. Both methods are important tools
-in the practical application of many statistical learning
-procedures. For example, cross-validation can be used to estimate the
-test error associated with a given statistical learning method in
-order to evaluate its performance, or to select the appropriate level
-of flexibility. The process of evaluating a model’s performance is
-known as model assessment, whereas the process of selecting the proper
-level of flexibility for a model is known as model selection. The
-bootstrap is widely used.
-
-Our simulations can be treated as computer experiments . This is particularly the case for Monte Carlo methods
-The results can be analysed with the same statistical tools as we would use analysing experimental data.
-As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
-
+
+
4. Ridge and Lasso Regression
+
+
4.1. Mathematical Interpretation of Ordinary Least Squares
+
What is presented here is a mathematical analysis of various regression algorithms (ordinary least squares, Ridge and Lasso Regression). The analysis is based on an important algorithm in linear algebra, the so-called Singular Value Decomposition (SVD).
+
We have shown that in ordinary least squares the optimal parameters \(\beta\) are given by
+
+\[
+\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.
+
This means that our best model is defined as
+
+\[
+\tilde{\boldsymbol{y}}=\boldsymbol{X}\hat{\boldsymbol{\beta}} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
+\]
+
We now define a matrix
+
+\[
+\boldsymbol{A}=\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T.
+\]
+
We can rewrite
+
+\[
+\tilde{\boldsymbol{y}}=\boldsymbol{X}\hat{\boldsymbol{\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.
+
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}\) .
+
If the matrix \(\boldsymbol{X}\) is an orthogonal (or unitary in case of complex values) matrix, we have
+
+\[
+\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{X}\boldsymbol{X}^T = \boldsymbol{I}.
+\]
+
In this case the matrix \(\boldsymbol{A}\) becomes
+
+\[
+\boldsymbol{A}=\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T)=\boldsymbol{I},
+\]
+
and we have the obvious case
+
+\[
+\boldsymbol{\epsilon}=\boldsymbol{y}-\tilde{\boldsymbol{y}}=0.
+\]
+
This serves also as a useful test of our codes.
-
-
4.2. Reminder on Statistics
-
-As in other experiments, many numerical experiments have two classes of errors:
-
-Statistical errors
-Systematical errors
-
-
-Statistical errors can be estimated using standard tools from statistics
-Systematical errors are method specific and must be treated differently from case to case.
-
+
+
4.2. The singular value decomposition
+
The examples we have looked at so far are cases where we normally can
+invert the matrix \(\boldsymbol{X}^T\boldsymbol{X}\) . Using a polynomial expansion where we fit of various functions leads to
+row vectors of the design matrix which are essentially orthogonal due
+to the polynomial character of our model. Obtaining the inverse of the
+design matrix is then often done via a so-called LU, QR or Cholesky
+decomposition.
+
As we will also see in the first project,
+this may
+however not the be case in general and a standard matrix inversion
+algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.
+
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.
+
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{split}
+\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*}
+\end{split}\]
+
The columns of \(\boldsymbol{X}\) are linearly dependent. We see this easily since the
+the first column is the row-wise sum of the other two columns. The rank (more correct,
+the column rank) of a matrix is the dimension of the space spanned by the
+column vectors. Hence, the rank of \(\mathbf{X}\) is equal to the number
+of linearly independent columns. In this particular case the matrix has rank 2.
+
Super-collinearity of an \((n \times p)\) -dimensional design matrix \(\mathbf{X}\) implies
+that the inverse of the matrix \(\boldsymbol{X}^T\boldsymbol{X}\) (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this
+
+\[\begin{split}
+\begin{align*}
+\boldsymbol{X} & = \left[
+\begin{array}{rr}
+1 & -1
+\\
+1 & -1
+\end{array} \right].
+\end{align*}
+\end{split}\]
+
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.
+
If our design matrix \(\boldsymbol{X}\) which enters the linear regression problem
+
+
+
+\[
+\begin{equation}
+\boldsymbol{\beta} = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y},
+\label{_auto1} \tag{1}
+\end{equation}
+\]
+
has linearly dependent column vectors, we will not be able to compute the inverse
+of \(\boldsymbol{X}^T\boldsymbol{X}\) and we cannot find the parameters (estimators) \(\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.
+
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.
+
+
+
4.3. Basic math of the SVD
+
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
+
+\[
+(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n),
+\]
+
and the eigenvalues are given by the diagonal matrix
+
+\[
+\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n).
+\]
+
The matrix \(\boldsymbol{X}\) can be written in terms of an orthogonal/unitary transformation \(\boldsymbol{U}\)
+
+\[
+\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,
+\]
+
with \(\boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I}\) or \(\boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I}\) .
+
Not all square matrices are diagonalizable. A matrix like the one discussed above
+
+\[\begin{split}
+\boldsymbol{X} = \begin{bmatrix}
+1& -1 \\
+1& -1\\
+\end{bmatrix}
+\end{split}\]
+
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.
+
However, and this is the strength of the SVD algorithm, any general
+matrix \(\boldsymbol{X}\) can be decomposed in terms of a diagonal matrix and
+two orthogonal/unitary matrices. The Singular Value Decompostion
+(SVD) theorem
+states that a general \(m\times n\) matrix \(\boldsymbol{X}\) can be written in
+terms of a diagonal matrix \(\boldsymbol{\Sigma}\) of dimensionality \(m\times n\)
+and two orthognal matrices \(\boldsymbol{U}\) and \(\boldsymbol{V}\) , where the first has
+dimensionality \(m \times m\) and the last dimensionality \(n\times n\) .
+We have then
+
+\[
+\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T
+\]
+
As an example, the above defective matrix can be decomposed as
+
+\[\begin{split}
+\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,
+\end{split}\]
+
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.
+
If we assume that \(n > p\) , then our matrix \(\boldsymbol{U}\) has dimension \(n
+\times n\) . The last \(n-p\) columns of \(\boldsymbol{U}\) become however
+irrelevant in our calculations since they are multiplied with the
+zeros in \(\boldsymbol{\Sigma}\) .
+
The economy-size decomposition removes extra rows or columns of zeros
+from the diagonal matrix of singular values, \(\boldsymbol{\Sigma}\) , along with the columns
+in either \(\boldsymbol{U}\) or \(\boldsymbol{V}\) that multiply those zeros in the expression.
+Removing these zeros and columns can improve execution time
+and reduce storage requirements without compromising the accuracy of
+the decomposition.
+
If \(n > p\) , we keep only the first \(p\) columns of \(\boldsymbol{U}\) and \(\boldsymbol{\Sigma}\) has dimension \(p\times p\) .
+If \(p > n\) , then only the first \(n\) columns of \(\boldsymbol{V}\) are computed and \(\boldsymbol{\Sigma}\) has dimension \(n\times n\) .
+The \(n=p\) case is obvious, we retain the full SVD.
+In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.
+
+
+
4.4. Codes for the SVD
+
+
+
+
[[ 1. -1.]
+ [ 1. -1.]]
+test U
+[[0. 0.]
+ [0. 0.]]
+test VT
+[[0. 0.]
+ [0. 0.]]
+[[-0.70710678 -0.70710678]
+ [-0.70710678 0.70710678]]
+[2. 0.]
+[[-0.70710678 0.70710678]
+ [ 0.70710678 0.70710678]]
+[[-3.33066907e-16 4.44089210e-16]
+ [ 0.00000000e+00 2.22044605e-16]]
+
+
+
+
+
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.
+
The \(U\) , \(S\) , and \(V\) matrices returned from the svd() function
+cannot be multiplied directly.
+
As you can see from the code, the \(S\) vector must be converted into a
+diagonal matrix. This may cause a problem as the size of the matrices
+do not fit the rules of matrix multiplication, where the number of
+columns in a matrix must match the number of rows in the subsequent
+matrix.
+
If you wish to include the zero singular values, you will need to
+resize the matrices and set up a diagonal matrix as done in the above
+example
+
+
+
4.5. Mathematics of the SVD and implications
+
Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies.
+
Our starting point is our design matrix \(\boldsymbol{X}\) of dimension \(n\times p\)
+
+\[\begin{split}
+\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}.
+\end{split}\]
+
We can SVD decompose our matrix as
+
+\[
+\boldsymbol{X}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,
+\]
+
where \(\boldsymbol{U}\) is an orthogonal matrix of dimension \(n\times n\) , meaning that \(\boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{U}^T\boldsymbol{U}=\boldsymbol{I}_n\) . Here \(\boldsymbol{I}_n\) is the unit matrix of dimension \(n \times n\) .
+
Similarly, \(\boldsymbol{V}\) is an orthogonal matrix of dimension \(p\times p\) , meaning that \(\boldsymbol{V}\boldsymbol{V}^T=\boldsymbol{V}^T\boldsymbol{V}=\boldsymbol{I}_p\) . Here \(\boldsymbol{I}_n\) is the unit matrix of dimension \(p \times p\) .
+
Finally \(\boldsymbol{\Sigma}\) contains the singular values \(\sigma_i\) . This matrix has dimension \(n\times p\) and the singular values \(\sigma_i\) are all positive. The non-zero values are ordered in descending order, that is
+
+\[
+\sigma_0 > \sigma_1 > \sigma_2 > \dots > \sigma_{p-1} > 0.
+\]
+
All values beyond \(p-1\) are all zero.
+
As an example, consider the following \(3\times 2\) example for the matrix \(\boldsymbol{\Sigma}\)
+
+\[\begin{split}
+\boldsymbol{\Sigma}=
+\begin{bmatrix}
+2& 0 \\
+0 & 1 \\
+0 & 0 \\
+\end{bmatrix}
+\end{split}\]
+
The singular values are \(\sigma_0=2\) and \(\sigma_1=1\) . It is common to rewrite the matrix \(\boldsymbol{\Sigma}\) as
+
+\[\begin{split}
+\boldsymbol{\Sigma}=
+\begin{bmatrix}
+\boldsymbol{\tilde{\Sigma}}\\
+\boldsymbol{0}\\
+\end{bmatrix},
+\end{split}\]
+
where
+
+\[\begin{split}
+\boldsymbol{\tilde{\Sigma}}=
+\begin{bmatrix}
+2& 0 \\
+0 & 1 \\
+\end{bmatrix},
+\end{split}\]
+
contains only the singular values. Note also (and we will use this below) that
+
+\[\begin{split}
+\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}=
+\begin{bmatrix}
+4& 0 \\
+0 & 1 \\
+\end{bmatrix},
+\end{split}\]
+
which is a \(2\times 2 \) matrix while
+
+\[\begin{split}
+\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T=
+\begin{bmatrix}
+4& 0 & 0\\
+0 & 1 & 0\\
+0 & 0 & 0\\
+\end{bmatrix},
+\end{split}\]
+
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.
+
The matrix that may cause problems for us is \(\boldsymbol{X}^T\boldsymbol{X}\) . Using the SVD we can rewrite this matrix as
+
+\[
+\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,
+\]
+
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\) .
+
This means, using the orthogonality of \(\boldsymbol{V}\) , that we get
+
+\[
+\boldsymbol{X}^T\boldsymbol{X}=\tilde{\boldsymbol{\Sigma}}^2.
+\]
+
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\tilde{\boldsymbol{\Sigma}}^{-2}\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{y},
+\]
+
which gives us, using the orthogonality of the matrices \(\boldsymbol{U}\) and \(\boldsymbol{V}\) ,
+
+\[
+\tilde{y}_{\mathrm{OLS}}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_i\boldsymbol{u}^T_j\boldsymbol{y},
+\]
+
Note here that when we perform the multiplication of the various matrices, the orthogonal vectors of the matrix \(\boldsymbol{U}\)
+
+\[
+\boldsymbol{U}=[\boldsymbol{u}_0,\boldsymbol{u}_1,\dots,\boldsymbol{u}_{n-1}],
+\]
+
that belong to \(i>p-1\) , result in only zeros when we perform the multiplications. This means that the sum above has non-zero elements only up to \(i=p-1\) . This corresponds also to the number of singular values (these are all non-zero).
+
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}\) .
+
+
+
4.6. Further properties (important for our analyses later)
+
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).
+
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.
+
+
+
4.7. Meet the Covariance Matrix
+
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
+
+\[
+\frac{\partial^2 C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}^T\partial \boldsymbol{\beta}} =\frac{2}{n}\boldsymbol{X}^T\boldsymbol{X}.
+\]
+
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.
+
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.
+
Suppose we have defined two vectors
+\(\hat{x}\) and \(\hat{y}\) with \(n\) elements each. The covariance matrix \(\boldsymbol{C}\) is defined as
+
+\[\begin{split}
+\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},
+\end{split}\]
+
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
+
+\[\begin{split}
+\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}.
+\end{split}\]
+
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 calculate the covariance, this
+quantity will be computed with a factor \(1/(n-1)\) .
+
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
+
+\[
+\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
+
+\[\begin{split}
+\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\
+ \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\
+ \end{bmatrix},
+\end{split}\]
+
In the above example this is the function we constructed using pandas .
+
In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression
+we defined the design/feature matrix \(\boldsymbol{X}\) as
+
+\[\begin{split}
+\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},
+\end{split}\]
+
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},
+\]
+
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\)
+
+\[\begin{split}
+\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},
+\end{split}\]
+
and the correlation matrix
+
+\[\begin{split}
+\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},
+\end{split}\]
+
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
+
+\[\begin{split}
+\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},
+\end{split}\]
+
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.
+
+
+
+
-0.01210814993019007
+3.8867467323038865
+[[0.91417278 2.88046462]
+ [2.88046462 9.9860803 ]]
+
+
+
+
+
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).
+
+
+
+
0.07423848370736122
+1.725394195434945
+[[1. 0.71606852]
+ [0.71606852 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.
+
The above procedure with numpy can be made more compact if we use pandas .
+
We whow here how we can set up the correlation matrix using pandas , as done in this simple code
+
+
+
+
[[ 0.52687171 0.97622676]
+ [-2.35038714 -6.09976319]
+ [-0.55707065 -1.51576807]
+ [-0.98314755 -2.54096582]
+ [-0.46556436 -0.43549028]
+ [ 3.28310983 9.01503674]
+ [ 0.76388013 2.67714918]
+ [-0.49722108 -2.64669382]
+ [ 1.20184113 3.80026635]
+ [-0.92231203 -3.22999784]]
+ 0 1
+0 0.526872 0.976227
+1 -2.350387 -6.099763
+2 -0.557071 -1.515768
+3 -0.983148 -2.540966
+4 -0.465564 -0.435490
+5 3.283110 9.015037
+6 0.763880 2.677149
+7 -0.497221 -2.646694
+8 1.201841 3.800266
+9 -0.922312 -3.229998
+ 0 1
+0 1.000000 0.988663
+1 0.988663 1.000000
+
+
+
+
+
+
We expand this model to the Franke function discussed earlier.
+
+
+
+
0 1 2 3 4 5 6 7 \
+0 0.0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
+1 0.0 0.075212 0.075261 0.077160 0.075772 0.074134 0.069902 0.068276
+2 0.0 0.075261 0.077533 0.076062 0.075562 0.074848 0.067985 0.066788
+3 0.0 0.077160 0.076062 0.084092 0.081886 0.079365 0.078927 0.076730
+4 0.0 0.075772 0.075562 0.081886 0.080115 0.078049 0.076398 0.074453
+5 0.0 0.074134 0.074848 0.079365 0.078049 0.076469 0.073567 0.071887
+6 0.0 0.069902 0.067985 0.078927 0.076398 0.073567 0.075821 0.073483
+7 0.0 0.068276 0.066788 0.076730 0.074453 0.071887 0.073483 0.071313
+8 0.0 0.066629 0.065591 0.074488 0.072471 0.070182 0.071096 0.069098
+9 0.0 0.064964 0.064410 0.072198 0.070456 0.068460 0.068654 0.066835
+10 0.0 0.061842 0.059571 0.071481 0.068920 0.066092 0.069814 0.067531
+11 0.0 0.060308 0.058282 0.069516 0.067123 0.064472 0.067777 0.065618
+12 0.0 0.058805 0.057035 0.067577 0.065355 0.062885 0.065762 0.063727
+13 0.0 0.057332 0.055831 0.065660 0.063615 0.061330 0.063763 0.061855
+14 0.0 0.055887 0.054674 0.063759 0.061896 0.059806 0.061774 0.059994
+
+ 8 9 10 11 12 13 14
+0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
+1 0.066629 0.064964 0.061842 0.060308 0.058805 0.057332 0.055887
+2 0.065591 0.064410 0.059571 0.058282 0.057035 0.055831 0.054674
+3 0.074488 0.072198 0.071481 0.069516 0.067577 0.065660 0.063759
+4 0.072471 0.070456 0.068920 0.067123 0.065355 0.063615 0.061896
+5 0.070182 0.068460 0.066092 0.064472 0.062885 0.061330 0.059806
+6 0.071096 0.068654 0.069814 0.067777 0.065762 0.063763 0.061774
+7 0.069098 0.066835 0.067531 0.065618 0.063727 0.061855 0.059994
+8 0.067061 0.064982 0.065202 0.063415 0.061652 0.059908 0.058178
+9 0.064982 0.063097 0.062822 0.061164 0.059531 0.057919 0.056326
+10 0.065202 0.062822 0.065086 0.063122 0.061176 0.059245 0.057320
+11 0.063415 0.061164 0.063122 0.061255 0.059406 0.057571 0.055744
+12 0.061652 0.059531 0.061176 0.059406 0.057654 0.055916 0.054187
+13 0.059908 0.057919 0.059245 0.057571 0.055916 0.054276 0.052645
+14 0.058178 0.056326 0.057320 0.055744 0.054187 0.052645 0.051115
+
+
+
+
+
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.
+
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}].
+\]
+
To see this let us simply look at a design matrix \(\boldsymbol{X}\in {\mathbb{R}}^{2\times 2}\)
+
+\[\begin{split}
+\boldsymbol{X}=\begin{bmatrix}
+x_{00} & x_{01}\\
+x_{10} & x_{11}\\
+\end{bmatrix}=\begin{bmatrix}
+\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\
+\end{bmatrix}.
+\end{split}\]
+
If we then compute the expectation value (note the \(1/n\) factor instead of \(1/(n-1)\) )
+
+\[\begin{split}
+\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},
+\end{split}\]
+
which is just
+
+\[\begin{split}
+\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},
+\end{split}\]
+
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}\) .
+
+
+
4.8. Linking with the SVD
+
We saw earlier that
+
+\[
+\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T.
+\]
+
Since the matrices here have dimension \(p\times p\) , with \(p\) corresponding to the singular values, we defined earlier the matrix
+
+\[\begin{split}
+\boldsymbol{\Sigma}^T\boldsymbol{\Sigma} = \begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \\ \boldsymbol{0}\\ \end{bmatrix},
+\end{split}\]
+
where the tilde-matrix \(\tilde{\boldsymbol{\Sigma}}\) is a matrix of dimension \(p\times p\) containing only the singular values \(\sigma_i\) , that is
+
+\[\begin{split}
+\tilde{\boldsymbol{\Sigma}}=\begin{bmatrix} \sigma_0 & 0 & 0 & \dots & 0 & 0 \\
+ 0 & \sigma_1 & 0 & \dots & 0 & 0 \\
+ 0 & 0 & \sigma_2 & \dots & 0 & 0 \\
+ 0 & 0 & 0 & \dots & \sigma_{p-2} & 0 \\
+ 0 & 0 & 0 & \dots & 0 & \sigma_{p-1} \\
+\end{bmatrix},
+\end{split}\]
+
meaning we can write
+
+\[
+\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2\boldsymbol{V}^T.
+\]
+
Multiplying from the right with \(\boldsymbol{V}\) (using the orthogonality of \(\boldsymbol{V}\) ) we get
+
+\[
+\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{V}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2.
+\]
+
This means the vectors \(\boldsymbol{v}_i\) of the orthogonal matrix \(\boldsymbol{V}\)
+are the eigenvectors of the matrix \(\boldsymbol{X}^T\boldsymbol{X}\) with eigenvalues
+given by the singular values squared, that is
+
+\[
+\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{v}_i=\boldsymbol{v}_i\sigma_i^2.
+\]
+
In other words, each non-zero singular value of \(\boldsymbol{X}\) is a positive
+square root of an eigenvalue of \(\boldsymbol{X}^T\boldsymbol{X}\) . It means also that
+the columns of \(\boldsymbol{V}\) are the eigenvectors of
+\(\boldsymbol{X}^T\boldsymbol{X}\) . Since we have ordered the singular values of
+\(\boldsymbol{X}\) in a descending order, it means that the column vectors
+\(\boldsymbol{v}_i\) are hierarchically ordered by how much correlation they
+encode from the columns of \(\boldsymbol{X}\) .
+
Note that these are also the eigenvectors and eigenvalues of the
+Hessian matrix.
+
If we now recall the definition of the covariance matrix (not using
+Bessel’s correction) we have
+
+\[
+\boldsymbol{C}[\boldsymbol{X}]=\frac{1}{n}\boldsymbol{X}^T\boldsymbol{X},
+\]
+
meaning that every squared non-singular value of \(\boldsymbol{X}\) divided by \(n\) (
+the number of samples) are the eigenvalues of the covariance
+matrix. Every singular value of \(\boldsymbol{X}\) is thus a positive square
+root of an eigenvalue of \(\boldsymbol{X}^T\boldsymbol{X}\) . If the matrix \(\boldsymbol{X}\) is
+self-adjoint, the singular values of \(\boldsymbol{X}\) are equal to the
+absolute value of the eigenvalues of \(\boldsymbol{X}\) .
+
For \(\boldsymbol{X}\boldsymbol{X}^T\) we found
+
+\[
+\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T=\boldsymbol{U}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{U}^T.
+\]
+
Since the matrices here have dimension \(n\times n\) , we have
+
+\[\begin{split}
+\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T = \begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \\ \boldsymbol{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \boldsymbol{0}\\ \end{bmatrix}=\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix},
+\end{split}\]
+
leading to
+
+\[\begin{split}
+\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{U}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}\boldsymbol{U}^T.
+\end{split}\]
+
Multiplying with \(\boldsymbol{U}\) from the right gives us the eigenvalue problem
+
+\[\begin{split}
+(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U}=\boldsymbol{U}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}.
+\end{split}\]
+
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}\) .
+
+
+
4.9. Ridge and LASSO Regression
+
Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is
+our optimization problem is
+
+\[
+{\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}.
+\]
+
or we can state it as
+
+\[
+{\displaystyle \min_{\boldsymbol{\beta}\in
+{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2,
+\]
+
where we have used the definition of a norm-2 vector, that is
+
+\[
+\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.
+\]
+
By minimizing the above equation with respect to the parameters
+\(\boldsymbol{\beta}\) we could then obtain an analytical expression for the
+parameters \(\boldsymbol{\beta}\) . We can add a regularization parameter \(\lambda\) by
+defining a new cost function to be optimized, that is
+
+\[
+{\displaystyle \min_{\boldsymbol{\beta}\in
+{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2
+\]
+
which leads to the Ridge regression minimization problem where we
+require that \(\vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t\) , where \(t\) is
+a finite number larger than zero. By defining
+
+\[
+C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1,
+\]
+
we have a new optimization equation
+
+\[
+{\displaystyle \min_{\boldsymbol{\beta}\in
+{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1
+\]
+
which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.
+
Here we have defined the norm-1 as
+
+\[
+\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert.
+\]
+
Using the matrix-vector expression for Ridge regression and dropping the parameter \(1/n\) in front of the standard means squared error equation, we have
+
+\[
+C(\boldsymbol{X},\boldsymbol{\beta})=\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta},
+\]
+
and
+taking the derivatives with respect to \(\boldsymbol{\beta}\) we obtain then
+a slightly modified matrix inversion problem which for finite values
+of \(\lambda\) does not suffer from singularity problems. We obtain
+the optimal parameters
+
+\[
+\hat{\boldsymbol{\beta}}_{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
+\]
+
with \(\boldsymbol{I}\) being a \(p\times p\) identity matrix with the constraint that
+
+\[
+\sum_{i=0}^{p-1} \beta_i^2 \leq t,
+\]
+
with \(t\) a finite positive number.
+
When we compare this with the ordinary least squares result we have
+
+\[
+\hat{\boldsymbol{\beta}}_{\mathrm{OLS}} = \left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
+\]
+
which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix \(\boldsymbol{X}^T\boldsymbol{X}\) .
+
We see that Ridge regression is nothing but the standard OLS with a
+modified diagonal term added to \(\boldsymbol{X}^T\boldsymbol{X}\) . The consequences, in
+particular for our discussion of the bias-variance tradeoff are rather
+interesting. We will see that for specific values of \(\lambda\) , we may
+even reduce the variance of the optimal parameters \(\boldsymbol{\beta}\) . These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.
+
Using our insights about the SVD of the design matrix \(\boldsymbol{X}\)
+We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \(\boldsymbol{U}\) as
+
+\[
+\tilde{\boldsymbol{y}}_{\mathrm{OLS}}=\boldsymbol{X}\boldsymbol{\beta} =\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}.
+\]
+
For Ridge regression this becomes
+
+\[
+\tilde{\boldsymbol{y}}_{\mathrm{Ridge}}=\boldsymbol{X}\boldsymbol{\beta}_{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{\Sigma}^2\boldsymbol{V}^T+\lambda\boldsymbol{I} \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\sum_{j=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{y},
+\]
+
with the vectors \(\boldsymbol{u}_j\) being the columns of \(\boldsymbol{U}\) from the SVD of the matrix \(\boldsymbol{X}\) .
+
Since \(\lambda \geq 0\) , it means that compared to OLS, we have
+
+\[
+\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1.
+\]
+
Ridge regression finds the coordinates of \(\boldsymbol{y}\) with respect to the
+orthonormal basis \(\boldsymbol{U}\) , it then shrinks the coordinates by
+\(\frac{\sigma_j^2}{\sigma_j^2+\lambda}\) . Recall that the SVD has
+eigenvalues ordered in a descending way, that is \(\sigma_i \geq
+\sigma_{i+1}\) .
+
For small eigenvalues \(\sigma_i\) it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.
+
For the sake of simplicity, let us assume that the design matrix is orthonormal, that is
+
+\[
+\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}.
+\]
+
In this case the standard OLS results in
+
+\[
+\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\boldsymbol{y},
+\]
+
and
+
+\[
+\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{I}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\left(1+\lambda\right)^{-1}\boldsymbol{\beta}^{\mathrm{OLS}},
+\]
+
that is the Ridge estimator scales the OLS estimator by the inverse of a factor \(1+\lambda\) , and
+the Ridge estimator converges to zero when the hyperparameter goes to
+infinity.
+
We will come back to more interpreations after we have gone through some of the statistical analysis part.
+
For more discussions of Ridge and Lasso regression, Wessel van Wieringen’s article is highly recommended.
+Similarly, Mehta et al’s article is also recommended.
+
Using the matrix-vector expression for Lasso regression and dropping the parameter \(1/n\) in front of the standard means squared error equation, we have the following cost function
+
+\[
+C(\boldsymbol{X},\boldsymbol{\beta})=\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1,
+\]
+
Taking the derivative with respect to \(\boldsymbol{\beta}\) and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)
+
+\[\begin{split}
+\frac{d \vert \beta\vert}{d \boldsymbol{\beta}}=\mathrm{sgn}(\boldsymbol{\beta})=\left\{\begin{array}{cc} 1 & \beta > 0 \\ 0 & \beta =0\\-1 & \beta < 0, \end{array}\right.
+\end{split}\]
+
we have that the derivative of the cost function is
+
+\[
+\frac{\partial C(\boldsymbol{X},\boldsymbol{\beta})}{\partial \boldsymbol{\beta}}=-2\boldsymbol{X}^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})+\lambda sgn(\boldsymbol{\beta})=0,
+\]
+
and reordering we have
+
+\[
+\boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta})+\lambda sgn(\boldsymbol{\beta})=2\boldsymbol{X}^T(\boldsymbol{y}.
+\]
+
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.
+
+
+
4.10. Code for SVD and Inversion of Matrices
+
How do we use the SVD to invert a matrix \(\boldsymbol{X}^\boldsymbol{X}\) which is singular or near singular?
+The simple answer is to use the linear algebra function for pseudoinvers, that is
+
+
+
+
---------------------------------------------------------------------------
+AttributeError Traceback (most recent call last)
+< ipython - input - 6 - 52 d2c51caad1 > in < module >
+----> 1 Ainv = np . linlag . pinv ( A )
+
+~/opt/anaconda3/lib/python3.8/site-packages/numpy/__init__.py in __getattr__ (attr)
+ 212 return Tester
+ 213 else :
+--> 214 raise AttributeError ( "module {!r} has no attribute "
+ 215 " {!r} " . format ( __name__ , attr ))
+ 216
+
+AttributeError : module 'numpy' has no attribute 'linlag'
+
+
+
+
+
Let us first look at a matrix which does not causes problems and write our own function where we just use the SVD.
+
+
Although our matrix to invert \(\boldsymbol{X}^T\boldsymbol{X}\) is a square matrix, our matrix may be singular.
+
The pseudoinverse is the generalization of the matrix inverse for square matrices to
+rectangular matrices where the number of rows and columns are not equal.
+
It is also called the the Moore-Penrose Inverse after two independent discoverers of the method or the Generalized Inverse.
+It is used for the calculation of the inverse for singular or near singular matrices and for rectangular matrices.
+
Using the SVD we can obtain the pseudoinverse of a matrix \(\boldsymbol{A}\) (labeled here as \(\boldsymbol{A}_{\mathrm{PI}}\)
+
+\[
+\boldsymbol{A}_{\mathrm{PI}}= \boldsymbol{V}\boldsymbol{D}_{\mathrm{PI}}\boldsymbol{U}^T,
+\]
+
where \(\boldsymbol{D}_{\mathrm{PI}}\) can be calculated by creating a diagonal matrix from \(\boldsymbol{Sigma}\) where we only keep the singular values (the non-zero values). The following code computes the pseudoinvers of the matrix based on the SVD.
+
+
As you can see from this example, our own decomposition based on the SVD agrees the pseudoinverse algorithm provided by Numpy .
+
+
+
4.11. Deriving the Ridge Regression Equations
+
Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is
+our optimization problem is
+
+\[
+{\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}.
+\]
+
or we can state it as
+
+\[
+{\displaystyle \min_{\boldsymbol{\beta}\in
+{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2,
+\]
+
where we have used the definition of a norm-2 vector, that is
+
+\[
+\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.
+\]
+
By minimizing the above equation with respect to the parameters
+\(\boldsymbol{\beta}\) we could then obtain an analytical expression for the
+parameters \(\boldsymbol{\beta}\) . We can add a regularization parameter \(\lambda\) by
+defining a new cost function to be optimized, that is
+
+\[
+{\displaystyle \min_{\boldsymbol{\beta}\in
+{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2
+\]
+
which leads to the Ridge regression minimization problem where we
+require that \(\vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t\) , where \(t\) is
+a finite number larger than zero. By defining
+
+\[
+C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1,
+\]
+
we have a new optimization equation
+
+\[
+{\displaystyle \min_{\boldsymbol{\beta}\in
+{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1
+\]
+
which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.
+
Here we have defined the norm-1 as
+
+\[
+\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert.
+\]
+
Using the matrix-vector expression for Ridge regression and dropping the parameter \(1/n\) in front of the standard means squared error equation, we have
+
+\[
+C(\boldsymbol{X},\boldsymbol{\beta})=\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta},
+\]
+
and
+taking the derivatives with respect to \(\boldsymbol{\beta}\) we obtain then
+a slightly modified matrix inversion problem which for finite values
+of \(\lambda\) does not suffer from singularity problems. We obtain
+the optimal parameters
+
+\[
+\hat{\boldsymbol{\beta}}_{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
+\]
+
with \(\boldsymbol{I}\) being a \(p\times p\) identity matrix with the constraint that
+
+\[
+\sum_{i=0}^{p-1} \beta_i^2 \leq t,
+\]
+
with \(t\) a finite positive number.
+
When we compare this with the ordinary least squares result we have
+
+\[
+\hat{\boldsymbol{\beta}}_{\mathrm{OLS}} = \left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
+\]
+
which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix \(\boldsymbol{X}^T\boldsymbol{X}\) .
+
We see that Ridge regression is nothing but the standard OLS with a
+modified diagonal term added to \(\boldsymbol{X}^T\boldsymbol{X}\) . The consequences, in
+particular for our discussion of the bias-variance tradeoff are rather
+interesting. We will see that for specific values of \(\lambda\) , we may
+even reduce the variance of the optimal parameters \(\boldsymbol{\beta}\) . These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.
+
Using our insights about the SVD of the design matrix \(\boldsymbol{X}\)
+We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \(\boldsymbol{U}\) as
+
+\[
+\tilde{\boldsymbol{y}}_{\mathrm{OLS}}=\boldsymbol{X}\boldsymbol{\beta} =\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}.
+\]
+
For Ridge regression this becomes
+
+\[
+\tilde{\boldsymbol{y}}_{\mathrm{Ridge}}=\boldsymbol{X}\boldsymbol{\beta}_{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{\Sigma}^2\boldsymbol{V}^T+\lambda\boldsymbol{I} \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\sum_{j=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{y},
+\]
+
with the vectors \(\boldsymbol{u}_j\) being the columns of \(\boldsymbol{U}\) from the SVD of the matrix \(\boldsymbol{X}\) .
+
Since \(\lambda \geq 0\) , it means that compared to OLS, we have
+
+\[
+\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1.
+\]
+
Ridge regression finds the coordinates of \(\boldsymbol{y}\) with respect to the
+orthonormal basis \(\boldsymbol{U}\) , it then shrinks the coordinates by
+\(\frac{\sigma_j^2}{\sigma_j^2+\lambda}\) . Recall that the SVD has
+eigenvalues ordered in a descending way, that is \(\sigma_i \geq
+\sigma_{i+1}\) .
+
For small eigenvalues \(\sigma_i\) it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.
+
For the sake of simplicity, let us assume that the design matrix is orthonormal, that is
+
+\[
+\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}.
+\]
+
In this case the standard OLS results in
+
+\[
+\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\boldsymbol{y},
+\]
+
and
+
+\[
+\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{I}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\left(1+\lambda\right)^{-1}\boldsymbol{\beta}^{\mathrm{OLS}},
+\]
+
that is the Ridge estimator scales the OLS estimator by the inverse of a factor \(1+\lambda\) , and
+the Ridge estimator converges to zero when the hyperparameter goes to
+infinity.
+
We will come back to more interpreations after we have gone through some of the statistical analysis part.
+
Using the matrix-vector expression for Lasso regression and dropping the parameter \(1/n\) in front of the standard mean squared error equation, we have the following cost function
+
+\[
+C(\boldsymbol{X},\boldsymbol{\beta})=\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1,
+\]
+
Taking the derivative with respect to \(\boldsymbol{\beta}\) and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)
+
+\[\begin{split}
+\frac{d \vert \beta\vert}{d \boldsymbol{\beta}}=\mathrm{sgn}(\boldsymbol{\beta})=\left\{\begin{array}{cc} 1 & \beta > 0 \\ 0 & \beta =0\\-1 & \beta < 0, \end{array}\right.
+\end{split}\]
+
we have that the derivative of the cost function is
+
+\[
+\frac{\partial C(\boldsymbol{X},\boldsymbol{\beta})}{\partial \boldsymbol{\beta}}=-2\boldsymbol{X}^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})+\lambda sgn(\boldsymbol{\beta})=0,
+\]
+
and reordering we have
+
+\[
+\boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}+\lambda sgn(\boldsymbol{\beta})=2\boldsymbol{X}^T\boldsymbol{y}.
+\]
+
This equation does not lead to a nice analytical equation as in 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.
+
Let us assume that our design matrix is given by unit (identity) matrix, that is a square diagonal matrix with ones only along the
+diagonal. In this case we have an equal number of rows and columns \(n=p\) .
+
Our model approximation is just \(\tilde{\boldsymbol{y}}=\boldsymbol{\beta}\) and the mean squared error and thereby the cost function for ordinary least sqquares (OLS) is then (we drop the term \(1/n\) )
+
+\[
+C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2,
+\]
+
and minimizing we have that
+
+\[
+\hat{\beta}_i^{\mathrm{OLS}} = y_i.
+\]
+
For Ridge regression our cost function is
+
+\[
+C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\beta_i^2,
+\]
+
and minimizing we have that
+
+\[
+\hat{\beta}_i^{\mathrm{Ridge}} = \frac{y_i}{1+\lambda}.
+\]
+
For Lasso regression our cost function is
+
+\[
+C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\vert\beta_i\vert=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\sqrt{\beta_i^2},
+\]
+
and minimizing we have that
+
+\[
+-2\sum_{i=0}^{p-1}(y_i-\beta_i)+\lambda \sum_{i=0}^{p-1}\frac{(\beta_i)}{\vert\beta_i\vert}=0,
+\]
+
which leads to
+
+\[\begin{split}
+\hat{\boldsymbol{\beta}}_i^{\mathrm{Lasso}} = \left\{\begin{array}{ccc}y_i-\frac{\lambda}{2} &\mathrm{if} & y_i> \frac{\lambda}{2}\\
+ y_i+\frac{\lambda}{2} &\mathrm{if} & y_i< -\frac{\lambda}{2}\\
+ 0 &\mathrm{if} & \vert y_i\vert\le \frac{\lambda}{2}\end{array}\right.\\.
+\end{split}\]
+
Plotting these results (figure in handwritten notes for week 36 ) shows clearly that Lasso regression suppresses (sets to zero) values of \(\beta_i\) for specific values of \(\lambda\) . Ridge regression reduces on the other hand the values of \(\beta_i\) as function of \(\lambda\) .
+
As another examples,
+let us assume we have a data set with outputs/targets given by the vector
+
+\[\begin{split}
+\boldsymbol{y}=\begin{bmatrix}4 \\ 2 \\3\end{bmatrix},
+\end{split}\]
+
and our inputs as a \(3\times 2\) design matrix
+
+\[\begin{split}
+\boldsymbol{X}=\begin{bmatrix}2 & 0\\ 0 & 1 \\ 0 & 0\end{bmatrix},
+\end{split}\]
+
meaning that we have two features and two unknown parameters \(\beta_0\) and \(\beta_1\) to be determined either by ordinary least squares, Ridge or Lasso regression.
+
For ordinary least squares (OLS) we know that the optimal solution is
+
+\[
+\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left( \boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
+\]
+
Inserting the above values we obtain that
+
+\[\begin{split}
+\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\begin{bmatrix}2 \\ 2\end{bmatrix},
+\end{split}\]
+
The code which implements this simpler case is presented after the discussion of Ridge and Lasso.
+
For Ridge regression we have
+
+\[
+\hat{\boldsymbol{\beta}}^{\mathrm{Ridge}}=\left( \boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
+\]
+
Inserting the above values we obtain that
+
+\[\begin{split}
+\hat{\boldsymbol{\beta}}^{\mathrm{Ridge}}=\begin{bmatrix}\frac{8}{4+\lambda} \\ \frac{2}{1+\lambda}\end{bmatrix},
+\end{split}\]
+
There is normally a constraint on the value of \(\vert\vert \boldsymbol{\beta}\vert\vert_2\) via the parameter \(\lambda\) .
+Let us for simplicity assume that \(\beta_0^2+\beta_1^2=1\) as constraint. This will allow us to find an expression for the optimal values of \(\beta\) and \(\lambda\) .
+
To see this, let us write the cost function for Ridge regression.
+
We define the MSE without the \(1/n\) factor and have then, using that
+
+\[\begin{split}
+\boldsymbol{X}\boldsymbol{\beta}=\begin{bmatrix} 2\beta_0 \\ \beta_1 \\0 \end{bmatrix},
+\end{split}\]
+
+\[
+C(\boldsymbol{\beta})=(4-2\beta_0)^2+(2-\beta_1)^2+\lambda(\beta_0^2+\beta_1^2),
+\]
+
and taking the derivative with respect to \(\beta_0\) we get
+
+\[
+\beta_0=\frac{8}{4+\lambda},
+\]
+
and for \(\beta_1\) we obtain
+
+\[
+\beta_1=\frac{2}{1+\lambda},
+\]
+
Using the constraint for \(\beta_0^2+\beta_1^2=1\) we can constrain \(\lambda\) by solving
+
+\[
+\left(\frac{8}{4+\lambda}\right)^2+\left(\frac{2}{1+\lambda}\right)^2=1,
+\]
+
which gives \(\lambda=4.571\) and \(\beta_0=0.933\) and \(\beta_1=0.359\) .
+
For Lasso we need now, keeping a constraint on \(\vert\beta_0\vert+\vert\beta_1\vert=1\) , to take the derivative of the absolute values of \(\beta_0\)
+and \(\beta_1\) . This gives us the following derivatives of the cost function
+
+\[
+C(\boldsymbol{\beta})=(4-2\beta_0)^2+(2-\beta_1)^2+\lambda(\vert\beta_0\vert+\vert\beta_1\vert),
+\]
+
+\[
+\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_0}=-4(4-2\beta_0)+\lambda\mathrm{sgn}(\beta_0)=0,
+\]
+
and
+
+\[
+\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_1}=-2(2-\beta_1)+\lambda\mathrm{sgn}(\beta_1)=0.
+\]
+
We have now four cases to solve besides the trivial cases \(\beta_0\) and/or \(\beta_1\) are zero, namely
+
+\(\beta_0 > 0\) and \(\beta_1 > 0\) ,
+\(\beta_0 > 0\) and \(\beta_1 < 0\) ,
+\(\beta_0 < 0\) and \(\beta_1 > 0\) ,
+\(\beta_0 < 0\) and \(\beta_1 < 0\) .
+
+
If we consider the first case, we have then
+
+\[
+-4(4-2\beta_0)+\lambda=0,
+\]
+
and
+
+\[
+-2(2-\beta_1)+\lambda=0.
+\]
+
which yields
+
+\[
+\beta_0=\frac{16+\lambda}{8},
+\]
+
and
+
+\[
+\beta_1=\frac{4+\lambda}{2}.
+\]
+
Using the constraint on \(\beta_0\) and \(\beta_1\) we can then find the optimal value of \(\lambda\) for the different cases. We leave this as an exercise to you.
+
Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of \(\lambda\) , meaning that we need to perform a search in order to find the optimal values.
+
First we study and compare the OLS and Ridge results. The next code compares all three methods.
+
+
We see here that we reach a plateau. What is actually happening?
+
+
Another Example, now with a polynomial fit.
+
+
+
+
4.12. Linking the regression analysis with a statistical interpretation
+
We will now couple the discussions of ordinary least squares, Ridge
+and Lasso regression with a statistical interpretation, that is we
+move from a linear algebra analysis to a statistical analysis. In
+particular, we will focus on what the regularization terms can result
+in. We will amongst other things show that the regularization
+parameter can reduce considerably the variance of the parameters
+\(\beta\) .
The
advantage of doing linear regression is that we actually end up with
analytical expressions for several statistical quantities.
@@ -484,8 +2156,7 @@ mean value \(\boldsymbol{X}\boldsymbo
\sigma^2 \, \mathbf{I}_{nn}\) . From \(\mbox{Var}(\boldsymbol{\beta}) = \sigma^2
\, (\mathbf{X}^{T} \mathbf{X})^{-1}\) , one obtains an estimate of the
variance of the estimate of the \(j\) -th regression coefficient:
-\(\boldsymbol{\sigma}^2 (\boldsymbol{\beta}_j ) = \boldsymbol{\sigma}^2 \sqrt{
-[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} }\) . This may be used to
+\(\boldsymbol{\sigma}^2 (\boldsymbol{\beta}_j ) = \boldsymbol{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} \) . This may be used to
construct a confidence interval for the estimates.
In a similar way, we can obtain analytical expressions for say the
expectation values of the parameters \(\boldsymbol{\beta}\) and their variance
@@ -512,865 +2183,236 @@ when we employ Ridge regression, allowing us again to define a confidence interv
matrix product is non-negative definite.
This means the variance we obtain with the standard OLS will always for \(\lambda > 0\) be larger than the variance of \(\boldsymbol{\beta}\) obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below.
-
-
4.3. Resampling methods
-
With all these analytical equations for both the OLS and Ridge
-regression, we will now outline how to assess a given model. This will
-lead us to a discussion of the so-called bias-variance tradeoff (see
-below) and so-called resampling methods.
-
One of the quantities we have discussed as a way to measure errors is
-the mean-squared error (MSE), mainly used for fitting of continuous
-functions. Another choice is the absolute error.
-
In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,
-we discuss the
-
-prediction error or simply the test error \(\mathrm{Err_{Test}}\) , where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the
-training error \(\mathrm{Err_{Train}}\) , which is the average loss over the training data.
-
-
As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.
-For a certain level of complexity the test error will reach minimum, before starting to increase again. The
-training error reaches a saturation.
-
Two famous
-resampling methods are the independent bootstrap and the jackknife .
-
The jackknife is a special case of the independent bootstrap. Still, the jackknife was made
-popular prior to the independent bootstrap. And as the popularity of
-the independent bootstrap soared, new variants, such as the dependent bootstrap .
-
The Jackknife and independent bootstrap work for
-independent, identically distributed random variables.
-If these conditions are not
-satisfied, the methods will fail. Yet, it should be said that if the data are
-independent, identically distributed, and we only want to estimate the
-variance of \(\overline{X}\) (which often is the case), then there is no
-need for bootstrapping.
-
The Jackknife works by making many replicas of the estimator \(\widehat{\theta}\) .
-The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \(\boldsymbol{x} = (x_1,x_2,\cdots,X_n)\) .
-Let \(\boldsymbol{x}_i\) denote the vector
+
+
4.13. Deriving OLS from a probability distribution
+
Our basic assumption when we derived the OLS equations was to assume
+that our output is determined by a given continuous function
+\(f(\boldsymbol{x})\) and a random noise \(\boldsymbol{\epsilon}\) given by the normal
+distribution with zero mean value and an undetermined variance
+\(\sigma^2\) .
+
We found above that the outputs \(\boldsymbol{y}\) have a mean value given by
+\(\boldsymbol{X}\hat{\boldsymbol{\beta}}\) and variance \(\sigma^2\) . Since the entries to
+the design matrix are not stochastic variables, we can assume that the
+probability distribution of our targets is also a normal distribution
+but now with mean value \(\boldsymbol{X}\hat{\boldsymbol{\beta}}\) . This means that a
+single output \(y_i\) is given by the Gaussian distribution
\[
-\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n),
+y_i\sim \mathcal{N}(\boldsymbol{X}_{i,*}\boldsymbol{\beta}, \sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
\]
-
which equals the vector \(\boldsymbol{x}\) with the exception that observation
-number \(i\) is left out. Using this notation, define
-\(\widehat{\theta}_i\) to be the estimator
-\(\widehat{\theta}\) computed using \(\vec{X}_i\) .
-
-
-
-
Runtime: 0.139475 sec
-Jackknife Statistics :
-original bias std. error
- 99.6714 99.6614 0.149667
-
-
-
-
-
-
4.3.1. Bootstrap
-
Bootstrapping is a nonparametric approach to statistical inference
-that substitutes computation for more traditional distributional
-assumptions and asymptotic results. Bootstrapping offers a number of
-advantages:
-
-The bootstrap is quite general, although there are some cases in which it fails.
-Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small.
-It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically.
-It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).
-
-
Since \(\widehat{\theta} = \widehat{\theta}(\boldsymbol{X})\) is a function of random variables,
-\(\widehat{\theta}\) itself must be a random variable. Thus it has
-a pdf, call this function \(p(\boldsymbol{t})\) . The aim of the bootstrap is to
-estimate \(p(\boldsymbol{t})\) by the relative frequency of
-\(\widehat{\theta}\) . You can think of this as using a histogram
-in the place of \(p(\boldsymbol{t})\) . If the relative frequency closely
-resembles \(p(\vec{t})\) , then using numerics, it is straight forward to
-estimate all the interesting parameters of \(p(\boldsymbol{t})\) using point
-estimators.
-
In the case that \(\widehat{\theta}\) has
-more than one component, and the components are independent, we use the
-same estimator on each component separately. If the probability
-density function of \(X_i\) , \(p(x)\) , had been known, then it would have
-been straight forward to do this by:
-
-Drawing lots of numbers from \(p(x)\) , suppose we call one such set of numbers \((X_1^*, X_2^*, \cdots, X_n^*)\) .
-Then using these numbers, we could compute a replica of \(\widehat{\theta}\) called \(\widehat{\theta}^*\) .
-
-
By repeated use of (1) and (2), many
-estimates of \(\widehat{\theta}\) could have been obtained. The
-idea is to use the relative frequency of \(\widehat{\theta}^*\)
-(think of a histogram) as an estimate of \(p(\boldsymbol{t})\) .
-
But
-unless there is enough information available about the process that
-generated \(X_1,X_2,\cdots,X_n\) , \(p(x)\) is in general
-unknown. Therefore, Efron in 1979 asked the
-question: What if we replace \(p(x)\) by the relative frequency
-of the observation \(X_i\) ; if we draw observations in accordance with
-the relative frequency of the observations, will we obtain the same
-result in some asymptotic sense? The answer is yes.
-
Instead of generating the histogram for the relative
-frequency of the observation \(X_i\) , just draw the values
-\((X_1^*,X_2^*,\cdots,X_n^*)\) with replacement from the vector
-\(\boldsymbol{X}\) .
-
The independent bootstrap works like this:
-
-Draw with replacement \(n\) numbers for the observed variables \(\boldsymbol{x} = (x_1,x_2,\cdots,x_n)\) .
-Define a vector \(\boldsymbol{x}^*\) containing the values which were drawn from \(\boldsymbol{x}\) .
-Using the vector \(\boldsymbol{x}^*\) compute \(\widehat{\theta}^*\) by evaluating \(\widehat \theta\) under the observations \(\boldsymbol{x}^*\) .
-Repeat this process \(k\) times.
-
-
When you are done, you can draw a histogram of the relative frequency
-of \(\widehat \theta^*\) . This is your estimate of the probability
-distribution \(p(t)\) . Using this probability distribution you can
-estimate any statistics thereof. In principle you never draw the
-histogram of the relative frequency of \(\widehat{\theta}^*\) . Instead
-you use the estimators corresponding to the statistic of interest. For
-example, if you are interested in estimating the variance of \(\widehat
-\theta\) , apply the etsimator \(\widehat \sigma^2\) to the values
-\(\widehat \theta ^*\) .
-
The following code starts with a Gaussian distribution with mean value
-\(\mu =100\) and variance \(\sigma=15\) . We use this to generate the data
-used in the bootstrap analysis. The bootstrap analysis returns a data
-set after a given number of bootstrap operations (as many as we have
-data points). This data set consists of estimated mean values for each
-bootstrap operation. The histogram generated by the bootstrap method
-shows that the distribution for these mean values is also a Gaussian,
-centered around the mean value \(\mu=100\) but with standard deviation
-\(\sigma/\sqrt{n}\) , where \(n\) is the number of bootstrap samples (in
-this case the same as the number of original data points). The value
-of the standard deviation is what we expect from the central limit
-theorem.
-
-
-
-
Runtime: 1.78195 sec
-Bootstrap Statistics :
-original bias std. error
- 100.073 14.9354 100.074 0.149903
-
-
-
---------------------------------------------------------------------------
-AttributeError Traceback (most recent call last)
-< ipython - input - 2 - 772 b904ae9cb > in < module >
- 31 t = bootstrap ( x , stat , datapoints )
- 32 # the histogram of the bootstrapped data
----> 33 n , binsboot , patches = plt . hist ( t , 50 , normed = 1 , facecolor = 'red' , alpha = 0.75 )
- 34
- 35 # add a 'best fit' line
-
-~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/pyplot.py in hist (x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, data, **kwargs)
- 2683 orientation = 'vertical' , rwidth = None , log = False , color = None ,
- 2684 label = None , stacked = False , * , data = None , ** kwargs ):
--> 2685 return gca () . hist (
- 2686 x , bins = bins , range = range , density = density , weights = weights ,
- 2687 cumulative = cumulative , bottom = bottom , histtype = histtype ,
-
-~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/__init__.py in inner (ax, data, *args, **kwargs)
- 1445 def inner ( ax , * args , data = None , ** kwargs ):
- 1446 if data is None :
--> 1447 return func ( ax , * map ( sanitize_sequence , args ), ** kwargs )
- 1448
- 1449 bound = new_sig . bind ( ax , * args , ** kwargs )
-
-~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/axes/_axes.py in hist (self, x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs)
- 6813 if patch :
- 6814 p = patch [ 0 ]
--> 6815 p . update ( kwargs )
- 6816 if lbl is not None :
- 6817 p . set_label ( lbl )
-
-~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/artist.py in update (self, props)
- 994 func = getattr ( self , f "set_ { k } " , None )
- 995 if not callable ( func ):
---> 996 raise AttributeError ( f " { type ( self ) . __name__ !r} object "
- 997 f "has no property { k !r} " )
- 998 ret . append ( func ( v ))
-
-AttributeError : 'Rectangle' object has no property 'normed'
-
-
-
-
-
-
-
-
-
4.4. Various steps in cross-validation
-
When the repetitive splitting of the data set is done randomly,
-samples may accidently end up in a fast majority of the splits in
-either training or test set. Such samples may have an unbalanced
-influence on either model building or prediction evaluation. To avoid
-this \(k\) -fold cross-validation structures the data splitting. The
-samples are divided into \(k\) more or less equally sized exhaustive and
-mutually exclusive subsets. In turn (at each split) one of these
-subsets plays the role of the test set while the union of the
-remaining subsets constitutes the training set. Such a splitting
-warrants a balanced representation of each sample in both training and
-test set over the splits. Still the division into the \(k\) subsets
-involves a degree of randomness. This may be fully excluded when
-choosing \(k=n\) . This particular case is referred to as leave-one-out
-cross-validation (LOOCV).
-
-Define a range of interest for the penalty parameter.
-Divide the data set into training and test set comprising samples \(\{1, \ldots, n\} \setminus i\) and \(\{ i \}\) , respectively.
-Fit the linear regression model by means of ridge estimation for each \(\lambda\) in the grid using the training set, and the corresponding estimate of the error variance \(\boldsymbol{\sigma}_{-i}^2(\lambda)\) , as
-
+
We assume now that the various \(y_i\) values are stochastically distributed according to the above Gaussian distribution.
+We define this distribution as
\[
-\begin{align*}
-\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T}
-\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1}
-\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i}
-\end{align*}
+p(y_i, \boldsymbol{X}\vert\boldsymbol{\beta})=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]},
\]
-
-Evaluate the prediction performance of these models on the test set by \(\log\{L[y_i, \boldsymbol{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}\) . Or, by the prediction error \(|y_i - \boldsymbol{X}_{i, \ast} \boldsymbol{\beta}_{-i}(\lambda)|\) , the relative error, the error squared or the R2 score function.
-Repeat the first three steps such that each sample plays the role of the test set once.
-Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as
-
+
which reads as finding the likelihood of an event \(y_i\) with the input variables \(\boldsymbol{X}\) given the parameters (to be determined) \(\boldsymbol{\beta}\) .
+
Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event \(\boldsymbol{y}\) as the product of the single events, that is we have
\[
-\begin{align*}
-\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}.
-\end{align*}
+p(\boldsymbol{y},\boldsymbol{X}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta}).
\]
-
For the various values of \(k\)
-
-shuffle the dataset randomly.
-Split the dataset into \(k\) groups.
-For each unique group:
-
-
a. Decide which group to use as set for test data
-
b. Take the remaining groups as a training data set
-
c. Fit a model on the training set and evaluate it on the test set
-
d. Retain the evaluation score and discard the model
-
-Summarize the model using the sample of model evaluation scores
-
-
The code here uses Ridge regression with cross-validation (CV) resampling and \(k\) -fold CV in order to fit a specific polynomial.
+
We will write this in a more compact form reserving \(\boldsymbol{D}\) for the domain of events, including the ouputs (targets) and the inputs. That is
+in case we have a simple one-dimensional input and output case
+
+\[
+\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})].
+\]
+
In the more general case the various inputs should be replaced by the possible features represented by the input data set \(\boldsymbol{X}\) .
+We can now rewrite the above probability as
+
+\[
+p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
+\]
+
It is a conditional probability (see below) and reads as the likelihood of a domain of events \(\boldsymbol{D}\) given a set of parameters \(\boldsymbol{\beta}\) .
+
In statistics, maximum likelihood estimation (MLE) is a method of
+estimating the parameters of an assumed probability distribution,
+given some observed data. This is achieved by maximizing a likelihood
+function so that, under the assumed statistical model, the observed
+data is the most probable.
+
We will assume here that our events are given by the above Gaussian
+distribution and we will determine the optimal parameters \(\beta\) by
+maximizing the above PDF. However, computing the derivatives of a
+product function is cumbersome and can easily lead to overflow and/or
+underflowproblems, with potentials for loss of numerical precision.
+
In practice, it is more convenient to maximize the logarithm of the
+PDF because it is a monotonically increasing function of the argument.
+Alternatively, and this will be our option, we will minimize the
+negative of the logarithm since this is a monotonically decreasing
+function.
+
Note also that maximization/minimization of the logarithm of the PDF
+is equivalent to the maximization/minimization of the function itself.
+
We could now define a new cost function to minimize, namely the negative logarithm of the above PDF
+
+\[
+C(\boldsymbol{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})},
+\]
+
which becomes
+
+\[
+C(\boldsymbol{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}.
+\]
+
Taking the derivative of the new cost function with respect to the parameters \(\beta\) we recognize our familiar OLS equation, namely
+
+\[
+\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right) =0,
+\]
+
which leads to the well-known OLS equation for the optimal paramters \(\beta\)
+
+\[
+\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}!
+\]
+
Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics.
+
A central theorem in statistics is Bayes’ theorem. This theorem plays a similar role as the good old Pythagoras’ theorem in geometry.
+Bayes’ theorem is extremely simple to derive. But to do so we need some basic axioms from statistics.
+
Assume we have two domains of events \(X=[x_0,x_1,\dots,x_{n-1}]\) and \(Y=[y_0,y_1,\dots,y_{n-1}]\) .
+
We define also the likelihood for \(X\) and \(Y\) as \(p(X)\) and \(p(Y)\) respectively.
+The likelihood of a specific event \(x_i\) (or \(y_i\) ) is then written as \(p(X=x_i)\) or just \(p(x_i)=p_i\) .
+
Union of events is given by.
+
+\[
+p(X \cup Y)= p(X)+p(Y)-p(X \cap Y).
+\]
+
The product rule (aka joint probability) is given by.
+
+\[
+p(X \cup Y)= p(X,Y)= p(X\vert Y)p(Y)=p(Y\vert X)p(X),
+\]
+
where we read \(p(X\vert Y)\) as the likelihood of obtaining \(X\) given \(Y\) .
+
If we have independent events then \(p(X,Y)=p(X)p(Y)\) .
+
The marginal probability is defined in terms of only one of the set of variables \(X,Y\) . For a discrete probability we have
+
+\[
+p(X)=\sum_{i=0}^{n-1}p(X,Y=y_i)=\sum_{i=0}^{n-1}p(X\vert Y=y_i)p(Y=y_i)=\sum_{i=0}^{n-1}p(X\vert y_i)p(y_i).
+\]
+
The conditional probability, if \(p(Y) > 0\) , is
+
+\[
+p(X\vert Y)= \frac{p(X,Y)}{p(Y)}=\frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}.
+\]
+
If we combine the conditional probability with the marginal probability and the standard product rule, we have
+
+\[
+p(X\vert Y)= \frac{p(X,Y)}{p(Y)},
+\]
+
which we can rewrite as
+
+\[
+p(X\vert Y)= \frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}=\frac{p(Y\vert X)p(X)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)},
+\]
+
which is Bayes’ theorem. It allows us to evaluate the uncertainty in in \(X\) after we have observed \(Y\) . We can easily interchange \(X\) with \(Y\) .
+
The quantity \(p(Y\vert X)\) on the right-hand side of the theorem is
+evaluated for the observed data \(Y\) and can be viewed as a function of
+the parameter space represented by \(X\) . This function is not
+necesseraly normalized and is normally called the likelihood function.
+
The function \(p(X)\) on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution.
+
Let us try to illustrate Bayes’ theorem through an example.
+
Let us suppose that you are undergoing a series of mammography scans in
+order to rule out possible breast cancer cases. We define the
+sensitivity for a positive event by the variable \(X\) . It takes binary
+values with \(X=1\) representing a positive event and \(X=0\) being a
+negative event. We reserve \(Y\) as a classification parameter for
+either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing).
+
We let \(Y=1\) represent the the case of having breast cancer and \(Y=0\) as not.
+
Let us assume that if you have breast cancer, the test will be positive with a probability of \(0.8\) , that is we have
+
+\[
+p(X=1\vert Y=1) =0.8.
+\]
+
This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of \(80\%\) for having cancer.
+It is however not correct, as the following Bayesian analysis shows.
+
If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number.
+Let us assume that the prior probability in the population as a whole is
+
+\[
+p(Y=1) =0.004.
+\]
+
We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have
+
+\[
+p(X=1\vert Y=0) =0.1.
+\]
+
Using Bayes’ theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute
+
+\[
+p(Y=1\vert X=1)=\frac{p(X=1\vert Y=1)p(Y=1)}{p(X=1\vert Y=1)p(Y=1)+p(X=1\vert Y=0)p(Y=0)}=\frac{0.8\times 0.004}{0.8\times 0.004+0.1\times 0.996}=0.031.
+\]
+
That is, in case of a positive test, there is only a \(3\%\) chance of having breast cancer!
+
+
+
4.14. Bayes’ Theorem and Ridge and Lasso Regression
+
Hitherto we have discussed Ridge and Lasso regression in terms of a
+linear analysis. This may to many of you feel rather technical and
+perhaps not that intuitive. The question is whether we can develop a
+more intuitive way of understanding what Ridge and Lasso express.
+
Before we proceed let us perform a Ridge, Lasso and OLS analysis of a polynomial fit.
+
We will play around with a study of the values for the optimal
+parameters \(\boldsymbol{\beta}\) using OLS, Ridge and Lasso regression. For
+OLS, you will notice as function of the noise and polynomial degree,
+that the parameters \(\beta\) will fluctuate from order to order in the
+polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS.
+
For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one.
-
-
-
4.5. The bias-variance tradeoff
-
We will discuss the bias-variance tradeoff in the context of
-continuous predictions such as regression. However, many of the
-intuitions and ideas discussed here also carry over to classification
-tasks. Consider a dataset \(\mathcal{L}\) consisting of the data
-\(\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}\) .
-
Let us assume that the true data is generated from a noisy model
-
-\[
-\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon}
-\]
-
where \(\epsilon\) is normally distributed with mean zero and standard deviation \(\sigma^2\) .
-
In our derivation of the ordinary least squares method we defined then
-an approximation to the function \(f\) in terms of the parameters
-\(\boldsymbol{\beta}\) and the design matrix \(\boldsymbol{X}\) which embody our model,
-that is \(\boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta}\) .
-
Thereafter we found the parameters \(\boldsymbol{\beta}\) by optimizing the means squared error via the so-called cost function
-
-\[
-C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right].
-\]
-
We can rewrite this as
-
-\[
-\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2.
-\]
-
The three terms represent the square of the bias of the learning
-method, which can be thought of as the error caused by the simplifying
-assumptions built into the method. The second term represents the
-variance of the chosen model and finally the last terms is variance of
-the error \(\boldsymbol{\epsilon}\) .
-
To derive this equation, we need to recall that the variance of \(\boldsymbol{y}\) and \(\boldsymbol{\epsilon}\) are both equal to \(\sigma^2\) . The mean value of \(\boldsymbol{\epsilon}\) is by definition equal to zero. Furthermore, the function \(f\) is not a stochastics variable, idem for \(\boldsymbol{\tilde{y}}\) .
-We use a more compact notation in terms of the expectation value
-
-\[
-\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right],
-\]
-
and adding and subtracting \(\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]\) we get
-
-\[
-\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right],
-\]
-
which, using the abovementioned expectation values can be rewritten as
-
-\[
-\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2,
-\]
-
that is the rewriting in terms of the so-called bias, the variance of the model \(\boldsymbol{\tilde{y}}\) and the variance of \(\boldsymbol{\epsilon}\) .
-
-
-
The bias-variance tradeoff summarizes the fundamental tension in
-machine learning, particularly supervised learning, between the
-complexity of a model and the amount of training data needed to train
-it. Since data is often limited, in practice it is often useful to
-use a less-complex model with higher bias, that is a model whose asymptotic
-performance is worse than another model because it is easier to
-train and less sensitive to sampling noise arising from having a
-finite-sized training dataset (smaller variance).
-
The above equations tell us that in
-order to minimize the expected test error, we need to select a
-statistical learning method that simultaneously achieves low variance
-and low bias. Note that variance is inherently a nonnegative quantity,
-and squared bias is also nonnegative. Hence, we see that the expected
-test MSE can never lie below \(Var(\epsilon)\) , the irreducible error.
-
What do we mean by the variance and bias of a statistical learning
-method? The variance refers to the amount by which our model would change if we
-estimated it using a different training data set. Since the training
-data are used to fit the statistical learning method, different
-training data sets will result in a different estimate. But ideally the
-estimate for our model should not vary too much between training
-sets. However, if a method has high variance then small changes in
-the training data can result in large changes in the model. In general, more
-flexible statistical methods have higher variance.
-
You may also find this recent article of interest.
-
-
-
-
-
+
How can we understand this?
+
Using Bayes’ theorem we can gain a better intuition about Ridge and Lasso regression.
+
For ordinary least squares we postulated that the maximum likelihood for the doamin of events \(\boldsymbol{D}\) (one-dimensional case)
+
+\[
+\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})],
+\]
+
is given by
+
+\[
+p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
+\]
+
In Bayes’ theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set \(\boldsymbol{\beta}\) given a domain of events \(\boldsymbol{D}\) ? That is, how can we define the posterior probability
+
+\[
+p(\boldsymbol{\beta}\vert\boldsymbol{D}).
+\]
+
Bayes’ theorem comes to our rescue here since (omitting the normalization constant)
+
+\[
+p(\boldsymbol{\beta}\vert\boldsymbol{D})\propto p(\boldsymbol{D}\vert\boldsymbol{\beta})p(\boldsymbol{\beta}).
+\]
+
We have a model for \(p(\boldsymbol{D}\vert\boldsymbol{\beta})\) but need one for the prior \(p(\boldsymbol{\beta}\) !
+
With the posterior probability defined by a likelihood which we have
+already modeled and an unknown prior, we are now ready to make
+additional models for the prior.
+
We can, based on our discussions of the variance of \(\boldsymbol{\beta}\) and the mean value, assume that the prior for the values \(\boldsymbol{\beta}\) is given by a Gaussian with mean value zero and variance \(\tau^2\) , that is
+
+\[
+p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}.
+\]
+
Our posterior probability becomes then (omitting the normalization factor which is just a constant)
+
+\[
+p(\boldsymbol{\beta\vert\boldsymbol{D})}=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}.
+\]
+
We can now optimize this quantity with respect to \(\boldsymbol{\beta}\) . As we
+did for OLS, this is most conveniently done by taking the negative
+logarithm of the posterior probability. Doing so and leaving out the
+constants terms that do not depend on \(\beta\) , we have
+
+\[
+C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{2\tau^2}\vert\vert\boldsymbol{\beta}\vert\vert_2^2,
+\]
+
and replacing \(1/2\tau^2\) with \(\lambda\) we have
+
+\[
+C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_2^2,
+\]
+
which is our Ridge cost function! Nice, isn’t it?
+
To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution (Laplace in this case ) with zero mean value, that is
+
+\[
+p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}.
+\]
+
Our posterior probability becomes then (omitting the normalization factor which is just a constant)
+
+\[
+p(\boldsymbol{\beta}\vert\boldsymbol{D})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}.
+\]
+
Taking the negative
+logarithm of the posterior probability and leaving out the
+constants terms that do not depend on \(\beta\) , we have
+
+\[
+C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{\tau}\vert\vert\boldsymbol{\beta}\vert\vert_1,
+\]
+
and replacing \(1/\tau\) with \(\lambda\) we have
+
+\[
+C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1,
+\]
+
which is our Lasso cost function!
@@ -1408,7 +2523,7 @@ flexible statistical methods have higher variance.
diff --git a/doc/LectureNotes/_build/html/chapter3.html b/doc/LectureNotes/_build/html/chapter3.html
index 63e1311af..989438d69 100644
--- a/doc/LectureNotes/_build/html/chapter3.html
+++ b/doc/LectureNotes/_build/html/chapter3.html
@@ -5,7 +5,7 @@
-
5. Ridge and Lasso Regression — Applied Data Analysis and Machine Learning
+
5. Resampling Methods — Applied Data Analysis and Machine Learning
@@ -55,7 +55,7 @@
-
+
@@ -139,17 +139,17 @@
- 3. Linear Regression, basic Elements
+ 3. Linear Regression
- 4. Resampling Methods
+ 4. Ridge and Lasso Regression
- 5. Ridge and Lasso Regression
+ 5. Resampling Methods
@@ -285,38 +285,35 @@
@@ -330,787 +327,1058 @@
-
-
5. Ridge and Lasso Regression
-
Video of Lecture
-
-
5.1. The singular value decomposition
-
The examples we have looked at so far are cases where we normally can
-invert the matrix \(\boldsymbol{X}^T\boldsymbol{X}\) . Using a polynomial expansion as we
-did both for the masses and the fitting of the equation of state,
-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.
-
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 partially 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 algorithm, perhaps
-the most powerful linear algebra algorithm. Let us look at a
-different example where we may have problems with the standard matrix
-inversion algorithm. Thereafter we dive into the math of the SVD.
-
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
+
+
5. Resampling Methods
+
+
5.1. Introduction
+
Resampling methods are an indispensable tool in modern
+statistics. They involve repeatedly drawing samples from a training
+set and refitting a model of interest on each sample in order to
+obtain additional information about the fitted model. For example, in
+order to estimate the variability of a linear regression fit, we can
+repeatedly draw different samples from the training data, fit a linear
+regression to each new sample, and then examine the extent to which
+the resulting fits differ. Such an approach may allow us to obtain
+information that would not be available from fitting the model only
+once using the original training sample.
+
Two resampling methods are often used in Machine Learning analyses,
+
+The bootstrap method
+and Cross-Validation
+
+
In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular
+cross-validation and the bootstrap method.
+
Resampling approaches can be computationally expensive, because they
+involve fitting the same statistical method multiple times using
+different subsets of the training data. However, due to recent
+advances in computing power, the computational requirements of
+resampling methods generally are not prohibitive. In this chapter, we
+discuss two of the most commonly used resampling methods,
+cross-validation and the bootstrap. Both methods are important tools
+in the practical application of many statistical learning
+procedures. For example, cross-validation can be used to estimate the
+test error associated with a given statistical learning method in
+order to evaluate its performance, or to select the appropriate level
+of flexibility. The process of evaluating a model’s performance is
+known as model assessment, whereas the process of selecting the proper
+level of flexibility for a model is known as model selection. The
+bootstrap is widely used.
+
+Our simulations can be treated as computer experiments . This is particularly the case for Monte Carlo methods
+The results can be analysed with the same statistical tools as we would use analysing experimental data.
+As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
+
+
+
+
5.2. Reminder on Statistics
+
+As in other experiments, many numerical experiments have two classes of errors:
+
+Statistical errors
+Systematical errors
+
+
+Statistical errors can be estimated using standard tools from statistics
+Systematical errors are method specific and must be treated differently from case to case.
+
+
The
+advantage of doing linear regression is that we actually end up with
+analytical expressions for several statistical quantities.
+Standard least squares and Ridge regression allow us to
+derive quantities like the variance and other expectation values in a
+rather straightforward way.
+
It is assumed that \(\varepsilon_i
+\sim \mathcal{N}(0, \sigma^2)\) and the \(\varepsilon_{i}\) are
+independent, i.e.:
\[\begin{split}
-\begin{align*}
-\mathbf{X} & = \left[
-\begin{array}{rrr}
-1 & -1 & 2
-\\
-1 & 0 & 1
-\\
-1 & 2 & -1
-\\
-1 & 1 & 0
-\end{array} \right]
+\begin{align*}
+\mbox{Cov}(\varepsilon_{i_1},
+\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if}
+& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right.
\end{align*}
\end{split}\]
-
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
+
The randomness of \(\varepsilon_i\) implies that
+\(\mathbf{y}_i\) is also a random variable. In particular,
+\(\mathbf{y}_i\) is normally distributed, because \(\varepsilon_i \sim
+\mathcal{N}(0, \sigma^2)\) and \(\mathbf{X}_{i,\ast} \, \boldsymbol{\beta}\) is a
+non-random scalar. To specify the parameters of the distribution of
+\(\mathbf{y}_i\) we need to calculate its first two moments.
+
Recall that \(\boldsymbol{X}\) is a matrix of dimensionality \(n\times p\) . The
+notation above \(\mathbf{X}_{i,\ast}\) means that we are looking at the
+row number \(i\) and perform a sum over all values \(p\) .
+
The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off)
+that there exists a function \(f(\boldsymbol{x})\) and a normal distributed error \(\boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2)\)
+which describe our data
+
+\[
+\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon}
+\]
+
We approximate this function with our model from the solution of the linear regression equations, that is our
+function \(f\) is approximated by \(\boldsymbol{\tilde{y}}\) where we want to minimize \((\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\) , our MSE, with
+
+\[
+\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}.
+\]
+
We can calculate the expectation value of \(\boldsymbol{y}\) for a given element \(i\)
+
+\[
+\begin{align*}
+\mathbb{E}(y_i) & =
+\mathbb{E}(\mathbf{X}_{i, \ast} \, \boldsymbol{\beta}) + \mathbb{E}(\varepsilon_i)
+\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta,
+\end{align*}
+\]
+
while
+its variance is
\[\begin{split}
-\begin{align*}
-\boldsymbol{X} & = \left[
-\begin{array}{rr}
-1 & -1
-\\
-1 & -1
-\end{array} \right].
+\begin{align*} \mbox{Var}(y_i) & = \mathbb{E} \{ [y_i
+- \mathbb{E}(y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( y_i^2 ) -
+[\mathbb{E}(y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \,
+\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 \\ &
+= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 \varepsilon_i
+\mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + \varepsilon_i^2 ] - ( \mathbf{X}_{i,
+\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2
+\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \boldsymbol{\beta} +
+\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2
+\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \,
+\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2.
\end{align*}
\end{split}\]
-
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.
-
If our design matrix \(\boldsymbol{X}\) which enters the linear regression problem
-
-
+
Hence, \(y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2)\) , that is \(\boldsymbol{y}\) follows a normal distribution with
+mean value \(\boldsymbol{X}\boldsymbol{\beta}\) and variance \(\sigma^2\) (not be confused with the singular values of the SVD).
+
With the OLS expressions for the parameters \(\boldsymbol{\beta}\) we can evaluate the expectation value
\[
-\begin{equation}
-\boldsymbol{\beta} = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y},
-\label{_auto1} \tag{1}
-\end{equation}
+\mathbb{E}(\boldsymbol{\beta}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}.
\]
-
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.
-
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.
-
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
-
-\[
-(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n),
-\]
-
and the eigenvalues are given by the diagonal matrix
-
-\[
-\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n).
-\]
-
The matrix \(\boldsymbol{X}\) can be written in terms of an orthogonal/unitary transformation \(\boldsymbol{U}\)
-
-\[
-\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,
-\]
-
with \(\boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I}\) or \(\boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I}\) .
-
Not all square matrices are diagonalizable. A matrix like the one discussed above
+
This means that the estimator of the regression parameters is unbiased.
+
We can also calculate the variance
+
The variance of \(\boldsymbol{\beta}\) is
\[\begin{split}
-\boldsymbol{X} = \begin{bmatrix}
-1& -1 \\
-1& -1\\
-\end{bmatrix}
+\begin{eqnarray*}
+\mbox{Var}(\boldsymbol{\beta}) & = & \mathbb{E} \{ [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})] [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})]^{T} \}
+\\
+& = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}]^{T} \}
+\\
+% & = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}]^{T} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+% \\
+% & = & \mathbb{E} \{ (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} \, \mathbf{Y}^{T} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+% \\
+& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \mathbb{E} \{ \mathbf{Y} \, \mathbf{Y}^{T} \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+\\
+& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+% \\
+% & = & (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1}
+% \\
+% & & + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \boldsymbol{\beta} \boldsymbol{\beta}^T
+\\
+& = & \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1},
+\end{eqnarray*}
\end{split}\]
-
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.
-
-
-
5.2. The SVD, a Fantastic Algorithm
-
However, and this is the strength of the SVD algorithm, any general
-matrix \(\boldsymbol{X}\) can be decomposed in terms of a diagonal matrix and
-two orthogonal/unitary matrices. The Singular Value Decompostion
-(SVD) theorem
-states that a general \(m\times n\) matrix \(\boldsymbol{X}\) can be written in
-terms of a diagonal matrix \(\boldsymbol{\Sigma}\) of dimensionality \(m\times n\)
-and two orthognal matrices \(\boldsymbol{U}\) and \(\boldsymbol{V}\) , where the first has
-dimensionality \(m \times m\) and the last dimensionality \(n\times n\) .
-We have then
+
where we have used that \(\mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) =
+\mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} +
+\sigma^2 \, \mathbf{I}_{nn}\) . From \(\mbox{Var}(\boldsymbol{\beta}) = \sigma^2
+\, (\mathbf{X}^{T} \mathbf{X})^{-1}\) , one obtains an estimate of the
+variance of the estimate of the \(j\) -th regression coefficient:
+\(\boldsymbol{\sigma}^2 (\boldsymbol{\beta}_j ) = \boldsymbol{\sigma}^2 \sqrt{
+[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} }\) . This may be used to
+construct a confidence interval for the estimates.
+
In a similar way, we can obtain analytical expressions for say the
+expectation values of the parameters \(\boldsymbol{\beta}\) and their variance
+when we employ Ridge regression, allowing us again to define a confidence interval.
+
It is rather straightforward to show that
\[
-\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T
+\mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\boldsymbol{\beta}^{\mathrm{OLS}}.
\]
-
As an example, the above defective matrix can be decomposed as
-
-\[\begin{split}
-\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,
-\end{split}\]
-
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.
-
-
-
5.3. Economy-size SVD
-
If we assume that \(n > p\) , then our matrix \(\boldsymbol{U}\) has dimension \(n
-\times n\) . The last \(n-p\) columns of \(\boldsymbol{U}\) become however
-irrelevant in our calculations since they are multiplied with the
-zeros in \(\boldsymbol{\Sigma}\) .
-
The economy-size decomposition removes extra rows or columns of zeros
-from the diagonal matrix of singular values, \(\boldsymbol{\Sigma}\) , along with the columns
-in either \(\boldsymbol{U}\) or \(\boldsymbol{V}\) that multiply those zeros in the expression.
-Removing these zeros and columns can improve execution time
-and reduce storage requirements without compromising the accuracy of
-the decomposition.
-
If \(n > p\) , we keep only the first \(p\) columns of \(\boldsymbol{U}\) and \(\boldsymbol{\Sigma}\) has dimension \(p\times p\) .
-If \(p > n\) , then only the first \(n\) columns of \(\boldsymbol{V}\) are computed and \(\boldsymbol{\Sigma}\) has dimension \(n\times n\) .
-The \(n=p\) case is obvious, we retain the full SVD.
-In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.
-
-
-
-
[[ 1. -1. 2.]
- [ 1. 0. 1.]
- [ 1. 2. -1.]
- [ 1. 1. 0.]]
-[[ 4. 2. 2.]
- [ 2. 6. -4.]
- [ 2. -4. 6.]]
-[[-1.18404906e-16 8.16496581e-01 -5.77350269e-01]
- [-7.07106781e-01 4.08248290e-01 5.77350269e-01]
- [ 7.07106781e-01 4.08248290e-01 5.77350269e-01]]
-[1.00000000e+01 6.00000000e+00 9.10898112e-32]
-[[ 3.33066907e-17 -7.07106781e-01 7.07106781e-01]
- [ 8.16496581e-01 4.08248290e-01 4.08248290e-01]
- [ 5.77350269e-01 -5.77350269e-01 -5.77350269e-01]]
-[[-3.65939208e+30 3.65939208e+30 3.65939208e+30]
- [ 3.65939208e+30 -3.65939208e+30 -3.65939208e+30]
- [ 3.65939208e+30 -3.65939208e+30 -3.65939208e+30]]
-
-
-
-
-
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.
-
There are several interesting mathematical properties which will be
-relevant when we are going to discuss the differences between say
-ordinary least squares (OLS) and Ridge regression.
-
We have from OLS that the parameters of the linear approximation are given by
+
We see clearly that
+\(\mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big] \not= \boldsymbol{\beta}^{\mathrm{OLS}}\) for any \(\lambda > 0\) . We say then that the ridge estimator is biased.
+
We can also compute the variance as
\[
-\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
+\mbox{Var}[\boldsymbol{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T},
\]
-
The matrix to invert can be rewritten in terms of our SVD decomposition as
+
and it is easy to see that if the parameter \(\lambda\) goes to infinity then the variance of Ridge parameters \(\boldsymbol{\beta}\) goes to zero.
+
With this, we can compute the difference
\[
-\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T.
+\mbox{Var}[\boldsymbol{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\boldsymbol{\beta}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}.
\]
-
Using the orthogonality properties of \(\boldsymbol{U}\) we have
-
-\[
-\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T = \boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T,
-\]
-
with \(\boldsymbol{D}\) being a diagonal matrix with values along the diagonal given by the singular values squared.
-
This means that
-
-\[
-(\boldsymbol{X}^T\boldsymbol{X})\boldsymbol{V} = \boldsymbol{V}\boldsymbol{D},
-\]
-
that is the eigenvectors of \((\boldsymbol{X}^T\boldsymbol{X})\) are given by the columns of the right singular matrix of \(\boldsymbol{X}\) and the eigenvalues are the squared singular values. It is easy to show (show this) that
-
-\[
-(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D},
-\]
-
that is, the eigenvectors of \((\boldsymbol{X}\boldsymbol{X})^T\) are the columns of the left singular matrix and the eigenvalues are the same.
-
Going back to our OLS equation we have
-
-\[
-\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}.
-\]
-
We will come back to this expression when we discuss Ridge regression.
-
$\( \tilde{y}^{OLS}=\boldsymbol{X}\hat{\beta}^{OLS}=\sum_{j=1}^p \boldsymbol{u}_j\boldsymbol{u}_j^T\boldsymbol{y}\) $ and for Ridge we have
-
$\( \tilde{y}^{Ridge}=\boldsymbol{X}\hat{\beta}^{Ridge}=\sum_{j=1}^p \boldsymbol{u}_j\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{u}_j^T\boldsymbol{y}\) $ .
-
It is indeed the economy-sized SVD, note the summation runs up tp $\(p\) \( only and not \) \(n\) $.
-
Here we have that $\(\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T\) \(, with \) \(\Sigma\) \( being an \) \( n\times p\) \( matrix and \) \(\boldsymbol{V}\) \( being a \) \( p\times p\) \( matrix. We also have assumed here that \) \( n > p\) $.
+
The difference is non-negative definite since each component of the
+matrix product is non-negative definite.
+This means the variance we obtain with the standard OLS will always for \(\lambda > 0\) be larger than the variance of \(\boldsymbol{\beta}\) obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below.
-
5.4. Ridge and LASSO Regression
-
Video of Lecture
-
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
+
5.3. Resampling methods
+
With all these analytical equations for both the OLS and Ridge
+regression, we will now outline how to assess a given model. This will
+lead us to a discussion of the so-called bias-variance tradeoff (see
+below) and so-called resampling methods.
+
One of the quantities we have discussed as a way to measure errors is
+the mean-squared error (MSE), mainly used for fitting of continuous
+functions. Another choice is the absolute error.
+
In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,
+we discuss the
+
+prediction error or simply the test error \(\mathrm{Err_{Test}}\) , where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the
+training error \(\mathrm{Err_{Train}}\) , which is the average loss over the training data.
+
+
As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.
+For a certain level of complexity the test error will reach minimum, before starting to increase again. The
+training error reaches a saturation.
+
Two famous
+resampling methods are the independent bootstrap and the jackknife .
+
The jackknife is a special case of the independent bootstrap. Still, the jackknife was made
+popular prior to the independent bootstrap. And as the popularity of
+the independent bootstrap soared, new variants, such as the dependent bootstrap .
+
The Jackknife and independent bootstrap work for
+independent, identically distributed random variables.
+If these conditions are not
+satisfied, the methods will fail. Yet, it should be said that if the data are
+independent, identically distributed, and we only want to estimate the
+variance of \(\overline{X}\) (which often is the case), then there is no
+need for bootstrapping.
+
The Jackknife works by making many replicas of the estimator \(\widehat{\theta}\) .
+The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \(\boldsymbol{x} = (x_1,x_2,\cdots,X_n)\) .
+Let \(\boldsymbol{x}_i\) denote the vector
\[
-{\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}.
+\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n),
\]
-
or we can state it as
-
-\[
-{\displaystyle \min_{\boldsymbol{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2,
-\]
-
where we have used the definition of a norm-2 vector, that is
-
-\[
-\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.
-\]
-
By minimizing the above equation with respect to the parameters
-\(\boldsymbol{\beta}\) we could then obtain an analytical expression for the
-parameters \(\boldsymbol{\beta}\) . We can add a regularization parameter \(\lambda\) by
-defining a new cost function to be optimized, that is
-
-\[
-{\displaystyle \min_{\boldsymbol{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2
-\]
-
which leads to the Ridge regression minimization problem where we
-require that \(\vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t\) , where \(t\) is
-a finite number larger than zero. By defining
-
-\[
-C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1,
-\]
-
we have a new optimization equation
-
-\[
-{\displaystyle \min_{\boldsymbol{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1
-\]
-
which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.
-
Here we have defined the norm-1 as
-
-\[
-\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert.
-\]
-
Using the matrix-vector expression for Ridge regression,
-
-\[
-C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta},
-\]
-
by 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
-
-\[
-\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
-\]
-
with \(\boldsymbol{I}\) being a \(p\times p\) identity matrix with the constraint that
-
-\[
-\sum_{i=0}^{p-1} \beta_i^2 \leq t,
-\]
-
with \(t\) a finite positive number.
-
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.
-
Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had
-
-\[
-(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}.
-\]
-
We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \(\boldsymbol{U}\) as
-
-\[
-\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}
-\]
-
For Ridge regression this becomes
-
-\[
-\boldsymbol{X}\boldsymbol{\beta}^{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T+\lambda\boldsymbol{I} \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\sum_{j=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{y},
-\]
-
with the vectors \(\boldsymbol{u}_j\) being the columns of \(\boldsymbol{U}\) .
-
Since \(\lambda \geq 0\) , it means that compared to OLS, we have
-
-\[
-\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1.
-\]
-
Ridge regression finds the coordinates of \(\boldsymbol{y}\) with respect to the
-orthonormal basis \(\boldsymbol{U}\) , it then shrinks the coordinates by
-\(\frac{\sigma_j^2}{\sigma_j^2+\lambda}\) . Recall that the SVD has
-eigenvalues ordered in a descending way, that is \(\sigma_i \geq
-\sigma_{i+1}\) .
-
For small eigenvalues \(\sigma_i\) it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom.
-Actually, calculating the variance of \(\boldsymbol{X}\boldsymbol{v}_j\) shows that this quantity is equal to \(\sigma_j^2/n\) .
-With a parameter \(\lambda\) we can thus shrink the role of specific parameters.
-
For the sake of simplicity, let us assume that the design matrix is orthonormal, that is
-
-\[
-\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}.
-\]
-
In this case the standard OLS results in
-
-\[
-\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\boldsymbol{y},
-\]
-
and
-
-\[
-\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{I}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\left(1+\lambda\right)^{-1}\boldsymbol{\beta}^{\mathrm{OLS}},
-\]
-
that is the Ridge estimator scales the OLS estimator by the inverse of a factor \(1+\lambda\) , and
-the Ridge estimator converges to zero when the hyperparameter goes to
-infinity.
-
We will come back to more interpreations after we have gone through some of the statistical analysis part.
-
For more discussions of Ridge and Lasso regression, Wessel van Wieringen’s article is highly recommended.
-Similarly, Mehta et al’s article is also recommended.
-
-
-
5.5. A better understanding of regularization
-
The parameter \(\lambda\) that we have introduced in the Ridge (and
-Lasso as well) regression is often called a regularization parameter
-or shrinkage parameter. It is common to call it a hyperparameter. What does it mean mathemtically?
-
Here we will first look at how to analyze the difference between the
-standard OLS equations and the Ridge expressions in terms of a linear
-algebra analysis using the SVD algorithm. Thereafter, we will link
-(see the material on the bias-variance tradeoff below) these
-observation to the statisical analysis of the results. In particular
-we consider how the variance of the parameters \(\boldsymbol{\beta}\) is
-affected by changing the parameter \(\lambda\) .
-
We have our design matrix
-\(\boldsymbol{X}\in {\mathbb{R}}^{n\times p}\) . With the SVD we decompose it as
-
-\[
-\boldsymbol{X} = \boldsymbol{U\Sigma V^T},
-\]
-
with \(\boldsymbol{U}\in {\mathbb{R}}^{n\times n}\) , \(\boldsymbol{\Sigma}\in {\mathbb{R}}^{n\times p}\)
-and \(\boldsymbol{V}\in {\mathbb{R}}^{p\times p}\) .
-
The matrices \(\boldsymbol{U}\) and \(\boldsymbol{V}\) are unitary/orthonormal matrices, that is in case the matrices are real we have \(\boldsymbol{U}^T\boldsymbol{U}=\boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I}\) and \(\boldsymbol{V}^T\boldsymbol{V}=\boldsymbol{V}\boldsymbol{V}^T=\boldsymbol{I}\) .
-
-
-
5.6. Introducing the Covariance and Correlation functions
-
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
-
Suppose we have defined two vectors
-\(\hat{x}\) and \(\hat{y}\) with \(n\) elements each. The covariance matrix \(\boldsymbol{C}\) is defined as
-
-\[\begin{split}
-\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},
-\end{split}\]
-
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
-
-\[\begin{split}
-\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}.
-\end{split}\]
-
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
-
-\[
-\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
-
-\[\begin{split}
-\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\
- \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\
- \end{bmatrix},
-\end{split}\]
-
In the above example this is the function we constructed using pandas .
-
In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression
-we defined the design/feature matrix \(\boldsymbol{X}\) as
-
-\[\begin{split}
-\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},
-\end{split}\]
-
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},
-\]
-
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\)
-correaltion/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\)
-
-\[\begin{split}
-\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},
-\end{split}\]
-
and the correlation matrix
-
-\[\begin{split}
-\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},
-\end{split}\]
-
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}\)
-
-\[\begin{split}
-\boldsymbol{W} = \begin{bmatrix} x_0 & y_0 \\
- x_1 & y_1 \\
- x_2 & y_2\\
- \dots & \dots \\
- x_{n-2} & y_{n-2}\\
- x_{n-1} & y_{n-1} &
- \end{bmatrix},
-\end{split}\]
-
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.
+
which equals the vector \(\boldsymbol{x}\) with the exception that observation
+number \(i\) is left out. Using this notation, define
+\(\widehat{\theta}_i\) to be the estimator
+\(\widehat{\theta}\) computed using \(\vec{X}_i\) .
+
+
5.4. Various steps in cross-validation
+
When the repetitive splitting of the data set is done randomly,
+samples may accidently end up in a fast majority of the splits in
+either training or test set. Such samples may have an unbalanced
+influence on either model building or prediction evaluation. To avoid
+this \(k\) -fold cross-validation structures the data splitting. The
+samples are divided into \(k\) more or less equally sized exhaustive and
+mutually exclusive subsets. In turn (at each split) one of these
+subsets plays the role of the test set while the union of the
+remaining subsets constitutes the training set. Such a splitting
+warrants a balanced representation of each sample in both training and
+test set over the splits. Still the division into the \(k\) subsets
+involves a degree of randomness. This may be fully excluded when
+choosing \(k=n\) . This particular case is referred to as leave-one-out
+cross-validation (LOOCV).
+
+Define a range of interest for the penalty parameter.
+Divide the data set into training and test set comprising samples \(\{1, \ldots, n\} \setminus i\) and \(\{ i \}\) , respectively.
+Fit the linear regression model by means of ridge estimation for each \(\lambda\) in the grid using the training set, and the corresponding estimate of the error variance \(\boldsymbol{\sigma}_{-i}^2(\lambda)\) , as
+
+
+\[
+\begin{align*}
+\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T}
+\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1}
+\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i}
+\end{align*}
+\]
+
+Evaluate the prediction performance of these models on the test set by \(\log\{L[y_i, \boldsymbol{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}\) . Or, by the prediction error \(|y_i - \boldsymbol{X}_{i, \ast} \boldsymbol{\beta}_{-i}(\lambda)|\) , the relative error, the error squared or the R2 score function.
+Repeat the first three steps such that each sample plays the role of the test set once.
+Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as
+
+
+\[
+\begin{align*}
+\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}.
+\end{align*}
+\]
+
For the various values of \(k\)
+
+shuffle the dataset randomly.
+Split the dataset into \(k\) groups.
+For each unique group:
+
+
a. Decide which group to use as set for test data
+
b. Take the remaining groups as a training data set
+
c. Fit a model on the training set and evaluate it on the test set
+
d. Retain the evaluation score and discard the model
+
+Summarize the model using the sample of model evaluation scores
+
+
The code here uses Ridge regression with cross-validation (CV) resampling and \(k\) -fold CV in order to fit a specific polynomial.
+
+
+
+
5.5. The bias-variance tradeoff
+
We will discuss the bias-variance tradeoff in the context of
+continuous predictions such as regression. However, many of the
+intuitions and ideas discussed here also carry over to classification
+tasks. Consider a dataset \(\mathcal{L}\) consisting of the data
+\(\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}\) .
+
Let us assume that the true data is generated from a noisy model
+
+\[
+\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon}
+\]
+
where \(\epsilon\) is normally distributed with mean zero and standard deviation \(\sigma^2\) .
+
In our derivation of the ordinary least squares method we defined then
+an approximation to the function \(f\) in terms of the parameters
+\(\boldsymbol{\beta}\) and the design matrix \(\boldsymbol{X}\) which embody our model,
+that is \(\boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta}\) .
+
Thereafter we found the parameters \(\boldsymbol{\beta}\) by optimizing the means squared error via the so-called cost function
+
+\[
+C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right].
+\]
+
We can rewrite this as
+
+\[
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2.
+\]
+
The three terms represent the square of the bias of the learning
+method, which can be thought of as the error caused by the simplifying
+assumptions built into the method. The second term represents the
+variance of the chosen model and finally the last terms is variance of
+the error \(\boldsymbol{\epsilon}\) .
+
To derive this equation, we need to recall that the variance of \(\boldsymbol{y}\) and \(\boldsymbol{\epsilon}\) are both equal to \(\sigma^2\) . The mean value of \(\boldsymbol{\epsilon}\) is by definition equal to zero. Furthermore, the function \(f\) is not a stochastics variable, idem for \(\boldsymbol{\tilde{y}}\) .
+We use a more compact notation in terms of the expectation value
+
+\[
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right],
+\]
+
and adding and subtracting \(\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]\) we get
+
+\[
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right],
+\]
+
which, using the abovementioned expectation values can be rewritten as
+
+\[
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2,
+\]
+
that is the rewriting in terms of the so-called bias, the variance of the model \(\boldsymbol{\tilde{y}}\) and the variance of \(\boldsymbol{\epsilon}\) .
+
+
-
-
-0.008885578722629236
-3.7522047280566193
-[[0.8520127 2.59480085]
- [2.59480085 8.99218987]]
+from sklearn.linear_model import LinearRegression , Ridge , Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+
+np . random . seed ( 2018 )
+
+n = 500
+n_boostraps = 100
+degree = 18 # A quite high value, just to show.
+noise = 0.1
+
+# Make data set.
+x = np . linspace ( - 1 , 3 , n ) . reshape ( - 1 , 1 )
+y = np . exp ( - x ** 2 ) + 1.5 * np . exp ( - ( x - 2 ) ** 2 ) + np . random . normal ( 0 , 0.1 , x . shape )
+
+# Hold out some test data that is never used in training.
+x_train , x_test , y_train , y_test = train_test_split ( x , y , test_size = 0.2 )
+
+# Combine x transformation and model into one operation.
+# Not neccesary, but convenient.
+model = make_pipeline ( PolynomialFeatures ( degree = degree ), LinearRegression ( fit_intercept = False ))
+
+# The following (m x n_bootstraps) matrix holds the column vectors y_pred
+# for each bootstrap iteration.
+y_pred = np . empty (( y_test . shape [ 0 ], n_boostraps ))
+for i in range ( n_boostraps ):
+ x_ , y_ = resample ( x_train , y_train )
+
+ # Evaluate the new model on the same test data each time.
+ y_pred [:, i ] = model . fit ( x_ , y_ ) . predict ( x_test ) . ravel ()
+
+# Note: Expectations and variances taken w.r.t. different training
+# data sets, hence the axis=1. Subsequent means are taken across the test data
+# set in order to obtain a total value, but before this we have error/bias/variance
+# calculated per data point in the test set.
+# Note 2: The use of keepdims=True is important in the calculation of bias as this
+# maintains the column vector form. Dropping this yields very unexpected results.
+error = np . mean ( np . mean (( y_test - y_pred ) ** 2 , axis = 1 , keepdims = True ) )
+bias = np . mean ( ( y_test - np . mean ( y_pred , axis = 1 , keepdims = True )) ** 2 )
+variance = np . mean ( np . var ( y_pred , axis = 1 , keepdims = True ) )
+print ( 'Error:' , error )
+print ( 'Bias^2:' , bias )
+print ( 'Var:' , variance )
+print ( ' {} >= {} + {} = {} ' . format ( error , bias , variance , bias + variance ))
+
+plt . plot ( x [:: 5 , :], y [:: 5 , :], label = 'f(x)' )
+plt . scatter ( x_test , y_test , label = 'Data points' )
+plt . scatter ( x_test , np . mean ( y_pred , axis = 1 ), label = 'Pred' )
+plt . legend ()
+plt . show ()
-
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).
-
-
0.06619182206626131
-2.1914224774238273
-[[1. 0.70589906]
- [0.70589906 1. ]]
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.linear_model import LinearRegression , Ridge , Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+
+np . random . seed ( 2018 )
+
+n = 40
+n_boostraps = 100
+maxdegree = 14
+
+
+# Make data set.
+x = np . linspace ( - 3 , 3 , n ) . reshape ( - 1 , 1 )
+y = np . exp ( - x ** 2 ) + 1.5 * np . exp ( - ( x - 2 ) ** 2 ) + np . random . normal ( 0 , 0.1 , x . shape )
+error = np . zeros ( maxdegree )
+bias = np . zeros ( maxdegree )
+variance = np . zeros ( maxdegree )
+polydegree = np . zeros ( maxdegree )
+x_train , x_test , y_train , y_test = train_test_split ( x , y , test_size = 0.2 )
+
+for degree in range ( maxdegree ):
+ model = make_pipeline ( PolynomialFeatures ( degree = degree ), LinearRegression ( fit_intercept = False ))
+ y_pred = np . empty (( y_test . shape [ 0 ], n_boostraps ))
+ for i in range ( n_boostraps ):
+ x_ , y_ = resample ( x_train , y_train )
+ y_pred [:, i ] = model . fit ( x_ , y_ ) . predict ( x_test ) . ravel ()
+
+ polydegree [ degree ] = degree
+ error [ degree ] = np . mean ( np . mean (( y_test - y_pred ) ** 2 , axis = 1 , keepdims = True ) )
+ bias [ degree ] = np . mean ( ( y_test - np . mean ( y_pred , axis = 1 , keepdims = True )) ** 2 )
+ variance [ degree ] = np . mean ( np . var ( y_pred , axis = 1 , keepdims = True ) )
+ print ( 'Polynomial degree:' , degree )
+ print ( 'Error:' , error [ degree ])
+ print ( 'Bias^2:' , bias [ degree ])
+ print ( 'Var:' , variance [ degree ])
+ print ( ' {} >= {} + {} = {} ' . format ( error [ degree ], bias [ degree ], variance [ degree ], bias [ degree ] + variance [ degree ]))
+
+plt . plot ( polydegree , error , label = 'Error' )
+plt . plot ( polydegree , bias , label = 'bias' )
+plt . plot ( polydegree , variance , label = 'Variance' )
+plt . legend ()
+plt . show ()
-
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.
-
The above procedure with numpy can be made more compact if we use pandas .
-
We whow here how we can set up the correlation matrix using pandas , as done in this simple code
+
The bias-variance tradeoff summarizes the fundamental tension in
+machine learning, particularly supervised learning, between the
+complexity of a model and the amount of training data needed to train
+it. Since data is often limited, in practice it is often useful to
+use a less-complex model with higher bias, that is a model whose asymptotic
+performance is worse than another model because it is easier to
+train and less sensitive to sampling noise arising from having a
+finite-sized training dataset (smaller variance).
+
The above equations tell us that in
+order to minimize the expected test error, we need to select a
+statistical learning method that simultaneously achieves low variance
+and low bias. Note that variance is inherently a nonnegative quantity,
+and squared bias is also nonnegative. Hence, we see that the expected
+test MSE can never lie below \(Var(\epsilon)\) , the irreducible error.
+
What do we mean by the variance and bias of a statistical learning
+method? The variance refers to the amount by which our model would change if we
+estimated it using a different training data set. Since the training
+data are used to fit the statistical learning method, different
+training data sets will result in a different estimate. But ideally the
+estimate for our model should not vary too much between training
+sets. However, if a method has high variance then small changes in
+the training data can result in large changes in the model. In general, more
+flexible statistical methods have higher variance.
+
You may also find this recent article of interest.
-
-
[[ 0.03067028 0.91697817]
- [-0.10806972 -2.26381865]
- [ 0.69519693 3.02968834]
- [-0.07521771 -0.93273404]
- [-0.25910749 -0.58239999]
- [ 0.25450941 0.36941772]
- [-1.65002433 -6.09672604]
- [ 0.58596975 2.19955871]
- [ 0.54121682 2.30685416]
- [-0.01514394 1.05318162]]
- 0 1
-0 0.030670 0.916978
-1 -0.108070 -2.263819
-2 0.695197 3.029688
-3 -0.075218 -0.932734
-4 -0.259107 -0.582400
-5 0.254509 0.369418
-6 -1.650024 -6.096726
-7 0.585970 2.199559
-8 0.541217 2.306854
-9 -0.015144 1.053182
- 0 1
-0 1.000000 0.948729
-1 0.948729 1.000000
+"""
+============================
+Underfitting vs. Overfitting
+============================
+
+This example demonstrates the problems of underfitting and overfitting and
+how we can use linear regression with polynomial features to approximate
+nonlinear functions. The plot shows the function that we want to approximate,
+which is a part of the cosine function. In addition, the samples from the
+real function and the approximations of different models are displayed. The
+models have polynomial features of different degrees. We can see that a
+linear function (polynomial with degree 1) is not sufficient to fit the
+training samples. This is called **underfitting**. A polynomial of degree 4
+approximates the true function almost perfectly. However, for higher degrees
+the model will **overfit** the training data, i.e. it learns the noise of the
+training data.
+We evaluate quantitatively **overfitting** / **underfitting** by using
+cross-validation. We calculate the mean squared error (MSE) on the validation
+set, the higher, the less likely the model generalizes correctly from the
+training data.
+"""
+
+print ( __doc__ )
+
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.linear_model import LinearRegression
+from sklearn.model_selection import cross_val_score
+
+
+def true_fun ( X ):
+ return np . cos ( 1.5 * np . pi * X )
+
+np . random . seed ( 0 )
+
+n_samples = 30
+degrees = [ 1 , 4 , 15 ]
+
+X = np . sort ( np . random . rand ( n_samples ))
+y = true_fun ( X ) + np . random . randn ( n_samples ) * 0.1
+
+plt . figure ( figsize = ( 14 , 5 ))
+for i in range ( len ( degrees )):
+ ax = plt . subplot ( 1 , len ( degrees ), i + 1 )
+ plt . setp ( ax , xticks = (), yticks = ())
+
+ polynomial_features = PolynomialFeatures ( degree = degrees [ i ],
+ include_bias = False )
+ linear_regression = LinearRegression ()
+ pipeline = Pipeline ([( "polynomial_features" , polynomial_features ),
+ ( "linear_regression" , linear_regression )])
+ pipeline . fit ( X [:, np . newaxis ], y )
+
+ # Evaluate the models using crossvalidation
+ scores = cross_val_score ( pipeline , X [:, np . newaxis ], y ,
+ scoring = "neg_mean_squared_error" , cv = 10 )
+
+ X_test = np . linspace ( 0 , 1 , 100 )
+ plt . plot ( X_test , pipeline . predict ( X_test [:, np . newaxis ]), label = "Model" )
+ plt . plot ( X_test , true_fun ( X_test ), label = "True function" )
+ plt . scatter ( X , y , edgecolor = 'b' , s = 20 , label = "Samples" )
+ plt . xlabel ( "x" )
+ plt . ylabel ( "y" )
+ plt . xlim (( 0 , 1 ))
+ plt . ylim (( - 2 , 2 ))
+ plt . legend ( loc = "best" )
+ plt . title ( "Degree {} \n MSE = {:.2e} (+/- {:.2e} )" . format (
+ degrees [ i ], - scores . mean (), scores . std ()))
+plt . show ()
-
We expand this model to the Franke function discussed above.
-
-
0 1 2 3 4 5 6 7 \
-0 0.0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
-1 0.0 0.082990 0.084167 0.081514 0.081402 0.081260 0.071681 0.071684
-2 0.0 0.084167 0.086116 0.083128 0.083376 0.083577 0.073602 0.073851
-3 0.0 0.081514 0.083128 0.084873 0.085285 0.085676 0.077469 0.077891
-4 0.0 0.081402 0.083376 0.085285 0.085951 0.086592 0.078311 0.078930
-5 0.0 0.081260 0.083577 0.085676 0.086592 0.087482 0.079139 0.079956
-6 0.0 0.071681 0.073602 0.077469 0.078311 0.079139 0.072620 0.073372
-7 0.0 0.071684 0.073851 0.077891 0.078930 0.079956 0.073372 0.074286
-8 0.0 0.071761 0.074170 0.078388 0.079624 0.080845 0.074191 0.075266
-9 0.0 0.071917 0.074568 0.078966 0.080398 0.081816 0.075084 0.076320
-10 0.0 0.062188 0.064304 0.069005 0.070131 0.071248 0.065994 0.066963
-11 0.0 0.062376 0.064686 0.069528 0.070815 0.072094 0.066761 0.067865
-12 0.0 0.062639 0.065144 0.070129 0.071579 0.073020 0.067601 0.068840
-13 0.0 0.062979 0.065680 0.070812 0.072424 0.074027 0.068514 0.069890
-14 0.0 0.063395 0.066294 0.071576 0.073352 0.075119 0.069503 0.071016
+trials = 100
+for polydegree in range ( 1 , Maxpolydegree ):
+ polynomial [ polydegree ] = polydegree
+ for degree in range ( polydegree ):
+ X [:, degree ] = Density ** ( degree / 3.0 )
- 8 9 10 11 12 13 14
-0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
-1 0.071761 0.071917 0.062188 0.062376 0.062639 0.062979 0.063395
-2 0.074170 0.074568 0.064304 0.064686 0.065144 0.065680 0.066294
-3 0.078388 0.078966 0.069005 0.069528 0.070129 0.070812 0.071576
-4 0.079624 0.080398 0.070131 0.070815 0.071579 0.072424 0.073352
-5 0.080845 0.081816 0.071248 0.072094 0.073020 0.074027 0.075119
-6 0.074191 0.075084 0.065994 0.066761 0.067601 0.068514 0.069503
-7 0.075266 0.076320 0.066963 0.067865 0.068840 0.069890 0.071016
-8 0.076408 0.077623 0.067990 0.069028 0.070138 0.071325 0.072589
-9 0.077623 0.079001 0.069081 0.070254 0.071502 0.072826 0.074230
-10 0.067990 0.069081 0.060919 0.061842 0.062829 0.063882 0.065003
-11 0.069028 0.070254 0.061842 0.062879 0.063982 0.065151 0.066389
-12 0.070138 0.071502 0.062829 0.063982 0.065200 0.066487 0.067844
-13 0.071325 0.072826 0.063882 0.065151 0.066487 0.067892 0.069369
-14 0.072589 0.074230 0.065003 0.066389 0.067844 0.069369 0.070967
+# loop over trials in order to estimate the expectation value of the MSE
+ testerror [ polydegree ] = 0.0
+ trainingerror [ polydegree ] = 0.0
+ for samples in range ( trials ):
+ x_train , x_test , y_train , y_test = train_test_split ( X , Energies , test_size = 0.2 )
+ model = LinearRegression ( fit_intercept = True ) . fit ( x_train , y_train )
+ ypred = model . predict ( x_train )
+ ytilde = model . predict ( x_test )
+ testerror [ polydegree ] += mean_squared_error ( y_test , ytilde )
+ trainingerror [ polydegree ] += mean_squared_error ( y_train , ypred )
+
+ testerror [ polydegree ] /= trials
+ trainingerror [ polydegree ] /= trials
+ print ( "Degree of polynomial: %3d " % polynomial [ polydegree ])
+ print ( "Mean squared error on training data: %.8f " % trainingerror [ polydegree ])
+ print ( "Mean squared error on test data: %.8f " % testerror [ polydegree ])
+
+plt . plot ( polynomial , np . log10 ( trainingerror ), label = 'Training Error' )
+plt . plot ( polynomial , np . log10 ( testerror ), label = 'Test Error' )
+plt . xlabel ( 'Polynomial degree' )
+plt . ylabel ( 'log10[MSE]' )
+plt . legend ()
+plt . show ()
-
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.
-
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}].
-\]
-
To see this let us simply look at a design matrix \(\boldsymbol{X}\in {\mathbb{R}}^{2\times 2}\)
-
-\[\begin{split}
-\boldsymbol{X}=\begin{bmatrix}
-x_{00} & x_{01}\\
-x_{10} & x_{11}\\
-\end{bmatrix}=\begin{bmatrix}
-\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\
-\end{bmatrix}.
-\end{split}\]
-
If we then compute the expectation value
-
-\[\begin{split}
-\mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}=\begin{bmatrix}
-x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\
-x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\
-\end{bmatrix},
-\end{split}\]
-
which is just
-
-\[\begin{split}
-\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},
-\end{split}\]
-
where we wrote $\(\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]\) \( to indicate that this 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}\) .
+
+
-
-
5.7. Linking with SVD
@@ -1139,7 +1407,7 @@ x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\
diff --git a/doc/LectureNotes/_build/html/genindex.html b/doc/LectureNotes/_build/html/genindex.html
index 31ddb0301..5097ffe24 100644
--- a/doc/LectureNotes/_build/html/genindex.html
+++ b/doc/LectureNotes/_build/html/genindex.html
@@ -142,12 +142,12 @@
- 4. Resampling Methods
+ 4. Ridge and Lasso Regression
- 5. Ridge and Lasso Regression
+ 5. Resampling Methods
diff --git a/doc/LectureNotes/_build/html/intro.html b/doc/LectureNotes/_build/html/intro.html
index ad0b53b89..33d4d30f2 100644
--- a/doc/LectureNotes/_build/html/intro.html
+++ b/doc/LectureNotes/_build/html/intro.html
@@ -143,12 +143,12 @@
- 4. Resampling Methods
+ 4. Ridge and Lasso Regression
- 5. Ridge and Lasso Regression
+ 5. Resampling Methods
diff --git a/doc/LectureNotes/_build/html/objects.inv b/doc/LectureNotes/_build/html/objects.inv
index c8ab047da..f8542ef28 100644
Binary files a/doc/LectureNotes/_build/html/objects.inv and b/doc/LectureNotes/_build/html/objects.inv differ
diff --git a/doc/LectureNotes/_build/html/reports/chapter2.log b/doc/LectureNotes/_build/html/reports/chapter2.log
index 825b97e1f..c33dc36fd 100644
--- a/doc/LectureNotes/_build/html/reports/chapter2.log
+++ b/doc/LectureNotes/_build/html/reports/chapter2.log
@@ -17,88 +17,21 @@ Traceback (most recent call last):
raise CellExecutionError.from_cell_and_msg(cell, exec_reply['content'])
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
-%matplotlib inline
-
-from numpy import *
-from numpy.random import randint, randn
-from time import time
-import matplotlib.mlab as mlab
-import matplotlib.pyplot as plt
-
-# Returns mean of bootstrap samples
-def stat(data):
- return mean(data)
-
-# Bootstrap algorithm
-def bootstrap(data, statistic, R):
- t = zeros(R); n = len(data); inds = arange(n); t0 = time()
- # non-parametric bootstrap
- for i in range(R):
- t[i] = statistic(data[randint(0,n,n)])
-
- # analysis
- print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
- print("original bias std. error")
- print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
- return t
-
-
-mu, sigma = 100, 15
-datapoints = 10000
-x = mu + sigma*random.randn(datapoints)
-# bootstrap returns the data sample
-t = bootstrap(x, stat, datapoints)
-# the histogram of the bootstrapped data
-n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
-
-# add a 'best fit' line
-y = mlab.normpdf( binsboot, mean(t), std(t))
-lt = plt.plot(binsboot, y, 'r--', linewidth=1)
-plt.xlabel('Smarts')
-plt.ylabel('Probability')
-plt.axis([99.5, 100.6, 0, 3.0])
-plt.grid(True)
-
-plt.show()
+Ainv = np.linlag.pinv(A)
------------------
[0;31m---------------------------------------------------------------------------[0m
[0;31mAttributeError[0m Traceback (most recent call last)
-[0;32m[0m in [0;36m[0;34m[0m
-[1;32m 31[0m [0mt[0m [0;34m=[0m [0mbootstrap[0m[0;34m([0m[0mx[0m[0;34m,[0m [0mstat[0m[0;34m,[0m [0mdatapoints[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m
-[1;32m 32[0m [0;31m# the histogram of the bootstrapped data[0m[0;34m[0m[0;34m[0m[0;34m[0m[0m
-[0;32m---> 33[0;31m [0mn[0m[0;34m,[0m [0mbinsboot[0m[0;34m,[0m [0mpatches[0m [0;34m=[0m [0mplt[0m[0;34m.[0m[0mhist[0m[0;34m([0m[0mt[0m[0;34m,[0m [0;36m50[0m[0;34m,[0m [0mnormed[0m[0;34m=[0m[0;36m1[0m[0;34m,[0m [0mfacecolor[0m[0;34m=[0m[0;34m'red'[0m[0;34m,[0m [0malpha[0m[0;34m=[0m[0;36m0.75[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m
-[0m[1;32m 34[0m [0;34m[0m[0m
-[1;32m 35[0m [0;31m# add a 'best fit' line[0m[0;34m[0m[0;34m[0m[0;34m[0m[0m
+[0;32m[0m in [0;36m[0;34m[0m
+[0;32m----> 1[0;31m [0mAinv[0m [0;34m=[0m [0mnp[0m[0;34m.[0m[0mlinlag[0m[0;34m.[0m[0mpinv[0m[0;34m([0m[0mA[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m
+[0m
+[0;32m~/opt/anaconda3/lib/python3.8/site-packages/numpy/__init__.py[0m in [0;36m__getattr__[0;34m(attr)[0m
+[1;32m 212[0m [0;32mreturn[0m [0mTester[0m[0;34m[0m[0;34m[0m[0m
+[1;32m 213[0m [0;32melse[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m
+[0;32m--> 214[0;31m raise AttributeError("module {!r} has no attribute "
+[0m[1;32m 215[0m "{!r}".format(__name__, attr))
+[1;32m 216[0m [0;34m[0m[0m
-[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/pyplot.py[0m in [0;36mhist[0;34m(x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, data, **kwargs)[0m
-[1;32m 2683[0m [0morientation[0m[0;34m=[0m[0;34m'vertical'[0m[0;34m,[0m [0mrwidth[0m[0;34m=[0m[0;32mNone[0m[0;34m,[0m [0mlog[0m[0;34m=[0m[0;32mFalse[0m[0;34m,[0m [0mcolor[0m[0;34m=[0m[0;32mNone[0m[0;34m,[0m[0;34m[0m[0;34m[0m[0m
-[1;32m 2684[0m label=None, stacked=False, *, data=None, **kwargs):
-[0;32m-> 2685[0;31m return gca().hist(
-[0m[1;32m 2686[0m [0mx[0m[0;34m,[0m [0mbins[0m[0;34m=[0m[0mbins[0m[0;34m,[0m [0mrange[0m[0;34m=[0m[0mrange[0m[0;34m,[0m [0mdensity[0m[0;34m=[0m[0mdensity[0m[0;34m,[0m [0mweights[0m[0;34m=[0m[0mweights[0m[0;34m,[0m[0;34m[0m[0;34m[0m[0m
-[1;32m 2687[0m [0mcumulative[0m[0;34m=[0m[0mcumulative[0m[0;34m,[0m [0mbottom[0m[0;34m=[0m[0mbottom[0m[0;34m,[0m [0mhisttype[0m[0;34m=[0m[0mhisttype[0m[0;34m,[0m[0;34m[0m[0;34m[0m[0m
-
-[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/__init__.py[0m in [0;36minner[0;34m(ax, data, *args, **kwargs)[0m
-[1;32m 1445[0m [0;32mdef[0m [0minner[0m[0;34m([0m[0max[0m[0;34m,[0m [0;34m*[0m[0margs[0m[0;34m,[0m [0mdata[0m[0;34m=[0m[0;32mNone[0m[0;34m,[0m [0;34m**[0m[0mkwargs[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m
-[1;32m 1446[0m [0;32mif[0m [0mdata[0m [0;32mis[0m [0;32mNone[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m
-[0;32m-> 1447[0;31m [0;32mreturn[0m [0mfunc[0m[0;34m([0m[0max[0m[0;34m,[0m [0;34m*[0m[0mmap[0m[0;34m([0m[0msanitize_sequence[0m[0;34m,[0m [0margs[0m[0;34m)[0m[0;34m,[0m [0;34m**[0m[0mkwargs[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m
-[0m[1;32m 1448[0m [0;34m[0m[0m
-[1;32m 1449[0m [0mbound[0m [0;34m=[0m [0mnew_sig[0m[0;34m.[0m[0mbind[0m[0;34m([0m[0max[0m[0;34m,[0m [0;34m*[0m[0margs[0m[0;34m,[0m [0;34m**[0m[0mkwargs[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m
-
-[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/axes/_axes.py[0m in [0;36mhist[0;34m(self, x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs)[0m
-[1;32m 6813[0m [0;32mif[0m [0mpatch[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m
-[1;32m 6814[0m [0mp[0m [0;34m=[0m [0mpatch[0m[0;34m[[0m[0;36m0[0m[0;34m][0m[0;34m[0m[0;34m[0m[0m
-[0;32m-> 6815[0;31m [0mp[0m[0;34m.[0m[0mupdate[0m[0;34m([0m[0mkwargs[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m
-[0m[1;32m 6816[0m [0;32mif[0m [0mlbl[0m [0;32mis[0m [0;32mnot[0m [0;32mNone[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m
-[1;32m 6817[0m [0mp[0m[0;34m.[0m[0mset_label[0m[0;34m([0m[0mlbl[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m
-
-[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/artist.py[0m in [0;36mupdate[0;34m(self, props)[0m
-[1;32m 994[0m [0mfunc[0m [0;34m=[0m [0mgetattr[0m[0;34m([0m[0mself[0m[0;34m,[0m [0;34mf"set_{k}"[0m[0;34m,[0m [0;32mNone[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m
-[1;32m 995[0m [0;32mif[0m [0;32mnot[0m [0mcallable[0m[0;34m([0m[0mfunc[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m
-[0;32m--> 996[0;31m raise AttributeError(f"{type(self).__name__!r} object "
-[0m[1;32m 997[0m f"has no property {k!r}")
-[1;32m 998[0m [0mret[0m[0;34m.[0m[0mappend[0m[0;34m([0m[0mfunc[0m[0;34m([0m[0mv[0m[0;34m)[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m
-
-[0;31mAttributeError[0m: 'Rectangle' object has no property 'normed'
-AttributeError: 'Rectangle' object has no property 'normed'
+[0;31mAttributeError[0m: module 'numpy' has no attribute 'linlag'
+AttributeError: module 'numpy' has no attribute 'linlag'
diff --git a/doc/LectureNotes/_build/html/search.html b/doc/LectureNotes/_build/html/search.html
index 73555f09a..1ff418ad7 100644
--- a/doc/LectureNotes/_build/html/search.html
+++ b/doc/LectureNotes/_build/html/search.html
@@ -147,12 +147,12 @@
- 4. Resampling Methods
+ 4. Ridge and Lasso Regression
- 5. Ridge and Lasso Regression
+ 5. Resampling Methods
diff --git a/doc/LectureNotes/_build/html/searchindex.js b/doc/LectureNotes/_build/html/searchindex.js
index 4d84307b6..9f0d08469 100644
--- a/doc/LectureNotes/_build/html/searchindex.js
+++ b/doc/LectureNotes/_build/html/searchindex.js
@@ -1 +1 @@
-Search.setIndex({docnames:["Clustering","chapter1","chapter10","chapter2","chapter3","chapter4","chapter5","chapter6","chapter7","chapter8","chapter9","content","intro","linalg","schedule","statistics","teachers","textbooks"],envversion:{"sphinx.domains.c":2,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":3,"sphinx.domains.index":1,"sphinx.domains.javascript":2,"sphinx.domains.math":2,"sphinx.domains.python":2,"sphinx.domains.rst":2,"sphinx.domains.std":1,"sphinx.ext.intersphinx":1,sphinx:56},filenames:["Clustering.ipynb","chapter1.ipynb","chapter10.ipynb","chapter2.ipynb","chapter3.ipynb","chapter4.ipynb","chapter5.ipynb","chapter6.ipynb","chapter7.ipynb","chapter8.ipynb","chapter9.ipynb","content.md","intro.md","linalg.ipynb","schedule.md","statistics.ipynb","teachers.md","textbooks.md"],objects:{},objnames:{},objtypes:{},terms:{"000":2,"000000":[1,4,9],"00000000e":[1,4],"0001":2,"00015921913736794912":7,"001":[2,5,6],"00109273":[],"00200":6,"0032873138755776365":15,"003704":1,"003717":1,"003759":1,"003774":1,"003788":1,"00433417":9,"004456043243408203":0,"00445655":9,"0049999999999999845":[],"004999999999999996":[],"004999999999999997":[],"0050000000000000044":[],"005000000000000007":1,"00727646693":1,"007789":[],"007824":1,"0086649156":1,"008885578722629236":4,"009154":1,"009735":9,"00973536":9,"009790":1,"009883615646716182":1,"009883615646716184":[],"009883615646716186":[],"009911":1,"01057384067458835":[],"010679893512872646":[],"0110":15,"011347":1,"0140617":[],"01514394":4,"015144":4,"01867234e":15,"01873344":9,"02161783e":15,"021901":9,"02190139":9,"02493044e":[],"02568378":[],"025709":9,"02625193":6,"02730126581656065":15,"02881304":[],"029688":4,"02968834":4,"030670":4,"03067028":4,"03256632e":2,"03303359":[],"03607832":[],"03697069":[],"03707133":9,"03750367":13,"03787596148305236":1,"03791824e":15,"038300":9,"03871832":[],"04205220e":15,"04260073e":[],"04330858":[],"04421672e":[],"044402":1,"0458":7,"04757618e":[],"04829457939163212":15,"051649":9,"05318162":4,"053182":4,"05364854":6,"05396545e":[],"056329":9,"057088709963637":1,"05755374":[],"059344":9,"060064":9,"060070":9,"06041458e":[],"060919":4,"06126507e":15,"061601":9,"061842":4,"06209126":[],"062188":4,"062376":4,"062639":4,"062660":9,"062829":4,"062879":4,"062923":9,"062979":4,"063178":9,"063324":9,"063395":4,"063882":4,"063982":4,"06412177e":15,"064304":4,"064648":9,"064686":4,"064783":9,"06492086e":1,"065003":4,"065110":9,"065144":4,"065151":4,"065200":4,"065680":4,"065860":9,"065994":4,"066002":9,"06600226":9,"066030":9,"066074":9,"06619182206626131":4,"066294":4,"066312":9,"066389":4,"066403":9,"066487":4,"066683":9,"066761":4,"066837":9,"066951":9,"066963":4,"067132":9,"067175":9,"067440":9,"067601":4,"067667":9,"067685":9,"067844":4,"067865":4,"067892":4,"067990":4,"068351":9,"068514":4,"068697":9,"068818":9,"068838":9,"068840":4,"069005":4,"069028":4,"069081":4,"069195":9,"069243":9,"069369":4,"069413":9,"069503":4,"069528":4,"069641":9,"069775":9,"069890":4,"069988":9,"070129":4,"070131":4,"070138":4,"070254":4,"070337":9,"070548":9,"070762":9,"070791":9,"070812":4,"070815":4,"070867":9,"070889":9,"070967":4,"071016":4,"071049":9,"07106781e":4,"07110274":13,"071248":4,"0713":1,"071325":4,"071435":9,"07145103":9,"071502":4,"071547":9,"07155335":[],"071576":4,"071579":4,"07159175":[],"071660":9,"071681":4,"071684":4,"071761":4,"071917":4,"072094":4,"072424":4,"072555":9,"072589":4,"072620":4,"072654":9,"072710":9,"072826":4,"072879":9,"073":3,"073020":4,"073096":9,"073310":9,"073352":4,"073371":9,"073372":4,"073598":9,"073602":4,"073656":9,"073765":9,"073851":4,"073915":1,"074":3,"074027":4,"074067":9,"074170":4,"074191":4,"074201":9,"074230":4,"074286":4,"074331":9,"074568":4,"074618":9,"074979":9,"075084":4,"075119":4,"075194":9,"07521771":4,"075218":4,"075266":4,"075296":9,"075526":9,"075545":9,"0755452":9,"075615":9,"075993":9,"076320":4,"076367":9,"076408":4,"076410":9,"076466":9,"076938":9,"077010":9,"077046":9,"077143":9,"07729012413236423":9,"077305":9,"07744472306026946":7,"077469":4,"077623":4,"077771":9,"07777777777777778":2,"077891":4,"077927":9,"078099":9,"078103":9,"078244":9,"078311":4,"078388":4,"078693":9,"078710":9,"078746":9,"078930":4,"078966":4,"079001":4,"079139":4,"07944154":13,"079624":4,"079785":9,"079848":9,"079956":4,"080024":9,"080084":1,"080264":9,"080325":9,"080398":4,"080570":9,"080626":9,"080675":9,"080845":4,"081077":9,"081129":9,"081210":9,"081260":4,"081402":4,"081489":9,"081514":4,"08170444":[],"081816":4,"082211":9,"082225":9,"082247":9,"08248290e":4,"08251898":15,"08271336":[],"082990":4,"083128":4,"08318298e":2,"0832":[],"083295":9,"083376":4,"083577":4,"083658":9,"08415761":[],"084167":4,"084249":9,"084604":9,"084813":9,"084873":4,"08501147":1,"085121":9,"085285":4,"085646":9,"085676":4,"085951":4,"08611111111111111":2,"086116":4,"086592":4,"086652":9,"086974":9,"087202":9,"087482":4,"087563":9,"08839750e":1,"088871":1,"08888888888888889":2,"089425":9,"090274":9,"09103481e":15,"09166666666666666":2,"0917":7,"093755":9,"09487315108590391":9,"096726":4,"09672604":4,"09678277e":15,"09741585e":[],"09903804":6,"100":[0,1,2,3,4,5,6,7,8,9,13,15,16],"1000":[0,1,2,5,6,9,12,15],"10000":[0,3,8,9,15],"100000":6,"10001":8,"1001":15,"1002":15,"1003":15,"1005":15,"1007125":1,"1009":15,"10094646e":[],"1011":15,"1013":15,"10131725":[],"1013904243":15,"1015":15,"102":1,"1022964509394572":2,"1023":15,"1026":15,"1027":15,"103":2,"1030":15,"10307631":[],"10327559":13,"1037":15,"10378326e":2,"1038":15,"1040":15,"10405456":9,"1047":15,"105137868830763":15,"10555555555555556":2,"106095":9,"108":1,"10806972":4,"108070":4,"10896672e":15,"10898112e":4,"10th":7,"10x":1,"110":1,"1100":15,"1101":15,"111":[2,5,10],"1111111111111111":2,"112283":1,"112383":9,"11304709e":15,"11388888888888889":2,"11456076e":[],"11507992e":2,"11666666666666667":2,"117":6,"11944444444444445":2,"12002944":[],"1203284":6,"121":[6,7,8],"122":[6,7,8],"12222222222222222":2,"12283463":[],"123190":1,"123459876":15,"12366979e":15,"124":1,"12497018e":1,"127773":15,"12777777777777777":2,"1298":7,"13055555555555556":2,"13060772":1,"13209041":[],"13266452e":1,"133":5,"13328820e":[],"13457922":[],"13519106":1,"13579199e":[],"1361111111111111":2,"137268":[],"137400784702912":1,"137652":9,"13803928":1,"138775":9,"139475":3,"1404":1,"1437":2,"1440501043841336":2,"1445":3,"14459063":[],"1446":3,"1447":3,"1448":3,"1449":3,"14662074":1,"14722222222222223":2,"147400":9,"147420":9,"149366":[],"149667":3,"149903":3,"14g":3,"150":6,"15024669":[],"152636":[],"1527777777777778":2,"153106":1,"15324631":1,"15332528e":[],"154720":1,"15475232":1,"154911":1,"155491":1,"155687":1,"155883":1,"156":1,"157":1,"158":1,"159":1,"15979239e":15,"15g":3,"160":1,"16111111111111112":2,"16496581e":4,"16553696":[],"16637855e":15,"16666666666666666":2,"16807":15,"16b8e3cda33a":2,"17117385":[],"17174962e":2,"17234827e":[],"17385778e":1,"1758506":1,"17654307":[],"17707436":[],"17777777777777778":2,"17953942":9,"1797":2,"180092462880674":[],"18220995":1,"18333333333333332":2,"18404906e":4,"1856411":[],"18611111111111112":2,"18620601e":1,"18673098":9,"18954529":[],"18968431e":15,"1914224774238273":4,"1940":1,"1943":10,"197":1,"1970":13,"1973":7,"197370":9,"19742904e":[],"1979":3,"1989":15,"19937":15,"19955871":4,"199559":4,"19972087e":15,"1_1":10,"1_2":10,"1_3":10,"1cm":[1,6,8,15],"1e10":0,"200":[1,6,7,8,15],"200000":1,"2004":5,"2006":17,"2010":2,"2011":2,"2015":2,"2016":1,"2018":3,"2021":0,"20277777777777778":2,"205466494327873":[],"207545":9,"20772452":[],"20819609e":[],"20833333333333334":2,"20843563e":[],"20906175e":15,"210340":9,"21208310e":[],"212327334149492":1,"2125":[],"2126":[],"2127":[],"2128":[],"2129":[],"213103":9,"21347282":[],"213743":9,"2147483647":15,"21623344":1,"216290":9,"216683":9,"22076362":1,"221":6,"22209371e":1,"22527008e":15,"22717936e":15,"23117916e":15,"23333333333333334":2,"2335879":[],"23382086e":[],"23438810e":1,"24444444444444444":2,"250":[5,7],"25000":1,"250000":1,"250154":1,"25190225e":1,"25226753e":15,"25240108":[],"253":[],"25303483":[],"253775":1,"254":[],"254509":4,"25450941":4,"25457052":[],"255":[],"2551":1,"256":[],"256962":1,"257":[],"25726439e":[],"2572e3a4b38d":2,"25803281":[],"259107":4,"25910749":4,"259153":9,"2627588":13,"26381865":4,"263819":4,"264":1,"265":1,"2653678":1,"266":1,"267":1,"2683":3,"2684":3,"2685":3,"2686":3,"2687":3,"26890510e":[],"269":1,"26974938e":[],"270":1,"27296891e":[],"276263":9,"27753165e":15,"27n_":15,"280647":9,"28166741":[],"282":1,"282727":9,"2836":15,"28475098":6,"2861":15,"2873":7,"2882":15,"2886":15,"2890":1,"2892":15,"28971976":9,"289720":9,"290":[],"291":[],"2915":15,"291614":[],"292":[],"293":[],"2931":[],"294":[],"295656121491569":[],"296247":1,"2968":[],"297219777724628":9,"297260":1,"2980":[],"298273":1,"2983233":13,"298375":1,"2990":[],"299444":9,"29944428":9,"2_1":10,"2_2":10,"2_3":10,"2_i":10,"2_m":15,"2_x":15,"2cm":6,"2ff97f4bf03b":15,"2nd":7,"2x_ix_jy_iy_j":6,"2x_j":6,"2y_i":8,"2y_j":6,"30000":1,"300162456113691":[],"30119421":6,"306854":4,"30685416":4,"30879705":1,"30968181":1,"31109204e":1,"3155":3,"3156929654100207":7,"31608475e":[],"31718909":9,"31730641":[],"317367":9,"31853484":[],"31896852":6,"3200":2,"32047562":1,"323291478597321":15,"3250":2,"32521615e":15,"327631":1,"32938847":13,"32945844e":15,"3304":1,"33066907e":4,"3310":1,"3317":1,"333":5,"333333":1,"3338":1,"3344":1,"33443859e":[],"33544681":[],"33569998e":1,"33861512":[],"339535706819584":15,"33953571":15,"340782":9,"34114641e":1,"34172919":[],"3436":1,"3437":1,"344172":1,"346433":9,"34643337":9,"34902789e":15,"351636":9,"35176067":[],"35216172e":1,"358869339268145":15,"35886934":15,"359640894899012":[],"360":2,"360688":1,"36436520e":[],"36468301":[],"369139":9,"36941772":4,"369418":4,"37416969":9,"374170":9,"37738324":[],"38207279e":[],"38216436":[],"38629436":13,"38937995e":15,"38986237":[],"396740":9,"39674043":9,"397700":9,"39792608e":[],"3cd19a0768e1":[],"4000":17,"401842":9,"40212127":[],"404":1,"40425078e":15,"405890":9,"40708470e":1,"40902095":[],"41511965e":2,"415634483874318":1,"416694683938511":9,"4171578884124756":0,"41754964":[],"41770932":[],"418506":9,"41876428e":[],"42847770e":15,"42937310e":15,"43766686":9,"442600":9,"44395541":[],"44625466e":15,"44970586e":2,"45013332e":[],"45019484":[],"450257":9,"4557763":9,"458078":9,"45937170e":[],"461":15,"462":5,"46323168e":15,"46423858e":1,"466":15,"46675058":1,"46914544e":[],"46929603e":[],"47079457e":15,"47566390e":15,"47654764e":[],"47815203":9,"48154187202453613":0,"48257387":16,"48471852e":[],"48476997":9,"48608063e":[],"4940954":1,"49865673":[],"4990":15,"4992":15,"4997":15,"4c4c7f":[7,8],"4y_i":8,"500":[2,3,5,7,8,15],"500000":1,"5018":15,"50394742":[],"506":1,"507d50":[7,8],"50j":5,"50x10":2,"510":2,"5120":0,"512132":1,"51257863e":[],"51345668e":[],"51363731e":[],"51523276e":[],"51893804e":[],"51943726":9,"519842":1,"52158335":1,"5222222222222223":2,"526744":9,"52722156":[],"5303329":9,"5305555555555556":2,"5378811":9,"539261":9,"54121682":4,"541217":4,"54152940e":[],"54237024":15,"54702088e":[],"55138385":9,"551384":9,"55280484":[],"5555555555555556":2,"557795":9,"55854694":9,"56216797e":1,"564374":9,"56536":1,"569":2,"57051369":[],"574465":9,"5755035":1,"57781668":[],"57871326":[],"581766":9,"58176612":9,"582":[1,2],"58228342e":15,"58239999":4,"582400":4,"584804":1,"58521266":9,"585213":9,"58596975":4,"585970":4,"587401":1,"58836420e":15,"5888888888888889":2,"59007674e":15,"59304755e":1,"5944444444444444":2,"59480085":4,"5cm":15,"60122668e":15,"60394236e":1,"60673226":9,"60999846":[],"61069091e":15,"6111111111111112":2,"61124978":[],"61234223":[],"614808":9,"61505887e":[],"61745046e":[],"618":1,"61869821":[],"622539":9,"62253933":9,"6226921":[],"62316154e":15,"62359224e":15,"62373464":9,"625":5,"62783293":[],"62856593":1,"629961":1,"6300745149331701":1,"63315151":1,"63339159":[],"63374631":[],"63437572":[],"63442451e":1,"636323":9,"63632311":9,"63680118":[],"637129335071195":1,"63993205e":[],"64166831e":[],"64447921":[],"64580686":[],"646283":9,"647473":9,"64857826e":[],"649382":9,"64x50":2,"650024":4,"65002433":4,"6510573774179256":15,"65105738":15,"65238878":13,"65245958":[],"653095390463358":1,"653702":13,"65482578":[],"65572035":[],"65599927":[],"65766387":[],"65933852":[],"65939208e":4,"66020213e":1,"6614":3,"66183486":9,"661835":9,"6628996975186952":1,"66302359":[],"66383151":[],"66677842":[],"66800261":[],"66880047":[],"67006792":[],"67060602":[],"671089":1,"6714":3,"67171347e":15,"67279536":[],"67303655":9,"673037":9,"67407338e":15,"67450955":[],"67708423":1,"68034946e":[],"6813":3,"6814":3,"6815":3,"6816":3,"6817":3,"6818813252071303":15,"68188133":15,"68316185":1,"68342382":[],"68616263":13,"68729414":[],"68937695":1,"689519":9,"69069n_":15,"693361":1,"69347005":[],"693850":9,"69385025":9,"69519693":4,"695197":4,"69573183":1,"69981195e":15,"6999536":9,"6ea927cc6e88":2,"6n_":15,"7022283":1,"70234019":[],"70415861":[],"70523024e":[],"70589906":4,"70790937":[],"70886748":1,"70946493e":[],"712018":9,"71281409":[],"71351486":[],"71442781":13,"7162":[],"71669651":1,"7172":[],"72108703":[],"72174172":9,"72218808":[],"72312577":[],"7240496":[],"72780613e":15,"72879865e":[],"72981762":6,"73091052e":1,"73453972":[],"73921714":[],"74081822":6,"74107697":9,"74143127e":1,"7432283":[],"74382593":1,"74495014":[],"74845978":[],"74921867":[],"751699":9,"7522047280566193":4,"75382481":[],"75524378":[],"75629493":[],"75841112":[],"75932862":[],"76172241e":[],"762":9,"7621419":1,"76290332":[],"76497666":[],"765":5,"76504618":[],"76570177":1,"76648901e":[],"7693978131030923":9,"7718":7,"772b904ae9cb":3,"77317984":1,"77350269e":4,"774300":1,"77661393e":15,"77714169":6,"78080633":1,"78195":3,"78857629":1,"78944806":[],"7899453":[],"79295029e":15,"79326583e":15,"79328828":[],"793701":1,"794282":9,"79459035":1,"79648291":1,"79902342":1,"7c394b1e8b71":7,"7d7d58":[7,8],"800":5,"80004454e":[],"80121":[],"8055555555555556":2,"81620806":[],"81633628":9,"81781888":9,"827265":1,"82889306e":15,"8305555555555556":2,"83425361":9,"834254":9,"83614019":[],"8388888888888889":2,"83935285":[],"84087101":[],"842":1,"84355903e":2,"84372853":1,"84443254e":2,"84658093e":15,"8479552268981934":0,"8520127":4,"85278450e":1,"85396354":[],"85450859":9,"85463934e":[],"85497163e":[],"85546305e":[],"861":1,"86145244":9,"8638888888888889":2,"86436607":[],"86574276":[],"8666666666666667":2,"86692943":[],"8718475896381779":15,"87184759":15,"8722222222222222":2,"875":2,"87761937":[],"8777777777777778":2,"87972591":[],"8802":[],"8805555555555555":2,"88297395":[],"88559559":[],"88693966e":15,"88712946":[],"8888888888888888":2,"8901":[],"8914984":[],"8921171964770647":9,"8923":1,"89288636":9,"89383322":[],"8944444444444445":2,"898500":9,"89850037":9,"89942598":1,"89975818":[],"8x8":2,"90233874":[],"90316476":[],"9040":7,"9055555555555556":2,"90618734e":15,"907307":9,"90730735":9,"90825063":1,"91012519e":[],"9111111111111111":2,"91145266e":15,"91549644":1,"9166666666666666":2,"916978":4,"91697817":4,"9171356":1,"9222222222222223":2,"924018":1,"925":2,"92507116e":2,"92605247":1,"92645039":9,"92646965":9,"926470":9,"92732185e":[],"9277777777777778":2,"9279671770201344":15,"92919670e":15,"9305555555555556":2,"931":1,"93100040e":15,"932734":4,"93273404":4,"9354":3,"9361111111111111":2,"937":15,"938":15,"9388888888888889":2,"939":[1,15],"94019247e":1,"94034531":1,"9444444444444444":2,"94536341":15,"94591015":13,"94639099":9,"946893955211749":1,"947543":9,"948729":4,"95014575":[],"9527777777777777":2,"954":15,"9547578478889096":1,"9555555555555556":2,"956563":9,"9583333333333334":2,"960":15,"961":15,"96104648":[],"9611111111111111":2,"962":15,"963499":9,"96349948":9,"965885569080809":[],"967809":9,"96793117e":[],"97101567e":15,"9722222222222222":2,"975":2,"9756404":1,"976":6,"97723801":[],"9777777777777777":2,"9780387310732":17,"9780387848570":17,"9781492032632":17,"9804422":1,"98046438":1,"9805555555555555":2,"98452685":[],"985":15,"98526763":1,"98528992":1,"98531221":1,"986":15,"98609175":15,"986091753050161":15,"9861111111111112":2,"98661465":[],"9877742":[],"987902":1,"9888888888888889":2,"98892195e":15,"98893512":[],"989":15,"98927731":[],"9898ff":[7,8],"99009739":[],"9901168":1,"99013921":1,"99016161":1,"99018401":1,"99043999":[],"9909252":[],"991":15,"991072":9,"99107239":9,"99126104":[],"99133007":[],"99160404":[],"99190487":[],"99194716":[],"992":15,"99218987":4,"99219378":[],"99242605":[],"99248001":[],"99273355":[],"99276945":[],"993":15,"99305549":[],"99305802":[],"99311297":[],"99346398":[],"99363129":[],"99363383":[],"99393624":[],"994":3,"99400444":[],"99418903":9,"99420743":[],"99420997":[],"99428016":[],"9945452":[],"99462421":[],"99473581":[],"99478645":[],"99478898":[],"99498985":1,"995":3,"99501236":1,"99503487":1,"99505739":1,"9950799":1,"99527696":[],"9953048353087299":[],"99536326":[],"9953658":[],"99544872":[],"9954538761021741":[],"99579317":[],"99581841":[],"99594294":[],"996":3,"99600927":[],"99636015":[],"99652042":[],"99652296":[],"99655111":[],"99696351":[],"997":3,"99709325":[],"99710078":[],"99723611":1,"99728435":[],"99730848":[],"99763569":[],"99767893":[],"99782689":[],"998":3,"99817842":[],"99825997":[],"99836973":[],"9984806":[],"99883879":[],"99891285":[],"999":[7,15],"99945628":[],"99988687":1,"9999095":1,"99993212":1,"99995475":1,"99995818594196":[],"999974281880048":1,"99997737":1,"9999794306626945":[],"9999822527140678":[],"9999864543345858":[],"9999868619217517":[],"9999878260589065":1,"9999910208315801":[],"9b9cf4fa1a95":[],"\u00f8yvind":16,"abstract":2,"break":[0,1,9],"byte":13,"case":[1,2,3,4,9,10,12,13,14],"catch":1,"char":15,"class":[1,2,3,5,6,7,9,10,15],"const":15,"default":[1,2,5,13],"ekstr\u00f8m":16,"export":7,"f\u00f8470":16,"final":[0,1,2,3,4,6,7,8,9,14,15,16],"float":[0,1,7,9,13,15],"function":[0,3,7,12,13],"import":[0,1,2,3,4,5,6,7,8,9,10],"int":[0,1,2,4,5,9,13,15],"long":[1,2,5,10,15],"new":[0,1,2,3,4,5,6,7,8,9,13,15],"null":15,"public":[1,12],"return":[0,1,2,3,4,5,6,7,9,13,15],"s\u00f8rli":16,"sch\u00f8yen":16,"short":[0,11],"steinsv\u00e5g":16,"super":4,"switch":[0,1],"throw":15,"true":[0,1,2,3,5,6,7,8,10,15],"try":[0,1,2,5,6,7,8,9,12,13,15],"var":[3,4,8,9,15],"while":[0,1,2,3,4,5,6,7,9,10,15],AGE:1,Adding:2,Age:5,And:[0,1,3,7,12,15],Are:9,Being:5,But:[0,2,3,7,8,15],CAS:[],DIS:1,Doing:[5,8],EoS:[1,3],FYS:14,For:[0,1,2,3,4,5,6,7,8,9,10,12,13,14,15,17],Going:[2,4],Ising:[4,10],Its:[2,9],MDS:9,NNs:10,N_s:6,Not:[1,2,3,4],OLS:[1,3,4],One:[1,2,3,4,5,6,9,10,15],PCs:[9,12],RMS:15,Such:[3,10,15],That:[0,1,5,8,9,10,15],The:[8,13,14,16,17],Then:[0,1,2,3,5,6,7,8,9,10,13,15],There:[0,1,4,6,7,9,10,11,13,14,15,16],These:[0,1,4,6,7,8,9,10,13,15],Use:[1,7],Useful:[3,13],Using:[1,3,4,6,8,10,13],With:[1,3,4,6,7,8,9,10,13,15],__class__:8,__doc__:3,__future__:[6,7],__init__:[2,3],__name__:[3,8],_auto10:10,_auto1:[4,5,10,13,15],_auto2:[10,13,15],_auto3:[10,13],_auto4:[10,13],_auto5:[10,13],_auto6:[10,13],_auto7:[10,13],_auto8:10,_auto9:10,_ax:3,_base:6,_build:[12,17],_check_optimize_result:9,_compon:9,_datafram:[],_depth:7,_fraction:7,_lambda:1,_leaf:7,_logist:9,_make_index:[],_multilayer_perceptron:[1,2],_node:7,_num_sampl:[],_ratio:9,_sampl:7,_split:7,_varianc:9,_weight:7,a0faa0:[7,8],a77d5ac269b2:5,a_0:1,a_1a:1,a_2a:1,a_3:1,a_3a:1,a_4:1,a_4a:1,a_h:2,a_i:[1,2,10],a_j:[2,10],a_k:[2,10],aaron:17,ab_channel:12,abandon:2,abbrevi:14,abid:15,abil:[1,8],abl:[2,4,5,8,10,15],abort:15,about:[0,1,2,3,4,5,6,7,8,9,10,12,13,17],abov:[0,1,2,3,4,5,6,7,8,9,10,13,15],abovement:3,abs:[0,1],abscissa:5,absolut:[1,3,4],acccess:[],accept:[1,7],access:[1,9,15],accid:3,accompani:1,accomplish:[6,7],accord:[0,1,2,3,5,7,10,15],accordingli:9,account:[1,15],accumul:[10,15],accur:[3,8,15],accuraci:[1,2,4,5,7,8,9,10],accuracy_scor:[1,2,8],accuracy_score_numpi:2,achiev:[1,2,3,6,10,13],aco:15,acquaint:12,acquir:[2,12],acr:1,across:[2,3,7,12],act:[2,13],action:15,activ:[0,1,7,14],actual:[1,2,3,4,6,9,13],ada_clf:8,adaboostclassifi:8,adam:2,adapt:[1,3,5,17],add:[1,2,3,4,6,8,9,10,15],add_subplot:[0,2,5,10],added:[1,2,4,5,6,13],adding:[0,2,3,13],addit:[0,1,3,5,6,7,8,10,12,13,15,16,17],addition:[5,10],address:[2,5,7,9,17],adjac:10,adjust:[5,10],admir:1,advanc:[3,10,17],advantag:[2,3,5,8,13],afecionado:[],affect:4,affin:[1,6,9],aficionado:[],aforement:0,african:1,after:[0,1,2,3,4,5,7,9,10,12,13,15],afterward:1,again:[0,1,2,3,5,6,8,9,10,15],against:[2,5,8],age:[1,5],agegroup:5,agegroupmean:5,aggreg:[7,8],agorithm:8,agre:15,ahead:7,aid:9,aim:[0,1,2,3,5,9,12,13],albeit:0,algebra:[1,4,5,12,14],algo:15,algorithm:[1,2,3,5,6,12,13,14,15,17],align:[1,3,4,5,6,15],all:[0,1,2,3,4,5,7,8,9,10,12,13,14,15,16,17],allevi:[2,5],alloc:13,allow:[1,2,3,5,6,8,12,13],almost:[1,2,3,5,6,9,15],alon:7,along:[0,3,4,7,8,9,12,13],alpha:[0,1,2,3,5,6,7,8,15],alpha_:8,alpha_i:5,alpha_k:5,alpha_m:8,alpha_opt:5,alreadi:[8,10,12,13,15],also:[0,1,2,3,4,5,6,7,8,9,10,12,13,14,15,17],alter:[2,15],altern:[1,2,6,7,9,13],although:[2,3,6,8],alwai:[0,1,3,4,5,10,15],ame2016:1,american:1,among:[1,7,8,10],amount:[0,2,3,6,8,12],an_:15,anaconda3:[1,2,3,6,9],anaconda:[1,2,12],analys:[3,4,15],analysi:[2,3,4,5,13,14,17],analyt:[1,3,4,5,10,12],analyz:[1,2,4,15],andrew:2,angl:[1,7,15],ani:[0,1,2,3,4,6,7,8,10,15],anim:10,ann:10,annot:[1,2,5,6],anoth:[1,2,3,5,6,8,9,10,13,15],ans:15,ansatz:1,answer:[1,2,3,13],anymor:[2,6],anyon:6,anyth:[2,15],anytim:16,apach:2,apart:[5,9],api:[2,12],appear:[1,2,13,15],append:[2,3,5,6,7,15],appli:[1,2,3,5,6,7,8,9,10,15,17],applic:[1,2,3,5,7,10,15,17],approach:[2,3,4,7,8,9,10,12,15,17],appropri:[3,7,10,12,15],approx:[1,5,8,9,15],approxim:[1,2,3,4,5,8,9,15],apt:[1,12],aptli:0,aragorn:[],arang:[2,3,5,7,8,10],arbitrari:[2,5,6,10,15],arbitrarili:[1,2,9],architectur:[10,17],area:[1,17],arg:3,argc:15,argmax:[2,9],argmin:[0,8],argsort:9,argu:2,arguabl:0,argument:[1,9,10,15],argv:15,aris:[1,3,5,10,15],arithmet:[1,13],arma:15,armadillo:[13,15],around:[1,2,3,9,15],arrai:[0,1,2,3,4,5,6,7,9,10,12,15],arriv:[1,7,9,13,15],arrow:10,arrowprop:6,art:[1,2,12],articl:[0,1,3,4,8,15],artifici:[1,5,10,17],artificialneuron:10,artist:3,asarrai:[1,7],ascii:15,ask:[3,9,10],aspect:[1,12],assembl:1,assess:[1,3],assign:[0,1,5,6,7,10,14,17],assign_points_to_clust:0,associ:[0,1,3,7,10,15],assum:[0,1,2,3,4,5,6,7,8,9,10,13,15],assumpt:[1,3,7,9,15],ast:[1,3],astyp:[7,8],asymmetri:1,asymptot:3,atoi:15,atom:1,attempt:[1,5,6,8],attend:14,attent:[1,13],attract:[1,8],attribut:[1,7],attributeerror:3,audi:1,aurelien:[1,14,17],author:[1,2,8,15],authour:1,auto:[7,8,15],autocor:15,autocorrelation_tim:15,autocorrelform:15,autocovari:15,autoencod:12,autoencond:12,autograd:12,autom:[1,12],automac:13,automag:[],automat:[1,2,9,12,13],autonom:17,avail:[1,2,3,8,9,12,13,14,17],averag:[0,1,2,3,7,8,15,16],avg:15,avoid:[0,1,3,4,7,9,13],awai:15,awar:8,award:16,axes3d:5,axes:[1,3,5,6,7,8,9],axessubplot:1,axhlin:6,axi:[0,1,2,3,5,6,7,8,9,10,15],axlabel:1,axvlin:6,b_1:[5,10],b_5:5,b_group:7,b_i:[1,2,10],b_ia_:1,b_index:7,b_j:[2,10],b_k:[2,5,10],b_m:10,b_score:7,b_valu:7,bachelor:14,back:[1,4,6,7,8,13,15],backbon:13,backend:2,background:17,backpropag:2,backtrack:7,backup:13,backward:[2,10,13],bad:15,badli:15,bag:[7,12,14],bag_clf:8,baggin:[],baggingboot:8,baggingclassifi:8,baggingtre:8,balanc:3,band:13,bandwidth:13,bar:[1,9],barber:17,bare:8,barebon:0,base:[0,1,2,4,5,6,7,8,12,15,16,17],basi:[4,5,6,8,9,10,13],basic:[4,6,10,12,14,15],batch:[5,9,10],batch_siz:2,bay:5,bayesian:[12,17],becaus:[0,1,2,3,5,6,7,10],becom:[0,1,2,3,4,5,7,10,15],been:[1,2,3,9,10,12,13],befor:[0,1,2,3,4,5,6,10,13,15],beforehand:[0,1,15],begin:[0,1,2,3,4,5,6,7,9,10,13,15],behav:[2,3,5],behavior:[1,2,5],behaviour:10,behind:[1,2,5,6],being:[0,1,2,4,5,6,8,9,10,15],believ:[7,13],belong:[0,5,6,7],below:[1,2,3,4,5,6,7,8,9,10,13,15],benchmark:8,bendik:16,benefici:2,benefit:[1,2,5,9,12],bengio:[2,14,17],benign:[2,5],best:[0,1,2,3,5,6,7,8,10,15,16],beta:[1,2,3,4,5,8,9],beta_0:[1,2,5],beta_0x_:1,beta_1:[1,2,5,8],beta_1x_0:1,beta_1x_1:[1,5],beta_1x_2:1,beta_1x_:1,beta_1x_i:5,beta_2:1,beta_2x_0:1,beta_2x_1:1,beta_2x_2:[1,5],beta_2x_:1,beta_:[1,5],beta_i:[1,4],beta_j:[1,5],beta_k:5,beta_linreg:5,beta_m:8,beta_mg_m:8,beta_p:5,beta_px_p:5,better:[0,1,2,7,8,9,10],between:[0,1,2,3,4,5,6,7,9,10,15],beyond:[1,2,5,6],bia:[1,2,4,6,7,8,10,14,15],bias:[2,3,7,10],big:[0,1,2,3],bigger:2,bigr:10,bike:7,bilbo:[],bilek:16,billion:[10,12],bin:[1,3,5,15],binari:[1,5,7,8,10,14,15],bind:[1,3],binomi:12,binsboot:3,bioinformat:1,biolog:[2,10,17],bios1100:12,bird:1,birth:[],bishop:[14,17],bit:[0,2,13,15],bitwis:15,bla:13,black:[0,6,7],block:[0,3,8,12,13],blockingavg:15,blockingstd:15,blockingvar:15,blocksiz:15,blocksizemax:15,blocksizemin:15,blue:1,bmatrix:[1,2,4,5,6,9,13],bmi:2,bodi:[1,2,10],bold:2,boldfac:1,boldsymbol:[0,1,2,3,4,5,6,8,9],boltzmann:[10,12],book:17,bool:0,boost:[2,7,12,14],boostrap:8,bootavg:15,bootstd:15,bootstrap:[2,12,14],bootvar:15,bootvec:15,borrow:[],boston_dataset:1,bot:6,both:[0,1,2,3,4,5,6,7,8,12,13,15,16],bottl:5,bottom:3,bound:[1,3,6,10],boundari:[6,9,10],box:7,boyd:[5,6],bracket:15,brain:[2,5,10],branch:7,breast:[5,9],brew:[1,12],brg:6,briefli:1,bring:[1,8],broad:1,broadcast:0,browser:[],brute:[4,9],bsol:[],bsubex:[],build:[1,3,8,13,15],built:[1,2,3],bunch:9,busi:1,c46dd114b2af:6,c_0:15,c_1:10,c_2:10,c_3:10,c_4:10,c_i:[5,10],c_k:15,cach:8,cal:[1,5,6,8,10],calcul:[0,1,2,3,4,5,6,7,8,9,10,13],call:[0,1,2,3,4,5,6,7,8,9,10,12,13,15,17],callabl:3,cambridg:[5,17],came:0,can:[0,1,2,3,4,5,6,7,8,9,10,12,13,15,17],cancel:1,cancer:8,cancerpd:5,candid:[6,7,8],cannot:[1,2,4,5,6,7,14,15],canopi:[1,12],capabl:[1,2,6,12],capita:1,captur:[9,10],card:[1,5],cardin:2,care:[0,9],carefulli:5,carlo:[1,3,12,15,17],carri:[3,5],cart:8,casella:17,cast:2,categor:[1,2,7,9],categori:[0,1,2,5,8,10,14],categorical_crossentropi:2,caus:[1,3,4,15],causal:1,causat:1,cax:2,cbar:2,ccc:10,cdf:15,cdot:[0,1,3,5,10,13,15],celebr:5,center:[0,1,2,3,5,6,7,9,15],centr:17,central:[1,3,6,13],centroid:[0,15],centroid_differ:0,centroid_list:0,certain:[0,1,3,5,7,15],cha:1,chain:[2,12,15],challeng:[0,5],chanc:[2,5,15],chang:[0,1,2,3,4,5,6,7,9,10,13,15],chapter:[0,3,8,9,13,14,17],charact:[1,4,6,15],character:[6,7,8,10,15],characterist:[1,2,8],charg:1,charl:1,chd:5,chddata:5,cheap:4,cheaper:[2,5],chebychev:0,check:[1,2,5,9,13],check_consistent_length:[],chemic:15,chen:8,choic:[0,1,2,3,5,7,10,13,15],choleski:[4,13],choos:[0,3,5,7,8,9,15],chosen:[1,2,3,5,6,7,8,15],chosen_datapoint:2,christian:17,christoph:[14,17],cin:15,circ:[2,10],circl:[1,6,10],circumfer:7,circumv:[2,4],clariti:[0,15],class_nam:7,class_val:7,class_valu:7,classic:[5,7],classif:[1,3,5,6,9,10,12,14,17],classifi:[1,2,5,7,8,9],classificaton:2,classifii:8,clean:2,clear:[2,8,10],clearer:0,clearli:[3,5,6,15],clever:[0,2,8],clf3:1,clf:[1,6,7,8],clf_ridg:1,clip:15,close:[0,1,2,3,5,6,7,9,10,15,17],closest:[0,5,6,9],closur:12,cloud:12,clust:0,cluster:[1,2,3,9,12,14],cluster_label:0,cmap:[1,2,6,7,8],cmath:15,cmb:14,cmd:7,cn_:15,cnn:10,cntk:12,code:[3,4,6,12,13,14,17],coef0:6,coef:1,coef_:[1,5,6,7],coeffici:[1,3,5,6,7,13],coerc:[1,3],coin:[8,15],coin_toss:8,col:[1,9],colab:12,cold:7,colinear:1,collaps:6,collect:[1,3,8,9,12,15,17],collinear:4,color:[1,3,6,7,8,15],colorbar:2,colsample_bytre:8,colsaobject:8,column:[1,2,3,4,5,6,7,9,10,13],columntransform:7,com:[12,16,17],combin:[2,3,5,8,15],come:[0,1,2,4,5,10],comma:[],command:[1,2,15],comment:1,commerci:[1,12],commod:1,common:[0,1,2,3,4,5,7,9,15],commonli:[0,2,3,5,7],commun:[1,10],compact:[0,1,2,3,4,5,7,9,10],compar:[0,1,3,4,5,9,13],compat:5,compet:1,competit:8,compil:[1,2,12,13,15],complet:[1,7,10],completenn:10,complex:[1,2,3,6,7,9,10],complic:[0,1,2,3,5,7],compon:[0,1,2,3,4,5,7,12,14],components_:9,compos:[0,7,10],compphys:[12,14,17],compress:1,compris:3,compromis:4,compulsori:12,comput:[0,1,2,3,4,6,8,9,10,12,13,14,17],computation:[1,3,5,7,15],concaten:0,concav:[2,5],concentr:[1,8],concept:[0,1,12],conceptu:[5,10],concern:[0,1,2,5],concic:[],conclud:1,conclus:2,conda:[1,2,12],condit:[1,3,4,6,7,9,15],conduct:12,confid:[1,3,5,6],confirm:10,confus:[3,8,13],confusion_matrix:7,congruenti:15,conjug:6,conjugaci:5,connect:[1,2,5,7,9,10,13],consequ:[3,4,5,6,8,10],conserv:[0,4],consid:[0,1,2,3,4,5,6,7,8,10,13,15],consider:[1,2,5],consist:[1,2,3,5,10,15],constant:[1,5,6,10,15],constitu:1,constitut:3,constrain:[2,5,9],constraint:[4,5,6],construct:[1,2,3,4,5,6,7,8,9,13,15,17],contact:1,contain:[0,1,3,5,6,7,9,10,13,15,17],contemporari:17,content:[2,12,13],context:[3,5,8],continu:[1,2,3,5,6,7,8,10,13],contour:[5,7,8],contourf:[6,7,8],contrast:[2,7,8,10],contribut:[1,4,15],contributor:1,control:[1,2,7,12],conveni:[1,3,5,10,13],convent:10,converg:[0,1,2,4,5,6,9],convergencewarn:[1,2,6,9],convert:[1,2,4,7,9,13],convinc:5,convolut:[2,12,14],cool:7,coordin:[0,4,10],coorel:1,copi:[0,2],core:8,corel:1,coronari:5,corr:[1,4,5,9],correalt:[4,9,12],correct:[0,1,2,4,13,15],correctli:[2,3,8],correl:[1,2,5,8,10,12],correlation_matrix:[1,4,5,9],correspond:[0,1,3,6,7,9,10,12,13,15],cortex:10,cos:[1,3,7],cosin:[0,3],cost:[1,3,4,6,7,10,15],could:[1,2,3,4,5,6,7,8,9,10,13,15],coulomb:1,count:[1,7,14,15,16],countor:5,cours:[1,2,9,14,15],courvil:[14,17],cout:15,cov:[3,4,9,13,15],cov_xi:[4,9],cov_xx:[4,9],cov_yi:[4,9],covari:[5,12,13],covariance_matrix:[0,4,9],cover:[1,11,12,17],covert:1,covxi:15,covxx:15,covxz:15,covyi:15,covyz:15,covzz:15,cpu:2,creat:[2,7,8,9,10,12],create_biases_and_weight:2,create_neural_network_kera:2,create_x:[1,4,9],credit:[1,5],crim:1,crime:1,criteria:[0,1,7,8,15],criterion:[5,7,8],cross:[1,2,5,7,8,12,14,15],cross_val_scor:3,cross_valid:[5,8],crossvalid:3,crucial:[2,15],csr_matrix:13,cstdlib:15,csv:[1,3,5,7],ctnk:2,cubic:1,cumsum:[8,9],cumul:[3,8],cumulative_heads_ratio:8,current:[0,2,5],curs:1,curv:[5,8,10],curvatur:5,custom:0,custom_cmap2:[7,8],custom_cmap:[7,8],cutpoint:7,cvxbook:5,cvxopt:6,cyber:17,cycl:[0,2,10,15],d_f:5,dagger:[4,13],dai:[2,7,12],dalen:16,darget:7,darkr:15,dat:1,dat_id:[1,3,5,7],data1:0,data2:0,data3:0,data4:0,data:[0,3,4,6,8,10,13,17],data_id:[1,3,5,7],data_indic:2,data_panda:[],data_path:[1,3,5,7],databas:2,datafil:[1,3,5,7],datafram:[1,4,5,7,9],datapoint:[1,2,3,4,5,9],dataset:[0,1,3,5,6,7,8,9],date:1,daughter:8,david:17,dbh:2,dbo:2,dcomposit:13,dead:2,deal:[0,1,2,5,6,9,13,15],debt:5,debug:3,decad:1,decai:[1,5,15],decent:8,decid:[3,7],decim:1,decis:[1,2,6,9,12,14,17],decision_funct:6,decision_tre:7,decisiontreeclassifi:[7,8],decisiontreeregressor:[1,7,8],declar:[1,13],decompos:[4,13],decomposit:[1,10],decompost:4,decorrel:8,decreas:[2,3,5,8,9],deduc:1,deep:[5,10,12,14,17],deep_tree_clf1:7,deep_tree_clf2:7,deep_tree_clf:[7,8],deepen:12,deeper:0,deeplearningbook:17,def:[0,1,2,3,4,5,6,7,8,9,15],def_covari:15,defect:4,defici:4,defin:[0,1,3,4,5,6,7,8,9,10,13,15],definit:[0,2,3,4,5,6,8,9,10,13],defint:15,degre:[3,4,6,7,8,9,15],del:2,delet:[3,15],deliv:14,delta:[0,1,6,10,15],delta_:[2,13],delta_h:[1,2],delta_j:10,delta_k:10,delta_l:2,delta_n:1,delug:12,delv:1,demand:5,demonstr:[1,3,4,5,9,10,12],denomin:2,denot:[2,3,5,15],dens:[0,2],densiti:[0,1,3,15],depart:16,depend:[0,1,2,3,4,5,6,9,10,12,15],depict:15,deploy:[1,12],deprec:1,depth:[7,8,13],deriv:[1,2,3,4,6,8,9,12],descend:[4,7,9],descent:[1,2,6,10],descr:1,describ:[0,1,3,6,8,9,10,13],descript:[0,1,6,7],design:[1,2,3,4,5,8,9,10],designmatrix:1,desir:[0,1,4,5],despit:[2,10],destroi:13,det:[4,13],detail:[0,1,5,9,13],detect:[6,10],determin:[1,5,6,7,8,9,10,13,15],determinist:[5,15],dev:[2,15],develop:[0,1,6,8,9,10,12,13],deviat:[1,2,3],devis:10,df1:[],diag:[4,6],diagnost:[2,8],diagon:[1,4,5,13,15],diagonaliz:4,diagram:8,dict:6,dict_kei:1,dictionari:1,did:[0,1,2,4,5,8,9],die:2,diffeent:6,differ:[0,1,2,3,4,7,8,9,10,12,13,15,17],differenti:[5,12,13],difficult:[0,1,2,3,8,15],difficulti:[1,2,5],digit:[1,2,14,16],dilut:2,dim:[0,9],dimens:[0,1,2,4,6,9,13],dimension:[0,1,3,4,5,7,9,12,13],dimensionless:1,diment:13,dimes:0,direct:[0,1,2,5,9,10],directli:[0,2,15],directori:5,disadvantag:1,discard:[3,9],disciplin:[1,10],disclaim:15,discourag:5,discov:1,discret:[2,5],discrimin:[5,8,9],discuss:[0,1,2,3,4,5,6,7,8,9,10,12,13,14,15,17],diseas:5,disk:[],disord:[2,5],displai:[0,1,2,3,5,6,7,8,9,10,15],displaystyl:[1,4],displot:1,disregard:1,dissimilar:[0,9],dist:0,distanc:[0,1,6,7,9,15],distance_list:7,distinct:[0,5,6,7,8],distinctli:6,distinguish:[1,5,6,15],distplot:1,distribut:[0,1,2,3,5,8,9,12,13],distrubut:[1,12],dive:[1,4,6],diverg:[2,5],divid:[1,2,3,6,7,9,10,15],divis:[3,6,7,13,15],dna:5,dnn:[1,2,10],dnn_kera:2,dnn_model:2,dnn_numpi:2,dnn_scikit:[1,2],doc:[12,14,17],doconc:[],document:9,doe:[0,1,2,3,4,5,6,8,9,10,13,15],doesn:[7,10],dog:2,doi:0,doing:[1,3,9],domain:[5,6],domin:1,don:[0,1,2,6,9,12,15],done:[0,1,3,4,7,8,9,13,15],dot:[1,4,5,6,7,8,9,10,13,15],doubl:[13,15],doubli:2,down:[1,5,7,9,10],download:[1,2,13,17],dozen:2,dramat:9,draw:[3,5,8],drawback:[1,2,5],drawn:[2,3,5,9,15],drop:[1,2,3,4,9,15],dropna:[1,3],dtype:[0,1,2,13],dub:1,due:[0,2,3,4,5,6,8,10],dummi:1,dure:[1,2,6,7,9,12],dwell:1,dwh:2,dwo:2,dx_1:15,dx_n:15,dying:2,each:[0,1,2,3,4,5,6,7,8,9,10,12,13,14,15,16],eapprox:1,earli:2,earlier:[1,5,6,7,9,10],eas:[0,7],easi:[1,3,4,5,6,7,8,9,10,12,13],easier:[3,6,7,15],easiest:5,easili:[1,2,4,5,6,7,8,9,10,13],eastern:16,ebind:1,eblock:7,econometr:[],ecosystem:12,ect:14,edgecolor:3,edit:[],edu:5,educ:1,eface79dac2c:8,eff:15,effect:[2,8,15],effic:2,effici:[1,5,8,12,13,15],efron:[3,15],eig:[4,5,9,13,15],eigen:15,eigenpair:[4,9],eigenvalu:[4,5,6,9,13],eigenvector:[4,5,9],eight:13,eigval:[13,15],eigvalu:[5,9],eigvec:[13,15],eigvector:[5,9],eispack:13,either:[1,2,3,4,5,6,7,8,9,15],ekstrom:16,elabor:15,electr:[1,10],electur:17,eleg:9,element:[2,3,4,5,6,9,10,12,13,14,17],elementari:[8,13],elessar:[],elif:0,elim:13,elimin:6,els:[2,5,7,10,15],elu:2,elus:1,email:[14,16],embed:[1,9],embodi:3,emit:15,emner:17,emphas:[1,8,12],emphasi:[1,12,17],empir:[2,9,15],emploi:[1,2,3,5,9,15],employ:1,empti:[3,8],emul:10,enabl:9,encapsul:0,encod:[0,1,7,9],encompass:[1,15],encount:[1,2,4,5,15],end:[0,1,2,3,4,5,6,7,8,9,10,13,15],endl:15,endpoint:15,energi:[1,3],enforc:10,eng:17,engin:[1,2,12,15],english:17,enough:[1,3,5],ensembl:[2,7,14,15],ensur:[1,2,3,5,9,15],enter:[4,15],enthought:[1,12],entir:[2,5,7,12,15],entiti:[7,10,13],entri:[1,4,6,9,10,13],entropi:[2,5,8],enumer:[1,2,6],env:15,environ:[12,17],eol:1,eosfit:1,epoch:[1,2,5,10],epsilon:[1,3,5],epsilon_0:1,epsilon_1:1,epsilon_2:1,epsilon_:1,epsilon_i:1,eqnarrai:3,equal:[0,1,2,3,4,5,6,7,9,10,13,15],equat:[0,2,3,4,6,7,8,9,13,15],equilibrium:10,equiv:[5,13,15],equival:[2,4,6,9,12,13],erf:15,eriador:[],eridg:1,err:[1,8],err_:3,errat:5,errno:5,error:[1,2,3,4,5,7,9,10,12,15],error_estimate_corr_tim:15,error_hidden:2,error_output:2,escap:5,esl:0,esol:[],especi:[2,7,10],essenti:[0,1,4,7,8,10,15],establish:[1,8,9],estim:[1,2,3,4,5,8,9,12,15],estimated_mse_fold:3,estimated_mse_kfold:3,estimated_mse_sklearn:3,esubex:[],eta0:[5,6],eta:[1,2,5,6,10],eta_v:[1,2],etc:[0,1,2,4,5,6,7,9,10,12,13,15],ethic:12,etsim:3,euclidean:[0,1],evalu:[1,3,4,5,7,15],even:[0,1,2,3,5,6,7,8,9,10,12,13,15],event:[5,8],eventu:[3,4,5,9,10,16],everi:[0,1,2,3,5,7,8,9,10,12,15],everyth:10,everywher:5,evolv:1,exact:[1,4,5,9,10,13,15],exactli:[1,10,12],examin:3,exampl:[3,4,9,10,12,13,14,17],exce:[2,10],excel:[0,1,2,8,17],except:[3,6,7,15],excess:1,excit:1,exclud:[2,3,10],exclus:[1,2,3,15],execut:4,exemplifi:5,exercis:[12,14],exhaust:3,exhibit:[1,6],exist:[0,1,2,3,5,6,7,13,17],exit:[4,13,15],exp:[1,2,3,4,5,6,8,9,10,15],exp_term:2,expand:[4,5,9],expans:[1,4,5,6,8,10],expect:[1,2,3,4,5,9,10,12],expectation_value_of_h_wrt_p:15,expens:[3,5,8,15],experi:[1,2,3,5,6,12],experiment:[1,3,7,15],expert:[2,7],explain:[0,1,5,7,8,9,15],explained_variance_ratio_:9,explanatori:1,explicit:[1,13],explicitli:[0,1],explod:2,exploit:[1,10],explor:[2,5,6,12],expon:2,exponenti:[1,2,5,8],export_graphviz:7,export_text:7,exporttext:7,expos:12,express:[1,3,4,8,10,13,15],exptmean:15,exptvari:15,extend:[9,12],extens:[1,10,12],extent:[1,2,3,17],extern:7,extra:[2,4],extract:[1,4,5,6,9,13],extrapol:1,extrem:[0,1,2,5,6,7,13],extremum:5,extrins:9,eye:[0,1,5,13],f11:1,f12:1,f13:1,f1d:5,f6d7a289d493:13,f_0:8,f_1:[5,8],f_2:[5,10],f_3:10,f_d:15,f_i:[3,10],f_m:8,face:5,facecolor:[3,6,15],facil:[1,12],facilit:10,fact:[1,2,4,5,7,9,10],factor:[1,2,4,7,8,9,13,15],fafab0:[7,8],fail:[3,5,6,9,16],failur:5,fairli:[0,2,15],fall:[6,7,14],fals:[0,1,2,3,5,7,8],famili:[1,5,6,15],familiar:[1,6,12,13,15],famou:[3,10,13],far:[0,1,4,5,6,9,10,15],fashion:[1,7,8],fast:[2,3,5,8,10,12,15],faster:[2,9],fastest:5,favor:5,favorit:15,featur:[1,2,3,4,5,6,8,9,10,12,15],feature_nam:[1,2,5,7],feautur:7,fed:2,feed:[1,9,12,14],feed_forward:2,feed_forward_out:2,feed_forward_train:2,feedforward:[2,10],feel:[0,1,9,12,16],feet:1,few:[0,2,7,11,15],fewer:[1,7,9],ffnn:[2,10],field:[1,10,12],fifth:1,fig:[0,1,2,5,10],fig_id:[1,3,5,7],figaxi:15,figsiz:[1,2,3,5,6,7,8],figur:[0,1,2,3,5,6,7,8,10,12],figure_id:[1,3,5,7],figurefil:[1,3,5,7],file:[1,2,3,5,6,7,13,15],filenam:[1,15],filenotfounderror:5,fileout:15,fill:[4,7],financ:1,find:[0,1,2,3,4,5,6,7,8,9,10,12,15],fine:[0,1],finit:[3,4,10,15],first:[0,1,2,3,4,6,7,8,9,13,15,17],firsteigvector:9,fit:[2,3,4,5,6,7,9,10,15],fit_intercept:3,fit_mod:7,fit_transform:[1,3,6,7,9],fiti:1,five:[1,7],fix:[1,3,5,8,9,10],flag:0,flat:[5,10],flatten:2,flexibl:[1,2,3,6,8,10],float32:7,float64:[1,13],flop:[4,13],flow:[2,10],fly:9,flyvbjerg:15,fmesh:5,focu:[1,3,12,17],focus:[2,5,13],fold:[3,7],folder:1,follow:[0,1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17],font:[1,5,15],fontdict:15,fontsiz:[2,6,7,8,15],fontweight:2,foral:6,forc:[1,4,8,9],forecast:10,forest:[1,2,7,12,14],forget:9,form:[1,3,4,5,6,7,9,10,12,13,15],formal:[0,15],format:[1,2,3,5,6,7,8,9,12,15,17],formatstrformatt:5,formul:[0,9],formula:[5,15],forth:10,fortran2003:12,fortran90:15,fortran:[1,12,13],fortun:[1,9],forward:[1,3,12,13,14],found:[2,3,5,10],foundat:12,four:[6,10,13,14],fourier:1,fourth:10,frac:[0,1,2,3,4,5,6,7,8,9,10,13,15],fraction:7,frame:5,framework:[2,6,8,15],frank:[4,9],frankefunct:[1,4,9],free:[1,9,12,13,15,16,17],freecodecamp:12,freedom:4,freeli:1,frequenc:[3,5,15],frequent:[1,5,6,7],frequentist:12,fresh:8,fret:0,fridai:14,friedman:[14,17],frodo:[],from:[0,1,2,3,4,5,6,7,9,12,13,14,15,16,17],from_cod:7,front:1,fruit:0,fstream:15,fulfil:[4,10],full:[1,2,4,5,7,8,15],fulli:[3,10,14,15],fun:12,func:3,functionali:9,fundament:[1,3,12],further:7,furthermor:[1,3,4,5,9,10,12],futur:[1,6,7],futurewarn:1,fys:16,g_1:8,g_2:8,g_m:8,gain:[0,2,4,7,8],galleri:1,gamge:[],gamma1:6,gamma2:6,gamma:[1,5,6,7,8,9],gamma_0:8,gamma_1:8,gamma_1x:8,gamma_:1,gamma_i:[1,6,15],gamma_j:5,gamma_k:5,gamma_m:8,gamma_x:1,gap:6,gate:10,gather:[2,10],gaug:10,gaussbacksub:13,gaussian:[0,3,6],gaussian_point:0,gaussian_rbf:6,gave:5,gbc:14,gca:[3,5,6],gd_clf:8,gdclassiffiercgain:8,gdclassiffierconfus:8,gdclassiffierroc:8,gdregress:8,gen:15,gender:1,gener:[0,1,2,3,4,5,6,8,9,10,13,17],generallay:10,generate_simple_clustering_dataset:0,genom:12,geodes:9,geometr:1,georg:17,geq:[4,5,6,7],geron:[1,14,17],get:[0,1,2,3,5,7,8,9,12,13,15],get_distances_to_clust:0,get_dummi:7,get_split:7,get_yaxi:6,getattr:3,gibb:12,gini:8,gini_index:7,git:[1,12],github:[1,12,14,17],gitlab:[1,12],give:[0,1,2,4,5,6,7,8,10,12,15,17],given:[0,1,2,3,4,5,6,7,8,9,10,13,15],glare:0,global:[5,15],glorot:2,gmail:16,goal:[1,5,7],goe:[0,1,2,3,4,5,13],going:[1,2,3,4,5,6,7,9,10],golden:5,gone:4,gong:2,good:[0,2,5,7,8,9,12,15,17],goodfellow:[14,17],googl:[0,2,12],got:2,gpu:2,grade:14,gradient:[1,6,7,10,12,14],gradientboostingclassifi:8,gradientboostingregressor:8,gradual:[0,2],graph:[2,5,7,9,10],graph_from_dot_data:7,graphic:[1,2,7],grasp:1,gray_r:2,great:5,greater:[2,5,15],greedi:7,green:[1,7,15],grid:[2,3,5,6,10,15],grossli:5,ground:1,group:[0,1,3,5,7,12,14],groupbi:1,grow:[2,7,8],growth:1,guarante:[1,5,15],guess:[0,2,5,8],guestrin:8,guid:2,h_1:5,h_2:5,h_m:8,had:[1,2,3,4,5],hadamard:[2,10],half:[2,6,7],halv:8,hand:[1,2,5,9,10,12,13,14,15,17],handl:[1,2,7,9,12],handle_unknown:7,handsid:10,handwrit:10,handwritten:[2,5],happen:[0,2,4,5,8,15],hard:[2,5,6,8],hardcopi:12,harder:[1,2],has:[0,1,2,3,4,5,6,7,8,9,10,13,15],hasn:[1,2],hassl:[1,12],hast:12,hasti:[0,1,14,17],hat:[2,4,5,7,8,9,10,13,15],have:[0,1,2,3,4,5,6,7,8,9,10,12,13,15],haven:2,hdf5:[],head:[1,8,15],header:1,heads_proba:8,hear:1,heart:[1,5],heatmap:[1,2,5],heavili:1,heavisid:2,height:2,help:[0,1,2,10],helper:0,henc:[1,3,4,5,6,7,8,10],her:5,here:[0,1,2,3,4,5,6,7,8,9,10,12,13,15,17],hereaft:[1,6,10],hermitian:13,hessenberg:13,heterogen:[7,8],hidden:[2,10],hidden_bia:2,hidden_bias_gradi:2,hidden_layer_s:[1,2],hidden_weight:2,hidden_weights_gradi:2,hierarch:0,high:[0,1,2,3,4,5,7,8,9,12,13],higher:[1,2,3,5,6],highest:2,highli:[1,4,8,12,13,15,17],highwai:1,hing:6,hint:5,hip:12,hire:1,his:5,hist:[3,5,15],histogram:[1,3,5,15],histor:[5,9],histori:10,histplot:1,histtyp:3,hjorth:16,hobbi:15,hoc:4,hoff:17,hold:[0,2,3,5,15],holder:1,home:1,homogen:[2,7,8],hopefulli:[1,9,15],horizont:9,hors:5,hot:[2,7],hour:[2,12,14,15,16],how:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,17],howev:[0,1,2,3,4,5,6,7,8,9,10,12,13,15],hspace:[1,6,8,15],hstack:2,htf:14,html:[9,12,14,17],http:[5,9,12,13,14,17],huang:1,huber:1,huge:[2,12],human:[1,2,7,10],humid:7,hundr:2,hungri:2,hybrid:14,hydrogen:1,hyperbol:[2,10],hyperparam:6,hyperparamet:[0,1,4,7],hyperplan:9,i_1:3,i_2:3,ian:17,idea:[1,2,3,5,7,8,10,13,15],ideal:[0,1,3,6,15],idem:3,ident:[3,4,10,13],identifi:[0,1,2,5,6,7,9,10],idum:15,ieor:15,ifi:17,ifs:12,ignor:[1,2,7],iii:13,ijca2016907841:0,illustr:[0,5,8,10,12],imag:[2,7,9,10,17],image_path:[1,3,5,7],imagin:2,immedi:[1,12],implement:[0,1,5,6,7,8,9,10],impli:[3,4,5,13],implicitli:[9,15],impos:[1,9,10],imposs:[1,4],impress:[1,10],improv:[0,4,7,8,9],impur:7,imshow:2,in3050:17,in4080:17,in4300:17,in5400:17,inaccur:5,inact:10,inadequ:1,includ:[1,2,5,9,10,12,15,16,17],include_bia:[3,7],incom:10,inconsist:[],incorrect:2,incoveni:6,increas:[1,2,3,6,7,9,10,15],increasingli:15,ind:3,inde:[1,4],indent:15,indentationerror:15,independ:[1,3,4,5,6,10,15],index:[0,1,2,8,12,15,17],index_col:1,indic:[1,2,4,7,8,9],indispens:3,individu:[2,5,8,10,15],indu:1,indx:13,ineffici:0,inequ:6,inequaltii:5,inf1000:12,inf1100:12,inf1100l:12,inf1110:12,inf3000:17,inf4490:17,inf5860:17,inf:1,infeas:7,infer:[1,2,3,17],inferenc:2,infil:[1,3,5,7],infin:[3,4,5,9],infinitesim:15,influenc:[3,8],influenti:2,info:[],inform:[0,1,2,3,5,7,9,10,13,17],infti:[5,15],ingeni:5,ingredi:[1,7],inher:3,inherit:13,initi:[0,1,2,3,5,8,13,15],initialis:15,inject:0,inlin:[0,1,2,3,5,6,7,8,9,10,13,15],inner:[3,5],innov:17,input:[0,1,2,3,4,5,6,7,8,10,13,15],input_dim:2,inputs:2,inputs_shuffl:2,insert:[6,8,15],insid:[1,5],insight:[1,2,4,12,17],insist:5,inspir:[1,2,10,17],instal:[1,2,7,14],instanc:[1,2,3,5,7,9],instanti:8,instead:[0,1,2,3,4,5,6,7,9,13,15],institut:2,instruct:[1,2],int32:8,int64:1,int_0:15,int_:15,int_a:15,integ:[0,2,13,15],integer_vector:2,integr:15,intellig:[0,1,17],intend:8,intens:2,intention:0,interact:[1,7,10,12],intercept:[1,5,6,9],intercept_:[1,5,6,7],interchang:[10,13],interconnect:2,interest:[1,2,3,4,5,6,7,10,12,15],interfac:[2,13],interior:[1,7],intermedi:13,intern:[2,8,10],interpol:[2,10],interpr:4,interpret:[1,2,7,8,10,13,14,15],interv:[1,3,5,15],intial:5,intimid:[],intract:1,intrins:[9,13,15],intro:[12,17],introduc:[1,2,5,6,8,10,13,15],introduct:[2,5,14,17],introductori:[1,13,17],intuit:[1,3,6,10],inv:[1,4,5],invalid:[2,6,13],invalu:[1,5,12],invari:2,invd:4,inver:6,invers:[1,4,5],invers_period:15,inverse_transform:6,invert:[1,4,5,8],invok:[1,6],involv:[1,3,5,9,10],iomanip:15,ios:15,iostream:15,ipca:9,ipynb:12,ipython:[0,1,2,3,5,6,7,8,9,12,13,15],irani:0,iri:[6,7],irreduc:3,irrelev:4,irrespect:1,isnul:1,isomap:9,issu:[2,7,13],it_arrai:5,item:1,items:13,iter:[0,1,2,3,6,9,15],its:[0,1,2,3,4,5,6,7,8,9,10,12,13,17],itself:[3,10,15],jackknavg:15,jackknif:[3,12],jackknstd:15,jackknvar:15,jackknvec:15,jacobian:5,jargon:15,jensen:16,jerom:17,job:[6,8],join:[1,3,5,7],journal:15,judg:5,julia:[12,13],jump:[0,15],jupyt:[0,1,12,17],just:[0,1,2,3,4,5,6,7,8,9,10,15],justif:1,justifi:8,k_mean:0,kappa_d:15,karim:16,karlsen:16,karush:6,keep:[0,1,2,4,5,9,13],keepdim:[2,3,8],kei:[1,2,10,17],kept:0,kera:[1,12,14],kernel:[1,2,12],kernel_regular:2,kernelpca:9,kev:1,kevin:17,keyword:13,kfold:3,kick:[2,5],kind:[0,1,6,10],kjm:12,kkt:6,kmeanspoint:0,kn_k:0,know:[0,1,2,4,5,6,12,15],knowledg:[1,12],known:[2,3,5,6,7,10,13,15,17],kondev:1,kpca:9,kroneck:0,kuhn:6,kwarg:3,kwown:1,l1_l2:2,l_1:5,l_2:5,l_j:10,la_i:10,la_k:10,lab:[12,14],label:[0,1,2,3,4,5,6,7,8,10,12,13,15],labelencod:[5,8],labels:[6,7],labels_shuffl:2,labor:0,laboratori:14,lack:[0,1],lagrang:[6,9],lambda:[1,2,3,4,5,6,8,10,15],lambda_0:9,lambda_1:[4,6,9],lambda_2:[6,9],lambda_:9,lambda_i:[6,9],lambda_iy_i:6,lambda_jy_iy_j:6,lambda_k:6,lambda_n:[4,6],lamda:2,land:[1,6],landmark:6,landscap:5,langl:[1,9,15],languag:[1,2,6,12,13,17],lapack:13,laptop:12,larg:[1,2,3,4,5,6,7,8,9,12,13,15,17],larger:[1,3,4,5,6,8,9,15],largest:[6,9],lasso:[1,3,5,12,14],last:[0,1,2,3,4,5,6,7,8,10,13,15],later:[0,1,2,4,5,6,10,12,15],latex:[],latter:[1,5,6,9,13,15],lattic:10,law:1,layer:1,lbfg:[5,7,8,9],lbl:3,lcc:3,lda:9,ldot:[1,3,9,15],lead:[1,2,3,4,5,6,7,8,9,10,13,15],leaf:7,leaki:2,lear:5,learn:[3,6,7,8,10,13,14,17],learner:8,learning_r:[6,8],learning_rate_init:[1,2],learning_schedul:5,least:[0,1,3,4,5,6,8,9,12,13,15],leav:[1,2,3,7,9],lectur:[1,2,4,5,8,9,10,12,13,14,17],lecturenot:[12,17],left:[1,2,3,4,5,6,7,8,9,10,13,15],leftarrow:[6,10],legend:[1,3,5,6,7,8],len:[0,1,2,3,4,6,7,8,9,10,13,15],length:[1,2,5,6,7,12,15],leq:[0,1,4,5,6,15],less:[1,2,3,4,6,7,15],lessen:2,let:[0,1,2,3,4,5,6,7,8,9,10,13,15],letter:[1,13,15],level:[1,2,3,7,12,13,14],lib:[1,2,3,6,9],liblinear:[6,8],librari:[1,2,7,8,9,13,15,17],licens:[1,2,12],lie:[3,9,15],lies:[6,9],life:[1,2,6,10],lift:0,light:[],like:[0,1,2,3,4,5,7,8,9,10,12,13,15],likelihood:[1,2,7],lim_:15,limit:[1,3,6,9,10,13],lin_clf:6,lin_model:1,lin_reg:7,linalg:[1,4,5,6,9,13,15],line1:6,line2:6,line3:6,line:[1,2,3,5,6,9,13,15],linear:[2,3,4,5,7,8,9,10,12,14,15],linear_model:[1,3,5,6,7,8,9],linear_regress:3,linearli:4,linearloc:5,linearregress:[1,3,5,7],linearsvc:6,liner:2,linerar:8,linewidth:[1,3,6,7,8],link:[1,5,7,10,12],linpack:13,linreg:1,linspac:[1,3,6,7,8,13,15],linu:16,linuek:16,linux:[1,2,12],liquid:1,list:[0,1,2,7,12],listedcolormap:[7,8],literatur:[0,2,5,17],littl:[2,7,10],live:6,lle:1,lloyd:0,lmb:3,lmbd:[1,2],lmbd_val:[1,2],lmbda:5,load:[1,2,5,7,8],load_boston:1,load_breast_canc:[2,5,7,8,9],load_digit:2,load_iri:[6,7],loc:[1,3,5,6,7,8],local:[1,2,5,10],locat:6,log10:3,log:[1,2,3,5,7,8,9,13],log_:1,log_clf:8,logarithm:[1,5,13],logic:[1,2,7],logist:[1,2,6,7,8,9,10,12,14],logisticregress:[5,7,8,9],logit:5,logreg:[5,7,8,9],logspac:[1,2,3],longer:[0,6,8,13,15],longest:0,loocv:3,look:[0,1,2,3,4,5,6,7,8,9,13,15],loop:[0,2,3,8,10,12,13,15],lose:2,loss:[1,2,3,4,6,8,9,13],lot:[0,1,2,3],low:[1,3,7,8,9,15],lower:[1,2,7,8,13],lowercas:13,lowest:[5,7,15],lstat:1,lstsq:1,lubksb:13,ludcmp:13,lux:13,lvert:2,m_1:0,m_h:1,m_k:0,m_l:10,m_n:1,m_p:1,machin:[2,3,7,8,9,10,13,14,17],machinelearn:[12,14,17],mackai:17,made:[1,2,3,4,5,7,9,10],mae:1,magic:0,magnitud:[2,5],mai:[1,2,3,4,5,6,7,9,10,12,13,15],mail:14,main:[1,2,4,5,7,13,17],mainli:[1,3,5,7],maintain:3,major:[2,3,5,7,8,13],make:[0,2,3,4,5,6,9,10,12,13,15,17],make_moon:[6,7,8],make_pipelin:[1,3,8],makedir:[1,3,5,7],makeplot:1,malcondit:13,malign:[2,5,7],manag:[1,12],manhattan:0,mani:[0,1,2,3,5,6,7,9,11,12,13,15,17],manifold:9,manual:0,map:[0,1,2,3,5,6,9,10,15],margin:[1,6],marit:1,mark:[],marker:[1,5,13],markov:12,marsaglia:15,mask:15,mass:[1,2,4],massag:1,masses2016:1,masses2016ol:1,masses2016tre:1,masseval2016:1,master:14,mat1100:12,mat1110:12,mat1120:12,mat3155:14,mat4155:14,mat:12,match:[0,2,5],materi:[4,5,13],math:[0,4,5,10,13,15,17],mathbb:[0,1,3,4,5,6,9,10,13,15],mathbf:[1,3,4,5,6,13,15],mathcal:[2,3,5],mathemat:[0,1,4,5,9,10,12,13,15,17],mathemati:[],mathemt:4,mathrm:[0,1,2,3,4,5,6,7,8,9,10,15],matmul:[2,4],matnat:[16,17],matplotlib:[0,1,2,3,5,6,7,8,9,10,12,13,15],matric:[1,2,4,5,6,9,12,13],matrix:[1,3,4,6,8],matshow:2,matter:5,max:[1,2,5,7,8,10],max_depth:[1,7,8],max_it:[1,2,5,6,9],max_iter:0,max_leaf_nod:8,max_sampl:8,maxdegre:[1,3,8],maxdepth:8,maxim:[2,5,6,9],maximum:[0,1,2,5,6,7,8],maxpolydegre:3,mbox:[3,4],mcculloch:10,mcint:15,mcintsqr2:15,mean:[1,2,3,4,5,7,8,9,10,12,13,14],mean_absolute_error:1,mean_divisor:0,mean_i:15,mean_matrix:0,mean_squared_error:[1,3,5,8],mean_squared_log_error:1,mean_vector:0,mean_x:15,meaning:[1,5],meansquarederror:1,meant:[5,8],meantempvec:15,meanvec:15,measur:[0,1,2,3,7,9,10,15],mechan:[1,15],median:1,medicin:10,medium:6,medv:1,meet:[1,16],mehta:[1,4],memori:[9,10,13],mention:[0,1,5,10,15],mere:1,mersienn:15,meshgrid:[1,4,6,7,8,9],met:[1,6],meteorolog:7,method:[0,1,2,4,6,9,10,12,13,14,17],metric:[0,1,2,3,5,7,8],metropoli:12,mev:[1,15],mglearn:12,mgrid:5,mhjensen:[1,2,6,9],microsoft:17,mid:2,midpoint:7,might:[1,2,5,7],mild:7,miller:15,million:1,mimic:10,min:[1,4,6,7],min_:[0,1,4],min_samples_leaf:7,mind:[0,1,5],mine:12,mini:[2,5,9,10],minibatch:[2,5,9],minibathc:5,minim:[0,1,2,3,4,5,6,7,8,9,10,15],minima:[1,2,5],minimum:[1,2,3,5,6,7,9],minkowski:0,minmaxscal:1,minor:15,minst:2,minu:5,mirror:7,misclassif:[6,7,8],misclassifi:[6,8],mismatch:2,miss:[1,8],mit:17,mix:2,mkdir:[1,3,5,7],mlab:[3,15],mle:5,mlp:2,mlpclassifi:2,mlpregressor:1,mnist:[2,9],mod:15,mode:[14,15],model:[0,3,4,5,6,7,8,9,12,15,17],model_select:[1,2,3,5,7,8,9],moder:8,modern:[1,3,5,12],modif:10,modifi:[1,2,4,5,6,8,10],modul:[1,3,5,7,8,9,13],modular:15,modulenotfounderror:7,modulo:15,moe:[4,9],moment:3,monoton:[10,15],mont:[1,3,12,15,17],montecarlocycl:15,more:[1,2,3,4,6,7,8,9,10,12,14,15],moreov:1,morten:16,most:[0,1,2,3,4,5,6,7,8,9,10,12,15],mostli:[2,9],motion:1,motiv:2,move:[0,1,5,7,10,15],mpl:[1,5],mpl_toolkit:5,mplot3d:5,mplregressor:2,mse:[1,3,4,7,8],mse_simpletre:8,msg:1,msle:1,mt19937_64:15,mu0:15,mu1:15,mu2:15,mu_:15,mu_n:9,mu_x:15,much:[1,2,3,5,6,7,8,9,10,13,15],multi:[1,2,5,12],multiclass:[2,5],multidimension:[9,10],multilay:2,multinomi:5,multipl:[3,5,10,15],multipli:[4,5,9,13,15],multiplum:6,multitud:[],multivari:[1,8,9,12,15],multivariate_norm:[0,9],murphi:[9,17],must:[0,2,3,5,6,8,10,15],mutat:5,mutual:[2,3,5],mx_:15,myriad:[1,12],mz1:15,mz2:15,n_0:[10,15],n_b:15,n_boostrap:[3,8],n_bootstrap:3,n_categori:2,n_cluster:0,n_compon:9,n_epoch:5,n_estim:8,n_featur:2,n_hidden_neuron:[1,2],n_i:15,n_input:2,n_instanc:7,n_iter_i:9,n_job:8,n_k:0,n_l:[10,15],n_layer:2,n_m:7,n_neuron:2,n_neurons_layer1:2,n_neurons_layer2:2,n_point:0,n_sampl:[0,3,6,7,8],n_split:3,nabla:[2,5],nabla_:5,naimi:1,naiv:[0,5],nall:1,name:[0,1,2,3,5,6,7,8,10,12,13,16],nameerror:8,namespac:15,nation:2,nativ:12,natur:[1,2,5,6,7,10,15,17],navier:10,nb_:13,nbconvert:[],nboot:15,nearest:[2,9],nearli:5,neat:[],neccesari:3,necessari:[0,1,2,6],necessarili:[1,9,15],neck:5,need:[0,1,2,3,4,5,6,7,8,9,10,13,15],neg:[1,2,3,5,8,15],neg_mean_squared_error:3,neglect:15,neglig:15,neighbor:9,neq:[0,5,15],nervou:10,nest:[7,10],net:10,netlib:13,network:[1,7,12,14,17],neural:[1,5,12,14,17],neural_network:[1,2],neuralnetwork:2,neuron:[2,10],neutral:1,neutron:1,never:[2,3,7,15],new_hobbit:[],new_sig:3,newaxi:[1,3,7],newli:1,newton:[2,6,15],next:[0,1,2,5,6,7,15],next_guess:5,nian:16,nice:[0,1,2,9],nichola:16,nicholaskarlsen1102:16,niter:5,nitric:1,nlambda:3,nm_n:1,nmse:3,nn_model:2,node:[2,7,8,10],nois:[1,3,5,6,7,8],noisi:[2,3],non:[0,1,2,3,4,5,7,8,9,10,13,15],none:[0,1,2,3,5,7,8,15],nonetheless:0,nonlinear:[3,6,7,9,10],nonneg:[3,5,7],nonparametr:3,nonsens:15,nonsingular:13,nonumb:[5,6,13],nor:2,norm:[1,2,3,4,5,6,9],normal:[3,4,5,6,7,8,9,10,12,13],normali:13,normpdf:3,notat:[0,1,3,15],note:[0,1,2,3,4,5,6,9,10,12,13,14,15,17],notebook:[0,1,2,7,12],noth:[0,2,4,6,10,15],notic:[10,13,15],novel:[3,8],novemb:2,now:[0,1,3,4,5,6,8,9,10,13,15],nowadai:[1,2,7,12],nox:1,np_assign_points_to_clust:0,np_get_distances_to_clust:0,np_k_mean:0,nsampl:3,nspin:15,nthi:1,nuclear:4,nuclei:[1,15],nucleon:1,nucleu:1,num_tre:8,number:[0,2,3,4,5,6,7,8,9,10,13,14,16],numberid:5,numer:[1,3,4,5,7,8,9,10,12,13,17],numpi:[0,1,2,3,4,5,6,7,8,9,10,12,15],obei:[5,9],object:[1,2,3,6,8,13],observ:[0,2,3,4,5,6,7,8,9,10],obtain:[0,1,2,3,4,5,6,7,8,10,13,15],obviou:[4,9,15],obviouli:1,obvious:[1,13],occupi:1,occur:[1,6,7,15],odd:[1,5],off:[2,3,7,15],offend:[],offer:[3,9,12,13,14],offic:16,offici:14,ofil:15,ofstream:15,often:[0,1,2,3,4,5,6,7,8,9,10,12,13,15],ofter:13,old:[2,5,8],omit:1,onc:[0,2,3,7,9,15],one:[0,1,2,3,4,6,7,8,9,12,13,15],onehot:2,onehot_vector:2,onehotencod:7,ones:[1,4,5,6,7,8,9,13],onli:[0,1,2,3,4,5,6,7,8,9,10,13,15],onlin:[9,14],onto:9,open:[1,2,3,5,7,12,14,15],oper:[1,2,3,4,8,9,10,12,13,15],operation:15,opinion:0,oplu:15,opmiz:5,opportun:1,opposit:[2,6],opt:[1,2,3,6,9],optim:[0,1,3,4,7,8,9,14],optimis:2,option:[2,6,9],optmiz:[2,6],orang:1,order:[1,2,3,4,5,6,7,8,9,10,13,15],ordinari:[1,3,4,5,9,12,14],oreilli:17,org:[9,12,13,17],organ:[0,3,5,8,13],orient:[2,3,15],origin:[1,3,6,9,10,13,15],orthogn:4,orthogon:[1,4,5,6,9,13],orthonorm:4,oscar:2,oslo:[1,14,16],osx:[1,12],other:[0,1,2,3,4,5,6,8,12,13,14,17],otherwis:[1,2,5],ouput:[5,10],our:[2,3,4,6,7,8,10,12,13],ourselv:[0,1,4,5,6,9],out:[0,1,2,3,5,6,7,8,9,10,12,13,15],out_fil:7,outcom:[1,5,7,8,10,15],outdoor:7,outer:10,outfilenam:15,outlier:[1,6],outlin:[3,8,9],outlook:7,outperform:8,output:[1,2,5,6,7,8,10,13],output_bia:2,output_bias_gradi:2,output_weight:2,output_weights_gradi:2,outputlayer1:10,outputlayer2:10,over:[0,1,2,3,5,7,8,10,15],overal:[2,8],overcast:7,overcom:10,overdetermin:1,overfit:[2,3,7,8],overflow:2,overhead:10,overlap:[5,6,7],overlin:[0,3,4,7,8,9,13],overst:1,overview:[0,17],own:[5,6,10,12,13],owner:1,oxid:1,oyvinssc:16,p_i:15,p_j:15,p_n:15,p_x:15,pack:1,packag:[1,2,3,4,5,6,9,12,15],page:[1,12],pai:[2,7],painless:[],pair:[1,7,12,15],panda:[1,3,4,5,7,9,12],panel:[],paper:2,paradigm:1,parallel:[8,13],paramet:[1,2,3,4,5,6,7,8,10,15],parameter:[1,8],parametr:[1,3],park:15,part:[0,1,2,3,4,8,13,14,15,17],partial:[1,2,4,5,6,8,9,10,15],particip:[12,14],particl:[1,15],particular:[1,2,3,4,5,7,8,9,10,15,17],particularli:[3,4,5,6,9,15],partit:[2,7],pass:[0,10,15],past:[8,15],patch:[3,15],path:[1,3,5,7,12],patient:5,pattern:[1,10,14,17],pauli:1,pca:[1,5,12,14],pdf:[1,3,7,17],pedagog:1,penalti:[3,5],pentagon:5,peopl:[1,2,7,12],per:[1,2,3,14],percentag:[1,8,9],perceptron:[1,2,5],peregrin:[],perfect:[1,2],perfectli:3,perform:[0,1,3,5,6,8,9,10,12,13,15],perhap:[1,4,5],perimet:2,period:2,permut:9,person:[5,14,16],perspect:17,pertin:10,petal:[6,7],peter:17,petersen:15,phantom:15,phase:10,phatak:0,phenomena:15,phi:6,phi_k:6,philip:16,philosophi:5,phone:16,phrase:1,physic:[1,2,5,10,15,16,17],pick:[0,2,5,7,8,9,15],pickl:2,pictur:1,pie:12,piec:[0,9],pillow:[1,12],pip3:[1,2],pip:[1,2,12],pipelin:[1,3,6,8],pippin:[],pise:0,pitt:10,pixel:2,pixel_height:2,pixel_width:2,place:[1,3,5,6,13],plai:[1,3,6,9,12],plain:[5,6,8,10],plan:[3,7,16,17],plane:[6,7],plateau:15,platform:12,plausibl:10,pleas:[1,9],plenti:2,plethora:10,plot:[0,1,2,3,5,6,7,8,9,10,12,13,15],plot_confusion_matrix:[5,8],plot_cumulative_gain:[5,8],plot_data:2,plot_dataset:6,plot_decision_boundari:[7,8],plot_import:8,plot_predict:6,plot_regression_predict:7,plot_roc:[5,8],plot_surfac:5,plot_train:7,plot_tre:[7,8],plt:[0,1,2,3,5,6,7,8,9,10,13,15],plu:[1,5],png:[1,3,5,7],point:[0,1,2,3,5,6,7,8,9,13,15,16],points_in_clust:0,poisson:12,poli:[3,6],poly100_kernel_svm_clf:6,poly3:1,poly3_plot:1,poly_featur:[6,7],poly_features10:7,poly_fit10:7,poly_fit:7,poly_kernel_svm_clf:6,polydegre:[3,8],polygon:5,polym:10,polynomi:[1,3,4,5,6,7,8,9],polynomial_featur:3,polynomial_svm_clf:6,polynomialfeatur:[1,3,6,7],polytrop:[1,3],poor:[2,5],popul:1,popular:[1,2,3,5,6,7,9,10,12,13,15],popularli:1,portabl:8,portion:9,pose:[1,9,15],posit:[0,1,2,4,5,6,8,9,13,15],possibl:[1,2,3,5,6,7,8,9,10,12,13,15,16],postpon:1,potenti:[1,10],pott:10,power:[1,2,3,4,6,7,10],practic:[1,3,5,6,15],practition:[1,2],preced:[2,9,10,15],preceq:6,precis:[1,4,9,13,15],pred:3,predict:[1,2,3,5,6,7,8,12,17],predict_prob:2,predict_proba:[5,8],predictor:[1,4,5,7,8,9],prefer:[1,2,6,7,9,12],prepar:1,preprocess:[3,5,6,7,8,9],prerequisit:1,present:[1,7,10,15],preserv:9,press:[5,17],pretrain:2,pretti:[1,6,7,12],prev_centroid:0,prevent:15,previou:[1,2,4,5,6,8,9,10,13,15],previous:[0,7,8,15],price:[1,7],primal:6,primari:[1,5],primarili:0,prime:15,princip:[1,5,12,14],principl:[0,1,3,5,6],print:[0,1,2,3,4,5,6,7,8,9,13,15],print_funct:[6,7],printout:1,prior:[1,3],privat:1,prob:[2,15],probabilist:[1,17],probabl:[1,2,3,5,8,12],problem:[1,3,4,6,7,8,9,10,12,13,14,15],proce:[1,5,6,7,8,9,13],procedur:[3,4,5,6,8,9],proceed:13,process:[0,1,3,5,7,8,10,12,13,15,17],prod:17,prod_:[2,5],produc:[0,1,4,7,8,9,10,12,13,15],product:[1,2,3,5,6,10,12,13],profess:1,profil:0,program:[0,1,2,4,6,10,12,13,14,15],programm:13,progress:[0,2],progression_plot:0,prohibit:3,project:[1,2,5,9,12,14,15,16],project_root_dir:[1,3,5,7],promin:10,promis:6,prone:7,pronounc:12,proof:[1,5,9,10],prop:3,proper:[1,3],properli:[0,2,6,8],properti:[1,2,3,4,5,10,13],proport:[1,2,7,9,15],propos:[2,8],propto:5,proton:1,prove:5,provid:[1,2,3,4,5,6,7,8,10,12,13,15,17],proxi:2,prun:0,prune:7,pseudorandom:15,psycholog:1,ptratio:1,punish:[1,2],pure:[7,15],purest:7,puriti:7,purpos:[0,1,8,10],put:2,pycod:[],pydata:12,pydot:7,pyhton2:[],pylab:[1,5],pypi:12,pyplot:[0,1,2,3,5,6,7,8,9,10,13,15],pythagora:0,python2:1,python3:[1,2,3,6,9,12],python:[2,6,9,10,14],pytorch:[1,12],qquad:[9,13],quad:[2,5,13],quadrat:[1,5,6,7],qualit:[7,15],qualiti:[1,7,12],quantifi:2,quantil:8,quantit:[1,3,7],quantiti:[0,1,3,4,5,7,8,9,10,13,15],quantum:10,quartil:1,queri:7,question:[1,3,5,7,9,10],quick:15,quickli:[2,5,7,9],quirk:0,quit:[2,3,7,8,10],quot:15,r2_score:1,r2score:1,r_1:7,r_2:7,r_j:7,r_m:7,rad:1,radial:[1,6,10],radioact:15,radiu:[1,2],rain:7,rais:3,ramp:2,ran1:15,ran2:15,ran3:15,rand:[1,3,5,7,8,13,15],rand_max:15,randint:[3,5,7],randn:[1,2,3,5,7,9],random:[0,1,2,3,4,5,6,7,12,13,14],random_devic:15,random_forest_model:8,random_index:5,random_indic:2,random_st:[1,5,6,7,8,9],randomforestclassifi:8,randomli:[0,2,3,5,7,15],randomnumbergener:15,rang:[0,1,2,3,4,5,7,8,9,10,13,15],rangl:[1,9,15],rangle_x:15,rank:4,raphson:[2,6],rapidli:1,rare:2,rate:[1,2,5,6,7,8,10],rather:[1,2,3,4,5,6,7,8,9,10,13,15],ratio:[5,7,8,9],rational:1,ravel:[1,3,4,5,6,7,8,9],raw:15,rbf:[6,9,10],rbf_kernel_svm_clf:6,rbf_pca:9,rcond:1,rcparam:[1,2,5,6,7,8,15],reach:[0,1,2,3,5,7,8,9,10,15],read:[0,1,3,5,6,9,10,13,14,15,17],read_csv:[1,3,5,7],read_fwf:1,readabl:0,reader:[1,13,15],readi:[0,1,2,6,8,9,10,13],readili:2,real:[1,2,3,4,5,8,9,10,13],realist:6,realiti:15,realiz:[2,10],realli:2,reason:[0,1,2,5,8,17],reassign:2,recal:[3,4,5,7,8,9,10,13,15],recalcul:15,receiv:[2,8,10,15],recent:[1,3,5,7,8],recept:10,recip:[1,5,13],recogn:[1,8],recognit:[1,2,10,14,17],recommend:[1,4,6,12,13,14,15,17],reconsid:7,reconstruct:9,record:[8,14],recreat:15,rectangl:[3,5,7],rectifi:[2,10],recur:[1,12],recurr:[2,12,14],recurs:[7,12,13],recycl:15,red:[1,3,6,7],redefin:[1,8],reduc:[2,4,5,7,8,9],reduct:[1,8,9,12,15],refer:[0,1,2,3,4,5,9,10,13,17],refin:10,refit:3,reflect:[1,2,15],refresh:[12,14],reg:[8,9],regard:[2,5,7],regardless:10,region:[7,10],regist:15,regr_1:[1,7],regr_2:[1,7],regr_3:[1,7],regress:[2,3,6,9,10,12,14],regressor:[1,5,8],regular:[1,5,7],reilli:[1,17],reinforc:[1,6,12],reiter:2,rel:[1,3,5,7,10,15],relat:[0,1,2,5,9,13,15],relationship:[1,7],relativeerror:1,releas:[2,12],relev:[1,2,4,5,9,12,15],reli:[1,6],reliabl:[5,15],remain:[2,3,10,13,15],remaind:15,remark:2,rememb:[1,6,13],remind:[1,4,9,13,15],remov:[1,4],render:1,reorder:5,reorgan:1,repeat:[0,1,2,3,5,7,8,9,13,15],repeated:1,repeatedli:[3,8,15],repetit:[3,14],rephras:5,replac:[0,1,2,3,5,8,10],replica:3,repositori:1,repres:[1,2,3,5,6,7,8,10,15],represent:[1,2,3,15],reproduc:[1,7,10,12,15],repuls:1,request:1,requir:[1,2,3,4,5,6,7,9,10,13],resampl:[1,5,8,12,14,15],rescal:[1,9,10],research:[1,12,17],resembl:[3,15],reserv:[2,3,15],reset:15,reshap:[0,1,2,3,6,7,8],residenti:1,residu:[1,5],respect:[0,1,2,3,4,5,6,8,9,10,15],respond:10,respons:[1,5,7,10],rest:[1,4],restat:[1,10],restrict:[1,7,10],result:[0,1,2,3,4,5,6,7,8,9,10,12,13,15],ret:3,retail:1,retain:[3,4],return_data:0,return_x_i:7,reus:2,reveal:[1,10],revers:2,review:[12,13],revisit:0,reward:1,rewrit:[1,3,4,5,6,8,9,10,13,15],rewritten:[3,4,6,8,15],rewrot:5,rgoj5yh7evk:12,rho:[1,8],rho_1:8,rho_2:8,rho_m:8,rich:1,rid:0,ride:7,rideclass:7,ridedata:7,ridg:[1,3,9,12,14],right:[1,2,3,4,5,6,7,8,10,13,15],rightarrow:[1,2,4,5,6,9,10,15],rigor:1,rise:1,risk:[1,5],river:1,rmse:1,rmsprop:2,rnd_clf:8,rnn:10,rntrick1:15,rntrick2:15,rntrick3:15,rntrick4:15,robert:17,robust:1,robustscal:1,roc:8,role:[1,3,4,6,12],room:[1,16],root:[1,5,7,15],rot:[],rotat:[2,6,7,8],rotation_matrix:7,roughli:2,round:[1,5,7],routin:[5,13],row:[1,2,3,4,7,9,13],rrr:4,rug:5,rule:[1,2],run:[0,1,2,3,4,5,6,7,9,12],runtim:[0,2,3],runtimewarn:2,rust:[1,12,13],rvert:2,rvert_2:2,rwidth:3,s_i:5,saddl:5,safe:15,sai:[0,1,2,3,4,5,6,7,8,9,10,13,15],said:[3,5,7],sake:[1,4,5,9],sale:1,sam:[],same:[0,1,2,3,4,5,6,7,9,10,13,15],samm:8,sampl:[0,1,2,3,4,5,6,7,8,12,13],sample_vari:0,sampleexptvari:15,samwis:[],sanitize_sequ:3,sastri:9,satisfactori:1,satisfi:[2,3,5,6,13,15],satur:[2,3],save:[1,3,5,7],save_fig:[1,3,5,7,8],savefig:[1,3,5,7,15],scalabl:8,scalar:[3,8],scale:[1,2,4,5,6,7,8,9,10,12,16],scaler:[1,5,6,7,8,9],scan:5,scatter:[0,1,2,3,5,6,7],scenario:5,scheme:[2,5],schrage:15,scienc:[1,2,5,8,10,12,14,15,17],scientif:[1,12],scientist:[0,1],scikit:[6,7,8,12,13,14,17],scikitlearn:1,scikitplot:[5,8],scipi:[1,4,5,12,13],score:[1,2,3,5,7,8,9,16],scores_kfold:3,scratch:2,sdg:5,seaborn:[1,2,5],seamless:[1,12],search:[1,2,5,7],sec:3,second:[0,1,3,5,6,7,9,10,12,13,15],secondeigvector:9,secondli:10,section:[0,9,11,13,14,15],sector:1,see:[0,1,2,3,4,5,6,8,9,10,12,13,14,15],seed:[0,1,2,3,5,6,7,9,15],seek:[2,6],seem:2,seemingli:1,seen:[1,2,8,10,15],segment:5,seldomli:1,select:[2,3,4,6,7,8,9,14,17],self:[2,3,15,17],semest:[5,14],semi:[5,6],send:[10,16],senior:14,sens:[1,3,6],sensit:[1,3,7],sentenc:10,separ:[0,1,2,3,6,7,10,12,15],sequenc:[0,5,7,8,10,12,13,15],sequenti:[2,8,10,15],seri:[1,2,5,8,9,10,13,14],serif:[1,5,15],serv:[1,2,5,17],session:[2,14],set:[0,2,3,4,5,6,8,9,12,13,15],set_:3,set_label:3,set_tick:[2,6],set_ticklabel:2,set_titl:[0,1,2,5,10],set_xlabel:[1,2,5,10],set_xlim:[5,10],set_xticklabel:2,set_ylabel:[1,2,5],set_ylim:[5,10],set_ytick:5,set_yticklabel:2,setiosflag:15,setminu:3,setosa:[6,7],setosa_or_versicolor:6,setp:3,setprecis:15,setup:[2,6,12],setw:15,sever:[1,3,4,5,6,7,9,10,12,13,14,15],sgd:2,sgd_clf:6,sgdclassifi:6,sgdreg:5,sgdregressor:5,shape:[0,1,2,3,4,5,6,7,8,9,13],share:2,she:5,shift:[2,10,15],shire:[],shortcom:5,shorter:15,shorthand:[],shortli:13,should:[0,1,3,4,6,7,9,10,13],show:[0,1,2,3,4,5,6,7,8,9,10,13,15],shown:[5,6,9,10,15],showpoint:15,shrink:[4,6,9],shrinkag:4,shrunk:9,shuffl:[2,3],side:[1,5,6,10,13],sigh:12,sigma0:15,sigma1:15,sigma2:15,sigma:[1,2,3,4,5,8,9,10,13,15],sigma_1:4,sigma_2:4,sigma_:[4,13,15],sigma_fn:[5,10],sigma_i:[1,4],sigma_j:4,sigma_m:15,sigma_n:[9,15],sigma_x:15,sigmoid:[2,5,6,8,10],sigmundson:16,sign:[2,5,6,8,15],signal:[2,8,10],signific:2,significantli:[2,5,15],sim:[3,15],similar:[0,1,2,3,5,6,7,8,9,12,13],similarli:[1,2,4,6,8,15],simpl:[0,2,3,4,6,8,9,10,12,13],simplepredict:8,simpler:[0,1,2,12],simplest:[0,1,2,7,8,10],simpletre:8,simpli:[1,2,3,4,6,7,8,9,10,12,13,15],simplic:[0,4,5,6,7,8,9,10],simplifi:[1,3,7,12],simplist:15,simul:[3,15],simultan:3,sin:[1,2,7,10,13],sinc:[1,2,3,4,5,6,7,8,9,13,15,17],sine:10,singl:[2,5,6,7,10,13,15],singular:[1,3,5,13],site:[1,2,3,6,9,14],situat:[1,4,5],six:15,size:[1,2,3,5,6,7,8,9,13,15],sketch:8,ski:7,skill:1,skip:9,skl:1,sklearn:[1,2,3,5,6,7,8,9],skplt:[5,8],slack:6,slice:13,slide:[1,15],slight:3,slightli:[2,3,4,8,15],slope:[6,9,10],slow:[1,5,6],slower:[4,13],slowli:10,slp:2,small:[0,1,2,3,4,5,6,7,8,9,10,12,13,15],smaller:[1,2,3,5,6,7,9,15],smallest:[0,1],smallest_row_index:0,smart:3,smooth:[1,5],sne:9,sneak:1,sns:[1,2,5],soar:3,social:1,soft:[2,5,8,10],soften:6,softmax:5,softwar:[1,6,12,13,14],sol:6,sole:1,solid:[1,5],solut:[1,2,3,4,5,6,8,9,13,15],solv:[1,2,4,6,8,9,10,13],solver:[5,6,7,8,9,13],some:[0,1,2,3,4,6,7,8,9,10,13,15],someth:[1,2,5,7,9,15],sometim:[0,1,2,9,10],soon:13,sophist:1,sopt:5,sort:[1,3,4,7,9,15],sourc:[0,1,2,3,12,13,15],space:[0,1,2,4,5,6,7,9,10,15],span:[1,4,7,9,13],spare:2,spars:13,sparse_mtx:13,sparsiti:8,spatial:[2,10],speak:15,special:[3,5,8,10,13,15],specif:[1,2,3,4,5,6,7,9,10,12,13,15],specifi:[0,1,3,5,7,9,15],specifici:[1,8],spectral:2,speech:[1,2,10],speed:2,spend:15,sphere:1,spite:1,spline:6,split:[0,2,3,6,7,8,9,15],splitter:[2,8],spontan:15,spread:[1,9,15],springer:17,sqrt:[1,3,4,5,6,8,9,15],squar:[0,1,2,3,4,5,6,7,9,12,13,15],squarederror:8,squaredeuclidean:0,squash:10,srand:15,stabl:[1,4,7,9,12],stack:3,stage:5,stai:[1,9],stand:[1,4,7,10],standard:[1,2,3,4,6,8,10,13],standardscal:[1,5,6,7,8,9],stanford:5,start:[0,1,2,3,5,6,7,8,9,10,13,15],start_tim:0,startpoint:15,stat:3,state:[0,2,4,5,6,8,9,10,12,15],statement:[1,5,13],statis:4,statist:[0,1,2,4,5,7,8,9,10,13,14,17],statu:[1,5,9],std:[3,15],stdev:15,steep:5,step:[0,1,2,7,8,9,10,13,15],step_fn:[5,10],step_length:5,steps_list:7,stian:16,still:[3,4,5,9,15],stimuli:10,stk2100:17,stk4021:17,stk4051:17,stk5000:17,stk:17,stochast:[1,2,3,6,9,10],stoke:10,stone:[1,5],stop:[0,2,7,9,15],storag:4,store:[1,2,5,9,15],str:2,straight:[1,3,5,6],straightforward:[1,3,5,6,7,8,13],strategi:[1,2,7],stratifi:3,strength:[0,4],stretch:9,strict:[5,6],strictli:[5,6],string:[2,15],stroke:5,strong:[7,8,10,15],strongli:[1,6,12,13],stronli:1,structur:[0,1,2,3,7,8,10,12],stuck:[2,5],student:[1,14,16,17],studi:[0,1,5,6,9,10,12,17],studier:17,style:[1,5,7],sub:[7,10],subdivid:[1,13],subfield:1,subject:[6,15],subplot:[0,1,2,3,5,6,7,8],subplots_adjust:[6,15],subprogram:13,subroutin:1,subscript:2,subsequ:[2,3,10,13,15],subset:[2,3,5,7,10,12],subspac:[1,6,9],substanti:[7,8],substep:9,substitut:[3,10,13],subsubset:7,subtl:2,subtract:[3,4,9,13,15],subtre:7,succeed:1,success:[5,7,15],successfulli:7,sucess:15,sudo:[1,12],suffer:[1,2,4,8],suffici:[2,3,5,6,9],suggest:[2,5,17],suit:[6,10],suitabl:[1,15],sum:[0,1,2,3,4,5,6,7,8,9,10,15],sum_:[0,1,2,3,4,5,6,7,8,9,10,13,15],sum_i:[3,4,5,6],sum_k:[6,10,13],summar:[0,3,7],summari:[0,2,8,14],summat:4,sunni:7,superscript:[2,10],supervis:[1,3,5,7,10,12],supplement:5,support:[1,2,7,8,9,12],suppos:[1,3,4,5,6,8,9,10,13],sure:2,surfac:1,surpris:1,surround:12,survei:1,svc:[6,7,8],svd:[1,3,9],svdinv:4,svm:[6,7,8,9],svm_clf:[6,8],symbol:[2,9,12,15],symmeteri:2,symmetr:[1,4,5,6,9,10,13],sympi:[1,12],synonim:15,syntax:[2,13],syntaxerror:[2,6,13],sys:5,system:[1,2,5,7,8,10,12,13,17],systemat:[3,15],t_0:[5,7],t_1:5,t_b:8,t_i:[2,10],t_j:10,t_k:7,tabl:[7,15,16],tabul:1,tabular:[],tackl:0,tag:[0,4,5,10,13,15],taht:1,tail:15,tailor:[6,9],taiwan:1,take:[0,1,2,3,4,5,6,7,8,9,10,12,13,15],taken:[1,2,3,8,13],tangent:[2,5,10],tanh:[2,5,6,10],target:[1,2,5,6,7,8,9,10],target_nam:7,task:[0,1,2,3,7,9,10],tau:15,tax:1,taylor:5,taylornr:5,team:2,teaser:1,technic:[0,1],techniqu:[1,2,6,8,12,15,17],technolog:[1,2],tek5040:17,tell:[3,5,8,9,15],temp1:2,temp2:2,temp:2,temperatur:[1,7],temporarili:2,ten:[],tend:[0,3,6,7,8,10],tendenc:1,tension:3,tensorflow:[0,1,6,12,13,14,17],term1:[1,4,9],term2:[1,4,9],term3:[1,4,9],term4:[1,4,9],term:[0,1,2,3,4,5,6,7,8,9,10,15],termin:[1,4,7,8],test:[3,4,5,6,7,8,15],test_accuraci:2,test_data:0,test_ind:3,test_pr:2,test_predict:2,test_scor:[5,8],test_siz:[1,2,3,8],test_split:7,testerror:3,text:[1,2,5,6,7,9,13,15,17],textual:7,textur:2,than:[1,2,3,4,7,8,9,10,12,15],thats:0,theano:[2,12],thei:[0,1,2,3,4,5,6,7,9,10,13,15],them:[1,2,5,6,7,8,9,10,13],theme:1,themselv:[1,15],thenc:3,theorem:[3,4,5],theoret:[1,8],theori:[1,2,5,6,7,10,12,17],thereaft:[1,3,4,9,10,13],therebi:[1,5,9,15],therefor:[1,2,3,5,6,9,15],therein:9,thereof:[1,3,5],theta:[2,3,5,15],theta_:2,theta_i:2,theta_k:15,theta_linreg:5,thi:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,17],thing:[0,1,2,5,7,15],think:[0,1,2,3,5,7,10,15],third:[1,5],thirti:5,thorough:0,those:[0,4,6,7,8,9,13,14],though:[2,13,15],thought:[0,3,15],thousand:[1,2],three:[1,2,3,6,7,10,13,14,16],threshold:[2,5,7,8,9,10],through:[0,1,2,4,5,6,9,10,12,13,15],throughout:[0,1,12,13,15],thu:[1,2,3,4,5,6,8,9,10,15,16],thumb:1,thursdai:14,tibshirani:[14,17],ticker:[5,15],tight_layout:[2,5],tightli:9,tild:[1,3,4,9,15],till:[1,5,6,7,8,10,13],time:[0,1,2,3,4,5,6,7,8,9,10,13,14,15],timefunct:15,tini:2,tip:11,titl:[1,2,3,5,6,7,8,15],to_categor:2,to_categorical_numpi:2,to_numer:[1,3],to_str:15,togeth:[1,6,9],toi:0,toler:0,tomographi:10,too:[1,3,4,5,7,9,15,17],took:6,tool:[0,1,2,3,12,15],toolbox:6,top:[1,3,7,8,12],topic:[0,1,5,6,12,17],topolog:[2,10],toss:8,total:[0,1,2,3,5,6,8,9,10,15,16],totalclustervari:0,totalscatt:0,totalvari:15,toward:[2,5,10],town:1,tpng:7,traceback:[3,5,7,8],track:[0,5,13],tract:1,tractabl:1,trade:[3,7],tradeoff:[1,4,14],tradit:[1,2,3],train:[3,5,6,7,8,9,10],train_accuraci:[1,2],train_end:2,train_ind:3,train_pr:2,train_siz:2,train_test_split:[1,2,3,5,7,8,9],train_test_split_numpi:2,trainingerror:3,trait:1,transfer:7,transform:[1,3,4,5,6,7,8,9,10,12,13],transit:10,translat:[2,8],transpos:[2,4,9],treat:[1,2,3,5,10,15],tree:[1,2,12,14],tree_clf:[7,8],tree_clf_:7,tree_clf_sr:7,tree_reg1:7,tree_reg2:7,tree_reg:7,trend:15,trevor:17,tri:7,trial:[1,3,5,15],triangl:5,triangular:13,trick:[6,9,15],trickier:15,tridiagon:13,trillion:12,trivial:[1,2,9,15],troubl:[1,6,10],true_divid:2,true_fun:3,tucker:6,tumor:[5,7],tumour:5,tunabl:2,tune:[7,13],turn:[1,2,3,4,5,6,7,8,9,10,13,15],tutori:2,tweak:[2,8,15],twice:5,twist:9,twister:15,two:[0,1,2,3,4,5,7,8,9,10,13,14,15,17],tx_1:5,type:[1,2,3,5,6,8,13,15],typeerror:[],typic:[1,2,4,5,7,8,10,15],u_i:10,u_m:8,ubuntu:[1,12],uci:1,uio:[16,17],unari:13,unbalanc:[3,7],unbias:[1,3,15],uncertainti:1,uncertitud:15,unchang:2,uncorrel:8,undefin:4,under:[1,2,3,5,8,12],underdetermin:1,underfit:[2,3],undergradu:14,underli:[1,2,5,7,15],underset:0,understand:[0,1,2,5,8,12],understood:[0,6],undesir:6,undetermin:6,unexpect:[3,15],unexpected:15,unfortun:[2,6,7,8],unicode_liter:[6,7],uniform:[1,2,4,5,9],uniform_real_distribut:15,uniformli:[5,15],unifrompdf:15,unimport:5,union:3,uniqu:[0,1,3,5,13],unique_cluster_label:0,unit:[1,2,8,10,15],unitari:[4,13],unitarili:13,uniti:15,univari:15,univers:[1,2,5,14,16],unix:2,unknow:[1,13],unknown:[1,2,3,6,8,13],unknowwn:10,unlabel:2,unless:[1,3,5,9],unlik:[2,5,6,15],unnecessarili:7,unravel:2,unrol:9,unseen:[5,7],unstabl:2,unsupervis:[1,2,10,12,14],unsymmetr:13,until:[0,2,5,7,10,15],unusu:10,updat:[0,2,3,8,10],upload:[12,17],upon:[2,9,13],upper:[1,6,7,13],uppercas:[13,15],ups:[],usag:[1,6,12,15],usd10000:1,usd:1,use:[0,1,3,4,5,6,7,8,9,10,12,13,14],usecol:1,used:[0,1,2,3,4,6,7,8,9,10,12,13,15,17],useful:[1,2,3,5,7,9,10,12,13,15,17],useless:2,user:[1,2,5,6,9,12,13],uses:[1,2,3,4,7,9,10,13,15],usetex:15,using:[0,2,3,4,6,7,8,9,10,13],usr:15,usual:[0,1,5,10],util:[0,2,3,5,8],v_0:9,valid:[1,2,5,7,8,12,14,15],valu:[0,1,2,3,5,6,7,8,10,12,13],valuat:7,valueerror:[],van:[1,4],vandenbergh:[5,6],vandermond:1,vanilla:9,vanish:[2,5,15],var_x:15,varabl:6,varepsilon:3,varepsilon_:3,varepsilon_i:3,vari:[1,2,3,8],variabl:[0,1,2,3,6,8,9,10,13],varianc:[0,1,2,4,5,7,8,9,12,13,14],variance_i:[4,9],variance_x:[4,9],variant:[1,2,3,5,6,10],variat:9,varieti:[1,10,12],variou:[2,4,5,6,7,9,10,12,13,15],vartempvec:15,varvec:15,vaue:2,vdot:5,vec:[3,15],vector:[0,1,2,3,4,5,7,8,9,12],vector_mean:0,ventur:[1,6,12],verbos:2,veri:[0,1,2,3,5,6,7,8,9,10,15,17],verifi:[9,13],versatil:6,versicolor:[6,7],version:[0,1,8,12,13,15],versu:2,vert:[1,2,4,5,6,7,9],vert_1:4,vert_2:[4,9],vertic:3,via:[1,3,4,5,6,7,8,9,10,12,13,14,15],vidal:9,video:[1,2,4,5,10,12,14],view:[2,10,15,17],violat:6,virginica:7,viridi:[1,2],virtual:2,vision:1,visual:[1,9,10,12],visualis:2,viz:[6,15],vmax:2,vmc:15,vmin:2,volum:1,vote:8,voting_clf:8,votingclassifi:8,votingsimpl:8,vstack:[4,9,13,15],w_1:[6,13],w_1x_1:6,w_1x_:6,w_2:[6,13],w_2x_2:6,w_2x_:6,w_3:13,w_4:13,w_i:[2,8],w_ix_i:10,w_j:13,w_m:13,w_px_:6,w_px_p:6,wai:[0,1,2,3,4,5,6,8,9,10,11,13,15],walk:7,walker:15,wang:1,want:[0,1,2,3,5,6,7,8,9,10,12,15],warn:[1,2,6],warrant:3,watch:12,wavelet:6,weak:[0,7,8],weather:[2,10],web:[12,14],websit:[13,14],wedg:[6,15],wednesdai:14,wee:9,week:5,weekli:[12,17],weight:[1,2,3,5,7,8,10,15],welcom:[6,12],well:[1,2,3,4,5,6,7,8,10,12,13,15,17],went:6,were:[0,1,2,3,4,5,6,8,9,10,15],wessel:[1,4],what:[0,2,3,4,5,6,7,8,9,10,12,13,14],when:[0,1,2,3,4,6,7,8,9,10,13,15],whenev:15,where:[0,1,2,3,4,5,6,7,8,9,10,12,13,15,16],wherea:[3,15],wherein:[2,10],whether:[1,5,7,15],which:[0,1,3,4,5,6,7,8,9,10,12,13,14,16],whichev:2,white:7,who:[1,14],whole:[0,2,7,9],whose:[3,8,15],whow:[4,9],why:[1,2,5],wide:[1,2,3,5,10,12,13],widehat:3,width:[1,6,7],wieringen:[1,4],win:8,wind:7,wing:16,wiscons:5,wisconsin:8,wise:[1,2,4,10],wish:[0,1,5,6,9,13],within:[0,1,5,7,10,15,17],withinclust:0,without:[1,2,4,5,6,7,9,10],won:1,wonder:6,word:[0,1,2,15],work:[0,1,2,3,5,6,7,12,14,15],world:[1,6],worldwid:1,wors:[1,2,3],worth:7,would:[1,2,3,5,6,7,8,9,10,13,15],wrap:13,write:[1,2,5,6,10,11,13,14,15],written:[1,4,5,9,10,12,13,15],wrong:[2,6],wrongli:[8,15],wrote:[4,9],wrt:8,wth:8,www:[12,13,17],wx_1:6,x0s:6,x1_exampl:6,x1d:6,x1s:[6,7,8],x2d:[6,9],x2d_train:9,x2dsl:9,x2s:[6,7,8],x3s:6,x_0:[1,4,9,13],x_1:[1,3,4,5,6,7,8,9,13,15],x_2:[1,3,4,5,6,7,8,9,13,15],x_3:[6,13,15],x_4:13,x_center:9,x_data:2,x_data_ful:2,x_i:[0,1,2,3,4,5,6,7,8,9,10,13,15],x_ix_:1,x_iy_i:6,x_j:[6,7,10,15],x_jy_j:6,x_k:[0,10,13,15],x_l:15,x_m:[10,13,15],x_n:[1,3,5,6,9,10,13,15],x_new:[7,8],x_p:[5,7],x_poli:7,x_poly10:7,x_reduc:9,x_scale:6,x_test:[1,2,3,5,7,8,9],x_test_scal:[1,5,7,8,9],x_train:[1,2,3,5,7,8,9],x_train_scal:[1,5,7,8,9],x_val:2,xarrai:12,xavier:2,xbnew:5,xcode:[1,12],xdclassiffierconfus:8,xdclassiffierroc:8,xg_clf:8,xgb:8,xgbclassifi:8,xgboost:7,xgboot:8,xgbregressor:8,xgparam:8,xgtree:8,xi_1:6,xi_:6,xi_i:6,xlabel:[1,2,3,5,6,7,8,15],xlim:[3,8],xmesh:5,xnew:[1,5],xpd:[4,9],xplot:1,xsr:7,xt_x:5,xtest:3,xtick:[3,6,7],xtrain:3,xytext:6,y_0:[1,4,9,13],y_1:[1,4,5,6,7,9,13],y_1y_1:6,y_1y_1k:6,y_1y_2:6,y_1y_2k:6,y_1y_n:6,y_1y_nk:6,y_2:[1,4,6,7,9,13],y_2y_1:6,y_2y_1k:6,y_2y_2:6,y_2y_2k:6,y_3:[1,7,13],y_4:13,y_data:[1,2],y_data_ful:2,y_decis:6,y_i:[1,2,3,4,5,6,7,8,9,10,13],y_if_:8,y_ix_:1,y_ix_i:[5,6],y_iy_jk:6,y_j:[3,6,10],y_k:10,y_m:13,y_model:1,y_n:[5,6],y_ny_1:6,y_ny_1k:6,y_ny_2:6,y_ny_2k:6,y_ny_n:6,y_ny_nk:6,y_plot:7,y_pred1:7,y_pred2:7,y_pred:[1,2,3,5,6,7,8],y_pred_rf:8,y_pred_tre:8,y_proba:[5,8],y_test:[1,2,3,5,7,8,9],y_test_onehot:2,y_test_predict:1,y_train:[1,2,3,5,7,8,9],y_train_onehot:2,y_train_predict:1,y_val:2,year:[1,12],yes:[3,5],yet:[1,2,3,6,9],yield:[0,1,3,5,6,8,10,13,15],ylabel:[1,2,3,5,6,7,8,15],ylim:3,ymesh:5,yoshua:[2,17],you:[0,1,2,3,5,6,7,8,9,12,13,15,17],young:1,your:[0,2,3,5,6,9,12,13,15],yourself:[5,9],youtub:12,ypred:3,ypredict2:5,ypredict:[1,5],yridg:1,ytest:3,ytick:[3,6,7],ytild:[1,3],ytildenp:1,ytrain:3,z_0:13,z_1:13,z_2:13,z_c:2,z_h:2,z_i:[2,10],z_j:[2,10],z_k:10,z_m:2,z_mod:7,z_o:2,zaman:15,zero:[0,1,2,3,4,5,6,7,8,9,10,13,15],zm_h:1,zone:1},titles:["11. Clustering Analysis","3. Linear Regression","13. Building a Feed Forward Neural Network","4. Resampling Methods","5. Ridge and Lasso Regression","6. Logistic Regression","7. Support Vector Machines, overarching aims","8. Decision trees, overarching aims","9. Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods","10. Basic ideas of the Principal Component Analysis (PCA)","12. Neural networks","Content in Jupyter Book","Applied Data Analysis and Machine Learning, FYS-STK3155/4155 at the University of Oslo, Norway","2. Linear Algebra, Handling of Arrays and more Python Features","Teaching schedule with links to material","1. Elements of Probability Theory and Statistical Data Analysis","Teachers and Grading","Textbooks"],titleterms:{"2021":16,"4155":12,"case":[5,6,8,15],"final":[5,10],"function":[1,2,4,5,6,8,9,10,15],"import":[13,15],And:5,Eye:8,FYS:12,The:[0,1,2,3,4,5,6,7,9,10,12,15],Useful:12,Using:5,activ:[2,10],actual:15,adaboost:8,adapt:8,adjust:2,again:7,aim:[6,7],algebra:13,algorithm:[0,4,7,8,9,10],algortithm:5,all:6,analysi:[0,1,9,12,15],ani:5,anoth:7,appli:12,approach:[1,5,6],approxim:10,architectur:2,arrai:13,assist:16,august:14,autocorrel:15,back:[2,9,10],background:12,bag:8,basic:[0,1,5,7,8,9,13],batch:2,befor:9,better:[4,6,15],bia:3,binari:2,binomi:15,bird:8,block:15,book:11,boost:8,bootstrap:[3,8,15],boston:1,breast:2,brief:5,bring:10,build:[2,7],calcul:15,cancer:[2,5,7,9],cart:7,central:[5,12,15],chain:10,chang:8,chi:1,choos:2,classic:9,classif:[2,7,8],classifi:6,clip:2,cluster:0,code:[0,1,2,5,7,9,10,15],collect:2,compar:8,compon:9,comput:[5,7,15],con:7,concept:15,condit:5,conjug:5,content:11,continu:15,convex:[5,6],convolut:10,correl:[4,9,15],correspond:5,cost:[2,5,8],cours:[12,17],covari:[4,9,15],cross:3,cumul:15,cython:[],data:[1,2,5,7,9,12,15],dataset:2,decemb:14,decis:[7,8],decomposit:[4,9,13],deep:2,defin:2,definit:15,degre:1,demonstr:15,dens:1,deriv:[5,10],descent:[5,8],develop:2,deviat:15,diagon:9,dice:15,differ:[5,6],dimension:6,disadvantag:7,discret:15,disguis:15,distribut:15,doing:2,domain:15,down:2,dropout:2,economi:4,element:[1,15],elimin:13,ensembl:8,entropi:7,environ:1,equat:[1,5,10],error:8,etc:[],evalu:2,event:15,exampl:[1,2,5,6,7,8,15],exercis:1,expect:15,experi:15,explor:1,exponenti:15,express:5,extend:5,extrem:8,fall:16,famili:2,famou:15,fantast:4,featur:[7,13],feed:[2,10],fine:2,first:[5,10],fit:[1,8],forest:8,forward:[2,10],frank:1,freedom:1,frequentist:1,fridai:5,from:[8,10],gaussian:[13,15],gener:[7,15],geometr:[5,9],gini:7,good:1,grade:16,gradient:[2,5,8],handl:13,has:12,hessian:5,homework:5,hous:1,how:15,hyperparamet:2,hyperplan:6,id3:7,idea:[0,9],ideal:5,implement:[2,15],improv:2,increment:9,index:7,inform:16,instal:12,instructor:16,interpret:[5,9],introduc:[4,9],introduct:[1,3,12,13],invers:13,iter:[5,8],its:15,jackknif:15,julia:[],jungl:8,jupyt:11,kera:2,kernel:[6,9],lagrangian:6,lasso:4,layer:[2,10],learn:[1,2,5,9,12],level:8,librari:12,likelihood:5,limit:[2,5,15],linear:[1,6,13],link:[4,9,14,17],logist:5,loss:5,machin:[1,5,6,12],main:15,make:[1,7,8],mani:[8,10],materi:14,mathemat:6,matric:[],matrix:[2,5,9,10,13,15],matter:1,mean:[0,15],meet:[8,15],mercer:6,mersenn:15,method:[3,5,7,8,15],mlp:10,model:[1,2,10],moment:15,moon:[6,7],more:[0,5,13],multilay:10,multipl:2,multipli:6,name:15,need:[],network:[2,5,10],neural:[2,10],newton:5,non:6,normal:[1,2,15],norwai:12,notat:10,novemb:14,now:[2,7],nuclear:1,nueral:5,numba:[],number:[1,15],numer:15,numpi:13,numpython:0,observ:15,obtain:9,octob:14,one:[5,10],optim:[2,5,6,12],organ:1,oslo:[12,17],other:[7,9,10,15],our:[0,1,5,9,15],outcom:12,output:15,overarch:[1,6,7],overview:8,own:[0,1,8,9],packag:13,panda:[],part:[5,12],pass:2,pca:9,pdf:15,perceptron:10,perform:[2,7],period:15,perspect:2,poisson:15,pre:2,preprocess:1,prerequisit:12,princip:9,pro:7,probabl:15,problem:[2,5],procedur:7,process:2,program:5,propag:[2,10],properti:15,pseudo:15,python:[0,1,7,12,13,15],quick:6,ran0:15,random:[8,9,15],raphson:5,read:7,recip:15,recurr:10,reduc:1,regress:[1,4,5,7,8],regular:[2,4],relev:17,relu:2,remind:[3,5,6],requir:12,resampl:3,revisit:5,ridg:[4,5],rng:15,rule:10,sampl:[9,15],schedul:14,schemat:7,scikit:[1,2,5,9],select:15,semest:16,sensit:5,septemb:[5,14],set:[1,7,10],sgd:5,should:[2,15],simpl:[1,5,7,15],singl:8,singular:[4,9],situat:15,size:4,slightli:5,soft:6,softmax:2,softwar:[],solv:5,some:5,split:1,squar:8,standard:[5,15],state:1,statist:[3,12,15],steepest:[5,8],step:[3,5],stk3155:12,stochast:[5,15],stop:5,supervis:2,support:6,svd:4,teach:[14,16],teacher:16,techniqu:9,technolog:12,tensorflow:2,test:[1,2],textbook:17,than:5,theorem:[6,9,10,15],theori:15,three:15,togeth:10,top:2,toss:15,toward:[0,9],tradeoff:3,train:[1,2],tree:[7,8],tune:2,two:[6,12],type:10,uncorrel:15,understand:4,uniform:15,univers:[10,12,17],use:[2,15],used:5,using:[1,5,15],valid:3,valu:[4,9,15],variabl:[5,15],varianc:[3,15],variou:[1,3],vector:[6,10,13],view:[1,8],visual:[2,7],wai:7,week:14,weekli:14,what:[1,15],when:5,which:[2,15],why:15,wisconsin:5,write:[0,9],xgboost:8,your:[1,8]}})
\ No newline at end of file
+Search.setIndex({docnames:["Clustering","chapter1","chapter10","chapter2","chapter3","chapter4","chapter5","chapter6","chapter7","chapter8","chapter9","content","intro","linalg","schedule","statistics","teachers","textbooks"],envversion:{"sphinx.domains.c":2,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":3,"sphinx.domains.index":1,"sphinx.domains.javascript":2,"sphinx.domains.math":2,"sphinx.domains.python":2,"sphinx.domains.rst":2,"sphinx.domains.std":1,"sphinx.ext.intersphinx":1,sphinx:56},filenames:["Clustering.ipynb","chapter1.ipynb","chapter10.ipynb","chapter2.ipynb","chapter3.ipynb","chapter4.ipynb","chapter5.ipynb","chapter6.ipynb","chapter7.ipynb","chapter8.ipynb","chapter9.ipynb","content.md","intro.md","linalg.ipynb","schedule.md","statistics.ipynb","teachers.md","textbooks.md"],objects:{},objnames:{},objtypes:{},terms:{"000":2,"000000":[1,3,9],"00000000e":[1,3],"0001":2,"00015921913736794912":7,"001":[2,5,6],"00109273":[],"00200":6,"0032873138755776365":15,"003704":1,"003717":1,"003759":1,"003774":1,"003788":1,"004":3,"00433417":9,"004456043243408203":0,"00445655":9,"0049999999999999845":[],"004999999999999996":[],"004999999999999997":[],"0050000000000000044":[],"005000000000000007":1,"00727646693":1,"007789":[],"007824":1,"0086649156":1,"008885578722629236":[],"009154":1,"009735":9,"00973536":9,"009790":1,"009883615646716182":1,"009883615646716184":[],"009883615646716186":[],"009911":1,"01057384067458835":[],"010679893512872646":[],"0110":15,"011347":1,"01210814993019007":3,"0140617":[],"01503674":3,"015037":3,"01514394":[],"015144":[],"01867234e":15,"01873344":9,"02161783e":15,"021901":9,"02190139":9,"02493044e":[],"02568378":[],"025709":9,"02625193":6,"02730126581656065":15,"02881304":[],"029688":[],"02968834":[],"030670":[],"03067028":[],"031":3,"03256632e":2,"03303359":[],"03607832":[],"03697069":[],"03707133":9,"03750367":13,"03787596148305236":1,"03791824e":15,"038300":9,"03871832":[],"04205220e":15,"04260073e":[],"04330858":[],"04421672e":[],"044402":1,"0458":7,"04757618e":[],"04829457939163212":15,"051115":3,"051649":9,"052645":3,"05318162":[],"053182":[],"05364854":6,"05396545e":[],"054187":3,"054276":3,"054674":3,"055":4,"055744":3,"055831":3,"055887":3,"055916":3,"056326":3,"056329":9,"057035":3,"057088709963637":1,"057320":3,"057332":3,"05755374":[],"057571":3,"057654":3,"057919":3,"058178":3,"058282":3,"058805":3,"059245":3,"059344":9,"059406":3,"059531":3,"059571":3,"059806":3,"059908":3,"059994":3,"060064":9,"060070":9,"060308":3,"06041458e":[],"060919":[],"061164":3,"061176":3,"061255":3,"06126507e":15,"061330":3,"061601":9,"061652":3,"061774":3,"061842":3,"061855":3,"061896":3,"06209126":[],"062188":[],"062376":[],"062639":[],"062660":9,"062822":3,"062829":[],"062879":[],"062885":3,"062923":9,"062979":[],"063097":3,"063122":3,"063178":9,"063324":9,"063395":[],"063415":3,"063615":3,"063727":3,"063759":3,"063763":3,"063882":[],"063982":[],"06412177e":15,"064304":[],"064410":3,"064472":3,"064648":9,"064686":[],"064783":9,"06492086e":1,"064964":3,"064982":3,"065":4,"065003":[],"065086":3,"065110":9,"065144":[],"065151":[],"065200":[],"065202":3,"065355":3,"065591":3,"065618":3,"065660":3,"065680":[],"065762":3,"065860":9,"065994":[],"066002":9,"06600226":9,"066030":9,"066074":9,"066092":3,"06619182206626131":[],"066294":[],"066312":9,"066389":[],"066403":9,"066487":[],"066629":3,"066683":9,"066761":[],"066788":3,"066835":3,"066837":9,"066951":9,"066963":[],"067061":3,"067123":3,"067132":9,"067175":9,"067440":9,"067531":3,"067577":3,"067601":[],"067667":9,"067685":9,"067777":3,"067844":[],"067865":[],"067892":[],"067985":3,"067990":[],"068276":3,"068351":9,"068460":3,"068514":[],"068654":3,"068697":9,"068818":9,"068838":9,"068840":[],"068920":3,"069005":[],"069028":[],"069081":[],"069098":3,"069195":9,"069243":9,"069369":[],"069413":9,"069503":[],"069516":3,"069528":[],"069641":9,"069775":9,"069814":3,"069890":[],"069902":3,"069988":9,"070129":[],"070131":[],"070138":[],"070182":3,"070254":[],"070337":9,"070456":3,"070548":9,"070762":9,"070791":9,"070812":[],"070815":[],"070867":9,"070889":9,"070967":[],"071016":[],"071049":9,"07106781e":[],"071096":3,"07110274":13,"071248":[],"0713":1,"071313":3,"071325":[],"071435":9,"07145103":9,"071481":3,"071502":[],"071547":9,"07155335":[],"071576":[],"071579":[],"07159175":[],"071660":9,"071681":[],"071684":[],"071761":[],"071887":3,"071917":[],"072094":[],"072198":3,"072424":[],"072471":3,"072555":9,"072589":[],"072620":[],"072654":9,"072710":9,"072826":[],"072879":9,"073":[],"073020":[],"073096":9,"073310":9,"073352":[],"073371":9,"073372":[],"073483":3,"073567":3,"073598":9,"073602":[],"073656":9,"073765":9,"073851":[],"073915":1,"074":[],"074027":[],"074067":9,"074134":3,"074170":[],"074191":[],"074201":9,"074230":[],"07423848370736122":3,"074286":[],"074331":9,"074453":3,"074488":3,"074568":[],"074618":9,"074848":3,"074979":9,"075084":[],"075119":[],"075194":9,"075212":3,"07521771":[],"075218":[],"075261":3,"075266":[],"075296":9,"075526":9,"075545":9,"0755452":9,"075562":3,"075615":9,"075772":3,"075821":3,"075993":9,"076062":3,"076320":[],"076367":9,"076398":3,"076408":[],"076410":9,"076466":9,"076469":3,"076730":3,"076938":9,"077010":9,"077046":9,"077143":9,"077160":3,"07729012413236423":9,"077305":9,"07744472306026946":7,"077469":[],"077533":3,"077623":[],"077771":9,"07777777777777778":2,"077891":[],"077927":9,"078049":3,"078099":9,"078103":9,"078244":9,"078311":[],"078388":[],"078693":9,"078710":9,"078746":9,"078927":3,"078930":[],"078966":[],"079001":[],"079139":[],"079365":3,"07944154":13,"079624":[],"079785":9,"079848":9,"079956":[],"080024":9,"080084":1,"080115":3,"080264":9,"080325":9,"080398":[],"080570":9,"080626":9,"080675":9,"080845":[],"081077":9,"081129":9,"081210":9,"081260":[],"081402":[],"081489":9,"081514":[],"08170444":[],"081816":[],"081886":3,"082211":9,"082225":9,"082247":9,"08248290e":[],"08251898":15,"08271336":[],"082990":[],"083128":[],"08318298e":2,"0832":[],"083295":9,"083376":[],"083577":[],"083658":9,"084092":3,"08415761":[],"084167":[],"084249":9,"084604":9,"084813":9,"084873":[],"08501147":1,"085121":9,"085285":[],"085646":9,"085676":[],"085951":[],"08611111111111111":2,"086116":[],"086592":[],"086652":9,"086974":9,"087202":9,"087482":[],"087563":9,"08839750e":1,"088871":1,"08888888888888889":2,"089425":9,"090274":9,"09103481e":15,"09166666666666666":2,"0917":7,"093755":9,"09487315108590391":9,"096726":[],"09672604":[],"09678277e":15,"09741585e":[],"09903804":6,"099763":3,"09976319":3,"100":[0,1,2,3,4,5,6,7,8,9,13,15,16],"1000":[0,1,2,5,6,9,12,15],"10000":[0,3,4,8,9,15],"100000":6,"10001":8,"1001":15,"1002":15,"1003":15,"1005":15,"1007125":1,"1009":15,"10094646e":[],"1011":15,"1013":15,"10131725":[],"1013904243":15,"1015":15,"102":1,"1022964509394572":2,"1023":15,"1026":15,"1027":15,"103":2,"1030":15,"10307631":[],"10327559":13,"1037":15,"10378326e":2,"1038":15,"1040":15,"10405456":9,"1047":15,"105137868830763":15,"10555555555555556":2,"106095":9,"108":1,"10806972":[],"108070":[],"10896672e":15,"10898112e":[],"10th":7,"10x":1,"110":1,"1100":15,"1101":15,"111":[2,5,10],"1111111111111111":2,"112283":1,"112383":9,"11304709e":15,"11388888888888889":2,"11456076e":[],"11507992e":2,"11666666666666667":2,"117":6,"11944444444444445":2,"12002944":[],"1203284":6,"121":[6,7,8],"122":[6,7,8],"12222222222222222":2,"12283463":[],"123190":1,"123459876":15,"12366979e":15,"124":1,"12497018e":1,"127773":15,"12777777777777777":2,"1298":7,"13055555555555556":2,"13060772":1,"13209041":[],"13266452e":1,"133":5,"13328820e":[],"13457922":[],"13519106":1,"13579199e":[],"1361111111111111":2,"137268":[],"137400784702912":1,"137652":9,"13803928":1,"138775":9,"139462":4,"139475":[],"1404":1,"1437":2,"1440501043841336":2,"1445":4,"14459063":[],"1446":4,"1447":4,"1448":4,"1449":4,"14662074":1,"14722222222222223":2,"147400":9,"147420":9,"147722":4,"148":4,"149366":[],"149667":[],"149894":4,"149903":[],"14g":4,"150":6,"15024669":[],"151":4,"152636":[],"1527777777777778":2,"153106":1,"15324631":1,"15332528e":[],"154720":1,"15475232":1,"154911":1,"155491":1,"155687":1,"155883":1,"156":1,"157":1,"158":1,"159":1,"15979239e":15,"15g":4,"160":1,"16111111111111112":2,"16496581e":[],"16553696":[],"16637855e":15,"16666666666666666":2,"16807":15,"16b8e3cda33a":2,"17117385":[],"17174962e":2,"17234827e":[],"17385778e":1,"1758506":1,"17654307":[],"17707436":[],"17777777777777778":2,"17953942":9,"1797":2,"180092462880674":[],"18220995":1,"18333333333333332":2,"18404906e":[],"1856411":[],"18611111111111112":2,"18620601e":1,"18673098":9,"18954529":[],"18968431e":15,"1914224774238273":[],"1940":1,"1943":10,"197":1,"1970":13,"1973":7,"197370":9,"19742904e":[],"1979":4,"1989":15,"19937":15,"19955871":[],"199559":[],"19972087e":15,"1_1":10,"1_2":10,"1_3":10,"1cm":[1,6,8,15],"1e10":0,"200":[1,6,7,8,15],"200000":1,"2004":5,"2006":17,"2010":2,"2011":2,"2015":2,"2016":1,"2018":4,"201841":3,"20184113":3,"2021":0,"20277777777777778":2,"205466494327873":[],"207545":9,"20772452":[],"20819609e":[],"20833333333333334":2,"20843563e":[],"20906175e":15,"210340":9,"212":3,"21208310e":[],"212327334149492":1,"2125":[],"2126":[],"2127":[],"2128":[],"2129":[],"213":3,"213103":9,"21347282":[],"213743":9,"214":3,"2147483647":15,"215":3,"216":3,"21623344":1,"216290":9,"216683":9,"22044605e":3,"22076362":1,"221":6,"22209371e":1,"22527008e":15,"22717936e":15,"22999784":3,"229998":3,"23117916e":15,"23333333333333334":2,"2335879":[],"23382086e":[],"23438810e":1,"24444444444444444":2,"250":[5,7],"25000":1,"250000":1,"250154":1,"25190225e":1,"25226753e":15,"25240108":[],"253":[],"25303483":[],"253775":1,"254":[],"254509":[],"25450941":[],"25457052":[],"255":[],"2551":1,"256":[],"256962":1,"257":[],"25726439e":[],"2572e3a4b38d":2,"25803281":[],"259107":[],"25910749":[],"259153":9,"2627588":13,"26381865":[],"263819":[],"264":1,"265":1,"2653678":1,"266":1,"267":1,"2683":4,"2684":4,"2685":4,"2686":4,"2687":4,"26890510e":[],"269":1,"26974938e":[],"270":1,"27296891e":[],"276263":9,"27753165e":15,"27n_":15,"280647":9,"28166741":[],"282":1,"282727":9,"28310983":3,"283110":3,"2836":15,"28475098":6,"2861":15,"2873":7,"2882":15,"2886":15,"2890":1,"2892":15,"28971976":9,"289720":9,"290":[],"291":[],"2915":15,"291614":[],"292":[],"293":[],"2931":[],"294":[],"295656121491569":[],"296247":1,"2968":[],"297219777724628":9,"297260":1,"2980":[],"298273":1,"2983233":13,"298375":1,"2990":[],"299444":9,"29944428":9,"2_1":10,"2_2":10,"2_3":10,"2_i":10,"2_m":15,"2_x":15,"2cm":6,"2ff97f4bf03b":15,"2nd":7,"2x_ix_jy_iy_j":6,"2x_j":6,"2y_i":8,"2y_j":6,"30000":1,"300162456113691":[],"30119421":6,"306854":[],"30685416":[],"30879705":1,"30968181":1,"31109204e":1,"3155":[3,4],"3156929654100207":7,"31608475e":[],"31718909":9,"31730641":[],"317367":9,"31853484":[],"31896852":6,"3200":2,"32047562":1,"323291478597321":15,"3250":2,"32521615e":15,"327631":1,"32938847":13,"32945844e":15,"3304":1,"33066907e":3,"3310":1,"3317":1,"333":5,"333333":1,"3338":1,"3344":1,"33443859e":[],"33544681":[],"33569998e":1,"33861512":[],"339535706819584":15,"33953571":15,"340782":9,"34114641e":1,"34172919":[],"3436":1,"3437":1,"344172":1,"346433":9,"34643337":9,"34902789e":15,"350387":3,"35038714":3,"351636":9,"35176067":[],"35216172e":1,"358869339268145":15,"35886934":15,"359":3,"359640894899012":[],"360":2,"360688":1,"36436520e":[],"36468301":[],"369139":9,"36941772":[],"369418":[],"37416969":9,"374170":9,"37738324":[],"38207279e":[],"38216436":[],"38629436":13,"38937995e":15,"38986237":[],"396740":9,"39674043":9,"397700":9,"39792608e":[],"3cd19a0768e1":[],"4000":17,"401842":9,"40212127":[],"404":1,"40425078e":15,"405890":9,"40708470e":1,"40859":4,"40902095":[],"41511965e":2,"415634483874318":1,"416694683938511":9,"4171578884124756":0,"41754964":[],"41770932":[],"418506":9,"41876428e":[],"42847770e":15,"42937310e":15,"435490":3,"43549028":3,"43766686":9,"44089210e":3,"442600":9,"44395541":[],"44625466e":15,"44970586e":2,"45013332e":[],"45019484":[],"450257":9,"4557763":9,"458078":9,"45937170e":[],"461":15,"462":5,"46323168e":15,"46423858e":1,"465564":3,"46556436":3,"466":15,"46675058":1,"46914544e":[],"46929603e":[],"47079457e":15,"47566390e":15,"47654764e":[],"47815203":9,"48154187202453613":0,"48257387":16,"48471852e":[],"48476997":9,"48608063e":[],"4940954":1,"497221":3,"49722108":3,"49865673":[],"4990":15,"4992":15,"4997":15,"4c4c7f":[7,8],"4y_i":8,"500":[2,4,5,7,8,15],"500000":1,"5018":15,"50394742":[],"506":1,"507d50":[7,8],"50j":5,"50x10":2,"510":2,"5120":0,"512132":1,"51257863e":[],"51345668e":[],"51363731e":[],"51523276e":[],"515768":3,"51576807":3,"51893804e":[],"51943726":9,"519842":1,"52158335":1,"5222222222222223":2,"526744":9,"52687171":3,"526872":3,"52722156":[],"52d2c51caad1":3,"5303329":9,"5305555555555556":2,"5378811":9,"539261":9,"54096582":3,"540966":3,"54121682":[],"541217":[],"54152940e":[],"54237024":15,"54702088e":[],"55138385":9,"551384":9,"55280484":[],"5555555555555556":2,"55707065":3,"557071":3,"557795":9,"55854694":9,"56216797e":1,"564374":9,"56536":1,"569":2,"57051369":[],"571":3,"574465":9,"5755035":1,"57781668":[],"57871326":[],"581766":9,"58176612":9,"582":[1,2],"58228342e":15,"58239999":[],"582400":[],"584804":1,"58521266":9,"585213":9,"58596975":[],"585970":[],"587401":1,"58836420e":15,"5888888888888889":2,"59007674e":15,"59304755e":1,"5944444444444444":2,"59480085":[],"5cm":15,"60122668e":15,"60394236e":1,"60673226":9,"60999846":[],"61069091e":15,"6111111111111112":2,"61124978":[],"61234223":[],"614808":9,"61505887e":[],"61745046e":[],"618":1,"61869821":[],"622539":9,"62253933":9,"6226921":[],"62316154e":15,"62359224e":15,"62373464":9,"625":5,"62783293":[],"62856593":1,"629961":1,"6300745149331701":1,"63315151":1,"63339159":[],"63374631":[],"63437572":[],"63442451e":1,"636323":9,"63632311":9,"63680118":[],"637129335071195":1,"63993205e":[],"64166831e":[],"64447921":[],"64580686":[],"646283":9,"64669382":3,"646694":3,"647473":9,"64857826e":[],"649382":9,"64x50":2,"650024":[],"65002433":[],"6510573774179256":15,"65105738":15,"65238878":13,"65245958":[],"653095390463358":1,"653702":13,"65482578":[],"65572035":[],"65599927":[],"65766387":[],"65933852":[],"65939208e":[],"66020213e":1,"6614":[],"66183486":9,"661835":9,"6628996975186952":1,"66302359":[],"66383151":[],"66677842":[],"66800261":[],"66880047":[],"67006792":[],"67060602":[],"671089":1,"6714":[],"67171347e":15,"67279536":[],"67303655":9,"673037":9,"67407338e":15,"67450955":[],"67708423":1,"677149":3,"67714918":3,"68034946e":[],"6813":4,"6814":4,"6815":4,"6816":4,"6817":4,"6818813252071303":15,"68188133":15,"68316185":1,"68342382":[],"68616263":13,"68729414":[],"68937695":1,"689519":9,"69069n_":15,"693361":1,"69347005":[],"693850":9,"69385025":9,"69519693":[],"695197":[],"69573183":1,"69981195e":15,"6999536":9,"6ea927cc6e88":2,"6n_":15,"7022283":1,"70234019":[],"70415861":[],"70523024e":[],"70589906":[],"70710678":3,"70790937":[],"70886748":1,"70946493e":[],"712018":9,"71281409":[],"71351486":[],"71442781":13,"71606852":3,"7162":[],"71669651":1,"7172":[],"72108703":[],"72174172":9,"72218808":[],"72312577":[],"7240496":[],"725394195434945":3,"72780613e":15,"72879865e":[],"72981762":6,"73091052e":1,"73453972":[],"73921714":[],"74081822":6,"74107697":9,"74143127e":1,"7432283":[],"74382593":1,"74495014":[],"74845978":[],"74921867":[],"751699":9,"7522047280566193":[],"75382481":[],"75524378":[],"75629493":[],"75841112":[],"75932862":[],"76172241e":[],"762":9,"7621419":1,"76290332":[],"763880":3,"76388013":3,"76497666":[],"765":5,"76504618":[],"76570177":1,"76648901e":[],"7693978131030923":9,"7718":7,"772b904ae9cb":4,"77317984":1,"7733":4,"77350269e":[],"774300":1,"77661393e":15,"77714169":6,"78080633":1,"78195":[],"78857629":1,"78944806":[],"7899453":[],"79295029e":15,"79326583e":15,"79328828":[],"793701":1,"794282":9,"79459035":1,"79648291":1,"79902342":1,"7c394b1e8b71":7,"7d7d58":[7,8],"800":5,"80004454e":[],"800266":3,"80026635":3,"80121":[],"8055555555555556":2,"81620806":[],"81633628":9,"81781888":9,"827265":1,"82889306e":15,"8305555555555556":2,"83425361":9,"834254":9,"83614019":[],"8388888888888889":2,"83935285":[],"84087101":[],"842":1,"84355903e":2,"84372853":1,"84443254e":2,"84658093e":15,"8479552268981934":0,"8520127":[],"85278450e":1,"85396354":[],"85450859":9,"85463934e":[],"85497163e":[],"85546305e":[],"861":1,"86145244":9,"8638888888888889":2,"86436607":[],"86574276":[],"8666666666666667":2,"86692943":[],"8718475896381779":15,"87184759":15,"8722222222222222":2,"875":2,"87761937":[],"8777777777777778":2,"87972591":[],"8802":[],"88046462":3,"8805555555555555":2,"88297395":[],"88559559":[],"8867467323038865":3,"88693966e":15,"88712946":[],"8888888888888888":2,"8901":[],"8914984":[],"8921171964770647":9,"8923":1,"89288636":9,"89383322":[],"8944444444444445":2,"898500":9,"89850037":9,"89942598":1,"89975818":[],"8x8":2,"90233874":[],"90316476":[],"9040":7,"9055555555555556":2,"90618734e":15,"907307":9,"90730735":9,"90825063":1,"91012519e":[],"9111111111111111":2,"91145266e":15,"91417278":3,"91549644":1,"9166666666666666":2,"916978":[],"91697817":[],"9171356":1,"9222222222222223":2,"922312":3,"92231203":3,"924018":1,"925":2,"92507116e":2,"92605247":1,"92645039":9,"92646965":9,"926470":9,"92732185e":[],"9277777777777778":2,"9279671770201344":15,"92919670e":15,"9305555555555556":2,"931":1,"93100040e":15,"932734":[],"93273404":[],"933":3,"9354":[],"9361111111111111":2,"937":15,"938":15,"9388888888888889":2,"939":[1,15],"94019247e":1,"94034531":1,"9444444444444444":2,"94536341":15,"94591015":13,"94639099":9,"946893955211749":1,"947543":9,"948729":[],"95014575":[],"9527777777777777":2,"954":15,"9547578478889096":1,"9555555555555556":2,"956563":9,"9583333333333334":2,"960":15,"961":15,"96104648":[],"9611111111111111":2,"962":15,"963499":9,"96349948":9,"965885569080809":[],"967809":9,"96793117e":[],"97101567e":15,"9722222222222222":2,"975":2,"9756404":1,"976":6,"97622676":3,"976227":3,"97723801":[],"9777777777777777":2,"9780387310732":17,"9780387848570":17,"9781492032632":17,"9804422":1,"98046438":1,"9805555555555555":2,"98314755":3,"983148":3,"98452685":[],"985":15,"98526763":1,"98528992":1,"98531221":1,"986":15,"9860803":3,"98609175":15,"986091753050161":15,"9861111111111112":2,"98661465":[],"9877742":[],"987902":1,"988663":3,"9888888888888889":2,"98892195e":15,"98893512":[],"989":15,"98927731":[],"9898ff":[7,8],"99009739":[],"9901168":1,"99013921":1,"99016161":1,"99018401":1,"99043999":[],"9909252":[],"991":15,"991072":9,"99107239":9,"99126104":[],"99133007":[],"99160404":[],"99190487":[],"99194716":[],"992":15,"99218987":[],"99219378":[],"99242605":[],"99248001":[],"99273355":[],"99276945":[],"993":15,"99305549":[],"99305802":[],"99311297":[],"99346398":[],"99363129":[],"99363383":[],"99393624":[],"994":4,"99400444":[],"99418903":9,"99420743":[],"99420997":[],"99428016":[],"9945452":[],"99462421":[],"99473581":[],"99478645":[],"99478898":[],"99498985":1,"995":4,"99501236":1,"99503487":1,"99505739":1,"9950799":1,"99527696":[],"9953048353087299":[],"99536326":[],"9953658":[],"99544872":[],"9954538761021741":[],"99579317":[],"99581841":[],"99594294":[],"996":[3,4],"99600927":[],"99636015":[],"99652042":[],"99652296":[],"99655111":[],"99696351":[],"997":4,"99709325":[],"99710078":[],"99723611":1,"99728435":[],"99730848":[],"99763569":[],"99767893":[],"99782689":[],"998":4,"99817842":[],"99825997":[],"99836973":[],"9984806":[],"99883879":[],"99891285":[],"999":[7,15],"99945628":[],"99988687":1,"9999095":1,"99993212":1,"99995475":1,"99995818594196":[],"999974281880048":1,"99997737":1,"9999794306626945":[],"9999822527140678":[],"9999864543345858":[],"9999868619217517":[],"9999878260589065":1,"9999910208315801":[],"9b9cf4fa1a95":[],"\u00f8yvind":16,"abstract":2,"break":[0,1,9],"byte":13,"case":[1,2,3,4,9,10,12,13,14],"catch":1,"char":15,"class":[1,2,4,5,6,7,9,10,15],"const":15,"default":[1,2,5,13],"ekstr\u00f8m":16,"export":7,"f\u00f8470":16,"final":[0,1,2,3,4,6,7,8,9,14,15,16],"float":[0,1,3,7,9,13,15],"function":[0,3,4,7,12,13],"import":[0,1,2,4,5,6,7,8,9,10],"int":[0,1,2,3,5,9,13,15],"long":[1,2,5,10,15],"new":[0,1,2,3,4,5,6,7,8,9,13,15],"null":15,"public":[1,12],"return":[0,1,2,3,4,5,6,7,9,13,15],"s\u00f8rli":16,"sch\u00f8yen":16,"short":[0,3,11],"steinsv\u00e5g":16,"super":3,"switch":[0,1],"throw":15,"true":[0,1,2,3,4,5,6,7,8,10,15],"try":[0,1,2,3,5,6,7,8,9,12,13,15],"var":[3,4,8,9,15],"while":[0,1,2,3,4,5,6,7,9,10,15],AGE:1,Adding:2,Age:5,And:[0,1,4,7,12,15],Are:9,Being:5,But:[0,2,3,4,7,8,15],CAS:[],DIS:1,Doing:[3,5,8],EoS:[1,4],FYS:14,For:[0,1,2,3,4,5,6,7,8,9,10,12,13,14,15,17],Going:2,Ising:[3,10],Its:[2,9],MDS:9,NNs:10,N_s:6,Not:[1,2,3,4],OLS:[1,4],One:[1,2,3,4,5,6,9,10,15],PCs:[9,12],RMS:15,Such:[4,10,15],That:[0,1,3,5,8,9,10,15],The:[8,13,14,16,17],Then:[0,1,2,4,5,6,7,8,9,10,13,15],There:[0,1,3,6,7,9,10,11,13,14,15,16],These:[0,1,3,6,7,8,9,10,13,15],Use:[1,7],Useful:[3,4,13],Using:[1,3,4,6,8,10,13],With:[1,3,4,6,7,8,9,10,13,15],__class__:8,__doc__:4,__future__:[6,7],__getattr__:3,__init__:[2,3,4],__name__:[3,4,8],_auto10:10,_auto1:[3,5,10,13,15],_auto2:[10,13,15],_auto3:[10,13],_auto4:[10,13],_auto5:[10,13],_auto6:[10,13],_auto7:[10,13],_auto8:10,_auto9:10,_ax:4,_base:6,_build:[12,17],_check_optimize_result:9,_compon:9,_datafram:[],_depth:7,_fraction:7,_lambda:1,_leaf:7,_logist:9,_make_index:[],_multilayer_perceptron:[1,2],_node:7,_num_sampl:[],_ratio:9,_sampl:7,_split:7,_varianc:9,_weight:7,a0faa0:[7,8],a77d5ac269b2:5,a_0:1,a_1a:1,a_2a:1,a_3:1,a_3a:1,a_4:1,a_4a:1,a_h:2,a_i:[1,2,10],a_j:[2,10],a_k:[2,10],aaron:17,ab_channel:12,abandon:2,abbrevi:14,abid:15,abil:[1,8],abl:[2,3,5,8,10,15],abort:15,about:[0,1,2,3,4,5,6,7,8,9,10,12,13,17],abov:[0,1,2,3,4,5,6,7,8,9,10,13,15],abovement:4,abs:[0,1,3],abscissa:5,absolut:[1,3,4],acccess:[],accept:[1,7],access:[1,9,15],accid:4,accompani:1,accomplish:[6,7],accord:[0,1,2,3,4,5,7,10,15],accordingli:9,account:[1,3,15],accumul:[10,15],accur:[4,8,15],accuraci:[1,2,3,5,7,8,9,10],accuracy_scor:[1,2,8],accuracy_score_numpi:2,achiev:[1,2,3,4,6,10,13],aco:15,acquaint:12,acquir:[2,12],acr:1,across:[2,4,7,12],act:[2,13],action:15,activ:[0,1,7,14],actual:[1,2,3,4,6,9,13],ada_clf:8,adaboostclassifi:8,adam:2,adapt:[1,4,5,17],add:[1,2,3,4,6,8,9,10,15],add_subplot:[0,2,5,10],added:[1,2,3,5,6,13],adding:[0,2,4,13],addit:[0,1,3,4,5,6,7,8,10,12,13,15,16,17],addition:[5,10],address:[2,5,7,9,17],adjac:10,adjoint:3,adjust:[5,10],admir:1,advanc:[4,10,17],advantag:[2,3,4,5,8,13],afecionado:[],affect:[],affin:[1,6,9],aficionado:[],aforement:0,african:1,after:[0,1,2,3,4,5,7,9,10,12,13,15],afterward:1,again:[0,1,2,3,4,5,6,8,9,10,15],against:[2,5,8],age:[1,5],agegroup:5,agegroupmean:5,aggreg:[7,8],agorithm:8,agre:[3,15],ahead:7,aid:9,aim:[0,1,2,4,5,9,12,13],ainv:3,aka:3,alarm:3,albeit:0,algebra:[1,3,5,12,14],algo:15,algorithm:[1,2,3,4,5,6,12,13,14,15,17],align:[1,3,4,5,6,15],all:[0,1,2,3,4,5,7,8,9,10,12,13,14,15,16,17],allevi:[2,5],alloc:13,allow:[1,2,3,4,5,6,8,12,13],almost:[1,2,4,5,6,9,15],alon:7,along:[0,3,4,7,8,9,12,13],alpha:[0,1,2,4,5,6,7,8,15],alpha_:8,alpha_i:5,alpha_k:5,alpha_m:8,alpha_opt:5,alreadi:[3,8,10,12,13,15],also:[0,1,2,3,4,5,6,7,8,9,10,12,13,14,15,17],alter:[2,15],altern:[1,2,3,6,7,9,13],although:[2,3,4,6,8],alwai:[0,1,3,4,5,10,15],ame2016:1,american:1,among:[1,3,7,8,10],amongst:3,amount:[0,2,4,6,8,12],an_:15,anaconda3:[1,2,3,4,6,9],anaconda:[1,2,12],analys:[4,15],analysi:[2,4,5,13,14,17],analyt:[1,3,4,5,10,12],analyz:[1,2,3,15],andrew:2,angl:[1,7,15],ani:[0,1,2,3,4,6,7,8,10,15],anim:10,ann:10,annot:[1,2,5,6],anoth:[1,2,3,4,5,6,8,9,10,13,15],ans:15,ansatz:1,answer:[1,2,3,4,13],anymor:[2,6],anyon:6,anyth:[2,15],anytim:16,apach:2,apart:[5,9],api:[2,12],appear:[1,2,13,15],append:[2,4,5,6,7,15],appli:[1,2,4,5,6,7,8,9,10,15,17],applic:[1,2,3,4,5,7,10,15,17],approach:[2,3,4,7,8,9,10,12,15,17],appropri:[4,7,10,12,15],approx:[1,5,8,9,15],approxim:[1,2,3,4,5,8,9,15],apt:[1,12],aptli:0,aragorn:[],arang:[2,4,5,7,8,10],arbitrari:[2,5,6,10,15],arbitrarili:[1,2,9],architectur:[10,17],area:[1,17],arg:4,argc:15,argmax:[2,9],argmin:[0,8],argsort:9,argu:2,arguabl:0,argument:[1,3,9,10,15],argv:15,aris:[1,4,5,10,15],arithmet:[1,13],arma:15,armadillo:[13,15],around:[1,2,3,4,9,15],arrai:[0,1,2,3,4,5,6,7,9,10,12,15],arriv:[1,7,9,13,15],arrow:10,arrowprop:6,art:[1,2,12],articl:[0,1,3,4,8,15],artifici:[1,5,10,17],artificialneuron:10,artist:4,asarrai:[1,7],ascii:15,ask:[3,4,9,10],aspect:[1,12],assembl:1,assess:[1,4],assign:[0,1,5,6,7,10,14,17],assign_points_to_clust:0,associ:[0,1,4,7,10,15],assum:[0,1,2,3,4,5,6,7,8,9,10,13,15],assumpt:[1,3,4,7,9,15],ast:[1,3,4],astyp:[7,8],asymmetri:1,asymptot:4,atoi:15,atom:1,attempt:[1,5,6,8],attend:14,attent:[1,13],attr:3,attract:[1,8],attribut:[1,3,7],attributeerror:[3,4],audi:1,aurelien:[1,14,17],author:[1,2,8,15],authour:1,auto:[7,8,15],autocor:15,autocorrelation_tim:15,autocorrelform:15,autocovari:15,autoencod:12,autoencond:12,autograd:12,autom:[1,12],automac:13,automag:[],automat:[1,2,9,12,13],autonom:17,avail:[1,2,4,8,9,12,13,14,17],averag:[0,1,2,4,7,8,15,16],avg:15,avoid:[0,1,3,4,7,9,13],awai:15,awar:8,award:16,axes3d:5,axes:[1,4,5,6,7,8,9],axessubplot:1,axhlin:6,axi:[0,1,2,4,5,6,7,8,9,10,15],axiom:3,axlabel:1,axvlin:6,b_1:[5,10],b_5:5,b_group:7,b_i:[1,2,10],b_ia_:1,b_index:7,b_j:[2,10],b_k:[2,5,10],b_m:10,b_score:7,b_valu:7,bachelor:14,back:[1,3,6,7,8,13,15],backbon:13,backend:2,background:17,backpropag:2,backtrack:7,backup:13,backward:[2,10,13],bad:15,badli:15,bag:[7,12,14],bag_clf:8,baggin:[],baggingboot:8,baggingclassifi:8,baggingtre:8,balanc:4,band:13,bandwidth:13,bar:[1,9],barber:17,bare:8,barebon:0,base:[0,1,2,3,5,6,7,8,12,15,16,17],basi:[3,5,6,8,9,10,13],basic:[6,10,12,14,15],batch:[5,9,10],batch_siz:2,bay:5,bayesian:[3,12,17],becaus:[0,1,2,3,4,5,6,7,10],becom:[0,1,2,3,4,5,7,10,15],been:[1,2,4,9,10,12,13],befor:[0,1,2,3,4,5,6,10,13,15],beforehand:[0,1,15],begin:[0,1,2,3,4,5,6,7,9,10,13,15],behav:[2,4,5],behavior:[1,2,5],behaviour:10,behind:[1,2,5,6],being:[0,1,2,3,5,6,8,9,10,15],believ:[7,13],belong:[0,3,5,6,7],below:[1,2,3,4,5,6,7,8,9,10,13,15],benchmark:8,bendik:16,benefici:2,benefit:[1,2,5,9,12],bengio:[2,14,17],benign:[2,5],besid:3,bessel:3,best:[0,1,2,3,4,5,6,7,8,10,15,16],beta:[1,2,3,4,5,8,9],beta_0:[1,2,3,5],beta_0x_:1,beta_1:[1,2,3,5,8],beta_1x_0:1,beta_1x_1:[1,5],beta_1x_2:1,beta_1x_:1,beta_1x_i:5,beta_2:1,beta_2x_0:1,beta_2x_1:1,beta_2x_2:[1,5],beta_2x_:1,beta_:[1,5],beta_i:[1,3],beta_j:[1,3,5],beta_k:5,beta_linreg:5,beta_m:8,beta_mg_m:8,beta_p:5,beta_px_p:5,better:[0,1,2,3,7,8,9,10],between:[0,1,2,3,4,5,6,7,9,10,15],beyond:[1,2,3,5,6],bia:[1,2,3,6,7,8,10,14,15],bias:[2,3,4,7,10],big:[0,1,2,3,4],bigger:2,bigr:10,bike:7,bilbo:[],bilek:16,billion:[10,12],bin:[1,4,5,15],binari:[1,3,5,7,8,10,14,15],bind:[1,4],binomi:12,binsboot:4,bioinformat:1,biolog:[2,10,17],bios1100:12,bird:1,birth:[],bishop:[14,17],bit:[0,2,13,15],bitwis:15,bla:13,black:[0,6,7],block:[0,4,8,12,13],blockingavg:15,blockingstd:15,blockingvar:15,blocksiz:15,blocksizemax:15,blocksizemin:15,blue:1,bmatrix:[1,2,3,5,6,9,13],bmi:2,bodi:[1,2,10],bold:2,boldfac:[1,3],boldsymbol:[0,1,2,3,4,5,6,8,9],boltzmann:[10,12],book:17,bool:0,boost:[2,7,12,14],boostrap:8,bootavg:15,bootstd:15,bootstrap:[2,12,14],bootvar:15,bootvec:15,borrow:[],boston_dataset:1,bot:6,both:[0,1,2,4,5,6,7,8,12,13,15,16],bottl:5,bottom:4,bound:[1,4,6,10],boundari:[6,9,10],box:7,boyd:[5,6],bracket:15,brain:[2,5,10],branch:7,breast:[3,5,9],brew:[1,12],brg:6,briefli:1,bring:[1,8],broad:1,broadcast:0,browser:[],brute:[3,9],bsol:[],bsubex:[],build:[1,3,4,8,13,15],built:[1,2,4],bunch:9,busi:1,c46dd114b2af:6,c_0:15,c_1:10,c_2:10,c_3:10,c_4:10,c_i:[5,10],c_k:15,cach:8,cal:[1,5,6,8,10],calcul:[0,1,2,3,4,5,6,7,8,9,10,13],call:[0,1,2,3,4,5,6,7,8,9,10,12,13,15,17],callabl:4,cambridg:[5,17],came:0,can:[0,1,2,3,4,5,6,7,8,9,10,12,13,15,17],cancel:1,cancer:[3,8],cancerpd:5,candid:[6,7,8],cannot:[1,2,3,5,6,7,14,15],canopi:[1,12],cap:3,capabl:[1,2,6,12],capita:1,captur:[9,10],card:[1,5],cardin:2,care:[0,9],carefulli:5,carlo:[1,4,12,15,17],carri:[4,5],cart:8,casella:17,cast:2,categor:[1,2,7,9],categori:[0,1,2,5,8,10,14],categorical_crossentropi:2,caus:[1,3,4,15],causal:1,causat:1,cax:2,cbar:2,ccc:[3,10],cdf:15,cdot:[0,1,4,5,10,13,15],celebr:5,center:[0,1,2,4,5,6,7,9,15],centr:17,central:[1,3,4,6,13],centroid:[0,15],centroid_differ:0,centroid_list:0,certain:[0,1,4,5,7,15],cha:1,chain:[2,12,15],challeng:[0,5],chanc:[2,3,5,15],chang:[0,1,2,3,4,5,6,7,9,10,13,15],chapter:[0,4,8,9,13,14,17],charact:[1,3,6,15],character:[6,7,8,10,15],characterist:[1,2,8],charg:1,charl:1,chd:5,chddata:5,cheap:3,cheaper:[2,5],chebychev:0,check:[1,2,5,9,13],check_consistent_length:[],chemic:15,chen:8,choic:[0,1,2,4,5,7,10,13,15],choleski:[3,13],choos:[0,4,5,7,8,9,15],chosen:[1,2,4,5,6,7,8,15],chosen_datapoint:2,christian:17,christoph:[14,17],cin:15,circ:[2,10],circl:[1,6,10],circumfer:7,circumv:[2,3],clariti:[0,15],class_nam:7,class_val:7,class_valu:7,classic:[5,7],classif:[1,3,4,5,6,9,10,12,14,17],classifi:[1,2,5,7,8,9],classificaton:2,classifii:8,clean:2,clear:[2,8,10],clearer:0,clearli:[3,4,5,6,15],clever:[0,2,8],clf3:1,clf:[1,6,7,8],clf_ridg:1,clip:15,close:[0,1,2,4,5,6,7,9,10,15,17],closer:3,closest:[0,5,6,9],closur:12,cloud:12,clust:0,cluster:[1,2,4,9,12,14],cluster_label:0,cmap:[1,2,6,7,8],cmath:15,cmb:14,cmd:7,cn_:15,cnn:10,cntk:12,code:[4,6,12,13,14,17],coef0:6,coef:1,coef_:[1,3,5,6,7],coeffici:[1,3,4,5,6,7,13],coerc:[1,4],coin:[8,15],coin_toss:8,col:[1,9],colab:12,cold:7,colinear:1,collaps:6,collect:[1,4,8,9,12,15,17],collinear:3,color:[1,4,6,7,8,15],colorbar:2,colsample_bytre:8,colsaobject:8,column:[1,2,3,4,5,6,7,9,10,13],columntransform:7,com:[12,16,17],combin:[2,3,4,5,8,15],come:[0,1,2,3,5,10],comma:[],command:[1,2,15],comment:1,commerci:[1,12],commod:1,common:[0,1,2,3,4,5,7,9,15],commonli:[0,2,4,5,7],commun:[1,10],compact:[0,1,2,3,4,5,7,9,10],compar:[0,1,3,4,5,9,13],compat:5,compet:1,competit:8,compil:[1,2,12,13,15],complet:[1,7,10],completenn:10,complex:[1,2,3,4,6,7,9,10],complic:[0,1,2,4,5,7],compon:[0,1,2,3,4,5,7,12,14],components_:9,compos:[0,7,10],compphys:[12,14,17],compress:1,compris:4,compromis:3,compulsori:12,comput:[0,1,2,3,4,6,8,9,10,12,13,14,17],computation:[1,4,5,7,15],concaten:0,concav:[2,5],concentr:[1,8],concept:[0,1,12],conceptu:[5,10],concern:[0,1,2,5],concic:[],conclud:[1,3],conclus:2,conda:[1,2,12],condit:[1,3,4,6,7,9,15],conduct:12,confid:[1,3,4,5,6],confirm:[3,10],confus:[3,4,8,13],confusion_matrix:7,congruenti:15,conjug:6,conjugaci:5,connect:[1,2,5,7,9,10,13],consequ:[3,4,5,6,8,10],conserv:[0,3],consid:[0,1,2,3,4,5,6,7,8,10,13,15],consider:[1,2,3,5],consist:[1,2,4,5,10,15],constant:[1,3,5,6,10,15],constitu:1,constitut:4,constrain:[2,3,5,9],constraint:[3,5,6],construct:[1,2,3,4,5,6,7,8,9,13,15,17],contact:1,contain:[0,1,3,4,5,6,7,9,10,13,15,17],contemporari:17,content:[2,12,13],context:[4,5,8],continu:[1,2,3,4,5,6,7,8,10,13],contour:[5,7,8],contourf:[6,7,8],contrast:[2,7,8,10],contribut:[1,3,15],contributor:1,control:[1,2,7,12],conveni:[1,3,4,5,10,13],convent:10,converg:[0,1,2,3,5,6,9],convergencewarn:[1,2,6,9],convert:[1,2,3,7,9,13],convex:3,convinc:5,convolut:[2,12,14],cool:7,coordin:[0,3,10],coorel:1,copi:[0,2],core:8,corel:1,coronari:5,corr:[1,3,5,9],correalt:[9,12],correct:[0,1,2,3,13,15],correctli:[2,4,8],correl:[1,2,3,5,8,10,12],correlation_matrix:[1,3,5,9],correspond:[0,1,3,4,6,7,9,10,12,13,15],cortex:10,cos:[1,4,7],cosin:[0,4],cost:[1,3,4,6,7,10,15],could:[1,2,3,4,5,6,7,8,9,10,13,15],coulomb:1,count:[1,7,14,15,16],countor:5,coupl:3,cours:[1,2,3,9,14,15],courvil:[14,17],cout:15,cov:[3,4,9,13,15],cov_xi:[3,9],cov_xx:[3,9],cov_yi:[3,9],covari:[5,12,13],covariance_matrix:[0,3,9],cover:[1,3,11,12,17],covert:1,covxi:15,covxx:15,covxz:15,covyi:15,covyz:15,covzz:15,cpu:2,creat:[2,3,7,8,9,10,12],create_biases_and_weight:2,create_neural_network_kera:2,create_x:[1,3,9],credit:[1,5],crim:1,crime:1,criteria:[0,1,7,8,15],criterion:[5,7,8],cross:[1,2,5,7,8,12,14,15],cross_val_scor:4,cross_valid:[5,8],crossvalid:4,crucial:[2,15],csr_matrix:13,cstdlib:15,csv:[1,4,5,7],ctnk:2,cubic:1,cumbersom:3,cumsum:[8,9],cumul:[4,8],cumulative_heads_ratio:8,cup:3,current:[0,2,5],curs:1,curv:[5,8,10],curvatur:5,custom:0,custom_cmap2:[7,8],custom_cmap:[7,8],cutpoint:7,cvxbook:5,cvxopt:[3,6],cyber:17,cycl:[0,2,10,15],d_f:5,dagger:[3,13],dai:[2,7,12],dalen:16,darget:7,darkr:15,dat:1,dat_id:[1,4,5,7],data1:0,data2:0,data3:0,data4:0,data:[0,3,4,6,8,10,13,17],data_id:[1,4,5,7],data_indic:2,data_panda:[],data_path:[1,4,5,7],databas:2,datafil:[1,4,5,7],datafram:[1,3,5,7,9],datapoint:[1,2,3,4,5,9],dataset:[0,1,4,5,6,7,8,9],date:1,daughter:8,david:17,dbh:2,dbo:2,dcomposit:13,dead:2,deal:[0,1,2,3,5,6,9,13,15],debt:5,debug:[3,4],decad:1,decai:[1,5,15],decent:8,decid:[3,4,7],decim:1,decis:[1,2,6,9,12,14,17],decision_funct:6,decision_tre:7,decisiontreeclassifi:[7,8],decisiontreeregressor:[1,7,8],declar:[1,13],decompos:[3,13],decomposit:[1,10],decompost:3,decorrel:8,decreas:[2,3,4,5,8,9],deduc:1,deep:[5,10,12,14,17],deep_tree_clf1:7,deep_tree_clf2:7,deep_tree_clf:[7,8],deepen:12,deeper:0,deeplearningbook:17,def:[0,1,2,3,4,5,6,7,8,9,15],def_covari:15,defect:3,defici:3,defin:[0,1,3,4,5,6,7,8,9,10,13,15],definit:[0,2,3,4,5,6,8,9,10,13],defint:15,degre:[3,4,6,7,8,9,15],del:2,delet:[4,15],deliv:14,delta:[0,1,6,10,15],delta_:[2,13],delta_h:[1,2],delta_j:10,delta_k:10,delta_l:2,delta_n:1,delug:12,delv:1,demand:5,demonstr:[1,3,4,5,9,10,12],denomin:[2,3],denot:[2,4,5,15],dens:[0,2],densiti:[0,1,4,15],depart:16,depend:[0,1,2,3,4,5,6,9,10,12,15],depict:15,deploy:[1,12],deprec:1,depth:[7,8,13],deriv:[1,2,4,6,8,9,12],descend:[3,7,9],descent:[1,2,6,10],descr:1,describ:[0,1,3,4,6,8,9,10,13],descript:[0,1,6,7],design:[1,2,3,4,5,8,9,10],designmatrix:1,desir:[0,1,3,5],despit:[2,10],destroi:13,det:[3,13],detail:[0,1,5,9,13],detect:[6,10],determin:[1,3,5,6,7,8,9,10,13,15],determinist:[5,15],dev:[2,15],develop:[0,1,3,6,8,9,10,12,13],deviat:[1,2,3,4],devis:10,df1:[],diag:[3,6],diagnost:[2,8],diagon:[1,3,5,13,15],diagonaliz:3,diagram:8,dict:6,dict_kei:1,dictionari:1,did:[0,1,2,3,5,8,9],die:2,diffeent:6,differ:[0,1,2,3,4,7,8,9,10,12,13,15,17],differenti:[5,12,13],difficult:[0,1,2,4,8,15],difficulti:[1,2,5],digit:[1,2,14,16],dilut:2,dim:[0,9],dimens:[0,1,2,3,6,9,13],dimension:[0,1,3,4,5,7,9,12,13],dimensionless:1,diment:13,dimes:0,direct:[0,1,2,5,9,10],directli:[0,2,3,15],directori:5,disadvantag:1,discard:[4,9],disciplin:[1,10],disclaim:15,discourag:5,discov:1,discover:3,discret:[2,3,5],discrimin:[5,8,9],discuss:[0,1,2,3,4,5,6,7,8,9,10,12,13,14,15,17],diseas:5,disk:[],disord:[2,5],displai:[0,1,2,4,5,6,7,8,9,10,15],displaystyl:[1,3],displot:1,disregard:1,dissimilar:[0,9],dist:0,distanc:[0,1,6,7,9,15],distance_list:7,distinct:[0,5,6,7,8],distinctli:6,distinguish:[1,5,6,15],distplot:1,distribut:[0,1,2,4,5,8,9,12,13],distrubut:[1,12],dive:[1,6],diverg:[2,5],divid:[1,2,3,4,6,7,9,10,15],divis:[4,6,7,13,15],dna:5,dnn:[1,2,10],dnn_kera:2,dnn_model:2,dnn_numpi:2,dnn_scikit:[1,2],doamin:3,doc:[12,14,17],doconc:[],document:9,doe:[0,1,2,3,4,5,6,8,9,10,13,15],doesn:[7,10],dog:2,doi:0,doing:[1,3,4,9],domain:[3,5,6],domin:1,don:[0,1,2,6,9,12,15],done:[0,1,3,4,7,8,9,13,15],dot:[1,3,5,6,7,8,9,10,13,15],doubl:[13,15],doubli:2,down:[1,5,7,9,10],download:[1,2,13,17],dozen:2,dramat:9,draw:[4,5,8],drawback:[1,2,5],drawn:[2,4,5,9,15],drop:[1,2,3,4,9,15],dropna:[1,4],dtype:[0,1,2,13],dub:1,due:[0,2,3,4,5,6,8,10],dummi:1,dure:[1,2,6,7,9,12],dwell:1,dwh:2,dwo:2,dx_1:15,dx_n:15,dying:2,each:[0,1,2,3,4,5,6,7,8,9,10,12,13,14,15,16],eapprox:1,earli:2,earlier:[1,3,5,6,7,9,10],eas:[0,7],easi:[1,3,4,5,6,7,8,9,10,12,13],easier:[3,4,6,7,15],easiest:5,easili:[1,2,3,5,6,7,8,9,10,13],eastern:16,ebind:1,eblock:7,econometr:[],economi:3,ecosystem:12,ect:14,edgecolor:4,edit:[],edu:5,educ:1,eface79dac2c:8,eff:15,effect:[2,8,15],effic:2,effici:[1,5,8,12,13,15],efron:[4,15],eig:[3,5,9,13,15],eigen:15,eigenpair:[3,9],eigenvalu:[3,5,6,9,13],eigenvector:[3,5,9],eight:13,eigval:[13,15],eigvalu:[5,9],eigvec:[13,15],eigvector:[5,9],eispack:13,either:[1,2,3,4,5,6,7,8,9,15],ekstrom:16,elabor:15,electr:[1,10],electur:17,eleg:9,element:[2,3,4,5,6,9,10,12,13,14,17],elementari:[8,13],elessar:[],elif:0,elim:13,elimin:6,els:[2,3,5,7,10,15],elu:2,elus:1,email:[14,16],embed:[1,9],embodi:4,emit:15,emner:17,emphas:[1,8,12],emphasi:[1,12,17],empir:[2,9,15],emploi:[1,2,3,4,5,9,15],employ:1,empti:[4,8],emul:10,enabl:9,encapsul:0,encod:[0,1,3,7,9],encompass:[1,15],encount:[1,2,3,5,15],end:[0,1,2,3,4,5,6,7,8,9,10,13,15],endl:15,endpoint:15,energi:[1,4],enforc:10,eng:17,engin:[1,2,12,15],english:17,enough:[1,4,5],ensembl:[2,7,14,15],ensur:[1,2,3,4,5,9,15],enter:[3,15],enthought:[1,12],entir:[2,5,7,12,15],entiti:[7,10,13],entri:[1,3,6,9,10,13],entropi:[2,5,8],enumer:[1,2,6],env:15,environ:[12,17],eol:1,eosfit:1,epoch:[1,2,5,10],epsilon:[1,3,4,5],epsilon_0:1,epsilon_1:1,epsilon_2:1,epsilon_:1,epsilon_i:1,eqnarrai:[3,4],equal:[0,1,2,3,4,5,6,7,9,10,13,15],equat:[0,2,4,6,7,8,9,13,15],equilibrium:10,equiv:[5,13,15],equival:[2,3,6,9,12,13],erf:15,eriador:[],eridg:1,err:[1,8],err_:4,errat:5,errno:5,error:[1,2,3,4,5,7,9,10,12,15],error_estimate_corr_tim:15,error_hidden:2,error_output:2,escap:5,esl:0,esol:[],especi:[2,7,10],essenti:[0,1,3,7,8,10,15],establish:[1,8,9],estim:[1,2,3,4,5,8,9,12,15],estimated_mse_fold:4,estimated_mse_kfold:4,estimated_mse_sklearn:4,esubex:[],eta0:[5,6],eta:[1,2,5,6,10],eta_v:[1,2],etc:[0,1,2,3,5,6,7,9,10,12,13,15],ethic:12,etsim:4,euclidean:[0,1],evalu:[1,3,4,5,7,15],even:[0,1,2,3,4,5,6,7,8,9,10,12,13,15],event:[3,5,8],eventu:[3,4,5,9,10,16],everi:[0,1,2,3,4,5,7,8,9,10,12,15],everyth:10,everywher:5,evolv:1,exact:[1,3,5,9,10,13,15],exactli:[1,10,12],examin:4,exampl:[3,4,9,10,12,13,14,17],exce:[2,10],excel:[0,1,2,8,17],except:[4,6,7,15],excess:1,excit:1,exclud:[2,4,10],exclus:[1,2,4,15],execut:3,exemplifi:5,exercis:[3,12,14],exhaust:4,exhibit:[1,6],exist:[0,1,2,3,4,5,6,7,13,17],exit:[3,13,15],exp:[1,2,3,4,5,6,8,9,10,15],exp_term:2,expand:[3,5,9],expans:[1,3,5,6,8,10],expect:[1,2,3,4,5,9,10,12],expectation_value_of_h_wrt_p:15,expens:[4,5,8,15],experi:[1,2,4,5,6,12],experiment:[1,4,7,15],expert:[2,7],explain:[0,1,5,7,8,9,15],explained_variance_ratio_:9,explanatori:1,explicit:[1,13],explicitli:[0,1],explod:2,exploit:[1,10],explor:[2,5,6,12],expon:2,exponenti:[1,2,3,5,8],export_graphviz:7,export_text:7,exporttext:7,expos:12,express:[1,3,4,8,10,13,15],exptmean:15,exptvari:15,extend:[9,12],extens:[1,10,12],extent:[1,2,4,17],extern:7,extra:[2,3],extract:[1,3,5,6,9,13],extrapol:1,extrem:[0,1,2,3,5,6,7,13],extremum:5,extrins:9,eye:[0,1,3,5,13],f11:1,f12:1,f13:1,f1d:5,f6d7a289d493:13,f_0:8,f_1:[5,8],f_2:[5,10],f_3:10,f_d:15,f_i:[4,10],f_m:8,face:5,facecolor:[4,6,15],facil:[1,12],facilit:10,fact:[1,2,3,5,7,9,10],factor:[1,2,3,7,8,9,13,15],fafab0:[7,8],fail:[4,5,6,9,16],failur:5,fairli:[0,2,15],fall:[6,7,14],fals:[0,1,2,3,4,5,7,8],famili:[1,5,6,15],familiar:[1,3,6,12,13,15],famou:[4,10,13],far:[0,1,3,5,6,9,10,15],fashion:[1,7,8],fast:[2,4,5,8,10,12,15],faster:[2,9],fastest:5,favor:5,favorit:15,featur:[1,2,3,4,5,6,8,9,10,12,15],feature_nam:[1,2,5,7],feautur:7,fed:2,feed:[1,9,12,14],feed_forward:2,feed_forward_out:2,feed_forward_train:2,feedforward:[2,10],feel:[0,1,3,9,12,16],feet:1,few:[0,2,7,11,15],fewer:[1,7,9],ffnn:[2,10],field:[1,10,12],fifth:1,fig:[0,1,2,5,10],fig_id:[1,4,5,7],figaxi:15,figsiz:[1,2,4,5,6,7,8],figur:[0,1,2,3,4,5,6,7,8,10,12],figure_id:[1,4,5,7],figurefil:[1,4,5,7],file:[1,2,4,5,6,7,13,15],filenam:[1,15],filenotfounderror:5,fileout:15,fill:[3,7],financ:1,find:[0,1,2,3,4,5,6,7,8,9,10,12,15],fine:[0,1],finit:[3,4,10,15],first:[0,1,2,3,4,6,7,8,9,13,15,17],firsteigvector:9,fit:[2,3,4,5,6,7,9,10,15],fit_intercept:[3,4],fit_mod:7,fit_transform:[1,4,6,7,9],fiti:1,five:[1,7],fix:[1,4,5,8,9,10],flag:0,flat:[5,10],flatten:2,flexibl:[1,2,4,6,8,10],float32:7,float64:[1,13],flop:[3,13],flow:[2,10],fluctuat:3,fly:9,flyvbjerg:15,fmesh:5,focu:[1,3,4,12,17],focus:[2,5,13],fold:[4,7],folder:1,follow:[0,1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17],font:[1,5,15],fontdict:15,fontsiz:[2,6,7,8,15],fontweight:2,foral:6,forc:[1,3,8,9],forecast:10,forest:[1,2,7,12,14],forget:9,form:[1,3,4,5,6,7,9,10,12,13,15],formal:[0,15],format:[1,2,3,4,5,6,7,8,9,12,15,17],formatstrformatt:5,formul:[0,9],formula:[5,15],forth:10,fortran2003:12,fortran90:15,fortran:[1,12,13],fortun:[1,9],forward:[1,4,12,13,14],found:[2,3,4,5,10],foundat:12,four:[3,6,10,13,14],fourier:1,fourth:10,frac:[0,1,2,3,4,5,6,7,8,9,10,13,15],fraction:7,frame:5,framework:[2,6,8,15],frank:[3,9],frankefunct:[1,3,9],free:[1,9,12,13,15,16,17],freecodecamp:12,freedom:3,freeli:1,frequenc:[4,5,15],frequent:[1,5,6,7],frequentist:12,fresh:8,fret:0,fridai:14,friedman:[14,17],frodo:[],from:[0,1,2,4,5,6,7,9,12,13,14,15,16,17],from_cod:7,front:[1,3],fruit:0,fstream:15,fulfil:[3,10],full:[1,2,3,5,7,8,15],full_matric:3,fulli:[4,10,14,15],fun:12,func:4,functionali:9,fundament:[1,4,12],further:7,furthermor:[1,3,4,5,9,10,12],futur:[1,6,7],futurewarn:1,fys:16,g_1:8,g_2:8,g_m:8,gain:[0,2,3,7,8],galleri:1,gamge:[],gamma1:6,gamma2:6,gamma:[1,5,6,7,8,9],gamma_0:8,gamma_1:8,gamma_1x:8,gamma_:1,gamma_i:[1,6,15],gamma_j:5,gamma_k:5,gamma_m:8,gamma_x:1,gap:6,gate:10,gather:[2,10],gaug:10,gaussbacksub:13,gaussian:[0,3,4,6],gaussian_point:0,gaussian_rbf:6,gave:5,gbc:14,gca:[4,5,6],gd_clf:8,gdclassiffiercgain:8,gdclassiffierconfus:8,gdclassiffierroc:8,gdregress:8,gen:15,gender:1,gener:[0,1,2,3,4,5,6,8,9,10,13,17],generallay:10,generate_simple_clustering_dataset:0,genom:12,geodes:9,geometr:1,geometri:3,georg:17,geq:[3,5,6,7],geron:[1,14,17],get:[0,1,2,3,4,5,7,8,9,12,13,15],get_distances_to_clust:0,get_dummi:7,get_split:7,get_yaxi:6,getattr:4,gibb:12,gini:8,gini_index:7,git:[1,12],github:[1,12,14,17],gitlab:[1,12],give:[0,1,2,3,5,6,7,8,10,12,15,17],given:[0,1,2,3,4,5,6,7,8,9,10,13,15],glare:0,global:[5,15],glorot:2,gmail:16,goal:[1,5,7],goe:[0,1,2,3,4,5,13],going:[1,2,3,4,5,6,7,9,10],golden:5,gone:3,gong:2,good:[0,2,3,5,7,8,9,12,15,17],goodfellow:[14,17],googl:[0,2,12],got:2,gpu:2,grade:14,gradient:[1,6,7,10,12,14],gradientboostingclassifi:8,gradientboostingregressor:8,gradual:[0,2],graph:[2,5,7,9,10],graph_from_dot_data:7,graphic:[1,2,7],grasp:1,gray_r:2,great:5,greater:[2,5,15],greedi:7,green:[1,7,15],grid:[2,4,5,6,10,15],grossli:5,ground:1,group:[0,1,4,5,7,12,14],groupbi:1,grow:[2,7,8],growth:1,guarante:[1,5,15],guess:[0,2,5,8],guestrin:8,guid:2,h_1:5,h_2:5,h_m:8,had:[1,2,4,5],hadamard:[2,10],half:[2,6,7],halv:8,hand:[1,2,3,5,9,10,12,13,14,15,17],handl:[1,2,3,7,9,12],handle_unknown:7,handsid:10,handwrit:10,handwritten:[2,3,5],happen:[0,2,3,5,8,15],hard:[2,5,6,8],hardcopi:12,harder:[1,2],has:[0,1,2,3,4,5,6,7,8,9,10,13,15],hasn:[1,2],hassl:[1,12],hast:12,hasti:[0,1,14,17],hat:[2,3,5,7,8,9,10,13,15],have:[0,1,2,3,4,5,6,7,8,9,10,12,13,15],haven:2,hdf5:[],head:[1,8,15],header:1,heads_proba:8,hear:1,heart:[1,5],heatmap:[1,2,5],heavili:1,heavisid:2,height:2,help:[0,1,2,10],helper:0,henc:[1,3,4,5,6,7,8,10],her:5,here:[0,1,2,3,4,5,6,7,8,9,10,12,13,15,17],hereaft:[1,6,10],hermitian:13,hessenberg:13,hessian:3,heterogen:[7,8],hidden:[2,10],hidden_bia:2,hidden_bias_gradi:2,hidden_layer_s:[1,2],hidden_weight:2,hidden_weights_gradi:2,hierarch:[0,3],high:[0,1,2,3,4,5,7,8,9,12,13],higher:[1,2,3,4,5,6],highest:2,highli:[1,3,8,12,13,15,17],highwai:1,hing:6,hint:5,hip:12,hire:1,his:5,hist:[4,5,15],histogram:[1,4,5,15],histor:[5,9],histori:10,histplot:1,histtyp:4,hitherto:3,hjorth:16,hobbi:15,hoc:3,hoff:17,hold:[0,2,4,5,15],holder:1,home:1,homogen:[2,7,8],hopefulli:[1,9,15],horizont:9,hors:5,hot:[2,7],hour:[2,12,14,15,16],how:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,17],howev:[0,1,2,3,4,5,6,7,8,9,10,12,13,15],hspace:[1,6,8,15],hstack:2,htf:14,html:[9,12,14,17],http:[5,9,12,13,14,17],huang:1,huber:1,huge:[2,12],human:[1,2,7,10],humid:7,hundr:2,hungri:2,hybrid:14,hydrogen:1,hyperbol:[2,10],hyperparam:6,hyperparamet:[0,1,3,7],hyperplan:9,i_1:[3,4],i_2:[3,4],ian:17,idea:[1,2,4,5,7,8,10,13,15],ideal:[0,1,4,6,15],idem:4,ident:[3,4,10,13],identical:3,identifi:[0,1,2,5,6,7,9,10],idum:15,ieor:15,ifi:17,ifs:12,ignor:[1,2,7],iii:13,ijca2016907841:0,illustr:[0,3,5,8,10,12],imag:[2,7,9,10,17],image_path:[1,4,5,7],imagin:2,immedi:[1,12],implement:[0,1,3,5,6,7,8,9,10],impli:[3,4,5,13],implicitli:[9,15],impos:[1,9,10],imposs:[1,3],impress:[1,10],improv:[0,3,7,8,9],impur:7,imshow:2,in3050:17,in4080:17,in4300:17,in5400:17,inaccur:5,inact:10,inadequ:1,includ:[1,2,3,5,9,10,12,15,16,17],include_bia:[4,7],incom:10,inconsist:[],incorrect:2,incoveni:6,increas:[1,2,3,4,6,7,9,10,15],increasingli:15,ind:4,inde:[1,3],indent:15,indentationerror:15,independ:[1,3,4,5,6,10,15],index:[0,1,2,8,12,15,17],index_col:1,indic:[1,2,3,7,8,9],indispens:4,individu:[2,5,8,10,15],indu:1,indx:13,ineffici:0,inequ:6,inequaltii:5,inf1000:12,inf1100:12,inf1100l:12,inf1110:12,inf3000:17,inf4490:17,inf5860:17,inf:1,infeas:7,infer:[1,2,4,17],inferenc:2,infil:[1,4,5,7],infin:[3,4,5,9],infinitesim:15,influenc:[4,8],influenti:2,info:[],inform:[0,1,2,4,5,7,9,10,13,17],infti:[5,15],ingeni:5,ingredi:[1,7],inher:4,inherit:13,initi:[0,1,2,4,5,8,13,15],initialis:15,inject:0,inlin:[0,1,2,3,4,5,6,7,8,9,10,13,15],inner:[4,5],innov:17,input:[0,1,2,3,4,5,6,7,8,10,13,15],input_dim:2,inputs:2,inputs_shuffl:2,insert:[3,6,8,15],insid:[1,5],insight:[1,2,3,12,17],insist:5,inspir:[1,2,10,17],instal:[1,2,7,14],instanc:[1,2,4,5,7,9],instanti:8,instead:[0,1,2,3,4,5,6,7,9,13,15],institut:2,instruct:[1,2],int32:8,int64:1,int_0:15,int_:15,int_a:15,integ:[0,2,13,15],integer_vector:2,integr:15,intellig:[0,1,17],intend:8,intens:2,intention:0,interact:[1,7,10,12],intercept:[1,5,6,9],intercept_:[1,5,6,7],interchang:[3,10,13],interconnect:2,interest:[1,2,3,4,5,6,7,10,12,15],interfac:[2,13],interior:[1,7],intermedi:13,intern:[2,8,10],interpol:[2,10],interpr:3,interpret:[1,2,7,8,10,13,14,15],interv:[1,3,4,5,15],intial:5,intimid:[],intract:1,intrins:[9,13,15],intro:[12,17],introduc:[1,2,3,5,6,8,10,13,15],introduct:[2,5,14,17],introductori:[1,13,17],intuit:[1,3,4,6,10],inv:[1,3,5],invalid:[2,6,13],invalu:[1,5,12],invari:2,invd:3,inver:6,invers:[1,5],invers_period:15,inverse_transform:6,invert:[1,3,5,8],invok:[1,6],involv:[1,4,5,9,10],iomanip:15,ios:15,iostream:15,ipca:9,ipynb:12,ipython:[0,1,2,3,4,5,6,7,8,9,12,13,15],irani:0,iri:[6,7],irreduc:4,irrelev:3,irrespect:1,isn:3,isnul:1,isomap:9,issu:[2,7,13],it_arrai:5,item:1,items:13,iter:[0,1,2,4,6,9,15],its:[0,1,2,3,4,5,6,7,8,9,10,12,13,17],itself:[3,4,10,15],jackknavg:15,jackknif:[4,12],jackknstd:15,jackknvar:15,jackknvec:15,jacobian:5,jargon:15,jensen:16,jerom:17,job:[6,8],join:[1,4,5,7],joint:3,journal:15,judg:5,julia:[12,13],jump:[0,15],jupyt:[0,1,12,17],just:[0,1,2,3,4,5,6,7,8,9,10,15],justif:1,justifi:8,k_mean:0,kappa_d:15,karim:16,karlsen:16,karush:6,keep:[0,1,2,3,5,9,13],keepdim:[2,4,8],kei:[1,2,10,17],kept:0,kera:[1,12,14],kernel:[1,2,12],kernel_regular:2,kernelpca:9,kev:1,kevin:17,keyword:13,kfold:4,kick:[2,5],kind:[0,1,6,10],kjm:12,kkt:6,kmeanspoint:0,kn_k:0,know:[0,1,2,3,5,6,12,15],knowledg:[1,12],known:[2,3,4,5,6,7,10,13,15,17],kondev:1,kpca:9,kroneck:0,kuhn:6,kwarg:4,kwown:1,l1_l2:2,l_1:5,l_2:5,l_j:10,la_i:10,la_k:10,lab:[12,14],label:[0,1,2,3,4,5,6,7,8,10,12,13,15],labelencod:[5,8],labels:[6,7],labels_shuffl:2,labor:0,laboratori:14,lack:[0,1],lagrang:[6,9],lambda:[1,2,3,4,5,6,8,10,15],lambda_0:9,lambda_1:[3,6,9],lambda_2:[6,9],lambda_:9,lambda_i:[6,9],lambda_iy_i:6,lambda_jy_iy_j:6,lambda_k:6,lambda_n:[3,6],lamda:2,land:[1,6],landmark:6,landscap:5,langl:[1,9,15],languag:[1,2,6,12,13,17],lapack:13,laplac:3,laptop:12,larg:[1,2,3,4,5,6,7,8,9,12,13,15,17],larger:[1,3,4,5,6,8,9,15],largest:[6,9],lasso:[1,4,5,12,14],last:[0,1,2,3,4,5,6,7,8,10,13,15],later:[0,1,2,5,6,10,12,15],latex:[],latter:[1,5,6,9,13,15],lattic:10,law:1,layer:1,lbfg:[5,7,8,9],lbl:4,lcc:[3,4],lda:9,ldot:[1,4,9,15],lead:[1,2,3,4,5,6,7,8,9,10,13,15],leaf:7,leaki:2,lear:5,learn:[3,4,6,7,8,10,13,14,17],learner:8,learning_r:[6,8],learning_rate_init:[1,2],learning_schedul:5,least:[0,1,4,5,6,8,9,12,13,15],leav:[1,2,3,4,7,9],lectur:[1,2,3,5,8,9,10,12,13,14,17],lecturenot:[12,17],left:[1,2,3,4,5,6,7,8,9,10,13,15],leftarrow:[6,10],legend:[1,3,4,5,6,7,8],len:[0,1,2,3,4,6,7,8,9,10,13,15],length:[1,2,5,6,7,12,15],leq:[0,1,3,5,6,15],less:[1,2,3,4,6,7,15],lessen:2,let:[0,1,2,3,4,5,6,7,8,9,10,13,15],letter:[1,13,15],level:[1,2,4,7,12,13,14],lib:[1,2,3,4,6,9],liblinear:[6,8],librari:[1,2,3,7,8,9,13,15,17],licens:[1,2,12],lie:[4,9,15],lies:[6,9],life:[1,2,6,10],lift:0,light:[],like:[0,1,2,3,4,5,7,8,9,10,12,13,15],likelihood:[1,2,3,7],lim_:15,limit:[1,4,6,9,10,13],lin_clf:6,lin_model:1,lin_reg:7,linalg:[1,3,5,6,9,13,15],line1:6,line2:6,line3:6,line:[1,2,4,5,6,9,13,15],linear:[2,3,4,5,7,8,9,10,12,14,15],linear_model:[1,3,4,5,6,7,8,9],linear_regress:4,linearli:3,linearloc:5,linearregress:[1,4,5,7],linearsvc:6,liner:2,linerar:8,linewidth:[1,4,6,7,8],link:[1,5,7,10,12],linlag:3,linpack:13,linreg:1,linspac:[1,4,6,7,8,13,15],linu:16,linuek:16,linux:[1,2,12],liquid:1,list:[0,1,2,7,12],listedcolormap:[7,8],literatur:[0,2,5,17],littl:[2,7,10],live:6,lle:1,lloyd:0,lmb:[3,4],lmbd:[1,2],lmbd_val:[1,2],lmbda:5,load:[1,2,5,7,8],load_boston:1,load_breast_canc:[2,5,7,8,9],load_digit:2,load_iri:[6,7],loc:[1,4,5,6,7,8],local:[1,2,5,10],locat:6,log10:[3,4],log:[1,2,3,4,5,7,8,9,13],log_:1,log_clf:8,logarithm:[1,3,5,13],logic:[1,2,7],logist:[1,2,6,7,8,9,10,12,14],logisticregress:[5,7,8,9],logit:5,logreg:[5,7,8,9],logspac:[1,2,3,4],longer:[0,6,8,13,15],longest:0,loocv:4,look:[0,1,2,3,4,5,6,7,8,9,13,15],loop:[0,2,4,8,10,12,13,15],lose:2,loss:[1,2,3,4,6,8,9,13],lot:[0,1,2,4],low:[1,4,7,8,9,15],lower:[1,2,7,8,13],lowercas:13,lowest:[5,7,15],lstat:1,lstsq:1,lubksb:13,ludcmp:13,lux:13,lvert:2,m_1:0,m_h:1,m_k:0,m_l:10,m_n:1,m_p:1,machin:[2,3,4,7,8,9,10,13,14,17],machinelearn:[12,14,17],mackai:17,made:[1,2,3,4,5,7,9,10],mae:1,magic:0,magnitud:[2,5],mai:[1,2,3,4,5,6,7,9,10,12,13,15],mail:14,main:[1,2,3,5,7,13,17],mainli:[1,3,4,5,7],maintain:4,major:[2,4,5,7,8,13],make:[0,2,3,4,5,6,9,10,12,13,15,17],make_moon:[6,7,8],make_pipelin:[1,4,8],makedir:[1,4,5,7],makeplot:1,malcondit:13,malign:[2,5,7],mammographi:3,manag:[1,12],manhattan:0,mani:[0,1,2,3,4,5,6,7,9,11,12,13,15,17],manifold:9,manual:0,map:[0,1,2,4,5,6,9,10,15],margin:[1,3,6],marit:1,mark:[],marker:[1,5,13],markov:12,marsaglia:15,mask:15,mass:[1,2,3],massag:1,masses2016:1,masses2016ol:1,masses2016tre:1,masseval2016:1,master:14,mat1100:12,mat1110:12,mat1120:12,mat3155:14,mat4155:14,mat:12,match:[0,2,3,5],materi:[3,5,13],math:[0,5,10,13,15,17],mathbb:[0,1,3,4,5,6,9,10,13,15],mathbf:[1,3,4,5,6,13,15],mathcal:[2,3,4,5],mathemat:[0,1,5,9,10,12,13,15,17],mathemati:[],mathemt:[],mathrm:[0,1,2,3,4,5,6,7,8,9,10,15],matmul:[2,3],matnat:[16,17],matplotlib:[0,1,2,3,4,5,6,7,8,9,10,12,13,15],matric:[1,2,5,6,9,12,13],matrix:[1,4,6,8],matshow:2,matter:5,max:[1,2,5,7,8,10],max_depth:[1,7,8],max_it:[1,2,5,6,9],max_iter:0,max_leaf_nod:8,max_sampl:8,maxdegre:[1,4,8],maxdepth:8,maxim:[2,3,5,6,9],maximum:[0,1,2,3,5,6,7,8],maxpolydegre:[3,4],mbox:[3,4],mcculloch:10,mcint:15,mcintsqr2:15,mean:[1,2,3,4,5,7,8,9,10,12,13,14],mean_absolute_error:1,mean_divisor:0,mean_i:15,mean_matrix:0,mean_squared_error:[1,4,5,8],mean_squared_log_error:1,mean_vector:0,mean_x:15,meaning:[1,5],meansquarederror:1,meant:[5,8],meantempvec:15,meanvec:15,measur:[0,1,2,3,4,7,9,10,15],mechan:[1,15],median:1,medicin:10,medium:6,medv:1,meet:[1,16],mehta:[1,3],memori:[9,10,13],mention:[0,1,5,10,15],mere:1,mersienn:15,meshgrid:[1,3,6,7,8,9],met:[1,6],meteorolog:7,method:[0,1,2,3,6,9,10,12,13,14,17],metric:[0,1,2,4,5,7,8],metropoli:12,mev:[1,15],mglearn:12,mgrid:5,mhjensen:[1,2,6,9],microsoft:17,mid:2,midpoint:7,might:[1,2,5,7],mild:7,miller:15,million:1,mimic:10,min:[1,3,6,7],min_:[0,1,3],min_samples_leaf:7,mind:[0,1,5],mine:12,mini:[2,5,9,10],minibatch:[2,5,9],minibathc:5,minim:[0,1,2,3,4,5,6,7,8,9,10,15],minima:[1,2,5],minimum:[1,2,4,5,6,7,9],minkowski:0,minmaxscal:1,minor:15,minst:2,minu:5,mirror:7,misclassif:[6,7,8],misclassifi:[6,8],mismatch:2,miss:[1,8],mit:17,mix:2,mkdir:[1,4,5,7],mlab:[4,15],mle:[3,5],mlp:2,mlpclassifi:2,mlpregressor:1,mnist:[2,9],mod:15,mode:[14,15],model:[0,3,4,5,6,7,8,9,12,15,17],model_select:[1,2,3,4,5,7,8,9],moder:8,modern:[1,4,5,12],modif:10,modifi:[1,2,3,5,6,8,10],modul:[1,3,4,5,7,8,9,13],modular:15,modulenotfounderror:7,modulo:15,moe:[3,9],moment:[3,4],monoton:[3,10,15],mont:[1,4,12,15,17],montecarlocycl:15,moor:3,more:[1,2,3,4,6,7,8,9,10,12,14,15],moreov:1,morten:16,most:[0,1,2,3,4,5,6,7,8,9,10,12,15],mostli:[2,9],motion:1,motiv:2,move:[0,1,3,5,7,10,15],mpl:[1,5],mpl_toolkit:5,mplot3d:5,mplregressor:2,mse:[1,3,4,7,8],mse_simpletre:8,mselassopredict:3,mselassotrain:3,msepredict:3,mseridgepredict:3,msetrain:3,msg:1,msle:1,mt19937_64:15,mu0:15,mu1:15,mu2:15,mu_:15,mu_n:9,mu_x:15,much:[1,2,3,4,5,6,7,8,9,10,13,15],multi:[1,2,5,12],multiclass:[2,5],multidimension:[9,10],multilay:2,multinomi:5,multipl:[3,4,5,10,15],multipli:[3,5,9,13,15],multiplum:6,multitud:[],multivari:[1,8,9,12,15],multivariate_norm:[0,9],murphi:[9,17],must:[0,2,3,4,5,6,8,10,15],mutat:5,mutual:[2,4,5],mx_:15,myriad:[1,12],mz1:15,mz2:15,n_0:[10,15],n_b:15,n_boostrap:[4,8],n_bootstrap:4,n_categori:2,n_cluster:0,n_compon:9,n_epoch:5,n_estim:8,n_featur:2,n_hidden_neuron:[1,2],n_i:15,n_input:2,n_instanc:7,n_iter_i:9,n_job:8,n_k:0,n_l:[10,15],n_layer:2,n_m:7,n_neuron:2,n_neurons_layer1:2,n_neurons_layer2:2,n_point:0,n_sampl:[0,4,6,7,8],n_split:4,nabla:[2,5],nabla_:5,naimi:1,naiv:[0,5],nall:1,name:[0,1,2,3,4,5,6,7,8,10,12,13,16],nameerror:8,namespac:15,nation:[2,3],nativ:12,natur:[1,2,5,6,7,10,15,17],navier:10,nb_:13,nbconvert:[],nboot:15,nearest:[2,9],nearli:5,neat:[],neccesari:4,necessari:[0,1,2,6],necessarili:[1,9,15],necesserali:3,neck:5,need:[0,1,2,3,4,5,6,7,8,9,10,13,15],neg:[1,2,3,4,5,8,15],neg_mean_squared_error:4,neglect:15,neglig:15,neighbor:9,neq:[0,5,15],nervou:10,nest:[7,10],net:10,netlib:13,network:[1,7,12,14,17],neural:[1,5,12,14,17],neural_network:[1,2],neuralnetwork:2,neuron:[2,10],neutral:1,neutron:1,never:[2,4,7,15],new_hobbit:[],new_sig:4,newaxi:[1,4,7],newli:1,newton:[2,6,15],next:[0,1,2,3,5,6,7,15],next_guess:5,nian:16,nice:[0,1,2,3,9],nichola:16,nicholaskarlsen1102:16,niter:5,nitric:1,nlambda:[3,4],nm_n:1,nmse:4,nn_model:2,node:[2,7,8,10],nois:[1,3,4,5,6,7,8],noisi:[2,4],non:[0,1,2,3,4,5,7,8,9,10,13,15],none:[0,1,2,3,4,5,7,8,15],nonetheless:0,nonlinear:[4,6,7,9,10],nonneg:[4,5,7],nonparametr:4,nonsens:15,nonsingular:13,nonumb:[5,6,13],nor:2,norm:[1,2,3,4,5,6,9],normal:[3,4,5,6,7,8,9,10,12,13],normali:13,normpdf:4,notat:[0,1,3,4,15],note:[0,1,2,3,4,5,6,9,10,12,13,14,15,17],notebook:[0,1,2,7,12],noth:[0,2,3,6,10,15],notic:[3,10,13,15],novel:[4,8],novemb:2,now:[0,1,3,4,5,6,8,9,10,13,15],nowadai:[1,2,7,12],nox:1,np_assign_points_to_clust:0,np_get_distances_to_clust:0,np_k_mean:0,nsampl:4,nspin:15,nthi:1,nuclear:3,nuclei:[1,15],nucleon:1,nucleu:1,num_tre:8,number:[0,2,3,4,5,6,7,8,9,10,13,14,16],numberid:5,numer:[1,3,4,5,7,8,9,10,12,13,17],numpi:[0,1,2,3,4,5,6,7,8,9,10,12,15],nunmpi:3,obei:[5,9],object:[1,2,4,6,8,13],obliqu:3,observ:[0,2,3,4,5,6,7,8,9,10],obtain:[0,1,2,3,4,5,6,7,8,10,13,15],obviou:[3,9,15],obviouli:1,obvious:[1,3,13],occupi:1,occur:[1,6,7,15],odd:[1,5],off:[2,3,4,7,15],offend:[],offer:[4,9,12,13,14],offic:16,offici:14,ofil:15,ofstream:15,often:[0,1,2,3,4,5,6,7,8,9,10,12,13,15],ofter:13,old:[2,3,5,8],olsbeta:3,omit:[1,3],onc:[0,2,4,7,9,15],one:[0,1,2,3,4,6,7,8,9,12,13,15],onehot:2,onehot_vector:2,onehotencod:7,ones:[1,3,5,6,7,8,9,13],onli:[0,1,2,3,4,5,6,7,8,9,10,13,15],onlin:[9,14],onto:[3,9],open:[1,2,4,5,7,12,14,15],oper:[1,2,3,4,8,9,10,12,13,15],operation:15,opinion:0,oplu:15,opmiz:5,opportun:1,opposit:[2,3,6],opt:[1,2,3,4,6,9],optim:[0,1,3,4,7,8,9,14],optimis:2,option:[2,3,6,9],optmiz:[2,6],orang:1,order:[1,2,3,4,5,6,7,8,9,10,13,15],ordinari:[1,4,5,9,12,14],oreilli:17,org:[9,12,13,17],organ:[0,4,5,8,13],orient:[2,3,4,15],origin:[1,3,4,6,9,10,13,15],orthogn:3,orthogon:[1,3,5,6,9,13],orthonorm:3,oscar:2,oslo:[1,14,16],osx:[1,12],other:[0,1,2,3,4,5,6,8,12,13,14,17],otherwis:[1,2,5],ouput:[3,5,10],our:[2,4,6,7,8,10,12,13],ourselv:[0,1,3,5,6,9],out:[0,1,2,3,4,5,6,7,8,9,10,12,13,15],out_fil:7,outcom:[1,5,7,8,10,15],outdoor:7,outer:10,outfilenam:15,outlier:[1,6],outlin:[4,8,9],outlook:7,outperform:8,output:[1,2,3,5,6,7,8,10,13],output_bia:2,output_bias_gradi:2,output_weight:2,output_weights_gradi:2,outputlayer1:10,outputlayer2:10,over:[0,1,2,3,4,5,7,8,10,15],overal:[2,8],overcast:7,overcom:10,overdetermin:1,overfit:[2,4,7,8],overflow:[2,3],overhead:10,overlap:[5,6,7],overlin:[0,3,4,7,8,9,13],overst:1,overview:[0,17],own:[3,5,6,10,12,13],owner:1,oxid:1,oyvinssc:16,p_i:[3,15],p_j:15,p_n:15,p_x:15,pack:1,packag:[1,2,3,4,5,6,9,12,15],page:[1,12],pai:[2,7],painless:[],pair:[1,7,12,15],panda:[1,3,4,5,7,9,12],panel:[],paper:2,paradigm:1,parallel:[8,13],paramet:[1,2,3,4,5,6,7,8,10,15],parameter:[1,8],parametr:[1,4],paramt:3,park:15,part:[0,1,2,3,4,8,13,14,15,17],partial:[1,2,3,5,6,8,9,10,15],particip:[12,14],particl:[1,15],particular:[1,2,3,4,5,7,8,9,10,15,17],particularli:[3,4,5,6,9,15],partit:[2,7],pass:[0,10,15],past:[8,15],patch:[4,15],path:[1,4,5,7,12],patient:5,pattern:[1,10,14,17],pauli:1,pca:[1,5,12,14],pdf:[1,3,4,7,17],pedagog:1,penalti:[4,5],penros:3,pentagon:5,peopl:[1,2,7,12],per:[1,2,4,14],percentag:[1,8,9],perceptron:[1,2,5],peregrin:[],perfect:[1,2],perfectli:4,perform:[0,1,3,4,5,6,8,9,10,12,13,15],perhap:[1,3,5],perimet:2,period:2,permut:9,person:[3,5,14,16],perspect:17,pertin:10,petal:[6,7],peter:17,petersen:15,phantom:15,phase:10,phatak:0,phenomena:15,phi:6,phi_k:6,philip:16,philosophi:5,phone:16,phrase:1,physic:[1,2,5,10,15,16,17],pick:[0,2,5,7,8,9,15],pickl:2,pictur:1,pie:12,piec:[0,9],pillow:[1,12],pinv:3,pip3:[1,2],pip:[1,2,12],pipelin:[1,4,6,8],pippin:[],pise:0,pitt:10,pixel:2,pixel_height:2,pixel_width:2,place:[1,4,5,6,13],plai:[1,3,4,6,9,12],plain:[5,6,8,10],plan:[4,7,16,17],plane:[6,7],plateau:[3,15],platform:12,plausibl:10,pleas:[1,9],plenti:2,plethora:10,plot:[0,1,2,3,4,5,6,7,8,9,10,12,13,15],plot_confusion_matrix:[5,8],plot_cumulative_gain:[5,8],plot_data:2,plot_dataset:6,plot_decision_boundari:[7,8],plot_import:8,plot_predict:6,plot_regression_predict:7,plot_roc:[5,8],plot_surfac:5,plot_train:7,plot_tre:[7,8],plt:[0,1,2,3,4,5,6,7,8,9,10,13,15],plu:[1,3,5],png:[1,4,5,7],point:[0,1,2,3,4,5,6,7,8,9,13,15,16],points_in_clust:0,poisson:12,poli:[4,6],poly100_kernel_svm_clf:6,poly3:1,poly3_plot:1,poly_featur:[6,7],poly_features10:7,poly_fit10:7,poly_fit:7,poly_kernel_svm_clf:6,polydegre:[3,4,8],polygon:5,polym:10,polynomi:[1,3,4,5,6,7,8,9],polynomial_featur:4,polynomial_svm_clf:6,polynomialfeatur:[1,4,6,7],polytrop:[1,4],poor:[2,5],popul:[1,3],popular:[1,2,4,5,6,7,9,10,12,13,15],popularli:1,portabl:8,portion:9,pose:[1,9,15],posit:[0,1,2,3,5,6,8,9,13,15],possibl:[1,2,3,4,5,6,7,8,9,10,12,13,15,16],posterior:3,postpon:1,postul:3,potenti:[1,3,10],pott:10,power:[1,2,3,4,6,7,10],practic:[1,3,4,5,6,15],practition:[1,2],preced:[2,9,10,15],preceq:6,precis:[1,3,9,13,15],pred:4,predict:[1,2,3,4,5,6,7,8,12,17],predict_prob:2,predict_proba:[5,8],predictor:[1,3,5,7,8,9],prefer:[1,2,6,7,9,12],prepar:1,preprocess:[4,5,6,7,8,9],prerequisit:1,present:[1,3,7,10,15],preserv:9,press:[5,17],pretrain:2,pretti:[1,6,7,12],prev_centroid:0,prevent:15,previou:[1,2,3,5,6,8,9,10,13,15],previous:[0,7,8,15],price:[1,7],primal:6,primari:[1,5],primarili:0,prime:15,princip:[1,3,5,12,14],principl:[0,1,4,5,6],print:[0,1,2,3,4,5,6,7,8,9,13,15],print_funct:[6,7],printout:1,prior:[1,3,4],privat:1,prob:[2,15],probabilist:[1,17],probabl:[1,2,4,5,8,12],problem:[1,3,4,6,7,8,9,10,12,13,14,15],proce:[1,3,5,6,7,8,9,13],procedur:[3,4,5,6,8,9],proceed:13,process:[0,1,4,5,7,8,10,12,13,15,17],prod:17,prod_:[2,3,5],produc:[0,1,3,7,8,9,10,12,13,15],product:[1,2,3,4,5,6,10,12,13],profess:1,profil:0,program:[0,1,2,3,6,10,12,13,14,15],programm:13,progress:[0,2],progression_plot:0,prohibit:4,project:[1,2,3,5,9,12,14,15,16],project_root_dir:[1,4,5,7],promin:10,promis:6,prone:7,pronounc:12,proof:[1,5,9,10],prop:4,proper:[1,4],properli:[0,2,6,8],properti:[1,2,4,5,10,13],proport:[1,2,3,7,9,15],propos:[2,8],propto:[3,5],proton:1,prove:5,provid:[1,2,3,4,5,6,7,8,10,12,13,15,17],proxi:2,prun:0,prune:7,pseudoinv:3,pseudoinvers:3,pseudorandom:15,psycholog:1,ptratio:1,punish:[1,2],pure:[7,15],purest:7,puriti:7,purpos:[0,1,8,10],put:2,pycod:[],pydata:12,pydot:7,pyhton2:[],pylab:[1,5],pypi:12,pyplot:[0,1,2,3,4,5,6,7,8,9,10,13,15],pythagora:[0,3],python2:1,python3:[1,2,3,4,6,9,12],python:[2,3,6,9,10,14],pytorch:[1,12],qquad:[9,13],quad:[2,5,13],quadrat:[1,5,6,7],qualit:[7,15],qualiti:[1,7,12],quantifi:2,quantil:8,quantit:[1,4,7],quantiti:[0,1,3,4,5,7,8,9,10,13,15],quantum:10,quartil:1,queri:7,question:[1,3,4,5,7,9,10],quick:15,quickli:[2,5,7,9],quirk:0,quit:[2,3,4,7,8,10],quot:15,r2_score:1,r2score:1,r_1:7,r_2:7,r_j:7,r_m:7,rad:1,radial:[1,6,10],radioact:15,radiu:[1,2],rain:7,rais:[3,4],ramp:2,ran1:15,ran2:15,ran3:15,rand:[1,3,4,5,7,8,13,15],rand_max:15,randint:[4,5,7],randn:[1,2,3,4,5,7,9],random:[0,1,2,3,4,5,6,7,12,13,14],random_devic:15,random_forest_model:8,random_index:5,random_indic:2,random_st:[1,5,6,7,8,9],randomforestclassifi:8,randomli:[0,2,4,5,7,15],randomnumbergener:15,rang:[0,1,2,3,4,5,7,8,9,10,13,15],rangl:[1,9,15],rangle_x:15,rank:3,raphson:[2,6],rapidli:1,rare:2,rate:[1,2,5,6,7,8,10],rather:[1,2,3,4,5,6,7,8,9,10,13,15],ratio:[5,7,8,9],rational:1,ravel:[1,3,4,5,6,7,8,9],raw:15,rbf:[6,9,10],rbf_kernel_svm_clf:6,rbf_pca:9,rcond:1,rcparam:[1,2,5,6,7,8,15],reach:[0,1,2,3,4,5,7,8,9,10,15],read:[0,1,3,4,5,6,9,10,13,14,15,17],read_csv:[1,4,5,7],read_fwf:1,readabl:0,reader:[1,13,15],readi:[0,1,2,3,6,8,9,10,13],readili:2,real:[1,2,4,5,8,9,10,13],realist:6,realiti:15,realiz:[2,10],realli:2,reason:[0,1,2,5,8,17],reassign:2,recal:[3,4,5,7,8,9,10,13,15],recalcul:15,receiv:[2,8,10,15],recent:[1,3,4,5,7,8],recept:10,recip:[1,5,13],reciproc:3,recogn:[1,3,8],recognit:[1,2,10,14,17],recommend:[1,3,6,12,13,14,15,17],reconsid:7,reconstruct:9,record:[8,14],recreat:15,rectangl:[4,5,7],rectangular:3,rectifi:[2,10],recur:[1,12],recurr:[2,12,14],recurs:[7,12,13],recycl:15,red:[1,4,6,7],redefin:[1,8],reduc:[2,3,5,7,8,9],reduct:[1,8,9,12,15],refer:[0,1,2,3,4,5,9,10,13,17],refin:10,refit:4,reflect:[1,2,15],refresh:[12,14],reg:[8,9],regard:[2,5,7],regardless:10,region:[7,10],regist:15,reglasso:3,regr_1:[1,7],regr_2:[1,7],regr_3:[1,7],regress:[2,4,6,9,10,12,14],regressor:[1,5,8],regridg:3,regular:[1,3,5,7],reilli:[1,17],reinforc:[1,6,12],reiter:2,rel:[1,4,5,7,10,15],relat:[0,1,2,3,5,9,13,15],relationship:[1,7],relativeerror:1,releas:[2,12],relev:[1,2,3,5,9,12,15],reli:[1,6],reliabl:[5,15],remain:[2,4,10,13,15],remaind:15,remark:2,rememb:[1,6,13],remind:[1,3,9,13,15],remov:[1,3],render:1,reorder:[3,5],reorgan:1,repeat:[0,1,2,3,4,5,7,8,9,13,15],repeated:1,repeatedli:[4,8,15],repetit:[4,14],rephras:5,replac:[0,1,2,3,4,5,8,10],replica:4,repositori:1,repres:[1,2,3,4,5,6,7,8,10,15],represent:[1,2,4,15],reproduc:[1,7,10,12,15],repuls:1,request:1,requir:[1,2,3,4,5,6,7,9,10,13],resampl:[1,5,8,12,14,15],rescal:[1,9,10],rescu:3,research:[1,12,17],resembl:[4,15],reserv:[2,3,4,15],reset:15,reshap:[0,1,2,4,6,7,8],residenti:1,residu:[1,3,5],resiz:3,respect:[0,1,2,3,4,5,6,8,9,10,15],respond:10,respons:[1,5,7,10],rest:[1,3],restat:[1,10],restrict:[1,7,10],result:[0,1,2,3,4,5,6,7,8,9,10,12,13,15],ret:4,retail:1,retain:[3,4],return_data:0,return_x_i:7,reus:2,reveal:[1,10],revers:2,review:[12,13],revisit:0,reward:1,rewrit:[1,3,4,5,6,8,9,10,13,15],rewritten:[4,6,8,15],rewrot:5,rgoj5yh7evk:12,rho:[1,8],rho_1:8,rho_2:8,rho_m:8,rich:1,rid:0,ride:7,rideclass:7,ridedata:7,ridg:[1,4,9,12,14],ridgebeta:3,right:[1,2,3,4,5,6,7,8,10,13,15],rightarrow:[1,2,3,5,6,9,10,15],rigor:1,rise:1,risk:[1,5],river:1,rmse:1,rmsprop:2,rnd_clf:8,rnn:10,rntrick1:15,rntrick2:15,rntrick3:15,rntrick4:15,robert:17,robust:1,robustscal:1,roc:8,role:[1,3,4,6,12],room:[1,16],root:[1,3,5,7,15],rot:[],rotat:[2,6,7,8],rotation_matrix:7,roughli:2,round:[1,5,7],routin:[5,13],row:[1,2,3,4,7,9,13],rrr:3,rug:5,rule:[1,2,3],run:[0,1,2,3,4,5,6,7,9,12],runtim:[0,2,4],runtimewarn:2,rust:[1,12,13],rvert:2,rvert_2:2,rwidth:4,s_i:5,saddl:5,safe:15,sai:[0,1,2,3,4,5,6,7,8,9,10,13,15],said:[4,5,7],sake:[1,3,5,9],sale:1,sam:[],same:[0,1,2,3,4,5,6,7,9,10,13,15],samm:8,sampl:[0,1,2,3,4,5,6,7,8,12,13],sample_vari:0,sampleexptvari:15,samwis:[],sanitize_sequ:4,sastri:9,satisfactori:1,satisfi:[2,4,5,6,13,15],satur:[2,4],save:[1,4,5,7],save_fig:[1,4,5,7,8],savefig:[1,4,5,7,15],saw:3,scalabl:8,scalar:[3,4,8],scale:[1,2,3,5,6,7,8,9,10,12,16],scaler:[1,5,6,7,8,9],scan:[3,5],scari:3,scatter:[0,1,2,4,5,6,7],scenario:5,scheme:[2,5],schrage:15,scienc:[1,2,5,8,10,12,14,15,17],scientif:[1,12],scientist:[0,1],scikit:[3,6,7,8,12,13,14,17],scikitlearn:1,scikitplot:[5,8],scipi:[1,3,5,12,13],score:[1,2,4,5,7,8,9,16],scores_kfold:4,scratch:2,sdg:5,seaborn:[1,2,5],seamless:[1,12],search:[1,2,3,5,7],sec:4,second:[0,1,3,4,5,6,7,9,10,12,13,15],secondeigvector:9,secondli:10,section:[0,9,11,13,14,15],sector:1,see:[0,1,2,3,4,5,6,8,9,10,12,13,14,15],seed:[0,1,2,3,4,5,6,7,9,15],seek:[2,6],seem:2,seemingli:1,seen:[1,2,8,10,15],segment:5,seldomli:1,select:[2,3,4,6,7,8,9,14,17],self:[2,3,4,15,17],semest:[5,14],semi:[5,6],send:[10,16],senior:14,sens:[1,4,6],sensit:[1,3,4,7],sentenc:10,separ:[0,1,2,4,6,7,10,12,15],sequenc:[0,5,7,8,10,12,13,15],sequenti:[2,8,10,15],seri:[1,2,3,5,8,9,10,13,14],serif:[1,5,15],serv:[1,2,3,5,17],session:[2,14],set:[0,2,3,4,5,6,8,9,12,13,15],set_:4,set_label:4,set_tick:[2,6],set_ticklabel:2,set_titl:[0,1,2,5,10],set_xlabel:[1,2,5,10],set_xlim:[5,10],set_xticklabel:2,set_ylabel:[1,2,5],set_ylim:[5,10],set_ytick:5,set_yticklabel:2,setiosflag:15,setminu:4,setosa:[6,7],setosa_or_versicolor:6,setp:4,setprecis:15,setup:[2,6,12],setw:15,sever:[1,3,4,5,6,7,9,10,12,13,14,15],sgd:2,sgd_clf:6,sgdclassifi:6,sgdreg:5,sgdregressor:5,sgn:3,shape:[0,1,2,3,4,5,6,7,8,9,13],share:2,she:5,shift:[2,10,15],shire:[],shortcom:5,shorter:15,shorthand:[],shortli:13,should:[0,1,3,4,6,7,9,10,13],show:[0,1,2,3,4,5,6,7,8,9,10,13,15],shown:[3,5,6,9,10,15],showpoint:15,shrink:[3,6,9],shrinkag:3,shrunk:9,shuffl:[2,4],side:[1,3,5,6,10,13],sigh:12,sigma0:15,sigma1:15,sigma2:15,sigma:[1,2,3,4,5,8,9,10,13,15],sigma_0:3,sigma_1:3,sigma_2:3,sigma_:[3,13,15],sigma_fn:[5,10],sigma_i:[1,3],sigma_j:3,sigma_m:15,sigma_n:[9,15],sigma_x:15,sigmoid:[2,5,6,8,10],sigmundson:16,sign:[2,5,6,8,15],signal:[2,8,10],signific:2,significantli:[2,5,15],sim:[3,4,15],similar:[0,1,2,3,4,5,6,7,8,9,12,13],similarli:[1,2,3,6,8,15],simpl:[0,2,3,4,6,8,9,10,12,13],simplepredict:8,simpler:[0,1,2,3,12],simplest:[0,1,2,7,8,10],simpletre:8,simpli:[1,2,3,4,6,7,8,9,10,12,13,15],simplic:[0,3,5,6,7,8,9,10],simplicti:3,simplifi:[1,4,7,12],simplist:15,simul:[4,15],simultan:4,sin:[1,2,7,10,13],sinc:[1,2,3,4,5,6,7,8,9,13,15,17],sine:10,singl:[2,3,5,6,7,10,13,15],singular:[1,4,5,13],site:[1,2,3,4,6,9,14],situat:[1,3,5],six:15,size:[1,2,3,4,5,6,7,8,9,13,15],sketch:8,ski:7,skill:1,skip:9,skl:1,sklearn:[1,2,3,4,5,6,7,8,9],skplt:[5,8],slack:6,slice:13,slide:[1,15],slight:4,slightli:[2,3,4,8,15],slope:[6,9,10],slow:[1,5,6],slower:[3,13],slowli:10,slp:2,small:[0,1,2,3,4,5,6,7,8,9,10,12,13,15],smaller:[1,2,4,5,6,7,9,15],smallest:[0,1],smallest_row_index:0,smart:4,smooth:[1,5],sne:9,sneak:1,sns:[1,2,5],soar:4,social:1,soft:[2,5,8,10],soften:6,softmax:5,softwar:[1,6,12,13,14],sol:6,sole:1,solid:[1,5],solut:[1,2,3,4,5,6,8,9,13,15],solv:[1,2,3,6,8,9,10,13],solver:[5,6,7,8,9,13],some:[0,1,2,3,4,6,7,8,9,10,13,15],someth:[1,2,5,7,9,15],sometim:[0,1,2,9,10],soon:13,sophist:1,sopt:5,sort:[1,3,4,7,9,15],sound:3,sourc:[0,1,2,4,12,13,15],space:[0,1,2,3,5,6,7,9,10,15],span:[1,3,7,9,13],spare:2,spars:13,sparse_mtx:13,sparsiti:8,spatial:[2,10],speak:15,special:[4,5,8,10,13,15],specif:[1,2,3,4,5,6,7,9,10,12,13,15],specifi:[0,1,3,4,5,7,9,15],specifici:[1,8],spectral:2,speech:[1,2,10],speed:2,spend:15,sphere:1,spite:1,spline:6,split:[0,2,3,4,6,7,8,9,15],splitter:[2,8],spontan:15,spread:[1,9,15],springer:17,sqquar:3,sqrt:[1,3,4,5,6,8,9,15],squar:[0,1,2,4,5,6,7,9,12,13,15],squarederror:8,squaredeuclidean:0,squash:10,srand:15,stabl:[1,3,7,9,12],stack:4,stage:5,stai:[1,3,9],stand:[1,3,7,10],standard:[1,2,3,4,6,8,10,13],standardscal:[1,5,6,7,8,9],stanford:5,start:[0,1,2,3,4,5,6,7,8,9,10,13,15],start_tim:0,startpoint:15,stat:4,state:[0,2,3,5,6,8,9,10,12,15],statement:[1,5,13],statis:[],statist:[0,1,2,5,7,8,9,10,13,14,17],statu:[1,5,9],std:[4,15],stdev:15,steep:5,step:[0,1,2,7,8,9,10,13,15],step_fn:[5,10],step_length:5,steps_list:7,stian:16,still:[3,4,5,9,15],stimuli:10,stk2100:17,stk4021:17,stk4051:17,stk5000:17,stk:17,stochast:[1,2,3,4,6,9,10],stoke:10,stone:[1,5],stop:[0,2,7,9,15],storag:3,store:[1,2,5,9,15],str:2,straight:[1,4,5,6],straightforward:[1,3,4,5,6,7,8,13],strategi:[1,2,7],stratifi:4,strength:[0,3],stretch:9,strict:[5,6],strictli:[5,6],string:[2,15],stroke:5,strong:[7,8,10,15],strongli:[1,6,12,13],stronli:1,structur:[0,1,2,4,7,8,10,12],stuck:[2,5],student:[1,14,16,17],studi:[0,1,3,5,6,9,10,12,17],studier:17,style:[1,5,7],sub:[7,10],subdivid:[1,13],subfield:1,subject:[6,15],subplot:[0,1,2,4,5,6,7,8],subplots_adjust:[6,15],subprogram:13,subroutin:1,subscript:2,subsequ:[2,3,4,10,13,15],subset:[2,4,5,7,10,12],subspac:[1,6,9],substanti:[7,8],substep:9,substitut:[4,10,13],subsubset:7,subtl:2,subtract:[3,4,9,13,15],subtre:7,succeed:1,success:[5,7,15],successfulli:7,sucess:15,sudo:[1,12],suffer:[1,2,3,8],suffici:[2,4,5,6,9],suggest:[2,5,17],suit:[6,10],suitabl:[1,15],sum:[0,1,2,3,4,5,6,7,8,9,10,15],sum_:[0,1,2,3,4,5,6,7,8,9,10,13,15],sum_i:[3,4,5,6],sum_k:[6,10,13],summar:[0,3,4,7],summari:[0,2,8,14],summat:[],sunni:7,superscript:[2,10],supervis:[1,3,4,5,7,10,12],supplement:5,support:[1,2,7,8,9,12],suppos:[1,3,4,5,6,8,9,10,13],suppress:3,sure:2,surfac:1,surpris:1,surround:12,survei:[1,3],svc:[6,7,8],svd:[1,4,9],svdinv:3,svm:[6,7,8,9],svm_clf:[6,8],swath:3,symbol:[2,3,9,12,15],symmeteri:2,symmetr:[1,3,5,6,9,10,13],sympi:[1,12],synonim:15,syntax:[2,13],syntaxerror:[2,6,13],sys:5,system:[1,2,5,7,8,10,12,13,17],systemat:[4,15],t_0:[5,7],t_1:5,t_b:8,t_i:[2,10],t_j:[3,10],t_k:7,tabl:[7,15,16],tabul:1,tabular:[],tackl:0,tag:[0,3,5,10,13,15],taht:1,tail:15,tailor:[6,9],taiwan:1,take:[0,1,2,3,4,5,6,7,8,9,10,12,13,15],taken:[1,2,4,8,13],tangent:[2,5,10],tanh:[2,5,6,10],target:[1,2,3,5,6,7,8,9,10],target_nam:7,task:[0,1,2,4,7,9,10],tau:[3,15],tax:1,taylor:5,taylornr:5,team:2,teaser:1,technic:[0,1,3],techniqu:[1,2,6,8,12,15,17],technolog:[1,2],tek5040:17,tell:[4,5,8,9,15],temp1:2,temp2:2,temp:2,temperatur:[1,7],temporarili:2,ten:[],tend:[0,3,4,6,7,8,10],tendenc:1,tension:4,tensorflow:[0,1,6,12,13,14,17],term1:[1,3,9],term2:[1,3,9],term3:[1,3,9],term4:[1,3,9],term:[0,1,2,3,4,5,6,7,8,9,10,15],termin:[1,3,7,8],test:[3,4,5,6,7,8,15],test_accuraci:2,test_data:0,test_ind:4,test_pr:2,test_predict:2,test_scor:[5,8],test_siz:[1,2,3,4,8],test_split:7,tester:3,testerror:4,text:[1,2,3,5,6,7,9,13,15,17],textual:7,textur:2,than:[1,2,3,4,7,8,9,10,12,15],thats:0,theano:[2,12],thei:[0,1,2,3,4,5,6,7,9,10,13,15],them:[1,2,5,6,7,8,9,10,13],theme:1,themselv:[1,15],thenc:4,theorem:[4,5],theoret:[1,8],theori:[1,2,5,6,7,10,12,17],thereaft:[1,4,9,10,13],therebi:[1,3,5,9,15],therefor:[1,2,4,5,6,9,15],therein:9,thereof:[1,4,5],theta:[2,4,5,15],theta_:2,theta_i:2,theta_k:15,theta_linreg:5,thi:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,17],thing:[0,1,2,3,5,7,15],think:[0,1,2,4,5,7,10,15],third:[1,5],thirti:5,thorough:0,those:[0,3,6,7,8,9,13,14],though:[2,13,15],thought:[0,4,15],thousand:[1,2],three:[1,2,3,4,6,7,10,13,14,16],threshold:[2,5,7,8,9,10],through:[0,1,2,3,5,6,9,10,12,13,15],throughout:[0,1,12,13,15],thu:[1,2,3,4,5,6,8,9,10,15,16],thumb:1,thursdai:14,tibshirani:[14,17],ticker:[5,15],tight_layout:[2,5],tightli:9,tild:[1,3,4,9,15],till:[1,5,6,7,8,10,13],time:[0,1,2,3,4,5,6,7,8,9,10,13,14,15],timefunct:15,tini:2,tip:11,titl:[1,2,4,5,6,7,8,15],to_categor:2,to_categorical_numpi:2,to_numer:[1,4],to_str:15,togeth:[1,6,9],toi:0,toler:0,tomographi:10,too:[1,3,4,5,7,9,15,17],took:6,tool:[0,1,2,4,12,15],toolbox:6,top:[1,3,4,7,8,12],topic:[0,1,3,5,6,12,17],topolog:[2,10],toss:8,total:[0,1,2,4,5,6,8,9,10,15,16],totalclustervari:0,totalscatt:0,totalvari:15,toward:[2,5,10],town:1,tpng:7,traceback:[3,4,5,7,8],track:[0,5,13],tract:1,tractabl:1,trade:[3,4,7],tradeoff:[1,3,14],tradit:[1,2,4],train:[3,4,5,6,7,8,9,10],train_accuraci:[1,2],train_end:2,train_ind:4,train_pr:2,train_siz:2,train_test_split:[1,2,3,4,5,7,8,9],train_test_split_numpi:2,trainingerror:4,trait:1,transfer:7,transform:[1,3,4,5,6,7,8,9,10,12,13],transit:10,translat:[2,8],transpos:[2,3,9],treat:[1,2,4,5,10,15],tree:[1,2,12,14],tree_clf:[7,8],tree_clf_:7,tree_clf_sr:7,tree_reg1:7,tree_reg2:7,tree_reg:7,trend:15,trevor:17,tri:7,trial:[1,4,5,15],triangl:5,triangular:13,trick:[6,9,15],trickier:15,tridiagon:13,trillion:12,trivial:[1,2,3,9,15],troubl:[1,6,10],true_divid:2,true_fun:4,tucker:6,tumor:[5,7],tumour:5,tunabl:2,tune:[7,13],turn:[1,2,3,4,5,6,7,8,9,10,13,15],tutori:2,tweak:[2,8,15],twice:5,twist:9,twister:15,two:[0,1,2,3,4,5,7,8,9,10,13,14,15,17],tx_1:5,type:[1,2,4,5,6,8,13,15],typeerror:[],typic:[1,2,3,5,7,8,10,15],u_i:10,u_m:8,ubuntu:[1,12],uci:1,uio:[16,17],unari:13,unbalanc:[4,7],unbias:[1,3,4,15],uncertainti:[1,3],uncertitud:15,unchang:2,uncorrel:8,undefin:3,under:[1,2,3,4,5,8,12],underdetermin:1,underfit:[2,4],underflowproblem:3,undergo:3,undergradu:14,underli:[1,2,5,7,15],underset:0,understand:[0,1,2,3,5,8,12],understood:[0,6],undesir:6,undetermin:[3,6],unexpect:[4,15],unexpected:15,unfortun:[2,6,7,8],unicode_liter:[6,7],uniform:[1,2,3,5,9],uniform_real_distribut:15,uniformli:[5,15],unifrompdf:15,unimport:5,union:[3,4],uniqu:[0,1,4,5,13],unique_cluster_label:0,unit:[1,2,3,8,10,15],unitari:[3,13],unitarili:13,uniti:15,univari:15,univers:[1,2,5,14,16],unix:2,unknow:[1,13],unknown:[1,2,3,4,6,8,13],unknowwn:10,unlabel:2,unless:[1,4,5,9],unlik:[2,5,6,15],unnecessarili:7,unravel:2,unrol:9,unseen:[5,7],unstabl:2,unsupervis:[1,2,10,12,14],unsymmetr:13,until:[0,2,5,7,10,15],unusu:10,updat:[0,2,4,8,10],upload:[12,17],upon:[2,9,13],upper:[1,6,7,13],uppercas:[13,15],ups:[],usag:[1,6,12,15],usd10000:1,usd:1,use:[0,1,3,4,5,6,7,8,9,10,12,13,14],usecol:1,used:[0,1,2,3,4,6,7,8,9,10,12,13,15,17],useful:[1,2,3,4,5,7,9,10,12,13,15,17],useless:2,user:[1,2,5,6,9,12,13],uses:[1,2,3,4,7,9,10,13,15],usetex:15,using:[0,2,3,4,6,7,8,9,10,13],usr:15,usual:[0,1,5,10],util:[0,2,4,5,8],v_0:9,valid:[1,2,5,7,8,12,14,15],valu:[0,1,2,4,5,6,7,8,10,12,13],valuat:7,valueerror:[],van:[1,3],vandenbergh:[5,6],vandermond:1,vanilla:9,vanish:[2,5,15],var_x:15,varabl:6,varepsilon:[3,4],varepsilon_:[3,4],varepsilon_i:[3,4],vari:[1,2,4,8],variabl:[0,1,2,3,4,6,8,9,10,13],varianc:[0,1,2,3,5,7,8,9,12,13,14],variance_i:[3,9],variance_x:[3,9],variant:[1,2,4,5,6,10],variat:9,varieti:[1,10,12],variou:[2,3,5,6,7,9,10,12,13,15],vartempvec:15,varvec:15,vaue:2,vdot:5,vec:[4,15],vector:[0,1,2,3,4,5,7,8,9,12],vector_mean:0,ventur:[1,6,12],verbos:2,veri:[0,1,2,3,4,5,6,7,8,9,10,15,17],verifi:[9,13],versatil:6,versicolor:[6,7],version:[0,1,8,12,13,15],versu:2,vert:[1,2,3,5,6,7,9],vert_1:3,vert_2:[3,9],vertic:4,via:[1,3,4,5,6,7,8,9,10,12,13,14,15],vidal:9,video:[1,2,5,10,12,14],view:[2,3,10,15,17],violat:6,virginica:7,viridi:[1,2],virtual:2,vision:1,visual:[1,9,10,12],visualis:2,viz:[6,15],vmax:2,vmc:15,vmin:2,volum:1,vote:8,voting_clf:8,votingclassifi:8,votingsimpl:8,vstack:[3,9,13,15],w_1:[6,13],w_1x_1:6,w_1x_:6,w_2:[6,13],w_2x_2:6,w_2x_:6,w_3:13,w_4:13,w_i:[2,8],w_ix_i:10,w_j:13,w_m:13,w_px_:6,w_px_p:6,wai:[0,1,2,3,4,5,6,8,9,10,11,13,15],walk:7,walker:15,wang:1,want:[0,1,2,3,4,5,6,7,8,9,10,12,15],warn:[1,2,6],warrant:4,watch:12,wavelet:6,weak:[0,7,8],weather:[2,10],web:[12,14],websit:[13,14],wedg:[6,15],wednesdai:14,wee:9,week:[3,5],weekli:[12,17],weight:[1,2,4,5,7,8,10,15],welcom:[6,12],well:[1,2,3,4,5,6,7,8,10,12,13,15,17],went:6,were:[0,1,2,3,4,5,6,8,9,10,15],wessel:[1,3],what:[0,2,3,4,5,6,7,8,9,10,12,13,14],when:[0,1,2,3,4,6,7,8,9,10,13,15],whenev:15,where:[0,1,2,3,4,5,6,7,8,9,10,12,13,15,16],wherea:[4,15],wherein:[2,10],whether:[1,3,5,7,15],which:[0,1,3,4,5,6,7,8,9,10,12,13,14,16],whichev:2,white:7,who:[1,14],whole:[0,2,3,7,9],whose:[4,8,15],whow:[3,9],why:[1,2,5],wide:[1,2,4,5,10,12,13],widehat:4,width:[1,6,7],wieringen:[1,3],win:8,wind:7,wing:16,wiscons:5,wisconsin:8,wise:[1,2,3,10],wish:[0,1,3,5,6,9,13],within:[0,1,5,7,10,15,17],withinclust:0,without:[1,2,3,5,6,7,9,10],won:1,wonder:6,word:[0,1,2,3,15],work:[0,1,2,4,5,6,7,12,14,15],world:[1,6],worldwid:1,wors:[1,2,4],worth:7,would:[1,2,3,4,5,6,7,8,9,10,13,15],wrap:13,write:[1,2,3,5,6,10,11,13,14,15],written:[1,3,5,9,10,12,13,15],wrong:[2,6],wrongli:[8,15],wrote:[3,9],wrt:8,wth:8,www:[12,13,17],wx_1:6,x0s:6,x1_exampl:6,x1d:6,x1s:[6,7,8],x2d:[6,9],x2d_train:9,x2dsl:9,x2s:[6,7,8],x3s:6,x_0:[1,3,9,13],x_1:[1,3,4,5,6,7,8,9,13,15],x_2:[1,3,4,5,6,7,8,9,13,15],x_3:[6,13,15],x_4:13,x_center:9,x_data:2,x_data_ful:2,x_i:[0,1,2,3,4,5,6,7,8,9,10,13,15],x_ix_:1,x_iy_i:6,x_j:[6,7,10,15],x_jy_j:6,x_k:[0,10,13,15],x_l:15,x_m:[10,13,15],x_n:[1,4,5,6,9,10,13,15],x_new:[7,8],x_p:[5,7],x_poli:7,x_poly10:7,x_reduc:9,x_scale:6,x_test:[1,2,3,4,5,7,8,9],x_test_scal:[1,5,7,8,9],x_train:[1,2,3,4,5,7,8,9],x_train_scal:[1,5,7,8,9],x_val:2,xarrai:12,xavier:2,xbnew:5,xcode:[1,12],xdclassiffierconfus:8,xdclassiffierroc:8,xg_clf:8,xgb:8,xgbclassifi:8,xgboost:7,xgboot:8,xgbregressor:8,xgparam:8,xgtree:8,xi_1:6,xi_:6,xi_i:6,xlabel:[1,2,3,4,5,6,7,8,15],xlim:[4,8],xmesh:5,xnew:[1,5],xpd:[3,9],xplot:1,xsr:7,xt_x:5,xtest:4,xtick:[4,6,7],xtrain:4,xytext:6,y_0:[1,3,9,13],y_1:[1,3,5,6,7,9,13],y_1y_1:6,y_1y_1k:6,y_1y_2:6,y_1y_2k:6,y_1y_n:6,y_1y_nk:6,y_2:[1,3,6,7,9,13],y_2y_1:6,y_2y_1k:6,y_2y_2:6,y_2y_2k:6,y_3:[1,7,13],y_4:13,y_data:[1,2,3],y_data_ful:2,y_decis:6,y_i:[1,2,3,4,5,6,7,8,9,10,13],y_if_:8,y_ix_:1,y_ix_i:[5,6],y_iy_jk:6,y_j:[4,6,10],y_k:10,y_m:13,y_model:[1,3],y_n:[5,6],y_ny_1:6,y_ny_1k:6,y_ny_2:6,y_ny_2k:6,y_ny_n:6,y_ny_nk:6,y_plot:7,y_pred1:7,y_pred2:7,y_pred:[1,2,4,5,6,7,8],y_pred_rf:8,y_pred_tre:8,y_proba:[5,8],y_test:[1,2,3,4,5,7,8,9],y_test_onehot:2,y_test_predict:1,y_train:[1,2,3,4,5,7,8,9],y_train_onehot:2,y_train_predict:1,y_val:2,year:[1,12],yes:[4,5],yet:[1,2,4,6,9],yield:[0,1,3,4,5,6,8,10,13,15],ylabel:[1,2,3,4,5,6,7,8,15],ylim:4,ymesh:5,yoshua:[2,17],you:[0,1,2,3,4,5,6,7,8,9,12,13,15,17],young:1,your:[0,2,4,5,6,9,12,13,15],yourself:[5,9],youtub:12,ypred:4,ypredict2:5,ypredict:[1,5],ypredictlasso:3,ypredictol:3,ypredictridg:3,yridg:1,ytest:4,ytick:[4,6,7],ytild:[1,4],ytildelasso:3,ytildenp:1,ytildeol:3,ytilderidg:3,ytrain:4,z_0:13,z_1:13,z_2:13,z_c:2,z_h:2,z_i:[2,10],z_j:[2,10],z_k:10,z_m:2,z_mod:7,z_o:2,zaman:15,zero:[0,1,2,3,4,5,6,7,8,9,10,13,15],zm_h:1,zone:1},titles:["11. Clustering Analysis","3. Linear Regression","13. Building a Feed Forward Neural Network","4. Ridge and Lasso Regression","5. Resampling Methods","6. Logistic Regression","7. Support Vector Machines, overarching aims","8. Decision trees, overarching aims","9. Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods","10. Basic ideas of the Principal Component Analysis (PCA)","12. Neural networks","Content in Jupyter Book","Applied Data Analysis and Machine Learning, FYS-STK3155/4155 at the University of Oslo, Norway","2. Linear Algebra, Handling of Arrays and more Python Features","Teaching schedule with links to material","1. Elements of Probability Theory and Statistical Data Analysis","Teachers and Grading","Textbooks"],titleterms:{"2021":16,"4155":12,"case":[5,6,8,15],"final":[5,10],"function":[1,2,5,6,8,9,10,15],"import":[3,13,15],And:5,Eye:8,FYS:12,OLS:3,The:[0,1,2,3,4,5,6,7,9,10,12,15],Useful:12,Using:5,activ:[2,10],actual:15,adaboost:8,adapt:8,adjust:2,again:7,aim:[6,7],algebra:13,algorithm:[0,7,8,9,10],algortithm:5,all:6,analys:3,analysi:[0,1,3,9,12,15],ani:5,anoth:7,appli:12,approach:[1,5,6],approxim:10,architectur:2,arrai:13,assist:16,august:14,autocorrel:15,back:[2,9,10],background:12,bag:8,basic:[0,1,3,5,7,8,9,13],batch:2,bay:3,befor:9,better:[6,15],bia:4,binari:2,binomi:15,bird:8,block:15,book:11,boost:8,bootstrap:[4,8,15],boston:1,breast:2,brief:5,bring:10,build:[2,7],calcul:15,cancer:[2,5,7,9],cart:7,central:[5,12,15],chain:10,chang:8,chi:1,choos:2,classic:9,classif:[2,7,8],classifi:6,clip:2,cluster:0,code:[0,1,2,3,5,7,9,10,15],collect:2,compar:8,compon:9,comput:[5,7,15],con:7,concept:15,condit:5,conjug:5,content:11,continu:15,convex:[5,6],convolut:10,correl:[9,15],correspond:5,cost:[2,5,8],cours:[12,17],covari:[3,9,15],cross:4,cumul:15,cython:[],data:[1,2,5,7,9,12,15],dataset:2,decemb:14,decis:[7,8],decomposit:[3,9,13],deep:2,defin:2,definit:15,degre:1,demonstr:15,dens:1,deriv:[3,5,10],descent:[5,8],develop:2,deviat:15,diagon:9,dice:15,differ:[5,6],dimension:6,disadvantag:7,discret:15,disguis:15,distribut:[3,15],doing:2,domain:15,down:2,dropout:2,economi:[],element:[1,15],elimin:13,ensembl:8,entropi:7,environ:1,equat:[1,3,5,10],error:8,etc:[],evalu:2,event:15,exampl:[1,2,5,6,7,8,15],exercis:1,expect:15,experi:15,explor:1,exponenti:15,express:5,extend:5,extrem:8,fall:16,famili:2,famou:15,fantast:[],featur:[7,13],feed:[2,10],fine:2,first:[5,10],fit:[1,8],forest:8,forward:[2,10],frank:1,freedom:1,frequentist:1,fridai:5,from:[3,8,10],further:3,gaussian:[13,15],gener:[7,15],geometr:[5,9],gini:7,good:1,grade:16,gradient:[2,5,8],handl:13,has:12,hessian:5,homework:5,hous:1,how:15,hyperparamet:2,hyperplan:6,id3:7,idea:[0,9],ideal:5,implement:[2,15],implic:3,improv:2,increment:9,index:7,inform:16,instal:12,instructor:16,interpret:[3,5,9],introduc:9,introduct:[1,4,12,13],invers:[3,13],iter:[5,8],its:15,jackknif:15,julia:[],jungl:8,jupyt:11,kera:2,kernel:[6,9],lagrangian:6,lasso:3,later:3,layer:[2,10],learn:[1,2,5,9,12],least:3,level:8,librari:12,likelihood:5,limit:[2,5,15],linear:[1,6,13],link:[3,9,14,17],logist:5,loss:5,machin:[1,5,6,12],main:15,make:[1,7,8],mani:[8,10],materi:14,math:3,mathemat:[3,6],matric:3,matrix:[2,3,5,9,10,13,15],matter:1,mean:[0,15],meet:[3,8,15],mercer:6,mersenn:15,method:[4,5,7,8,15],mlp:10,model:[1,2,10],moment:15,moon:[6,7],more:[0,5,13],multilay:10,multipl:2,multipli:6,name:15,need:[],network:[2,5,10],neural:[2,10],newton:5,non:6,normal:[1,2,15],norwai:12,notat:10,novemb:14,now:[2,7],nuclear:1,nueral:5,numba:[],number:[1,15],numer:15,numpi:13,numpython:0,observ:15,obtain:9,octob:14,one:[5,10],optim:[2,5,6,12],ordinari:3,organ:1,oslo:[12,17],other:[7,9,10,15],our:[0,1,3,5,9,15],outcom:12,output:15,overarch:[1,6,7],overview:8,own:[0,1,8,9],packag:13,panda:[],part:[5,12],pass:2,pca:9,pdf:15,perceptron:10,perform:[2,7],period:15,perspect:2,poisson:15,pre:2,preprocess:1,prerequisit:12,princip:9,pro:7,probabl:[3,15],problem:[2,5],procedur:7,process:2,program:5,propag:[2,10],properti:[3,15],pseudo:15,python:[0,1,7,12,13,15],quick:6,ran0:15,random:[8,9,15],raphson:5,read:7,recip:15,recurr:10,reduc:1,regress:[1,3,5,7,8],regular:2,relev:17,relu:2,remind:[4,5,6],requir:12,resampl:4,revisit:5,ridg:[3,5],rng:15,rule:10,sampl:[9,15],schedul:14,schemat:7,scikit:[1,2,5,9],select:15,semest:16,sensit:5,septemb:[5,14],set:[1,7,10],sgd:5,should:[2,15],simpl:[1,5,7,15],singl:8,singular:[3,9],situat:15,size:[],slightli:5,soft:6,softmax:2,softwar:[],solv:5,some:5,split:1,squar:[3,8],standard:[5,15],state:1,statist:[3,4,12,15],steepest:[5,8],step:[4,5],stk3155:12,stochast:[5,15],stop:5,supervis:2,support:6,svd:3,teach:[14,16],teacher:16,techniqu:9,technolog:12,tensorflow:2,test:[1,2],textbook:17,than:5,theorem:[3,6,9,10,15],theori:15,three:15,togeth:10,top:2,toss:15,toward:[0,9],tradeoff:4,train:[1,2],tree:[7,8],tune:2,two:[6,12],type:10,uncorrel:15,understand:[],uniform:15,univers:[10,12,17],use:[2,15],used:5,using:[1,5,15],valid:4,valu:[3,9,15],variabl:[5,15],varianc:[4,15],variou:[1,4],vector:[6,10,13],view:[1,8],visual:[2,7],wai:7,week:14,weekli:14,what:[1,15],when:5,which:[2,15],why:15,wisconsin:5,write:[0,9],xgboost:8,your:[1,8]}})
\ No newline at end of file
diff --git a/doc/LectureNotes/_build/jupyter_execute/chapter2.ipynb b/doc/LectureNotes/_build/jupyter_execute/chapter2.ipynb
index 431ae83d6..ec7aa8c86 100644
--- a/doc/LectureNotes/_build/jupyter_execute/chapter2.ipynb
+++ b/doc/LectureNotes/_build/jupyter_execute/chapter2.ipynb
@@ -4,66 +4,3475 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "# Resampling Methods\n",
- "\n",
- "## Introduction\n",
- "\n",
- "Resampling methods are an indispensable tool in modern\n",
- "statistics. They involve repeatedly drawing samples from a training\n",
- "set and refitting a model of interest on each sample in order to\n",
- "obtain additional information about the fitted model. For example, in\n",
- "order to estimate the variability of a linear regression fit, we can\n",
- "repeatedly draw different samples from the training data, fit a linear\n",
- "regression to each new sample, and then examine the extent to which\n",
- "the resulting fits differ. Such an approach may allow us to obtain\n",
- "information that would not be available from fitting the model only\n",
- "once using the original training sample.\n",
- "\n",
- "Two resampling methods are often used in Machine Learning analyses,\n",
- "1. The **bootstrap method**\n",
- "\n",
- "2. and **Cross-Validation**\n",
- "\n",
- "In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular\n",
- "cross-validation and the bootstrap method. \n",
+ "# Ridge and Lasso Regression\n",
"\n",
"\n",
- "Resampling approaches can be computationally expensive, because they\n",
- "involve fitting the same statistical method multiple times using\n",
- "different subsets of the training data. However, due to recent\n",
- "advances in computing power, the computational requirements of\n",
- "resampling methods generally are not prohibitive. In this chapter, we\n",
- "discuss two of the most commonly used resampling methods,\n",
- "cross-validation and the bootstrap. Both methods are important tools\n",
- "in the practical application of many statistical learning\n",
- "procedures. For example, cross-validation can be used to estimate the\n",
- "test error associated with a given statistical learning method in\n",
- "order to evaluate its performance, or to select the appropriate level\n",
- "of flexibility. The process of evaluating a model’s performance is\n",
- "known as model assessment, whereas the process of selecting the proper\n",
- "level of flexibility for a model is known as model selection. The\n",
- "bootstrap is widely used.\n",
+ "\n",
+ "## Mathematical Interpretation of Ordinary Least Squares\n",
+ "\n",
+ "What is presented here is a mathematical analysis of various regression algorithms (ordinary least squares, Ridge and Lasso Regression). The analysis is based on an important algorithm in linear algebra, the so-called Singular Value Decomposition (SVD). \n",
"\n",
"\n",
- "* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods\n",
+ "We have shown that in ordinary least squares the optimal parameters $\\beta$ are given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The **hat** over $\\boldsymbol{\\beta}$ means we have the optimal parameters after minimization of the cost function.\n",
"\n",
- "* The results can be analysed with the same statistical tools as we would use analysing experimental data.\n",
- "\n",
- "* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n",
- "\n",
- "## Reminder on Statistics\n",
+ "This means that our best model is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}=\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}} = \\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We now define a matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can rewrite"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}=\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}} = \\boldsymbol{A}\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The matrix $\\boldsymbol{A}$ has the important property that $\\boldsymbol{A}^2=\\boldsymbol{A}$. This is the definition of a projection matrix.\n",
+ "We can then interpret our optimal model $\\tilde{\\boldsymbol{y}}$ as being represented by an orthogonal projection of $\\boldsymbol{y}$ onto a space defined by the column vectors of $\\boldsymbol{X}$. In our case here the matrix $\\boldsymbol{A}$ is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix.\n",
"\n",
"\n",
- "* As in other experiments, many numerical experiments have two classes of errors:\n",
- "\n",
- " * Statistical errors\n",
- "\n",
- " * Systematical errors\n",
"\n",
"\n",
- "* Statistical errors can be estimated using standard tools from statistics\n",
+ "We have defined the residual error as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\epsilon}=\\boldsymbol{y}-\\tilde{\\boldsymbol{y}}=\\left[\\boldsymbol{I}-\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\right]\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The residual errors are then the projections of $\\boldsymbol{y}$ onto the orthogonal component of the space defined by the column vectors of $\\boldsymbol{X}$.\n",
+ "\n",
+ "\n",
+ "If the matrix $\\boldsymbol{X}$ is an orthogonal (or unitary in case of complex values) matrix, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{X}\\boldsymbol{X}^T = \\boldsymbol{I}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this case the matrix $\\boldsymbol{A}$ becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T)=\\boldsymbol{I},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and we have the obvious case"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\epsilon}=\\boldsymbol{y}-\\tilde{\\boldsymbol{y}}=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This serves also as a useful test of our codes. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## The singular value decomposition\n",
+ "\n",
+ "\n",
+ "The examples we have looked at so far are cases where we normally can\n",
+ "invert the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$. Using a polynomial expansion where we fit of various functions leads to\n",
+ "row vectors of the design matrix which are essentially orthogonal due\n",
+ "to the polynomial character of our model. Obtaining the inverse of the\n",
+ "design matrix is then often done via a so-called LU, QR or Cholesky\n",
+ "decomposition.\n",
+ "\n",
+ "\n",
+ "As we will also see in the first project, \n",
+ "this may\n",
+ "however not the be case in general and a standard matrix inversion\n",
+ "algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.\n",
+ "\n",
+ "There is however a way to circumvent this problem and also\n",
+ "gain some insights about the ordinary least squares approach, and\n",
+ "later shrinkage methods like Ridge and Lasso regressions.\n",
+ "\n",
+ "This is given by the **Singular Value Decomposition** (SVD) algorithm,\n",
+ "perhaps the most powerful linear algebra algorithm. The SVD provides\n",
+ "a numerically stable matrix decomposition that is used in a large\n",
+ "swath oc applications and the decomposition is always stable\n",
+ "numerically.\n",
+ "\n",
+ "In machine learning it plays a central role in dealing with for\n",
+ "example design matrices that may be near singular or singular.\n",
+ "Furthermore, as we will see here, the singular values can be related\n",
+ "to the covariance matrix (and thereby the correlation matrix) and in\n",
+ "turn the variance of a given quantity. It plays also an important role\n",
+ "in the principal component analysis where high-dimensional data can be\n",
+ "reduced to the statistically relevant features.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "One of the typical problems we encounter with linear regression, in particular \n",
+ "when the matrix $\\boldsymbol{X}$ (our so-called design matrix) is high-dimensional, \n",
+ "are problems with near singular or singular matrices. The column vectors of $\\boldsymbol{X}$ \n",
+ "may be linearly dependent, normally referred to as super-collinearity. \n",
+ "This means that the matrix may be rank deficient and it is basically impossible to \n",
+ "to model the data using linear regression. As an example, consider the matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\mathbf{X} & = \\left[\n",
+ "\\begin{array}{rrr}\n",
+ "1 & -1 & 2\n",
+ "\\\\\n",
+ "1 & 0 & 1\n",
+ "\\\\\n",
+ "1 & 2 & -1\n",
+ "\\\\\n",
+ "1 & 1 & 0\n",
+ "\\end{array} \\right]\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The columns of $\\boldsymbol{X}$ are linearly dependent. We see this easily since the \n",
+ "the first column is the row-wise sum of the other two columns. The rank (more correct,\n",
+ "the column rank) of a matrix is the dimension of the space spanned by the\n",
+ "column vectors. Hence, the rank of $\\mathbf{X}$ is equal to the number\n",
+ "of linearly independent columns. In this particular case the matrix has rank 2.\n",
+ "\n",
+ "Super-collinearity of an $(n \\times p)$-dimensional design matrix $\\mathbf{X}$ implies\n",
+ "that the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\boldsymbol{X} & = \\left[\n",
+ "\\begin{array}{rr}\n",
+ "1 & -1\n",
+ "\\\\\n",
+ "1 & -1\n",
+ "\\end{array} \\right].\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see easily that $\\mbox{det}(\\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \\times (-1) - 1 \\times (-1) = 0$. Hence, $\\mathbf{X}$ is singular and its inverse is undefined.\n",
+ "This is equivalent to saying that the matrix $\\boldsymbol{X}$ has at least an eigenvalue which is zero.\n",
+ "\n",
+ "\n",
+ "\n",
+ "If our design matrix $\\boldsymbol{X}$ which enters the linear regression problem"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "
\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\boldsymbol{\\beta} = (\\boldsymbol{X}^{T} \\boldsymbol{X})^{-1} \\boldsymbol{X}^{T} \\boldsymbol{y},\n",
+ "\\label{_auto1} \\tag{1}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "has linearly dependent column vectors, we will not be able to compute the inverse\n",
+ "of $\\boldsymbol{X}^T\\boldsymbol{X}$ and we cannot find the parameters (estimators) $\\beta_i$. \n",
+ "The estimators are only well-defined if $(\\boldsymbol{X}^{T}\\boldsymbol{X})^{-1}$ exits. \n",
+ "This is more likely to happen when the matrix $\\boldsymbol{X}$ is high-dimensional. In this case it is likely to encounter a situation where \n",
+ "the regression parameters $\\beta_i$ cannot be estimated.\n",
+ "\n",
+ "A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^{T} \\boldsymbol{X} \\rightarrow \\boldsymbol{X}^{T} \\boldsymbol{X}+\\lambda \\boldsymbol{I},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\boldsymbol{I}$ is the identity matrix. When we discuss **Ridge** regression this is actually what we end up evaluating. The parameter $\\lambda$ is called a hyperparameter. More about this later. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Basic math of the SVD\n",
+ "\n",
+ "\n",
+ "From standard linear algebra we know that a square matrix $\\boldsymbol{X}$ can be diagonalized if and only it is \n",
+ "a so-called [normal matrix](https://en.wikipedia.org/wiki/Normal_matrix), that is if $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$\n",
+ "we have $\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ or if $\\boldsymbol{X}\\in {\\mathbb{C}}^{n\\times n}$ we have $\\boldsymbol{X}\\boldsymbol{X}^{\\dagger}=\\boldsymbol{X}^{\\dagger}\\boldsymbol{X}$.\n",
+ "The matrix has then a set of eigenpairs"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "(\\lambda_1,\\boldsymbol{u}_1),\\dots, (\\lambda_n,\\boldsymbol{u}_n),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and the eigenvalues are given by the diagonal matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}=\\mathrm{Diag}(\\lambda_1, \\dots,\\lambda_n).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The matrix $\\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\\boldsymbol{U}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ or $\\boldsymbol{U}\\boldsymbol{U}^{\\dagger}=\\boldsymbol{I}$.\n",
+ "\n",
+ "Not all square matrices are diagonalizable. A matrix like the one discussed above"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\begin{bmatrix} \n",
+ "1& -1 \\\\\n",
+ "1& -1\\\\\n",
+ "\\end{bmatrix}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "is not diagonalizable, it is a so-called [defective matrix](https://en.wikipedia.org/wiki/Defective_matrix). It is easy to see that the condition\n",
+ "$\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ is not fulfilled. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "However, and this is the strength of the SVD algorithm, any general\n",
+ "matrix $\\boldsymbol{X}$ can be decomposed in terms of a diagonal matrix and\n",
+ "two orthogonal/unitary matrices. The [Singular Value Decompostion\n",
+ "(SVD) theorem](https://en.wikipedia.org/wiki/Singular_value_decomposition)\n",
+ "states that a general $m\\times n$ matrix $\\boldsymbol{X}$ can be written in\n",
+ "terms of a diagonal matrix $\\boldsymbol{\\Sigma}$ of dimensionality $m\\times n$\n",
+ "and two orthognal matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$, where the first has\n",
+ "dimensionality $m \\times m$ and the last dimensionality $n\\times n$.\n",
+ "We have then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As an example, the above defective matrix can be decomposed as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& 1 \\\\ 1& -1\\\\ \\end{bmatrix} \\begin{bmatrix} 2& 0 \\\\ 0& 0\\\\ \\end{bmatrix} \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& -1 \\\\ 1& 1\\\\ \\end{bmatrix}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with eigenvalues $\\sigma_1=2$ and $\\sigma_2=0$. \n",
+ "The SVD exits always! \n",
+ "\n",
+ "The SVD\n",
+ "decomposition (singular values) gives eigenvalues \n",
+ "$\\sigma_i\\geq\\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=p$, the\n",
+ "eigenvalues (singular values) are zero.\n",
+ "\n",
+ "In the general case, where our design matrix $\\boldsymbol{X}$ has dimension\n",
+ "$n\\times p$, the matrix is thus decomposed into an $n\\times n$\n",
+ "orthogonal matrix $\\boldsymbol{U}$, a $p\\times p$ orthogonal matrix $\\boldsymbol{V}$\n",
+ "and a diagonal matrix $\\boldsymbol{\\Sigma}$ with $r=\\mathrm{min}(n,p)$\n",
+ "singular values $\\sigma_i\\geq 0$ on the main diagonal and zeros filling\n",
+ "the rest of the matrix. There are at most $p$ singular values\n",
+ "assuming that $n > p$. In our regression examples for the nuclear\n",
+ "masses and the equation of state this is indeed the case, while for\n",
+ "the Ising model we have $p > n$. These are often cases that lead to\n",
+ "near singular or singular matrices.\n",
+ "\n",
+ "The columns of $\\boldsymbol{U}$ are called the left singular vectors while the columns of $\\boldsymbol{V}$ are the right singular vectors.\n",
+ "\n",
+ "\n",
+ "If we assume that $n > p$, then our matrix $\\boldsymbol{U}$ has dimension $n\n",
+ "\\times n$. The last $n-p$ columns of $\\boldsymbol{U}$ become however\n",
+ "irrelevant in our calculations since they are multiplied with the\n",
+ "zeros in $\\boldsymbol{\\Sigma}$.\n",
+ "\n",
+ "The economy-size decomposition removes extra rows or columns of zeros\n",
+ "from the diagonal matrix of singular values, $\\boldsymbol{\\Sigma}$, along with the columns\n",
+ "in either $\\boldsymbol{U}$ or $\\boldsymbol{V}$ that multiply those zeros in the expression. \n",
+ "Removing these zeros and columns can improve execution time\n",
+ "and reduce storage requirements without compromising the accuracy of\n",
+ "the decomposition.\n",
+ "\n",
+ "If $n > p$, we keep only the first $p$ columns of $\\boldsymbol{U}$ and $\\boldsymbol{\\Sigma}$ has dimension $p\\times p$. \n",
+ "If $p > n$, then only the first $n$ columns of $\\boldsymbol{V}$ are computed and $\\boldsymbol{\\Sigma}$ has dimension $n\\times n$.\n",
+ "The $n=p$ case is obvious, we retain the full SVD. \n",
+ "In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.\n",
+ "\n",
+ "## Codes for the SVD"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[[ 1. -1.]\n",
+ " [ 1. -1.]]\n",
+ "test U\n",
+ "[[0. 0.]\n",
+ " [0. 0.]]\n",
+ "test VT\n",
+ "[[0. 0.]\n",
+ " [0. 0.]]\n",
+ "[[-0.70710678 -0.70710678]\n",
+ " [-0.70710678 0.70710678]]\n",
+ "[2. 0.]\n",
+ "[[-0.70710678 0.70710678]\n",
+ " [ 0.70710678 0.70710678]]\n",
+ "[[-3.33066907e-16 4.44089210e-16]\n",
+ " [ 0.00000000e+00 2.22044605e-16]]\n"
+ ]
+ }
+ ],
+ "source": [
+ "import numpy as np\n",
+ "# SVD inversion\n",
+ "def SVD(A):\n",
+ " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n",
+ " SVD is numerically more stable than the inversion algorithms provided by\n",
+ " numpy and scipy.linalg at the cost of being slower.\n",
+ " '''\n",
+ " U, S, VT = np.linalg.svd(A,full_matrices=True)\n",
+ " print('test U')\n",
+ " print( (np.transpose(U) @ U - U @np.transpose(U)))\n",
+ " print('test VT')\n",
+ " print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n",
+ " print(U)\n",
+ " print(S)\n",
+ " print(VT)\n",
+ "\n",
+ " D = np.zeros((len(U),len(VT)))\n",
+ " for i in range(0,len(VT)):\n",
+ " D[i,i]=S[i]\n",
+ " return U @ D @ VT\n",
+ "\n",
+ "\n",
+ "X = np.array([ [1.0,-1.0], [1.0,-1.0]])\n",
+ "#X = np.array([[1, 2], [3, 4], [5, 6]])\n",
+ "\n",
+ "print(X)\n",
+ "C = SVD(X)\n",
+ "# Print the difference between the original matrix and the SVD one\n",
+ "print(C-X)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The matrix $\\boldsymbol{X}$ has columns that are linearly dependent. The first\n",
+ "column is the row-wise sum of the other two columns. The rank of a\n",
+ "matrix (the column rank) is the dimension of space spanned by the\n",
+ "column vectors. The rank of the matrix is the number of linearly\n",
+ "independent columns, in this case just $2$. We see this from the\n",
+ "singular values when running the above code. Running the standard\n",
+ "inversion algorithm for matrix inversion with $\\boldsymbol{X}^T\\boldsymbol{X}$ results\n",
+ "in the program terminating due to a singular matrix.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The $U$, $S$, and $V$ matrices returned from the **svd()** function\n",
+ "cannot be multiplied directly.\n",
+ "\n",
+ "As you can see from the code, the $S$ vector must be converted into a\n",
+ "diagonal matrix. This may cause a problem as the size of the matrices\n",
+ "do not fit the rules of matrix multiplication, where the number of\n",
+ "columns in a matrix must match the number of rows in the subsequent\n",
+ "matrix.\n",
+ "\n",
+ "If you wish to include the zero singular values, you will need to\n",
+ "resize the matrices and set up a diagonal matrix as done in the above\n",
+ "example\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Mathematics of the SVD and implications\n",
+ "\n",
+ "Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies.\n",
+ "\n",
+ "Our starting point is our design matrix $\\boldsymbol{X}$ of dimension $n\\times p$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}\n",
+ "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
+ "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
+ "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
+ "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
+ "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
+ "\\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can SVD decompose our matrix as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\boldsymbol{U}$ is an orthogonal matrix of dimension $n\\times n$, meaning that $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{U}^T\\boldsymbol{U}=\\boldsymbol{I}_n$. Here $\\boldsymbol{I}_n$ is the unit matrix of dimension $n \\times n$.\n",
+ "\n",
+ "Similarly, $\\boldsymbol{V}$ is an orthogonal matrix of dimension $p\\times p$, meaning that $\\boldsymbol{V}\\boldsymbol{V}^T=\\boldsymbol{V}^T\\boldsymbol{V}=\\boldsymbol{I}_p$. Here $\\boldsymbol{I}_n$ is the unit matrix of dimension $p \\times p$.\n",
+ "\n",
+ "Finally $\\boldsymbol{\\Sigma}$ contains the singular values $\\sigma_i$. This matrix has dimension $n\\times p$ and the singular values $\\sigma_i$ are all positive. The non-zero values are ordered in descending order, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma_0 > \\sigma_1 > \\sigma_2 > \\dots > \\sigma_{p-1} > 0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "All values beyond $p-1$ are all zero.\n",
+ "\n",
+ "\n",
+ "As an example, consider the following $3\\times 2$ example for the matrix $\\boldsymbol{\\Sigma}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}=\n",
+ "\\begin{bmatrix}\n",
+ "2& 0 \\\\\n",
+ "0 & 1 \\\\\n",
+ "0 & 0 \\\\\n",
+ "\\end{bmatrix}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The singular values are $\\sigma_0=2$ and $\\sigma_1=1$. It is common to rewrite the matrix $\\boldsymbol{\\Sigma}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}=\n",
+ "\\begin{bmatrix}\n",
+ "\\boldsymbol{\\tilde{\\Sigma}}\\\\\n",
+ "\\boldsymbol{0}\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\tilde{\\Sigma}}=\n",
+ "\\begin{bmatrix}\n",
+ "2& 0 \\\\\n",
+ "0 & 1 \\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "contains only the singular values. Note also (and we will use this below) that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}=\n",
+ "\\begin{bmatrix}\n",
+ "4& 0 \\\\\n",
+ "0 & 1 \\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is a $2\\times 2 $ matrix while"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T=\n",
+ "\\begin{bmatrix}\n",
+ "4& 0 & 0\\\\\n",
+ "0 & 1 & 0\\\\\n",
+ "0 & 0 & 0\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "is a $3\\times 3 $ matrix. The last row and column of this last matrix\n",
+ "contain only zeros. This will have important consequences for our SVD\n",
+ "decomposition of the design matrix.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The matrix that may cause problems for us is $\\boldsymbol{X}^T\\boldsymbol{X}$. Using the SVD we can rewrite this matrix as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and using the orthogonality of the matrix $\\boldsymbol{U}$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We define $\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}=\\tilde{\\boldsymbol{\\Sigma}}^2$ which is a diagonal matrix containing only the singular values squared. It has dimensionality $p \\times p$.\n",
+ "\n",
+ "This means, using the orthogonality of $\\boldsymbol{V}$, that we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\tilde{\\boldsymbol{\\Sigma}}^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can now insert the result for the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ into our equation for ordinary least squares where"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and using our SVD decomposition of $\\boldsymbol{X}$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\tilde{\\boldsymbol{\\Sigma}}^{-2}\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which gives us, using the orthogonality of the matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_i\\boldsymbol{u}^T_j\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note here that when we perform the multiplication of the various matrices, the orthogonal vectors of the matrix $\\boldsymbol{U}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{U}=[\\boldsymbol{u}_0,\\boldsymbol{u}_1,\\dots,\\boldsymbol{u}_{n-1}],\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "that belong to $i>p-1$, result in only zeros when we perform the multiplications. This means that the sum above has non-zero elements only up to $i=p-1$. This corresponds also to the number of singular values (these are all non-zero).\n",
+ "\n",
+ "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}$.\n",
+ "\n",
+ "\n",
+ "## Further properties (important for our analyses later)\n",
+ "\n",
+ "Let us study again $\\boldsymbol{X}^T\\boldsymbol{X}$ in terms of our SVD,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we now multiply from the right with $\\boldsymbol{V}$ (using the orthogonality of $\\boldsymbol{V}$) we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{V}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This means the vectors $\\boldsymbol{v}_i$ of the orthogonal matrix $\\boldsymbol{V}$ are the eigenvectors of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$\n",
+ "with eigenvalues given by the singular values squared, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{v}_i=\\boldsymbol{v}_i\\sigma_i^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Similarly, if we use the SVD decomposition for the matrix $\\boldsymbol{X}\\boldsymbol{X}^T$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we now multiply from the right with $\\boldsymbol{U}$ (using the orthogonality of $\\boldsymbol{U}$) we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}\\boldsymbol{X}^T\\right)\\boldsymbol{U}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This means the vectors $\\boldsymbol{u}_i$ of the orthogonal matrix $\\boldsymbol{U}$ are the eigenvectors of the matrix $\\boldsymbol{X}\\boldsymbol{X}^T$\n",
+ "with eigenvalues given by the singular values squared, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}\\boldsymbol{X}^T\\right)\\boldsymbol{u}_i=\\boldsymbol{u}_i\\sigma_i^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Important note**: we have defined our design matrix $\\boldsymbol{X}$ to be an\n",
+ "$n\\times p$ matrix. In most supervised learning cases we have that $n\n",
+ "\\ge p$, and quite often we have $n >> p$. For linear algebra based methods like ordinary least squares or Ridge regression, this leads to a matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ which is small and thereby easier to handle from a computational point of view (in terms of number of floating point operations).\n",
+ "\n",
+ "In our lectures, the number of columns will\n",
+ "always refer to the number of features in our data set, while the\n",
+ "number of rows represents the number of data inputs. Note that in\n",
+ "other texts you may find the opposite notation. This has consequences\n",
+ "for the definition of for example the covariance matrix and its relation to the SVD.\n",
+ "\n",
+ "\n",
+ "## Meet the Covariance Matrix\n",
+ "\n",
+ "\n",
+ "Before we move on to a discussion of Ridge and Lasso regression, we want to show an important example of the above.\n",
+ "\n",
+ "We have already noted that the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ in ordinary\n",
+ "least squares is proportional to the second derivative of the cost\n",
+ "function, that is we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial^2 C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}^T\\partial \\boldsymbol{\\beta}} =\\frac{2}{n}\\boldsymbol{X}^T\\boldsymbol{X}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This quantity defines was what is called the Hessian matrix (the second derivative of a function we want to optimize).\n",
+ "\n",
+ "The Hessian matrix plays an important role and is defined in this course as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{H}=\\boldsymbol{X}^T\\boldsymbol{X}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The Hessian matrix for ordinary least squares is also proportional to\n",
+ "the covariance matrix. This means also that we can use the SVD to find\n",
+ "the eigenvalues of the covariance matrix and the Hessian matrix in\n",
+ "terms of the singular values. Let us develop these arguments, as they will play an important role in our machine learning studies.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about\n",
+ "the definition of the covariance and the correlation function. These are quantities that play a central role in machine learning methods.\n",
+ "\n",
+ "Suppose we have defined two vectors\n",
+ "$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
+ " \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where for example"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With this definition and recalling that the variance is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we can rewrite the covariance matrix as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
+ " \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n",
+ " \\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**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. \n",
+ "What you will find in essentially all statistics texts are equations\n",
+ "with a factor $1/(n-1)$. This is called [Bessel's correction](https://mathworld.wolfram.com/BesselsCorrection.html). This\n",
+ "method corrects the bias in the estimation of the population variance\n",
+ "and covariance. It also partially corrects the bias in the estimation\n",
+ "of the population standard deviation. If you use a library like\n",
+ "**Scikit-Learn** or **nunmpy's** function calculate the covariance, this\n",
+ "quantity will be computed with a factor $1/(n-1)$.\n",
+ "\n",
+ "\n",
+ "The covariance takes values between zero and infinity and may thus\n",
+ "lead to problems with loss of numerical precision for particularly\n",
+ "large values. It is common to scale the covariance matrix by\n",
+ "introducing instead the correlation matrix defined via the so-called\n",
+ "correlation function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]=\\frac{\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}]}{\\sqrt{\\mathrm{var}[\\boldsymbol{x}] \\mathrm{var}[\\boldsymbol{y}]}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The correlation function is then given by values $\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]\n",
+ "\\in [-1,1]$. This avoids eventual problems with too large values. We\n",
+ "can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n",
+ "and $\\boldsymbol{y}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
+ " \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the above example this is the function we constructed using **pandas**.\n",
+ "\n",
+ "\n",
+ "\n",
+ "In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**\n",
+ "we defined the design/feature matrix $\\boldsymbol{X}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}\n",
+ "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
+ "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
+ "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
+ "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
+ "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ refering to the column numbers and the\n",
+ "entries $n$ being the row elements.\n",
+ "We can rewrite the design/feature matrix in terms of its column vectors as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with a given vector"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{x}_i^T = \\begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \\dots & \\dots x_{n-1,i}\\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With these definitions, we can now rewrite our $2\\times 2$\n",
+ "correlation/covariance matrix in terms of a moe general design/feature\n",
+ "matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$\n",
+ "covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i=0,1,\\dots,p-1$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
+ "\\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}]\\\\\n",
+ "\\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}]\\\\\n",
+ "\\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}]\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\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}]\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and the correlation matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
+ "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}]\\\\\n",
+ "\\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}]\\\\\n",
+ "\\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}]\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\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\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The Numpy function **np.cov** calculates the covariance elements using\n",
+ "the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n",
+ "the exact mean values. The following simple function uses the\n",
+ "**np.vstack** function which takes each vector of dimension $1\\times n$\n",
+ "and produces a $2\\times n$ matrix $\\boldsymbol{W}$\n",
+ "\n",
+ "Note that this assumes you have the features as the rows, and the inputs as columns, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{W} = \\begin{bmatrix} x_0 & x_1 & x_2 & \\dots & x_{n-2} & x_{n-1} \\\\\n",
+ " y_0 & y_1 & y_2 & \\dots & y_{n-2} & y_{n-1} \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which in turn is converted into into the $2\\times 2$ covariance matrix\n",
+ "$\\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate\n",
+ "the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n",
+ "function **np.mean(x)**. We can also extract the eigenvalues of the\n",
+ "covariance matrix through the **np.linalg.eig()** function."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "-0.01210814993019007\n",
+ "3.8867467323038865\n",
+ "[[0.91417278 2.88046462]\n",
+ " [2.88046462 9.9860803 ]]\n"
+ ]
+ }
+ ],
+ "source": [
+ "# Importing various packages\n",
+ "import numpy as np\n",
+ "n = 100\n",
+ "x = np.random.normal(size=n)\n",
+ "print(np.mean(x))\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "print(np.mean(y))\n",
+ "W = np.vstack((x, y))\n",
+ "C = np.cov(W)\n",
+ "print(C)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The previous example can be converted into the correlation matrix by\n",
+ "simply scaling the matrix elements with the variances. We should also\n",
+ "subtract the mean values for each column. This leads to the following\n",
+ "code which sets up the correlations matrix for the previous example in\n",
+ "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)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "0.07423848370736122\n",
+ "1.725394195434945\n",
+ "[[1. 0.71606852]\n",
+ " [0.71606852 1. ]]\n"
+ ]
+ }
+ ],
+ "source": [
+ "import numpy as np\n",
+ "n = 100\n",
+ "# define two vectors \n",
+ "x = np.random.random(size=n)\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "#scaling the x and y vectors \n",
+ "x = x - np.mean(x)\n",
+ "y = y - np.mean(y)\n",
+ "variance_x = np.sum(x@x)/n\n",
+ "variance_y = np.sum(y@y)/n\n",
+ "print(variance_x)\n",
+ "print(variance_y)\n",
+ "cov_xy = np.sum(x@y)/n\n",
+ "cov_xx = np.sum(x@x)/n\n",
+ "cov_yy = np.sum(y@y)/n\n",
+ "C = np.zeros((2,2))\n",
+ "C[0,0]= cov_xx/variance_x\n",
+ "C[1,1]= cov_yy/variance_y\n",
+ "C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n",
+ "C[1,0]= C[0,1]\n",
+ "print(C)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see that the matrix elements along the diagonal are one as they\n",
+ "should be and that the matrix is symmetric. Furthermore, diagonalizing\n",
+ "this matrix we easily see that it is a positive definite matrix.\n",
+ "\n",
+ "The above procedure with **numpy** can be made more compact if we use **pandas**.\n",
+ "\n",
+ "\n",
+ "\n",
+ "We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[[ 0.52687171 0.97622676]\n",
+ " [-2.35038714 -6.09976319]\n",
+ " [-0.55707065 -1.51576807]\n",
+ " [-0.98314755 -2.54096582]\n",
+ " [-0.46556436 -0.43549028]\n",
+ " [ 3.28310983 9.01503674]\n",
+ " [ 0.76388013 2.67714918]\n",
+ " [-0.49722108 -2.64669382]\n",
+ " [ 1.20184113 3.80026635]\n",
+ " [-0.92231203 -3.22999784]]\n",
+ " 0 1\n",
+ "0 0.526872 0.976227\n",
+ "1 -2.350387 -6.099763\n",
+ "2 -0.557071 -1.515768\n",
+ "3 -0.983148 -2.540966\n",
+ "4 -0.465564 -0.435490\n",
+ "5 3.283110 9.015037\n",
+ "6 0.763880 2.677149\n",
+ "7 -0.497221 -2.646694\n",
+ "8 1.201841 3.800266\n",
+ "9 -0.922312 -3.229998\n",
+ " 0 1\n",
+ "0 1.000000 0.988663\n",
+ "1 0.988663 1.000000"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "n = 10\n",
+ "x = np.random.normal(size=n)\n",
+ "x = x - np.mean(x)\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "y = y - np.mean(y)\n",
+ "# Note that we transpose the matrix in order to stay with our ordering n x p\n",
+ "X = (np.vstack((x, y))).T\n",
+ "print(X)\n",
+ "Xpd = pd.DataFrame(X)\n",
+ "print(Xpd)\n",
+ "correlation_matrix = Xpd.corr()\n",
+ "print(correlation_matrix)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We expand this model to the Franke function discussed earlier."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ " 0 1 2 3 4 5 6 7 \\\n",
+ "0 0.0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 \n",
+ "1 0.0 0.075212 0.075261 0.077160 0.075772 0.074134 0.069902 0.068276 \n",
+ "2 0.0 0.075261 0.077533 0.076062 0.075562 0.074848 0.067985 0.066788 \n",
+ "3 0.0 0.077160 0.076062 0.084092 0.081886 0.079365 0.078927 0.076730 \n",
+ "4 0.0 0.075772 0.075562 0.081886 0.080115 0.078049 0.076398 0.074453 \n",
+ "5 0.0 0.074134 0.074848 0.079365 0.078049 0.076469 0.073567 0.071887 \n",
+ "6 0.0 0.069902 0.067985 0.078927 0.076398 0.073567 0.075821 0.073483 \n",
+ "7 0.0 0.068276 0.066788 0.076730 0.074453 0.071887 0.073483 0.071313 \n",
+ "8 0.0 0.066629 0.065591 0.074488 0.072471 0.070182 0.071096 0.069098 \n",
+ "9 0.0 0.064964 0.064410 0.072198 0.070456 0.068460 0.068654 0.066835 \n",
+ "10 0.0 0.061842 0.059571 0.071481 0.068920 0.066092 0.069814 0.067531 \n",
+ "11 0.0 0.060308 0.058282 0.069516 0.067123 0.064472 0.067777 0.065618 \n",
+ "12 0.0 0.058805 0.057035 0.067577 0.065355 0.062885 0.065762 0.063727 \n",
+ "13 0.0 0.057332 0.055831 0.065660 0.063615 0.061330 0.063763 0.061855 \n",
+ "14 0.0 0.055887 0.054674 0.063759 0.061896 0.059806 0.061774 0.059994 \n",
+ "\n",
+ " 8 9 10 11 12 13 14 \n",
+ "0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 \n",
+ "1 0.066629 0.064964 0.061842 0.060308 0.058805 0.057332 0.055887 \n",
+ "2 0.065591 0.064410 0.059571 0.058282 0.057035 0.055831 0.054674 \n",
+ "3 0.074488 0.072198 0.071481 0.069516 0.067577 0.065660 0.063759 \n",
+ "4 0.072471 0.070456 0.068920 0.067123 0.065355 0.063615 0.061896 \n",
+ "5 0.070182 0.068460 0.066092 0.064472 0.062885 0.061330 0.059806 \n",
+ "6 0.071096 0.068654 0.069814 0.067777 0.065762 0.063763 0.061774 \n",
+ "7 0.069098 0.066835 0.067531 0.065618 0.063727 0.061855 0.059994 \n",
+ "8 0.067061 0.064982 0.065202 0.063415 0.061652 0.059908 0.058178 \n",
+ "9 0.064982 0.063097 0.062822 0.061164 0.059531 0.057919 0.056326 \n",
+ "10 0.065202 0.062822 0.065086 0.063122 0.061176 0.059245 0.057320 \n",
+ "11 0.063415 0.061164 0.063122 0.061255 0.059406 0.057571 0.055744 \n",
+ "12 0.061652 0.059531 0.061176 0.059406 0.057654 0.055916 0.054187 \n",
+ "13 0.059908 0.057919 0.059245 0.057571 0.055916 0.054276 0.052645 \n",
+ "14 0.058178 0.056326 0.057320 0.055744 0.054187 0.052645 0.051115 \n"
+ ]
+ }
+ ],
+ "source": [
+ "# Common imports\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "\n",
+ "\n",
+ "def FrankeFunction(x,y):\n",
+ "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
+ "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
+ "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
+ "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
+ "\treturn term1 + term2 + term3 + term4\n",
+ "\n",
+ "\n",
+ "def create_X(x, y, n ):\n",
+ "\tif len(x.shape) > 1:\n",
+ "\t\tx = np.ravel(x)\n",
+ "\t\ty = np.ravel(y)\n",
+ "\n",
+ "\tN = len(x)\n",
+ "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n",
+ "\tX = np.ones((N,l))\n",
+ "\n",
+ "\tfor i in range(1,n+1):\n",
+ "\t\tq = int((i)*(i+1)/2)\n",
+ "\t\tfor k in range(i+1):\n",
+ "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n",
+ "\n",
+ "\treturn X\n",
+ "\n",
+ "\n",
+ "# Making meshgrid of datapoints and compute Franke's function\n",
+ "n = 4\n",
+ "N = 100\n",
+ "x = np.sort(np.random.uniform(0, 1, N))\n",
+ "y = np.sort(np.random.uniform(0, 1, N))\n",
+ "z = FrankeFunction(x, y)\n",
+ "X = create_X(x, y, n=n) \n",
+ "\n",
+ "Xpd = pd.DataFrame(X)\n",
+ "# subtract the mean values and set up the covariance matrix\n",
+ "Xpd = Xpd - Xpd.mean()\n",
+ "covariance_matrix = Xpd.cov()\n",
+ "print(covariance_matrix)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We note here that the covariance is zero for the first rows and\n",
+ "columns since all matrix elements in the design matrix were set to one\n",
+ "(we are fitting the function in terms of a polynomial of degree $n$).\n",
+ "\n",
+ "This means that the variance for these elements will be zero and will\n",
+ "cause problems when we set up the correlation matrix. We can simply\n",
+ "drop these elements and construct a correlation\n",
+ "matrix without these elements. \n",
+ "\n",
+ "\n",
+ "\n",
+ "We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\\boldsymbol{X}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}\n",
+ "x_{00} & x_{01}\\\\\n",
+ "x_{10} & x_{11}\\\\\n",
+ "\\end{bmatrix}=\\begin{bmatrix}\n",
+ "\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n",
+ "\\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we then compute the expectation value (note the $1/n$ factor instead of $1/(n-1)$)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}=\\frac{1}{n}\\begin{bmatrix}\n",
+ "x_{00}^2+x_{10}^2 & x_{00}x_{01}+x_{10}x_{11}\\\\\n",
+ "x_{01}x_{00}+x_{11}x_{10} & x_{01}^2+x_{11}^2\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is just"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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] \\\\\n",
+ " \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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}$.\n",
+ "\n",
+ "It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Linking with the SVD\n",
+ "\n",
+ "We saw earlier that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Since the matrices here have dimension $p\\times p$, with $p$ corresponding to the singular values, we defined earlier the matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma} = \\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0}\\\\ \\end{bmatrix}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\\\ \\boldsymbol{0}\\\\ \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where the tilde-matrix $\\tilde{\\boldsymbol{\\Sigma}}$ is a matrix of dimension $p\\times p$ containing only the singular values $\\sigma_i$, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{\\Sigma}}=\\begin{bmatrix} \\sigma_0 & 0 & 0 & \\dots & 0 & 0 \\\\\n",
+ " 0 & \\sigma_1 & 0 & \\dots & 0 & 0 \\\\\n",
+ "\t\t\t\t 0 & 0 & \\sigma_2 & \\dots & 0 & 0 \\\\\n",
+ "\t\t\t\t 0 & 0 & 0 & \\dots & \\sigma_{p-2} & 0 \\\\\n",
+ "\t\t\t\t 0 & 0 & 0 & \\dots & 0 & \\sigma_{p-1} \\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "meaning we can write"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\tilde{\\boldsymbol{\\Sigma}}^2\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Multiplying from the right with $\\boldsymbol{V}$ (using the orthogonality of $\\boldsymbol{V}$) we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{V}=\\boldsymbol{V}\\tilde{\\boldsymbol{\\Sigma}}^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This means the vectors $\\boldsymbol{v}_i$ of the orthogonal matrix $\\boldsymbol{V}$\n",
+ "are the eigenvectors of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ with eigenvalues\n",
+ "given by the singular values squared, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{v}_i=\\boldsymbol{v}_i\\sigma_i^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In other words, each non-zero singular value of $\\boldsymbol{X}$ is a positive\n",
+ "square root of an eigenvalue of $\\boldsymbol{X}^T\\boldsymbol{X}$. It means also that\n",
+ "the columns of $\\boldsymbol{V}$ are the eigenvectors of\n",
+ "$\\boldsymbol{X}^T\\boldsymbol{X}$. Since we have ordered the singular values of\n",
+ "$\\boldsymbol{X}$ in a descending order, it means that the column vectors\n",
+ "$\\boldsymbol{v}_i$ are hierarchically ordered by how much correlation they\n",
+ "encode from the columns of $\\boldsymbol{X}$. \n",
+ "\n",
+ "\n",
+ "Note that these are also the eigenvectors and eigenvalues of the\n",
+ "Hessian matrix.\n",
+ "\n",
+ "If we now recall the definition of the covariance matrix (not using\n",
+ "Bessel's correction) we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{X}]=\\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "meaning that every squared non-singular value of $\\boldsymbol{X}$ divided by $n$ (\n",
+ "the number of samples) are the eigenvalues of the covariance\n",
+ "matrix. Every singular value of $\\boldsymbol{X}$ is thus a positive square\n",
+ "root of an eigenvalue of $\\boldsymbol{X}^T\\boldsymbol{X}$. If the matrix $\\boldsymbol{X}$ is\n",
+ "self-adjoint, the singular values of $\\boldsymbol{X}$ are equal to the\n",
+ "absolute value of the eigenvalues of $\\boldsymbol{X}$.\n",
+ "\n",
+ "\n",
+ "For $\\boldsymbol{X}\\boldsymbol{X}^T$ we found"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{U}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Since the matrices here have dimension $n\\times n$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T = \\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\\\ \\boldsymbol{0}\\\\ \\end{bmatrix}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\boldsymbol{0}\\\\ \\end{bmatrix}=\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "leading to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix}\\boldsymbol{U}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Multiplying with $\\boldsymbol{U}$ from the right gives us the eigenvalue problem"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U}=\\boldsymbol{U}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It means that the eigenvalues of $\\boldsymbol{X}\\boldsymbol{X}^T$ are again given by\n",
+ "the non-zero singular values plus now a series of zeros. The column\n",
+ "vectors of $\\boldsymbol{U}$ are the eigenvectors of $\\boldsymbol{X}\\boldsymbol{X}^T$ and\n",
+ "measure how much correlations are contained in the rows of $\\boldsymbol{X}$.\n",
+ "\n",
+ "Since we will mainly be interested in the correlations among the features\n",
+ "of our data (the columns of $\\boldsymbol{X}$, the quantity of interest for us are the non-zero singular\n",
+ "values and the column vectors of $\\boldsymbol{V}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Ridge and LASSO Regression\n",
+ "\n",
+ "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n",
+ "our optimization problem is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or we can state it as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have used the definition of a norm-2 vector, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "By minimizing the above equation with respect to the parameters\n",
+ "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n",
+ "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n",
+ "defining a new cost function to be optimized, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to the Ridge regression minimization problem where we\n",
+ "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n",
+ "a finite number larger than zero. By defining"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have a new optimization equation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n",
+ "\n",
+ "Here we have defined the norm-1 as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and \n",
+ "taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n",
+ "a slightly modified matrix inversion problem which for finite values\n",
+ "of $\\lambda$ does not suffer from singularity problems. We obtain\n",
+ "the optimal parameters"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $t$ a finite positive number. \n",
+ "\n",
+ "When we compare this with the ordinary least squares result we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$.\n",
+ "\n",
+ "\n",
+ "We see that Ridge regression is nothing but the standard OLS with a\n",
+ "modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The consequences, in\n",
+ "particular for our discussion of the bias-variance tradeoff are rather\n",
+ "interesting. We will see that for specific values of $\\lambda$, we may\n",
+ "even reduce the variance of the optimal parameters $\\boldsymbol{\\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.\n",
+ "\n",
+ "Using our insights about the SVD of the design matrix $\\boldsymbol{X}$ \n",
+ "We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}_{\\mathrm{OLS}}=\\boldsymbol{X}\\boldsymbol{\\beta} =\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For Ridge regression this becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}_{\\mathrm{Ridge}}=\\boldsymbol{X}\\boldsymbol{\\beta}_{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{\\Sigma}^2\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$ from the SVD of the matrix $\\boldsymbol{X}$. \n",
+ "\n",
+ "\n",
+ "Since $\\lambda \\geq 0$, it means that compared to OLS, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n",
+ "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n",
+ "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n",
+ "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n",
+ "\\sigma_{i+1}$.\n",
+ "\n",
+ "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.\n",
+ "\n",
+ "\n",
+ "\n",
+ "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this case the standard OLS results in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n",
+ "the Ridge estimator converges to zero when the hyperparameter goes to\n",
+ "infinity.\n",
+ "\n",
+ "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n",
+ "\n",
+ "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n",
+ "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\n",
+ "\n",
+ "\n",
+ "Using the matrix-vector expression for Lasso regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have the following **cost** function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{d \\vert \\beta\\vert}{d \\boldsymbol{\\beta}}=\\mathrm{sgn}(\\boldsymbol{\\beta})=\\left\\{\\begin{array}{cc} 1 & \\beta > 0 \\\\ 0 & \\beta =0\\\\-1 & \\beta < 0, \\end{array}\\right.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have that the derivative of the cost function is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{X},\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}=-2\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})+\\lambda sgn(\\boldsymbol{\\beta})=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and reordering we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta})+\\lambda sgn(\\boldsymbol{\\beta})=2\\boldsymbol{X}^T(\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This equation does not lead to a nice analytical equation as in either Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms using for example the Python package [CVXOPT](https://cvxopt.org/). We will discuss this later. \n",
+ "\n",
+ "## Code for SVD and Inversion of Matrices\n",
+ "\n",
+ "How do we use the SVD to invert a matrix $\\boldsymbol{X}^\\boldsymbol{X}$ which is singular or near singular?\n",
+ "The simple answer is to use the linear algebra function for pseudoinvers, that is"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [
+ {
+ "ename": "AttributeError",
+ "evalue": "module 'numpy' has no attribute 'linlag'",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
+ "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mAinv\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlinlag\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpinv\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mA\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
+ "\u001b[0;32m~/opt/anaconda3/lib/python3.8/site-packages/numpy/__init__.py\u001b[0m in \u001b[0;36m__getattr__\u001b[0;34m(attr)\u001b[0m\n\u001b[1;32m 212\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mTester\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 213\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 214\u001b[0;31m raise AttributeError(\"module {!r} has no attribute \"\n\u001b[0m\u001b[1;32m 215\u001b[0m \"{!r}\".format(__name__, attr))\n\u001b[1;32m 216\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
+ "\u001b[0;31mAttributeError\u001b[0m: module 'numpy' has no attribute 'linlag'"
+ ]
+ }
+ ],
+ "source": [
+ "Ainv = np.linlag.pinv(A)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let us first look at a matrix which does not causes problems and write our own function where we just use the SVD."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "# SVD inversion\n",
+ "def SVDinv(A):\n",
+ " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n",
+ " SVD is numerically more stable than the inversion algorithms provided by\n",
+ " numpy and scipy.linalg at the cost of being slower.\n",
+ " '''\n",
+ " U, s, VT = np.linalg.svd(A)\n",
+ " print('test U')\n",
+ " print( (np.transpose(U) @ U - U @np.transpose(U)))\n",
+ " print('test VT')\n",
+ " print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n",
+ "\n",
+ "\n",
+ " D = np.zeros((len(U),len(VT)))\n",
+ " D = np.diag(s)\n",
+ " UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)\n",
+ " return np.matmul(V,np.matmul(invD,UT))\n",
+ "\n",
+ "\n",
+ "#X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])\n",
+ "# Non-singular square matrix\n",
+ "X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])\n",
+ "print(X)\n",
+ "A = np.transpose(X) @ X\n",
+ "# Brute force inversion\n",
+ "B = np.linalg.inv(A) # here we could use np.linalg.pinv(A)\n",
+ "C = SVDinv(A)\n",
+ "print(np.abs(B-C))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Although our matrix to invert $\\boldsymbol{X}^T\\boldsymbol{X}$ is a square matrix, our matrix may be singular. \n",
+ "\n",
+ "The pseudoinverse is the generalization of the matrix inverse for square matrices to\n",
+ "rectangular matrices where the number of rows and columns are not equal.\n",
+ "\n",
+ "It is also called the the Moore-Penrose Inverse after two independent discoverers of the method or the Generalized Inverse.\n",
+ "It is used for the calculation of the inverse for singular or near singular matrices and for rectangular matrices.\n",
+ "\n",
+ "Using the SVD we can obtain the pseudoinverse of a matrix $\\boldsymbol{A}$ (labeled here as $\\boldsymbol{A}_{\\mathrm{PI}}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}_{\\mathrm{PI}}= \\boldsymbol{V}\\boldsymbol{D}_{\\mathrm{PI}}\\boldsymbol{U}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\boldsymbol{D}_{\\mathrm{PI}}$ can be calculated by creating a diagonal matrix from $\\boldsymbol{Sigma}$ where we only keep the singular values (the non-zero values). The following code computes the pseudoinvers of the matrix based on the SVD."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "# SVD inversion\n",
+ "def SVDinv(A):\n",
+ " U, s, VT = np.linalg.svd(A)\n",
+ " # reciprocals of singular values of s\n",
+ " d = 1.0 / s\n",
+ " # create m x n D matrix\n",
+ " D = np.zeros(A.shape)\n",
+ " # populate D with n x n diagonal matrix\n",
+ " D[:A.shape[1], :A.shape[1]] = np.diag(d)\n",
+ " UT = np.transpose(U)\n",
+ " V = np.transpose(VT)\n",
+ " return np.matmul(V,np.matmul(D.T,UT))\n",
+ "\n",
+ "\n",
+ "A = np.array([ [0.3, 0.4], [0.5, 0.6], [0.7, 0.8],[0.9, 1.0]])\n",
+ "print(A)\n",
+ "# Brute force inversion of super-collinear matrix\n",
+ "B = np.linalg.pinv(A)\n",
+ "print(B)\n",
+ "# Compare our own algorithm with pinv\n",
+ "C = SVDinv(A)\n",
+ "print(np.abs(C-B))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see from this example, our own decomposition based on the SVD agrees the pseudoinverse algorithm provided by **Numpy**.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Deriving the Ridge Regression Equations\n",
+ "\n",
+ "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n",
+ "our optimization problem is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or we can state it as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have used the definition of a norm-2 vector, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "By minimizing the above equation with respect to the parameters\n",
+ "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n",
+ "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n",
+ "defining a new cost function to be optimized, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to the Ridge regression minimization problem where we\n",
+ "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n",
+ "a finite number larger than zero. By defining"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have a new optimization equation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n",
+ "\n",
+ "Here we have defined the norm-1 as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and \n",
+ "taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n",
+ "a slightly modified matrix inversion problem which for finite values\n",
+ "of $\\lambda$ does not suffer from singularity problems. We obtain\n",
+ "the optimal parameters"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $t$ a finite positive number. \n",
+ "\n",
+ "When we compare this with the ordinary least squares result we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$.\n",
+ "\n",
+ "\n",
+ "We see that Ridge regression is nothing but the standard OLS with a\n",
+ "modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The consequences, in\n",
+ "particular for our discussion of the bias-variance tradeoff are rather\n",
+ "interesting. We will see that for specific values of $\\lambda$, we may\n",
+ "even reduce the variance of the optimal parameters $\\boldsymbol{\\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Using our insights about the SVD of the design matrix $\\boldsymbol{X}$ \n",
+ "We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}_{\\mathrm{OLS}}=\\boldsymbol{X}\\boldsymbol{\\beta} =\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For Ridge regression this becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}_{\\mathrm{Ridge}}=\\boldsymbol{X}\\boldsymbol{\\beta}_{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{\\Sigma}^2\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$ from the SVD of the matrix $\\boldsymbol{X}$. \n",
+ "\n",
+ "\n",
+ "\n",
+ "Since $\\lambda \\geq 0$, it means that compared to OLS, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n",
+ "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n",
+ "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n",
+ "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n",
+ "\\sigma_{i+1}$.\n",
+ "\n",
+ "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.\n",
+ "\n",
+ "\n",
+ "\n",
+ "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this case the standard OLS results in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n",
+ "the Ridge estimator converges to zero when the hyperparameter goes to\n",
+ "infinity.\n",
+ "\n",
+ "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n",
+ "\n",
+ "\n",
+ "\n",
+ "Using the matrix-vector expression for Lasso regression and dropping the parameter $1/n$ in front of the standard mean squared error equation, we have the following **cost** function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{d \\vert \\beta\\vert}{d \\boldsymbol{\\beta}}=\\mathrm{sgn}(\\boldsymbol{\\beta})=\\left\\{\\begin{array}{cc} 1 & \\beta > 0 \\\\ 0 & \\beta =0\\\\-1 & \\beta < 0, \\end{array}\\right.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have that the derivative of the cost function is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{X},\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}=-2\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})+\\lambda sgn(\\boldsymbol{\\beta})=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and reordering we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta}+\\lambda sgn(\\boldsymbol{\\beta})=2\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This equation does not lead to a nice analytical equation as in 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](https://cvxopt.org/). We will discuss this later. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Let us assume that our design matrix is given by unit (identity) matrix, that is a square diagonal matrix with ones only along the\n",
+ "diagonal. In this case we have an equal number of rows and columns $n=p$.\n",
+ "\n",
+ "Our model approximation is just $\\tilde{\\boldsymbol{y}}=\\boldsymbol{\\beta}$ and the mean squared error and thereby the cost function for ordinary least sqquares (OLS) is then (we drop the term $1/n$)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and minimizing we have that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\beta}_i^{\\mathrm{OLS}} = y_i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For Ridge regression our cost function is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\beta_i^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and minimizing we have that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\beta}_i^{\\mathrm{Ridge}} = \\frac{y_i}{1+\\lambda}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For Lasso regression our cost function is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\vert\\beta_i\\vert=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\sqrt{\\beta_i^2},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and minimizing we have that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "-2\\sum_{i=0}^{p-1}(y_i-\\beta_i)+\\lambda \\sum_{i=0}^{p-1}\\frac{(\\beta_i)}{\\vert\\beta_i\\vert}=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_i^{\\mathrm{Lasso}} = \\left\\{\\begin{array}{ccc}y_i-\\frac{\\lambda}{2} &\\mathrm{if} & y_i> \\frac{\\lambda}{2}\\\\\n",
+ " y_i+\\frac{\\lambda}{2} &\\mathrm{if} & y_i< -\\frac{\\lambda}{2}\\\\\n",
+ "\t\t\t\t\t\t\t 0 &\\mathrm{if} & \\vert y_i\\vert\\le \\frac{\\lambda}{2}\\end{array}\\right.\\\\.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Plotting these results ([figure in handwritten notes for week 36](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2021/NotesSeptember9.pdf)) shows clearly that Lasso regression suppresses (sets to zero) values of $\\beta_i$ for specific values of $\\lambda$. Ridge regression reduces on the other hand the values of $\\beta_i$ as function of $\\lambda$.\n",
+ "\n",
+ "\n",
+ "As another examples, \n",
+ "let us assume we have a data set with outputs/targets given by the vector"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{y}=\\begin{bmatrix}4 \\\\ 2 \\\\3\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and our inputs as a $3\\times 2$ design matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}2 & 0\\\\ 0 & 1 \\\\ 0 & 0\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "meaning that we have two features and two unknown parameters $\\beta_0$ and $\\beta_1$ to be determined either by ordinary least squares, Ridge or Lasso regression.\n",
+ "\n",
+ "\n",
+ "For ordinary least squares (OLS) we know that the optimal solution is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\left( \\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Inserting the above values we obtain that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\begin{bmatrix}2 \\\\ 2\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The code which implements this simpler case is presented after the discussion of Ridge and Lasso.\n",
+ "\n",
+ "\n",
+ "For Ridge regression we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}}=\\left( \\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Inserting the above values we obtain that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}}=\\begin{bmatrix}\\frac{8}{4+\\lambda} \\\\ \\frac{2}{1+\\lambda}\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "There is normally a constraint on the value of $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2$ via the parameter $\\lambda$.\n",
+ "Let us for simplicity assume that $\\beta_0^2+\\beta_1^2=1$ as constraint. This will allow us to find an expression for the optimal values of $\\beta$ and $\\lambda$.\n",
+ "\n",
+ "To see this, let us write the cost function for Ridge regression. \n",
+ "\n",
+ "\n",
+ "\n",
+ "We define the MSE without the $1/n$ factor and have then, using that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}\\boldsymbol{\\beta}=\\begin{bmatrix} 2\\beta_0 \\\\ \\beta_1 \\\\0 \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=(4-2\\beta_0)^2+(2-\\beta_1)^2+\\lambda(\\beta_0^2+\\beta_1^2),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and taking the derivative with respect to $\\beta_0$ we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_0=\\frac{8}{4+\\lambda},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and for $\\beta_1$ we obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_1=\\frac{2}{1+\\lambda},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using the constraint for $\\beta_0^2+\\beta_1^2=1$ we can constrain $\\lambda$ by solving"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\frac{8}{4+\\lambda}\\right)^2+\\left(\\frac{2}{1+\\lambda}\\right)^2=1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which gives $\\lambda=4.571$ and $\\beta_0=0.933$ and $\\beta_1=0.359$.\n",
+ "\n",
+ "\n",
+ "For Lasso we need now, keeping a constraint on $\\vert\\beta_0\\vert+\\vert\\beta_1\\vert=1$, to take the derivative of the absolute values of $\\beta_0$\n",
+ "and $\\beta_1$. This gives us the following derivatives of the cost function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=(4-2\\beta_0)^2+(2-\\beta_1)^2+\\lambda(\\vert\\beta_0\\vert+\\vert\\beta_1\\vert),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_0}=-4(4-2\\beta_0)+\\lambda\\mathrm{sgn}(\\beta_0)=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_1}=-2(2-\\beta_1)+\\lambda\\mathrm{sgn}(\\beta_1)=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We have now four cases to solve besides the trivial cases $\\beta_0$ and/or $\\beta_1$ are zero, namely\n",
+ "1. $\\beta_0 > 0$ and $\\beta_1 > 0$,\n",
+ "\n",
+ "2. $\\beta_0 > 0$ and $\\beta_1 < 0$,\n",
+ "\n",
+ "3. $\\beta_0 < 0$ and $\\beta_1 > 0$,\n",
+ "\n",
+ "4. $\\beta_0 < 0$ and $\\beta_1 < 0$.\n",
+ "\n",
+ "If we consider the first case, we have then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "-4(4-2\\beta_0)+\\lambda=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "-2(2-\\beta_1)+\\lambda=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which yields"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_0=\\frac{16+\\lambda}{8},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_1=\\frac{4+\\lambda}{2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using the constraint on $\\beta_0$ and $\\beta_1$ we can then find the optimal value of $\\lambda$ for the different cases. We leave this as an exercise to you.\n",
+ "\n",
+ "\n",
+ "Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of $\\lambda$, meaning that we need to perform a search in order to find the optimal values.\n",
+ "\n",
+ "First we study and compare the OLS and Ridge results. The next code compares all three methods."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "def R2(y_data, y_model):\n",
+ " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
+ "\n",
+ "\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "\n",
+ "X = np.array( [ [ 2, 0], [0, 1], [0,0]])\n",
+ "y = np.array( [4, 2, 3])\n",
+ "\n",
+ "\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y\n",
+ "print(OLSbeta)\n",
+ "# and then make the prediction\n",
+ "ytildeOLS = X @ OLSbeta\n",
+ "print(\"Training MSE for OLS\")\n",
+ "print(MSE(y,ytildeOLS))\n",
+ "ypredictOLS = X @ OLSbeta\n",
+ "\n",
+ "# Repeat now for Ridge regression and various values of the regularization parameter\n",
+ "I = np.eye(2,2)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 100\n",
+ "MSEPredict = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 4, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y\n",
+ "# print(Ridgebeta)\n",
+ " # and then make the prediction\n",
+ " ypredictRidge = X @ Ridgebeta\n",
+ " MSEPredict[i] = MSE(y,ypredictRidge)\n",
+ "# print(MSEPredict[i])\n",
+ " # Now plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Train')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see here that we reach a plateau. What is actually happening?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn import linear_model\n",
+ "\n",
+ "def R2(y_data, y_model):\n",
+ " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
+ "\n",
+ "\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "\n",
+ "X = np.array( [ [ 2, 0], [0, 1], [0,0]])\n",
+ "y = np.array( [4, 2, 3])\n",
+ "\n",
+ "\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y\n",
+ "print(OLSbeta)\n",
+ "# and then make the prediction\n",
+ "ytildeOLS = X @ OLSbeta\n",
+ "print(\"Training MSE for OLS\")\n",
+ "print(MSE(y,ytildeOLS))\n",
+ "ypredictOLS = X @ OLSbeta\n",
+ "\n",
+ "# Repeat now for Ridge regression and various values of the regularization parameter\n",
+ "I = np.eye(2,2)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 100\n",
+ "MSERidgePredict = np.zeros(nlambdas)\n",
+ "MSELassoPredict = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 4, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y\n",
+ " print(Ridgebeta)\n",
+ " # and then make the prediction\n",
+ " ypredictRidge = X @ Ridgebeta\n",
+ " MSERidgePredict[i] = MSE(y,ypredictRidge)\n",
+ " RegLasso = linear_model.Lasso(lmb)\n",
+ " RegLasso.fit(X,y)\n",
+ " ypredictLasso = RegLasso.predict(X)\n",
+ " print(RegLasso.coef_)\n",
+ " MSELassoPredict[i] = MSE(y,ypredictLasso)\n",
+ "# Now plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSERidgePredict, 'r--', label = 'MSE Ridge Train')\n",
+ "plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Train')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Another Example, now with a polynomial fit."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn import linear_model\n",
+ "\n",
+ "def R2(y_data, y_model):\n",
+ " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
+ "\n",
+ "\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "np.random.seed(3155)\n",
+ "\n",
+ "x = np.random.rand(100)\n",
+ "y = 2.0+5*x*x+0.1*np.random.randn(100)\n",
+ "\n",
+ "# number of features p (here degree of polynomial\n",
+ "p = 3\n",
+ "# The design matrix now as function of a given polynomial\n",
+ "X = np.zeros((len(x),p))\n",
+ "X[:,0] = 1.0\n",
+ "X[:,1] = x\n",
+ "X[:,2] = x*x\n",
+ "# We split the data in test and training data\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
+ "\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n",
+ "print(OLSbeta)\n",
+ "# and then make the prediction\n",
+ "ytildeOLS = X_train @ OLSbeta\n",
+ "print(\"Training MSE for OLS\")\n",
+ "print(MSE(y_train,ytildeOLS))\n",
+ "ypredictOLS = X_test @ OLSbeta\n",
+ "print(\"Test MSE OLS\")\n",
+ "print(MSE(y_test,ypredictOLS))\n",
+ "\n",
+ "# Repeat now for Lasso and Ridge regression and various values of the regularization parameter\n",
+ "I = np.eye(p,p)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 100\n",
+ "MSEPredict = np.zeros(nlambdas)\n",
+ "MSETrain = np.zeros(nlambdas)\n",
+ "MSELassoPredict = np.zeros(nlambdas)\n",
+ "MSELassoTrain = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 4, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n",
+ " # include lasso using Scikit-Learn\n",
+ " RegLasso = linear_model.Lasso(lmb)\n",
+ " RegLasso.fit(X_train,y_train)\n",
+ " # and then make the prediction\n",
+ " ytildeRidge = X_train @ Ridgebeta\n",
+ " ypredictRidge = X_test @ Ridgebeta\n",
+ " ytildeLasso = RegLasso.predict(X_train)\n",
+ " ypredictLasso = RegLasso.predict(X_test)\n",
+ " MSEPredict[i] = MSE(y_test,ypredictRidge)\n",
+ " MSETrain[i] = MSE(y_train,ytildeRidge)\n",
+ " MSELassoPredict[i] = MSE(y_test,ypredictLasso)\n",
+ " MSELassoTrain[i] = MSE(y_train,ytildeLasso)\n",
+ "\n",
+ "# Now plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSETrain, label = 'MSE Ridge train')\n",
+ "plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Test')\n",
+ "plt.plot(np.log10(lambdas), MSELassoTrain, label = 'MSE Lasso train')\n",
+ "plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Test')\n",
+ "\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Linking the regression analysis with a statistical interpretation\n",
+ "\n",
+ "We will now couple the discussions of ordinary least squares, Ridge\n",
+ "and Lasso regression with a statistical interpretation, that is we\n",
+ "move from a linear algebra analysis to a statistical analysis. In\n",
+ "particular, we will focus on what the regularization terms can result\n",
+ "in. We will amongst other things show that the regularization\n",
+ "parameter can reduce considerably the variance of the parameters\n",
+ "$\\beta$.\n",
"\n",
- "* Systematical errors are method specific and must be treated differently from case to case. \n",
"\n",
"The\n",
"advantage of doing linear regression is that we actually end up with\n",
@@ -107,6 +3516,7 @@
"row number $i$ and perform a sum over all values $p$.\n",
"\n",
"\n",
+ "\n",
"The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off)\n",
"that there exists a function $f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim \\mathcal{N}(0, \\sigma^2)$\n",
"which describe our data"
@@ -254,8 +3664,7 @@
"\\sigma^2 \\, \\mathbf{I}_{nn}$. From $\\mbox{Var}(\\boldsymbol{\\beta}) = \\sigma^2\n",
"\\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}$, one obtains an estimate of the\n",
"variance of the estimate of the $j$-th regression coefficient:\n",
- "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 \\sqrt{\n",
- "[(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} }$. This may be used to\n",
+ "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 [(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} $. This may be used to\n",
"construct a confidence interval for the estimates.\n",
"\n",
"\n",
@@ -322,48 +3731,20 @@
"\n",
"\n",
"\n",
- "## Resampling methods\n",
+ "## Deriving OLS from a probability distribution\n",
"\n",
- "With all these analytical equations for both the OLS and Ridge\n",
- "regression, we will now outline how to assess a given model. This will\n",
- "lead us to a discussion of the so-called bias-variance tradeoff (see\n",
- "below) and so-called resampling methods.\n",
+ "Our basic assumption when we derived the OLS equations was to assume\n",
+ "that our output is determined by a given continuous function\n",
+ "$f(\\boldsymbol{x})$ and a random noise $\\boldsymbol{\\epsilon}$ given by the normal\n",
+ "distribution with zero mean value and an undetermined variance\n",
+ "$\\sigma^2$.\n",
"\n",
- "One of the quantities we have discussed as a way to measure errors is\n",
- "the mean-squared error (MSE), mainly used for fitting of continuous\n",
- "functions. Another choice is the absolute error.\n",
- "\n",
- "In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,\n",
- "we discuss the\n",
- "1. prediction error or simply the **test error** $\\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the \n",
- "\n",
- "2. training error $\\mathrm{Err_{Train}}$, which is the average loss over the training data.\n",
- "\n",
- "As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.\n",
- "For a certain level of complexity the test error will reach minimum, before starting to increase again. The\n",
- "training error reaches a saturation.\n",
- "\n",
- "\n",
- "\n",
- "Two famous\n",
- "resampling methods are the **independent bootstrap** and **the jackknife**. \n",
- "\n",
- "The jackknife is a special case of the independent bootstrap. Still, the jackknife was made\n",
- "popular prior to the independent bootstrap. And as the popularity of\n",
- "the independent bootstrap soared, new variants, such as **the dependent bootstrap**.\n",
- "\n",
- "The Jackknife and independent bootstrap work for\n",
- "independent, identically distributed random variables.\n",
- "If these conditions are not\n",
- "satisfied, the methods will fail. Yet, it should be said that if the data are\n",
- "independent, identically distributed, and we only want to estimate the\n",
- "variance of $\\overline{X}$ (which often is the case), then there is no\n",
- "need for bootstrapping. \n",
- "\n",
- "\n",
- "The Jackknife works by making many replicas of the estimator $\\widehat{\\theta}$. \n",
- "The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\\boldsymbol{x} = (x_1,x_2,\\cdots,X_n)$. \n",
- "Let $\\boldsymbol{x}_i$ denote the vector"
+ "We found above that the outputs $\\boldsymbol{y}$ have a mean value given by\n",
+ "$\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$ and variance $\\sigma^2$. Since the entries to\n",
+ "the design matrix are not stochastic variables, we can assume that the\n",
+ "probability distribution of our targets is also a normal distribution\n",
+ "but now with mean value $\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$. This means that a\n",
+ "single output $y_i$ is given by the Gaussian distribution"
]
},
{
@@ -371,7 +3752,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{x}_i = (x_1,x_2,\\cdots,x_{i-1},x_{i+1},\\cdots,x_n),\n",
+ "y_i\\sim \\mathcal{N}(\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta}, \\sigma^2)=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
"$$"
]
},
@@ -379,281 +3760,8 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "which equals the vector $\\boldsymbol{x}$ with the exception that observation\n",
- "number $i$ is left out. Using this notation, define\n",
- "$\\widehat{\\theta}_i$ to be the estimator\n",
- "$\\widehat{\\theta}$ computed using $\\vec{X}_i$."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Runtime: 0.139475 sec\n",
- "Jackknife Statistics :\n",
- "original bias std. error\n",
- " 99.6714 99.6614 0.149667\n"
- ]
- }
- ],
- "source": [
- "from numpy import *\n",
- "from numpy.random import randint, randn\n",
- "from time import time\n",
- "\n",
- "def jackknife(data, stat):\n",
- " n = len(data);t = zeros(n); inds = arange(n); t0 = time()\n",
- " ## 'jackknifing' by leaving out an observation for each i \n",
- " for i in range(n):\n",
- " t[i] = stat(delete(data,i) )\n",
- "\n",
- " # analysis \n",
- " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Jackknife Statistics :\")\n",
- " print(\"original bias std. error\")\n",
- " print(\"%8g %14g %15g\" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))\n",
- "\n",
- " return t\n",
- "\n",
- "\n",
- "# Returns mean of data samples \n",
- "def stat(data):\n",
- " return mean(data)\n",
- "\n",
- "\n",
- "mu, sigma = 100, 15\n",
- "datapoints = 10000\n",
- "x = mu + sigma*random.randn(datapoints)\n",
- "# jackknife returns the data sample \n",
- "t = jackknife(x, stat)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Bootstrap\n",
- "\n",
- "Bootstrapping is a nonparametric approach to statistical inference\n",
- "that substitutes computation for more traditional distributional\n",
- "assumptions and asymptotic results. Bootstrapping offers a number of\n",
- "advantages: \n",
- "1. The bootstrap is quite general, although there are some cases in which it fails. \n",
- "\n",
- "2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. \n",
- "\n",
- "3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. \n",
- "\n",
- "4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).\n",
- "\n",
- "Since $\\widehat{\\theta} = \\widehat{\\theta}(\\boldsymbol{X})$ is a function of random variables,\n",
- "$\\widehat{\\theta}$ itself must be a random variable. Thus it has\n",
- "a pdf, call this function $p(\\boldsymbol{t})$. The aim of the bootstrap is to\n",
- "estimate $p(\\boldsymbol{t})$ by the relative frequency of\n",
- "$\\widehat{\\theta}$. You can think of this as using a histogram\n",
- "in the place of $p(\\boldsymbol{t})$. If the relative frequency closely\n",
- "resembles $p(\\vec{t})$, then using numerics, it is straight forward to\n",
- "estimate all the interesting parameters of $p(\\boldsymbol{t})$ using point\n",
- "estimators. \n",
- "\n",
- "\n",
- "\n",
- "In the case that $\\widehat{\\theta}$ has\n",
- "more than one component, and the components are independent, we use the\n",
- "same estimator on each component separately. If the probability\n",
- "density function of $X_i$, $p(x)$, had been known, then it would have\n",
- "been straight forward to do this by: \n",
- "1. Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \\cdots, X_n^*)$. \n",
- "\n",
- "2. Then using these numbers, we could compute a replica of $\\widehat{\\theta}$ called $\\widehat{\\theta}^*$. \n",
- "\n",
- "By repeated use of (1) and (2), many\n",
- "estimates of $\\widehat{\\theta}$ could have been obtained. The\n",
- "idea is to use the relative frequency of $\\widehat{\\theta}^*$\n",
- "(think of a histogram) as an estimate of $p(\\boldsymbol{t})$.\n",
- "\n",
- "\n",
- "But\n",
- "unless there is enough information available about the process that\n",
- "generated $X_1,X_2,\\cdots,X_n$, $p(x)$ is in general\n",
- "unknown. Therefore, [Efron in 1979](https://projecteuclid.org/euclid.aos/1176344552) asked the\n",
- "question: What if we replace $p(x)$ by the relative frequency\n",
- "of the observation $X_i$; if we draw observations in accordance with\n",
- "the relative frequency of the observations, will we obtain the same\n",
- "result in some asymptotic sense? The answer is yes.\n",
- "\n",
- "\n",
- "Instead of generating the histogram for the relative\n",
- "frequency of the observation $X_i$, just draw the values\n",
- "$(X_1^*,X_2^*,\\cdots,X_n^*)$ with replacement from the vector\n",
- "$\\boldsymbol{X}$. \n",
- "\n",
- "\n",
- "The independent bootstrap works like this: \n",
- "\n",
- "1. Draw with replacement $n$ numbers for the observed variables $\\boldsymbol{x} = (x_1,x_2,\\cdots,x_n)$. \n",
- "\n",
- "2. Define a vector $\\boldsymbol{x}^*$ containing the values which were drawn from $\\boldsymbol{x}$. \n",
- "\n",
- "3. Using the vector $\\boldsymbol{x}^*$ compute $\\widehat{\\theta}^*$ by evaluating $\\widehat \\theta$ under the observations $\\boldsymbol{x}^*$. \n",
- "\n",
- "4. Repeat this process $k$ times. \n",
- "\n",
- "When you are done, you can draw a histogram of the relative frequency\n",
- "of $\\widehat \\theta^*$. This is your estimate of the probability\n",
- "distribution $p(t)$. Using this probability distribution you can\n",
- "estimate any statistics thereof. In principle you never draw the\n",
- "histogram of the relative frequency of $\\widehat{\\theta}^*$. Instead\n",
- "you use the estimators corresponding to the statistic of interest. For\n",
- "example, if you are interested in estimating the variance of $\\widehat\n",
- "\\theta$, apply the etsimator $\\widehat \\sigma^2$ to the values\n",
- "$\\widehat \\theta ^*$.\n",
- "\n",
- "\n",
- "\n",
- "The following code starts with a Gaussian distribution with mean value\n",
- "$\\mu =100$ and variance $\\sigma=15$. We use this to generate the data\n",
- "used in the bootstrap analysis. The bootstrap analysis returns a data\n",
- "set after a given number of bootstrap operations (as many as we have\n",
- "data points). This data set consists of estimated mean values for each\n",
- "bootstrap operation. The histogram generated by the bootstrap method\n",
- "shows that the distribution for these mean values is also a Gaussian,\n",
- "centered around the mean value $\\mu=100$ but with standard deviation\n",
- "$\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in\n",
- "this case the same as the number of original data points). The value\n",
- "of the standard deviation is what we expect from the central limit\n",
- "theorem."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Runtime: 1.78195 sec\n",
- "Bootstrap Statistics :\n",
- "original bias std. error\n",
- " 100.073 14.9354 100.074 0.149903\n"
- ]
- },
- {
- "ename": "AttributeError",
- "evalue": "'Rectangle' object has no property 'normed'",
- "output_type": "error",
- "traceback": [
- "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
- "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
- "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 31\u001b[0m \u001b[0mt\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mbootstrap\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstat\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdatapoints\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 32\u001b[0m \u001b[0;31m# the histogram of the bootstrapped data\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 33\u001b[0;31m \u001b[0mn\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbinsboot\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpatches\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mplt\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mhist\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mt\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m50\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnormed\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfacecolor\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'red'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0malpha\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m0.75\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 34\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 35\u001b[0m \u001b[0;31m# add a 'best fit' line\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
- "\u001b[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/pyplot.py\u001b[0m in \u001b[0;36mhist\u001b[0;34m(x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, data, **kwargs)\u001b[0m\n\u001b[1;32m 2683\u001b[0m \u001b[0morientation\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'vertical'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mrwidth\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mlog\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcolor\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2684\u001b[0m label=None, stacked=False, *, data=None, **kwargs):\n\u001b[0;32m-> 2685\u001b[0;31m return gca().hist(\n\u001b[0m\u001b[1;32m 2686\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbins\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mbins\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mrange\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdensity\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mdensity\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mweights\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mweights\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2687\u001b[0m \u001b[0mcumulative\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mcumulative\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbottom\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mbottom\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mhisttype\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mhisttype\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
- "\u001b[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/__init__.py\u001b[0m in \u001b[0;36minner\u001b[0;34m(ax, data, *args, **kwargs)\u001b[0m\n\u001b[1;32m 1445\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0minner\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0max\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdata\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1446\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mdata\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1447\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mfunc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0max\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0mmap\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msanitize_sequence\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0margs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1448\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1449\u001b[0m \u001b[0mbound\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mnew_sig\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mbind\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0max\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
- "\u001b[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/axes/_axes.py\u001b[0m in \u001b[0;36mhist\u001b[0;34m(self, x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs)\u001b[0m\n\u001b[1;32m 6813\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mpatch\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6814\u001b[0m \u001b[0mp\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mpatch\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 6815\u001b[0;31m \u001b[0mp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mupdate\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 6816\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mlbl\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6817\u001b[0m \u001b[0mp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mset_label\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlbl\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
- "\u001b[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/artist.py\u001b[0m in \u001b[0;36mupdate\u001b[0;34m(self, props)\u001b[0m\n\u001b[1;32m 994\u001b[0m \u001b[0mfunc\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mgetattr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34mf\"set_{k}\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 995\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mcallable\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfunc\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 996\u001b[0;31m raise AttributeError(f\"{type(self).__name__!r} object \"\n\u001b[0m\u001b[1;32m 997\u001b[0m f\"has no property {k!r}\")\n\u001b[1;32m 998\u001b[0m \u001b[0mret\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfunc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mv\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
- "\u001b[0;31mAttributeError\u001b[0m: 'Rectangle' object has no property 'normed'"
- ]
- },
- {
- "data": {
- "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXcAAAD4CAYAAAAXUaZHAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/Il7ecAAAACXBIWXMAAAsTAAALEwEAmpwYAAAR1ElEQVR4nO3df5CdV13H8feH1oJUJbSNmZCkbkcqDuMMpezQ4g8Eogxt1XQUKow/Ckbzh60D6oxERsdR+CN1VCijU8lQMHWUUirYABWpAQYdpZJCLaUtNNTUJJM2K5aqdBTRr3/cE72E3ezd3Xvvbk7er5k793nOc557z+lNP3v2POc+m6pCktSXJ612AyRJ42e4S1KHDHdJ6pDhLkkdMtwlqUNnrnYDAM4777yamZlZ7WZI0inlrrvu+ueqWj/fsTUR7jMzM+zfv3+1myFJp5QkDy90zGkZSeqQ4S5JHTLcJalDhrskdchwl6QOGe6S1CHDXZI6ZLhLUocMd0nq0Jr4hqo0LTM7Pzhv+cFdV0y5JdJkOXKXpA45cpeWyd8CtJY5cpekDo0U7knWJbk1yQNJ7k/ygiTnJLkjyYPt+emtbpK8NcmBJPckuXiyXZAknWjUaZnrgQ9V1cuTnAU8FXgDsK+qdiXZCewEXg9cBlzYHpcAN7Rn6ZSz0NSLtNYtOnJP8jTghcCNAFX1lar6ErAN2NOq7QGubNvbgJtq4BPAuiQbx9xuSdJJjDItcwEwB7wzyaeTvD3J2cCGqjra6jwCbGjbm4BDQ+cfbmVfI8mOJPuT7J+bm1t+DyRJX2eUcD8TuBi4oaqeC3yZwRTM/6mqAmopb1xVu6tqtqpm16+f969ESZKWaZRwPwwcrqo72/6tDML+0ePTLe35WDt+BNgydP7mViZJmpJFL6hW1SNJDiV5VlV9DtgK3NceVwO72vNt7ZS9wLVJbmZwIfXxoekbaU3ywql6M+pqmV8A/qStlHkIeA2DUf8tSbYDDwNXtbq3A5cDB4AnWl1J0hSNFO5VdTcwO8+hrfPULeCalTVLkrQSfkNVkjpkuEtShwx3SeqQ4S5JHTLcJalDhrskdchwl6QOGe6S1CH/zJ665O0EdLpz5C5JHTLcJalDhrskdchwl6QOGe6S1CHDXZI6ZLhLUocMd0nqkOEuSR0y3CWpQ95+QJqShW6JcHDXFVNuiU4HjtwlqUOO3KUx86ZlWgscuUtShwx3SerQSOGe5GCSzyS5O8n+VnZOkjuSPNien97Kk+StSQ4kuSfJxZPsgCTp6y1l5P7iqrqoqmbb/k5gX1VdCOxr+wCXARe2xw7ghnE1VpI0mpVMy2wD9rTtPcCVQ+U31cAngHVJNq7gfSRJSzTqapkCPpykgLdV1W5gQ1UdbccfATa07U3AoaFzD7eyo0hj5soUaX6jhvv3VtWRJN8K3JHkgeGDVVUt+EeWZAeDaRvOP//8pZwqSVrESNMyVXWkPR8D3gc8H3j0+HRLez7Wqh8BtgydvrmVnfiau6tqtqpm169fv/weSJK+zqIj9yRnA0+qqn9r2y8FfgvYC1wN7GrPt7VT9gLXJrkZuAR4fGj6RloWp1+kpRllWmYD8L4kx+v/aVV9KMkngVuSbAceBq5q9W8HLgcOAE8Arxl7qyVJJ7VouFfVQ8Bz5in/IrB1nvICrhlL6yRJy+I3VCWpQ4a7JHXIcJekDhnuktQhw12SOuQf69Ca4np2aTwcuUtShxy5S6vMP5ytSXDkLkkdMtwlqUOGuyR1yHCXpA4Z7pLUIcNdkjpkuEtShwx3SeqQ4S5JHTLcJalDhrskdchwl6QOeeMwaY3yhmJaCUfuktQhw12SOmS4S1KHDHdJ6tDI4Z7kjCSfTvKBtn9BkjuTHEjy7iRntfInt/0D7fjMhNouSVrAUkburwXuH9q/DnhzVT0TeAzY3sq3A4+18je3epKkKRop3JNsBq4A3t72A7wEuLVV2QNc2ba3tX3a8a2tviRpSkYdub8F+BXgf9r+ucCXquqrbf8wsKltbwIOAbTjj7f6XyPJjiT7k+yfm5tbXuslSfNaNNyT/BBwrKruGucbV9Xuqpqtqtn169eP86Ul6bQ3yjdUvwf4kSSXA08BvgW4HliX5Mw2Ot8MHGn1jwBbgMNJzgSeBnxx7C2XJC1o0ZF7Vf1qVW2uqhnglcBHquongI8CL2/VrgZua9t72z7t+EeqqsbaaknSSa1knfvrgV9KcoDBnPqNrfxG4NxW/kvAzpU1UZK0VEu6cVhVfQz4WNt+CHj+PHX+A3jFGNomSVomv6EqSR3ylr/SKcZbAWsUjtwlqUOGuyR1yHCXpA4Z7pLUIcNdkjpkuEtShwx3SeqQ4S5JHTLcJalDhrskdchwl6QOeW8ZrYqF7o8iaTwcuUtShwx3SeqQ4S5JHTLcJalDhrskdchwl6QOGe6S1CHDXZI6ZLhLUocMd0nq0KK3H0jyFODjwJNb/Vur6jeSXADcDJwL3AX8VFV9JcmTgZuA5wFfBH68qg5OqP1a47zNgLQ6Rhm5/yfwkqp6DnAR8LIklwLXAW+uqmcCjwHbW/3twGOt/M2tniRpihYN9xr497b7De1RwEuAW1v5HuDKtr2t7dOOb02ScTVYkrS4kebck5yR5G7gGHAH8AXgS1X11VblMLCpbW8CDgG0448zmLo58TV3JNmfZP/c3NyKOiFJ+loj3fK3qv4buCjJOuB9wHeu9I2rajewG2B2drZW+nrS6W6h6xsHd10x5ZZoLVjSapmq+hLwUeAFwLokx384bAaOtO0jwBaAdvxpDC6sSpKmZNFwT7K+jdhJ8o3ADwL3Mwj5l7dqVwO3te29bZ92/CNV5chckqZolGmZjcCeJGcw+GFwS1V9IMl9wM1J3gR8Grix1b8R+OMkB4B/AV45gXZLkk5i0XCvqnuA585T/hDw/HnK/wN4xVhaJ0laFv+GqsbCLytJa4vhLnXOVTSnJ+8tI0kdMtwlqUOGuyR1yHCXpA4Z7pLUIcNdkjpkuEtShwx3SeqQ4S5JHTLcJalDhrskdchwl6QOGe6S1CHDXZI6ZLhLUocMd0nqkOEuSR0y3CWpQ4a7JHXIcJekDhnuktQhw12SOnTmYhWSbAFuAjYABeyuquuTnAO8G5gBDgJXVdVjSQJcD1wOPAG8uqo+NZnma9pmdn5wtZsgaQSjjNy/CvxyVT0buBS4JsmzgZ3Avqq6ENjX9gEuAy5sjx3ADWNvtSTppBYN96o6enzkXVX/BtwPbAK2AXtatT3AlW17G3BTDXwCWJdk47gbLkla2JLm3JPMAM8F7gQ2VNXRdugRBtM2MAj+Q0OnHW5lJ77WjiT7k+yfm5tbarslSScxcrgn+Sbgz4DXVdW/Dh+rqmIwHz+yqtpdVbNVNbt+/fqlnCpJWsRI4Z7kGxgE+59U1Xtb8aPHp1va87FWfgTYMnT65lYmSZqSUVbLBLgRuL+qfm/o0F7gamBXe75tqPzaJDcDlwCPD03fSFojFlr5dHDXFVNuiSZh0XAHvgf4KeAzSe5uZW9gEOq3JNkOPAxc1Y7dzmAZ5AEGSyFfM84GS5IWt2i4V9XfAFng8NZ56hdwzQrbJUlaAb+hKkkdMtwlqUOjzLnrNORtBqRTmyN3SeqQ4S5JHTLcJalDhrskdchwl6QOGe6S1CHDXZI6ZLhLUof8EtNpzC8qaT7eLbIPjtwlqUOGuyR1yHCXpA4Z7pLUIcNdkjpkuEtSh1wKKWkkJ1s66zLJtceRuyR1yHCXpA4Z7pLUIcNdkjpkuEtShxZdLZPkHcAPAceq6rta2TnAu4EZ4CBwVVU9liTA9cDlwBPAq6vqU5NpukblDcKk088oI/c/Al52QtlOYF9VXQjsa/sAlwEXtscO4IbxNFOStBSLjtyr6uNJZk4o3ga8qG3vAT4GvL6V31RVBXwiybokG6vq6NhaLGnN8TbBa89y59w3DAX2I8CGtr0JODRU73ArkyRN0YovqLZRei31vCQ7kuxPsn9ubm6lzZAkDVluuD+aZCNAez7Wyo8AW4bqbW5lX6eqdlfVbFXNrl+/fpnNkCTNZ7n3ltkLXA3sas+3DZVfm+Rm4BLgcefbp8dVMZKOG2Up5LsYXDw9L8lh4DcYhPotSbYDDwNXteq3M1gGeYDBUsjXTKDNkqRFjLJa5lULHNo6T90CrllpoyRJK+M3VCWpQ4a7JHXIP9YhaWL8ctPqceQuSR0y3CWpQ4a7JHXIcJekDhnuktQhw12SOmS4S1KHDHdJ6pBfYjoFefdHner8ctPkOXKXpA4Z7pLUIadl1jCnXyQtl+Euac1wLn58DPc1wBG6pHFzzl2SOmS4S1KHDHdJ6pDhLkkd8oKqpDXPVTRL58hdkjrkyF3SKcsR/cIM9xVwfbqktWoi4Z7kZcD1wBnA26tq1yTeR5Lms9SBV48j/bGHe5IzgD8AfhA4DHwyyd6qum/c7zUtjtClvvU4vTOJkfvzgQNV9RBAkpuBbcBEwn2cH4ohLmnYNDJhUj9AJhHum4BDQ/uHgUtOrJRkB7Cj7f57ks+NsxG5bpyvxnnAP4/1FVdfj32CPvvVY5+gz34tuU8rzKpvW+jAql1QrardwO7Vev+lSLK/qmZXux3j1GOfoM9+9dgn6LNfa6lPk1jnfgTYMrS/uZVJkqZkEuH+SeDCJBckOQt4JbB3Au8jSVrA2KdlquqrSa4F/pLBUsh3VNVnx/0+U3ZKTB8tUY99gj771WOfoM9+rZk+papWuw2SpDHz3jKS1CHDXZI6dFqHe5LXJrk3yWeTvK6VPSfJ3yX5TJL3J/mWBc5dl+TWJA8kuT/JC6ba+JNYYb9+sZ13b5J3JXnKVBv/tW15R5JjSe4dKjsnyR1JHmzPT2/lSfLWJAeS3JPk4gVe83ntv8GBVj/T6k97/7H2KclTk3yw/Tv8bJJVudXHJD6rodfZO/y60zKhf39nJdmd5PPtM/uxiXWgqk7LB/BdwL3AUxlcWP4r4JkMVvt8f6vzM8AbFzh/D/CzbfssYN1q92ml/WLwBbR/BL6x7d8CvHoV+/JC4GLg3qGy3wZ2tu2dwHVt+3LgL4AAlwJ3LvCaf9+Op9W/7FTuU/ucXzz07/Cvp92nSX1Wre6PAn86/Lqncp+A3wTe1LafBJw3sfZP+z/YWnkArwBuHNr/deBXgMf5/wvNW4D75jn3aS0Es9r9GHO/jn+7+BwGPxg+ALx0lfszc8L/XJ8DNrbtjcDn2vbbgFfNV2+obCPwwND+q4C3ncp9mue1rwd+7lT/rFr5NwF/Azx7NcJ9Qn06BJw9jbafztMy9wLfl+TcJE9l8JN3C/BZBvfCgUFQbpnn3AuAOeCdST6d5O1Jzp5Go0ew7H5V1RHgd4B/Ao4Cj1fVh6fS6tFtqKqjbfsRYEPbnu+2F5tOOHdTKz9ZndWwkj79nyTrgB8G9k2gjcux0n69Efhd4ImJtXDplt2n9vkAvDHJp5K8J8kGJuS0Dfequh+4Dvgw8CHgbuC/GUxZ/HySu4BvBr4yz+lnMvh17Yaqei7wZQa/oq26lfSrzR9uY/DD6xnA2Ul+cjotX7oaDIW6Wsu73D4lORN4F/DWajftW0uW2q8kFwHfXlXvm1ijVmgZn9WZDL6x/7dVdTHwdwwGUxNx2oY7QFXdWFXPq6oXAo8Bn6+qB6rqpVX1PAb/s3xhnlMPA4er6s62fyuDsF8TVtCvHwD+sarmquq/gPcC3z29lo/k0SQbAdrzsVY+ym0vjrTyk9VZDSvp03G7gQer6i2TauQyrKRfLwBmkxxkMDXzHUk+NtHWjmYlffoig99C3tv238MEc+O0Dvck39qez6dduBkqexLwa8AfnnheVT0CHEryrFa0lQnd0ng5ltsvBtMxl7YVGGHQr/un0+qR7QWubttXA7cNlf90W7VwKYMppaPDJ7b9f01yaevfTw+dv5qW3SeAJG9icB3odVNo61Ks5LO6oaqeUVUzwPcyGKC8aDrNPqmV9KmA9wMvakWTzY3VuEixVh4MVhbcB/wDsLWVvRb4fHvs4v8vQj4DuH3o3IuA/cA9wJ8DT1/t/oypX78JPMBg7v6PgSevYj/exWDu/78Y/La0HTiXwZzygwxWAp3T6obBH4n5AvAZYHbode4e2p5tffsC8PtM+aL4uPvEYIRYDH4I390eP9vDZzVUNsPqrJaZxL+/bwM+3nJjH3D+pNrv7QckqUOn9bSMJPXKcJekDhnuktQhw12SOmS4S1KHDHdJ6pDhLkkd+l+o5yFN+3mp1gAAAABJRU5ErkJggg==\n",
- "text/plain": [
- ""
- ]
- },
- "metadata": {
- "filenames": {
- "image/png": "/Users/mhjensen/Teaching/MachineLearning/doc/LectureNotes/_build/jupyter_execute/chapter2_25_2.png"
- },
- "needs_background": "light"
- },
- "output_type": "display_data"
- }
- ],
- "source": [
- "%matplotlib inline\n",
- "\n",
- "from numpy import *\n",
- "from numpy.random import randint, randn\n",
- "from time import time\n",
- "import matplotlib.mlab as mlab\n",
- "import matplotlib.pyplot as plt\n",
- "\n",
- "# Returns mean of bootstrap samples \n",
- "def stat(data):\n",
- " return mean(data)\n",
- "\n",
- "# Bootstrap algorithm\n",
- "def bootstrap(data, statistic, R):\n",
- " t = zeros(R); n = len(data); inds = arange(n); t0 = time()\n",
- " # non-parametric bootstrap \n",
- " for i in range(R):\n",
- " t[i] = statistic(data[randint(0,n,n)])\n",
- "\n",
- " # analysis \n",
- " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Bootstrap Statistics :\")\n",
- " print(\"original bias std. error\")\n",
- " print(\"%8g %8g %14g %15g\" % (statistic(data), std(data),mean(t),std(t)))\n",
- " return t\n",
- "\n",
- "\n",
- "mu, sigma = 100, 15\n",
- "datapoints = 10000\n",
- "x = mu + sigma*random.randn(datapoints)\n",
- "# bootstrap returns the data sample \n",
- "t = bootstrap(x, stat, datapoints)\n",
- "# the histogram of the bootstrapped data \n",
- "n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)\n",
- "\n",
- "# add a 'best fit' line \n",
- "y = mlab.normpdf( binsboot, mean(t), std(t))\n",
- "lt = plt.plot(binsboot, y, 'r--', linewidth=1)\n",
- "plt.xlabel('Smarts')\n",
- "plt.ylabel('Probability')\n",
- "plt.axis([99.5, 100.6, 0, 3.0])\n",
- "plt.grid(True)\n",
- "\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Various steps in cross-validation\n",
- "\n",
- "When the repetitive splitting of the data set is done randomly,\n",
- "samples may accidently end up in a fast majority of the splits in\n",
- "either training or test set. Such samples may have an unbalanced\n",
- "influence on either model building or prediction evaluation. To avoid\n",
- "this $k$-fold cross-validation structures the data splitting. The\n",
- "samples are divided into $k$ more or less equally sized exhaustive and\n",
- "mutually exclusive subsets. In turn (at each split) one of these\n",
- "subsets plays the role of the test set while the union of the\n",
- "remaining subsets constitutes the training set. Such a splitting\n",
- "warrants a balanced representation of each sample in both training and\n",
- "test set over the splits. Still the division into the $k$ subsets\n",
- "involves a degree of randomness. This may be fully excluded when\n",
- "choosing $k=n$. This particular case is referred to as leave-one-out\n",
- "cross-validation (LOOCV). \n",
- "\n",
- "\n",
- "* Define a range of interest for the penalty parameter.\n",
- "\n",
- "* Divide the data set into training and test set comprising samples $\\{1, \\ldots, n\\} \\setminus i$ and $\\{ i \\}$, respectively.\n",
- "\n",
- "* Fit the linear regression model by means of ridge estimation for each $\\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\\boldsymbol{\\sigma}_{-i}^2(\\lambda)$, as"
+ "We assume now that the various $y_i$ values are stochastically distributed according to the above Gaussian distribution. \n",
+ "We define this distribution as"
]
},
{
@@ -661,11 +3769,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\begin{align*}\n",
- "\\boldsymbol{\\beta}_{-i}(\\lambda) & = ( \\boldsymbol{X}_{-i, \\ast}^{T}\n",
- "\\boldsymbol{X}_{-i, \\ast} + \\lambda \\boldsymbol{I}_{pp})^{-1}\n",
- "\\boldsymbol{X}_{-i, \\ast}^{T} \\boldsymbol{y}_{-i}\n",
- "\\end{align*}\n",
+ "p(y_i, \\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]},\n",
"$$"
]
},
@@ -673,11 +3777,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "* Evaluate the prediction performance of these models on the test set by $\\log\\{L[y_i, \\boldsymbol{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}$. Or, by the prediction error $|y_i - \\boldsymbol{X}_{i, \\ast} \\boldsymbol{\\beta}_{-i}(\\lambda)|$, the relative error, the error squared or the R2 score function.\n",
+ "which reads as finding the likelihood of an event $y_i$ with the input variables $\\boldsymbol{X}$ given the parameters (to be determined) $\\boldsymbol{\\beta}$.\n",
"\n",
- "* Repeat the first three steps such that each sample plays the role of the test set once.\n",
- "\n",
- "* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as"
+ "Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event $\\boldsymbol{y}$ as the product of the single events, that is we have"
]
},
{
@@ -685,9 +3787,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\begin{align*}\n",
- "\\frac{1}{n} \\sum_{i = 1}^n \\log\\{L[y_i, \\mathbf{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}.\n",
- "\\end{align*}\n",
+ "p(\\boldsymbol{y},\\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}=\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta}).\n",
"$$"
]
},
@@ -695,26 +3795,360 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "For the various values of $k$\n",
- "\n",
- "1. shuffle the dataset randomly.\n",
- "\n",
- "2. Split the dataset into $k$ groups.\n",
- "\n",
- "3. For each unique group:\n",
- "\n",
- "a. Decide which group to use as set for test data\n",
- "\n",
- "b. Take the remaining groups as a training data set\n",
- "\n",
- "c. Fit a model on the training set and evaluate it on the test set\n",
- "\n",
- "d. Retain the evaluation score and discard the model\n",
+ "We will write this in a more compact form reserving $\\boldsymbol{D}$ for the domain of events, including the ouputs (targets) and the inputs. That is\n",
+ "in case we have a simple one-dimensional input and output case"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})].\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the more general case the various inputs should be replaced by the possible features represented by the input data set $\\boldsymbol{X}$. \n",
+ "We can now rewrite the above probability as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It is a conditional probability (see below) and reads as the likelihood of a domain of events $\\boldsymbol{D}$ given a set of parameters $\\boldsymbol{\\beta}$.\n",
"\n",
"\n",
- "5. Summarize the model using the sample of model evaluation scores\n",
+ "In statistics, maximum likelihood estimation (MLE) is a method of\n",
+ "estimating the parameters of an assumed probability distribution,\n",
+ "given some observed data. This is achieved by maximizing a likelihood\n",
+ "function so that, under the assumed statistical model, the observed\n",
+ "data is the most probable. \n",
"\n",
- "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial."
+ "\n",
+ "We will assume here that our events are given by the above Gaussian\n",
+ "distribution and we will determine the optimal parameters $\\beta$ by\n",
+ "maximizing the above PDF. However, computing the derivatives of a\n",
+ "product function is cumbersome and can easily lead to overflow and/or\n",
+ "underflowproblems, with potentials for loss of numerical precision.\n",
+ "\n",
+ "\n",
+ "In practice, it is more convenient to maximize the logarithm of the\n",
+ "PDF because it is a monotonically increasing function of the argument.\n",
+ "Alternatively, and this will be our option, we will minimize the\n",
+ "negative of the logarithm since this is a monotonically decreasing\n",
+ "function.\n",
+ "\n",
+ "Note also that maximization/minimization of the logarithm of the PDF\n",
+ "is equivalent to the maximization/minimization of the function itself.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "We could now define a new cost function to minimize, namely the negative logarithm of the above PDF"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta}=-\\log{\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})}=-\\sum_{i=0}^{n-1}\\log{p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta}=\\frac{n}{2}\\log{2\\pi\\sigma^2}+\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Taking the derivative of the *new* cost function with respect to the parameters $\\beta$ we recognize our familiar OLS equation, namely"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right) =0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to the well-known OLS equation for the optimal paramters $\\beta$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}!\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics. \n",
+ "\n",
+ "\n",
+ "A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry.\n",
+ "Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics.\n",
+ "\n",
+ "Assume we have two domains of events $X=[x_0,x_1,\\dots,x_{n-1}]$ and $Y=[y_0,y_1,\\dots,y_{n-1}]$.\n",
+ "\n",
+ "We define also the likelihood for $X$ and $Y$ as $p(X)$ and $p(Y)$ respectively.\n",
+ "The likelihood of a specific event $x_i$ (or $y_i$) is then written as $p(X=x_i)$ or just $p(x_i)=p_i$. \n",
+ "\n",
+ "**Union of events is given by.**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X \\cup Y)= p(X)+p(Y)-p(X \\cap Y).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**The product rule (aka joint probability) is given by.**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X \\cup Y)= p(X,Y)= p(X\\vert Y)p(Y)=p(Y\\vert X)p(X),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we read $p(X\\vert Y)$ as the likelihood of obtaining $X$ given $Y$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "If we have independent events then $p(X,Y)=p(X)p(Y)$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The marginal probability is defined in terms of only one of the set of variables $X,Y$. For a discrete probability we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X)=\\sum_{i=0}^{n-1}p(X,Y=y_i)=\\sum_{i=0}^{n-1}p(X\\vert Y=y_i)p(Y=y_i)=\\sum_{i=0}^{n-1}p(X\\vert y_i)p(y_i).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The conditional probability, if $p(Y) > 0$, is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)}=\\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we combine the conditional probability with the marginal probability and the standard product rule, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which we can rewrite as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X\\vert Y)= \\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}=\\frac{p(Y\\vert X)p(X)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is Bayes' theorem. It allows us to evaluate the uncertainty in in $X$ after we have observed $Y$. We can easily interchange $X$ with $Y$. \n",
+ "\n",
+ "\n",
+ "The quantity $p(Y\\vert X)$ on the right-hand side of the theorem is\n",
+ "evaluated for the observed data $Y$ and can be viewed as a function of\n",
+ "the parameter space represented by $X$. This function is not\n",
+ "necesseraly normalized and is normally called the likelihood function.\n",
+ "\n",
+ "The function $p(X)$ on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution.\n",
+ "\n",
+ "Let us try to illustrate Bayes' theorem through an example.\n",
+ "\n",
+ "\n",
+ "Let us suppose that you are undergoing a series of mammography scans in\n",
+ "order to rule out possible breast cancer cases. We define the\n",
+ "sensitivity for a positive event by the variable $X$. It takes binary\n",
+ "values with $X=1$ representing a positive event and $X=0$ being a\n",
+ "negative event. We reserve $Y$ as a classification parameter for\n",
+ "either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing).\n",
+ "\n",
+ "We let $Y=1$ represent the the case of having breast cancer and $Y=0$ as not.\n",
+ "\n",
+ "Let us assume that if you have breast cancer, the test will be positive with a probability of $0.8$, that is we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X=1\\vert Y=1) =0.8.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of $80\\%$ for having cancer.\n",
+ "It is however not correct, as the following Bayesian analysis shows.\n",
+ "\n",
+ "\n",
+ "If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number.\n",
+ "Let us assume that the prior probability in the population as a whole is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(Y=1) =0.004.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X=1\\vert Y=0) =0.1.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(Y=1\\vert X=1)=\\frac{p(X=1\\vert Y=1)p(Y=1)}{p(X=1\\vert Y=1)p(Y=1)+p(X=1\\vert Y=0)p(Y=0)}=\\frac{0.8\\times 0.004}{0.8\\times 0.004+0.1\\times 0.996}=0.031.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "That is, in case of a positive test, there is only a $3\\%$ chance of having breast cancer!\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Bayes' Theorem and Ridge and Lasso Regression\n",
+ "\n",
+ "Hitherto we have discussed Ridge and Lasso regression in terms of a\n",
+ "linear analysis. This may to many of you feel rather technical and\n",
+ "perhaps not that intuitive. The question is whether we can develop a\n",
+ "more intuitive way of understanding what Ridge and Lasso express.\n",
+ "\n",
+ "Before we proceed let us perform a Ridge, Lasso and OLS analysis of a polynomial fit. \n",
+ "\n",
+ "\n",
+ "We will play around with a study of the values for the optimal\n",
+ "parameters $\\boldsymbol{\\beta}$ using OLS, Ridge and Lasso regression. For\n",
+ "OLS, you will notice as function of the noise and polynomial degree,\n",
+ "that the parameters $\\beta$ will fluctuate from order to order in the\n",
+ "polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS.\n",
+ "\n",
+ "For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one."
]
},
{
@@ -728,674 +4162,289 @@
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
- "from sklearn.model_selection import KFold\n",
- "from sklearn.linear_model import Ridge\n",
- "from sklearn.model_selection import cross_val_score\n",
- "from sklearn.preprocessing import PolynomialFeatures\n",
- "\n",
- "# A seed just to ensure that the random numbers are the same for every run.\n",
- "# Useful for eventual debugging.\n",
- "np.random.seed(3155)\n",
- "\n",
- "# Generate the data.\n",
- "nsamples = 100\n",
- "x = np.random.randn(nsamples)\n",
- "y = 3*x**2 + np.random.randn(nsamples)\n",
- "\n",
- "## Cross-validation on Ridge regression using KFold only\n",
- "\n",
- "# Decide degree on polynomial to fit\n",
- "poly = PolynomialFeatures(degree = 6)\n",
- "\n",
- "# Decide which values of lambda to use\n",
- "nlambdas = 500\n",
- "lambdas = np.logspace(-3, 5, nlambdas)\n",
- "\n",
- "# Initialize a KFold instance\n",
- "k = 5\n",
- "kfold = KFold(n_splits = k)\n",
- "\n",
- "# Perform the cross-validation to estimate MSE\n",
- "scores_KFold = np.zeros((nlambdas, k))\n",
- "\n",
- "i = 0\n",
- "for lmb in lambdas:\n",
- " ridge = Ridge(alpha = lmb)\n",
- " j = 0\n",
- " for train_inds, test_inds in kfold.split(x):\n",
- " xtrain = x[train_inds]\n",
- " ytrain = y[train_inds]\n",
- "\n",
- " xtest = x[test_inds]\n",
- " ytest = y[test_inds]\n",
- "\n",
- " Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n",
- " ridge.fit(Xtrain, ytrain[:, np.newaxis])\n",
- "\n",
- " Xtest = poly.fit_transform(xtest[:, np.newaxis])\n",
- " ypred = ridge.predict(Xtest)\n",
- "\n",
- " scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n",
- "\n",
- " j += 1\n",
- " i += 1\n",
- "\n",
- "\n",
- "estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n",
- "\n",
- "## Cross-validation using cross_val_score from sklearn along with KFold\n",
- "\n",
- "# kfold is an instance initialized above as:\n",
- "# kfold = KFold(n_splits = k)\n",
- "\n",
- "estimated_mse_sklearn = np.zeros(nlambdas)\n",
- "i = 0\n",
- "for lmb in lambdas:\n",
- " ridge = Ridge(alpha = lmb)\n",
- "\n",
- " X = poly.fit_transform(x[:, np.newaxis])\n",
- " estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n",
- "\n",
- " # cross_val_score return an array containing the estimated negative mse for every fold.\n",
- " # we have to the the mean of every array in order to get an estimate of the mse of the model\n",
- " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n",
- "\n",
- " i += 1\n",
- "\n",
- "## Plot and compare the slightly different ways to perform cross-validation\n",
- "\n",
- "plt.figure()\n",
- "\n",
- "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n",
- "plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n",
- "\n",
- "plt.xlabel('log10(lambda)')\n",
- "plt.ylabel('mse')\n",
- "\n",
- "plt.legend()\n",
- "\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## The bias-variance tradeoff\n",
- "\n",
- "\n",
- "We will discuss the bias-variance tradeoff in the context of\n",
- "continuous predictions such as regression. However, many of the\n",
- "intuitions and ideas discussed here also carry over to classification\n",
- "tasks. Consider a dataset $\\mathcal{L}$ consisting of the data\n",
- "$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$. \n",
- "\n",
- "Let us assume that the true data is generated from a noisy model"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "where $\\epsilon$ is normally distributed with mean zero and standard deviation $\\sigma^2$.\n",
- "\n",
- "In our derivation of the ordinary least squares method we defined then\n",
- "an approximation to the function $f$ in terms of the parameters\n",
- "$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n",
- "that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$. \n",
- "\n",
- "Thereafter we found the parameters $\\boldsymbol{\\beta}$ by optimizing the means squared error via the so-called cost function"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We can rewrite this as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\frac{1}{n}\\sum_i(f_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\sigma^2.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The three terms represent the square of the bias of the learning\n",
- "method, which can be thought of as the error caused by the simplifying\n",
- "assumptions built into the method. The second term represents the\n",
- "variance of the chosen model and finally the last terms is variance of\n",
- "the error $\\boldsymbol{\\epsilon}$.\n",
- "\n",
- "To derive this equation, we need to recall that the variance of $\\boldsymbol{y}$ and $\\boldsymbol{\\epsilon}$ are both equal to $\\sigma^2$. The mean value of $\\boldsymbol{\\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\\boldsymbol{\\tilde{y}}$.\n",
- "We use a more compact notation in terms of the expectation value"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}})^2\\right],\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "and adding and subtracting $\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]$ we get"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}}+\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right],\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which, using the abovementioned expectation values can be rewritten as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right]+\\mathrm{Var}\\left[\\boldsymbol{\\tilde{y}}\\right]+\\sigma^2,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "that is the rewriting in terms of the so-called bias, the variance of the model $\\boldsymbol{\\tilde{y}}$ and the variance of $\\boldsymbol{\\epsilon}$."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "import matplotlib.pyplot as plt\n",
- "import numpy as np\n",
- "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
- "from sklearn.preprocessing import PolynomialFeatures\n",
"from sklearn.model_selection import train_test_split\n",
- "from sklearn.pipeline import make_pipeline\n",
- "from sklearn.utils import resample\n",
+ "from sklearn import linear_model\n",
"\n",
- "np.random.seed(2018)\n",
- "\n",
- "n = 500\n",
- "n_boostraps = 100\n",
- "degree = 18 # A quite high value, just to show.\n",
- "noise = 0.1\n",
+ "def R2(y_data, y_model):\n",
+ " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
"\n",
"# Make data set.\n",
- "x = np.linspace(-1, 3, n).reshape(-1, 1)\n",
- "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)\n",
+ "n = 10000\n",
+ "x = np.random.rand(n)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n",
"\n",
- "# Hold out some test data that is never used in training.\n",
- "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
- "\n",
- "# Combine x transformation and model into one operation.\n",
- "# Not neccesary, but convenient.\n",
- "model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
- "\n",
- "# The following (m x n_bootstraps) matrix holds the column vectors y_pred\n",
- "# for each bootstrap iteration.\n",
- "y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
- "for i in range(n_boostraps):\n",
- " x_, y_ = resample(x_train, y_train)\n",
- "\n",
- " # Evaluate the new model on the same test data each time.\n",
- " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
- "\n",
- "# Note: Expectations and variances taken w.r.t. different training\n",
- "# data sets, hence the axis=1. Subsequent means are taken across the test data\n",
- "# set in order to obtain a total value, but before this we have error/bias/variance\n",
- "# calculated per data point in the test set.\n",
- "# Note 2: The use of keepdims=True is important in the calculation of bias as this \n",
- "# maintains the column vector form. Dropping this yields very unexpected results.\n",
- "error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
- "bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
- "variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
- "print('Error:', error)\n",
- "print('Bias^2:', bias)\n",
- "print('Var:', variance)\n",
- "print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))\n",
- "\n",
- "plt.plot(x[::5, :], y[::5, :], label='f(x)')\n",
- "plt.scatter(x_test, y_test, label='Data points')\n",
- "plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')\n",
- "plt.legend()\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "import matplotlib.pyplot as plt\n",
- "import numpy as np\n",
- "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
- "from sklearn.preprocessing import PolynomialFeatures\n",
- "from sklearn.model_selection import train_test_split\n",
- "from sklearn.pipeline import make_pipeline\n",
- "from sklearn.utils import resample\n",
- "\n",
- "np.random.seed(2018)\n",
- "\n",
- "n = 40\n",
- "n_boostraps = 100\n",
- "maxdegree = 14\n",
- "\n",
- "\n",
- "# Make data set.\n",
- "x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
- "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
- "error = np.zeros(maxdegree)\n",
- "bias = np.zeros(maxdegree)\n",
- "variance = np.zeros(maxdegree)\n",
- "polydegree = np.zeros(maxdegree)\n",
- "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
- "\n",
- "for degree in range(maxdegree):\n",
- " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
- " y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
- " for i in range(n_boostraps):\n",
- " x_, y_ = resample(x_train, y_train)\n",
- " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
- "\n",
- " polydegree[degree] = degree\n",
- " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
- " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
- " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
- " print('Polynomial degree:', degree)\n",
- " print('Error:', error[degree])\n",
- " print('Bias^2:', bias[degree])\n",
- " print('Var:', variance[degree])\n",
- " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n",
- "\n",
- "plt.plot(polydegree, error, label='Error')\n",
- "plt.plot(polydegree, bias, label='bias')\n",
- "plt.plot(polydegree, variance, label='Variance')\n",
- "plt.legend()\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The bias-variance tradeoff summarizes the fundamental tension in\n",
- "machine learning, particularly supervised learning, between the\n",
- "complexity of a model and the amount of training data needed to train\n",
- "it. Since data is often limited, in practice it is often useful to\n",
- "use a less-complex model with higher bias, that is a model whose asymptotic\n",
- "performance is worse than another model because it is easier to\n",
- "train and less sensitive to sampling noise arising from having a\n",
- "finite-sized training dataset (smaller variance). \n",
- "\n",
- "\n",
- "\n",
- "The above equations tell us that in\n",
- "order to minimize the expected test error, we need to select a\n",
- "statistical learning method that simultaneously achieves low variance\n",
- "and low bias. Note that variance is inherently a nonnegative quantity,\n",
- "and squared bias is also nonnegative. Hence, we see that the expected\n",
- "test MSE can never lie below $Var(\\epsilon)$, the irreducible error.\n",
- "\n",
- "\n",
- "What do we mean by the variance and bias of a statistical learning\n",
- "method? The variance refers to the amount by which our model would change if we\n",
- "estimated it using a different training data set. Since the training\n",
- "data are used to fit the statistical learning method, different\n",
- "training data sets will result in a different estimate. But ideally the\n",
- "estimate for our model should not vary too much between training\n",
- "sets. However, if a method has high variance then small changes in\n",
- "the training data can result in large changes in the model. In general, more\n",
- "flexible statistical methods have higher variance.\n",
- "\n",
- "\n",
- "You may also find this recent [article](https://www.pnas.org/content/116/32/15849) of interest."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "\"\"\"\n",
- "============================\n",
- "Underfitting vs. Overfitting\n",
- "============================\n",
- "\n",
- "This example demonstrates the problems of underfitting and overfitting and\n",
- "how we can use linear regression with polynomial features to approximate\n",
- "nonlinear functions. The plot shows the function that we want to approximate,\n",
- "which is a part of the cosine function. In addition, the samples from the\n",
- "real function and the approximations of different models are displayed. The\n",
- "models have polynomial features of different degrees. We can see that a\n",
- "linear function (polynomial with degree 1) is not sufficient to fit the\n",
- "training samples. This is called **underfitting**. A polynomial of degree 4\n",
- "approximates the true function almost perfectly. However, for higher degrees\n",
- "the model will **overfit** the training data, i.e. it learns the noise of the\n",
- "training data.\n",
- "We evaluate quantitatively **overfitting** / **underfitting** by using\n",
- "cross-validation. We calculate the mean squared error (MSE) on the validation\n",
- "set, the higher, the less likely the model generalizes correctly from the\n",
- "training data.\n",
- "\"\"\"\n",
- "\n",
- "print(__doc__)\n",
- "\n",
- "import numpy as np\n",
- "import matplotlib.pyplot as plt\n",
- "from sklearn.pipeline import Pipeline\n",
- "from sklearn.preprocessing import PolynomialFeatures\n",
- "from sklearn.linear_model import LinearRegression\n",
- "from sklearn.model_selection import cross_val_score\n",
- "\n",
- "\n",
- "def true_fun(X):\n",
- " return np.cos(1.5 * np.pi * X)\n",
- "\n",
- "np.random.seed(0)\n",
- "\n",
- "n_samples = 30\n",
- "degrees = [1, 4, 15]\n",
- "\n",
- "X = np.sort(np.random.rand(n_samples))\n",
- "y = true_fun(X) + np.random.randn(n_samples) * 0.1\n",
- "\n",
- "plt.figure(figsize=(14, 5))\n",
- "for i in range(len(degrees)):\n",
- " ax = plt.subplot(1, len(degrees), i + 1)\n",
- " plt.setp(ax, xticks=(), yticks=())\n",
- "\n",
- " polynomial_features = PolynomialFeatures(degree=degrees[i],\n",
- " include_bias=False)\n",
- " linear_regression = LinearRegression()\n",
- " pipeline = Pipeline([(\"polynomial_features\", polynomial_features),\n",
- " (\"linear_regression\", linear_regression)])\n",
- " pipeline.fit(X[:, np.newaxis], y)\n",
- "\n",
- " # Evaluate the models using crossvalidation\n",
- " scores = cross_val_score(pipeline, X[:, np.newaxis], y,\n",
- " scoring=\"neg_mean_squared_error\", cv=10)\n",
- "\n",
- " X_test = np.linspace(0, 1, 100)\n",
- " plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label=\"Model\")\n",
- " plt.plot(X_test, true_fun(X_test), label=\"True function\")\n",
- " plt.scatter(X, y, edgecolor='b', s=20, label=\"Samples\")\n",
- " plt.xlabel(\"x\")\n",
- " plt.ylabel(\"y\")\n",
- " plt.xlim((0, 1))\n",
- " plt.ylim((-2, 2))\n",
- " plt.legend(loc=\"best\")\n",
- " plt.title(\"Degree {}\\nMSE = {:.2e}(+/- {:.2e})\".format(\n",
- " degrees[i], -scores.mean(), scores.std()))\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "# Common imports\n",
- "import os\n",
- "import numpy as np\n",
- "import pandas as pd\n",
- "import matplotlib.pyplot as plt\n",
- "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
- "from sklearn.model_selection import train_test_split\n",
- "from sklearn.utils import resample\n",
- "from sklearn.metrics import mean_squared_error\n",
- "# Where to save the figures and data files\n",
- "PROJECT_ROOT_DIR = \"Results\"\n",
- "FIGURE_ID = \"Results/FigureFiles\"\n",
- "DATA_ID = \"DataFiles/\"\n",
- "\n",
- "if not os.path.exists(PROJECT_ROOT_DIR):\n",
- " os.mkdir(PROJECT_ROOT_DIR)\n",
- "\n",
- "if not os.path.exists(FIGURE_ID):\n",
- " os.makedirs(FIGURE_ID)\n",
- "\n",
- "if not os.path.exists(DATA_ID):\n",
- " os.makedirs(DATA_ID)\n",
- "\n",
- "def image_path(fig_id):\n",
- " return os.path.join(FIGURE_ID, fig_id)\n",
- "\n",
- "def data_path(dat_id):\n",
- " return os.path.join(DATA_ID, dat_id)\n",
- "\n",
- "def save_fig(fig_id):\n",
- " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
- "\n",
- "infile = open(data_path(\"EoS.csv\"),'r')\n",
- "\n",
- "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
- "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
- "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
- "EoS = EoS.dropna()\n",
- "Energies = EoS['Energy']\n",
- "Density = EoS['Density']\n",
- "# The design matrix now as function of various polytrops\n",
- "\n",
- "Maxpolydegree = 30\n",
- "X = np.zeros((len(Density),Maxpolydegree))\n",
+ "Maxpolydegree = 5\n",
+ "X = np.zeros((len(x),Maxpolydegree))\n",
"X[:,0] = 1.0\n",
- "testerror = np.zeros(Maxpolydegree)\n",
- "trainingerror = np.zeros(Maxpolydegree)\n",
- "polynomial = np.zeros(Maxpolydegree)\n",
- "\n",
- "trials = 100\n",
- "for polydegree in range(1, Maxpolydegree):\n",
- " polynomial[polydegree] = polydegree\n",
- " for degree in range(polydegree):\n",
- " X[:,degree] = Density**(degree/3.0)\n",
- "\n",
- "# loop over trials in order to estimate the expectation value of the MSE\n",
- " testerror[polydegree] = 0.0\n",
- " trainingerror[polydegree] = 0.0\n",
- " for samples in range(trials):\n",
- " x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n",
- " model = LinearRegression(fit_intercept=True).fit(x_train, y_train)\n",
- " ypred = model.predict(x_train)\n",
- " ytilde = model.predict(x_test)\n",
- " testerror[polydegree] += mean_squared_error(y_test, ytilde)\n",
- " trainingerror[polydegree] += mean_squared_error(y_train, ypred) \n",
- "\n",
- " testerror[polydegree] /= trials\n",
- " trainingerror[polydegree] /= trials\n",
- " print(\"Degree of polynomial: %3d\"% polynomial[polydegree])\n",
- " print(\"Mean squared error on training data: %.8f\" % trainingerror[polydegree])\n",
- " print(\"Mean squared error on test data: %.8f\" % testerror[polydegree])\n",
- "\n",
- "plt.plot(polynomial, np.log10(trainingerror), label='Training Error')\n",
- "plt.plot(polynomial, np.log10(testerror), label='Test Error')\n",
- "plt.xlabel('Polynomial degree')\n",
- "plt.ylabel('log10[MSE]')\n",
- "plt.legend()\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "# Common imports\n",
- "import os\n",
- "import numpy as np\n",
- "import pandas as pd\n",
- "import matplotlib.pyplot as plt\n",
- "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
- "from sklearn.metrics import mean_squared_error\n",
- "from sklearn.model_selection import KFold\n",
- "from sklearn.model_selection import cross_val_score\n",
- "\n",
- "\n",
- "# Where to save the figures and data files\n",
- "PROJECT_ROOT_DIR = \"Results\"\n",
- "FIGURE_ID = \"Results/FigureFiles\"\n",
- "DATA_ID = \"DataFiles/\"\n",
- "\n",
- "if not os.path.exists(PROJECT_ROOT_DIR):\n",
- " os.mkdir(PROJECT_ROOT_DIR)\n",
- "\n",
- "if not os.path.exists(FIGURE_ID):\n",
- " os.makedirs(FIGURE_ID)\n",
- "\n",
- "if not os.path.exists(DATA_ID):\n",
- " os.makedirs(DATA_ID)\n",
- "\n",
- "def image_path(fig_id):\n",
- " return os.path.join(FIGURE_ID, fig_id)\n",
- "\n",
- "def data_path(dat_id):\n",
- " return os.path.join(DATA_ID, dat_id)\n",
- "\n",
- "def save_fig(fig_id):\n",
- " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
- "\n",
- "infile = open(data_path(\"EoS.csv\"),'r')\n",
- "\n",
- "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
- "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
- "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
- "EoS = EoS.dropna()\n",
- "Energies = EoS['Energy']\n",
- "Density = EoS['Density']\n",
- "# The design matrix now as function of various polytrops\n",
- "\n",
- "Maxpolydegree = 30\n",
- "X = np.zeros((len(Density),Maxpolydegree))\n",
- "X[:,0] = 1.0\n",
- "estimated_mse_sklearn = np.zeros(Maxpolydegree)\n",
- "polynomial = np.zeros(Maxpolydegree)\n",
- "k =5\n",
- "kfold = KFold(n_splits = k)\n",
"\n",
"for polydegree in range(1, Maxpolydegree):\n",
- " polynomial[polydegree] = polydegree\n",
" for degree in range(polydegree):\n",
- " X[:,degree] = Density**(degree/3.0)\n",
- " OLS = LinearRegression()\n",
- "# loop over trials in order to estimate the expectation value of the MSE\n",
- " estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)\n",
- "#[:, np.newaxis]\n",
- " estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)\n",
+ " X[:,degree] = x**(degree)\n",
"\n",
- "plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')\n",
- "plt.xlabel('Polynomial degree')\n",
- "plt.ylabel('log10[MSE]')\n",
- "plt.legend()\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "import numpy as np\n",
- "import matplotlib.pyplot as plt\n",
- "from sklearn.model_selection import KFold\n",
- "from sklearn.linear_model import Ridge\n",
- "from sklearn.model_selection import cross_val_score\n",
- "from sklearn.preprocessing import PolynomialFeatures\n",
"\n",
- "# A seed just to ensure that the random numbers are the same for every run.\n",
- "np.random.seed(3155)\n",
- "# Generate the data.\n",
- "n = 100\n",
- "x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
- "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
- "# Decide degree on polynomial to fit\n",
- "poly = PolynomialFeatures(degree = 10)\n",
+ "# We split the data in test and training data\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
"\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.pinv(X_train.T @ X_train) @ X_train.T @ y_train\n",
+ "print(OLSbeta)\n",
+ "ypredictOLS = X_test @ OLSbeta\n",
+ "print(\"Test MSE OLS\")\n",
+ "print(MSE(y_test,ypredictOLS))\n",
+ "# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn\n",
"# Decide which values of lambda to use\n",
- "nlambdas = 500\n",
- "lambdas = np.logspace(-3, 5, nlambdas)\n",
- "# Initialize a KFold instance\n",
- "k = 5\n",
- "kfold = KFold(n_splits = k)\n",
- "estimated_mse_sklearn = np.zeros(nlambdas)\n",
- "i = 0\n",
- "for lmb in lambdas:\n",
- " ridge = Ridge(alpha = lmb)\n",
- " estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)\n",
- " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n",
- " i += 1\n",
+ "nlambdas = 4\n",
+ "MSERidgePredict = np.zeros(nlambdas)\n",
+ "MSELassoPredict = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-3, 1, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " # Make the fit using Ridge and Lasso\n",
+ " RegRidge = linear_model.Ridge(lmb,fit_intercept=False)\n",
+ " RegRidge.fit(X_train,y_train)\n",
+ " RegLasso = linear_model.Lasso(lmb,fit_intercept=False)\n",
+ " RegLasso.fit(X_train,y_train)\n",
+ " # and then make the prediction\n",
+ " ypredictRidge = RegRidge.predict(X_test)\n",
+ " ypredictLasso = RegLasso.predict(X_test)\n",
+ " # Compute the MSE and print it\n",
+ " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n",
+ " MSELassoPredict[i] = MSE(y_test,ypredictLasso)\n",
+ " print(lmb,RegRidge.coef_)\n",
+ " print(lmb,RegLasso.coef_)\n",
+ "# Now plot the results\n",
"plt.figure()\n",
- "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n",
+ "plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')\n",
+ "plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')\n",
"plt.xlabel('log10(lambda)')\n",
"plt.ylabel('MSE')\n",
"plt.legend()\n",
"plt.show()"
]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "How can we understand this? \n",
+ "\n",
+ "\n",
+ "\n",
+ "Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression. \n",
+ "\n",
+ "For ordinary least squares we postulated that the maximum likelihood for the doamin of events $\\boldsymbol{D}$ (one-dimensional case)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})],\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "is given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set $\\boldsymbol{\\beta}$ given a domain of events $\\boldsymbol{D}$? That is, how can we define the posterior probability"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Bayes' theorem comes to our rescue here since (omitting the normalization constant)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})\\propto p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})p(\\boldsymbol{\\beta}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We have a model for $p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})$ but need one for the **prior** $p(\\boldsymbol{\\beta}$! \n",
+ "\n",
+ "\n",
+ "\n",
+ "With the posterior probability defined by a likelihood which we have\n",
+ "already modeled and an unknown prior, we are now ready to make\n",
+ "additional models for the prior.\n",
+ "\n",
+ "We can, based on our discussions of the variance of $\\boldsymbol{\\beta}$ and the mean value, assume that the prior for the values $\\boldsymbol{\\beta}$ is given by a Gaussian with mean value zero and variance $\\tau^2$, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Our posterior probability becomes then (omitting the normalization factor which is just a constant)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta\\vert\\boldsymbol{D})}=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can now optimize this quantity with respect to $\\boldsymbol{\\beta}$. As we\n",
+ "did for OLS, this is most conveniently done by taking the negative\n",
+ "logarithm of the posterior probability. Doing so and leaving out the\n",
+ "constants terms that do not depend on $\\beta$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{2\\tau^2}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and replacing $1/2\\tau^2$ with $\\lambda$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is our Ridge cost function! Nice, isn't it?\n",
+ "\n",
+ "\n",
+ "To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution ([Laplace in this case](https://en.wikipedia.org/wiki/Laplace_distribution)) with zero mean value, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Our posterior probability becomes then (omitting the normalization factor which is just a constant)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Taking the negative\n",
+ "logarithm of the posterior probability and leaving out the\n",
+ "constants terms that do not depend on $\\beta$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{\\tau}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and replacing $1/\\tau$ with $\\lambda$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is our Lasso cost function!"
+ ]
}
],
"metadata": {
diff --git a/doc/LectureNotes/_build/jupyter_execute/chapter2.py b/doc/LectureNotes/_build/jupyter_execute/chapter2.py
index 6aaa20907..59a7cc107 100644
--- a/doc/LectureNotes/_build/jupyter_execute/chapter2.py
+++ b/doc/LectureNotes/_build/jupyter_execute/chapter2.py
@@ -1,63 +1,1822 @@
-# Resampling Methods
-
-## Introduction
-
-Resampling methods are an indispensable tool in modern
-statistics. They involve repeatedly drawing samples from a training
-set and refitting a model of interest on each sample in order to
-obtain additional information about the fitted model. For example, in
-order to estimate the variability of a linear regression fit, we can
-repeatedly draw different samples from the training data, fit a linear
-regression to each new sample, and then examine the extent to which
-the resulting fits differ. Such an approach may allow us to obtain
-information that would not be available from fitting the model only
-once using the original training sample.
-
-Two resampling methods are often used in Machine Learning analyses,
-1. The **bootstrap method**
-
-2. and **Cross-Validation**
-
-In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular
-cross-validation and the bootstrap method.
+# Ridge and Lasso Regression
-Resampling approaches can be computationally expensive, because they
-involve fitting the same statistical method multiple times using
-different subsets of the training data. However, due to recent
-advances in computing power, the computational requirements of
-resampling methods generally are not prohibitive. In this chapter, we
-discuss two of the most commonly used resampling methods,
-cross-validation and the bootstrap. Both methods are important tools
-in the practical application of many statistical learning
-procedures. For example, cross-validation can be used to estimate the
-test error associated with a given statistical learning method in
-order to evaluate its performance, or to select the appropriate level
-of flexibility. The process of evaluating a model’s performance is
-known as model assessment, whereas the process of selecting the proper
-level of flexibility for a model is known as model selection. The
-bootstrap is widely used.
+
+## Mathematical Interpretation of Ordinary Least Squares
+
+What is presented here is a mathematical analysis of various regression algorithms (ordinary least squares, Ridge and Lasso Regression). The analysis is based on an important algorithm in linear algebra, the so-called Singular Value Decomposition (SVD).
-* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods
+We have shown that in ordinary least squares the optimal parameters $\beta$ are given by
-* The results can be analysed with the same statistical tools as we would use analysing experimental data.
+$$
+\hat{\boldsymbol{\beta}} = \left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
+$$
-* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
+The **hat** over $\boldsymbol{\beta}$ means we have the optimal parameters after minimization of the cost function.
-## Reminder on Statistics
+This means that our best model is defined as
+
+$$
+\tilde{\boldsymbol{y}}=\boldsymbol{X}\hat{\boldsymbol{\beta}} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
+$$
+
+We now define a matrix
+
+$$
+\boldsymbol{A}=\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T.
+$$
+
+We can rewrite
+
+$$
+\tilde{\boldsymbol{y}}=\boldsymbol{X}\hat{\boldsymbol{\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.
-* As in other experiments, many numerical experiments have two classes of errors:
-
- * Statistical errors
-
- * Systematical errors
-* Statistical errors can be estimated using standard tools from statistics
+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}$.
+
+
+If the matrix $\boldsymbol{X}$ is an orthogonal (or unitary in case of complex values) matrix, we have
+
+$$
+\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{X}\boldsymbol{X}^T = \boldsymbol{I}.
+$$
+
+In this case the matrix $\boldsymbol{A}$ becomes
+
+$$
+\boldsymbol{A}=\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T)=\boldsymbol{I},
+$$
+
+and we have the obvious case
+
+$$
+\boldsymbol{\epsilon}=\boldsymbol{y}-\tilde{\boldsymbol{y}}=0.
+$$
+
+This serves also as a useful test of our codes.
+
+
+
+
+## The singular value decomposition
+
+
+The examples we have looked at so far are cases where we normally can
+invert the matrix $\boldsymbol{X}^T\boldsymbol{X}$. Using a polynomial expansion where we fit of various functions leads to
+row vectors of the design matrix which are essentially orthogonal due
+to the polynomial character of our model. Obtaining the inverse of the
+design matrix is then often done via a so-called LU, QR or Cholesky
+decomposition.
+
+
+As we will also see in the first project,
+this may
+however not the be case in general and a standard matrix inversion
+algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.
+
+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.
+
+
+
+
+One of the typical problems we encounter with linear regression, in particular
+when the matrix $\boldsymbol{X}$ (our so-called design matrix) is high-dimensional,
+are problems with near singular or singular matrices. The column vectors of $\boldsymbol{X}$
+may be linearly dependent, normally referred to as super-collinearity.
+This means that the matrix may be rank deficient and it is basically impossible to
+to model the data using linear regression. As an example, consider the matrix
+
+$$
+\begin{align*}
+\mathbf{X} & = \left[
+\begin{array}{rrr}
+1 & -1 & 2
+\\
+1 & 0 & 1
+\\
+1 & 2 & -1
+\\
+1 & 1 & 0
+\end{array} \right]
+\end{align*}
+$$
+
+The columns of $\boldsymbol{X}$ are linearly dependent. We see this easily since the
+the first column is the row-wise sum of the other two columns. The rank (more correct,
+the column rank) of a matrix is the dimension of the space spanned by the
+column vectors. Hence, the rank of $\mathbf{X}$ is equal to the number
+of linearly independent columns. In this particular case the matrix has rank 2.
+
+Super-collinearity of an $(n \times p)$-dimensional design matrix $\mathbf{X}$ implies
+that the inverse of the matrix $\boldsymbol{X}^T\boldsymbol{X}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this
+
+$$
+\begin{align*}
+\boldsymbol{X} & = \left[
+\begin{array}{rr}
+1 & -1
+\\
+1 & -1
+\end{array} \right].
+\end{align*}
+$$
+
+We see easily that $\mbox{det}(\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0$. Hence, $\mathbf{X}$ is singular and its inverse is undefined.
+This is equivalent to saying that the matrix $\boldsymbol{X}$ has at least an eigenvalue which is zero.
+
+
+
+If our design matrix $\boldsymbol{X}$ which enters the linear regression problem
+
+
+
+
+$$
+\begin{equation}
+\boldsymbol{\beta} = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y},
+\label{_auto1} \tag{1}
+\end{equation}
+$$
+
+has linearly dependent column vectors, we will not be able to compute the inverse
+of $\boldsymbol{X}^T\boldsymbol{X}$ and we cannot find the parameters (estimators) $\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.
+
+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.
+
+
+
+
+## Basic math of the SVD
+
+
+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](https://en.wikipedia.org/wiki/Normal_matrix), that is if $\boldsymbol{X}\in {\mathbb{R}}^{n\times n}$
+we have $\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X}$ or if $\boldsymbol{X}\in {\mathbb{C}}^{n\times n}$ we have $\boldsymbol{X}\boldsymbol{X}^{\dagger}=\boldsymbol{X}^{\dagger}\boldsymbol{X}$.
+The matrix has then a set of eigenpairs
+
+$$
+(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n),
+$$
+
+and the eigenvalues are given by the diagonal matrix
+
+$$
+\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n).
+$$
+
+The matrix $\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\boldsymbol{U}$
+
+$$
+\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,
+$$
+
+with $\boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I}$ or $\boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I}$.
+
+Not all square matrices are diagonalizable. A matrix like the one discussed above
+
+$$
+\boldsymbol{X} = \begin{bmatrix}
+1& -1 \\
+1& -1\\
+\end{bmatrix}
+$$
+
+is not diagonalizable, it is a so-called [defective matrix](https://en.wikipedia.org/wiki/Defective_matrix). It is easy to see that the condition
+$\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X}$ is not fulfilled.
+
+
+
+
+
+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](https://en.wikipedia.org/wiki/Singular_value_decomposition)
+states that a general $m\times n$ matrix $\boldsymbol{X}$ can be written in
+terms of a diagonal matrix $\boldsymbol{\Sigma}$ of dimensionality $m\times n$
+and two orthognal matrices $\boldsymbol{U}$ and $\boldsymbol{V}$, where the first has
+dimensionality $m \times m$ and the last dimensionality $n\times n$.
+We have then
+
+$$
+\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T
+$$
+
+As an example, the above defective matrix can be decomposed as
+
+$$
+\boldsymbol{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,
+$$
+
+with eigenvalues $\sigma_1=2$ and $\sigma_2=0$.
+The SVD exits always!
+
+The SVD
+decomposition (singular values) gives eigenvalues
+$\sigma_i\geq\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=p$, the
+eigenvalues (singular values) are zero.
+
+In the general case, where our design matrix $\boldsymbol{X}$ has dimension
+$n\times p$, the matrix is thus decomposed into an $n\times n$
+orthogonal matrix $\boldsymbol{U}$, a $p\times p$ orthogonal matrix $\boldsymbol{V}$
+and a diagonal matrix $\boldsymbol{\Sigma}$ with $r=\mathrm{min}(n,p)$
+singular values $\sigma_i\geq 0$ on the main diagonal and zeros filling
+the rest of the matrix. There are at most $p$ singular values
+assuming that $n > p$. In our regression examples for the nuclear
+masses and the equation of state this is indeed the case, while for
+the Ising model we have $p > n$. These are often cases that lead to
+near singular or singular matrices.
+
+The columns of $\boldsymbol{U}$ are called the left singular vectors while the columns of $\boldsymbol{V}$ are the right singular vectors.
+
+
+If we assume that $n > p$, then our matrix $\boldsymbol{U}$ has dimension $n
+\times n$. The last $n-p$ columns of $\boldsymbol{U}$ become however
+irrelevant in our calculations since they are multiplied with the
+zeros in $\boldsymbol{\Sigma}$.
+
+The economy-size decomposition removes extra rows or columns of zeros
+from the diagonal matrix of singular values, $\boldsymbol{\Sigma}$, along with the columns
+in either $\boldsymbol{U}$ or $\boldsymbol{V}$ that multiply those zeros in the expression.
+Removing these zeros and columns can improve execution time
+and reduce storage requirements without compromising the accuracy of
+the decomposition.
+
+If $n > p$, we keep only the first $p$ columns of $\boldsymbol{U}$ and $\boldsymbol{\Sigma}$ has dimension $p\times p$.
+If $p > n$, then only the first $n$ columns of $\boldsymbol{V}$ are computed and $\boldsymbol{\Sigma}$ has dimension $n\times n$.
+The $n=p$ case is obvious, we retain the full SVD.
+In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.
+
+## Codes for the SVD
+
+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.
+
+
+
+The $U$, $S$, and $V$ matrices returned from the **svd()** function
+cannot be multiplied directly.
+
+As you can see from the code, the $S$ vector must be converted into a
+diagonal matrix. This may cause a problem as the size of the matrices
+do not fit the rules of matrix multiplication, where the number of
+columns in a matrix must match the number of rows in the subsequent
+matrix.
+
+If you wish to include the zero singular values, you will need to
+resize the matrices and set up a diagonal matrix as done in the above
+example
+
+
+
+
+
+## Mathematics of the SVD and implications
+
+Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies.
+
+Our starting point is our design matrix $\boldsymbol{X}$ of dimension $n\times p$
+
+$$
+\boldsymbol{X}=\begin{bmatrix}
+x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\
+x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\
+x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\
+\dots & \dots & \dots & \dots \dots & \dots \\
+x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\
+x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\
+\end{bmatrix}.
+$$
+
+We can SVD decompose our matrix as
+
+$$
+\boldsymbol{X}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,
+$$
+
+where $\boldsymbol{U}$ is an orthogonal matrix of dimension $n\times n$, meaning that $\boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{U}^T\boldsymbol{U}=\boldsymbol{I}_n$. Here $\boldsymbol{I}_n$ is the unit matrix of dimension $n \times n$.
+
+Similarly, $\boldsymbol{V}$ is an orthogonal matrix of dimension $p\times p$, meaning that $\boldsymbol{V}\boldsymbol{V}^T=\boldsymbol{V}^T\boldsymbol{V}=\boldsymbol{I}_p$. Here $\boldsymbol{I}_n$ is the unit matrix of dimension $p \times p$.
+
+Finally $\boldsymbol{\Sigma}$ contains the singular values $\sigma_i$. This matrix has dimension $n\times p$ and the singular values $\sigma_i$ are all positive. The non-zero values are ordered in descending order, that is
+
+$$
+\sigma_0 > \sigma_1 > \sigma_2 > \dots > \sigma_{p-1} > 0.
+$$
+
+All values beyond $p-1$ are all zero.
+
+
+As an example, consider the following $3\times 2$ example for the matrix $\boldsymbol{\Sigma}$
+
+$$
+\boldsymbol{\Sigma}=
+\begin{bmatrix}
+2& 0 \\
+0 & 1 \\
+0 & 0 \\
+\end{bmatrix}
+$$
+
+The singular values are $\sigma_0=2$ and $\sigma_1=1$. It is common to rewrite the matrix $\boldsymbol{\Sigma}$ as
+
+$$
+\boldsymbol{\Sigma}=
+\begin{bmatrix}
+\boldsymbol{\tilde{\Sigma}}\\
+\boldsymbol{0}\\
+\end{bmatrix},
+$$
+
+where
+
+$$
+\boldsymbol{\tilde{\Sigma}}=
+\begin{bmatrix}
+2& 0 \\
+0 & 1 \\
+\end{bmatrix},
+$$
+
+contains only the singular values. Note also (and we will use this below) that
+
+$$
+\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}=
+\begin{bmatrix}
+4& 0 \\
+0 & 1 \\
+\end{bmatrix},
+$$
+
+which is a $2\times 2 $ matrix while
+
+$$
+\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T=
+\begin{bmatrix}
+4& 0 & 0\\
+0 & 1 & 0\\
+0 & 0 & 0\\
+\end{bmatrix},
+$$
+
+is a $3\times 3 $ matrix. The last row and column of this last matrix
+contain only zeros. This will have important consequences for our SVD
+decomposition of the design matrix.
+
+
+
+The matrix that may cause problems for us is $\boldsymbol{X}^T\boldsymbol{X}$. Using the SVD we can rewrite this matrix as
+
+$$
+\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,
+$$
+
+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$.
+
+This means, using the orthogonality of $\boldsymbol{V}$, that we get
+
+$$
+\boldsymbol{X}^T\boldsymbol{X}=\tilde{\boldsymbol{\Sigma}}^2.
+$$
+
+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\tilde{\boldsymbol{\Sigma}}^{-2}\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{y},
+$$
+
+which gives us, using the orthogonality of the matrices $\boldsymbol{U}$ and $\boldsymbol{V}$,
+
+$$
+\tilde{y}_{\mathrm{OLS}}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_i\boldsymbol{u}^T_j\boldsymbol{y},
+$$
+
+Note here that when we perform the multiplication of the various matrices, the orthogonal vectors of the matrix $\boldsymbol{U}$
+
+$$
+\boldsymbol{U}=[\boldsymbol{u}_0,\boldsymbol{u}_1,\dots,\boldsymbol{u}_{n-1}],
+$$
+
+that belong to $i>p-1$, result in only zeros when we perform the multiplications. This means that the sum above has non-zero elements only up to $i=p-1$. This corresponds also to the number of singular values (these are all non-zero).
+
+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}$.
+
+
+## Further properties (important for our analyses later)
+
+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).
+
+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.
+
+
+## Meet the Covariance Matrix
+
+
+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
+
+$$
+\frac{\partial^2 C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}^T\partial \boldsymbol{\beta}} =\frac{2}{n}\boldsymbol{X}^T\boldsymbol{X}.
+$$
+
+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.
+
+
+
+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.
+
+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](https://mathworld.wolfram.com/BesselsCorrection.html). 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 calculate the covariance, this
+quantity will be computed with a factor $1/(n-1)$.
+
+
+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
+
+$$
+\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 \\
+ \end{bmatrix},
+$$
+
+In the above example this is the function we constructed using **pandas**.
+
+
+
+In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**
+we defined the design/feature matrix $\boldsymbol{X}$ 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{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix},
+$$
+
+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$
+
+$$
+\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 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.
+
+# 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)
+
+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)
+
+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.
+
+The above procedure with **numpy** can be made more compact if we use **pandas**.
+
+
+
+We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code
+
+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)
+
+We expand this model to the Franke function discussed earlier.
+
+# 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 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.
+
+
+
+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}].
+$$
+
+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}.
+$$
+
+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}$.
+
+
+
+## Linking with the SVD
+
+We saw earlier that
+
+$$
+\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T.
+$$
+
+Since the matrices here have dimension $p\times p$, with $p$ corresponding to the singular values, we defined earlier the matrix
+
+$$
+\boldsymbol{\Sigma}^T\boldsymbol{\Sigma} = \begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \\ \boldsymbol{0}\\ \end{bmatrix},
+$$
+
+where the tilde-matrix $\tilde{\boldsymbol{\Sigma}}$ is a matrix of dimension $p\times p$ containing only the singular values $\sigma_i$, that is
+
+$$
+\tilde{\boldsymbol{\Sigma}}=\begin{bmatrix} \sigma_0 & 0 & 0 & \dots & 0 & 0 \\
+ 0 & \sigma_1 & 0 & \dots & 0 & 0 \\
+ 0 & 0 & \sigma_2 & \dots & 0 & 0 \\
+ 0 & 0 & 0 & \dots & \sigma_{p-2} & 0 \\
+ 0 & 0 & 0 & \dots & 0 & \sigma_{p-1} \\
+\end{bmatrix},
+$$
+
+meaning we can write
+
+$$
+\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2\boldsymbol{V}^T.
+$$
+
+Multiplying from the right with $\boldsymbol{V}$ (using the orthogonality of $\boldsymbol{V}$) we get
+
+$$
+\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{V}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2.
+$$
+
+This means the vectors $\boldsymbol{v}_i$ of the orthogonal matrix $\boldsymbol{V}$
+are the eigenvectors of the matrix $\boldsymbol{X}^T\boldsymbol{X}$ with eigenvalues
+given by the singular values squared, that is
+
+$$
+\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{v}_i=\boldsymbol{v}_i\sigma_i^2.
+$$
+
+In other words, each non-zero singular value of $\boldsymbol{X}$ is a positive
+square root of an eigenvalue of $\boldsymbol{X}^T\boldsymbol{X}$. It means also that
+the columns of $\boldsymbol{V}$ are the eigenvectors of
+$\boldsymbol{X}^T\boldsymbol{X}$. Since we have ordered the singular values of
+$\boldsymbol{X}$ in a descending order, it means that the column vectors
+$\boldsymbol{v}_i$ are hierarchically ordered by how much correlation they
+encode from the columns of $\boldsymbol{X}$.
+
+
+Note that these are also the eigenvectors and eigenvalues of the
+Hessian matrix.
+
+If we now recall the definition of the covariance matrix (not using
+Bessel's correction) we have
+
+$$
+\boldsymbol{C}[\boldsymbol{X}]=\frac{1}{n}\boldsymbol{X}^T\boldsymbol{X},
+$$
+
+meaning that every squared non-singular value of $\boldsymbol{X}$ divided by $n$ (
+the number of samples) are the eigenvalues of the covariance
+matrix. Every singular value of $\boldsymbol{X}$ is thus a positive square
+root of an eigenvalue of $\boldsymbol{X}^T\boldsymbol{X}$. If the matrix $\boldsymbol{X}$ is
+self-adjoint, the singular values of $\boldsymbol{X}$ are equal to the
+absolute value of the eigenvalues of $\boldsymbol{X}$.
+
+
+For $\boldsymbol{X}\boldsymbol{X}^T$ we found
+
+$$
+\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T=\boldsymbol{U}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{U}^T.
+$$
+
+Since the matrices here have dimension $n\times n$, we have
+
+$$
+\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T = \begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \\ \boldsymbol{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \boldsymbol{0}\\ \end{bmatrix}=\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix},
+$$
+
+leading to
+
+$$
+\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{U}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}\boldsymbol{U}^T.
+$$
+
+Multiplying with $\boldsymbol{U}$ from the right gives us the eigenvalue problem
+
+$$
+(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U}=\boldsymbol{U}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}.
+$$
+
+It means that the eigenvalues of $\boldsymbol{X}\boldsymbol{X}^T$ are again given by
+the non-zero singular values plus now a series of zeros. The column
+vectors of $\boldsymbol{U}$ are the eigenvectors of $\boldsymbol{X}\boldsymbol{X}^T$ and
+measure how much correlations are contained in the rows of $\boldsymbol{X}$.
+
+Since we will mainly be interested in the correlations among the features
+of our data (the columns of $\boldsymbol{X}$, the quantity of interest for us are the non-zero singular
+values and the column vectors of $\boldsymbol{V}$.
+
+
+
+## Ridge and LASSO Regression
+
+Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is
+our optimization problem is
+
+$$
+{\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}.
+$$
+
+or we can state it as
+
+$$
+{\displaystyle \min_{\boldsymbol{\beta}\in
+{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2,
+$$
+
+where we have used the definition of a norm-2 vector, that is
+
+$$
+\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.
+$$
+
+By minimizing the above equation with respect to the parameters
+$\boldsymbol{\beta}$ we could then obtain an analytical expression for the
+parameters $\boldsymbol{\beta}$. We can add a regularization parameter $\lambda$ by
+defining a new cost function to be optimized, that is
+
+$$
+{\displaystyle \min_{\boldsymbol{\beta}\in
+{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2
+$$
+
+which leads to the Ridge regression minimization problem where we
+require that $\vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t$, where $t$ is
+a finite number larger than zero. By defining
+
+$$
+C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1,
+$$
+
+we have a new optimization equation
+
+$$
+{\displaystyle \min_{\boldsymbol{\beta}\in
+{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1
+$$
+
+which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.
+
+Here we have defined the norm-1 as
+
+$$
+\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert.
+$$
+
+Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have
+
+$$
+C(\boldsymbol{X},\boldsymbol{\beta})=\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta},
+$$
+
+and
+taking the derivatives with respect to $\boldsymbol{\beta}$ we obtain then
+a slightly modified matrix inversion problem which for finite values
+of $\lambda$ does not suffer from singularity problems. We obtain
+the optimal parameters
+
+$$
+\hat{\boldsymbol{\beta}}_{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
+$$
+
+with $\boldsymbol{I}$ being a $p\times p$ identity matrix with the constraint that
+
+$$
+\sum_{i=0}^{p-1} \beta_i^2 \leq t,
+$$
+
+with $t$ a finite positive number.
+
+When we compare this with the ordinary least squares result we have
+
+$$
+\hat{\boldsymbol{\beta}}_{\mathrm{OLS}} = \left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
+$$
+
+which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\boldsymbol{X}^T\boldsymbol{X}$.
+
+
+We see that Ridge regression is nothing but the standard OLS with a
+modified diagonal term added to $\boldsymbol{X}^T\boldsymbol{X}$. The consequences, in
+particular for our discussion of the bias-variance tradeoff are rather
+interesting. We will see that for specific values of $\lambda$, we may
+even reduce the variance of the optimal parameters $\boldsymbol{\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.
+
+Using our insights about the SVD of the design matrix $\boldsymbol{X}$
+We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\boldsymbol{U}$ as
+
+$$
+\tilde{\boldsymbol{y}}_{\mathrm{OLS}}=\boldsymbol{X}\boldsymbol{\beta} =\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}.
+$$
+
+For Ridge regression this becomes
+
+$$
+\tilde{\boldsymbol{y}}_{\mathrm{Ridge}}=\boldsymbol{X}\boldsymbol{\beta}_{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{\Sigma}^2\boldsymbol{V}^T+\lambda\boldsymbol{I} \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\sum_{j=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{y},
+$$
+
+with the vectors $\boldsymbol{u}_j$ being the columns of $\boldsymbol{U}$ from the SVD of the matrix $\boldsymbol{X}$.
+
+
+Since $\lambda \geq 0$, it means that compared to OLS, we have
+
+$$
+\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1.
+$$
+
+Ridge regression finds the coordinates of $\boldsymbol{y}$ with respect to the
+orthonormal basis $\boldsymbol{U}$, it then shrinks the coordinates by
+$\frac{\sigma_j^2}{\sigma_j^2+\lambda}$. Recall that the SVD has
+eigenvalues ordered in a descending way, that is $\sigma_i \geq
+\sigma_{i+1}$.
+
+For small eigenvalues $\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.
+
+
+
+For the sake of simplicity, let us assume that the design matrix is orthonormal, that is
+
+$$
+\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}.
+$$
+
+In this case the standard OLS results in
+
+$$
+\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\boldsymbol{y},
+$$
+
+and
+
+$$
+\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{I}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\left(1+\lambda\right)^{-1}\boldsymbol{\beta}^{\mathrm{OLS}},
+$$
+
+that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\lambda$, and
+the Ridge estimator converges to zero when the hyperparameter goes to
+infinity.
+
+We will come back to more interpreations after we have gone through some of the statistical analysis part.
+
+For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.
+Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.
+
+
+Using the matrix-vector expression for Lasso regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have the following **cost** function
+
+$$
+C(\boldsymbol{X},\boldsymbol{\beta})=\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1,
+$$
+
+Taking the derivative with respect to $\boldsymbol{\beta}$ and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)
+
+$$
+\frac{d \vert \beta\vert}{d \boldsymbol{\beta}}=\mathrm{sgn}(\boldsymbol{\beta})=\left\{\begin{array}{cc} 1 & \beta > 0 \\ 0 & \beta =0\\-1 & \beta < 0, \end{array}\right.
+$$
+
+we have that the derivative of the cost function is
+
+$$
+\frac{\partial C(\boldsymbol{X},\boldsymbol{\beta})}{\partial \boldsymbol{\beta}}=-2\boldsymbol{X}^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})+\lambda sgn(\boldsymbol{\beta})=0,
+$$
+
+and reordering we have
+
+$$
+\boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta})+\lambda sgn(\boldsymbol{\beta})=2\boldsymbol{X}^T(\boldsymbol{y}.
+$$
+
+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](https://cvxopt.org/). We will discuss this later.
+
+## Code for SVD and Inversion of Matrices
+
+How do we use the SVD to invert a matrix $\boldsymbol{X}^\boldsymbol{X}$ which is singular or near singular?
+The simple answer is to use the linear algebra function for pseudoinvers, that is
+
+Ainv = np.linlag.pinv(A)
+
+Let us first look at a matrix which does not causes problems and write our own function where we just use the SVD.
+
+import numpy as np
+# SVD inversion
+def SVDinv(A):
+ ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).
+ SVD is numerically more stable than the inversion algorithms provided by
+ numpy and scipy.linalg at the cost of being slower.
+ '''
+ U, s, VT = np.linalg.svd(A)
+ print('test U')
+ print( (np.transpose(U) @ U - U @np.transpose(U)))
+ print('test VT')
+ print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))
+
+
+ D = np.zeros((len(U),len(VT)))
+ D = np.diag(s)
+ UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)
+ return np.matmul(V,np.matmul(invD,UT))
+
+
+#X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])
+# Non-singular square matrix
+X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])
+print(X)
+A = np.transpose(X) @ X
+# Brute force inversion
+B = np.linalg.inv(A) # here we could use np.linalg.pinv(A)
+C = SVDinv(A)
+print(np.abs(B-C))
+
+Although our matrix to invert $\boldsymbol{X}^T\boldsymbol{X}$ is a square matrix, our matrix may be singular.
+
+The pseudoinverse is the generalization of the matrix inverse for square matrices to
+rectangular matrices where the number of rows and columns are not equal.
+
+It is also called the the Moore-Penrose Inverse after two independent discoverers of the method or the Generalized Inverse.
+It is used for the calculation of the inverse for singular or near singular matrices and for rectangular matrices.
+
+Using the SVD we can obtain the pseudoinverse of a matrix $\boldsymbol{A}$ (labeled here as $\boldsymbol{A}_{\mathrm{PI}}$
+
+$$
+\boldsymbol{A}_{\mathrm{PI}}= \boldsymbol{V}\boldsymbol{D}_{\mathrm{PI}}\boldsymbol{U}^T,
+$$
+
+where $\boldsymbol{D}_{\mathrm{PI}}$ can be calculated by creating a diagonal matrix from $\boldsymbol{Sigma}$ where we only keep the singular values (the non-zero values). The following code computes the pseudoinvers of the matrix based on the SVD.
+
+import numpy as np
+# SVD inversion
+def SVDinv(A):
+ U, s, VT = np.linalg.svd(A)
+ # reciprocals of singular values of s
+ d = 1.0 / s
+ # create m x n D matrix
+ D = np.zeros(A.shape)
+ # populate D with n x n diagonal matrix
+ D[:A.shape[1], :A.shape[1]] = np.diag(d)
+ UT = np.transpose(U)
+ V = np.transpose(VT)
+ return np.matmul(V,np.matmul(D.T,UT))
+
+
+A = np.array([ [0.3, 0.4], [0.5, 0.6], [0.7, 0.8],[0.9, 1.0]])
+print(A)
+# Brute force inversion of super-collinear matrix
+B = np.linalg.pinv(A)
+print(B)
+# Compare our own algorithm with pinv
+C = SVDinv(A)
+print(np.abs(C-B))
+
+As you can see from this example, our own decomposition based on the SVD agrees the pseudoinverse algorithm provided by **Numpy**.
+
+
+
+## Deriving the Ridge Regression Equations
+
+Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is
+our optimization problem is
+
+$$
+{\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}.
+$$
+
+or we can state it as
+
+$$
+{\displaystyle \min_{\boldsymbol{\beta}\in
+{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2,
+$$
+
+where we have used the definition of a norm-2 vector, that is
+
+$$
+\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.
+$$
+
+By minimizing the above equation with respect to the parameters
+$\boldsymbol{\beta}$ we could then obtain an analytical expression for the
+parameters $\boldsymbol{\beta}$. We can add a regularization parameter $\lambda$ by
+defining a new cost function to be optimized, that is
+
+$$
+{\displaystyle \min_{\boldsymbol{\beta}\in
+{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2
+$$
+
+which leads to the Ridge regression minimization problem where we
+require that $\vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t$, where $t$ is
+a finite number larger than zero. By defining
+
+$$
+C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1,
+$$
+
+we have a new optimization equation
+
+$$
+{\displaystyle \min_{\boldsymbol{\beta}\in
+{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1
+$$
+
+which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.
+
+Here we have defined the norm-1 as
+
+$$
+\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert.
+$$
+
+Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have
+
+$$
+C(\boldsymbol{X},\boldsymbol{\beta})=\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta},
+$$
+
+and
+taking the derivatives with respect to $\boldsymbol{\beta}$ we obtain then
+a slightly modified matrix inversion problem which for finite values
+of $\lambda$ does not suffer from singularity problems. We obtain
+the optimal parameters
+
+$$
+\hat{\boldsymbol{\beta}}_{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
+$$
+
+with $\boldsymbol{I}$ being a $p\times p$ identity matrix with the constraint that
+
+$$
+\sum_{i=0}^{p-1} \beta_i^2 \leq t,
+$$
+
+with $t$ a finite positive number.
+
+When we compare this with the ordinary least squares result we have
+
+$$
+\hat{\boldsymbol{\beta}}_{\mathrm{OLS}} = \left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
+$$
+
+which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\boldsymbol{X}^T\boldsymbol{X}$.
+
+
+We see that Ridge regression is nothing but the standard OLS with a
+modified diagonal term added to $\boldsymbol{X}^T\boldsymbol{X}$. The consequences, in
+particular for our discussion of the bias-variance tradeoff are rather
+interesting. We will see that for specific values of $\lambda$, we may
+even reduce the variance of the optimal parameters $\boldsymbol{\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.
+
+
+
+Using our insights about the SVD of the design matrix $\boldsymbol{X}$
+We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\boldsymbol{U}$ as
+
+$$
+\tilde{\boldsymbol{y}}_{\mathrm{OLS}}=\boldsymbol{X}\boldsymbol{\beta} =\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}.
+$$
+
+For Ridge regression this becomes
+
+$$
+\tilde{\boldsymbol{y}}_{\mathrm{Ridge}}=\boldsymbol{X}\boldsymbol{\beta}_{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{\Sigma}^2\boldsymbol{V}^T+\lambda\boldsymbol{I} \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\sum_{j=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{y},
+$$
+
+with the vectors $\boldsymbol{u}_j$ being the columns of $\boldsymbol{U}$ from the SVD of the matrix $\boldsymbol{X}$.
+
+
+
+Since $\lambda \geq 0$, it means that compared to OLS, we have
+
+$$
+\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1.
+$$
+
+Ridge regression finds the coordinates of $\boldsymbol{y}$ with respect to the
+orthonormal basis $\boldsymbol{U}$, it then shrinks the coordinates by
+$\frac{\sigma_j^2}{\sigma_j^2+\lambda}$. Recall that the SVD has
+eigenvalues ordered in a descending way, that is $\sigma_i \geq
+\sigma_{i+1}$.
+
+For small eigenvalues $\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.
+
+
+
+For the sake of simplicity, let us assume that the design matrix is orthonormal, that is
+
+$$
+\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}.
+$$
+
+In this case the standard OLS results in
+
+$$
+\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\boldsymbol{y},
+$$
+
+and
+
+$$
+\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{I}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\left(1+\lambda\right)^{-1}\boldsymbol{\beta}^{\mathrm{OLS}},
+$$
+
+that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\lambda$, and
+the Ridge estimator converges to zero when the hyperparameter goes to
+infinity.
+
+We will come back to more interpreations after we have gone through some of the statistical analysis part.
+
+
+
+Using the matrix-vector expression for Lasso regression and dropping the parameter $1/n$ in front of the standard mean squared error equation, we have the following **cost** function
+
+$$
+C(\boldsymbol{X},\boldsymbol{\beta})=\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1,
+$$
+
+Taking the derivative with respect to $\boldsymbol{\beta}$ and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)
+
+$$
+\frac{d \vert \beta\vert}{d \boldsymbol{\beta}}=\mathrm{sgn}(\boldsymbol{\beta})=\left\{\begin{array}{cc} 1 & \beta > 0 \\ 0 & \beta =0\\-1 & \beta < 0, \end{array}\right.
+$$
+
+we have that the derivative of the cost function is
+
+$$
+\frac{\partial C(\boldsymbol{X},\boldsymbol{\beta})}{\partial \boldsymbol{\beta}}=-2\boldsymbol{X}^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})+\lambda sgn(\boldsymbol{\beta})=0,
+$$
+
+and reordering we have
+
+$$
+\boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}+\lambda sgn(\boldsymbol{\beta})=2\boldsymbol{X}^T\boldsymbol{y}.
+$$
+
+This equation does not lead to a nice analytical equation as in 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](https://cvxopt.org/). We will discuss this later.
+
+
+
+
+
+Let us assume that our design matrix is given by unit (identity) matrix, that is a square diagonal matrix with ones only along the
+diagonal. In this case we have an equal number of rows and columns $n=p$.
+
+Our model approximation is just $\tilde{\boldsymbol{y}}=\boldsymbol{\beta}$ and the mean squared error and thereby the cost function for ordinary least sqquares (OLS) is then (we drop the term $1/n$)
+
+$$
+C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2,
+$$
+
+and minimizing we have that
+
+$$
+\hat{\beta}_i^{\mathrm{OLS}} = y_i.
+$$
+
+For Ridge regression our cost function is
+
+$$
+C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\beta_i^2,
+$$
+
+and minimizing we have that
+
+$$
+\hat{\beta}_i^{\mathrm{Ridge}} = \frac{y_i}{1+\lambda}.
+$$
+
+For Lasso regression our cost function is
+
+$$
+C(\boldsymbol{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\vert\beta_i\vert=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\sqrt{\beta_i^2},
+$$
+
+and minimizing we have that
+
+$$
+-2\sum_{i=0}^{p-1}(y_i-\beta_i)+\lambda \sum_{i=0}^{p-1}\frac{(\beta_i)}{\vert\beta_i\vert}=0,
+$$
+
+which leads to
+
+$$
+\hat{\boldsymbol{\beta}}_i^{\mathrm{Lasso}} = \left\{\begin{array}{ccc}y_i-\frac{\lambda}{2} &\mathrm{if} & y_i> \frac{\lambda}{2}\\
+ y_i+\frac{\lambda}{2} &\mathrm{if} & y_i< -\frac{\lambda}{2}\\
+ 0 &\mathrm{if} & \vert y_i\vert\le \frac{\lambda}{2}\end{array}\right.\\.
+$$
+
+Plotting these results ([figure in handwritten notes for week 36](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2021/NotesSeptember9.pdf)) shows clearly that Lasso regression suppresses (sets to zero) values of $\beta_i$ for specific values of $\lambda$. Ridge regression reduces on the other hand the values of $\beta_i$ as function of $\lambda$.
+
+
+As another examples,
+let us assume we have a data set with outputs/targets given by the vector
+
+$$
+\boldsymbol{y}=\begin{bmatrix}4 \\ 2 \\3\end{bmatrix},
+$$
+
+and our inputs as a $3\times 2$ design matrix
+
+$$
+\boldsymbol{X}=\begin{bmatrix}2 & 0\\ 0 & 1 \\ 0 & 0\end{bmatrix},
+$$
+
+meaning that we have two features and two unknown parameters $\beta_0$ and $\beta_1$ to be determined either by ordinary least squares, Ridge or Lasso regression.
+
+
+For ordinary least squares (OLS) we know that the optimal solution is
+
+$$
+\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left( \boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
+$$
+
+Inserting the above values we obtain that
+
+$$
+\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\begin{bmatrix}2 \\ 2\end{bmatrix},
+$$
+
+The code which implements this simpler case is presented after the discussion of Ridge and Lasso.
+
+
+For Ridge regression we have
+
+$$
+\hat{\boldsymbol{\beta}}^{\mathrm{Ridge}}=\left( \boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
+$$
+
+Inserting the above values we obtain that
+
+$$
+\hat{\boldsymbol{\beta}}^{\mathrm{Ridge}}=\begin{bmatrix}\frac{8}{4+\lambda} \\ \frac{2}{1+\lambda}\end{bmatrix},
+$$
+
+There is normally a constraint on the value of $\vert\vert \boldsymbol{\beta}\vert\vert_2$ via the parameter $\lambda$.
+Let us for simplicity assume that $\beta_0^2+\beta_1^2=1$ as constraint. This will allow us to find an expression for the optimal values of $\beta$ and $\lambda$.
+
+To see this, let us write the cost function for Ridge regression.
+
+
+
+We define the MSE without the $1/n$ factor and have then, using that
+
+$$
+\boldsymbol{X}\boldsymbol{\beta}=\begin{bmatrix} 2\beta_0 \\ \beta_1 \\0 \end{bmatrix},
+$$
+
+$$
+C(\boldsymbol{\beta})=(4-2\beta_0)^2+(2-\beta_1)^2+\lambda(\beta_0^2+\beta_1^2),
+$$
+
+and taking the derivative with respect to $\beta_0$ we get
+
+$$
+\beta_0=\frac{8}{4+\lambda},
+$$
+
+and for $\beta_1$ we obtain
+
+$$
+\beta_1=\frac{2}{1+\lambda},
+$$
+
+Using the constraint for $\beta_0^2+\beta_1^2=1$ we can constrain $\lambda$ by solving
+
+$$
+\left(\frac{8}{4+\lambda}\right)^2+\left(\frac{2}{1+\lambda}\right)^2=1,
+$$
+
+which gives $\lambda=4.571$ and $\beta_0=0.933$ and $\beta_1=0.359$.
+
+
+For Lasso we need now, keeping a constraint on $\vert\beta_0\vert+\vert\beta_1\vert=1$, to take the derivative of the absolute values of $\beta_0$
+and $\beta_1$. This gives us the following derivatives of the cost function
+
+$$
+C(\boldsymbol{\beta})=(4-2\beta_0)^2+(2-\beta_1)^2+\lambda(\vert\beta_0\vert+\vert\beta_1\vert),
+$$
+
+$$
+\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_0}=-4(4-2\beta_0)+\lambda\mathrm{sgn}(\beta_0)=0,
+$$
+
+and
+
+$$
+\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_1}=-2(2-\beta_1)+\lambda\mathrm{sgn}(\beta_1)=0.
+$$
+
+We have now four cases to solve besides the trivial cases $\beta_0$ and/or $\beta_1$ are zero, namely
+1. $\beta_0 > 0$ and $\beta_1 > 0$,
+
+2. $\beta_0 > 0$ and $\beta_1 < 0$,
+
+3. $\beta_0 < 0$ and $\beta_1 > 0$,
+
+4. $\beta_0 < 0$ and $\beta_1 < 0$.
+
+If we consider the first case, we have then
+
+$$
+-4(4-2\beta_0)+\lambda=0,
+$$
+
+and
+
+$$
+-2(2-\beta_1)+\lambda=0.
+$$
+
+which yields
+
+$$
+\beta_0=\frac{16+\lambda}{8},
+$$
+
+and
+
+$$
+\beta_1=\frac{4+\lambda}{2}.
+$$
+
+Using the constraint on $\beta_0$ and $\beta_1$ we can then find the optimal value of $\lambda$ for the different cases. We leave this as an exercise to you.
+
+
+Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of $\lambda$, meaning that we need to perform a search in order to find the optimal values.
+
+First we study and compare the OLS and Ridge results. The next code compares all three methods.
+
+%matplotlib inline
+
+import os
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+
+# A seed just to ensure that the random numbers are the same for every run.
+# Useful for eventual debugging.
+
+X = np.array( [ [ 2, 0], [0, 1], [0,0]])
+y = np.array( [4, 2, 3])
+
+
+# matrix inversion to find beta
+OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y
+print(OLSbeta)
+# and then make the prediction
+ytildeOLS = X @ OLSbeta
+print("Training MSE for OLS")
+print(MSE(y,ytildeOLS))
+ypredictOLS = X @ OLSbeta
+
+# Repeat now for Ridge regression and various values of the regularization parameter
+I = np.eye(2,2)
+# Decide which values of lambda to use
+nlambdas = 100
+MSEPredict = np.zeros(nlambdas)
+lambdas = np.logspace(-4, 4, nlambdas)
+for i in range(nlambdas):
+ lmb = lambdas[i]
+ Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y
+# print(Ridgebeta)
+ # and then make the prediction
+ ypredictRidge = X @ Ridgebeta
+ MSEPredict[i] = MSE(y,ypredictRidge)
+# print(MSEPredict[i])
+ # Now plot the results
+plt.figure()
+plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Train')
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
+
+We see here that we reach a plateau. What is actually happening?
+
+import os
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn import linear_model
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+
+# A seed just to ensure that the random numbers are the same for every run.
+# Useful for eventual debugging.
+
+X = np.array( [ [ 2, 0], [0, 1], [0,0]])
+y = np.array( [4, 2, 3])
+
+
+# matrix inversion to find beta
+OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y
+print(OLSbeta)
+# and then make the prediction
+ytildeOLS = X @ OLSbeta
+print("Training MSE for OLS")
+print(MSE(y,ytildeOLS))
+ypredictOLS = X @ OLSbeta
+
+# Repeat now for Ridge regression and various values of the regularization parameter
+I = np.eye(2,2)
+# Decide which values of lambda to use
+nlambdas = 100
+MSERidgePredict = np.zeros(nlambdas)
+MSELassoPredict = np.zeros(nlambdas)
+lambdas = np.logspace(-4, 4, nlambdas)
+for i in range(nlambdas):
+ lmb = lambdas[i]
+ Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y
+ print(Ridgebeta)
+ # and then make the prediction
+ ypredictRidge = X @ Ridgebeta
+ MSERidgePredict[i] = MSE(y,ypredictRidge)
+ RegLasso = linear_model.Lasso(lmb)
+ RegLasso.fit(X,y)
+ ypredictLasso = RegLasso.predict(X)
+ print(RegLasso.coef_)
+ MSELassoPredict[i] = MSE(y,ypredictLasso)
+# Now plot the results
+plt.figure()
+plt.plot(np.log10(lambdas), MSERidgePredict, 'r--', label = 'MSE Ridge Train')
+plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Train')
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
+
+Another Example, now with a polynomial fit.
+
+import os
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.model_selection import train_test_split
+from sklearn import linear_model
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+
+# A seed just to ensure that the random numbers are the same for every run.
+# Useful for eventual debugging.
+np.random.seed(3155)
+
+x = np.random.rand(100)
+y = 2.0+5*x*x+0.1*np.random.randn(100)
+
+# number of features p (here degree of polynomial
+p = 3
+# The design matrix now as function of a given polynomial
+X = np.zeros((len(x),p))
+X[:,0] = 1.0
+X[:,1] = x
+X[:,2] = x*x
+# We split the data in test and training data
+X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
+
+# matrix inversion to find beta
+OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train
+print(OLSbeta)
+# and then make the prediction
+ytildeOLS = X_train @ OLSbeta
+print("Training MSE for OLS")
+print(MSE(y_train,ytildeOLS))
+ypredictOLS = X_test @ OLSbeta
+print("Test MSE OLS")
+print(MSE(y_test,ypredictOLS))
+
+# Repeat now for Lasso and Ridge regression and various values of the regularization parameter
+I = np.eye(p,p)
+# Decide which values of lambda to use
+nlambdas = 100
+MSEPredict = np.zeros(nlambdas)
+MSETrain = np.zeros(nlambdas)
+MSELassoPredict = np.zeros(nlambdas)
+MSELassoTrain = np.zeros(nlambdas)
+lambdas = np.logspace(-4, 4, nlambdas)
+for i in range(nlambdas):
+ lmb = lambdas[i]
+ Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train
+ # include lasso using Scikit-Learn
+ RegLasso = linear_model.Lasso(lmb)
+ RegLasso.fit(X_train,y_train)
+ # and then make the prediction
+ ytildeRidge = X_train @ Ridgebeta
+ ypredictRidge = X_test @ Ridgebeta
+ ytildeLasso = RegLasso.predict(X_train)
+ ypredictLasso = RegLasso.predict(X_test)
+ MSEPredict[i] = MSE(y_test,ypredictRidge)
+ MSETrain[i] = MSE(y_train,ytildeRidge)
+ MSELassoPredict[i] = MSE(y_test,ypredictLasso)
+ MSELassoTrain[i] = MSE(y_train,ytildeLasso)
+
+# Now plot the results
+plt.figure()
+plt.plot(np.log10(lambdas), MSETrain, label = 'MSE Ridge train')
+plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Test')
+plt.plot(np.log10(lambdas), MSELassoTrain, label = 'MSE Lasso train')
+plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Test')
+
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
+
+## Linking the regression analysis with a statistical interpretation
+
+We will now couple the discussions of ordinary least squares, Ridge
+and Lasso regression with a statistical interpretation, that is we
+move from a linear algebra analysis to a statistical analysis. In
+particular, we will focus on what the regularization terms can result
+in. We will amongst other things show that the regularization
+parameter can reduce considerably the variance of the parameters
+$\beta$.
-* Systematical errors are method specific and must be treated differently from case to case.
The
advantage of doing linear regression is that we actually end up with
@@ -91,6 +1850,7 @@ notation above $\mathbf{X}_{i,\ast}$ means that we are looking at the
row number $i$ and perform a sum over all values $p$.
+
The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off)
that there exists a function $f(\boldsymbol{x})$ and a normal distributed error $\boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2)$
which describe our data
@@ -178,8 +1938,7 @@ where we have used that $\mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) =
\sigma^2 \, \mathbf{I}_{nn}$. From $\mbox{Var}(\boldsymbol{\beta}) = \sigma^2
\, (\mathbf{X}^{T} \mathbf{X})^{-1}$, one obtains an estimate of the
variance of the estimate of the $j$-th regression coefficient:
-$\boldsymbol{\sigma}^2 (\boldsymbol{\beta}_j ) = \boldsymbol{\sigma}^2 \sqrt{
-[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} }$. This may be used to
+$\boldsymbol{\sigma}^2 (\boldsymbol{\beta}_j ) = \boldsymbol{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} $. This may be used to
construct a confidence interval for the estimates.
@@ -216,824 +1975,391 @@ This means the variance we obtain with the standard OLS will always for $\lambda
-## Resampling methods
+## Deriving OLS from a probability distribution
-With all these analytical equations for both the OLS and Ridge
-regression, we will now outline how to assess a given model. This will
-lead us to a discussion of the so-called bias-variance tradeoff (see
-below) and so-called resampling methods.
+Our basic assumption when we derived the OLS equations was to assume
+that our output is determined by a given continuous function
+$f(\boldsymbol{x})$ and a random noise $\boldsymbol{\epsilon}$ given by the normal
+distribution with zero mean value and an undetermined variance
+$\sigma^2$.
-One of the quantities we have discussed as a way to measure errors is
-the mean-squared error (MSE), mainly used for fitting of continuous
-functions. Another choice is the absolute error.
-
-In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,
-we discuss the
-1. prediction error or simply the **test error** $\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the
-
-2. training error $\mathrm{Err_{Train}}$, which is the average loss over the training data.
-
-As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.
-For a certain level of complexity the test error will reach minimum, before starting to increase again. The
-training error reaches a saturation.
-
-
-
-Two famous
-resampling methods are the **independent bootstrap** and **the jackknife**.
-
-The jackknife is a special case of the independent bootstrap. Still, the jackknife was made
-popular prior to the independent bootstrap. And as the popularity of
-the independent bootstrap soared, new variants, such as **the dependent bootstrap**.
-
-The Jackknife and independent bootstrap work for
-independent, identically distributed random variables.
-If these conditions are not
-satisfied, the methods will fail. Yet, it should be said that if the data are
-independent, identically distributed, and we only want to estimate the
-variance of $\overline{X}$ (which often is the case), then there is no
-need for bootstrapping.
-
-
-The Jackknife works by making many replicas of the estimator $\widehat{\theta}$.
-The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\boldsymbol{x} = (x_1,x_2,\cdots,X_n)$.
-Let $\boldsymbol{x}_i$ denote the vector
+We found above that the outputs $\boldsymbol{y}$ have a mean value given by
+$\boldsymbol{X}\hat{\boldsymbol{\beta}}$ and variance $\sigma^2$. Since the entries to
+the design matrix are not stochastic variables, we can assume that the
+probability distribution of our targets is also a normal distribution
+but now with mean value $\boldsymbol{X}\hat{\boldsymbol{\beta}}$. This means that a
+single output $y_i$ is given by the Gaussian distribution
$$
-\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n),
+y_i\sim \mathcal{N}(\boldsymbol{X}_{i,*}\boldsymbol{\beta}, \sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
$$
-which equals the vector $\boldsymbol{x}$ with the exception that observation
-number $i$ is left out. Using this notation, define
-$\widehat{\theta}_i$ to be the estimator
-$\widehat{\theta}$ computed using $\vec{X}_i$.
-
-from numpy import *
-from numpy.random import randint, randn
-from time import time
-
-def jackknife(data, stat):
- n = len(data);t = zeros(n); inds = arange(n); t0 = time()
- ## 'jackknifing' by leaving out an observation for each i
- for i in range(n):
- t[i] = stat(delete(data,i) )
-
- # analysis
- print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :")
- print("original bias std. error")
- print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))
-
- return t
-
-
-# Returns mean of data samples
-def stat(data):
- return mean(data)
-
-
-mu, sigma = 100, 15
-datapoints = 10000
-x = mu + sigma*random.randn(datapoints)
-# jackknife returns the data sample
-t = jackknife(x, stat)
-
-### Bootstrap
-
-Bootstrapping is a nonparametric approach to statistical inference
-that substitutes computation for more traditional distributional
-assumptions and asymptotic results. Bootstrapping offers a number of
-advantages:
-1. The bootstrap is quite general, although there are some cases in which it fails.
-
-2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small.
-
-3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically.
-
-4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).
-
-Since $\widehat{\theta} = \widehat{\theta}(\boldsymbol{X})$ is a function of random variables,
-$\widehat{\theta}$ itself must be a random variable. Thus it has
-a pdf, call this function $p(\boldsymbol{t})$. The aim of the bootstrap is to
-estimate $p(\boldsymbol{t})$ by the relative frequency of
-$\widehat{\theta}$. You can think of this as using a histogram
-in the place of $p(\boldsymbol{t})$. If the relative frequency closely
-resembles $p(\vec{t})$, then using numerics, it is straight forward to
-estimate all the interesting parameters of $p(\boldsymbol{t})$ using point
-estimators.
-
-
-
-In the case that $\widehat{\theta}$ has
-more than one component, and the components are independent, we use the
-same estimator on each component separately. If the probability
-density function of $X_i$, $p(x)$, had been known, then it would have
-been straight forward to do this by:
-1. Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \cdots, X_n^*)$.
-
-2. Then using these numbers, we could compute a replica of $\widehat{\theta}$ called $\widehat{\theta}^*$.
-
-By repeated use of (1) and (2), many
-estimates of $\widehat{\theta}$ could have been obtained. The
-idea is to use the relative frequency of $\widehat{\theta}^*$
-(think of a histogram) as an estimate of $p(\boldsymbol{t})$.
-
-
-But
-unless there is enough information available about the process that
-generated $X_1,X_2,\cdots,X_n$, $p(x)$ is in general
-unknown. Therefore, [Efron in 1979](https://projecteuclid.org/euclid.aos/1176344552) asked the
-question: What if we replace $p(x)$ by the relative frequency
-of the observation $X_i$; if we draw observations in accordance with
-the relative frequency of the observations, will we obtain the same
-result in some asymptotic sense? The answer is yes.
-
-
-Instead of generating the histogram for the relative
-frequency of the observation $X_i$, just draw the values
-$(X_1^*,X_2^*,\cdots,X_n^*)$ with replacement from the vector
-$\boldsymbol{X}$.
-
-
-The independent bootstrap works like this:
-
-1. Draw with replacement $n$ numbers for the observed variables $\boldsymbol{x} = (x_1,x_2,\cdots,x_n)$.
-
-2. Define a vector $\boldsymbol{x}^*$ containing the values which were drawn from $\boldsymbol{x}$.
-
-3. Using the vector $\boldsymbol{x}^*$ compute $\widehat{\theta}^*$ by evaluating $\widehat \theta$ under the observations $\boldsymbol{x}^*$.
-
-4. Repeat this process $k$ times.
-
-When you are done, you can draw a histogram of the relative frequency
-of $\widehat \theta^*$. This is your estimate of the probability
-distribution $p(t)$. Using this probability distribution you can
-estimate any statistics thereof. In principle you never draw the
-histogram of the relative frequency of $\widehat{\theta}^*$. Instead
-you use the estimators corresponding to the statistic of interest. For
-example, if you are interested in estimating the variance of $\widehat
-\theta$, apply the etsimator $\widehat \sigma^2$ to the values
-$\widehat \theta ^*$.
-
-
-
-The following code starts with a Gaussian distribution with mean value
-$\mu =100$ and variance $\sigma=15$. We use this to generate the data
-used in the bootstrap analysis. The bootstrap analysis returns a data
-set after a given number of bootstrap operations (as many as we have
-data points). This data set consists of estimated mean values for each
-bootstrap operation. The histogram generated by the bootstrap method
-shows that the distribution for these mean values is also a Gaussian,
-centered around the mean value $\mu=100$ but with standard deviation
-$\sigma/\sqrt{n}$, where $n$ is the number of bootstrap samples (in
-this case the same as the number of original data points). The value
-of the standard deviation is what we expect from the central limit
-theorem.
-
-%matplotlib inline
-
-from numpy import *
-from numpy.random import randint, randn
-from time import time
-import matplotlib.mlab as mlab
-import matplotlib.pyplot as plt
-
-# Returns mean of bootstrap samples
-def stat(data):
- return mean(data)
-
-# Bootstrap algorithm
-def bootstrap(data, statistic, R):
- t = zeros(R); n = len(data); inds = arange(n); t0 = time()
- # non-parametric bootstrap
- for i in range(R):
- t[i] = statistic(data[randint(0,n,n)])
-
- # analysis
- print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
- print("original bias std. error")
- print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
- return t
-
-
-mu, sigma = 100, 15
-datapoints = 10000
-x = mu + sigma*random.randn(datapoints)
-# bootstrap returns the data sample
-t = bootstrap(x, stat, datapoints)
-# the histogram of the bootstrapped data
-n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
-
-# add a 'best fit' line
-y = mlab.normpdf( binsboot, mean(t), std(t))
-lt = plt.plot(binsboot, y, 'r--', linewidth=1)
-plt.xlabel('Smarts')
-plt.ylabel('Probability')
-plt.axis([99.5, 100.6, 0, 3.0])
-plt.grid(True)
-
-plt.show()
-
-## Various steps in cross-validation
-
-When the repetitive splitting of the data set is done randomly,
-samples may accidently end up in a fast majority of the splits in
-either training or test set. Such samples may have an unbalanced
-influence on either model building or prediction evaluation. To avoid
-this $k$-fold cross-validation structures the data splitting. The
-samples are divided into $k$ more or less equally sized exhaustive and
-mutually exclusive subsets. In turn (at each split) one of these
-subsets plays the role of the test set while the union of the
-remaining subsets constitutes the training set. Such a splitting
-warrants a balanced representation of each sample in both training and
-test set over the splits. Still the division into the $k$ subsets
-involves a degree of randomness. This may be fully excluded when
-choosing $k=n$. This particular case is referred to as leave-one-out
-cross-validation (LOOCV).
-
-
-* Define a range of interest for the penalty parameter.
-
-* Divide the data set into training and test set comprising samples $\{1, \ldots, n\} \setminus i$ and $\{ i \}$, respectively.
-
-* Fit the linear regression model by means of ridge estimation for each $\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\boldsymbol{\sigma}_{-i}^2(\lambda)$, as
+We assume now that the various $y_i$ values are stochastically distributed according to the above Gaussian distribution.
+We define this distribution as
$$
-\begin{align*}
-\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T}
-\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1}
-\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i}
-\end{align*}
+p(y_i, \boldsymbol{X}\vert\boldsymbol{\beta})=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]},
$$
-* Evaluate the prediction performance of these models on the test set by $\log\{L[y_i, \boldsymbol{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}$. Or, by the prediction error $|y_i - \boldsymbol{X}_{i, \ast} \boldsymbol{\beta}_{-i}(\lambda)|$, the relative error, the error squared or the R2 score function.
+which reads as finding the likelihood of an event $y_i$ with the input variables $\boldsymbol{X}$ given the parameters (to be determined) $\boldsymbol{\beta}$.
-* Repeat the first three steps such that each sample plays the role of the test set once.
-
-* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as
+Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event $\boldsymbol{y}$ as the product of the single events, that is we have
$$
-\begin{align*}
-\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}.
-\end{align*}
+p(\boldsymbol{y},\boldsymbol{X}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta}).
$$
-For the various values of $k$
+We will write this in a more compact form reserving $\boldsymbol{D}$ for the domain of events, including the ouputs (targets) and the inputs. That is
+in case we have a simple one-dimensional input and output case
-1. shuffle the dataset randomly.
+$$
+\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})].
+$$
-2. Split the dataset into $k$ groups.
+In the more general case the various inputs should be replaced by the possible features represented by the input data set $\boldsymbol{X}$.
+We can now rewrite the above probability as
-3. For each unique group:
+$$
+p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
+$$
-a. Decide which group to use as set for test data
-
-b. Take the remaining groups as a training data set
-
-c. Fit a model on the training set and evaluate it on the test set
-
-d. Retain the evaluation score and discard the model
+It is a conditional probability (see below) and reads as the likelihood of a domain of events $\boldsymbol{D}$ given a set of parameters $\boldsymbol{\beta}$.
-5. Summarize the model using the sample of model evaluation scores
+In statistics, maximum likelihood estimation (MLE) is a method of
+estimating the parameters of an assumed probability distribution,
+given some observed data. This is achieved by maximizing a likelihood
+function so that, under the assumed statistical model, the observed
+data is the most probable.
-The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial.
+
+We will assume here that our events are given by the above Gaussian
+distribution and we will determine the optimal parameters $\beta$ by
+maximizing the above PDF. However, computing the derivatives of a
+product function is cumbersome and can easily lead to overflow and/or
+underflowproblems, with potentials for loss of numerical precision.
+
+
+In practice, it is more convenient to maximize the logarithm of the
+PDF because it is a monotonically increasing function of the argument.
+Alternatively, and this will be our option, we will minimize the
+negative of the logarithm since this is a monotonically decreasing
+function.
+
+Note also that maximization/minimization of the logarithm of the PDF
+is equivalent to the maximization/minimization of the function itself.
+
+
+
+
+We could now define a new cost function to minimize, namely the negative logarithm of the above PDF
+
+$$
+C(\boldsymbol{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})},
+$$
+
+which becomes
+
+$$
+C(\boldsymbol{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}.
+$$
+
+Taking the derivative of the *new* cost function with respect to the parameters $\beta$ we recognize our familiar OLS equation, namely
+
+$$
+\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right) =0,
+$$
+
+which leads to the well-known OLS equation for the optimal paramters $\beta$
+
+$$
+\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}!
+$$
+
+Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics.
+
+
+A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry.
+Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics.
+
+Assume we have two domains of events $X=[x_0,x_1,\dots,x_{n-1}]$ and $Y=[y_0,y_1,\dots,y_{n-1}]$.
+
+We define also the likelihood for $X$ and $Y$ as $p(X)$ and $p(Y)$ respectively.
+The likelihood of a specific event $x_i$ (or $y_i$) is then written as $p(X=x_i)$ or just $p(x_i)=p_i$.
+
+**Union of events is given by.**
+
+$$
+p(X \cup Y)= p(X)+p(Y)-p(X \cap Y).
+$$
+
+**The product rule (aka joint probability) is given by.**
+
+$$
+p(X \cup Y)= p(X,Y)= p(X\vert Y)p(Y)=p(Y\vert X)p(X),
+$$
+
+where we read $p(X\vert Y)$ as the likelihood of obtaining $X$ given $Y$.
+
+
+
+If we have independent events then $p(X,Y)=p(X)p(Y)$.
+
+
+
+The marginal probability is defined in terms of only one of the set of variables $X,Y$. For a discrete probability we have
+
+$$
+p(X)=\sum_{i=0}^{n-1}p(X,Y=y_i)=\sum_{i=0}^{n-1}p(X\vert Y=y_i)p(Y=y_i)=\sum_{i=0}^{n-1}p(X\vert y_i)p(y_i).
+$$
+
+The conditional probability, if $p(Y) > 0$, is
+
+$$
+p(X\vert Y)= \frac{p(X,Y)}{p(Y)}=\frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}.
+$$
+
+If we combine the conditional probability with the marginal probability and the standard product rule, we have
+
+$$
+p(X\vert Y)= \frac{p(X,Y)}{p(Y)},
+$$
+
+which we can rewrite as
+
+$$
+p(X\vert Y)= \frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}=\frac{p(Y\vert X)p(X)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)},
+$$
+
+which is Bayes' theorem. It allows us to evaluate the uncertainty in in $X$ after we have observed $Y$. We can easily interchange $X$ with $Y$.
+
+
+The quantity $p(Y\vert X)$ on the right-hand side of the theorem is
+evaluated for the observed data $Y$ and can be viewed as a function of
+the parameter space represented by $X$. This function is not
+necesseraly normalized and is normally called the likelihood function.
+
+The function $p(X)$ on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution.
+
+Let us try to illustrate Bayes' theorem through an example.
+
+
+Let us suppose that you are undergoing a series of mammography scans in
+order to rule out possible breast cancer cases. We define the
+sensitivity for a positive event by the variable $X$. It takes binary
+values with $X=1$ representing a positive event and $X=0$ being a
+negative event. We reserve $Y$ as a classification parameter for
+either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing).
+
+We let $Y=1$ represent the the case of having breast cancer and $Y=0$ as not.
+
+Let us assume that if you have breast cancer, the test will be positive with a probability of $0.8$, that is we have
+
+$$
+p(X=1\vert Y=1) =0.8.
+$$
+
+This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of $80\%$ for having cancer.
+It is however not correct, as the following Bayesian analysis shows.
+
+
+If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number.
+Let us assume that the prior probability in the population as a whole is
+
+$$
+p(Y=1) =0.004.
+$$
+
+We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have
+
+$$
+p(X=1\vert Y=0) =0.1.
+$$
+
+Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute
+
+$$
+p(Y=1\vert X=1)=\frac{p(X=1\vert Y=1)p(Y=1)}{p(X=1\vert Y=1)p(Y=1)+p(X=1\vert Y=0)p(Y=0)}=\frac{0.8\times 0.004}{0.8\times 0.004+0.1\times 0.996}=0.031.
+$$
+
+That is, in case of a positive test, there is only a $3\%$ chance of having breast cancer!
+
+
+
+## Bayes' Theorem and Ridge and Lasso Regression
+
+Hitherto we have discussed Ridge and Lasso regression in terms of a
+linear analysis. This may to many of you feel rather technical and
+perhaps not that intuitive. The question is whether we can develop a
+more intuitive way of understanding what Ridge and Lasso express.
+
+Before we proceed let us perform a Ridge, Lasso and OLS analysis of a polynomial fit.
+
+
+We will play around with a study of the values for the optimal
+parameters $\boldsymbol{\beta}$ using OLS, Ridge and Lasso regression. For
+OLS, you will notice as function of the noise and polynomial degree,
+that the parameters $\beta$ will fluctuate from order to order in the
+polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS.
+
+For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one.
import numpy as np
import matplotlib.pyplot as plt
-from sklearn.model_selection import KFold
-from sklearn.linear_model import Ridge
-from sklearn.model_selection import cross_val_score
-from sklearn.preprocessing import PolynomialFeatures
-
-# A seed just to ensure that the random numbers are the same for every run.
-# Useful for eventual debugging.
-np.random.seed(3155)
-
-# Generate the data.
-nsamples = 100
-x = np.random.randn(nsamples)
-y = 3*x**2 + np.random.randn(nsamples)
-
-## Cross-validation on Ridge regression using KFold only
-
-# Decide degree on polynomial to fit
-poly = PolynomialFeatures(degree = 6)
-
-# Decide which values of lambda to use
-nlambdas = 500
-lambdas = np.logspace(-3, 5, nlambdas)
-
-# Initialize a KFold instance
-k = 5
-kfold = KFold(n_splits = k)
-
-# Perform the cross-validation to estimate MSE
-scores_KFold = np.zeros((nlambdas, k))
-
-i = 0
-for lmb in lambdas:
- ridge = Ridge(alpha = lmb)
- j = 0
- for train_inds, test_inds in kfold.split(x):
- xtrain = x[train_inds]
- ytrain = y[train_inds]
-
- xtest = x[test_inds]
- ytest = y[test_inds]
-
- Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
- ridge.fit(Xtrain, ytrain[:, np.newaxis])
-
- Xtest = poly.fit_transform(xtest[:, np.newaxis])
- ypred = ridge.predict(Xtest)
-
- scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
-
- j += 1
- i += 1
-
-
-estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
-
-## Cross-validation using cross_val_score from sklearn along with KFold
-
-# kfold is an instance initialized above as:
-# kfold = KFold(n_splits = k)
-
-estimated_mse_sklearn = np.zeros(nlambdas)
-i = 0
-for lmb in lambdas:
- ridge = Ridge(alpha = lmb)
-
- X = poly.fit_transform(x[:, np.newaxis])
- estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
-
- # cross_val_score return an array containing the estimated negative mse for every fold.
- # we have to the the mean of every array in order to get an estimate of the mse of the model
- estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
-
- i += 1
-
-## Plot and compare the slightly different ways to perform cross-validation
-
-plt.figure()
-
-plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
-plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
-
-plt.xlabel('log10(lambda)')
-plt.ylabel('mse')
-
-plt.legend()
-
-plt.show()
-
-## The bias-variance tradeoff
-
-
-We will discuss the bias-variance tradeoff in the context of
-continuous predictions such as regression. However, many of the
-intuitions and ideas discussed here also carry over to classification
-tasks. Consider a dataset $\mathcal{L}$ consisting of the data
-$\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}$.
-
-Let us assume that the true data is generated from a noisy model
-
-$$
-\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon}
-$$
-
-where $\epsilon$ is normally distributed with mean zero and standard deviation $\sigma^2$.
-
-In our derivation of the ordinary least squares method we defined then
-an approximation to the function $f$ in terms of the parameters
-$\boldsymbol{\beta}$ and the design matrix $\boldsymbol{X}$ which embody our model,
-that is $\boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta}$.
-
-Thereafter we found the parameters $\boldsymbol{\beta}$ by optimizing the means squared error via the so-called cost function
-
-$$
-C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right].
-$$
-
-We can rewrite this as
-
-$$
-\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2.
-$$
-
-The three terms represent the square of the bias of the learning
-method, which can be thought of as the error caused by the simplifying
-assumptions built into the method. The second term represents the
-variance of the chosen model and finally the last terms is variance of
-the error $\boldsymbol{\epsilon}$.
-
-To derive this equation, we need to recall that the variance of $\boldsymbol{y}$ and $\boldsymbol{\epsilon}$ are both equal to $\sigma^2$. The mean value of $\boldsymbol{\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\boldsymbol{\tilde{y}}$.
-We use a more compact notation in terms of the expectation value
-
-$$
-\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right],
-$$
-
-and adding and subtracting $\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]$ we get
-
-$$
-\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right],
-$$
-
-which, using the abovementioned expectation values can be rewritten as
-
-$$
-\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2,
-$$
-
-that is the rewriting in terms of the so-called bias, the variance of the model $\boldsymbol{\tilde{y}}$ and the variance of $\boldsymbol{\epsilon}$.
-
-import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.linear_model import LinearRegression, Ridge, Lasso
-from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import train_test_split
-from sklearn.pipeline import make_pipeline
-from sklearn.utils import resample
+from sklearn import linear_model
-np.random.seed(2018)
-
-n = 500
-n_boostraps = 100
-degree = 18 # A quite high value, just to show.
-noise = 0.1
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
# Make data set.
-x = np.linspace(-1, 3, n).reshape(-1, 1)
-y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)
+n = 10000
+x = np.random.rand(n)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
-# Hold out some test data that is never used in training.
-x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
-
-# Combine x transformation and model into one operation.
-# Not neccesary, but convenient.
-model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
-
-# The following (m x n_bootstraps) matrix holds the column vectors y_pred
-# for each bootstrap iteration.
-y_pred = np.empty((y_test.shape[0], n_boostraps))
-for i in range(n_boostraps):
- x_, y_ = resample(x_train, y_train)
-
- # Evaluate the new model on the same test data each time.
- y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
-
-# Note: Expectations and variances taken w.r.t. different training
-# data sets, hence the axis=1. Subsequent means are taken across the test data
-# set in order to obtain a total value, but before this we have error/bias/variance
-# calculated per data point in the test set.
-# Note 2: The use of keepdims=True is important in the calculation of bias as this
-# maintains the column vector form. Dropping this yields very unexpected results.
-error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
-bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
-variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )
-print('Error:', error)
-print('Bias^2:', bias)
-print('Var:', variance)
-print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))
-
-plt.plot(x[::5, :], y[::5, :], label='f(x)')
-plt.scatter(x_test, y_test, label='Data points')
-plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')
-plt.legend()
-plt.show()
-
-import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.linear_model import LinearRegression, Ridge, Lasso
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.model_selection import train_test_split
-from sklearn.pipeline import make_pipeline
-from sklearn.utils import resample
-
-np.random.seed(2018)
-
-n = 40
-n_boostraps = 100
-maxdegree = 14
-
-
-# Make data set.
-x = np.linspace(-3, 3, n).reshape(-1, 1)
-y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
-error = np.zeros(maxdegree)
-bias = np.zeros(maxdegree)
-variance = np.zeros(maxdegree)
-polydegree = np.zeros(maxdegree)
-x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
-
-for degree in range(maxdegree):
- model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
- y_pred = np.empty((y_test.shape[0], n_boostraps))
- for i in range(n_boostraps):
- x_, y_ = resample(x_train, y_train)
- y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
-
- polydegree[degree] = degree
- error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
- bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
- variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
- print('Polynomial degree:', degree)
- print('Error:', error[degree])
- print('Bias^2:', bias[degree])
- print('Var:', variance[degree])
- print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
-
-plt.plot(polydegree, error, label='Error')
-plt.plot(polydegree, bias, label='bias')
-plt.plot(polydegree, variance, label='Variance')
-plt.legend()
-plt.show()
-
-The bias-variance tradeoff summarizes the fundamental tension in
-machine learning, particularly supervised learning, between the
-complexity of a model and the amount of training data needed to train
-it. Since data is often limited, in practice it is often useful to
-use a less-complex model with higher bias, that is a model whose asymptotic
-performance is worse than another model because it is easier to
-train and less sensitive to sampling noise arising from having a
-finite-sized training dataset (smaller variance).
-
-
-
-The above equations tell us that in
-order to minimize the expected test error, we need to select a
-statistical learning method that simultaneously achieves low variance
-and low bias. Note that variance is inherently a nonnegative quantity,
-and squared bias is also nonnegative. Hence, we see that the expected
-test MSE can never lie below $Var(\epsilon)$, the irreducible error.
-
-
-What do we mean by the variance and bias of a statistical learning
-method? The variance refers to the amount by which our model would change if we
-estimated it using a different training data set. Since the training
-data are used to fit the statistical learning method, different
-training data sets will result in a different estimate. But ideally the
-estimate for our model should not vary too much between training
-sets. However, if a method has high variance then small changes in
-the training data can result in large changes in the model. In general, more
-flexible statistical methods have higher variance.
-
-
-You may also find this recent [article](https://www.pnas.org/content/116/32/15849) of interest.
-
-"""
-============================
-Underfitting vs. Overfitting
-============================
-
-This example demonstrates the problems of underfitting and overfitting and
-how we can use linear regression with polynomial features to approximate
-nonlinear functions. The plot shows the function that we want to approximate,
-which is a part of the cosine function. In addition, the samples from the
-real function and the approximations of different models are displayed. The
-models have polynomial features of different degrees. We can see that a
-linear function (polynomial with degree 1) is not sufficient to fit the
-training samples. This is called **underfitting**. A polynomial of degree 4
-approximates the true function almost perfectly. However, for higher degrees
-the model will **overfit** the training data, i.e. it learns the noise of the
-training data.
-We evaluate quantitatively **overfitting** / **underfitting** by using
-cross-validation. We calculate the mean squared error (MSE) on the validation
-set, the higher, the less likely the model generalizes correctly from the
-training data.
-"""
-
-print(__doc__)
-
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.pipeline import Pipeline
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.linear_model import LinearRegression
-from sklearn.model_selection import cross_val_score
-
-
-def true_fun(X):
- return np.cos(1.5 * np.pi * X)
-
-np.random.seed(0)
-
-n_samples = 30
-degrees = [1, 4, 15]
-
-X = np.sort(np.random.rand(n_samples))
-y = true_fun(X) + np.random.randn(n_samples) * 0.1
-
-plt.figure(figsize=(14, 5))
-for i in range(len(degrees)):
- ax = plt.subplot(1, len(degrees), i + 1)
- plt.setp(ax, xticks=(), yticks=())
-
- polynomial_features = PolynomialFeatures(degree=degrees[i],
- include_bias=False)
- linear_regression = LinearRegression()
- pipeline = Pipeline([("polynomial_features", polynomial_features),
- ("linear_regression", linear_regression)])
- pipeline.fit(X[:, np.newaxis], y)
-
- # Evaluate the models using crossvalidation
- scores = cross_val_score(pipeline, X[:, np.newaxis], y,
- scoring="neg_mean_squared_error", cv=10)
-
- X_test = np.linspace(0, 1, 100)
- plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
- plt.plot(X_test, true_fun(X_test), label="True function")
- plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
- plt.xlabel("x")
- plt.ylabel("y")
- plt.xlim((0, 1))
- plt.ylim((-2, 2))
- plt.legend(loc="best")
- plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
- degrees[i], -scores.mean(), scores.std()))
-plt.show()
-
-# Common imports
-import os
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression, Ridge, Lasso
-from sklearn.model_selection import train_test_split
-from sklearn.utils import resample
-from sklearn.metrics import mean_squared_error
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
- os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
- os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
- os.makedirs(DATA_ID)
-
-def image_path(fig_id):
- return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
- return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
-
-infile = open(data_path("EoS.csv"),'r')
-
-# Read the EoS data as csv file and organize the data into two arrays with density and energies
-EoS = pd.read_csv(infile, names=('Density', 'Energy'))
-EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
-EoS = EoS.dropna()
-Energies = EoS['Energy']
-Density = EoS['Density']
-# The design matrix now as function of various polytrops
-
-Maxpolydegree = 30
-X = np.zeros((len(Density),Maxpolydegree))
+Maxpolydegree = 5
+X = np.zeros((len(x),Maxpolydegree))
X[:,0] = 1.0
-testerror = np.zeros(Maxpolydegree)
-trainingerror = np.zeros(Maxpolydegree)
-polynomial = np.zeros(Maxpolydegree)
-
-trials = 100
-for polydegree in range(1, Maxpolydegree):
- polynomial[polydegree] = polydegree
- for degree in range(polydegree):
- X[:,degree] = Density**(degree/3.0)
-
-# loop over trials in order to estimate the expectation value of the MSE
- testerror[polydegree] = 0.0
- trainingerror[polydegree] = 0.0
- for samples in range(trials):
- x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
- model = LinearRegression(fit_intercept=True).fit(x_train, y_train)
- ypred = model.predict(x_train)
- ytilde = model.predict(x_test)
- testerror[polydegree] += mean_squared_error(y_test, ytilde)
- trainingerror[polydegree] += mean_squared_error(y_train, ypred)
-
- testerror[polydegree] /= trials
- trainingerror[polydegree] /= trials
- print("Degree of polynomial: %3d"% polynomial[polydegree])
- print("Mean squared error on training data: %.8f" % trainingerror[polydegree])
- print("Mean squared error on test data: %.8f" % testerror[polydegree])
-
-plt.plot(polynomial, np.log10(trainingerror), label='Training Error')
-plt.plot(polynomial, np.log10(testerror), label='Test Error')
-plt.xlabel('Polynomial degree')
-plt.ylabel('log10[MSE]')
-plt.legend()
-plt.show()
-
-# Common imports
-import os
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression, Ridge, Lasso
-from sklearn.metrics import mean_squared_error
-from sklearn.model_selection import KFold
-from sklearn.model_selection import cross_val_score
-
-
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
- os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
- os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
- os.makedirs(DATA_ID)
-
-def image_path(fig_id):
- return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
- return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
-
-infile = open(data_path("EoS.csv"),'r')
-
-# Read the EoS data as csv file and organize the data into two arrays with density and energies
-EoS = pd.read_csv(infile, names=('Density', 'Energy'))
-EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
-EoS = EoS.dropna()
-Energies = EoS['Energy']
-Density = EoS['Density']
-# The design matrix now as function of various polytrops
-
-Maxpolydegree = 30
-X = np.zeros((len(Density),Maxpolydegree))
-X[:,0] = 1.0
-estimated_mse_sklearn = np.zeros(Maxpolydegree)
-polynomial = np.zeros(Maxpolydegree)
-k =5
-kfold = KFold(n_splits = k)
for polydegree in range(1, Maxpolydegree):
- polynomial[polydegree] = polydegree
for degree in range(polydegree):
- X[:,degree] = Density**(degree/3.0)
- OLS = LinearRegression()
-# loop over trials in order to estimate the expectation value of the MSE
- estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)
-#[:, np.newaxis]
- estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)
+ X[:,degree] = x**(degree)
-plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')
-plt.xlabel('Polynomial degree')
-plt.ylabel('log10[MSE]')
-plt.legend()
-plt.show()
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.model_selection import KFold
-from sklearn.linear_model import Ridge
-from sklearn.model_selection import cross_val_score
-from sklearn.preprocessing import PolynomialFeatures
-
-# A seed just to ensure that the random numbers are the same for every run.
-np.random.seed(3155)
-# Generate the data.
-n = 100
-x = np.linspace(-3, 3, n).reshape(-1, 1)
-y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
-# Decide degree on polynomial to fit
-poly = PolynomialFeatures(degree = 10)
+# We split the data in test and training data
+X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
+# matrix inversion to find beta
+OLSbeta = np.linalg.pinv(X_train.T @ X_train) @ X_train.T @ y_train
+print(OLSbeta)
+ypredictOLS = X_test @ OLSbeta
+print("Test MSE OLS")
+print(MSE(y_test,ypredictOLS))
+# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn
# Decide which values of lambda to use
-nlambdas = 500
-lambdas = np.logspace(-3, 5, nlambdas)
-# Initialize a KFold instance
-k = 5
-kfold = KFold(n_splits = k)
-estimated_mse_sklearn = np.zeros(nlambdas)
-i = 0
-for lmb in lambdas:
- ridge = Ridge(alpha = lmb)
- estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)
- estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
- i += 1
+nlambdas = 4
+MSERidgePredict = np.zeros(nlambdas)
+MSELassoPredict = np.zeros(nlambdas)
+lambdas = np.logspace(-3, 1, nlambdas)
+for i in range(nlambdas):
+ lmb = lambdas[i]
+ # Make the fit using Ridge and Lasso
+ RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
+ RegRidge.fit(X_train,y_train)
+ RegLasso = linear_model.Lasso(lmb,fit_intercept=False)
+ RegLasso.fit(X_train,y_train)
+ # and then make the prediction
+ ypredictRidge = RegRidge.predict(X_test)
+ ypredictLasso = RegLasso.predict(X_test)
+ # Compute the MSE and print it
+ MSERidgePredict[i] = MSE(y_test,ypredictRidge)
+ MSELassoPredict[i] = MSE(y_test,ypredictLasso)
+ print(lmb,RegRidge.coef_)
+ print(lmb,RegLasso.coef_)
+# Now plot the results
plt.figure()
-plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
+plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')
+plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')
plt.xlabel('log10(lambda)')
plt.ylabel('MSE')
plt.legend()
-plt.show()
\ No newline at end of file
+plt.show()
+
+How can we understand this?
+
+
+
+Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression.
+
+For ordinary least squares we postulated that the maximum likelihood for the doamin of events $\boldsymbol{D}$ (one-dimensional case)
+
+$$
+\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})],
+$$
+
+is given by
+
+$$
+p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
+$$
+
+In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set $\boldsymbol{\beta}$ given a domain of events $\boldsymbol{D}$? That is, how can we define the posterior probability
+
+$$
+p(\boldsymbol{\beta}\vert\boldsymbol{D}).
+$$
+
+Bayes' theorem comes to our rescue here since (omitting the normalization constant)
+
+$$
+p(\boldsymbol{\beta}\vert\boldsymbol{D})\propto p(\boldsymbol{D}\vert\boldsymbol{\beta})p(\boldsymbol{\beta}).
+$$
+
+We have a model for $p(\boldsymbol{D}\vert\boldsymbol{\beta})$ but need one for the **prior** $p(\boldsymbol{\beta}$!
+
+
+
+With the posterior probability defined by a likelihood which we have
+already modeled and an unknown prior, we are now ready to make
+additional models for the prior.
+
+We can, based on our discussions of the variance of $\boldsymbol{\beta}$ and the mean value, assume that the prior for the values $\boldsymbol{\beta}$ is given by a Gaussian with mean value zero and variance $\tau^2$, that is
+
+$$
+p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}.
+$$
+
+Our posterior probability becomes then (omitting the normalization factor which is just a constant)
+
+$$
+p(\boldsymbol{\beta\vert\boldsymbol{D})}=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}.
+$$
+
+We can now optimize this quantity with respect to $\boldsymbol{\beta}$. As we
+did for OLS, this is most conveniently done by taking the negative
+logarithm of the posterior probability. Doing so and leaving out the
+constants terms that do not depend on $\beta$, we have
+
+$$
+C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{2\tau^2}\vert\vert\boldsymbol{\beta}\vert\vert_2^2,
+$$
+
+and replacing $1/2\tau^2$ with $\lambda$ we have
+
+$$
+C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_2^2,
+$$
+
+which is our Ridge cost function! Nice, isn't it?
+
+
+To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution ([Laplace in this case](https://en.wikipedia.org/wiki/Laplace_distribution)) with zero mean value, that is
+
+$$
+p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}.
+$$
+
+Our posterior probability becomes then (omitting the normalization factor which is just a constant)
+
+$$
+p(\boldsymbol{\beta}\vert\boldsymbol{D})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}.
+$$
+
+Taking the negative
+logarithm of the posterior probability and leaving out the
+constants terms that do not depend on $\beta$, we have
+
+$$
+C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{\tau}\vert\vert\boldsymbol{\beta}\vert\vert_1,
+$$
+
+and replacing $1/\tau$ with $\lambda$ we have
+
+$$
+C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1,
+$$
+
+which is our Lasso cost function!
\ No newline at end of file
diff --git a/doc/LectureNotes/_build/jupyter_execute/chapter3.ipynb b/doc/LectureNotes/_build/jupyter_execute/chapter3.ipynb
index f83430cea..11daf9011 100644
--- a/doc/LectureNotes/_build/jupyter_execute/chapter3.ipynb
+++ b/doc/LectureNotes/_build/jupyter_execute/chapter3.ipynb
@@ -4,40 +4,78 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "# Ridge and Lasso Regression\n",
+ "# Resampling Methods\n",
"\n",
- "[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember10.mp4?vrtx=view-as-webpage)\n",
+ "## Introduction\n",
+ "\n",
+ "Resampling methods are an indispensable tool in modern\n",
+ "statistics. They involve repeatedly drawing samples from a training\n",
+ "set and refitting a model of interest on each sample in order to\n",
+ "obtain additional information about the fitted model. For example, in\n",
+ "order to estimate the variability of a linear regression fit, we can\n",
+ "repeatedly draw different samples from the training data, fit a linear\n",
+ "regression to each new sample, and then examine the extent to which\n",
+ "the resulting fits differ. Such an approach may allow us to obtain\n",
+ "information that would not be available from fitting the model only\n",
+ "once using the original training sample.\n",
+ "\n",
+ "Two resampling methods are often used in Machine Learning analyses,\n",
+ "1. The **bootstrap method**\n",
+ "\n",
+ "2. and **Cross-Validation**\n",
+ "\n",
+ "In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular\n",
+ "cross-validation and the bootstrap method. \n",
"\n",
"\n",
- "## The singular value decomposition\n",
- "\n",
- "The examples we have looked at so far are cases where we normally can\n",
- "invert the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$. Using a polynomial expansion as we\n",
- "did both for the masses and the fitting of the equation of state,\n",
- "leads to row vectors of the design matrix which are essentially\n",
- "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. \n",
+ "Resampling approaches can be computationally expensive, because they\n",
+ "involve fitting the same statistical method multiple times using\n",
+ "different subsets of the training data. However, due to recent\n",
+ "advances in computing power, the computational requirements of\n",
+ "resampling methods generally are not prohibitive. In this chapter, we\n",
+ "discuss two of the most commonly used resampling methods,\n",
+ "cross-validation and the bootstrap. Both methods are important tools\n",
+ "in the practical application of many statistical learning\n",
+ "procedures. For example, cross-validation can be used to estimate the\n",
+ "test error associated with a given statistical learning method in\n",
+ "order to evaluate its performance, or to select the appropriate level\n",
+ "of flexibility. The process of evaluating a model’s performance is\n",
+ "known as model assessment, whereas the process of selecting the proper\n",
+ "level of flexibility for a model is known as model selection. The\n",
+ "bootstrap is widely used.\n",
"\n",
"\n",
+ "* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods\n",
"\n",
- "This may\n",
- "however not the be case in general and a standard matrix inversion\n",
- "algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.\n",
+ "* The results can be analysed with the same statistical tools as we would use analysing experimental data.\n",
"\n",
- "There is however a way to partially circumvent this problem and also gain some insights about the ordinary least squares approach, and later shrinkage methods like Ridge and Lasso regressions. \n",
+ "* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n",
"\n",
- "This is given by the **Singular Value Decomposition** algorithm, perhaps\n",
- "the most powerful linear algebra algorithm. Let us look at a\n",
- "different example where we may have problems with the standard matrix\n",
- "inversion algorithm. Thereafter we dive into the math of the SVD.\n",
+ "## Reminder on Statistics\n",
"\n",
"\n",
+ "* As in other experiments, many numerical experiments have two classes of errors:\n",
"\n",
- "One of the typical problems we encounter with linear regression, in particular \n",
- "when the matrix $\\boldsymbol{X}$ (our so-called design matrix) is high-dimensional, \n",
- "are problems with near singular or singular matrices. The column vectors of $\\boldsymbol{X}$ \n",
- "may be linearly dependent, normally referred to as super-collinearity. \n",
- "This means that the matrix may be rank deficient and it is basically impossible to \n",
- "to model the data using linear regression. As an example, consider the matrix"
+ " * Statistical errors\n",
+ "\n",
+ " * Systematical errors\n",
+ "\n",
+ "\n",
+ "* Statistical errors can be estimated using standard tools from statistics\n",
+ "\n",
+ "* Systematical errors are method specific and must be treated differently from case to case. \n",
+ "\n",
+ "The\n",
+ "advantage of doing linear regression is that we actually end up with\n",
+ "analytical expressions for several statistical quantities. \n",
+ "Standard least squares and Ridge regression allow us to\n",
+ "derive quantities like the variance and other expectation values in a\n",
+ "rather straightforward way.\n",
+ "\n",
+ "\n",
+ "It is assumed that $\\varepsilon_i\n",
+ "\\sim \\mathcal{N}(0, \\sigma^2)$ and the $\\varepsilon_{i}$ are\n",
+ "independent, i.e.:"
]
},
{
@@ -45,17 +83,10 @@
"metadata": {},
"source": [
"$$\n",
- "\\begin{align*}\n",
- "\\mathbf{X} & = \\left[\n",
- "\\begin{array}{rrr}\n",
- "1 & -1 & 2\n",
- "\\\\\n",
- "1 & 0 & 1\n",
- "\\\\\n",
- "1 & 2 & -1\n",
- "\\\\\n",
- "1 & 1 & 0\n",
- "\\end{array} \\right]\n",
+ "\\begin{align*} \n",
+ "\\mbox{Cov}(\\varepsilon_{i_1},\n",
+ "\\varepsilon_{i_2}) & = \\left\\{ \\begin{array}{lcc} \\sigma^2 & \\mbox{if}\n",
+ "& i_1 = i_2, \\\\ 0 & \\mbox{if} & i_1 \\not= i_2. \\end{array} \\right.\n",
"\\end{align*}\n",
"$$"
]
@@ -64,14 +95,21 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The columns of $\\boldsymbol{X}$ are linearly dependent. We see this easily since the \n",
- "the first column is the row-wise sum of the other two columns. The rank (more correct,\n",
- "the column rank) of a matrix is the dimension of the space spanned by the\n",
- "column vectors. Hence, the rank of $\\mathbf{X}$ is equal to the number\n",
- "of linearly independent columns. In this particular case the matrix has rank 2.\n",
+ "The randomness of $\\varepsilon_i$ implies that\n",
+ "$\\mathbf{y}_i$ is also a random variable. In particular,\n",
+ "$\\mathbf{y}_i$ is normally distributed, because $\\varepsilon_i \\sim\n",
+ "\\mathcal{N}(0, \\sigma^2)$ and $\\mathbf{X}_{i,\\ast} \\, \\boldsymbol{\\beta}$ is a\n",
+ "non-random scalar. To specify the parameters of the distribution of\n",
+ "$\\mathbf{y}_i$ we need to calculate its first two moments. \n",
"\n",
- "Super-collinearity of an $(n \\times p)$-dimensional design matrix $\\mathbf{X}$ implies\n",
- "that the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this"
+ "Recall that $\\boldsymbol{X}$ is a matrix of dimensionality $n\\times p$. The\n",
+ "notation above $\\mathbf{X}_{i,\\ast}$ means that we are looking at the\n",
+ "row number $i$ and perform a sum over all values $p$.\n",
+ "\n",
+ "\n",
+ "The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off)\n",
+ "that there exists a function $f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim \\mathcal{N}(0, \\sigma^2)$\n",
+ "which describe our data"
]
},
{
@@ -79,13 +117,43 @@
"metadata": {},
"source": [
"$$\n",
- "\\begin{align*}\n",
- "\\boldsymbol{X} & = \\left[\n",
- "\\begin{array}{rr}\n",
- "1 & -1\n",
- "\\\\\n",
- "1 & -1\n",
- "\\end{array} \\right].\n",
+ "\\boldsymbol{y} = f(\\boldsymbol{x})+\\boldsymbol{\\varepsilon}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We approximate this function with our model from the solution of the linear regression equations, that is our\n",
+ "function $f$ is approximated by $\\boldsymbol{\\tilde{y}}$ where we want to minimize $(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2$, our MSE, with"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can calculate the expectation value of $\\boldsymbol{y}$ for a given element $i$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*} \n",
+ "\\mathbb{E}(y_i) & =\n",
+ "\\mathbb{E}(\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}) + \\mathbb{E}(\\varepsilon_i)\n",
+ "\\, \\, \\, = \\, \\, \\, \\mathbf{X}_{i, \\ast} \\, \\beta, \n",
"\\end{align*}\n",
"$$"
]
@@ -94,39 +162,8 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "We see easily that $\\mbox{det}(\\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \\times (-1) - 1 \\times (-1) = 0$. Hence, $\\mathbf{X}$ is singular and its inverse is undefined.\n",
- "This is equivalent to saying that the matrix $\\boldsymbol{X}$ has at least an eigenvalue which is zero.\n",
- "\n",
- "\n",
- "If our design matrix $\\boldsymbol{X}$ which enters the linear regression problem"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "
\n",
- "\n",
- "$$\n",
- "\\begin{equation}\n",
- "\\boldsymbol{\\beta} = (\\boldsymbol{X}^{T} \\boldsymbol{X})^{-1} \\boldsymbol{X}^{T} \\boldsymbol{y},\n",
- "\\label{_auto1} \\tag{1}\n",
- "\\end{equation}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "has linearly dependent column vectors, we will not be able to compute the inverse\n",
- "of $\\boldsymbol{X}^T\\boldsymbol{X}$ and we cannot find the parameters (estimators) $\\beta_i$. \n",
- "The estimators are only well-defined if $(\\boldsymbol{X}^{T}\\boldsymbol{X})^{-1}$ exits. \n",
- "This is more likely to happen when the matrix $\\boldsymbol{X}$ is high-dimensional. In this case it is likely to encounter a situation where \n",
- "the regression parameters $\\beta_i$ cannot be estimated.\n",
- "\n",
- "A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change"
+ "while\n",
+ "its variance is"
]
},
{
@@ -134,7 +171,18 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X}^{T} \\boldsymbol{X} \\rightarrow \\boldsymbol{X}^{T} \\boldsymbol{X}+\\lambda \\boldsymbol{I},\n",
+ "\\begin{align*} \\mbox{Var}(y_i) & = \\mathbb{E} \\{ [y_i\n",
+ "- \\mathbb{E}(y_i)]^2 \\} \\, \\, \\, = \\, \\, \\, \\mathbb{E} ( y_i^2 ) -\n",
+ "[\\mathbb{E}(y_i)]^2 \\\\ & = \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\,\n",
+ "\\beta + \\varepsilon_i )^2] - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \\\\ &\n",
+ "= \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2 \\varepsilon_i\n",
+ "\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} + \\varepsilon_i^2 ] - ( \\mathbf{X}_{i,\n",
+ "\\ast} \\, \\beta)^2 \\\\ & = ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2\n",
+ "\\mathbb{E}(\\varepsilon_i) \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} +\n",
+ "\\mathbb{E}(\\varepsilon_i^2 ) - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \n",
+ "\\\\ & = \\mathbb{E}(\\varepsilon_i^2 ) \\, \\, \\, = \\, \\, \\,\n",
+ "\\mbox{Var}(\\varepsilon_i) \\, \\, \\, = \\, \\, \\, \\sigma^2. \n",
+ "\\end{align*}\n",
"$$"
]
},
@@ -142,16 +190,11 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "where $\\boldsymbol{I}$ is the identity matrix. When we discuss **Ridge** regression this is actually what we end up evaluating. The parameter $\\lambda$ is called a hyperparameter. More about this later. \n",
+ "Hence, $y_i \\sim \\mathcal{N}( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}, \\sigma^2)$, that is $\\boldsymbol{y}$ follows a normal distribution with \n",
+ "mean value $\\boldsymbol{X}\\boldsymbol{\\beta}$ and variance $\\sigma^2$ (not be confused with the singular values of the SVD). \n",
"\n",
"\n",
- "\n",
- "\n",
- "\n",
- "From standard linear algebra we know that a square matrix $\\boldsymbol{X}$ can be diagonalized if and only it is \n",
- "a so-called [normal matrix](https://en.wikipedia.org/wiki/Normal_matrix), that is if $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$\n",
- "we have $\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ or if $\\boldsymbol{X}\\in {\\mathbb{C}}^{n\\times n}$ we have $\\boldsymbol{X}\\boldsymbol{X}^{\\dagger}=\\boldsymbol{X}^{\\dagger}\\boldsymbol{X}$.\n",
- "The matrix has then a set of eigenpairs"
+ "With the OLS expressions for the parameters $\\boldsymbol{\\beta}$ we can evaluate the expectation value"
]
},
{
@@ -159,7 +202,7 @@
"metadata": {},
"source": [
"$$\n",
- "(\\lambda_1,\\boldsymbol{u}_1),\\dots, (\\lambda_n,\\boldsymbol{u}_n),\n",
+ "\\mathbb{E}(\\boldsymbol{\\beta}) = \\mathbb{E}[ (\\mathbf{X}^{\\top} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbb{E}[ \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\mathbf{X}^{T}\\mathbf{X}\\boldsymbol{\\beta}=\\boldsymbol{\\beta}.\n",
"$$"
]
},
@@ -167,7 +210,11 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "and the eigenvalues are given by the diagonal matrix"
+ "This means that the estimator of the regression parameters is unbiased.\n",
+ "\n",
+ "We can also calculate the variance\n",
+ "\n",
+ "The variance of $\\boldsymbol{\\beta}$ is"
]
},
{
@@ -175,7 +222,26 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{\\Sigma}=\\mathrm{Diag}(\\lambda_1, \\dots,\\lambda_n).\n",
+ "\\begin{eqnarray*}\n",
+ "\\mbox{Var}(\\boldsymbol{\\beta}) & = & \\mathbb{E} \\{ [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})] [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})]^{T} \\}\n",
+ "\\\\\n",
+ "& = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} - \\boldsymbol{\\beta}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} - \\boldsymbol{\\beta}]^{T} \\}\n",
+ "\\\\\n",
+ "% & = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y}]^{T} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "% \\\\\n",
+ "% & = & \\mathbb{E} \\{ (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} \\, \\mathbf{Y}^{T} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "% \\\\\n",
+ "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\mathbb{E} \\{ \\mathbf{Y} \\, \\mathbf{Y}^{T} \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "\\\\\n",
+ "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\{ \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} + \\sigma^2 \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "% \\\\\n",
+ "% & = & (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^T \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T % \\mathbf{X})^{-1}\n",
+ "% \\\\\n",
+ "% & & + \\, \\, \\sigma^2 \\, (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\boldsymbol{\\beta}^T\n",
+ "\\\\\n",
+ "& = & \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} + \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "\\, \\, \\, = \\, \\, \\, \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1},\n",
+ "\\end{eqnarray*}\n",
"$$"
]
},
@@ -183,7 +249,21 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The matrix $\\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\\boldsymbol{U}$"
+ "where we have used that $\\mathbb{E} (\\mathbf{Y} \\mathbf{Y}^{T}) =\n",
+ "\\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} +\n",
+ "\\sigma^2 \\, \\mathbf{I}_{nn}$. From $\\mbox{Var}(\\boldsymbol{\\beta}) = \\sigma^2\n",
+ "\\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}$, one obtains an estimate of the\n",
+ "variance of the estimate of the $j$-th regression coefficient:\n",
+ "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 \\sqrt{\n",
+ "[(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} }$. This may be used to\n",
+ "construct a confidence interval for the estimates.\n",
+ "\n",
+ "\n",
+ "In a similar way, we can obtain analytical expressions for say the\n",
+ "expectation values of the parameters $\\boldsymbol{\\beta}$ and their variance\n",
+ "when we employ Ridge regression, allowing us again to define a confidence interval. \n",
+ "\n",
+ "It is rather straightforward to show that"
]
},
{
@@ -191,7 +271,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "\\mathbb{E} \\big[ \\boldsymbol{\\beta}^{\\mathrm{Ridge}} \\big]=(\\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I}_{pp})^{-1} (\\mathbf{X}^{\\top} \\mathbf{X})\\boldsymbol{\\beta}^{\\mathrm{OLS}}.\n",
"$$"
]
},
@@ -199,9 +279,10 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "with $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ or $\\boldsymbol{U}\\boldsymbol{U}^{\\dagger}=\\boldsymbol{I}$.\n",
+ "We see clearly that \n",
+ "$\\mathbb{E} \\big[ \\boldsymbol{\\beta}^{\\mathrm{Ridge}} \\big] \\not= \\boldsymbol{\\beta}^{\\mathrm{OLS}}$ for any $\\lambda > 0$. We say then that the ridge estimator is biased.\n",
"\n",
- "Not all square matrices are diagonalizable. A matrix like the one discussed above"
+ "We can also compute the variance as"
]
},
{
@@ -209,10 +290,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X} = \\begin{bmatrix} \n",
- "1& -1 \\\\\n",
- "1& -1\\\\\n",
- "\\end{bmatrix}\n",
+ "\\mbox{Var}[\\boldsymbol{\\beta}^{\\mathrm{Ridge}}]=\\sigma^2[ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1} \\mathbf{X}^{T} \\mathbf{X} \\{ [ \\mathbf{X}^{\\top} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T},\n",
"$$"
]
},
@@ -220,23 +298,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "is not diagonalizable, it is a so-called [defective matrix](https://en.wikipedia.org/wiki/Defective_matrix). It is easy to see that the condition\n",
- "$\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ is not fulfilled. \n",
+ "and it is easy to see that if the parameter $\\lambda$ goes to infinity then the variance of Ridge parameters $\\boldsymbol{\\beta}$ goes to zero. \n",
"\n",
- "\n",
- "\n",
- "## The SVD, a Fantastic Algorithm\n",
- "\n",
- "\n",
- "However, and this is the strength of the SVD algorithm, any general\n",
- "matrix $\\boldsymbol{X}$ can be decomposed in terms of a diagonal matrix and\n",
- "two orthogonal/unitary matrices. The [Singular Value Decompostion\n",
- "(SVD) theorem](https://en.wikipedia.org/wiki/Singular_value_decomposition)\n",
- "states that a general $m\\times n$ matrix $\\boldsymbol{X}$ can be written in\n",
- "terms of a diagonal matrix $\\boldsymbol{\\Sigma}$ of dimensionality $m\\times n$\n",
- "and two orthognal matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$, where the first has\n",
- "dimensionality $m \\times m$ and the last dimensionality $n\\times n$.\n",
- "We have then"
+ "With this, we can compute the difference"
]
},
{
@@ -244,7 +308,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\n",
+ "\\mbox{Var}[\\boldsymbol{\\beta}^{\\mathrm{OLS}}]-\\mbox{Var}(\\boldsymbol{\\beta}^{\\mathrm{Ridge}})=\\sigma^2 [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}[ 2\\lambda\\mathbf{I} + \\lambda^2 (\\mathbf{X}^{T} \\mathbf{X})^{-1} ] \\{ [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T}.\n",
"$$"
]
},
@@ -252,7 +316,54 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "As an example, the above defective matrix can be decomposed as"
+ "The difference is non-negative definite since each component of the\n",
+ "matrix product is non-negative definite. \n",
+ "This means the variance we obtain with the standard OLS will always for $\\lambda > 0$ be larger than the variance of $\\boldsymbol{\\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. \n",
+ "\n",
+ "\n",
+ "\n",
+ "## Resampling methods\n",
+ "\n",
+ "With all these analytical equations for both the OLS and Ridge\n",
+ "regression, we will now outline how to assess a given model. This will\n",
+ "lead us to a discussion of the so-called bias-variance tradeoff (see\n",
+ "below) and so-called resampling methods.\n",
+ "\n",
+ "One of the quantities we have discussed as a way to measure errors is\n",
+ "the mean-squared error (MSE), mainly used for fitting of continuous\n",
+ "functions. Another choice is the absolute error.\n",
+ "\n",
+ "In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,\n",
+ "we discuss the\n",
+ "1. prediction error or simply the **test error** $\\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the \n",
+ "\n",
+ "2. training error $\\mathrm{Err_{Train}}$, which is the average loss over the training data.\n",
+ "\n",
+ "As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.\n",
+ "For a certain level of complexity the test error will reach minimum, before starting to increase again. The\n",
+ "training error reaches a saturation.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Two famous\n",
+ "resampling methods are the **independent bootstrap** and **the jackknife**. \n",
+ "\n",
+ "The jackknife is a special case of the independent bootstrap. Still, the jackknife was made\n",
+ "popular prior to the independent bootstrap. And as the popularity of\n",
+ "the independent bootstrap soared, new variants, such as **the dependent bootstrap**.\n",
+ "\n",
+ "The Jackknife and independent bootstrap work for\n",
+ "independent, identically distributed random variables.\n",
+ "If these conditions are not\n",
+ "satisfied, the methods will fail. Yet, it should be said that if the data are\n",
+ "independent, identically distributed, and we only want to estimate the\n",
+ "variance of $\\overline{X}$ (which often is the case), then there is no\n",
+ "need for bootstrapping. \n",
+ "\n",
+ "\n",
+ "The Jackknife works by making many replicas of the estimator $\\widehat{\\theta}$. \n",
+ "The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\\boldsymbol{x} = (x_1,x_2,\\cdots,X_n)$. \n",
+ "Let $\\boldsymbol{x}_i$ denote the vector"
]
},
{
@@ -260,7 +371,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X} = \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& 1 \\\\ 1& -1\\\\ \\end{bmatrix} \\begin{bmatrix} 2& 0 \\\\ 0& 0\\\\ \\end{bmatrix} \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& -1 \\\\ 1& 1\\\\ \\end{bmatrix}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "\\boldsymbol{x}_i = (x_1,x_2,\\cdots,x_{i-1},x_{i+1},\\cdots,x_n),\n",
"$$"
]
},
@@ -268,45 +379,10 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "with eigenvalues $\\sigma_1=2$ and $\\sigma_2=0$. \n",
- "The SVD exits always! \n",
- "\n",
- "The SVD\n",
- "decomposition (singular values) gives eigenvalues \n",
- "$\\sigma_i\\geq\\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=p$, the\n",
- "eigenvalues (singular values) are zero.\n",
- "\n",
- "In the general case, where our design matrix $\\boldsymbol{X}$ has dimension\n",
- "$n\\times p$, the matrix is thus decomposed into an $n\\times n$\n",
- "orthogonal matrix $\\boldsymbol{U}$, a $p\\times p$ orthogonal matrix $\\boldsymbol{V}$\n",
- "and a diagonal matrix $\\boldsymbol{\\Sigma}$ with $r=\\mathrm{min}(n,p)$\n",
- "singular values $\\sigma_i\\geq 0$ on the main diagonal and zeros filling\n",
- "the rest of the matrix. There are at most $p$ singular values\n",
- "assuming that $n > p$. In our regression examples for the nuclear\n",
- "masses and the equation of state this is indeed the case, while for\n",
- "the Ising model we have $p > n$. These are often cases that lead to\n",
- "near singular or singular matrices.\n",
- "\n",
- "The columns of $\\boldsymbol{U}$ are called the left singular vectors while the columns of $\\boldsymbol{V}$ are the right singular vectors.\n",
- "\n",
- "## Economy-size SVD\n",
- "\n",
- "If we assume that $n > p$, then our matrix $\\boldsymbol{U}$ has dimension $n\n",
- "\\times n$. The last $n-p$ columns of $\\boldsymbol{U}$ become however\n",
- "irrelevant in our calculations since they are multiplied with the\n",
- "zeros in $\\boldsymbol{\\Sigma}$.\n",
- "\n",
- "The economy-size decomposition removes extra rows or columns of zeros\n",
- "from the diagonal matrix of singular values, $\\boldsymbol{\\Sigma}$, along with the columns\n",
- "in either $\\boldsymbol{U}$ or $\\boldsymbol{V}$ that multiply those zeros in the expression. \n",
- "Removing these zeros and columns can improve execution time\n",
- "and reduce storage requirements without compromising the accuracy of\n",
- "the decomposition.\n",
- "\n",
- "If $n > p$, we keep only the first $p$ columns of $\\boldsymbol{U}$ and $\\boldsymbol{\\Sigma}$ has dimension $p\\times p$. \n",
- "If $p > n$, then only the first $n$ columns of $\\boldsymbol{V}$ are computed and $\\boldsymbol{\\Sigma}$ has dimension $n\\times n$.\n",
- "The $n=p$ case is obvious, we retain the full SVD. \n",
- "In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy."
+ "which equals the vector $\\boldsymbol{x}$ with the exception that observation\n",
+ "number $i$ is left out. Using this notation, define\n",
+ "$\\widehat{\\theta}_i$ to be the estimator\n",
+ "$\\widehat{\\theta}$ computed using $\\vec{X}_i$."
]
},
{
@@ -321,817 +397,139 @@
"name": "stdout",
"output_type": "stream",
"text": [
- "[[ 1. -1. 2.]\n",
- " [ 1. 0. 1.]\n",
- " [ 1. 2. -1.]\n",
- " [ 1. 1. 0.]]\n",
- "[[ 4. 2. 2.]\n",
- " [ 2. 6. -4.]\n",
- " [ 2. -4. 6.]]\n",
- "[[-1.18404906e-16 8.16496581e-01 -5.77350269e-01]\n",
- " [-7.07106781e-01 4.08248290e-01 5.77350269e-01]\n",
- " [ 7.07106781e-01 4.08248290e-01 5.77350269e-01]]\n",
- "[1.00000000e+01 6.00000000e+00 9.10898112e-32]\n",
- "[[ 3.33066907e-17 -7.07106781e-01 7.07106781e-01]\n",
- " [ 8.16496581e-01 4.08248290e-01 4.08248290e-01]\n",
- " [ 5.77350269e-01 -5.77350269e-01 -5.77350269e-01]]\n",
- "[[-3.65939208e+30 3.65939208e+30 3.65939208e+30]\n",
- " [ 3.65939208e+30 -3.65939208e+30 -3.65939208e+30]\n",
- " [ 3.65939208e+30 -3.65939208e+30 -3.65939208e+30]]\n"
+ "Runtime: 0.139462 sec\n",
+ "Jackknife Statistics :\n",
+ "original bias std. error\n",
+ " 100.065 100.055 0.149894\n"
]
}
],
"source": [
- "import numpy as np\n",
- "# SVD inversion\n",
- "def SVDinv(A):\n",
- " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n",
- " SVD is numerically more stable than the inversion algorithms provided by\n",
- " numpy and scipy.linalg at the cost of being slower.\n",
- " '''\n",
- " U, s, VT = np.linalg.svd(A)\n",
- "# print('test U')\n",
- "# print( (np.transpose(U) @ U - U @np.transpose(U)))\n",
- "# print('test VT')\n",
- "# print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n",
- " print(U)\n",
- " print(s)\n",
- " print(VT)\n",
+ "from numpy import *\n",
+ "from numpy.random import randint, randn\n",
+ "from time import time\n",
"\n",
- " D = np.zeros((len(U),len(VT)))\n",
- " for i in range(0,len(VT)):\n",
- " D[i,i]=s[i]\n",
- " UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)\n",
- " return np.matmul(V,np.matmul(invD,UT))\n",
+ "def jackknife(data, stat):\n",
+ " n = len(data);t = zeros(n); inds = arange(n); t0 = time()\n",
+ " ## 'jackknifing' by leaving out an observation for each i \n",
+ " for i in range(n):\n",
+ " t[i] = stat(delete(data,i) )\n",
+ "\n",
+ " # analysis \n",
+ " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Jackknife Statistics :\")\n",
+ " print(\"original bias std. error\")\n",
+ " print(\"%8g %14g %15g\" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))\n",
+ "\n",
+ " return t\n",
"\n",
"\n",
- "X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])\n",
- "print(X)\n",
- "A = np.transpose(X) @ X\n",
- "print(A)\n",
- "# Brute force inversion of super-collinear matrix\n",
- "#B = np.linalg.inv(A)\n",
- "#print(B)\n",
- "C = SVDinv(A)\n",
- "print(C)"
+ "# Returns mean of data samples \n",
+ "def stat(data):\n",
+ " return mean(data)\n",
+ "\n",
+ "\n",
+ "mu, sigma = 100, 15\n",
+ "datapoints = 10000\n",
+ "x = mu + sigma*random.randn(datapoints)\n",
+ "# jackknife returns the data sample \n",
+ "t = jackknife(x, stat)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "The matrix $\\boldsymbol{X}$ has columns that are linearly dependent. The first\n",
- "column is the row-wise sum of the other two columns. The rank of a\n",
- "matrix (the column rank) is the dimension of space spanned by the\n",
- "column vectors. The rank of the matrix is the number of linearly\n",
- "independent columns, in this case just $2$. We see this from the\n",
- "singular values when running the above code. Running the standard\n",
- "inversion algorithm for matrix inversion with $\\boldsymbol{X}^T\\boldsymbol{X}$ results\n",
- "in the program terminating due to a singular matrix.\n",
+ "### Bootstrap\n",
+ "\n",
+ "Bootstrapping is a nonparametric approach to statistical inference\n",
+ "that substitutes computation for more traditional distributional\n",
+ "assumptions and asymptotic results. Bootstrapping offers a number of\n",
+ "advantages: \n",
+ "1. The bootstrap is quite general, although there are some cases in which it fails. \n",
+ "\n",
+ "2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. \n",
+ "\n",
+ "3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. \n",
+ "\n",
+ "4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).\n",
+ "\n",
+ "Since $\\widehat{\\theta} = \\widehat{\\theta}(\\boldsymbol{X})$ is a function of random variables,\n",
+ "$\\widehat{\\theta}$ itself must be a random variable. Thus it has\n",
+ "a pdf, call this function $p(\\boldsymbol{t})$. The aim of the bootstrap is to\n",
+ "estimate $p(\\boldsymbol{t})$ by the relative frequency of\n",
+ "$\\widehat{\\theta}$. You can think of this as using a histogram\n",
+ "in the place of $p(\\boldsymbol{t})$. If the relative frequency closely\n",
+ "resembles $p(\\vec{t})$, then using numerics, it is straight forward to\n",
+ "estimate all the interesting parameters of $p(\\boldsymbol{t})$ using point\n",
+ "estimators. \n",
"\n",
"\n",
"\n",
+ "In the case that $\\widehat{\\theta}$ has\n",
+ "more than one component, and the components are independent, we use the\n",
+ "same estimator on each component separately. If the probability\n",
+ "density function of $X_i$, $p(x)$, had been known, then it would have\n",
+ "been straight forward to do this by: \n",
+ "1. Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \\cdots, X_n^*)$. \n",
"\n",
- "There are several interesting mathematical properties which will be\n",
- "relevant when we are going to discuss the differences between say\n",
- "ordinary least squares (OLS) and **Ridge** regression.\n",
+ "2. Then using these numbers, we could compute a replica of $\\widehat{\\theta}$ called $\\widehat{\\theta}^*$. \n",
"\n",
- "We have from OLS that the parameters of the linear approximation are given by"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The matrix to invert can be rewritten in terms of our SVD decomposition as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}^T\\boldsymbol{X} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Using the orthogonality properties of $\\boldsymbol{U}$ we have"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}^T\\boldsymbol{X} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T = \\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with $\\boldsymbol{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared. \n",
- "\n",
- "This means that"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "(\\boldsymbol{X}^T\\boldsymbol{X})\\boldsymbol{V} = \\boldsymbol{V}\\boldsymbol{D},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "that is the eigenvectors of $(\\boldsymbol{X}^T\\boldsymbol{X})$ are given by the columns of the right singular matrix of $\\boldsymbol{X}$ and the eigenvalues are the squared singular values. It is easy to show (show this) that"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U} = \\boldsymbol{U}\\boldsymbol{D},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "that is, the eigenvectors of $(\\boldsymbol{X}\\boldsymbol{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same. \n",
- "\n",
- "Going back to our OLS equation we have"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We will come back to this expression when we discuss Ridge regression. \n",
+ "By repeated use of (1) and (2), many\n",
+ "estimates of $\\widehat{\\theta}$ could have been obtained. The\n",
+ "idea is to use the relative frequency of $\\widehat{\\theta}^*$\n",
+ "(think of a histogram) as an estimate of $p(\\boldsymbol{t})$.\n",
"\n",
"\n",
- "$$ \\tilde{y}^{OLS}=\\boldsymbol{X}\\hat{\\beta}^{OLS}=\\sum_{j=1}^p \\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y}$$ and for Ridge we have \n",
+ "But\n",
+ "unless there is enough information available about the process that\n",
+ "generated $X_1,X_2,\\cdots,X_n$, $p(x)$ is in general\n",
+ "unknown. Therefore, [Efron in 1979](https://projecteuclid.org/euclid.aos/1176344552) asked the\n",
+ "question: What if we replace $p(x)$ by the relative frequency\n",
+ "of the observation $X_i$; if we draw observations in accordance with\n",
+ "the relative frequency of the observations, will we obtain the same\n",
+ "result in some asymptotic sense? The answer is yes.\n",
"\n",
- "$$ \\tilde{y}^{Ridge}=\\boldsymbol{X}\\hat{\\beta}^{Ridge}=\\sum_{j=1}^p \\boldsymbol{u}_j\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{u}_j^T\\boldsymbol{y}$$ . \n",
"\n",
- "It is indeed the economy-sized SVD, note the summation runs up tp $$p$$ only and not $$n$$. \n",
+ "Instead of generating the histogram for the relative\n",
+ "frequency of the observation $X_i$, just draw the values\n",
+ "$(X_1^*,X_2^*,\\cdots,X_n^*)$ with replacement from the vector\n",
+ "$\\boldsymbol{X}$. \n",
"\n",
- "Here we have that $$\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T$$, with $$\\Sigma$$ being an $$ n\\times p$$ matrix and $$\\boldsymbol{V}$$ being a $$ p\\times p$$ matrix. We also have assumed here that $$ n > p$$. \n",
+ "\n",
+ "The independent bootstrap works like this: \n",
+ "\n",
+ "1. Draw with replacement $n$ numbers for the observed variables $\\boldsymbol{x} = (x_1,x_2,\\cdots,x_n)$. \n",
+ "\n",
+ "2. Define a vector $\\boldsymbol{x}^*$ containing the values which were drawn from $\\boldsymbol{x}$. \n",
+ "\n",
+ "3. Using the vector $\\boldsymbol{x}^*$ compute $\\widehat{\\theta}^*$ by evaluating $\\widehat \\theta$ under the observations $\\boldsymbol{x}^*$. \n",
+ "\n",
+ "4. Repeat this process $k$ times. \n",
+ "\n",
+ "When you are done, you can draw a histogram of the relative frequency\n",
+ "of $\\widehat \\theta^*$. This is your estimate of the probability\n",
+ "distribution $p(t)$. Using this probability distribution you can\n",
+ "estimate any statistics thereof. In principle you never draw the\n",
+ "histogram of the relative frequency of $\\widehat{\\theta}^*$. Instead\n",
+ "you use the estimators corresponding to the statistic of interest. For\n",
+ "example, if you are interested in estimating the variance of $\\widehat\n",
+ "\\theta$, apply the etsimator $\\widehat \\sigma^2$ to the values\n",
+ "$\\widehat \\theta ^*$.\n",
"\n",
"\n",
"\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "## Ridge and LASSO Regression\n",
- "\n",
- "[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember11.mp4?vrtx=view-as-webpage)\n",
- "\n",
- "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n",
- "our optimization problem is"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "or we can state it as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
- "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "where we have used the definition of a norm-2 vector, that is"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "By minimizing the above equation with respect to the parameters\n",
- "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n",
- "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n",
- "defining a new cost function to be optimized, that is"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
- "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which leads to the Ridge regression minimization problem where we\n",
- "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n",
- "a finite number larger than zero. By defining"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "we have a new optimization equation"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
- "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n",
- "\n",
- "Here we have defined the norm-1 as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Using the matrix-vector expression for Ridge regression,"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "by taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n",
- "a slightly modified matrix inversion problem which for finite values\n",
- "of $\\lambda$ does not suffer from singularity problems. We obtain"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with $t$ a finite positive number. \n",
- "\n",
- "We see that Ridge regression is nothing but the standard\n",
- "OLS with a modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The\n",
- "consequences, in particular for our discussion of the bias-variance tradeoff \n",
- "are rather interesting.\n",
- "\n",
- "Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U} = \\boldsymbol{U}\\boldsymbol{D}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "For Ridge regression this becomes"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$. \n",
- "\n",
- "\n",
- "Since $\\lambda \\geq 0$, it means that compared to OLS, we have"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n",
- "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n",
- "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n",
- "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n",
- "\\sigma_{i+1}$.\n",
- "\n",
- "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom.\n",
- "Actually, calculating the variance of $\\boldsymbol{X}\\boldsymbol{v}_j$ shows that this quantity is equal to $\\sigma_j^2/n$.\n",
- "With a parameter $\\lambda$ we can thus shrink the role of specific parameters. \n",
- "\n",
- "\n",
- "\n",
- "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In this case the standard OLS results in"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "and"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n",
- "the Ridge estimator converges to zero when the hyperparameter goes to\n",
- "infinity.\n",
- "\n",
- "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n",
- "\n",
- "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n",
- "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\n",
- "\n",
- "\n",
- "\n",
- "## A better understanding of regularization\n",
- "\n",
- "The parameter $\\lambda$ that we have introduced in the Ridge (and\n",
- "Lasso as well) regression is often called a regularization parameter\n",
- "or shrinkage parameter. It is common to call it a hyperparameter. What does it mean mathemtically?\n",
- "\n",
- "Here we will first look at how to analyze the difference between the\n",
- "standard OLS equations and the Ridge expressions in terms of a linear\n",
- "algebra analysis using the SVD algorithm. Thereafter, we will link\n",
- "(see the material on the bias-variance tradeoff below) these\n",
- "observation to the statisical analysis of the results. In particular\n",
- "we consider how the variance of the parameters $\\boldsymbol{\\beta}$ is\n",
- "affected by changing the parameter $\\lambda$.\n",
- "\n",
- "\n",
- "We have our design matrix\n",
- " $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. With the SVD we decompose it as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X} = \\boldsymbol{U\\Sigma V^T},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with $\\boldsymbol{U}\\in {\\mathbb{R}}^{n\\times n}$, $\\boldsymbol{\\Sigma}\\in {\\mathbb{R}}^{n\\times p}$\n",
- "and $\\boldsymbol{V}\\in {\\mathbb{R}}^{p\\times p}$.\n",
- "\n",
- "The matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$ are unitary/orthonormal matrices, that is in case the matrices are real we have $\\boldsymbol{U}^T\\boldsymbol{U}=\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ and $\\boldsymbol{V}^T\\boldsymbol{V}=\\boldsymbol{V}\\boldsymbol{V}^T=\\boldsymbol{I}$.\n",
- "\n",
- "\n",
- "\n",
- "## Introducing the Covariance and Correlation functions\n",
- "\n",
- "Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about\n",
- "the definition of the covariance and the correlation function. These are quantities \n",
- "\n",
- "Suppose we have defined two vectors\n",
- "$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
- " \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "where for example"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "With this definition and recalling that the variance is defined as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "we can rewrite the covariance matrix as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
- " \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n",
- " \\end{bmatrix}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The covariance takes values between zero and infinity and may thus\n",
- "lead to problems with loss of numerical precision for particularly\n",
- "large values. It is common to scale the covariance matrix by\n",
- "introducing instead the correlation matrix defined via the so-called\n",
- "correlation function"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]=\\frac{\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}]}{\\sqrt{\\mathrm{var}[\\boldsymbol{x}] \\mathrm{var}[\\boldsymbol{y}]}}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The correlation function is then given by values $\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]\n",
- "\\in [-1,1]$. This avoids eventual problems with too large values. We\n",
- "can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n",
- "and $\\boldsymbol{y}$ as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
- " \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In the above example this is the function we constructed using **pandas**.\n",
- "\n",
- "\n",
- "\n",
- "In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**\n",
- "we defined the design/feature matrix $\\boldsymbol{X}$ as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}=\\begin{bmatrix}\n",
- "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
- "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
- "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
- "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
- "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
- "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ refering to the column numbers and the\n",
- "entries $n$ being the row elements.\n",
- "We can rewrite the design/feature matrix in terms of its column vectors as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with a given vector"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{x}_i^T = \\begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \\dots & \\dots x_{n-1,i}\\end{bmatrix}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "With these definitions, we can now rewrite our $2\\times 2$\n",
- "correaltion/covariance matrix in terms of a moe general design/feature\n",
- "matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$\n",
- "covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i=0,1,\\dots,p-1$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
- "\\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}]\\\\\n",
- "\\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}]\\\\\n",
- "\\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}]\\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\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}]\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "and the correlation matrix"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
- "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}]\\\\\n",
- "\\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}]\\\\\n",
- "\\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}]\\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\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\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The Numpy function **np.cov** calculates the covariance elements using\n",
- "the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n",
- "the exact mean values. The following simple function uses the\n",
- "**np.vstack** function which takes each vector of dimension $1\\times n$\n",
- "and produces a $2\\times n$ matrix $\\boldsymbol{W}$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{W} = \\begin{bmatrix} x_0 & y_0 \\\\\n",
- " x_1 & y_1 \\\\\n",
- " x_2 & y_2\\\\\n",
- " \\dots & \\dots \\\\\n",
- " x_{n-2} & y_{n-2}\\\\\n",
- " x_{n-1} & y_{n-1} & \n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which in turn is converted into into the $2\\times 2$ covariance matrix\n",
- "$\\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate\n",
- "the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n",
- "function **np.mean(x)**. We can also extract the eigenvalues of the\n",
- "covariance matrix through the **np.linalg.eig()** function."
+ "The following code starts with a Gaussian distribution with mean value\n",
+ "$\\mu =100$ and variance $\\sigma=15$. We use this to generate the data\n",
+ "used in the bootstrap analysis. The bootstrap analysis returns a data\n",
+ "set after a given number of bootstrap operations (as many as we have\n",
+ "data points). This data set consists of estimated mean values for each\n",
+ "bootstrap operation. The histogram generated by the bootstrap method\n",
+ "shows that the distribution for these mean values is also a Gaussian,\n",
+ "centered around the mean value $\\mu=100$ but with standard deviation\n",
+ "$\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in\n",
+ "this case the same as the number of original data points). The value\n",
+ "of the standard deviation is what we expect from the central limit\n",
+ "theorem."
]
},
{
@@ -1146,346 +544,857 @@
"name": "stdout",
"output_type": "stream",
"text": [
- "-0.008885578722629236\n",
- "3.7522047280566193\n",
- "[[0.8520127 2.59480085]\n",
- " [2.59480085 8.99218987]]\n"
+ "Runtime: 2.40859 sec\n",
+ "Bootstrap Statistics :\n",
+ "original bias std. error\n",
+ " 100.148 14.7733 100.151 0.147722\n"
]
+ },
+ {
+ "ename": "AttributeError",
+ "evalue": "'Rectangle' object has no property 'normed'",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
+ "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 31\u001b[0m \u001b[0mt\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mbootstrap\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstat\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdatapoints\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 32\u001b[0m \u001b[0;31m# the histogram of the bootstrapped data\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 33\u001b[0;31m \u001b[0mn\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbinsboot\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpatches\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mplt\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mhist\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mt\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m50\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnormed\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfacecolor\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'red'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0malpha\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m0.75\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 34\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 35\u001b[0m \u001b[0;31m# add a 'best fit' line\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
+ "\u001b[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/pyplot.py\u001b[0m in \u001b[0;36mhist\u001b[0;34m(x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, data, **kwargs)\u001b[0m\n\u001b[1;32m 2683\u001b[0m \u001b[0morientation\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'vertical'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mrwidth\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mlog\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcolor\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2684\u001b[0m label=None, stacked=False, *, data=None, **kwargs):\n\u001b[0;32m-> 2685\u001b[0;31m return gca().hist(\n\u001b[0m\u001b[1;32m 2686\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbins\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mbins\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mrange\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdensity\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mdensity\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mweights\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mweights\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2687\u001b[0m \u001b[0mcumulative\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mcumulative\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbottom\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mbottom\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mhisttype\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mhisttype\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
+ "\u001b[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/__init__.py\u001b[0m in \u001b[0;36minner\u001b[0;34m(ax, data, *args, **kwargs)\u001b[0m\n\u001b[1;32m 1445\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0minner\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0max\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdata\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1446\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mdata\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1447\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mfunc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0max\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0mmap\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msanitize_sequence\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0margs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1448\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1449\u001b[0m \u001b[0mbound\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mnew_sig\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mbind\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0max\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
+ "\u001b[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/axes/_axes.py\u001b[0m in \u001b[0;36mhist\u001b[0;34m(self, x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs)\u001b[0m\n\u001b[1;32m 6813\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mpatch\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6814\u001b[0m \u001b[0mp\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mpatch\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 6815\u001b[0;31m \u001b[0mp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mupdate\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 6816\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mlbl\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6817\u001b[0m \u001b[0mp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mset_label\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlbl\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
+ "\u001b[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/artist.py\u001b[0m in \u001b[0;36mupdate\u001b[0;34m(self, props)\u001b[0m\n\u001b[1;32m 994\u001b[0m \u001b[0mfunc\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mgetattr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34mf\"set_{k}\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 995\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mcallable\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfunc\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 996\u001b[0;31m raise AttributeError(f\"{type(self).__name__!r} object \"\n\u001b[0m\u001b[1;32m 997\u001b[0m f\"has no property {k!r}\")\n\u001b[1;32m 998\u001b[0m \u001b[0mret\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfunc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mv\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
+ "\u001b[0;31mAttributeError\u001b[0m: 'Rectangle' object has no property 'normed'"
+ ]
+ },
+ {
+ "data": {
+ "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYIAAAD6CAYAAACs/ECRAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/Il7ecAAAACXBIWXMAAAsTAAALEwEAmpwYAAATaUlEQVR4nO3df6zdd33f8eeLhNCSdjg/bi1ju3U0PCpUiSRcgVk7RvFAJGnraCsR0ba4mTvvR1bBOqm406YNwR/OtI0m2pTVwnRO1QZCCotLM0ZmQG21JuUGUpPEgThpMttz4tsQzErUtXTv/XE+Lifede65955zf/jzfEhH5/P9fD/f7/l8fI7P635/nlQVkqR+vWKlOyBJWlkGgSR1ziCQpM4ZBJLUOYNAkjpnEEhS5+YNgiSvT/Lw0ONbSd6f5NIk9yd5oj1f0tonye1JjiY5nOTqyQ9DkrRYWch1BEkuAE4AbwFuAb5RVXuT7AEuqaoPJLkW+Dng2tbutqp6y8ut9/LLL68tW7YscgiS1KeHHnroj6pqaqnruXCB7bcDT1bVM0l2AG9v9QeALwIfAHYAd9YgYR5Isi7Jhqo6ea6VbtmyhZmZmQV3XpJ6luSZcaxnoccI3gvc1crrh77cnwXWt/JG4NjQMsdbnSRpFRo5CJJcBPwU8Mmz57W//hd0r4oku5PMJJmZnZ1dyKKSpDFayBbBNcCXq+q5Nv1ckg0A7flUqz8BbB5ablOre4mq2ldV01U1PTW15F1ckqRFWkgQ3Mh3dwsBHAR2tvJO4N6h+pva2UPbgNMvd3xAkrSyRjpYnORi4J3APxiq3gvcnWQX8AxwQ6u/j8EZQ0eBF4Gbx9ZbSdLYjRQEVfVt4LKz6p5ncBbR2W2LwamlkqQ1wCuLJalzBoEkdc4gkKTOLfTKYmlN27Lnt+asf3rvdcvcE2n1cItAkjpnEEhS5wwCSeqcQSBJnTMIJKlzBoEkdc4gkKTOGQSS1DmDQJI655XFEl5xrL65RSBJnTMIJKlzBoEkdc4gkKTOGQSS1DnPGtJ56VxnAY1zPZ5RpPOFWwSS1DmDQJI6N1IQJFmX5J4kjyc5kuStSS5Ncn+SJ9rzJa1tktye5GiSw0munuwQJElLMeoWwW3AZ6vqh4E3AkeAPcChqtoKHGrTANcAW9tjN3DHWHssSRqreYMgyWuAtwH7AarqT6vqm8AO4EBrdgC4vpV3AHfWwAPAuiQbxtxvSdKYjLJFcAUwC/xKkq8k+WiSi4H1VXWytXkWWN/KG4FjQ8sfb3WSpFVolCC4ELgauKOqrgK+zXd3AwFQVQXUQl44ye4kM0lmZmdnF7KoJGmMRgmC48DxqnqwTd/DIBieO7PLpz2favNPAJuHlt/U6l6iqvZV1XRVTU9NTS22/5KkJZo3CKrqWeBYkte3qu3AY8BBYGer2wnc28oHgZva2UPbgNNDu5AkSavMqFcW/xzwa0kuAp4CbmYQIncn2QU8A9zQ2t4HXAscBV5sbSVJq9RIQVBVDwPTc8zaPkfbAm5ZWrckScvFK4slqXPedE5r2rhuLif1zC0CSeqcQSBJnTMIJKlzBoEkdc4gkKTOGQSS1DmDQJI6ZxBIUue8oEwas3Nd5Pb03uuWuSfSaNwikKTOGQSS1Dl3DUmL5H2OdL5wi0CSOmcQSFLnDAJJ6pzHCLQmuD9emhy3CCSpcwaBJHXOIJCkzhkEktS5kYIgydNJvprk4SQzre7SJPcneaI9X9Lqk+T2JEeTHE5y9SQHIElamoVsEfx4VV1ZVdNteg9wqKq2AofaNMA1wNb22A3cMa7OSpLGbym7hnYAB1r5AHD9UP2dNfAAsC7JhiW8jiRpgkYNggI+l+ShJLtb3fqqOtnKzwLrW3kjcGxo2eOt7iWS7E4yk2RmdnZ2EV2XJI3DqBeU/VhVnUjyA8D9SR4fnllVlaQW8sJVtQ/YBzA9Pb2gZaW1yN8p0Go10hZBVZ1oz6eATwNvBp47s8unPZ9qzU8Am4cW39TqJEmr0LxBkOTiJN9/pgy8C3gEOAjsbM12Ave28kHgpnb20Dbg9NAuJEnSKjPKrqH1wKeTnGn/61X12SRfAu5Osgt4Brihtb8PuBY4CrwI3Dz2XkuSxmbeIKiqp4A3zlH/PLB9jvoCbhlL7yRJE+fdR6UV5kFkrTSDQKuKt5uWlp/3GpKkzhkEktQ5g0CSOmcQSFLnDAJJ6pxBIEmdMwgkqXMGgSR1ziCQpM4ZBJLUOYNAkjpnEEhS5wwCSeqcQSBJnTMIJKlz/h6BtEr5gzVaLm4RSFLnDAJJ6pxBIEmdGzkIklyQ5CtJPtOmr0jyYJKjST6R5KJW/6o2fbTN3zKhvkuSxmAhWwTvA44MTd8KfKSqXge8AOxq9buAF1r9R1o7SdIqNVIQJNkEXAd8tE0HeAdwT2tyALi+lXe0adr87a29JGkVGnWL4JeAXwD+b5u+DPhmVX2nTR8HNrbyRuAYQJt/urWXJK1C8wZBkp8ATlXVQ+N84SS7k8wkmZmdnR3nqiVJCzDKFsGPAj+V5Gng4wx2Cd0GrEty5oK0TcCJVj4BbAZo818DPH/2SqtqX1VNV9X01NTUkgYhSVq8eYOgqn6xqjZV1RbgvcDnq+pvA18Afro12wnc28oH2zRt/uerqsbaa0nS2CzlOoIPAD+f5CiDYwD7W/1+4LJW//PAnqV1UZI0SQu611BVfRH4Yis/Bbx5jjZ/ArxnDH2TJC0DryyWpM5591GtiHPdWVPS8nOLQJI6ZxBIUucMAknqnEEgSZ0zCCSpcwaBJHXOIJCkzhkEktQ5g0CSOueVxdIac66rsp/ee90y90TnC7cIJKlzBoEkdc4gkKTOeYxAE+VdRqXVzy0CSeqcQSBJnTMIJKlzBoEkdc4gkKTOGQSS1Ll5gyDJ9yT5/SR/kOTRJB9s9VckeTDJ0SSfSHJRq39Vmz7a5m+Z8BgkSUswyhbB/wHeUVVvBK4E3p1kG3Ar8JGqeh3wArCrtd8FvNDqP9LaSZJWqXmDoAb+uE2+sj0KeAdwT6s/AFzfyjvaNG3+9iQZV4clSeM10jGCJBckeRg4BdwPPAl8s6q+05ocBza28kbgGECbfxq4bIx9liSN0UhBUFV/XlVXApuANwM/vNQXTrI7yUySmdnZ2aWuTpK0SAs6a6iqvgl8AXgrsC7JmXsVbQJOtPIJYDNAm/8a4Pk51rWvqqaranpqampxvZckLdkoZw1NJVnXyt8LvBM4wiAQfro12wnc28oH2zRt/uerqsbYZ0nSGI1y99ENwIEkFzAIjrur6jNJHgM+nuTDwFeA/a39fuBXkxwFvgG8dwL9liSNybxBUFWHgavmqH+KwfGCs+v/BHjPWHonSZo4f49AY+HvDkhrl7eYkKTOGQSS1DmDQJI6ZxBIUuc8WCydJ851wP7pvdctc0+01rhFIEmdMwgkqXMGgSR1ziCQpM4ZBJLUOYNAkjpnEEhS5wwCSeqcQSBJnTMIJKlzBoEkdc57DWlB/AGatcd7EGk+bhFIUucMAknqnEEgSZ0zCCSpc/MGQZLNSb6Q5LEkjyZ5X6u/NMn9SZ5oz5e0+iS5PcnRJIeTXD3pQUiSFm+ULYLvAP+sqt4AbANuSfIGYA9wqKq2AofaNMA1wNb22A3cMfZeS5LGZt4gqKqTVfXlVv7fwBFgI7ADONCaHQCub+UdwJ018ACwLsmGcXdckjQeCzpGkGQLcBXwILC+qk62Wc8C61t5I3BsaLHjre7sde1OMpNkZnZ2dqH9liSNychBkOT7gN8A3l9V3xqeV1UF1EJeuKr2VdV0VU1PTU0tZFFJ0hiNFARJXskgBH6tqj7Vqp87s8unPZ9q9SeAzUOLb2p1kqRVaJSzhgLsB45U1b8fmnUQ2NnKO4F7h+pvamcPbQNOD+1CkiStMqPca+hHgb8LfDXJw63unwN7gbuT7AKeAW5o8+4DrgWOAi8CN4+zw5Kk8Zo3CKrqd4GcY/b2OdoXcMsS+yVJWiZeWSxJnfM21JqTt5s+/3l7ap3hFoEkdc4gkKTOGQSS1DmDQJI6ZxBIUucMAknqnEEgSZ0zCCSpcwaBJHXOIJCkzhkEktQ5g0CSOmcQSFLnDAJJ6pxBIEmdMwgkqXP+ME3H/PEZzcUfrOmPWwSS1Dm3CDrgX/6SXs68QZDkY8BPAKeq6kda3aXAJ4AtwNPADVX1QpIAtwHXAi8CP1NVX55M1yUtp5f7g8LdRmvbKLuG/jPw7rPq9gCHqmorcKhNA1wDbG2P3cAd4+mmJGlS5g2Cqvpt4BtnVe8ADrTyAeD6ofo7a+ABYF2SDWPqqyRpAhZ7sHh9VZ1s5WeB9a28ETg21O54q5MkrVJLPmuoqgqohS6XZHeSmSQzs7OzS+2GJGmRFhsEz53Z5dOeT7X6E8DmoXabWt3/p6r2VdV0VU1PTU0tshuSpKVabBAcBHa28k7g3qH6mzKwDTg9tAtJkrQKjXL66F3A24HLkxwH/hWwF7g7yS7gGeCG1vw+BqeOHmVw+ujNE+izJGmM5g2CqrrxHLO2z9G2gFuW2ilJ0vLxFhOS1DmDQJI6572GziPeU0jSYrhFIEmdMwgkqXPuGpK0ZP6YzdrmFoEkdc4gkKTOGQSS1DmPEaxBniYqaZzcIpCkzhkEktQ5g0CSOmcQSFLnDAJJ6pxnDa1inh2ktW6hn2GvRF4ZBsEq4Be+pJXkriFJ6pxbBJJWDW9etzIMAkmrngExWe4akqTOGQSS1LmJ7BpK8m7gNuAC4KNVtXcSr7PWeHaQNF7uMhqPsQdBkguA/wi8EzgOfCnJwap6bNyvtVr5hS+tLANiYSaxRfBm4GhVPQWQ5OPADuC8CwK/8KXzQ+/BMYkg2AgcG5o+DrxlAq8DLPwN9Mtb6tdC//+PMyBWc9is2OmjSXYDu9vkHyf52ljXfysAlwN/NM71rqDzaSzgeFaz82ksMIHxtO+XlVrX8Hh+aBx9mEQQnAA2D01vanUvUVX7gH0TeP2/kGSmqqYn+RrL5XwaCzie1ex8Ggs4nlFM4vTRLwFbk1yR5CLgvcDBCbyOJGkMxr5FUFXfSfJPgP/G4PTRj1XVo+N+HUnSeEzkGEFV3QfcN4l1L9BEdz0ts/NpLOB4VrPzaSzgeOaVqhr3OiVJa4i3mJCkzq3JIEjyviSPJHk0yftb3RuT/F6Sryb5zSR/6RzLrktyT5LHkxxJ8tZl7fzcfVrKeP5pW+6RJHcl+Z5l7fygDx9LcirJI0N1lya5P8kT7fmSVp8ktyc5muRwkqvPsc43tbEfbe2zVseT5NVJfqt95h5Nsmy3XJnEezO0noPD610OE/qsXZRkX5Kvt/fob63x8dzY/u8cTvLZJJfP25GqWlMP4EeAR4BXMzjG8d+B1zE4W+mvtzZ/D/jQOZY/APxsK18ErFur42Fw8d4fAt/bpu8GfmYFxvA24GrgkaG6fwPsaeU9wK2tfC3wX4EA24AHz7HO32/z09pfs1bH097bHx/6zP3Oco1nEu9Na/s3gV8fXu9aHQ/wQeDDrfwK4PK1Op72HXLqzBjauv71vP1YzjdxTP9w7wH2D03/S+AXgNN895jHZuCxOZZ9TfvizEqPY0zjOXMV96XtA/AZ4F0rNI4tZ32YvwZsaOUNwNda+ZeBG+dqN1S3AXh8aPpG4JfX6njmWPdtwN9fq2MBvg/4XeANLHMQTGg8x4CLl3sckxgP8EpglsGFZgH+E7B7vj6sxV1DjwB/LcllSV7NICU3A48yuKcRDL5cN8+x7BUM/pF+JclXknw0ycXL0emXsejxVNUJ4N8C/xM4CZyuqs8tS6/nt76qTrbys8D6Vp7rFiQbz1p2Y6t/uTbLbSnj+QtJ1gE/CRyaQB9HtdSxfAj4d8CLE+vhwix6PO39APhQki8n+WSS9aysRY+nqv4M+EfAV4H/xSCs98/3gmsuCKrqCHAr8Dngs8DDwJ8z2H3yj5M8BHw/8KdzLH4hg82wO6rqKuDbDDa9VsxSxtP2He5gEHCvBS5O8neWp+ejq8GfKufN6WmLHU+SC4G7gNur3ZRxpS10LEmuBP5yVX16Yp1agkW8NxcyuPvB/6iqq4HfY/DH1aqwiPfnlQyC4CoG3wmHgV+cb7k1FwQAVbW/qt5UVW8DXgC+XlWPV9W7qupNDP6zPTnHoseB41X1YJu+h0EwrKgljOdvAH9YVbPtL4FPAX91+Xr+sp5LsgGgPZ9q9aPcguREq3+5NsttKeM5Yx/wRFX90qQ6OaKljOWtwHSSpxnsHvorSb440d7ObynjeZ7Bls2n2vQnWfnvhKWM50qAqnqyhcjdjPCdsCaDIMkPtOcfpB20Gqp7BfAvGOwbe4mqehY4luT1rWo7q+D22IsdD4NdQtvaWSlhMJ4jy9PreR0EdrbyTuDeofqb2hkQ2xjszjo5vGCb/laSbW1cNw0tv1IWPR6AJB9mcIzq/cvQ1/ks5b25o6peW1VbgB9j8EfL25en2+e0lPEU8JvA21vVavhOWMpn7QTwhiRTbfqdjPKdsFIHSJZ4cOV3GLxZfwBsb3XvA77eHnv57oHW1wL3DS17JTDDYJPpvwCXrPHxfBB4nMGxhl8FXrUC/b+LwTGKP2Ow1bULuIzBfvAnGJwJdWlrGwY/XPQkg/2Y00PreXioPN3G9CTwH1jGA/zjHg+Dv9yq/Yd8uD1+di2O5ax1b2H5zxqaxGfth4Dfbt8Jh4AfXOPj+Yfts3aYQchdNl8/vLJYkjq3JncNSZLGxyCQpM4ZBJLUOYNAkjpnEEhS5wwCSeqcQSBJnTMIJKlz/w96PpEQZR0rUwAAAABJRU5ErkJggg==\n",
+ "text/plain": [
+ ""
+ ]
+ },
+ "metadata": {
+ "filenames": {
+ "image/png": "/Users/mhjensen/Teaching/MachineLearning/doc/LectureNotes/_build/jupyter_execute/chapter3_25_2.png"
+ },
+ "needs_background": "light"
+ },
+ "output_type": "display_data"
}
],
"source": [
- "# Importing various packages\n",
- "import numpy as np\n",
- "n = 100\n",
- "x = np.random.normal(size=n)\n",
- "print(np.mean(x))\n",
- "y = 4+3*x+np.random.normal(size=n)\n",
- "print(np.mean(y))\n",
- "W = np.vstack((x, y))\n",
- "C = np.cov(W)\n",
- "print(C)"
+ "%matplotlib inline\n",
+ "\n",
+ "from numpy import *\n",
+ "from numpy.random import randint, randn\n",
+ "from time import time\n",
+ "import matplotlib.mlab as mlab\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "# Returns mean of bootstrap samples \n",
+ "def stat(data):\n",
+ " return mean(data)\n",
+ "\n",
+ "# Bootstrap algorithm\n",
+ "def bootstrap(data, statistic, R):\n",
+ " t = zeros(R); n = len(data); inds = arange(n); t0 = time()\n",
+ " # non-parametric bootstrap \n",
+ " for i in range(R):\n",
+ " t[i] = statistic(data[randint(0,n,n)])\n",
+ "\n",
+ " # analysis \n",
+ " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Bootstrap Statistics :\")\n",
+ " print(\"original bias std. error\")\n",
+ " print(\"%8g %8g %14g %15g\" % (statistic(data), std(data),mean(t),std(t)))\n",
+ " return t\n",
+ "\n",
+ "\n",
+ "mu, sigma = 100, 15\n",
+ "datapoints = 10000\n",
+ "x = mu + sigma*random.randn(datapoints)\n",
+ "# bootstrap returns the data sample \n",
+ "t = bootstrap(x, stat, datapoints)\n",
+ "# the histogram of the bootstrapped data \n",
+ "n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)\n",
+ "\n",
+ "# add a 'best fit' line \n",
+ "y = mlab.normpdf( binsboot, mean(t), std(t))\n",
+ "lt = plt.plot(binsboot, y, 'r--', linewidth=1)\n",
+ "plt.xlabel('Smarts')\n",
+ "plt.ylabel('Probability')\n",
+ "plt.axis([99.5, 100.6, 0, 3.0])\n",
+ "plt.grid(True)\n",
+ "\n",
+ "plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "The previous example can be converted into the correlation matrix by\n",
- "simply scaling the matrix elements with the variances. We should also\n",
- "subtract the mean values for each column. This leads to the following\n",
- "code which sets up the correlations matrix for the previous example in\n",
- "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)."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "0.06619182206626131\n",
- "2.1914224774238273\n",
- "[[1. 0.70589906]\n",
- " [0.70589906 1. ]]\n"
- ]
- }
- ],
- "source": [
- "import numpy as np\n",
- "n = 100\n",
- "# define two vectors \n",
- "x = np.random.random(size=n)\n",
- "y = 4+3*x+np.random.normal(size=n)\n",
- "#scaling the x and y vectors \n",
- "x = x - np.mean(x)\n",
- "y = y - np.mean(y)\n",
- "variance_x = np.sum(x@x)/n\n",
- "variance_y = np.sum(y@y)/n\n",
- "print(variance_x)\n",
- "print(variance_y)\n",
- "cov_xy = np.sum(x@y)/n\n",
- "cov_xx = np.sum(x@x)/n\n",
- "cov_yy = np.sum(y@y)/n\n",
- "C = np.zeros((2,2))\n",
- "C[0,0]= cov_xx/variance_x\n",
- "C[1,1]= cov_yy/variance_y\n",
- "C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n",
- "C[1,0]= C[0,1]\n",
- "print(C)"
+ "## Various steps in cross-validation\n",
+ "\n",
+ "When the repetitive splitting of the data set is done randomly,\n",
+ "samples may accidently end up in a fast majority of the splits in\n",
+ "either training or test set. Such samples may have an unbalanced\n",
+ "influence on either model building or prediction evaluation. To avoid\n",
+ "this $k$-fold cross-validation structures the data splitting. The\n",
+ "samples are divided into $k$ more or less equally sized exhaustive and\n",
+ "mutually exclusive subsets. In turn (at each split) one of these\n",
+ "subsets plays the role of the test set while the union of the\n",
+ "remaining subsets constitutes the training set. Such a splitting\n",
+ "warrants a balanced representation of each sample in both training and\n",
+ "test set over the splits. Still the division into the $k$ subsets\n",
+ "involves a degree of randomness. This may be fully excluded when\n",
+ "choosing $k=n$. This particular case is referred to as leave-one-out\n",
+ "cross-validation (LOOCV). \n",
+ "\n",
+ "\n",
+ "* Define a range of interest for the penalty parameter.\n",
+ "\n",
+ "* Divide the data set into training and test set comprising samples $\\{1, \\ldots, n\\} \\setminus i$ and $\\{ i \\}$, respectively.\n",
+ "\n",
+ "* Fit the linear regression model by means of ridge estimation for each $\\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\\boldsymbol{\\sigma}_{-i}^2(\\lambda)$, as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "We see that the matrix elements along the diagonal are one as they\n",
- "should be and that the matrix is symmetric. Furthermore, diagonalizing\n",
- "this matrix we easily see that it is a positive definite matrix.\n",
- "\n",
- "The above procedure with **numpy** can be made more compact if we use **pandas**.\n",
- "\n",
- "\n",
- "We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "[[ 0.03067028 0.91697817]\n",
- " [-0.10806972 -2.26381865]\n",
- " [ 0.69519693 3.02968834]\n",
- " [-0.07521771 -0.93273404]\n",
- " [-0.25910749 -0.58239999]\n",
- " [ 0.25450941 0.36941772]\n",
- " [-1.65002433 -6.09672604]\n",
- " [ 0.58596975 2.19955871]\n",
- " [ 0.54121682 2.30685416]\n",
- " [-0.01514394 1.05318162]]\n",
- " 0 1\n",
- "0 0.030670 0.916978\n",
- "1 -0.108070 -2.263819\n",
- "2 0.695197 3.029688\n",
- "3 -0.075218 -0.932734\n",
- "4 -0.259107 -0.582400\n",
- "5 0.254509 0.369418\n",
- "6 -1.650024 -6.096726\n",
- "7 0.585970 2.199559\n",
- "8 0.541217 2.306854\n",
- "9 -0.015144 1.053182\n",
- " 0 1\n",
- "0 1.000000 0.948729\n",
- "1 0.948729 1.000000\n"
- ]
- }
- ],
- "source": [
- "import numpy as np\n",
- "import pandas as pd\n",
- "n = 10\n",
- "x = np.random.normal(size=n)\n",
- "x = x - np.mean(x)\n",
- "y = 4+3*x+np.random.normal(size=n)\n",
- "y = y - np.mean(y)\n",
- "X = (np.vstack((x, y))).T\n",
- "print(X)\n",
- "Xpd = pd.DataFrame(X)\n",
- "print(Xpd)\n",
- "correlation_matrix = Xpd.corr()\n",
- "print(correlation_matrix)"
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\boldsymbol{\\beta}_{-i}(\\lambda) & = ( \\boldsymbol{X}_{-i, \\ast}^{T}\n",
+ "\\boldsymbol{X}_{-i, \\ast} + \\lambda \\boldsymbol{I}_{pp})^{-1}\n",
+ "\\boldsymbol{X}_{-i, \\ast}^{T} \\boldsymbol{y}_{-i}\n",
+ "\\end{align*}\n",
+ "$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "We expand this model to the Franke function discussed above."
+ "* Evaluate the prediction performance of these models on the test set by $\\log\\{L[y_i, \\boldsymbol{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}$. Or, by the prediction error $|y_i - \\boldsymbol{X}_{i, \\ast} \\boldsymbol{\\beta}_{-i}(\\lambda)|$, the relative error, the error squared or the R2 score function.\n",
+ "\n",
+ "* Repeat the first three steps such that each sample plays the role of the test set once.\n",
+ "\n",
+ "* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\frac{1}{n} \\sum_{i = 1}^n \\log\\{L[y_i, \\mathbf{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}.\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For the various values of $k$\n",
+ "\n",
+ "1. shuffle the dataset randomly.\n",
+ "\n",
+ "2. Split the dataset into $k$ groups.\n",
+ "\n",
+ "3. For each unique group:\n",
+ "\n",
+ "a. Decide which group to use as set for test data\n",
+ "\n",
+ "b. Take the remaining groups as a training data set\n",
+ "\n",
+ "c. Fit a model on the training set and evaluate it on the test set\n",
+ "\n",
+ "d. Retain the evaluation score and discard the model\n",
+ "\n",
+ "\n",
+ "5. Summarize the model using the sample of model evaluation scores\n",
+ "\n",
+ "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial."
]
},
{
"cell_type": "code",
- "execution_count": 5,
+ "execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- " 0 1 2 3 4 5 6 7 \\\n",
- "0 0.0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 \n",
- "1 0.0 0.082990 0.084167 0.081514 0.081402 0.081260 0.071681 0.071684 \n",
- "2 0.0 0.084167 0.086116 0.083128 0.083376 0.083577 0.073602 0.073851 \n",
- "3 0.0 0.081514 0.083128 0.084873 0.085285 0.085676 0.077469 0.077891 \n",
- "4 0.0 0.081402 0.083376 0.085285 0.085951 0.086592 0.078311 0.078930 \n",
- "5 0.0 0.081260 0.083577 0.085676 0.086592 0.087482 0.079139 0.079956 \n",
- "6 0.0 0.071681 0.073602 0.077469 0.078311 0.079139 0.072620 0.073372 \n",
- "7 0.0 0.071684 0.073851 0.077891 0.078930 0.079956 0.073372 0.074286 \n",
- "8 0.0 0.071761 0.074170 0.078388 0.079624 0.080845 0.074191 0.075266 \n",
- "9 0.0 0.071917 0.074568 0.078966 0.080398 0.081816 0.075084 0.076320 \n",
- "10 0.0 0.062188 0.064304 0.069005 0.070131 0.071248 0.065994 0.066963 \n",
- "11 0.0 0.062376 0.064686 0.069528 0.070815 0.072094 0.066761 0.067865 \n",
- "12 0.0 0.062639 0.065144 0.070129 0.071579 0.073020 0.067601 0.068840 \n",
- "13 0.0 0.062979 0.065680 0.070812 0.072424 0.074027 0.068514 0.069890 \n",
- "14 0.0 0.063395 0.066294 0.071576 0.073352 0.075119 0.069503 0.071016 \n",
- "\n",
- " 8 9 10 11 12 13 14 \n",
- "0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 \n",
- "1 0.071761 0.071917 0.062188 0.062376 0.062639 0.062979 0.063395 \n",
- "2 0.074170 0.074568 0.064304 0.064686 0.065144 0.065680 0.066294 \n",
- "3 0.078388 0.078966 0.069005 0.069528 0.070129 0.070812 0.071576 \n",
- "4 0.079624 0.080398 0.070131 0.070815 0.071579 0.072424 0.073352 \n",
- "5 0.080845 0.081816 0.071248 0.072094 0.073020 0.074027 0.075119 \n",
- "6 0.074191 0.075084 0.065994 0.066761 0.067601 0.068514 0.069503 \n",
- "7 0.075266 0.076320 0.066963 0.067865 0.068840 0.069890 0.071016 \n",
- "8 0.076408 0.077623 0.067990 0.069028 0.070138 0.071325 0.072589 \n",
- "9 0.077623 0.079001 0.069081 0.070254 0.071502 0.072826 0.074230 \n",
- "10 0.067990 0.069081 0.060919 0.061842 0.062829 0.063882 0.065003 \n",
- "11 0.069028 0.070254 0.061842 0.062879 0.063982 0.065151 0.066389 \n",
- "12 0.070138 0.071502 0.062829 0.063982 0.065200 0.066487 0.067844 \n",
- "13 0.071325 0.072826 0.063882 0.065151 0.066487 0.067892 0.069369 \n",
- "14 0.072589 0.074230 0.065003 0.066389 0.067844 0.069369 0.070967 \n"
- ]
- }
- ],
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import KFold\n",
+ "from sklearn.linear_model import Ridge\n",
+ "from sklearn.model_selection import cross_val_score\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "np.random.seed(3155)\n",
+ "\n",
+ "# Generate the data.\n",
+ "nsamples = 100\n",
+ "x = np.random.randn(nsamples)\n",
+ "y = 3*x**2 + np.random.randn(nsamples)\n",
+ "\n",
+ "## Cross-validation on Ridge regression using KFold only\n",
+ "\n",
+ "# Decide degree on polynomial to fit\n",
+ "poly = PolynomialFeatures(degree = 6)\n",
+ "\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 500\n",
+ "lambdas = np.logspace(-3, 5, nlambdas)\n",
+ "\n",
+ "# Initialize a KFold instance\n",
+ "k = 5\n",
+ "kfold = KFold(n_splits = k)\n",
+ "\n",
+ "# Perform the cross-validation to estimate MSE\n",
+ "scores_KFold = np.zeros((nlambdas, k))\n",
+ "\n",
+ "i = 0\n",
+ "for lmb in lambdas:\n",
+ " ridge = Ridge(alpha = lmb)\n",
+ " j = 0\n",
+ " for train_inds, test_inds in kfold.split(x):\n",
+ " xtrain = x[train_inds]\n",
+ " ytrain = y[train_inds]\n",
+ "\n",
+ " xtest = x[test_inds]\n",
+ " ytest = y[test_inds]\n",
+ "\n",
+ " Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n",
+ " ridge.fit(Xtrain, ytrain[:, np.newaxis])\n",
+ "\n",
+ " Xtest = poly.fit_transform(xtest[:, np.newaxis])\n",
+ " ypred = ridge.predict(Xtest)\n",
+ "\n",
+ " scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n",
+ "\n",
+ " j += 1\n",
+ " i += 1\n",
+ "\n",
+ "\n",
+ "estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n",
+ "\n",
+ "## Cross-validation using cross_val_score from sklearn along with KFold\n",
+ "\n",
+ "# kfold is an instance initialized above as:\n",
+ "# kfold = KFold(n_splits = k)\n",
+ "\n",
+ "estimated_mse_sklearn = np.zeros(nlambdas)\n",
+ "i = 0\n",
+ "for lmb in lambdas:\n",
+ " ridge = Ridge(alpha = lmb)\n",
+ "\n",
+ " X = poly.fit_transform(x[:, np.newaxis])\n",
+ " estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n",
+ "\n",
+ " # cross_val_score return an array containing the estimated negative mse for every fold.\n",
+ " # we have to the the mean of every array in order to get an estimate of the mse of the model\n",
+ " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n",
+ "\n",
+ " i += 1\n",
+ "\n",
+ "## Plot and compare the slightly different ways to perform cross-validation\n",
+ "\n",
+ "plt.figure()\n",
+ "\n",
+ "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n",
+ "plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n",
+ "\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('mse')\n",
+ "\n",
+ "plt.legend()\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## The bias-variance tradeoff\n",
+ "\n",
+ "\n",
+ "We will discuss the bias-variance tradeoff in the context of\n",
+ "continuous predictions such as regression. However, many of the\n",
+ "intuitions and ideas discussed here also carry over to classification\n",
+ "tasks. Consider a dataset $\\mathcal{L}$ consisting of the data\n",
+ "$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$. \n",
+ "\n",
+ "Let us assume that the true data is generated from a noisy model"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\epsilon$ is normally distributed with mean zero and standard deviation $\\sigma^2$.\n",
+ "\n",
+ "In our derivation of the ordinary least squares method we defined then\n",
+ "an approximation to the function $f$ in terms of the parameters\n",
+ "$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n",
+ "that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$. \n",
+ "\n",
+ "Thereafter we found the parameters $\\boldsymbol{\\beta}$ by optimizing the means squared error via the so-called cost function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can rewrite this as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\frac{1}{n}\\sum_i(f_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\sigma^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The three terms represent the square of the bias of the learning\n",
+ "method, which can be thought of as the error caused by the simplifying\n",
+ "assumptions built into the method. The second term represents the\n",
+ "variance of the chosen model and finally the last terms is variance of\n",
+ "the error $\\boldsymbol{\\epsilon}$.\n",
+ "\n",
+ "To derive this equation, we need to recall that the variance of $\\boldsymbol{y}$ and $\\boldsymbol{\\epsilon}$ are both equal to $\\sigma^2$. The mean value of $\\boldsymbol{\\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\\boldsymbol{\\tilde{y}}$.\n",
+ "We use a more compact notation in terms of the expectation value"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}})^2\\right],\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and adding and subtracting $\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]$ we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}}+\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right],\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which, using the abovementioned expectation values can be rewritten as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right]+\\mathrm{Var}\\left[\\boldsymbol{\\tilde{y}}\\right]+\\sigma^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "that is the rewriting in terms of the so-called bias, the variance of the model $\\boldsymbol{\\tilde{y}}$ and the variance of $\\boldsymbol{\\epsilon}$."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.pipeline import make_pipeline\n",
+ "from sklearn.utils import resample\n",
+ "\n",
+ "np.random.seed(2018)\n",
+ "\n",
+ "n = 500\n",
+ "n_boostraps = 100\n",
+ "degree = 18 # A quite high value, just to show.\n",
+ "noise = 0.1\n",
+ "\n",
+ "# Make data set.\n",
+ "x = np.linspace(-1, 3, n).reshape(-1, 1)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)\n",
+ "\n",
+ "# Hold out some test data that is never used in training.\n",
+ "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
+ "\n",
+ "# Combine x transformation and model into one operation.\n",
+ "# Not neccesary, but convenient.\n",
+ "model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
+ "\n",
+ "# The following (m x n_bootstraps) matrix holds the column vectors y_pred\n",
+ "# for each bootstrap iteration.\n",
+ "y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
+ "for i in range(n_boostraps):\n",
+ " x_, y_ = resample(x_train, y_train)\n",
+ "\n",
+ " # Evaluate the new model on the same test data each time.\n",
+ " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
+ "\n",
+ "# Note: Expectations and variances taken w.r.t. different training\n",
+ "# data sets, hence the axis=1. Subsequent means are taken across the test data\n",
+ "# set in order to obtain a total value, but before this we have error/bias/variance\n",
+ "# calculated per data point in the test set.\n",
+ "# Note 2: The use of keepdims=True is important in the calculation of bias as this \n",
+ "# maintains the column vector form. Dropping this yields very unexpected results.\n",
+ "error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
+ "bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
+ "variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
+ "print('Error:', error)\n",
+ "print('Bias^2:', bias)\n",
+ "print('Var:', variance)\n",
+ "print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))\n",
+ "\n",
+ "plt.plot(x[::5, :], y[::5, :], label='f(x)')\n",
+ "plt.scatter(x_test, y_test, label='Data points')\n",
+ "plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.pipeline import make_pipeline\n",
+ "from sklearn.utils import resample\n",
+ "\n",
+ "np.random.seed(2018)\n",
+ "\n",
+ "n = 40\n",
+ "n_boostraps = 100\n",
+ "maxdegree = 14\n",
+ "\n",
+ "\n",
+ "# Make data set.\n",
+ "x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
+ "error = np.zeros(maxdegree)\n",
+ "bias = np.zeros(maxdegree)\n",
+ "variance = np.zeros(maxdegree)\n",
+ "polydegree = np.zeros(maxdegree)\n",
+ "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
+ "\n",
+ "for degree in range(maxdegree):\n",
+ " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
+ " y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
+ " for i in range(n_boostraps):\n",
+ " x_, y_ = resample(x_train, y_train)\n",
+ " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
+ "\n",
+ " polydegree[degree] = degree\n",
+ " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
+ " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
+ " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
+ " print('Polynomial degree:', degree)\n",
+ " print('Error:', error[degree])\n",
+ " print('Bias^2:', bias[degree])\n",
+ " print('Var:', variance[degree])\n",
+ " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n",
+ "\n",
+ "plt.plot(polydegree, error, label='Error')\n",
+ "plt.plot(polydegree, bias, label='bias')\n",
+ "plt.plot(polydegree, variance, label='Variance')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The bias-variance tradeoff summarizes the fundamental tension in\n",
+ "machine learning, particularly supervised learning, between the\n",
+ "complexity of a model and the amount of training data needed to train\n",
+ "it. Since data is often limited, in practice it is often useful to\n",
+ "use a less-complex model with higher bias, that is a model whose asymptotic\n",
+ "performance is worse than another model because it is easier to\n",
+ "train and less sensitive to sampling noise arising from having a\n",
+ "finite-sized training dataset (smaller variance). \n",
+ "\n",
+ "\n",
+ "\n",
+ "The above equations tell us that in\n",
+ "order to minimize the expected test error, we need to select a\n",
+ "statistical learning method that simultaneously achieves low variance\n",
+ "and low bias. Note that variance is inherently a nonnegative quantity,\n",
+ "and squared bias is also nonnegative. Hence, we see that the expected\n",
+ "test MSE can never lie below $Var(\\epsilon)$, the irreducible error.\n",
+ "\n",
+ "\n",
+ "What do we mean by the variance and bias of a statistical learning\n",
+ "method? The variance refers to the amount by which our model would change if we\n",
+ "estimated it using a different training data set. Since the training\n",
+ "data are used to fit the statistical learning method, different\n",
+ "training data sets will result in a different estimate. But ideally the\n",
+ "estimate for our model should not vary too much between training\n",
+ "sets. However, if a method has high variance then small changes in\n",
+ "the training data can result in large changes in the model. In general, more\n",
+ "flexible statistical methods have higher variance.\n",
+ "\n",
+ "\n",
+ "You may also find this recent [article](https://www.pnas.org/content/116/32/15849) of interest."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "\"\"\"\n",
+ "============================\n",
+ "Underfitting vs. Overfitting\n",
+ "============================\n",
+ "\n",
+ "This example demonstrates the problems of underfitting and overfitting and\n",
+ "how we can use linear regression with polynomial features to approximate\n",
+ "nonlinear functions. The plot shows the function that we want to approximate,\n",
+ "which is a part of the cosine function. In addition, the samples from the\n",
+ "real function and the approximations of different models are displayed. The\n",
+ "models have polynomial features of different degrees. We can see that a\n",
+ "linear function (polynomial with degree 1) is not sufficient to fit the\n",
+ "training samples. This is called **underfitting**. A polynomial of degree 4\n",
+ "approximates the true function almost perfectly. However, for higher degrees\n",
+ "the model will **overfit** the training data, i.e. it learns the noise of the\n",
+ "training data.\n",
+ "We evaluate quantitatively **overfitting** / **underfitting** by using\n",
+ "cross-validation. We calculate the mean squared error (MSE) on the validation\n",
+ "set, the higher, the less likely the model generalizes correctly from the\n",
+ "training data.\n",
+ "\"\"\"\n",
+ "\n",
+ "print(__doc__)\n",
+ "\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.pipeline import Pipeline\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "from sklearn.linear_model import LinearRegression\n",
+ "from sklearn.model_selection import cross_val_score\n",
+ "\n",
+ "\n",
+ "def true_fun(X):\n",
+ " return np.cos(1.5 * np.pi * X)\n",
+ "\n",
+ "np.random.seed(0)\n",
+ "\n",
+ "n_samples = 30\n",
+ "degrees = [1, 4, 15]\n",
+ "\n",
+ "X = np.sort(np.random.rand(n_samples))\n",
+ "y = true_fun(X) + np.random.randn(n_samples) * 0.1\n",
+ "\n",
+ "plt.figure(figsize=(14, 5))\n",
+ "for i in range(len(degrees)):\n",
+ " ax = plt.subplot(1, len(degrees), i + 1)\n",
+ " plt.setp(ax, xticks=(), yticks=())\n",
+ "\n",
+ " polynomial_features = PolynomialFeatures(degree=degrees[i],\n",
+ " include_bias=False)\n",
+ " linear_regression = LinearRegression()\n",
+ " pipeline = Pipeline([(\"polynomial_features\", polynomial_features),\n",
+ " (\"linear_regression\", linear_regression)])\n",
+ " pipeline.fit(X[:, np.newaxis], y)\n",
+ "\n",
+ " # Evaluate the models using crossvalidation\n",
+ " scores = cross_val_score(pipeline, X[:, np.newaxis], y,\n",
+ " scoring=\"neg_mean_squared_error\", cv=10)\n",
+ "\n",
+ " X_test = np.linspace(0, 1, 100)\n",
+ " plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label=\"Model\")\n",
+ " plt.plot(X_test, true_fun(X_test), label=\"True function\")\n",
+ " plt.scatter(X, y, edgecolor='b', s=20, label=\"Samples\")\n",
+ " plt.xlabel(\"x\")\n",
+ " plt.ylabel(\"y\")\n",
+ " plt.xlim((0, 1))\n",
+ " plt.ylim((-2, 2))\n",
+ " plt.legend(loc=\"best\")\n",
+ " plt.title(\"Degree {}\\nMSE = {:.2e}(+/- {:.2e})\".format(\n",
+ " degrees[i], -scores.mean(), scores.std()))\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
"source": [
"# Common imports\n",
+ "import os\n",
"import numpy as np\n",
"import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.utils import resample\n",
+ "from sklearn.metrics import mean_squared_error\n",
+ "# Where to save the figures and data files\n",
+ "PROJECT_ROOT_DIR = \"Results\"\n",
+ "FIGURE_ID = \"Results/FigureFiles\"\n",
+ "DATA_ID = \"DataFiles/\"\n",
"\n",
+ "if not os.path.exists(PROJECT_ROOT_DIR):\n",
+ " os.mkdir(PROJECT_ROOT_DIR)\n",
"\n",
- "def FrankeFunction(x,y):\n",
- "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
- "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
- "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
- "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
- "\treturn term1 + term2 + term3 + term4\n",
+ "if not os.path.exists(FIGURE_ID):\n",
+ " os.makedirs(FIGURE_ID)\n",
"\n",
+ "if not os.path.exists(DATA_ID):\n",
+ " os.makedirs(DATA_ID)\n",
"\n",
- "def create_X(x, y, n ):\n",
- "\tif len(x.shape) > 1:\n",
- "\t\tx = np.ravel(x)\n",
- "\t\ty = np.ravel(y)\n",
+ "def image_path(fig_id):\n",
+ " return os.path.join(FIGURE_ID, fig_id)\n",
"\n",
- "\tN = len(x)\n",
- "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n",
- "\tX = np.ones((N,l))\n",
+ "def data_path(dat_id):\n",
+ " return os.path.join(DATA_ID, dat_id)\n",
"\n",
- "\tfor i in range(1,n+1):\n",
- "\t\tq = int((i)*(i+1)/2)\n",
- "\t\tfor k in range(i+1):\n",
- "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n",
+ "def save_fig(fig_id):\n",
+ " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
"\n",
- "\treturn X\n",
+ "infile = open(data_path(\"EoS.csv\"),'r')\n",
"\n",
+ "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
+ "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
+ "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
+ "EoS = EoS.dropna()\n",
+ "Energies = EoS['Energy']\n",
+ "Density = EoS['Density']\n",
+ "# The design matrix now as function of various polytrops\n",
"\n",
- "# Making meshgrid of datapoints and compute Franke's function\n",
- "n = 4\n",
- "N = 100\n",
- "x = np.sort(np.random.uniform(0, 1, N))\n",
- "y = np.sort(np.random.uniform(0, 1, N))\n",
- "z = FrankeFunction(x, y)\n",
- "X = create_X(x, y, n=n) \n",
+ "Maxpolydegree = 30\n",
+ "X = np.zeros((len(Density),Maxpolydegree))\n",
+ "X[:,0] = 1.0\n",
+ "testerror = np.zeros(Maxpolydegree)\n",
+ "trainingerror = np.zeros(Maxpolydegree)\n",
+ "polynomial = np.zeros(Maxpolydegree)\n",
"\n",
- "Xpd = pd.DataFrame(X)\n",
- "# subtract the mean values and set up the covariance matrix\n",
- "Xpd = Xpd - Xpd.mean()\n",
- "covariance_matrix = Xpd.cov()\n",
- "print(covariance_matrix)"
+ "trials = 100\n",
+ "for polydegree in range(1, Maxpolydegree):\n",
+ " polynomial[polydegree] = polydegree\n",
+ " for degree in range(polydegree):\n",
+ " X[:,degree] = Density**(degree/3.0)\n",
+ "\n",
+ "# loop over trials in order to estimate the expectation value of the MSE\n",
+ " testerror[polydegree] = 0.0\n",
+ " trainingerror[polydegree] = 0.0\n",
+ " for samples in range(trials):\n",
+ " x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n",
+ " model = LinearRegression(fit_intercept=True).fit(x_train, y_train)\n",
+ " ypred = model.predict(x_train)\n",
+ " ytilde = model.predict(x_test)\n",
+ " testerror[polydegree] += mean_squared_error(y_test, ytilde)\n",
+ " trainingerror[polydegree] += mean_squared_error(y_train, ypred) \n",
+ "\n",
+ " testerror[polydegree] /= trials\n",
+ " trainingerror[polydegree] /= trials\n",
+ " print(\"Degree of polynomial: %3d\"% polynomial[polydegree])\n",
+ " print(\"Mean squared error on training data: %.8f\" % trainingerror[polydegree])\n",
+ " print(\"Mean squared error on test data: %.8f\" % testerror[polydegree])\n",
+ "\n",
+ "plt.plot(polynomial, np.log10(trainingerror), label='Training Error')\n",
+ "plt.plot(polynomial, np.log10(testerror), label='Test Error')\n",
+ "plt.xlabel('Polynomial degree')\n",
+ "plt.ylabel('log10[MSE]')\n",
+ "plt.legend()\n",
+ "plt.show()"
]
},
{
- "cell_type": "markdown",
- "metadata": {},
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
"source": [
- "We note here that the covariance is zero for the first rows and\n",
- "columns since all matrix elements in the design matrix were set to one\n",
- "(we are fitting the function in terms of a polynomial of degree $n$).\n",
- "\n",
- "This means that the variance for these elements will be zero and will\n",
- "cause problems when we set up the correlation matrix. We can simply\n",
- "drop these elements and construct a correlation\n",
- "matrix without these elements. \n",
+ "# Common imports\n",
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.metrics import mean_squared_error\n",
+ "from sklearn.model_selection import KFold\n",
+ "from sklearn.model_selection import cross_val_score\n",
"\n",
"\n",
+ "# Where to save the figures and data files\n",
+ "PROJECT_ROOT_DIR = \"Results\"\n",
+ "FIGURE_ID = \"Results/FigureFiles\"\n",
+ "DATA_ID = \"DataFiles/\"\n",
"\n",
+ "if not os.path.exists(PROJECT_ROOT_DIR):\n",
+ " os.mkdir(PROJECT_ROOT_DIR)\n",
"\n",
- "We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\\boldsymbol{X}$ as"
+ "if not os.path.exists(FIGURE_ID):\n",
+ " os.makedirs(FIGURE_ID)\n",
+ "\n",
+ "if not os.path.exists(DATA_ID):\n",
+ " os.makedirs(DATA_ID)\n",
+ "\n",
+ "def image_path(fig_id):\n",
+ " return os.path.join(FIGURE_ID, fig_id)\n",
+ "\n",
+ "def data_path(dat_id):\n",
+ " return os.path.join(DATA_ID, dat_id)\n",
+ "\n",
+ "def save_fig(fig_id):\n",
+ " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
+ "\n",
+ "infile = open(data_path(\"EoS.csv\"),'r')\n",
+ "\n",
+ "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
+ "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
+ "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
+ "EoS = EoS.dropna()\n",
+ "Energies = EoS['Energy']\n",
+ "Density = EoS['Density']\n",
+ "# The design matrix now as function of various polytrops\n",
+ "\n",
+ "Maxpolydegree = 30\n",
+ "X = np.zeros((len(Density),Maxpolydegree))\n",
+ "X[:,0] = 1.0\n",
+ "estimated_mse_sklearn = np.zeros(Maxpolydegree)\n",
+ "polynomial = np.zeros(Maxpolydegree)\n",
+ "k =5\n",
+ "kfold = KFold(n_splits = k)\n",
+ "\n",
+ "for polydegree in range(1, Maxpolydegree):\n",
+ " polynomial[polydegree] = polydegree\n",
+ " for degree in range(polydegree):\n",
+ " X[:,degree] = Density**(degree/3.0)\n",
+ " OLS = LinearRegression()\n",
+ "# loop over trials in order to estimate the expectation value of the MSE\n",
+ " estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)\n",
+ "#[:, np.newaxis]\n",
+ " estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)\n",
+ "\n",
+ "plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')\n",
+ "plt.xlabel('Polynomial degree')\n",
+ "plt.ylabel('log10[MSE]')\n",
+ "plt.legend()\n",
+ "plt.show()"
]
},
{
- "cell_type": "markdown",
- "metadata": {},
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
"source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}=\\begin{bmatrix}\n",
- "x_{00} & x_{01}\\\\\n",
- "x_{10} & x_{11}\\\\\n",
- "\\end{bmatrix}=\\begin{bmatrix}\n",
- "\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n",
- "\\end{bmatrix}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "If we then compute the expectation value"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}=\\begin{bmatrix}\n",
- "x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\\\\n",
- "x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which is just"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\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] \\\\\n",
- " \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "where we wrote $$\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]$$ to indicate that this the covariance of the vectors $\\boldsymbol{x}$ of the design/feature matrix $\\boldsymbol{X}$.\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import KFold\n",
+ "from sklearn.linear_model import Ridge\n",
+ "from sklearn.model_selection import cross_val_score\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
"\n",
- "It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$.\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "np.random.seed(3155)\n",
+ "# Generate the data.\n",
+ "n = 100\n",
+ "x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
+ "# Decide degree on polynomial to fit\n",
+ "poly = PolynomialFeatures(degree = 10)\n",
"\n",
- "\n",
- "## Linking with SVD"
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 500\n",
+ "lambdas = np.logspace(-3, 5, nlambdas)\n",
+ "# Initialize a KFold instance\n",
+ "k = 5\n",
+ "kfold = KFold(n_splits = k)\n",
+ "estimated_mse_sklearn = np.zeros(nlambdas)\n",
+ "i = 0\n",
+ "for lmb in lambdas:\n",
+ " ridge = Ridge(alpha = lmb)\n",
+ " estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)\n",
+ " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n",
+ " i += 1\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
]
}
],
diff --git a/doc/LectureNotes/_build/jupyter_execute/chapter3.py b/doc/LectureNotes/_build/jupyter_execute/chapter3.py
index 9469762fc..6aaa20907 100644
--- a/doc/LectureNotes/_build/jupyter_execute/chapter3.py
+++ b/doc/LectureNotes/_build/jupyter_execute/chapter3.py
@@ -1,790 +1,1039 @@
-# Ridge and Lasso Regression
+# Resampling Methods
-[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember10.mp4?vrtx=view-as-webpage)
+## Introduction
+
+Resampling methods are an indispensable tool in modern
+statistics. They involve repeatedly drawing samples from a training
+set and refitting a model of interest on each sample in order to
+obtain additional information about the fitted model. For example, in
+order to estimate the variability of a linear regression fit, we can
+repeatedly draw different samples from the training data, fit a linear
+regression to each new sample, and then examine the extent to which
+the resulting fits differ. Such an approach may allow us to obtain
+information that would not be available from fitting the model only
+once using the original training sample.
+
+Two resampling methods are often used in Machine Learning analyses,
+1. The **bootstrap method**
+
+2. and **Cross-Validation**
+
+In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular
+cross-validation and the bootstrap method.
-## The singular value decomposition
-
-The examples we have looked at so far are cases where we normally can
-invert the matrix $\boldsymbol{X}^T\boldsymbol{X}$. Using a polynomial expansion as we
-did both for the masses and the fitting of the equation of state,
-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.
+Resampling approaches can be computationally expensive, because they
+involve fitting the same statistical method multiple times using
+different subsets of the training data. However, due to recent
+advances in computing power, the computational requirements of
+resampling methods generally are not prohibitive. In this chapter, we
+discuss two of the most commonly used resampling methods,
+cross-validation and the bootstrap. Both methods are important tools
+in the practical application of many statistical learning
+procedures. For example, cross-validation can be used to estimate the
+test error associated with a given statistical learning method in
+order to evaluate its performance, or to select the appropriate level
+of flexibility. The process of evaluating a model’s performance is
+known as model assessment, whereas the process of selecting the proper
+level of flexibility for a model is known as model selection. The
+bootstrap is widely used.
+* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods
-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.
+* The results can be analysed with the same statistical tools as we would use analysing experimental data.
-There is however a way to partially circumvent this problem and also gain some insights about the ordinary least squares approach, and later shrinkage methods like Ridge and Lasso regressions.
+* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
-This is given by the **Singular Value Decomposition** algorithm, perhaps
-the most powerful linear algebra algorithm. Let us look at a
-different example where we may have problems with the standard matrix
-inversion algorithm. Thereafter we dive into the math of the SVD.
+## Reminder on Statistics
+* As in other experiments, many numerical experiments have two classes of errors:
-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
+ * Statistical errors
+
+ * Systematical errors
+
+
+* Statistical errors can be estimated using standard tools from statistics
+
+* Systematical errors are method specific and must be treated differently from case to case.
+
+The
+advantage of doing linear regression is that we actually end up with
+analytical expressions for several statistical quantities.
+Standard least squares and Ridge regression allow us to
+derive quantities like the variance and other expectation values in a
+rather straightforward way.
+
+
+It is assumed that $\varepsilon_i
+\sim \mathcal{N}(0, \sigma^2)$ and the $\varepsilon_{i}$ are
+independent, i.e.:
$$
-\begin{align*}
-\mathbf{X} & = \left[
-\begin{array}{rrr}
-1 & -1 & 2
-\\
-1 & 0 & 1
-\\
-1 & 2 & -1
-\\
-1 & 1 & 0
-\end{array} \right]
+\begin{align*}
+\mbox{Cov}(\varepsilon_{i_1},
+\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if}
+& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \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.
+The randomness of $\varepsilon_i$ implies that
+$\mathbf{y}_i$ is also a random variable. In particular,
+$\mathbf{y}_i$ is normally distributed, because $\varepsilon_i \sim
+\mathcal{N}(0, \sigma^2)$ and $\mathbf{X}_{i,\ast} \, \boldsymbol{\beta}$ is a
+non-random scalar. To specify the parameters of the distribution of
+$\mathbf{y}_i$ we need to calculate its first two moments.
-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
+Recall that $\boldsymbol{X}$ is a matrix of dimensionality $n\times p$. The
+notation above $\mathbf{X}_{i,\ast}$ means that we are looking at the
+row number $i$ and perform a sum over all values $p$.
+
+
+The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off)
+that there exists a function $f(\boldsymbol{x})$ and a normal distributed error $\boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2)$
+which describe our data
$$
-\begin{align*}
-\boldsymbol{X} & = \left[
-\begin{array}{rr}
-1 & -1
-\\
-1 & -1
-\end{array} \right].
+\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon}
+$$
+
+We approximate this function with our model from the solution of the linear regression equations, that is our
+function $f$ is approximated by $\boldsymbol{\tilde{y}}$ where we want to minimize $(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2$, our MSE, with
+
+$$
+\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}.
+$$
+
+We can calculate the expectation value of $\boldsymbol{y}$ for a given element $i$
+
+$$
+\begin{align*}
+\mathbb{E}(y_i) & =
+\mathbb{E}(\mathbf{X}_{i, \ast} \, \boldsymbol{\beta}) + \mathbb{E}(\varepsilon_i)
+\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta,
\end{align*}
$$
-We see easily that $\mbox{det}(\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0$. Hence, $\mathbf{X}$ is singular and its inverse is undefined.
-This is equivalent to saying that the matrix $\boldsymbol{X}$ has at least an eigenvalue which is zero.
-
-
-If our design matrix $\boldsymbol{X}$ which enters the linear regression problem
-
-
-
+while
+its variance is
$$
-\begin{equation}
-\boldsymbol{\beta} = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y},
-\label{_auto1} \tag{1}
-\end{equation}
+\begin{align*} \mbox{Var}(y_i) & = \mathbb{E} \{ [y_i
+- \mathbb{E}(y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( y_i^2 ) -
+[\mathbb{E}(y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \,
+\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 \\ &
+= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 \varepsilon_i
+\mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + \varepsilon_i^2 ] - ( \mathbf{X}_{i,
+\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2
+\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \boldsymbol{\beta} +
+\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2
+\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \,
+\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2.
+\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.
+Hence, $y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2)$, that is $\boldsymbol{y}$ follows a normal distribution with
+mean value $\boldsymbol{X}\boldsymbol{\beta}$ and variance $\sigma^2$ (not be confused with the singular values of the SVD).
-A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change
+
+With the OLS expressions for the parameters $\boldsymbol{\beta}$ we can evaluate the expectation value
$$
-\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I},
+\mathbb{E}(\boldsymbol{\beta}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}.
$$
-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.
+This means that the estimator of the regression parameters is unbiased.
+We can also calculate the variance
-
-
-
-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](https://en.wikipedia.org/wiki/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
+The variance of $\boldsymbol{\beta}$ is
$$
-(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n),
+\begin{eqnarray*}
+\mbox{Var}(\boldsymbol{\beta}) & = & \mathbb{E} \{ [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})] [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})]^{T} \}
+\\
+& = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}]^{T} \}
+\\
+% & = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}]^{T} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+% \\
+% & = & \mathbb{E} \{ (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} \, \mathbf{Y}^{T} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+% \\
+& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \mathbb{E} \{ \mathbf{Y} \, \mathbf{Y}^{T} \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+\\
+& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+% \\
+% & = & (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1}
+% \\
+% & & + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \boldsymbol{\beta} \boldsymbol{\beta}^T
+\\
+& = & \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1},
+\end{eqnarray*}
$$
-and the eigenvalues are given by the diagonal matrix
+where we have used that $\mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) =
+\mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} +
+\sigma^2 \, \mathbf{I}_{nn}$. From $\mbox{Var}(\boldsymbol{\beta}) = \sigma^2
+\, (\mathbf{X}^{T} \mathbf{X})^{-1}$, one obtains an estimate of the
+variance of the estimate of the $j$-th regression coefficient:
+$\boldsymbol{\sigma}^2 (\boldsymbol{\beta}_j ) = \boldsymbol{\sigma}^2 \sqrt{
+[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} }$. This may be used to
+construct a confidence interval for the estimates.
+
+
+In a similar way, we can obtain analytical expressions for say the
+expectation values of the parameters $\boldsymbol{\beta}$ and their variance
+when we employ Ridge regression, allowing us again to define a confidence interval.
+
+It is rather straightforward to show that
$$
-\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n).
+\mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\boldsymbol{\beta}^{\mathrm{OLS}}.
$$
-The matrix $\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\boldsymbol{U}$
+We see clearly that
+$\mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big] \not= \boldsymbol{\beta}^{\mathrm{OLS}}$ for any $\lambda > 0$. We say then that the ridge estimator is biased.
+
+We can also compute the variance as
$$
-\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,
+\mbox{Var}[\boldsymbol{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T},
$$
-with $\boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I}$ or $\boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I}$.
+and it is easy to see that if the parameter $\lambda$ goes to infinity then the variance of Ridge parameters $\boldsymbol{\beta}$ goes to zero.
-Not all square matrices are diagonalizable. A matrix like the one discussed above
+With this, we can compute the difference
$$
-\boldsymbol{X} = \begin{bmatrix}
-1& -1 \\
-1& -1\\
-\end{bmatrix}
+\mbox{Var}[\boldsymbol{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\boldsymbol{\beta}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}.
$$
-is not diagonalizable, it is a so-called [defective matrix](https://en.wikipedia.org/wiki/Defective_matrix). It is easy to see that the condition
-$\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X}$ is not fulfilled.
+The difference is non-negative definite since each component of the
+matrix product is non-negative definite.
+This means the variance we obtain with the standard OLS will always for $\lambda > 0$ be larger than the variance of $\boldsymbol{\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below.
-## The SVD, a Fantastic Algorithm
+## Resampling methods
+
+With all these analytical equations for both the OLS and Ridge
+regression, we will now outline how to assess a given model. This will
+lead us to a discussion of the so-called bias-variance tradeoff (see
+below) and so-called resampling methods.
+
+One of the quantities we have discussed as a way to measure errors is
+the mean-squared error (MSE), mainly used for fitting of continuous
+functions. Another choice is the absolute error.
+
+In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,
+we discuss the
+1. prediction error or simply the **test error** $\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the
+
+2. training error $\mathrm{Err_{Train}}$, which is the average loss over the training data.
+
+As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.
+For a certain level of complexity the test error will reach minimum, before starting to increase again. The
+training error reaches a saturation.
-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](https://en.wikipedia.org/wiki/Singular_value_decomposition)
-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
+
+Two famous
+resampling methods are the **independent bootstrap** and **the jackknife**.
+
+The jackknife is a special case of the independent bootstrap. Still, the jackknife was made
+popular prior to the independent bootstrap. And as the popularity of
+the independent bootstrap soared, new variants, such as **the dependent bootstrap**.
+
+The Jackknife and independent bootstrap work for
+independent, identically distributed random variables.
+If these conditions are not
+satisfied, the methods will fail. Yet, it should be said that if the data are
+independent, identically distributed, and we only want to estimate the
+variance of $\overline{X}$ (which often is the case), then there is no
+need for bootstrapping.
+
+
+The Jackknife works by making many replicas of the estimator $\widehat{\theta}$.
+The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\boldsymbol{x} = (x_1,x_2,\cdots,X_n)$.
+Let $\boldsymbol{x}_i$ denote the vector
$$
-\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T
+\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n),
$$
-As an example, the above defective matrix can be decomposed as
+which equals the vector $\boldsymbol{x}$ with the exception that observation
+number $i$ is left out. Using this notation, define
+$\widehat{\theta}_i$ to be the estimator
+$\widehat{\theta}$ computed using $\vec{X}_i$.
+
+from numpy import *
+from numpy.random import randint, randn
+from time import time
+
+def jackknife(data, stat):
+ n = len(data);t = zeros(n); inds = arange(n); t0 = time()
+ ## 'jackknifing' by leaving out an observation for each i
+ for i in range(n):
+ t[i] = stat(delete(data,i) )
+
+ # analysis
+ print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :")
+ print("original bias std. error")
+ print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))
+
+ return t
+
+
+# Returns mean of data samples
+def stat(data):
+ return mean(data)
+
+
+mu, sigma = 100, 15
+datapoints = 10000
+x = mu + sigma*random.randn(datapoints)
+# jackknife returns the data sample
+t = jackknife(x, stat)
+
+### Bootstrap
+
+Bootstrapping is a nonparametric approach to statistical inference
+that substitutes computation for more traditional distributional
+assumptions and asymptotic results. Bootstrapping offers a number of
+advantages:
+1. The bootstrap is quite general, although there are some cases in which it fails.
+
+2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small.
+
+3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically.
+
+4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).
+
+Since $\widehat{\theta} = \widehat{\theta}(\boldsymbol{X})$ is a function of random variables,
+$\widehat{\theta}$ itself must be a random variable. Thus it has
+a pdf, call this function $p(\boldsymbol{t})$. The aim of the bootstrap is to
+estimate $p(\boldsymbol{t})$ by the relative frequency of
+$\widehat{\theta}$. You can think of this as using a histogram
+in the place of $p(\boldsymbol{t})$. If the relative frequency closely
+resembles $p(\vec{t})$, then using numerics, it is straight forward to
+estimate all the interesting parameters of $p(\boldsymbol{t})$ using point
+estimators.
+
+
+
+In the case that $\widehat{\theta}$ has
+more than one component, and the components are independent, we use the
+same estimator on each component separately. If the probability
+density function of $X_i$, $p(x)$, had been known, then it would have
+been straight forward to do this by:
+1. Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \cdots, X_n^*)$.
+
+2. Then using these numbers, we could compute a replica of $\widehat{\theta}$ called $\widehat{\theta}^*$.
+
+By repeated use of (1) and (2), many
+estimates of $\widehat{\theta}$ could have been obtained. The
+idea is to use the relative frequency of $\widehat{\theta}^*$
+(think of a histogram) as an estimate of $p(\boldsymbol{t})$.
+
+
+But
+unless there is enough information available about the process that
+generated $X_1,X_2,\cdots,X_n$, $p(x)$ is in general
+unknown. Therefore, [Efron in 1979](https://projecteuclid.org/euclid.aos/1176344552) asked the
+question: What if we replace $p(x)$ by the relative frequency
+of the observation $X_i$; if we draw observations in accordance with
+the relative frequency of the observations, will we obtain the same
+result in some asymptotic sense? The answer is yes.
+
+
+Instead of generating the histogram for the relative
+frequency of the observation $X_i$, just draw the values
+$(X_1^*,X_2^*,\cdots,X_n^*)$ with replacement from the vector
+$\boldsymbol{X}$.
+
+
+The independent bootstrap works like this:
+
+1. Draw with replacement $n$ numbers for the observed variables $\boldsymbol{x} = (x_1,x_2,\cdots,x_n)$.
+
+2. Define a vector $\boldsymbol{x}^*$ containing the values which were drawn from $\boldsymbol{x}$.
+
+3. Using the vector $\boldsymbol{x}^*$ compute $\widehat{\theta}^*$ by evaluating $\widehat \theta$ under the observations $\boldsymbol{x}^*$.
+
+4. Repeat this process $k$ times.
+
+When you are done, you can draw a histogram of the relative frequency
+of $\widehat \theta^*$. This is your estimate of the probability
+distribution $p(t)$. Using this probability distribution you can
+estimate any statistics thereof. In principle you never draw the
+histogram of the relative frequency of $\widehat{\theta}^*$. Instead
+you use the estimators corresponding to the statistic of interest. For
+example, if you are interested in estimating the variance of $\widehat
+\theta$, apply the etsimator $\widehat \sigma^2$ to the values
+$\widehat \theta ^*$.
+
+
+
+The following code starts with a Gaussian distribution with mean value
+$\mu =100$ and variance $\sigma=15$. We use this to generate the data
+used in the bootstrap analysis. The bootstrap analysis returns a data
+set after a given number of bootstrap operations (as many as we have
+data points). This data set consists of estimated mean values for each
+bootstrap operation. The histogram generated by the bootstrap method
+shows that the distribution for these mean values is also a Gaussian,
+centered around the mean value $\mu=100$ but with standard deviation
+$\sigma/\sqrt{n}$, where $n$ is the number of bootstrap samples (in
+this case the same as the number of original data points). The value
+of the standard deviation is what we expect from the central limit
+theorem.
+
+%matplotlib inline
+
+from numpy import *
+from numpy.random import randint, randn
+from time import time
+import matplotlib.mlab as mlab
+import matplotlib.pyplot as plt
+
+# Returns mean of bootstrap samples
+def stat(data):
+ return mean(data)
+
+# Bootstrap algorithm
+def bootstrap(data, statistic, R):
+ t = zeros(R); n = len(data); inds = arange(n); t0 = time()
+ # non-parametric bootstrap
+ for i in range(R):
+ t[i] = statistic(data[randint(0,n,n)])
+
+ # analysis
+ print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
+ print("original bias std. error")
+ print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
+ return t
+
+
+mu, sigma = 100, 15
+datapoints = 10000
+x = mu + sigma*random.randn(datapoints)
+# bootstrap returns the data sample
+t = bootstrap(x, stat, datapoints)
+# the histogram of the bootstrapped data
+n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
+
+# add a 'best fit' line
+y = mlab.normpdf( binsboot, mean(t), std(t))
+lt = plt.plot(binsboot, y, 'r--', linewidth=1)
+plt.xlabel('Smarts')
+plt.ylabel('Probability')
+plt.axis([99.5, 100.6, 0, 3.0])
+plt.grid(True)
+
+plt.show()
+
+## Various steps in cross-validation
+
+When the repetitive splitting of the data set is done randomly,
+samples may accidently end up in a fast majority of the splits in
+either training or test set. Such samples may have an unbalanced
+influence on either model building or prediction evaluation. To avoid
+this $k$-fold cross-validation structures the data splitting. The
+samples are divided into $k$ more or less equally sized exhaustive and
+mutually exclusive subsets. In turn (at each split) one of these
+subsets plays the role of the test set while the union of the
+remaining subsets constitutes the training set. Such a splitting
+warrants a balanced representation of each sample in both training and
+test set over the splits. Still the division into the $k$ subsets
+involves a degree of randomness. This may be fully excluded when
+choosing $k=n$. This particular case is referred to as leave-one-out
+cross-validation (LOOCV).
+
+
+* Define a range of interest for the penalty parameter.
+
+* Divide the data set into training and test set comprising samples $\{1, \ldots, n\} \setminus i$ and $\{ i \}$, respectively.
+
+* Fit the linear regression model by means of ridge estimation for each $\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\boldsymbol{\sigma}_{-i}^2(\lambda)$, 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,
+\begin{align*}
+\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T}
+\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1}
+\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i}
+\end{align*}
$$
-with eigenvalues $\sigma_1=2$ and $\sigma_2=0$.
-The SVD exits always!
+* Evaluate the prediction performance of these models on the test set by $\log\{L[y_i, \boldsymbol{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}$. Or, by the prediction error $|y_i - \boldsymbol{X}_{i, \ast} \boldsymbol{\beta}_{-i}(\lambda)|$, the relative error, the error squared or the R2 score function.
-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.
+* Repeat the first three steps such that each sample plays the role of the test set once.
-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.
+* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as
-The columns of $\boldsymbol{U}$ are called the left singular vectors while the columns of $\boldsymbol{V}$ are the right singular vectors.
+$$
+\begin{align*}
+\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}.
+\end{align*}
+$$
-## Economy-size SVD
+For the various values of $k$
-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}$.
+1. shuffle the dataset randomly.
-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.
+2. Split the dataset into $k$ groups.
-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.
+3. For each unique group:
+
+a. Decide which group to use as set for test data
+
+b. Take the remaining groups as a training data set
+
+c. Fit a model on the training set and evaluate it on the test set
+
+d. Retain the evaluation score and discard the model
+
+
+5. Summarize the model using the sample of model evaluation scores
+
+The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial.
import numpy as np
-# SVD inversion
-def SVDinv(A):
- ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).
- SVD is numerically more stable than the inversion algorithms provided by
- numpy and scipy.linalg at the cost of being slower.
- '''
- U, s, VT = np.linalg.svd(A)
-# print('test U')
-# print( (np.transpose(U) @ U - U @np.transpose(U)))
-# print('test VT')
-# print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))
- 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]
- UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)
- return np.matmul(V,np.matmul(invD,UT))
-
-
-X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])
-print(X)
-A = np.transpose(X) @ X
-print(A)
-# Brute force inversion of super-collinear matrix
-#B = np.linalg.inv(A)
-#print(B)
-C = SVDinv(A)
-print(C)
-
-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.
-
-
-
-
-There are several interesting mathematical properties which will be
-relevant when we are going to discuss the differences between say
-ordinary least squares (OLS) and **Ridge** regression.
-
-We have from OLS that the parameters of the linear approximation are given by
+import matplotlib.pyplot as plt
+from sklearn.model_selection import KFold
+from sklearn.linear_model import Ridge
+from sklearn.model_selection import cross_val_score
+from sklearn.preprocessing import PolynomialFeatures
-$$
-\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
-$$
-
-The matrix to invert can be rewritten in terms of our SVD decomposition as
-
-$$
-\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T.
-$$
-
-Using the orthogonality properties of $\boldsymbol{U}$ we have
-
-$$
-\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T = \boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T,
-$$
-
-with $\boldsymbol{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared.
-
-This means that
-
-$$
-(\boldsymbol{X}^T\boldsymbol{X})\boldsymbol{V} = \boldsymbol{V}\boldsymbol{D},
-$$
-
-that is the eigenvectors of $(\boldsymbol{X}^T\boldsymbol{X})$ are given by the columns of the right singular matrix of $\boldsymbol{X}$ and the eigenvalues are the squared singular values. It is easy to show (show this) that
-
-$$
-(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D},
-$$
-
-that is, the eigenvectors of $(\boldsymbol{X}\boldsymbol{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same.
-
-Going back to our OLS equation we have
-
-$$
-\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}.
-$$
-
-We will come back to this expression when we discuss Ridge regression.
-
-
-$$ \tilde{y}^{OLS}=\boldsymbol{X}\hat{\beta}^{OLS}=\sum_{j=1}^p \boldsymbol{u}_j\boldsymbol{u}_j^T\boldsymbol{y}$$ and for Ridge we have
-
-$$ \tilde{y}^{Ridge}=\boldsymbol{X}\hat{\beta}^{Ridge}=\sum_{j=1}^p \boldsymbol{u}_j\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{u}_j^T\boldsymbol{y}$$ .
-
-It is indeed the economy-sized SVD, note the summation runs up tp $$p$$ only and not $$n$$.
-
-Here we have that $$\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T$$, with $$\Sigma$$ being an $$ n\times p$$ matrix and $$\boldsymbol{V}$$ being a $$ p\times p$$ matrix. We also have assumed here that $$ n > p$$.
-
-
-
-
-
-
-
-
-## Ridge and LASSO Regression
-
-[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember11.mp4?vrtx=view-as-webpage)
-
-Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is
-our optimization problem is
-
-$$
-{\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}.
-$$
-
-or we can state it as
-
-$$
-{\displaystyle \min_{\boldsymbol{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2,
-$$
-
-where we have used the definition of a norm-2 vector, that is
-
-$$
-\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.
-$$
-
-By minimizing the above equation with respect to the parameters
-$\boldsymbol{\beta}$ we could then obtain an analytical expression for the
-parameters $\boldsymbol{\beta}$. We can add a regularization parameter $\lambda$ by
-defining a new cost function to be optimized, that is
-
-$$
-{\displaystyle \min_{\boldsymbol{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2
-$$
-
-which leads to the Ridge regression minimization problem where we
-require that $\vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t$, where $t$ is
-a finite number larger than zero. By defining
-
-$$
-C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1,
-$$
-
-we have a new optimization equation
-
-$$
-{\displaystyle \min_{\boldsymbol{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1
-$$
-
-which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.
-
-Here we have defined the norm-1 as
+# A seed just to ensure that the random numbers are the same for every run.
+# Useful for eventual debugging.
+np.random.seed(3155)
-$$
-\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert.
-$$
+# Generate the data.
+nsamples = 100
+x = np.random.randn(nsamples)
+y = 3*x**2 + np.random.randn(nsamples)
-Using the matrix-vector expression for Ridge regression,
+## Cross-validation on Ridge regression using KFold only
-$$
-C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta},
-$$
+# Decide degree on polynomial to fit
+poly = PolynomialFeatures(degree = 6)
-by 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
+# Decide which values of lambda to use
+nlambdas = 500
+lambdas = np.logspace(-3, 5, nlambdas)
-$$
-\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
-$$
+# Initialize a KFold instance
+k = 5
+kfold = KFold(n_splits = k)
-with $\boldsymbol{I}$ being a $p\times p$ identity matrix with the constraint that
+# Perform the cross-validation to estimate MSE
+scores_KFold = np.zeros((nlambdas, k))
-$$
-\sum_{i=0}^{p-1} \beta_i^2 \leq t,
-$$
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
+ j = 0
+ for train_inds, test_inds in kfold.split(x):
+ xtrain = x[train_inds]
+ ytrain = y[train_inds]
-with $t$ a finite positive number.
+ xtest = x[test_inds]
+ ytest = y[test_inds]
-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.
+ Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
+ ridge.fit(Xtrain, ytrain[:, np.newaxis])
-Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had
+ Xtest = poly.fit_transform(xtest[:, np.newaxis])
+ ypred = ridge.predict(Xtest)
-$$
-(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}.
-$$
+ scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
-We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\boldsymbol{U}$ as
+ j += 1
+ i += 1
-$$
-\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}
-$$
-For Ridge regression this becomes
+estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
-$$
-\boldsymbol{X}\boldsymbol{\beta}^{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T+\lambda\boldsymbol{I} \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\sum_{j=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{y},
-$$
+## Cross-validation using cross_val_score from sklearn along with KFold
-with the vectors $\boldsymbol{u}_j$ being the columns of $\boldsymbol{U}$.
+# kfold is an instance initialized above as:
+# kfold = KFold(n_splits = k)
+estimated_mse_sklearn = np.zeros(nlambdas)
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
-Since $\lambda \geq 0$, it means that compared to OLS, we have
+ X = poly.fit_transform(x[:, np.newaxis])
+ estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
-$$
-\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1.
-$$
+ # cross_val_score return an array containing the estimated negative mse for every fold.
+ # we have to the the mean of every array in order to get an estimate of the mse of the model
+ estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
-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}$.
+ i += 1
-For small eigenvalues $\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom.
-Actually, calculating the variance of $\boldsymbol{X}\boldsymbol{v}_j$ shows that this quantity is equal to $\sigma_j^2/n$.
-With a parameter $\lambda$ we can thus shrink the role of specific parameters.
+## Plot and compare the slightly different ways to perform cross-validation
+plt.figure()
+plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
+plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
-For the sake of simplicity, let us assume that the design matrix is orthonormal, that is
+plt.xlabel('log10(lambda)')
+plt.ylabel('mse')
-$$
-\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}.
-$$
-
-In this case the standard OLS results in
-
-$$
-\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\boldsymbol{y},
-$$
-
-and
-
-$$
-\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{I}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\left(1+\lambda\right)^{-1}\boldsymbol{\beta}^{\mathrm{OLS}},
-$$
-
-that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\lambda$, and
-the Ridge estimator converges to zero when the hyperparameter goes to
-infinity.
-
-We will come back to more interpreations after we have gone through some of the statistical analysis part.
-
-For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.
-Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.
+plt.legend()
+plt.show()
+## The bias-variance tradeoff
-## A better understanding of regularization
-The parameter $\lambda$ that we have introduced in the Ridge (and
-Lasso as well) regression is often called a regularization parameter
-or shrinkage parameter. It is common to call it a hyperparameter. What does it mean mathemtically?
+We will discuss the bias-variance tradeoff in the context of
+continuous predictions such as regression. However, many of the
+intuitions and ideas discussed here also carry over to classification
+tasks. Consider a dataset $\mathcal{L}$ consisting of the data
+$\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}$.
-Here we will first look at how to analyze the difference between the
-standard OLS equations and the Ridge expressions in terms of a linear
-algebra analysis using the SVD algorithm. Thereafter, we will link
-(see the material on the bias-variance tradeoff below) these
-observation to the statisical analysis of the results. In particular
-we consider how the variance of the parameters $\boldsymbol{\beta}$ is
-affected by changing the parameter $\lambda$.
-
-
-We have our design matrix
- $\boldsymbol{X}\in {\mathbb{R}}^{n\times p}$. With the SVD we decompose it as
+Let us assume that the true data is generated from a noisy model
$$
-\boldsymbol{X} = \boldsymbol{U\Sigma V^T},
+\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon}
$$
-with $\boldsymbol{U}\in {\mathbb{R}}^{n\times n}$, $\boldsymbol{\Sigma}\in {\mathbb{R}}^{n\times p}$
-and $\boldsymbol{V}\in {\mathbb{R}}^{p\times p}$.
-
-The matrices $\boldsymbol{U}$ and $\boldsymbol{V}$ are unitary/orthonormal matrices, that is in case the matrices are real we have $\boldsymbol{U}^T\boldsymbol{U}=\boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I}$ and $\boldsymbol{V}^T\boldsymbol{V}=\boldsymbol{V}\boldsymbol{V}^T=\boldsymbol{I}$.
-
+where $\epsilon$ is normally distributed with mean zero and standard deviation $\sigma^2$.
+In our derivation of the ordinary least squares method we defined then
+an approximation to the function $f$ in terms of the parameters
+$\boldsymbol{\beta}$ and the design matrix $\boldsymbol{X}$ which embody our model,
+that is $\boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta}$.
-## Introducing the Covariance and Correlation functions
-
-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
-
-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}.
-$$
-
-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
-
-$$
-\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 \\
- \end{bmatrix},
-$$
-
-In the above example this is the function we constructed using **pandas**.
-
-
-
-In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**
-we defined the design/feature matrix $\boldsymbol{X}$ as
+Thereafter we found the parameters $\boldsymbol{\beta}$ by optimizing the means squared error via the so-called cost function
$$
-\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},
+C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right].
$$
-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
+We can rewrite this as
$$
-\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix},
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2.
$$
-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}.
-$$
+The three terms represent the square of the bias of the learning
+method, which can be thought of as the error caused by the simplifying
+assumptions built into the method. The second term represents the
+variance of the chosen model and finally the last terms is variance of
+the error $\boldsymbol{\epsilon}$.
-With these definitions, we can now rewrite our $2\times 2$
-correaltion/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$
+To derive this equation, we need to recall that the variance of $\boldsymbol{y}$ and $\boldsymbol{\epsilon}$ are both equal to $\sigma^2$. The mean value of $\boldsymbol{\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\boldsymbol{\tilde{y}}$.
+We use a more compact notation in terms of the expectation value
$$
-\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},
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right],
$$
-and the correlation matrix
+and adding and subtracting $\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]$ we get
$$
-\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},
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right],
$$
-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}$
+which, using the abovementioned expectation values can be rewritten as
$$
-\boldsymbol{W} = \begin{bmatrix} x_0 & y_0 \\
- x_1 & y_1 \\
- x_2 & y_2\\
- \dots & \dots \\
- x_{n-2} & y_{n-2}\\
- x_{n-1} & y_{n-1} &
- \end{bmatrix},
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2,
$$
-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.
+that is the rewriting in terms of the so-called bias, the variance of the model $\boldsymbol{\tilde{y}}$ and the variance of $\boldsymbol{\epsilon}$.
-# Importing various packages
+import matplotlib.pyplot as plt
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)
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
-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).
+np.random.seed(2018)
+
+n = 500
+n_boostraps = 100
+degree = 18 # A quite high value, just to show.
+noise = 0.1
+
+# Make data set.
+x = np.linspace(-1, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)
+
+# Hold out some test data that is never used in training.
+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+# Combine x transformation and model into one operation.
+# Not neccesary, but convenient.
+model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
+
+# The following (m x n_bootstraps) matrix holds the column vectors y_pred
+# for each bootstrap iteration.
+y_pred = np.empty((y_test.shape[0], n_boostraps))
+for i in range(n_boostraps):
+ x_, y_ = resample(x_train, y_train)
+
+ # Evaluate the new model on the same test data each time.
+ y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
+
+# Note: Expectations and variances taken w.r.t. different training
+# data sets, hence the axis=1. Subsequent means are taken across the test data
+# set in order to obtain a total value, but before this we have error/bias/variance
+# calculated per data point in the test set.
+# Note 2: The use of keepdims=True is important in the calculation of bias as this
+# maintains the column vector form. Dropping this yields very unexpected results.
+error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+print('Error:', error)
+print('Bias^2:', bias)
+print('Var:', variance)
+print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))
+
+plt.plot(x[::5, :], y[::5, :], label='f(x)')
+plt.scatter(x_test, y_test, label='Data points')
+plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')
+plt.legend()
+plt.show()
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+
+np.random.seed(2018)
+
+n = 40
+n_boostraps = 100
+maxdegree = 14
+
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+for degree in range(maxdegree):
+ model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
+ y_pred = np.empty((y_test.shape[0], n_boostraps))
+ for i in range(n_boostraps):
+ x_, y_ = resample(x_train, y_train)
+ y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
+
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+ variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+ print('Polynomial degree:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+plt.show()
+
+The bias-variance tradeoff summarizes the fundamental tension in
+machine learning, particularly supervised learning, between the
+complexity of a model and the amount of training data needed to train
+it. Since data is often limited, in practice it is often useful to
+use a less-complex model with higher bias, that is a model whose asymptotic
+performance is worse than another model because it is easier to
+train and less sensitive to sampling noise arising from having a
+finite-sized training dataset (smaller variance).
+
+
+
+The above equations tell us that in
+order to minimize the expected test error, we need to select a
+statistical learning method that simultaneously achieves low variance
+and low bias. Note that variance is inherently a nonnegative quantity,
+and squared bias is also nonnegative. Hence, we see that the expected
+test MSE can never lie below $Var(\epsilon)$, the irreducible error.
+
+
+What do we mean by the variance and bias of a statistical learning
+method? The variance refers to the amount by which our model would change if we
+estimated it using a different training data set. Since the training
+data are used to fit the statistical learning method, different
+training data sets will result in a different estimate. But ideally the
+estimate for our model should not vary too much between training
+sets. However, if a method has high variance then small changes in
+the training data can result in large changes in the model. In general, more
+flexible statistical methods have higher variance.
+
+
+You may also find this recent [article](https://www.pnas.org/content/116/32/15849) of interest.
+
+"""
+============================
+Underfitting vs. Overfitting
+============================
+
+This example demonstrates the problems of underfitting and overfitting and
+how we can use linear regression with polynomial features to approximate
+nonlinear functions. The plot shows the function that we want to approximate,
+which is a part of the cosine function. In addition, the samples from the
+real function and the approximations of different models are displayed. The
+models have polynomial features of different degrees. We can see that a
+linear function (polynomial with degree 1) is not sufficient to fit the
+training samples. This is called **underfitting**. A polynomial of degree 4
+approximates the true function almost perfectly. However, for higher degrees
+the model will **overfit** the training data, i.e. it learns the noise of the
+training data.
+We evaluate quantitatively **overfitting** / **underfitting** by using
+cross-validation. We calculate the mean squared error (MSE) on the validation
+set, the higher, the less likely the model generalizes correctly from the
+training data.
+"""
+
+print(__doc__)
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)
-
-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.
-
-The above procedure with **numpy** can be made more compact if we use **pandas**.
+import matplotlib.pyplot as plt
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.linear_model import LinearRegression
+from sklearn.model_selection import cross_val_score
-We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code
+def true_fun(X):
+ return np.cos(1.5 * np.pi * 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)
-X = (np.vstack((x, y))).T
-print(X)
-Xpd = pd.DataFrame(X)
-print(Xpd)
-correlation_matrix = Xpd.corr()
-print(correlation_matrix)
+np.random.seed(0)
-We expand this model to the Franke function discussed above.
+n_samples = 30
+degrees = [1, 4, 15]
+
+X = np.sort(np.random.rand(n_samples))
+y = true_fun(X) + np.random.randn(n_samples) * 0.1
+
+plt.figure(figsize=(14, 5))
+for i in range(len(degrees)):
+ ax = plt.subplot(1, len(degrees), i + 1)
+ plt.setp(ax, xticks=(), yticks=())
+
+ polynomial_features = PolynomialFeatures(degree=degrees[i],
+ include_bias=False)
+ linear_regression = LinearRegression()
+ pipeline = Pipeline([("polynomial_features", polynomial_features),
+ ("linear_regression", linear_regression)])
+ pipeline.fit(X[:, np.newaxis], y)
+
+ # Evaluate the models using crossvalidation
+ scores = cross_val_score(pipeline, X[:, np.newaxis], y,
+ scoring="neg_mean_squared_error", cv=10)
+
+ X_test = np.linspace(0, 1, 100)
+ plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
+ plt.plot(X_test, true_fun(X_test), label="True function")
+ plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
+ plt.xlabel("x")
+ plt.ylabel("y")
+ plt.xlim((0, 1))
+ plt.ylim((-2, 2))
+ plt.legend(loc="best")
+ plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
+ degrees[i], -scores.mean(), scores.std()))
+plt.show()
# Common imports
+import os
import numpy as np
import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.model_selection import train_test_split
+from sklearn.utils import resample
+from sklearn.metrics import mean_squared_error
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
+
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
+
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
+
+infile = open(data_path("EoS.csv"),'r')
+
+# Read the EoS data as csv file and organize the data into two arrays with density and energies
+EoS = pd.read_csv(infile, names=('Density', 'Energy'))
+EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
+EoS = EoS.dropna()
+Energies = EoS['Energy']
+Density = EoS['Density']
+# The design matrix now as function of various polytrops
+
+Maxpolydegree = 30
+X = np.zeros((len(Density),Maxpolydegree))
+X[:,0] = 1.0
+testerror = np.zeros(Maxpolydegree)
+trainingerror = np.zeros(Maxpolydegree)
+polynomial = np.zeros(Maxpolydegree)
+
+trials = 100
+for polydegree in range(1, Maxpolydegree):
+ polynomial[polydegree] = polydegree
+ for degree in range(polydegree):
+ X[:,degree] = Density**(degree/3.0)
+
+# loop over trials in order to estimate the expectation value of the MSE
+ testerror[polydegree] = 0.0
+ trainingerror[polydegree] = 0.0
+ for samples in range(trials):
+ x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
+ model = LinearRegression(fit_intercept=True).fit(x_train, y_train)
+ ypred = model.predict(x_train)
+ ytilde = model.predict(x_test)
+ testerror[polydegree] += mean_squared_error(y_test, ytilde)
+ trainingerror[polydegree] += mean_squared_error(y_train, ypred)
+
+ testerror[polydegree] /= trials
+ trainingerror[polydegree] /= trials
+ print("Degree of polynomial: %3d"% polynomial[polydegree])
+ print("Mean squared error on training data: %.8f" % trainingerror[polydegree])
+ print("Mean squared error on test data: %.8f" % testerror[polydegree])
+
+plt.plot(polynomial, np.log10(trainingerror), label='Training Error')
+plt.plot(polynomial, np.log10(testerror), label='Test Error')
+plt.xlabel('Polynomial degree')
+plt.ylabel('log10[MSE]')
+plt.legend()
+plt.show()
+
+# Common imports
+import os
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.metrics import mean_squared_error
+from sklearn.model_selection import KFold
+from sklearn.model_selection import cross_val_score
-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
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
-def create_X(x, y, n ):
- if len(x.shape) > 1:
- x = np.ravel(x)
- y = np.ravel(y)
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
- N = len(x)
- l = int((n+1)*(n+2)/2) # Number of elements in beta
- X = np.ones((N,l))
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
- 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)
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
- return X
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
-# 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)
+infile = open(data_path("EoS.csv"),'r')
-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)
+# Read the EoS data as csv file and organize the data into two arrays with density and energies
+EoS = pd.read_csv(infile, names=('Density', 'Energy'))
+EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
+EoS = EoS.dropna()
+Energies = EoS['Energy']
+Density = EoS['Density']
+# The design matrix now as function of various polytrops
-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$).
+Maxpolydegree = 30
+X = np.zeros((len(Density),Maxpolydegree))
+X[:,0] = 1.0
+estimated_mse_sklearn = np.zeros(Maxpolydegree)
+polynomial = np.zeros(Maxpolydegree)
+k =5
+kfold = KFold(n_splits = k)
-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.
+for polydegree in range(1, Maxpolydegree):
+ polynomial[polydegree] = polydegree
+ for degree in range(polydegree):
+ X[:,degree] = Density**(degree/3.0)
+ OLS = LinearRegression()
+# loop over trials in order to estimate the expectation value of the MSE
+ estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)
+#[:, np.newaxis]
+ estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)
+plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')
+plt.xlabel('Polynomial degree')
+plt.ylabel('log10[MSE]')
+plt.legend()
+plt.show()
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.model_selection import KFold
+from sklearn.linear_model import Ridge
+from sklearn.model_selection import cross_val_score
+from sklearn.preprocessing import PolynomialFeatures
+# A seed just to ensure that the random numbers are the same for every run.
+np.random.seed(3155)
+# Generate the data.
+n = 100
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+# Decide degree on polynomial to fit
+poly = PolynomialFeatures(degree = 10)
-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}].
-$$
-
-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}.
-$$
-
-If we then compute the expectation value
-
-$$
-\mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}=\begin{bmatrix}
-x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\
-x_{10}x_{00}+x_{11}x_{01} & x_{10}^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 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}$.
-
-
-## Linking with SVD
\ No newline at end of file
+# Decide which values of lambda to use
+nlambdas = 500
+lambdas = np.logspace(-3, 5, nlambdas)
+# Initialize a KFold instance
+k = 5
+kfold = KFold(n_splits = k)
+estimated_mse_sklearn = np.zeros(nlambdas)
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
+ estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)
+ estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
+ i += 1
+plt.figure()
+plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
\ No newline at end of file
diff --git a/doc/LectureNotes/_build/jupyter_execute/chapter3_25_2.png b/doc/LectureNotes/_build/jupyter_execute/chapter3_25_2.png
new file mode 100644
index 000000000..98e9e3a97
Binary files /dev/null and b/doc/LectureNotes/_build/jupyter_execute/chapter3_25_2.png differ
diff --git a/doc/LectureNotes/chapter2.ipynb b/doc/LectureNotes/chapter2.ipynb
index d7f8222d5..1c18a18a0 100644
--- a/doc/LectureNotes/chapter2.ipynb
+++ b/doc/LectureNotes/chapter2.ipynb
@@ -4,66 +4,3340 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "# Resampling Methods\n",
- "\n",
- "## Introduction\n",
- "\n",
- "Resampling methods are an indispensable tool in modern\n",
- "statistics. They involve repeatedly drawing samples from a training\n",
- "set and refitting a model of interest on each sample in order to\n",
- "obtain additional information about the fitted model. For example, in\n",
- "order to estimate the variability of a linear regression fit, we can\n",
- "repeatedly draw different samples from the training data, fit a linear\n",
- "regression to each new sample, and then examine the extent to which\n",
- "the resulting fits differ. Such an approach may allow us to obtain\n",
- "information that would not be available from fitting the model only\n",
- "once using the original training sample.\n",
- "\n",
- "Two resampling methods are often used in Machine Learning analyses,\n",
- "1. The **bootstrap method**\n",
- "\n",
- "2. and **Cross-Validation**\n",
- "\n",
- "In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular\n",
- "cross-validation and the bootstrap method. \n",
+ "# Ridge and Lasso Regression\n",
"\n",
"\n",
- "Resampling approaches can be computationally expensive, because they\n",
- "involve fitting the same statistical method multiple times using\n",
- "different subsets of the training data. However, due to recent\n",
- "advances in computing power, the computational requirements of\n",
- "resampling methods generally are not prohibitive. In this chapter, we\n",
- "discuss two of the most commonly used resampling methods,\n",
- "cross-validation and the bootstrap. Both methods are important tools\n",
- "in the practical application of many statistical learning\n",
- "procedures. For example, cross-validation can be used to estimate the\n",
- "test error associated with a given statistical learning method in\n",
- "order to evaluate its performance, or to select the appropriate level\n",
- "of flexibility. The process of evaluating a model’s performance is\n",
- "known as model assessment, whereas the process of selecting the proper\n",
- "level of flexibility for a model is known as model selection. The\n",
- "bootstrap is widely used.\n",
+ "\n",
+ "## Mathematical Interpretation of Ordinary Least Squares\n",
+ "\n",
+ "What is presented here is a mathematical analysis of various regression algorithms (ordinary least squares, Ridge and Lasso Regression). The analysis is based on an important algorithm in linear algebra, the so-called Singular Value Decomposition (SVD). \n",
"\n",
"\n",
- "* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods\n",
+ "We have shown that in ordinary least squares the optimal parameters $\\beta$ are given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The **hat** over $\\boldsymbol{\\beta}$ means we have the optimal parameters after minimization of the cost function.\n",
"\n",
- "* The results can be analysed with the same statistical tools as we would use analysing experimental data.\n",
- "\n",
- "* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n",
- "\n",
- "## Reminder on Statistics\n",
+ "This means that our best model is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}=\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}} = \\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We now define a matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can rewrite"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}=\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}} = \\boldsymbol{A}\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The matrix $\\boldsymbol{A}$ has the important property that $\\boldsymbol{A}^2=\\boldsymbol{A}$. This is the definition of a projection matrix.\n",
+ "We can then interpret our optimal model $\\tilde{\\boldsymbol{y}}$ as being represented by an orthogonal projection of $\\boldsymbol{y}$ onto a space defined by the column vectors of $\\boldsymbol{X}$. In our case here the matrix $\\boldsymbol{A}$ is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix.\n",
"\n",
"\n",
- "* As in other experiments, many numerical experiments have two classes of errors:\n",
- "\n",
- " * Statistical errors\n",
- "\n",
- " * Systematical errors\n",
"\n",
"\n",
- "* Statistical errors can be estimated using standard tools from statistics\n",
+ "We have defined the residual error as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\epsilon}=\\boldsymbol{y}-\\tilde{\\boldsymbol{y}}=\\left[\\boldsymbol{I}-\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\right]\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The residual errors are then the projections of $\\boldsymbol{y}$ onto the orthogonal component of the space defined by the column vectors of $\\boldsymbol{X}$.\n",
+ "\n",
+ "\n",
+ "If the matrix $\\boldsymbol{X}$ is an orthogonal (or unitary in case of complex values) matrix, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{X}\\boldsymbol{X}^T = \\boldsymbol{I}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this case the matrix $\\boldsymbol{A}$ becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T)=\\boldsymbol{I},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and we have the obvious case"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\epsilon}=\\boldsymbol{y}-\\tilde{\\boldsymbol{y}}=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This serves also as a useful test of our codes. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## The singular value decomposition\n",
+ "\n",
+ "\n",
+ "The examples we have looked at so far are cases where we normally can\n",
+ "invert the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$. Using a polynomial expansion where we fit of various functions leads to\n",
+ "row vectors of the design matrix which are essentially orthogonal due\n",
+ "to the polynomial character of our model. Obtaining the inverse of the\n",
+ "design matrix is then often done via a so-called LU, QR or Cholesky\n",
+ "decomposition.\n",
+ "\n",
+ "\n",
+ "As we will also see in the first project, \n",
+ "this may\n",
+ "however not the be case in general and a standard matrix inversion\n",
+ "algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.\n",
+ "\n",
+ "There is however a way to circumvent this problem and also\n",
+ "gain some insights about the ordinary least squares approach, and\n",
+ "later shrinkage methods like Ridge and Lasso regressions.\n",
+ "\n",
+ "This is given by the **Singular Value Decomposition** (SVD) algorithm,\n",
+ "perhaps the most powerful linear algebra algorithm. The SVD provides\n",
+ "a numerically stable matrix decomposition that is used in a large\n",
+ "swath oc applications and the decomposition is always stable\n",
+ "numerically.\n",
+ "\n",
+ "In machine learning it plays a central role in dealing with for\n",
+ "example design matrices that may be near singular or singular.\n",
+ "Furthermore, as we will see here, the singular values can be related\n",
+ "to the covariance matrix (and thereby the correlation matrix) and in\n",
+ "turn the variance of a given quantity. It plays also an important role\n",
+ "in the principal component analysis where high-dimensional data can be\n",
+ "reduced to the statistically relevant features.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "One of the typical problems we encounter with linear regression, in particular \n",
+ "when the matrix $\\boldsymbol{X}$ (our so-called design matrix) is high-dimensional, \n",
+ "are problems with near singular or singular matrices. The column vectors of $\\boldsymbol{X}$ \n",
+ "may be linearly dependent, normally referred to as super-collinearity. \n",
+ "This means that the matrix may be rank deficient and it is basically impossible to \n",
+ "to model the data using linear regression. As an example, consider the matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\mathbf{X} & = \\left[\n",
+ "\\begin{array}{rrr}\n",
+ "1 & -1 & 2\n",
+ "\\\\\n",
+ "1 & 0 & 1\n",
+ "\\\\\n",
+ "1 & 2 & -1\n",
+ "\\\\\n",
+ "1 & 1 & 0\n",
+ "\\end{array} \\right]\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The columns of $\\boldsymbol{X}$ are linearly dependent. We see this easily since the \n",
+ "the first column is the row-wise sum of the other two columns. The rank (more correct,\n",
+ "the column rank) of a matrix is the dimension of the space spanned by the\n",
+ "column vectors. Hence, the rank of $\\mathbf{X}$ is equal to the number\n",
+ "of linearly independent columns. In this particular case the matrix has rank 2.\n",
+ "\n",
+ "Super-collinearity of an $(n \\times p)$-dimensional design matrix $\\mathbf{X}$ implies\n",
+ "that the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\boldsymbol{X} & = \\left[\n",
+ "\\begin{array}{rr}\n",
+ "1 & -1\n",
+ "\\\\\n",
+ "1 & -1\n",
+ "\\end{array} \\right].\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see easily that $\\mbox{det}(\\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \\times (-1) - 1 \\times (-1) = 0$. Hence, $\\mathbf{X}$ is singular and its inverse is undefined.\n",
+ "This is equivalent to saying that the matrix $\\boldsymbol{X}$ has at least an eigenvalue which is zero.\n",
+ "\n",
+ "\n",
+ "\n",
+ "If our design matrix $\\boldsymbol{X}$ which enters the linear regression problem"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "
\n",
+ "\n",
+ "$$\n",
+ "\\begin{equation}\n",
+ "\\boldsymbol{\\beta} = (\\boldsymbol{X}^{T} \\boldsymbol{X})^{-1} \\boldsymbol{X}^{T} \\boldsymbol{y},\n",
+ "\\label{_auto1} \\tag{1}\n",
+ "\\end{equation}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "has linearly dependent column vectors, we will not be able to compute the inverse\n",
+ "of $\\boldsymbol{X}^T\\boldsymbol{X}$ and we cannot find the parameters (estimators) $\\beta_i$. \n",
+ "The estimators are only well-defined if $(\\boldsymbol{X}^{T}\\boldsymbol{X})^{-1}$ exits. \n",
+ "This is more likely to happen when the matrix $\\boldsymbol{X}$ is high-dimensional. In this case it is likely to encounter a situation where \n",
+ "the regression parameters $\\beta_i$ cannot be estimated.\n",
+ "\n",
+ "A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^{T} \\boldsymbol{X} \\rightarrow \\boldsymbol{X}^{T} \\boldsymbol{X}+\\lambda \\boldsymbol{I},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\boldsymbol{I}$ is the identity matrix. When we discuss **Ridge** regression this is actually what we end up evaluating. The parameter $\\lambda$ is called a hyperparameter. More about this later. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Basic math of the SVD\n",
+ "\n",
+ "\n",
+ "From standard linear algebra we know that a square matrix $\\boldsymbol{X}$ can be diagonalized if and only it is \n",
+ "a so-called [normal matrix](https://en.wikipedia.org/wiki/Normal_matrix), that is if $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$\n",
+ "we have $\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ or if $\\boldsymbol{X}\\in {\\mathbb{C}}^{n\\times n}$ we have $\\boldsymbol{X}\\boldsymbol{X}^{\\dagger}=\\boldsymbol{X}^{\\dagger}\\boldsymbol{X}$.\n",
+ "The matrix has then a set of eigenpairs"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "(\\lambda_1,\\boldsymbol{u}_1),\\dots, (\\lambda_n,\\boldsymbol{u}_n),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and the eigenvalues are given by the diagonal matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}=\\mathrm{Diag}(\\lambda_1, \\dots,\\lambda_n).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The matrix $\\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\\boldsymbol{U}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ or $\\boldsymbol{U}\\boldsymbol{U}^{\\dagger}=\\boldsymbol{I}$.\n",
+ "\n",
+ "Not all square matrices are diagonalizable. A matrix like the one discussed above"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\begin{bmatrix} \n",
+ "1& -1 \\\\\n",
+ "1& -1\\\\\n",
+ "\\end{bmatrix}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "is not diagonalizable, it is a so-called [defective matrix](https://en.wikipedia.org/wiki/Defective_matrix). It is easy to see that the condition\n",
+ "$\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ is not fulfilled. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "However, and this is the strength of the SVD algorithm, any general\n",
+ "matrix $\\boldsymbol{X}$ can be decomposed in terms of a diagonal matrix and\n",
+ "two orthogonal/unitary matrices. The [Singular Value Decompostion\n",
+ "(SVD) theorem](https://en.wikipedia.org/wiki/Singular_value_decomposition)\n",
+ "states that a general $m\\times n$ matrix $\\boldsymbol{X}$ can be written in\n",
+ "terms of a diagonal matrix $\\boldsymbol{\\Sigma}$ of dimensionality $m\\times n$\n",
+ "and two orthognal matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$, where the first has\n",
+ "dimensionality $m \\times m$ and the last dimensionality $n\\times n$.\n",
+ "We have then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As an example, the above defective matrix can be decomposed as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X} = \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& 1 \\\\ 1& -1\\\\ \\end{bmatrix} \\begin{bmatrix} 2& 0 \\\\ 0& 0\\\\ \\end{bmatrix} \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& -1 \\\\ 1& 1\\\\ \\end{bmatrix}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with eigenvalues $\\sigma_1=2$ and $\\sigma_2=0$. \n",
+ "The SVD exits always! \n",
+ "\n",
+ "The SVD\n",
+ "decomposition (singular values) gives eigenvalues \n",
+ "$\\sigma_i\\geq\\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=p$, the\n",
+ "eigenvalues (singular values) are zero.\n",
+ "\n",
+ "In the general case, where our design matrix $\\boldsymbol{X}$ has dimension\n",
+ "$n\\times p$, the matrix is thus decomposed into an $n\\times n$\n",
+ "orthogonal matrix $\\boldsymbol{U}$, a $p\\times p$ orthogonal matrix $\\boldsymbol{V}$\n",
+ "and a diagonal matrix $\\boldsymbol{\\Sigma}$ with $r=\\mathrm{min}(n,p)$\n",
+ "singular values $\\sigma_i\\geq 0$ on the main diagonal and zeros filling\n",
+ "the rest of the matrix. There are at most $p$ singular values\n",
+ "assuming that $n > p$. In our regression examples for the nuclear\n",
+ "masses and the equation of state this is indeed the case, while for\n",
+ "the Ising model we have $p > n$. These are often cases that lead to\n",
+ "near singular or singular matrices.\n",
+ "\n",
+ "The columns of $\\boldsymbol{U}$ are called the left singular vectors while the columns of $\\boldsymbol{V}$ are the right singular vectors.\n",
+ "\n",
+ "\n",
+ "If we assume that $n > p$, then our matrix $\\boldsymbol{U}$ has dimension $n\n",
+ "\\times n$. The last $n-p$ columns of $\\boldsymbol{U}$ become however\n",
+ "irrelevant in our calculations since they are multiplied with the\n",
+ "zeros in $\\boldsymbol{\\Sigma}$.\n",
+ "\n",
+ "The economy-size decomposition removes extra rows or columns of zeros\n",
+ "from the diagonal matrix of singular values, $\\boldsymbol{\\Sigma}$, along with the columns\n",
+ "in either $\\boldsymbol{U}$ or $\\boldsymbol{V}$ that multiply those zeros in the expression. \n",
+ "Removing these zeros and columns can improve execution time\n",
+ "and reduce storage requirements without compromising the accuracy of\n",
+ "the decomposition.\n",
+ "\n",
+ "If $n > p$, we keep only the first $p$ columns of $\\boldsymbol{U}$ and $\\boldsymbol{\\Sigma}$ has dimension $p\\times p$. \n",
+ "If $p > n$, then only the first $n$ columns of $\\boldsymbol{V}$ are computed and $\\boldsymbol{\\Sigma}$ has dimension $n\\times n$.\n",
+ "The $n=p$ case is obvious, we retain the full SVD. \n",
+ "In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.\n",
+ "\n",
+ "## Codes for the SVD"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "# SVD inversion\n",
+ "def SVD(A):\n",
+ " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n",
+ " SVD is numerically more stable than the inversion algorithms provided by\n",
+ " numpy and scipy.linalg at the cost of being slower.\n",
+ " '''\n",
+ " U, S, VT = np.linalg.svd(A,full_matrices=True)\n",
+ " print('test U')\n",
+ " print( (np.transpose(U) @ U - U @np.transpose(U)))\n",
+ " print('test VT')\n",
+ " print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n",
+ " print(U)\n",
+ " print(S)\n",
+ " print(VT)\n",
+ "\n",
+ " D = np.zeros((len(U),len(VT)))\n",
+ " for i in range(0,len(VT)):\n",
+ " D[i,i]=S[i]\n",
+ " return U @ D @ VT\n",
+ "\n",
+ "\n",
+ "X = np.array([ [1.0,-1.0], [1.0,-1.0]])\n",
+ "#X = np.array([[1, 2], [3, 4], [5, 6]])\n",
+ "\n",
+ "print(X)\n",
+ "C = SVD(X)\n",
+ "# Print the difference between the original matrix and the SVD one\n",
+ "print(C-X)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The matrix $\\boldsymbol{X}$ has columns that are linearly dependent. The first\n",
+ "column is the row-wise sum of the other two columns. The rank of a\n",
+ "matrix (the column rank) is the dimension of space spanned by the\n",
+ "column vectors. The rank of the matrix is the number of linearly\n",
+ "independent columns, in this case just $2$. We see this from the\n",
+ "singular values when running the above code. Running the standard\n",
+ "inversion algorithm for matrix inversion with $\\boldsymbol{X}^T\\boldsymbol{X}$ results\n",
+ "in the program terminating due to a singular matrix.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The $U$, $S$, and $V$ matrices returned from the **svd()** function\n",
+ "cannot be multiplied directly.\n",
+ "\n",
+ "As you can see from the code, the $S$ vector must be converted into a\n",
+ "diagonal matrix. This may cause a problem as the size of the matrices\n",
+ "do not fit the rules of matrix multiplication, where the number of\n",
+ "columns in a matrix must match the number of rows in the subsequent\n",
+ "matrix.\n",
+ "\n",
+ "If you wish to include the zero singular values, you will need to\n",
+ "resize the matrices and set up a diagonal matrix as done in the above\n",
+ "example\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Mathematics of the SVD and implications\n",
+ "\n",
+ "Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies.\n",
+ "\n",
+ "Our starting point is our design matrix $\\boldsymbol{X}$ of dimension $n\\times p$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}\n",
+ "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
+ "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
+ "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
+ "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
+ "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
+ "\\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can SVD decompose our matrix as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\boldsymbol{U}$ is an orthogonal matrix of dimension $n\\times n$, meaning that $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{U}^T\\boldsymbol{U}=\\boldsymbol{I}_n$. Here $\\boldsymbol{I}_n$ is the unit matrix of dimension $n \\times n$.\n",
+ "\n",
+ "Similarly, $\\boldsymbol{V}$ is an orthogonal matrix of dimension $p\\times p$, meaning that $\\boldsymbol{V}\\boldsymbol{V}^T=\\boldsymbol{V}^T\\boldsymbol{V}=\\boldsymbol{I}_p$. Here $\\boldsymbol{I}_n$ is the unit matrix of dimension $p \\times p$.\n",
+ "\n",
+ "Finally $\\boldsymbol{\\Sigma}$ contains the singular values $\\sigma_i$. This matrix has dimension $n\\times p$ and the singular values $\\sigma_i$ are all positive. The non-zero values are ordered in descending order, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sigma_0 > \\sigma_1 > \\sigma_2 > \\dots > \\sigma_{p-1} > 0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "All values beyond $p-1$ are all zero.\n",
+ "\n",
+ "\n",
+ "As an example, consider the following $3\\times 2$ example for the matrix $\\boldsymbol{\\Sigma}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}=\n",
+ "\\begin{bmatrix}\n",
+ "2& 0 \\\\\n",
+ "0 & 1 \\\\\n",
+ "0 & 0 \\\\\n",
+ "\\end{bmatrix}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The singular values are $\\sigma_0=2$ and $\\sigma_1=1$. It is common to rewrite the matrix $\\boldsymbol{\\Sigma}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}=\n",
+ "\\begin{bmatrix}\n",
+ "\\boldsymbol{\\tilde{\\Sigma}}\\\\\n",
+ "\\boldsymbol{0}\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\tilde{\\Sigma}}=\n",
+ "\\begin{bmatrix}\n",
+ "2& 0 \\\\\n",
+ "0 & 1 \\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "contains only the singular values. Note also (and we will use this below) that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}=\n",
+ "\\begin{bmatrix}\n",
+ "4& 0 \\\\\n",
+ "0 & 1 \\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is a $2\\times 2 $ matrix while"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T=\n",
+ "\\begin{bmatrix}\n",
+ "4& 0 & 0\\\\\n",
+ "0 & 1 & 0\\\\\n",
+ "0 & 0 & 0\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "is a $3\\times 3 $ matrix. The last row and column of this last matrix\n",
+ "contain only zeros. This will have important consequences for our SVD\n",
+ "decomposition of the design matrix.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The matrix that may cause problems for us is $\\boldsymbol{X}^T\\boldsymbol{X}$. Using the SVD we can rewrite this matrix as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and using the orthogonality of the matrix $\\boldsymbol{U}$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We define $\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}=\\tilde{\\boldsymbol{\\Sigma}}^2$ which is a diagonal matrix containing only the singular values squared. It has dimensionality $p \\times p$.\n",
+ "\n",
+ "This means, using the orthogonality of $\\boldsymbol{V}$, that we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\tilde{\\boldsymbol{\\Sigma}}^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can now insert the result for the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ into our equation for ordinary least squares where"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and using our SVD decomposition of $\\boldsymbol{X}$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\tilde{\\boldsymbol{\\Sigma}}^{-2}\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which gives us, using the orthogonality of the matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_i\\boldsymbol{u}^T_j\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note here that when we perform the multiplication of the various matrices, the orthogonal vectors of the matrix $\\boldsymbol{U}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{U}=[\\boldsymbol{u}_0,\\boldsymbol{u}_1,\\dots,\\boldsymbol{u}_{n-1}],\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "that belong to $i>p-1$, result in only zeros when we perform the multiplications. This means that the sum above has non-zero elements only up to $i=p-1$. This corresponds also to the number of singular values (these are all non-zero).\n",
+ "\n",
+ "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}$.\n",
+ "\n",
+ "\n",
+ "## Further properties (important for our analyses later)\n",
+ "\n",
+ "Let us study again $\\boldsymbol{X}^T\\boldsymbol{X}$ in terms of our SVD,"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we now multiply from the right with $\\boldsymbol{V}$ (using the orthogonality of $\\boldsymbol{V}$) we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{V}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This means the vectors $\\boldsymbol{v}_i$ of the orthogonal matrix $\\boldsymbol{V}$ are the eigenvectors of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$\n",
+ "with eigenvalues given by the singular values squared, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{v}_i=\\boldsymbol{v}_i\\sigma_i^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Similarly, if we use the SVD decomposition for the matrix $\\boldsymbol{X}\\boldsymbol{X}^T$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we now multiply from the right with $\\boldsymbol{U}$ (using the orthogonality of $\\boldsymbol{U}$) we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}\\boldsymbol{X}^T\\right)\\boldsymbol{U}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This means the vectors $\\boldsymbol{u}_i$ of the orthogonal matrix $\\boldsymbol{U}$ are the eigenvectors of the matrix $\\boldsymbol{X}\\boldsymbol{X}^T$\n",
+ "with eigenvalues given by the singular values squared, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}\\boldsymbol{X}^T\\right)\\boldsymbol{u}_i=\\boldsymbol{u}_i\\sigma_i^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**Important note**: we have defined our design matrix $\\boldsymbol{X}$ to be an\n",
+ "$n\\times p$ matrix. In most supervised learning cases we have that $n\n",
+ "\\ge p$, and quite often we have $n >> p$. For linear algebra based methods like ordinary least squares or Ridge regression, this leads to a matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ which is small and thereby easier to handle from a computational point of view (in terms of number of floating point operations).\n",
+ "\n",
+ "In our lectures, the number of columns will\n",
+ "always refer to the number of features in our data set, while the\n",
+ "number of rows represents the number of data inputs. Note that in\n",
+ "other texts you may find the opposite notation. This has consequences\n",
+ "for the definition of for example the covariance matrix and its relation to the SVD.\n",
+ "\n",
+ "\n",
+ "## Meet the Covariance Matrix\n",
+ "\n",
+ "\n",
+ "Before we move on to a discussion of Ridge and Lasso regression, we want to show an important example of the above.\n",
+ "\n",
+ "We have already noted that the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ in ordinary\n",
+ "least squares is proportional to the second derivative of the cost\n",
+ "function, that is we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial^2 C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}^T\\partial \\boldsymbol{\\beta}} =\\frac{2}{n}\\boldsymbol{X}^T\\boldsymbol{X}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This quantity defines was what is called the Hessian matrix (the second derivative of a function we want to optimize).\n",
+ "\n",
+ "The Hessian matrix plays an important role and is defined in this course as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{H}=\\boldsymbol{X}^T\\boldsymbol{X}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The Hessian matrix for ordinary least squares is also proportional to\n",
+ "the covariance matrix. This means also that we can use the SVD to find\n",
+ "the eigenvalues of the covariance matrix and the Hessian matrix in\n",
+ "terms of the singular values. Let us develop these arguments, as they will play an important role in our machine learning studies.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about\n",
+ "the definition of the covariance and the correlation function. These are quantities that play a central role in machine learning methods.\n",
+ "\n",
+ "Suppose we have defined two vectors\n",
+ "$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
+ " \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where for example"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With this definition and recalling that the variance is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we can rewrite the covariance matrix as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
+ " \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n",
+ " \\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**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. \n",
+ "What you will find in essentially all statistics texts are equations\n",
+ "with a factor $1/(n-1)$. This is called [Bessel's correction](https://mathworld.wolfram.com/BesselsCorrection.html). This\n",
+ "method corrects the bias in the estimation of the population variance\n",
+ "and covariance. It also partially corrects the bias in the estimation\n",
+ "of the population standard deviation. If you use a library like\n",
+ "**Scikit-Learn** or **nunmpy's** function calculate the covariance, this\n",
+ "quantity will be computed with a factor $1/(n-1)$.\n",
+ "\n",
+ "\n",
+ "The covariance takes values between zero and infinity and may thus\n",
+ "lead to problems with loss of numerical precision for particularly\n",
+ "large values. It is common to scale the covariance matrix by\n",
+ "introducing instead the correlation matrix defined via the so-called\n",
+ "correlation function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]=\\frac{\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}]}{\\sqrt{\\mathrm{var}[\\boldsymbol{x}] \\mathrm{var}[\\boldsymbol{y}]}}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The correlation function is then given by values $\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]\n",
+ "\\in [-1,1]$. This avoids eventual problems with too large values. We\n",
+ "can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n",
+ "and $\\boldsymbol{y}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
+ " \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the above example this is the function we constructed using **pandas**.\n",
+ "\n",
+ "\n",
+ "\n",
+ "In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**\n",
+ "we defined the design/feature matrix $\\boldsymbol{X}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}\n",
+ "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
+ "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
+ "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
+ "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
+ "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ refering to the column numbers and the\n",
+ "entries $n$ being the row elements.\n",
+ "We can rewrite the design/feature matrix in terms of its column vectors as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with a given vector"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{x}_i^T = \\begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \\dots & \\dots x_{n-1,i}\\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "With these definitions, we can now rewrite our $2\\times 2$\n",
+ "correlation/covariance matrix in terms of a moe general design/feature\n",
+ "matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$\n",
+ "covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i=0,1,\\dots,p-1$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
+ "\\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}]\\\\\n",
+ "\\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}]\\\\\n",
+ "\\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}]\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\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}]\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and the correlation matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
+ "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}]\\\\\n",
+ "\\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}]\\\\\n",
+ "\\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}]\\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
+ "\\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\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The Numpy function **np.cov** calculates the covariance elements using\n",
+ "the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n",
+ "the exact mean values. The following simple function uses the\n",
+ "**np.vstack** function which takes each vector of dimension $1\\times n$\n",
+ "and produces a $2\\times n$ matrix $\\boldsymbol{W}$\n",
+ "\n",
+ "Note that this assumes you have the features as the rows, and the inputs as columns, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{W} = \\begin{bmatrix} x_0 & x_1 & x_2 & \\dots & x_{n-2} & x_{n-1} \\\\\n",
+ " y_0 & y_1 & y_2 & \\dots & y_{n-2} & y_{n-1} \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which in turn is converted into into the $2\\times 2$ covariance matrix\n",
+ "$\\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate\n",
+ "the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n",
+ "function **np.mean(x)**. We can also extract the eigenvalues of the\n",
+ "covariance matrix through the **np.linalg.eig()** function."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Importing various packages\n",
+ "import numpy as np\n",
+ "n = 100\n",
+ "x = np.random.normal(size=n)\n",
+ "print(np.mean(x))\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "print(np.mean(y))\n",
+ "W = np.vstack((x, y))\n",
+ "C = np.cov(W)\n",
+ "print(C)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The previous example can be converted into the correlation matrix by\n",
+ "simply scaling the matrix elements with the variances. We should also\n",
+ "subtract the mean values for each column. This leads to the following\n",
+ "code which sets up the correlations matrix for the previous example in\n",
+ "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)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "n = 100\n",
+ "# define two vectors \n",
+ "x = np.random.random(size=n)\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "#scaling the x and y vectors \n",
+ "x = x - np.mean(x)\n",
+ "y = y - np.mean(y)\n",
+ "variance_x = np.sum(x@x)/n\n",
+ "variance_y = np.sum(y@y)/n\n",
+ "print(variance_x)\n",
+ "print(variance_y)\n",
+ "cov_xy = np.sum(x@y)/n\n",
+ "cov_xx = np.sum(x@x)/n\n",
+ "cov_yy = np.sum(y@y)/n\n",
+ "C = np.zeros((2,2))\n",
+ "C[0,0]= cov_xx/variance_x\n",
+ "C[1,1]= cov_yy/variance_y\n",
+ "C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n",
+ "C[1,0]= C[0,1]\n",
+ "print(C)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see that the matrix elements along the diagonal are one as they\n",
+ "should be and that the matrix is symmetric. Furthermore, diagonalizing\n",
+ "this matrix we easily see that it is a positive definite matrix.\n",
+ "\n",
+ "The above procedure with **numpy** can be made more compact if we use **pandas**.\n",
+ "\n",
+ "\n",
+ "\n",
+ "We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "n = 10\n",
+ "x = np.random.normal(size=n)\n",
+ "x = x - np.mean(x)\n",
+ "y = 4+3*x+np.random.normal(size=n)\n",
+ "y = y - np.mean(y)\n",
+ "# Note that we transpose the matrix in order to stay with our ordering n x p\n",
+ "X = (np.vstack((x, y))).T\n",
+ "print(X)\n",
+ "Xpd = pd.DataFrame(X)\n",
+ "print(Xpd)\n",
+ "correlation_matrix = Xpd.corr()\n",
+ "print(correlation_matrix)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We expand this model to the Franke function discussed earlier."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Common imports\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "\n",
+ "\n",
+ "def FrankeFunction(x,y):\n",
+ "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
+ "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
+ "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
+ "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
+ "\treturn term1 + term2 + term3 + term4\n",
+ "\n",
+ "\n",
+ "def create_X(x, y, n ):\n",
+ "\tif len(x.shape) > 1:\n",
+ "\t\tx = np.ravel(x)\n",
+ "\t\ty = np.ravel(y)\n",
+ "\n",
+ "\tN = len(x)\n",
+ "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n",
+ "\tX = np.ones((N,l))\n",
+ "\n",
+ "\tfor i in range(1,n+1):\n",
+ "\t\tq = int((i)*(i+1)/2)\n",
+ "\t\tfor k in range(i+1):\n",
+ "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n",
+ "\n",
+ "\treturn X\n",
+ "\n",
+ "\n",
+ "# Making meshgrid of datapoints and compute Franke's function\n",
+ "n = 4\n",
+ "N = 100\n",
+ "x = np.sort(np.random.uniform(0, 1, N))\n",
+ "y = np.sort(np.random.uniform(0, 1, N))\n",
+ "z = FrankeFunction(x, y)\n",
+ "X = create_X(x, y, n=n) \n",
+ "\n",
+ "Xpd = pd.DataFrame(X)\n",
+ "# subtract the mean values and set up the covariance matrix\n",
+ "Xpd = Xpd - Xpd.mean()\n",
+ "covariance_matrix = Xpd.cov()\n",
+ "print(covariance_matrix)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We note here that the covariance is zero for the first rows and\n",
+ "columns since all matrix elements in the design matrix were set to one\n",
+ "(we are fitting the function in terms of a polynomial of degree $n$).\n",
+ "\n",
+ "This means that the variance for these elements will be zero and will\n",
+ "cause problems when we set up the correlation matrix. We can simply\n",
+ "drop these elements and construct a correlation\n",
+ "matrix without these elements. \n",
+ "\n",
+ "\n",
+ "\n",
+ "We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\\boldsymbol{X}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}\n",
+ "x_{00} & x_{01}\\\\\n",
+ "x_{10} & x_{11}\\\\\n",
+ "\\end{bmatrix}=\\begin{bmatrix}\n",
+ "\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n",
+ "\\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we then compute the expectation value (note the $1/n$ factor instead of $1/(n-1)$)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}=\\frac{1}{n}\\begin{bmatrix}\n",
+ "x_{00}^2+x_{10}^2 & x_{00}x_{01}+x_{10}x_{11}\\\\\n",
+ "x_{01}x_{00}+x_{11}x_{10} & x_{01}^2+x_{11}^2\\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is just"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\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] \\\\\n",
+ " \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n",
+ " \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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}$.\n",
+ "\n",
+ "It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Linking with the SVD\n",
+ "\n",
+ "We saw earlier that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Since the matrices here have dimension $p\\times p$, with $p$ corresponding to the singular values, we defined earlier the matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma} = \\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0}\\\\ \\end{bmatrix}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\\\ \\boldsymbol{0}\\\\ \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where the tilde-matrix $\\tilde{\\boldsymbol{\\Sigma}}$ is a matrix of dimension $p\\times p$ containing only the singular values $\\sigma_i$, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{\\Sigma}}=\\begin{bmatrix} \\sigma_0 & 0 & 0 & \\dots & 0 & 0 \\\\\n",
+ " 0 & \\sigma_1 & 0 & \\dots & 0 & 0 \\\\\n",
+ "\t\t\t\t 0 & 0 & \\sigma_2 & \\dots & 0 & 0 \\\\\n",
+ "\t\t\t\t 0 & 0 & 0 & \\dots & \\sigma_{p-2} & 0 \\\\\n",
+ "\t\t\t\t 0 & 0 & 0 & \\dots & 0 & \\sigma_{p-1} \\\\\n",
+ "\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "meaning we can write"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\tilde{\\boldsymbol{\\Sigma}}^2\\boldsymbol{V}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Multiplying from the right with $\\boldsymbol{V}$ (using the orthogonality of $\\boldsymbol{V}$) we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{V}=\\boldsymbol{V}\\tilde{\\boldsymbol{\\Sigma}}^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This means the vectors $\\boldsymbol{v}_i$ of the orthogonal matrix $\\boldsymbol{V}$\n",
+ "are the eigenvectors of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ with eigenvalues\n",
+ "given by the singular values squared, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{v}_i=\\boldsymbol{v}_i\\sigma_i^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In other words, each non-zero singular value of $\\boldsymbol{X}$ is a positive\n",
+ "square root of an eigenvalue of $\\boldsymbol{X}^T\\boldsymbol{X}$. It means also that\n",
+ "the columns of $\\boldsymbol{V}$ are the eigenvectors of\n",
+ "$\\boldsymbol{X}^T\\boldsymbol{X}$. Since we have ordered the singular values of\n",
+ "$\\boldsymbol{X}$ in a descending order, it means that the column vectors\n",
+ "$\\boldsymbol{v}_i$ are hierarchically ordered by how much correlation they\n",
+ "encode from the columns of $\\boldsymbol{X}$. \n",
+ "\n",
+ "\n",
+ "Note that these are also the eigenvectors and eigenvalues of the\n",
+ "Hessian matrix.\n",
+ "\n",
+ "If we now recall the definition of the covariance matrix (not using\n",
+ "Bessel's correction) we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{C}[\\boldsymbol{X}]=\\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "meaning that every squared non-singular value of $\\boldsymbol{X}$ divided by $n$ (\n",
+ "the number of samples) are the eigenvalues of the covariance\n",
+ "matrix. Every singular value of $\\boldsymbol{X}$ is thus a positive square\n",
+ "root of an eigenvalue of $\\boldsymbol{X}^T\\boldsymbol{X}$. If the matrix $\\boldsymbol{X}$ is\n",
+ "self-adjoint, the singular values of $\\boldsymbol{X}$ are equal to the\n",
+ "absolute value of the eigenvalues of $\\boldsymbol{X}$.\n",
+ "\n",
+ "\n",
+ "For $\\boldsymbol{X}\\boldsymbol{X}^T$ we found"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{U}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Since the matrices here have dimension $n\\times n$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T = \\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\\\ \\boldsymbol{0}\\\\ \\end{bmatrix}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\boldsymbol{0}\\\\ \\end{bmatrix}=\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "leading to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix}\\boldsymbol{U}^T.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Multiplying with $\\boldsymbol{U}$ from the right gives us the eigenvalue problem"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U}=\\boldsymbol{U}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It means that the eigenvalues of $\\boldsymbol{X}\\boldsymbol{X}^T$ are again given by\n",
+ "the non-zero singular values plus now a series of zeros. The column\n",
+ "vectors of $\\boldsymbol{U}$ are the eigenvectors of $\\boldsymbol{X}\\boldsymbol{X}^T$ and\n",
+ "measure how much correlations are contained in the rows of $\\boldsymbol{X}$.\n",
+ "\n",
+ "Since we will mainly be interested in the correlations among the features\n",
+ "of our data (the columns of $\\boldsymbol{X}$, the quantity of interest for us are the non-zero singular\n",
+ "values and the column vectors of $\\boldsymbol{V}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Ridge and LASSO Regression\n",
+ "\n",
+ "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n",
+ "our optimization problem is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or we can state it as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have used the definition of a norm-2 vector, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "By minimizing the above equation with respect to the parameters\n",
+ "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n",
+ "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n",
+ "defining a new cost function to be optimized, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to the Ridge regression minimization problem where we\n",
+ "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n",
+ "a finite number larger than zero. By defining"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have a new optimization equation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n",
+ "\n",
+ "Here we have defined the norm-1 as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and \n",
+ "taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n",
+ "a slightly modified matrix inversion problem which for finite values\n",
+ "of $\\lambda$ does not suffer from singularity problems. We obtain\n",
+ "the optimal parameters"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $t$ a finite positive number. \n",
+ "\n",
+ "When we compare this with the ordinary least squares result we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$.\n",
+ "\n",
+ "\n",
+ "We see that Ridge regression is nothing but the standard OLS with a\n",
+ "modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The consequences, in\n",
+ "particular for our discussion of the bias-variance tradeoff are rather\n",
+ "interesting. We will see that for specific values of $\\lambda$, we may\n",
+ "even reduce the variance of the optimal parameters $\\boldsymbol{\\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.\n",
+ "\n",
+ "Using our insights about the SVD of the design matrix $\\boldsymbol{X}$ \n",
+ "We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}_{\\mathrm{OLS}}=\\boldsymbol{X}\\boldsymbol{\\beta} =\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For Ridge regression this becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}_{\\mathrm{Ridge}}=\\boldsymbol{X}\\boldsymbol{\\beta}_{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{\\Sigma}^2\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$ from the SVD of the matrix $\\boldsymbol{X}$. \n",
+ "\n",
+ "\n",
+ "Since $\\lambda \\geq 0$, it means that compared to OLS, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n",
+ "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n",
+ "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n",
+ "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n",
+ "\\sigma_{i+1}$.\n",
+ "\n",
+ "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.\n",
+ "\n",
+ "\n",
+ "\n",
+ "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this case the standard OLS results in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n",
+ "the Ridge estimator converges to zero when the hyperparameter goes to\n",
+ "infinity.\n",
+ "\n",
+ "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n",
+ "\n",
+ "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n",
+ "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\n",
+ "\n",
+ "\n",
+ "Using the matrix-vector expression for Lasso regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have the following **cost** function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{d \\vert \\beta\\vert}{d \\boldsymbol{\\beta}}=\\mathrm{sgn}(\\boldsymbol{\\beta})=\\left\\{\\begin{array}{cc} 1 & \\beta > 0 \\\\ 0 & \\beta =0\\\\-1 & \\beta < 0, \\end{array}\\right.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have that the derivative of the cost function is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{X},\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}=-2\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})+\\lambda sgn(\\boldsymbol{\\beta})=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and reordering we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta})+\\lambda sgn(\\boldsymbol{\\beta})=2\\boldsymbol{X}^T(\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This equation does not lead to a nice analytical equation as in either Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms using for example the Python package [CVXOPT](https://cvxopt.org/). We will discuss this later. \n",
+ "\n",
+ "## Code for SVD and Inversion of Matrices\n",
+ "\n",
+ "How do we use the SVD to invert a matrix $\\boldsymbol{X}^\\boldsymbol{X}$ which is singular or near singular?\n",
+ "The simple answer is to use the linear algebra function for pseudoinvers, that is"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "Ainv = np.linlag.pinv(A)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let us first look at a matrix which does not causes problems and write our own function where we just use the SVD."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "# SVD inversion\n",
+ "def SVDinv(A):\n",
+ " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n",
+ " SVD is numerically more stable than the inversion algorithms provided by\n",
+ " numpy and scipy.linalg at the cost of being slower.\n",
+ " '''\n",
+ " U, s, VT = np.linalg.svd(A)\n",
+ " print('test U')\n",
+ " print( (np.transpose(U) @ U - U @np.transpose(U)))\n",
+ " print('test VT')\n",
+ " print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n",
+ "\n",
+ "\n",
+ " D = np.zeros((len(U),len(VT)))\n",
+ " D = np.diag(s)\n",
+ " UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)\n",
+ " return np.matmul(V,np.matmul(invD,UT))\n",
+ "\n",
+ "\n",
+ "#X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])\n",
+ "# Non-singular square matrix\n",
+ "X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])\n",
+ "print(X)\n",
+ "A = np.transpose(X) @ X\n",
+ "# Brute force inversion\n",
+ "B = np.linalg.inv(A) # here we could use np.linalg.pinv(A)\n",
+ "C = SVDinv(A)\n",
+ "print(np.abs(B-C))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Although our matrix to invert $\\boldsymbol{X}^T\\boldsymbol{X}$ is a square matrix, our matrix may be singular. \n",
+ "\n",
+ "The pseudoinverse is the generalization of the matrix inverse for square matrices to\n",
+ "rectangular matrices where the number of rows and columns are not equal.\n",
+ "\n",
+ "It is also called the the Moore-Penrose Inverse after two independent discoverers of the method or the Generalized Inverse.\n",
+ "It is used for the calculation of the inverse for singular or near singular matrices and for rectangular matrices.\n",
+ "\n",
+ "Using the SVD we can obtain the pseudoinverse of a matrix $\\boldsymbol{A}$ (labeled here as $\\boldsymbol{A}_{\\mathrm{PI}}$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{A}_{\\mathrm{PI}}= \\boldsymbol{V}\\boldsymbol{D}_{\\mathrm{PI}}\\boldsymbol{U}^T,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\boldsymbol{D}_{\\mathrm{PI}}$ can be calculated by creating a diagonal matrix from $\\boldsymbol{Sigma}$ where we only keep the singular values (the non-zero values). The following code computes the pseudoinvers of the matrix based on the SVD."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "# SVD inversion\n",
+ "def SVDinv(A):\n",
+ " U, s, VT = np.linalg.svd(A)\n",
+ " # reciprocals of singular values of s\n",
+ " d = 1.0 / s\n",
+ " # create m x n D matrix\n",
+ " D = np.zeros(A.shape)\n",
+ " # populate D with n x n diagonal matrix\n",
+ " D[:A.shape[1], :A.shape[1]] = np.diag(d)\n",
+ " UT = np.transpose(U)\n",
+ " V = np.transpose(VT)\n",
+ " return np.matmul(V,np.matmul(D.T,UT))\n",
+ "\n",
+ "\n",
+ "A = np.array([ [0.3, 0.4], [0.5, 0.6], [0.7, 0.8],[0.9, 1.0]])\n",
+ "print(A)\n",
+ "# Brute force inversion of super-collinear matrix\n",
+ "B = np.linalg.pinv(A)\n",
+ "print(B)\n",
+ "# Compare our own algorithm with pinv\n",
+ "C = SVDinv(A)\n",
+ "print(np.abs(C-B))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see from this example, our own decomposition based on the SVD agrees the pseudoinverse algorithm provided by **Numpy**.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Deriving the Ridge Regression Equations\n",
+ "\n",
+ "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n",
+ "our optimization problem is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or we can state it as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we have used the definition of a norm-2 vector, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "By minimizing the above equation with respect to the parameters\n",
+ "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n",
+ "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n",
+ "defining a new cost function to be optimized, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to the Ridge regression minimization problem where we\n",
+ "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n",
+ "a finite number larger than zero. By defining"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have a new optimization equation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
+ "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n",
+ "\n",
+ "Here we have defined the norm-1 as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and \n",
+ "taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n",
+ "a slightly modified matrix inversion problem which for finite values\n",
+ "of $\\lambda$ does not suffer from singularity problems. We obtain\n",
+ "the optimal parameters"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with $t$ a finite positive number. \n",
+ "\n",
+ "When we compare this with the ordinary least squares result we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$.\n",
+ "\n",
+ "\n",
+ "We see that Ridge regression is nothing but the standard OLS with a\n",
+ "modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The consequences, in\n",
+ "particular for our discussion of the bias-variance tradeoff are rather\n",
+ "interesting. We will see that for specific values of $\\lambda$, we may\n",
+ "even reduce the variance of the optimal parameters $\\boldsymbol{\\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Using our insights about the SVD of the design matrix $\\boldsymbol{X}$ \n",
+ "We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}_{\\mathrm{OLS}}=\\boldsymbol{X}\\boldsymbol{\\beta} =\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For Ridge regression this becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\tilde{\\boldsymbol{y}}_{\\mathrm{Ridge}}=\\boldsymbol{X}\\boldsymbol{\\beta}_{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{\\Sigma}^2\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$ from the SVD of the matrix $\\boldsymbol{X}$. \n",
+ "\n",
+ "\n",
+ "\n",
+ "Since $\\lambda \\geq 0$, it means that compared to OLS, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n",
+ "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n",
+ "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n",
+ "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n",
+ "\\sigma_{i+1}$.\n",
+ "\n",
+ "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.\n",
+ "\n",
+ "\n",
+ "\n",
+ "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this case the standard OLS results in"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n",
+ "the Ridge estimator converges to zero when the hyperparameter goes to\n",
+ "infinity.\n",
+ "\n",
+ "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n",
+ "\n",
+ "\n",
+ "\n",
+ "Using the matrix-vector expression for Lasso regression and dropping the parameter $1/n$ in front of the standard mean squared error equation, we have the following **cost** function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{d \\vert \\beta\\vert}{d \\boldsymbol{\\beta}}=\\mathrm{sgn}(\\boldsymbol{\\beta})=\\left\\{\\begin{array}{cc} 1 & \\beta > 0 \\\\ 0 & \\beta =0\\\\-1 & \\beta < 0, \\end{array}\\right.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we have that the derivative of the cost function is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{X},\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}=-2\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})+\\lambda sgn(\\boldsymbol{\\beta})=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and reordering we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta}+\\lambda sgn(\\boldsymbol{\\beta})=2\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This equation does not lead to a nice analytical equation as in 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](https://cvxopt.org/). We will discuss this later. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "Let us assume that our design matrix is given by unit (identity) matrix, that is a square diagonal matrix with ones only along the\n",
+ "diagonal. In this case we have an equal number of rows and columns $n=p$.\n",
+ "\n",
+ "Our model approximation is just $\\tilde{\\boldsymbol{y}}=\\boldsymbol{\\beta}$ and the mean squared error and thereby the cost function for ordinary least sqquares (OLS) is then (we drop the term $1/n$)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and minimizing we have that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\beta}_i^{\\mathrm{OLS}} = y_i.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For Ridge regression our cost function is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\beta_i^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and minimizing we have that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\beta}_i^{\\mathrm{Ridge}} = \\frac{y_i}{1+\\lambda}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For Lasso regression our cost function is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\vert\\beta_i\\vert=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\sqrt{\\beta_i^2},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and minimizing we have that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "-2\\sum_{i=0}^{p-1}(y_i-\\beta_i)+\\lambda \\sum_{i=0}^{p-1}\\frac{(\\beta_i)}{\\vert\\beta_i\\vert}=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}_i^{\\mathrm{Lasso}} = \\left\\{\\begin{array}{ccc}y_i-\\frac{\\lambda}{2} &\\mathrm{if} & y_i> \\frac{\\lambda}{2}\\\\\n",
+ " y_i+\\frac{\\lambda}{2} &\\mathrm{if} & y_i< -\\frac{\\lambda}{2}\\\\\n",
+ "\t\t\t\t\t\t\t 0 &\\mathrm{if} & \\vert y_i\\vert\\le \\frac{\\lambda}{2}\\end{array}\\right.\\\\.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Plotting these results ([figure in handwritten notes for week 36](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2021/NotesSeptember9.pdf)) shows clearly that Lasso regression suppresses (sets to zero) values of $\\beta_i$ for specific values of $\\lambda$. Ridge regression reduces on the other hand the values of $\\beta_i$ as function of $\\lambda$.\n",
+ "\n",
+ "\n",
+ "As another examples, \n",
+ "let us assume we have a data set with outputs/targets given by the vector"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{y}=\\begin{bmatrix}4 \\\\ 2 \\\\3\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and our inputs as a $3\\times 2$ design matrix"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}=\\begin{bmatrix}2 & 0\\\\ 0 & 1 \\\\ 0 & 0\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "meaning that we have two features and two unknown parameters $\\beta_0$ and $\\beta_1$ to be determined either by ordinary least squares, Ridge or Lasso regression.\n",
+ "\n",
+ "\n",
+ "For ordinary least squares (OLS) we know that the optimal solution is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\left( \\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Inserting the above values we obtain that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\begin{bmatrix}2 \\\\ 2\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The code which implements this simpler case is presented after the discussion of Ridge and Lasso.\n",
+ "\n",
+ "\n",
+ "For Ridge regression we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}}=\\left( \\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Inserting the above values we obtain that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}}=\\begin{bmatrix}\\frac{8}{4+\\lambda} \\\\ \\frac{2}{1+\\lambda}\\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "There is normally a constraint on the value of $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2$ via the parameter $\\lambda$.\n",
+ "Let us for simplicity assume that $\\beta_0^2+\\beta_1^2=1$ as constraint. This will allow us to find an expression for the optimal values of $\\beta$ and $\\lambda$.\n",
+ "\n",
+ "To see this, let us write the cost function for Ridge regression. \n",
+ "\n",
+ "\n",
+ "\n",
+ "We define the MSE without the $1/n$ factor and have then, using that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}\\boldsymbol{\\beta}=\\begin{bmatrix} 2\\beta_0 \\\\ \\beta_1 \\\\0 \\end{bmatrix},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=(4-2\\beta_0)^2+(2-\\beta_1)^2+\\lambda(\\beta_0^2+\\beta_1^2),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and taking the derivative with respect to $\\beta_0$ we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_0=\\frac{8}{4+\\lambda},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and for $\\beta_1$ we obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_1=\\frac{2}{1+\\lambda},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using the constraint for $\\beta_0^2+\\beta_1^2=1$ we can constrain $\\lambda$ by solving"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\left(\\frac{8}{4+\\lambda}\\right)^2+\\left(\\frac{2}{1+\\lambda}\\right)^2=1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which gives $\\lambda=4.571$ and $\\beta_0=0.933$ and $\\beta_1=0.359$.\n",
+ "\n",
+ "\n",
+ "For Lasso we need now, keeping a constraint on $\\vert\\beta_0\\vert+\\vert\\beta_1\\vert=1$, to take the derivative of the absolute values of $\\beta_0$\n",
+ "and $\\beta_1$. This gives us the following derivatives of the cost function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=(4-2\\beta_0)^2+(2-\\beta_1)^2+\\lambda(\\vert\\beta_0\\vert+\\vert\\beta_1\\vert),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_0}=-4(4-2\\beta_0)+\\lambda\\mathrm{sgn}(\\beta_0)=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_1}=-2(2-\\beta_1)+\\lambda\\mathrm{sgn}(\\beta_1)=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We have now four cases to solve besides the trivial cases $\\beta_0$ and/or $\\beta_1$ are zero, namely\n",
+ "1. $\\beta_0 > 0$ and $\\beta_1 > 0$,\n",
+ "\n",
+ "2. $\\beta_0 > 0$ and $\\beta_1 < 0$,\n",
+ "\n",
+ "3. $\\beta_0 < 0$ and $\\beta_1 > 0$,\n",
+ "\n",
+ "4. $\\beta_0 < 0$ and $\\beta_1 < 0$.\n",
+ "\n",
+ "If we consider the first case, we have then"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "-4(4-2\\beta_0)+\\lambda=0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "-2(2-\\beta_1)+\\lambda=0.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which yields"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_0=\\frac{16+\\lambda}{8},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\beta_1=\\frac{4+\\lambda}{2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using the constraint on $\\beta_0$ and $\\beta_1$ we can then find the optimal value of $\\lambda$ for the different cases. We leave this as an exercise to you.\n",
+ "\n",
+ "\n",
+ "Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of $\\lambda$, meaning that we need to perform a search in order to find the optimal values.\n",
+ "\n",
+ "First we study and compare the OLS and Ridge results. The next code compares all three methods."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "def R2(y_data, y_model):\n",
+ " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
+ "\n",
+ "\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "\n",
+ "X = np.array( [ [ 2, 0], [0, 1], [0,0]])\n",
+ "y = np.array( [4, 2, 3])\n",
+ "\n",
+ "\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y\n",
+ "print(OLSbeta)\n",
+ "# and then make the prediction\n",
+ "ytildeOLS = X @ OLSbeta\n",
+ "print(\"Training MSE for OLS\")\n",
+ "print(MSE(y,ytildeOLS))\n",
+ "ypredictOLS = X @ OLSbeta\n",
+ "\n",
+ "# Repeat now for Ridge regression and various values of the regularization parameter\n",
+ "I = np.eye(2,2)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 100\n",
+ "MSEPredict = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 4, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y\n",
+ "# print(Ridgebeta)\n",
+ " # and then make the prediction\n",
+ " ypredictRidge = X @ Ridgebeta\n",
+ " MSEPredict[i] = MSE(y,ypredictRidge)\n",
+ "# print(MSEPredict[i])\n",
+ " # Now plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Train')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We see here that we reach a plateau. What is actually happening?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn import linear_model\n",
+ "\n",
+ "def R2(y_data, y_model):\n",
+ " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
+ "\n",
+ "\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "\n",
+ "X = np.array( [ [ 2, 0], [0, 1], [0,0]])\n",
+ "y = np.array( [4, 2, 3])\n",
+ "\n",
+ "\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y\n",
+ "print(OLSbeta)\n",
+ "# and then make the prediction\n",
+ "ytildeOLS = X @ OLSbeta\n",
+ "print(\"Training MSE for OLS\")\n",
+ "print(MSE(y,ytildeOLS))\n",
+ "ypredictOLS = X @ OLSbeta\n",
+ "\n",
+ "# Repeat now for Ridge regression and various values of the regularization parameter\n",
+ "I = np.eye(2,2)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 100\n",
+ "MSERidgePredict = np.zeros(nlambdas)\n",
+ "MSELassoPredict = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 4, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y\n",
+ " print(Ridgebeta)\n",
+ " # and then make the prediction\n",
+ " ypredictRidge = X @ Ridgebeta\n",
+ " MSERidgePredict[i] = MSE(y,ypredictRidge)\n",
+ " RegLasso = linear_model.Lasso(lmb)\n",
+ " RegLasso.fit(X,y)\n",
+ " ypredictLasso = RegLasso.predict(X)\n",
+ " print(RegLasso.coef_)\n",
+ " MSELassoPredict[i] = MSE(y,ypredictLasso)\n",
+ "# Now plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSERidgePredict, 'r--', label = 'MSE Ridge Train')\n",
+ "plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Train')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Another Example, now with a polynomial fit."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn import linear_model\n",
+ "\n",
+ "def R2(y_data, y_model):\n",
+ " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
+ "\n",
+ "\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "np.random.seed(3155)\n",
+ "\n",
+ "x = np.random.rand(100)\n",
+ "y = 2.0+5*x*x+0.1*np.random.randn(100)\n",
+ "\n",
+ "# number of features p (here degree of polynomial\n",
+ "p = 3\n",
+ "# The design matrix now as function of a given polynomial\n",
+ "X = np.zeros((len(x),p))\n",
+ "X[:,0] = 1.0\n",
+ "X[:,1] = x\n",
+ "X[:,2] = x*x\n",
+ "# We split the data in test and training data\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
+ "\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n",
+ "print(OLSbeta)\n",
+ "# and then make the prediction\n",
+ "ytildeOLS = X_train @ OLSbeta\n",
+ "print(\"Training MSE for OLS\")\n",
+ "print(MSE(y_train,ytildeOLS))\n",
+ "ypredictOLS = X_test @ OLSbeta\n",
+ "print(\"Test MSE OLS\")\n",
+ "print(MSE(y_test,ypredictOLS))\n",
+ "\n",
+ "# Repeat now for Lasso and Ridge regression and various values of the regularization parameter\n",
+ "I = np.eye(p,p)\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 100\n",
+ "MSEPredict = np.zeros(nlambdas)\n",
+ "MSETrain = np.zeros(nlambdas)\n",
+ "MSELassoPredict = np.zeros(nlambdas)\n",
+ "MSELassoTrain = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-4, 4, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n",
+ " # include lasso using Scikit-Learn\n",
+ " RegLasso = linear_model.Lasso(lmb)\n",
+ " RegLasso.fit(X_train,y_train)\n",
+ " # and then make the prediction\n",
+ " ytildeRidge = X_train @ Ridgebeta\n",
+ " ypredictRidge = X_test @ Ridgebeta\n",
+ " ytildeLasso = RegLasso.predict(X_train)\n",
+ " ypredictLasso = RegLasso.predict(X_test)\n",
+ " MSEPredict[i] = MSE(y_test,ypredictRidge)\n",
+ " MSETrain[i] = MSE(y_train,ytildeRidge)\n",
+ " MSELassoPredict[i] = MSE(y_test,ypredictLasso)\n",
+ " MSELassoTrain[i] = MSE(y_train,ytildeLasso)\n",
+ "\n",
+ "# Now plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSETrain, label = 'MSE Ridge train')\n",
+ "plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Test')\n",
+ "plt.plot(np.log10(lambdas), MSELassoTrain, label = 'MSE Lasso train')\n",
+ "plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Test')\n",
+ "\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Linking the regression analysis with a statistical interpretation\n",
+ "\n",
+ "We will now couple the discussions of ordinary least squares, Ridge\n",
+ "and Lasso regression with a statistical interpretation, that is we\n",
+ "move from a linear algebra analysis to a statistical analysis. In\n",
+ "particular, we will focus on what the regularization terms can result\n",
+ "in. We will amongst other things show that the regularization\n",
+ "parameter can reduce considerably the variance of the parameters\n",
+ "$\\beta$.\n",
"\n",
- "* Systematical errors are method specific and must be treated differently from case to case. \n",
"\n",
"The\n",
"advantage of doing linear regression is that we actually end up with\n",
@@ -107,6 +3381,7 @@
"row number $i$ and perform a sum over all values $p$.\n",
"\n",
"\n",
+ "\n",
"The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off)\n",
"that there exists a function $f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim \\mathcal{N}(0, \\sigma^2)$\n",
"which describe our data"
@@ -254,8 +3529,7 @@
"\\sigma^2 \\, \\mathbf{I}_{nn}$. From $\\mbox{Var}(\\boldsymbol{\\beta}) = \\sigma^2\n",
"\\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}$, one obtains an estimate of the\n",
"variance of the estimate of the $j$-th regression coefficient:\n",
- "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 \\sqrt{\n",
- "[(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} }$. This may be used to\n",
+ "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 [(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} $. This may be used to\n",
"construct a confidence interval for the estimates.\n",
"\n",
"\n",
@@ -322,48 +3596,20 @@
"\n",
"\n",
"\n",
- "## Resampling methods\n",
+ "## Deriving OLS from a probability distribution\n",
"\n",
- "With all these analytical equations for both the OLS and Ridge\n",
- "regression, we will now outline how to assess a given model. This will\n",
- "lead us to a discussion of the so-called bias-variance tradeoff (see\n",
- "below) and so-called resampling methods.\n",
+ "Our basic assumption when we derived the OLS equations was to assume\n",
+ "that our output is determined by a given continuous function\n",
+ "$f(\\boldsymbol{x})$ and a random noise $\\boldsymbol{\\epsilon}$ given by the normal\n",
+ "distribution with zero mean value and an undetermined variance\n",
+ "$\\sigma^2$.\n",
"\n",
- "One of the quantities we have discussed as a way to measure errors is\n",
- "the mean-squared error (MSE), mainly used for fitting of continuous\n",
- "functions. Another choice is the absolute error.\n",
- "\n",
- "In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,\n",
- "we discuss the\n",
- "1. prediction error or simply the **test error** $\\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the \n",
- "\n",
- "2. training error $\\mathrm{Err_{Train}}$, which is the average loss over the training data.\n",
- "\n",
- "As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.\n",
- "For a certain level of complexity the test error will reach minimum, before starting to increase again. The\n",
- "training error reaches a saturation.\n",
- "\n",
- "\n",
- "\n",
- "Two famous\n",
- "resampling methods are the **independent bootstrap** and **the jackknife**. \n",
- "\n",
- "The jackknife is a special case of the independent bootstrap. Still, the jackknife was made\n",
- "popular prior to the independent bootstrap. And as the popularity of\n",
- "the independent bootstrap soared, new variants, such as **the dependent bootstrap**.\n",
- "\n",
- "The Jackknife and independent bootstrap work for\n",
- "independent, identically distributed random variables.\n",
- "If these conditions are not\n",
- "satisfied, the methods will fail. Yet, it should be said that if the data are\n",
- "independent, identically distributed, and we only want to estimate the\n",
- "variance of $\\overline{X}$ (which often is the case), then there is no\n",
- "need for bootstrapping. \n",
- "\n",
- "\n",
- "The Jackknife works by making many replicas of the estimator $\\widehat{\\theta}$. \n",
- "The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\\boldsymbol{x} = (x_1,x_2,\\cdots,X_n)$. \n",
- "Let $\\boldsymbol{x}_i$ denote the vector"
+ "We found above that the outputs $\\boldsymbol{y}$ have a mean value given by\n",
+ "$\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$ and variance $\\sigma^2$. Since the entries to\n",
+ "the design matrix are not stochastic variables, we can assume that the\n",
+ "probability distribution of our targets is also a normal distribution\n",
+ "but now with mean value $\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$. This means that a\n",
+ "single output $y_i$ is given by the Gaussian distribution"
]
},
{
@@ -371,7 +3617,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{x}_i = (x_1,x_2,\\cdots,x_{i-1},x_{i+1},\\cdots,x_n),\n",
+ "y_i\\sim \\mathcal{N}(\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta}, \\sigma^2)=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
"$$"
]
},
@@ -379,229 +3625,8 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "which equals the vector $\\boldsymbol{x}$ with the exception that observation\n",
- "number $i$ is left out. Using this notation, define\n",
- "$\\widehat{\\theta}_i$ to be the estimator\n",
- "$\\widehat{\\theta}$ computed using $\\vec{X}_i$."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "from numpy import *\n",
- "from numpy.random import randint, randn\n",
- "from time import time\n",
- "\n",
- "def jackknife(data, stat):\n",
- " n = len(data);t = zeros(n); inds = arange(n); t0 = time()\n",
- " ## 'jackknifing' by leaving out an observation for each i \n",
- " for i in range(n):\n",
- " t[i] = stat(delete(data,i) )\n",
- "\n",
- " # analysis \n",
- " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Jackknife Statistics :\")\n",
- " print(\"original bias std. error\")\n",
- " print(\"%8g %14g %15g\" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))\n",
- "\n",
- " return t\n",
- "\n",
- "\n",
- "# Returns mean of data samples \n",
- "def stat(data):\n",
- " return mean(data)\n",
- "\n",
- "\n",
- "mu, sigma = 100, 15\n",
- "datapoints = 10000\n",
- "x = mu + sigma*random.randn(datapoints)\n",
- "# jackknife returns the data sample \n",
- "t = jackknife(x, stat)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Bootstrap\n",
- "\n",
- "Bootstrapping is a nonparametric approach to statistical inference\n",
- "that substitutes computation for more traditional distributional\n",
- "assumptions and asymptotic results. Bootstrapping offers a number of\n",
- "advantages: \n",
- "1. The bootstrap is quite general, although there are some cases in which it fails. \n",
- "\n",
- "2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. \n",
- "\n",
- "3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. \n",
- "\n",
- "4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).\n",
- "\n",
- "Since $\\widehat{\\theta} = \\widehat{\\theta}(\\boldsymbol{X})$ is a function of random variables,\n",
- "$\\widehat{\\theta}$ itself must be a random variable. Thus it has\n",
- "a pdf, call this function $p(\\boldsymbol{t})$. The aim of the bootstrap is to\n",
- "estimate $p(\\boldsymbol{t})$ by the relative frequency of\n",
- "$\\widehat{\\theta}$. You can think of this as using a histogram\n",
- "in the place of $p(\\boldsymbol{t})$. If the relative frequency closely\n",
- "resembles $p(\\vec{t})$, then using numerics, it is straight forward to\n",
- "estimate all the interesting parameters of $p(\\boldsymbol{t})$ using point\n",
- "estimators. \n",
- "\n",
- "\n",
- "\n",
- "In the case that $\\widehat{\\theta}$ has\n",
- "more than one component, and the components are independent, we use the\n",
- "same estimator on each component separately. If the probability\n",
- "density function of $X_i$, $p(x)$, had been known, then it would have\n",
- "been straight forward to do this by: \n",
- "1. Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \\cdots, X_n^*)$. \n",
- "\n",
- "2. Then using these numbers, we could compute a replica of $\\widehat{\\theta}$ called $\\widehat{\\theta}^*$. \n",
- "\n",
- "By repeated use of (1) and (2), many\n",
- "estimates of $\\widehat{\\theta}$ could have been obtained. The\n",
- "idea is to use the relative frequency of $\\widehat{\\theta}^*$\n",
- "(think of a histogram) as an estimate of $p(\\boldsymbol{t})$.\n",
- "\n",
- "\n",
- "But\n",
- "unless there is enough information available about the process that\n",
- "generated $X_1,X_2,\\cdots,X_n$, $p(x)$ is in general\n",
- "unknown. Therefore, [Efron in 1979](https://projecteuclid.org/euclid.aos/1176344552) asked the\n",
- "question: What if we replace $p(x)$ by the relative frequency\n",
- "of the observation $X_i$; if we draw observations in accordance with\n",
- "the relative frequency of the observations, will we obtain the same\n",
- "result in some asymptotic sense? The answer is yes.\n",
- "\n",
- "\n",
- "Instead of generating the histogram for the relative\n",
- "frequency of the observation $X_i$, just draw the values\n",
- "$(X_1^*,X_2^*,\\cdots,X_n^*)$ with replacement from the vector\n",
- "$\\boldsymbol{X}$. \n",
- "\n",
- "\n",
- "The independent bootstrap works like this: \n",
- "\n",
- "1. Draw with replacement $n$ numbers for the observed variables $\\boldsymbol{x} = (x_1,x_2,\\cdots,x_n)$. \n",
- "\n",
- "2. Define a vector $\\boldsymbol{x}^*$ containing the values which were drawn from $\\boldsymbol{x}$. \n",
- "\n",
- "3. Using the vector $\\boldsymbol{x}^*$ compute $\\widehat{\\theta}^*$ by evaluating $\\widehat \\theta$ under the observations $\\boldsymbol{x}^*$. \n",
- "\n",
- "4. Repeat this process $k$ times. \n",
- "\n",
- "When you are done, you can draw a histogram of the relative frequency\n",
- "of $\\widehat \\theta^*$. This is your estimate of the probability\n",
- "distribution $p(t)$. Using this probability distribution you can\n",
- "estimate any statistics thereof. In principle you never draw the\n",
- "histogram of the relative frequency of $\\widehat{\\theta}^*$. Instead\n",
- "you use the estimators corresponding to the statistic of interest. For\n",
- "example, if you are interested in estimating the variance of $\\widehat\n",
- "\\theta$, apply the etsimator $\\widehat \\sigma^2$ to the values\n",
- "$\\widehat \\theta ^*$.\n",
- "\n",
- "\n",
- "\n",
- "The following code starts with a Gaussian distribution with mean value\n",
- "$\\mu =100$ and variance $\\sigma=15$. We use this to generate the data\n",
- "used in the bootstrap analysis. The bootstrap analysis returns a data\n",
- "set after a given number of bootstrap operations (as many as we have\n",
- "data points). This data set consists of estimated mean values for each\n",
- "bootstrap operation. The histogram generated by the bootstrap method\n",
- "shows that the distribution for these mean values is also a Gaussian,\n",
- "centered around the mean value $\\mu=100$ but with standard deviation\n",
- "$\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in\n",
- "this case the same as the number of original data points). The value\n",
- "of the standard deviation is what we expect from the central limit\n",
- "theorem."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "%matplotlib inline\n",
- "\n",
- "from numpy import *\n",
- "from numpy.random import randint, randn\n",
- "from time import time\n",
- "import matplotlib.mlab as mlab\n",
- "import matplotlib.pyplot as plt\n",
- "\n",
- "# Returns mean of bootstrap samples \n",
- "def stat(data):\n",
- " return mean(data)\n",
- "\n",
- "# Bootstrap algorithm\n",
- "def bootstrap(data, statistic, R):\n",
- " t = zeros(R); n = len(data); inds = arange(n); t0 = time()\n",
- " # non-parametric bootstrap \n",
- " for i in range(R):\n",
- " t[i] = statistic(data[randint(0,n,n)])\n",
- "\n",
- " # analysis \n",
- " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Bootstrap Statistics :\")\n",
- " print(\"original bias std. error\")\n",
- " print(\"%8g %8g %14g %15g\" % (statistic(data), std(data),mean(t),std(t)))\n",
- " return t\n",
- "\n",
- "\n",
- "mu, sigma = 100, 15\n",
- "datapoints = 10000\n",
- "x = mu + sigma*random.randn(datapoints)\n",
- "# bootstrap returns the data sample \n",
- "t = bootstrap(x, stat, datapoints)\n",
- "# the histogram of the bootstrapped data \n",
- "n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)\n",
- "\n",
- "# add a 'best fit' line \n",
- "y = mlab.normpdf( binsboot, mean(t), std(t))\n",
- "lt = plt.plot(binsboot, y, 'r--', linewidth=1)\n",
- "plt.xlabel('Smarts')\n",
- "plt.ylabel('Probability')\n",
- "plt.axis([99.5, 100.6, 0, 3.0])\n",
- "plt.grid(True)\n",
- "\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Various steps in cross-validation\n",
- "\n",
- "When the repetitive splitting of the data set is done randomly,\n",
- "samples may accidently end up in a fast majority of the splits in\n",
- "either training or test set. Such samples may have an unbalanced\n",
- "influence on either model building or prediction evaluation. To avoid\n",
- "this $k$-fold cross-validation structures the data splitting. The\n",
- "samples are divided into $k$ more or less equally sized exhaustive and\n",
- "mutually exclusive subsets. In turn (at each split) one of these\n",
- "subsets plays the role of the test set while the union of the\n",
- "remaining subsets constitutes the training set. Such a splitting\n",
- "warrants a balanced representation of each sample in both training and\n",
- "test set over the splits. Still the division into the $k$ subsets\n",
- "involves a degree of randomness. This may be fully excluded when\n",
- "choosing $k=n$. This particular case is referred to as leave-one-out\n",
- "cross-validation (LOOCV). \n",
- "\n",
- "\n",
- "* Define a range of interest for the penalty parameter.\n",
- "\n",
- "* Divide the data set into training and test set comprising samples $\\{1, \\ldots, n\\} \\setminus i$ and $\\{ i \\}$, respectively.\n",
- "\n",
- "* Fit the linear regression model by means of ridge estimation for each $\\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\\boldsymbol{\\sigma}_{-i}^2(\\lambda)$, as"
+ "We assume now that the various $y_i$ values are stochastically distributed according to the above Gaussian distribution. \n",
+ "We define this distribution as"
]
},
{
@@ -609,11 +3634,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\begin{align*}\n",
- "\\boldsymbol{\\beta}_{-i}(\\lambda) & = ( \\boldsymbol{X}_{-i, \\ast}^{T}\n",
- "\\boldsymbol{X}_{-i, \\ast} + \\lambda \\boldsymbol{I}_{pp})^{-1}\n",
- "\\boldsymbol{X}_{-i, \\ast}^{T} \\boldsymbol{y}_{-i}\n",
- "\\end{align*}\n",
+ "p(y_i, \\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]},\n",
"$$"
]
},
@@ -621,11 +3642,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "* Evaluate the prediction performance of these models on the test set by $\\log\\{L[y_i, \\boldsymbol{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}$. Or, by the prediction error $|y_i - \\boldsymbol{X}_{i, \\ast} \\boldsymbol{\\beta}_{-i}(\\lambda)|$, the relative error, the error squared or the R2 score function.\n",
+ "which reads as finding the likelihood of an event $y_i$ with the input variables $\\boldsymbol{X}$ given the parameters (to be determined) $\\boldsymbol{\\beta}$.\n",
"\n",
- "* Repeat the first three steps such that each sample plays the role of the test set once.\n",
- "\n",
- "* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as"
+ "Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event $\\boldsymbol{y}$ as the product of the single events, that is we have"
]
},
{
@@ -633,9 +3652,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\begin{align*}\n",
- "\\frac{1}{n} \\sum_{i = 1}^n \\log\\{L[y_i, \\mathbf{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}.\n",
- "\\end{align*}\n",
+ "p(\\boldsymbol{y},\\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}=\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta}).\n",
"$$"
]
},
@@ -643,26 +3660,360 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "For the various values of $k$\n",
- "\n",
- "1. shuffle the dataset randomly.\n",
- "\n",
- "2. Split the dataset into $k$ groups.\n",
- "\n",
- "3. For each unique group:\n",
- "\n",
- "a. Decide which group to use as set for test data\n",
- "\n",
- "b. Take the remaining groups as a training data set\n",
- "\n",
- "c. Fit a model on the training set and evaluate it on the test set\n",
- "\n",
- "d. Retain the evaluation score and discard the model\n",
+ "We will write this in a more compact form reserving $\\boldsymbol{D}$ for the domain of events, including the ouputs (targets) and the inputs. That is\n",
+ "in case we have a simple one-dimensional input and output case"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})].\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the more general case the various inputs should be replaced by the possible features represented by the input data set $\\boldsymbol{X}$. \n",
+ "We can now rewrite the above probability as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It is a conditional probability (see below) and reads as the likelihood of a domain of events $\\boldsymbol{D}$ given a set of parameters $\\boldsymbol{\\beta}$.\n",
"\n",
"\n",
- "5. Summarize the model using the sample of model evaluation scores\n",
+ "In statistics, maximum likelihood estimation (MLE) is a method of\n",
+ "estimating the parameters of an assumed probability distribution,\n",
+ "given some observed data. This is achieved by maximizing a likelihood\n",
+ "function so that, under the assumed statistical model, the observed\n",
+ "data is the most probable. \n",
"\n",
- "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial."
+ "\n",
+ "We will assume here that our events are given by the above Gaussian\n",
+ "distribution and we will determine the optimal parameters $\\beta$ by\n",
+ "maximizing the above PDF. However, computing the derivatives of a\n",
+ "product function is cumbersome and can easily lead to overflow and/or\n",
+ "underflowproblems, with potentials for loss of numerical precision.\n",
+ "\n",
+ "\n",
+ "In practice, it is more convenient to maximize the logarithm of the\n",
+ "PDF because it is a monotonically increasing function of the argument.\n",
+ "Alternatively, and this will be our option, we will minimize the\n",
+ "negative of the logarithm since this is a monotonically decreasing\n",
+ "function.\n",
+ "\n",
+ "Note also that maximization/minimization of the logarithm of the PDF\n",
+ "is equivalent to the maximization/minimization of the function itself.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "We could now define a new cost function to minimize, namely the negative logarithm of the above PDF"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta}=-\\log{\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})}=-\\sum_{i=0}^{n-1}\\log{p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which becomes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta}=\\frac{n}{2}\\log{2\\pi\\sigma^2}+\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Taking the derivative of the *new* cost function with respect to the parameters $\\beta$ we recognize our familiar OLS equation, namely"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right) =0,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which leads to the well-known OLS equation for the optimal paramters $\\beta$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}!\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics. \n",
+ "\n",
+ "\n",
+ "A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry.\n",
+ "Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics.\n",
+ "\n",
+ "Assume we have two domains of events $X=[x_0,x_1,\\dots,x_{n-1}]$ and $Y=[y_0,y_1,\\dots,y_{n-1}]$.\n",
+ "\n",
+ "We define also the likelihood for $X$ and $Y$ as $p(X)$ and $p(Y)$ respectively.\n",
+ "The likelihood of a specific event $x_i$ (or $y_i$) is then written as $p(X=x_i)$ or just $p(x_i)=p_i$. \n",
+ "\n",
+ "**Union of events is given by.**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X \\cup Y)= p(X)+p(Y)-p(X \\cap Y).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**The product rule (aka joint probability) is given by.**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X \\cup Y)= p(X,Y)= p(X\\vert Y)p(Y)=p(Y\\vert X)p(X),\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where we read $p(X\\vert Y)$ as the likelihood of obtaining $X$ given $Y$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "If we have independent events then $p(X,Y)=p(X)p(Y)$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The marginal probability is defined in terms of only one of the set of variables $X,Y$. For a discrete probability we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X)=\\sum_{i=0}^{n-1}p(X,Y=y_i)=\\sum_{i=0}^{n-1}p(X\\vert Y=y_i)p(Y=y_i)=\\sum_{i=0}^{n-1}p(X\\vert y_i)p(y_i).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The conditional probability, if $p(Y) > 0$, is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)}=\\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we combine the conditional probability with the marginal probability and the standard product rule, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which we can rewrite as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X\\vert Y)= \\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}=\\frac{p(Y\\vert X)p(X)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is Bayes' theorem. It allows us to evaluate the uncertainty in in $X$ after we have observed $Y$. We can easily interchange $X$ with $Y$. \n",
+ "\n",
+ "\n",
+ "The quantity $p(Y\\vert X)$ on the right-hand side of the theorem is\n",
+ "evaluated for the observed data $Y$ and can be viewed as a function of\n",
+ "the parameter space represented by $X$. This function is not\n",
+ "necesseraly normalized and is normally called the likelihood function.\n",
+ "\n",
+ "The function $p(X)$ on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution.\n",
+ "\n",
+ "Let us try to illustrate Bayes' theorem through an example.\n",
+ "\n",
+ "\n",
+ "Let us suppose that you are undergoing a series of mammography scans in\n",
+ "order to rule out possible breast cancer cases. We define the\n",
+ "sensitivity for a positive event by the variable $X$. It takes binary\n",
+ "values with $X=1$ representing a positive event and $X=0$ being a\n",
+ "negative event. We reserve $Y$ as a classification parameter for\n",
+ "either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing).\n",
+ "\n",
+ "We let $Y=1$ represent the the case of having breast cancer and $Y=0$ as not.\n",
+ "\n",
+ "Let us assume that if you have breast cancer, the test will be positive with a probability of $0.8$, that is we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X=1\\vert Y=1) =0.8.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of $80\\%$ for having cancer.\n",
+ "It is however not correct, as the following Bayesian analysis shows.\n",
+ "\n",
+ "\n",
+ "If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number.\n",
+ "Let us assume that the prior probability in the population as a whole is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(Y=1) =0.004.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X=1\\vert Y=0) =0.1.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(Y=1\\vert X=1)=\\frac{p(X=1\\vert Y=1)p(Y=1)}{p(X=1\\vert Y=1)p(Y=1)+p(X=1\\vert Y=0)p(Y=0)}=\\frac{0.8\\times 0.004}{0.8\\times 0.004+0.1\\times 0.996}=0.031.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "That is, in case of a positive test, there is only a $3\\%$ chance of having breast cancer!\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Bayes' Theorem and Ridge and Lasso Regression\n",
+ "\n",
+ "Hitherto we have discussed Ridge and Lasso regression in terms of a\n",
+ "linear analysis. This may to many of you feel rather technical and\n",
+ "perhaps not that intuitive. The question is whether we can develop a\n",
+ "more intuitive way of understanding what Ridge and Lasso express.\n",
+ "\n",
+ "Before we proceed let us perform a Ridge, Lasso and OLS analysis of a polynomial fit. \n",
+ "\n",
+ "\n",
+ "We will play around with a study of the values for the optimal\n",
+ "parameters $\\boldsymbol{\\beta}$ using OLS, Ridge and Lasso regression. For\n",
+ "OLS, you will notice as function of the noise and polynomial degree,\n",
+ "that the parameters $\\beta$ will fluctuate from order to order in the\n",
+ "polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS.\n",
+ "\n",
+ "For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one."
]
},
{
@@ -676,674 +4027,289 @@
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
- "from sklearn.model_selection import KFold\n",
- "from sklearn.linear_model import Ridge\n",
- "from sklearn.model_selection import cross_val_score\n",
- "from sklearn.preprocessing import PolynomialFeatures\n",
- "\n",
- "# A seed just to ensure that the random numbers are the same for every run.\n",
- "# Useful for eventual debugging.\n",
- "np.random.seed(3155)\n",
- "\n",
- "# Generate the data.\n",
- "nsamples = 100\n",
- "x = np.random.randn(nsamples)\n",
- "y = 3*x**2 + np.random.randn(nsamples)\n",
- "\n",
- "## Cross-validation on Ridge regression using KFold only\n",
- "\n",
- "# Decide degree on polynomial to fit\n",
- "poly = PolynomialFeatures(degree = 6)\n",
- "\n",
- "# Decide which values of lambda to use\n",
- "nlambdas = 500\n",
- "lambdas = np.logspace(-3, 5, nlambdas)\n",
- "\n",
- "# Initialize a KFold instance\n",
- "k = 5\n",
- "kfold = KFold(n_splits = k)\n",
- "\n",
- "# Perform the cross-validation to estimate MSE\n",
- "scores_KFold = np.zeros((nlambdas, k))\n",
- "\n",
- "i = 0\n",
- "for lmb in lambdas:\n",
- " ridge = Ridge(alpha = lmb)\n",
- " j = 0\n",
- " for train_inds, test_inds in kfold.split(x):\n",
- " xtrain = x[train_inds]\n",
- " ytrain = y[train_inds]\n",
- "\n",
- " xtest = x[test_inds]\n",
- " ytest = y[test_inds]\n",
- "\n",
- " Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n",
- " ridge.fit(Xtrain, ytrain[:, np.newaxis])\n",
- "\n",
- " Xtest = poly.fit_transform(xtest[:, np.newaxis])\n",
- " ypred = ridge.predict(Xtest)\n",
- "\n",
- " scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n",
- "\n",
- " j += 1\n",
- " i += 1\n",
- "\n",
- "\n",
- "estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n",
- "\n",
- "## Cross-validation using cross_val_score from sklearn along with KFold\n",
- "\n",
- "# kfold is an instance initialized above as:\n",
- "# kfold = KFold(n_splits = k)\n",
- "\n",
- "estimated_mse_sklearn = np.zeros(nlambdas)\n",
- "i = 0\n",
- "for lmb in lambdas:\n",
- " ridge = Ridge(alpha = lmb)\n",
- "\n",
- " X = poly.fit_transform(x[:, np.newaxis])\n",
- " estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n",
- "\n",
- " # cross_val_score return an array containing the estimated negative mse for every fold.\n",
- " # we have to the the mean of every array in order to get an estimate of the mse of the model\n",
- " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n",
- "\n",
- " i += 1\n",
- "\n",
- "## Plot and compare the slightly different ways to perform cross-validation\n",
- "\n",
- "plt.figure()\n",
- "\n",
- "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n",
- "plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n",
- "\n",
- "plt.xlabel('log10(lambda)')\n",
- "plt.ylabel('mse')\n",
- "\n",
- "plt.legend()\n",
- "\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## The bias-variance tradeoff\n",
- "\n",
- "\n",
- "We will discuss the bias-variance tradeoff in the context of\n",
- "continuous predictions such as regression. However, many of the\n",
- "intuitions and ideas discussed here also carry over to classification\n",
- "tasks. Consider a dataset $\\mathcal{L}$ consisting of the data\n",
- "$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$. \n",
- "\n",
- "Let us assume that the true data is generated from a noisy model"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "where $\\epsilon$ is normally distributed with mean zero and standard deviation $\\sigma^2$.\n",
- "\n",
- "In our derivation of the ordinary least squares method we defined then\n",
- "an approximation to the function $f$ in terms of the parameters\n",
- "$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n",
- "that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$. \n",
- "\n",
- "Thereafter we found the parameters $\\boldsymbol{\\beta}$ by optimizing the means squared error via the so-called cost function"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We can rewrite this as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\frac{1}{n}\\sum_i(f_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\sigma^2.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The three terms represent the square of the bias of the learning\n",
- "method, which can be thought of as the error caused by the simplifying\n",
- "assumptions built into the method. The second term represents the\n",
- "variance of the chosen model and finally the last terms is variance of\n",
- "the error $\\boldsymbol{\\epsilon}$.\n",
- "\n",
- "To derive this equation, we need to recall that the variance of $\\boldsymbol{y}$ and $\\boldsymbol{\\epsilon}$ are both equal to $\\sigma^2$. The mean value of $\\boldsymbol{\\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\\boldsymbol{\\tilde{y}}$.\n",
- "We use a more compact notation in terms of the expectation value"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}})^2\\right],\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "and adding and subtracting $\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]$ we get"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}}+\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right],\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which, using the abovementioned expectation values can be rewritten as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right]+\\mathrm{Var}\\left[\\boldsymbol{\\tilde{y}}\\right]+\\sigma^2,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "that is the rewriting in terms of the so-called bias, the variance of the model $\\boldsymbol{\\tilde{y}}$ and the variance of $\\boldsymbol{\\epsilon}$."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "import matplotlib.pyplot as plt\n",
- "import numpy as np\n",
- "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
- "from sklearn.preprocessing import PolynomialFeatures\n",
"from sklearn.model_selection import train_test_split\n",
- "from sklearn.pipeline import make_pipeline\n",
- "from sklearn.utils import resample\n",
+ "from sklearn import linear_model\n",
"\n",
- "np.random.seed(2018)\n",
- "\n",
- "n = 500\n",
- "n_boostraps = 100\n",
- "degree = 18 # A quite high value, just to show.\n",
- "noise = 0.1\n",
+ "def R2(y_data, y_model):\n",
+ " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
"\n",
"# Make data set.\n",
- "x = np.linspace(-1, 3, n).reshape(-1, 1)\n",
- "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)\n",
+ "n = 10000\n",
+ "x = np.random.rand(n)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n",
"\n",
- "# Hold out some test data that is never used in training.\n",
- "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
- "\n",
- "# Combine x transformation and model into one operation.\n",
- "# Not neccesary, but convenient.\n",
- "model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
- "\n",
- "# The following (m x n_bootstraps) matrix holds the column vectors y_pred\n",
- "# for each bootstrap iteration.\n",
- "y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
- "for i in range(n_boostraps):\n",
- " x_, y_ = resample(x_train, y_train)\n",
- "\n",
- " # Evaluate the new model on the same test data each time.\n",
- " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
- "\n",
- "# Note: Expectations and variances taken w.r.t. different training\n",
- "# data sets, hence the axis=1. Subsequent means are taken across the test data\n",
- "# set in order to obtain a total value, but before this we have error/bias/variance\n",
- "# calculated per data point in the test set.\n",
- "# Note 2: The use of keepdims=True is important in the calculation of bias as this \n",
- "# maintains the column vector form. Dropping this yields very unexpected results.\n",
- "error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
- "bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
- "variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
- "print('Error:', error)\n",
- "print('Bias^2:', bias)\n",
- "print('Var:', variance)\n",
- "print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))\n",
- "\n",
- "plt.plot(x[::5, :], y[::5, :], label='f(x)')\n",
- "plt.scatter(x_test, y_test, label='Data points')\n",
- "plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')\n",
- "plt.legend()\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "import matplotlib.pyplot as plt\n",
- "import numpy as np\n",
- "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
- "from sklearn.preprocessing import PolynomialFeatures\n",
- "from sklearn.model_selection import train_test_split\n",
- "from sklearn.pipeline import make_pipeline\n",
- "from sklearn.utils import resample\n",
- "\n",
- "np.random.seed(2018)\n",
- "\n",
- "n = 40\n",
- "n_boostraps = 100\n",
- "maxdegree = 14\n",
- "\n",
- "\n",
- "# Make data set.\n",
- "x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
- "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
- "error = np.zeros(maxdegree)\n",
- "bias = np.zeros(maxdegree)\n",
- "variance = np.zeros(maxdegree)\n",
- "polydegree = np.zeros(maxdegree)\n",
- "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
- "\n",
- "for degree in range(maxdegree):\n",
- " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
- " y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
- " for i in range(n_boostraps):\n",
- " x_, y_ = resample(x_train, y_train)\n",
- " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
- "\n",
- " polydegree[degree] = degree\n",
- " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
- " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
- " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
- " print('Polynomial degree:', degree)\n",
- " print('Error:', error[degree])\n",
- " print('Bias^2:', bias[degree])\n",
- " print('Var:', variance[degree])\n",
- " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n",
- "\n",
- "plt.plot(polydegree, error, label='Error')\n",
- "plt.plot(polydegree, bias, label='bias')\n",
- "plt.plot(polydegree, variance, label='Variance')\n",
- "plt.legend()\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The bias-variance tradeoff summarizes the fundamental tension in\n",
- "machine learning, particularly supervised learning, between the\n",
- "complexity of a model and the amount of training data needed to train\n",
- "it. Since data is often limited, in practice it is often useful to\n",
- "use a less-complex model with higher bias, that is a model whose asymptotic\n",
- "performance is worse than another model because it is easier to\n",
- "train and less sensitive to sampling noise arising from having a\n",
- "finite-sized training dataset (smaller variance). \n",
- "\n",
- "\n",
- "\n",
- "The above equations tell us that in\n",
- "order to minimize the expected test error, we need to select a\n",
- "statistical learning method that simultaneously achieves low variance\n",
- "and low bias. Note that variance is inherently a nonnegative quantity,\n",
- "and squared bias is also nonnegative. Hence, we see that the expected\n",
- "test MSE can never lie below $Var(\\epsilon)$, the irreducible error.\n",
- "\n",
- "\n",
- "What do we mean by the variance and bias of a statistical learning\n",
- "method? The variance refers to the amount by which our model would change if we\n",
- "estimated it using a different training data set. Since the training\n",
- "data are used to fit the statistical learning method, different\n",
- "training data sets will result in a different estimate. But ideally the\n",
- "estimate for our model should not vary too much between training\n",
- "sets. However, if a method has high variance then small changes in\n",
- "the training data can result in large changes in the model. In general, more\n",
- "flexible statistical methods have higher variance.\n",
- "\n",
- "\n",
- "You may also find this recent [article](https://www.pnas.org/content/116/32/15849) of interest."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "\"\"\"\n",
- "============================\n",
- "Underfitting vs. Overfitting\n",
- "============================\n",
- "\n",
- "This example demonstrates the problems of underfitting and overfitting and\n",
- "how we can use linear regression with polynomial features to approximate\n",
- "nonlinear functions. The plot shows the function that we want to approximate,\n",
- "which is a part of the cosine function. In addition, the samples from the\n",
- "real function and the approximations of different models are displayed. The\n",
- "models have polynomial features of different degrees. We can see that a\n",
- "linear function (polynomial with degree 1) is not sufficient to fit the\n",
- "training samples. This is called **underfitting**. A polynomial of degree 4\n",
- "approximates the true function almost perfectly. However, for higher degrees\n",
- "the model will **overfit** the training data, i.e. it learns the noise of the\n",
- "training data.\n",
- "We evaluate quantitatively **overfitting** / **underfitting** by using\n",
- "cross-validation. We calculate the mean squared error (MSE) on the validation\n",
- "set, the higher, the less likely the model generalizes correctly from the\n",
- "training data.\n",
- "\"\"\"\n",
- "\n",
- "print(__doc__)\n",
- "\n",
- "import numpy as np\n",
- "import matplotlib.pyplot as plt\n",
- "from sklearn.pipeline import Pipeline\n",
- "from sklearn.preprocessing import PolynomialFeatures\n",
- "from sklearn.linear_model import LinearRegression\n",
- "from sklearn.model_selection import cross_val_score\n",
- "\n",
- "\n",
- "def true_fun(X):\n",
- " return np.cos(1.5 * np.pi * X)\n",
- "\n",
- "np.random.seed(0)\n",
- "\n",
- "n_samples = 30\n",
- "degrees = [1, 4, 15]\n",
- "\n",
- "X = np.sort(np.random.rand(n_samples))\n",
- "y = true_fun(X) + np.random.randn(n_samples) * 0.1\n",
- "\n",
- "plt.figure(figsize=(14, 5))\n",
- "for i in range(len(degrees)):\n",
- " ax = plt.subplot(1, len(degrees), i + 1)\n",
- " plt.setp(ax, xticks=(), yticks=())\n",
- "\n",
- " polynomial_features = PolynomialFeatures(degree=degrees[i],\n",
- " include_bias=False)\n",
- " linear_regression = LinearRegression()\n",
- " pipeline = Pipeline([(\"polynomial_features\", polynomial_features),\n",
- " (\"linear_regression\", linear_regression)])\n",
- " pipeline.fit(X[:, np.newaxis], y)\n",
- "\n",
- " # Evaluate the models using crossvalidation\n",
- " scores = cross_val_score(pipeline, X[:, np.newaxis], y,\n",
- " scoring=\"neg_mean_squared_error\", cv=10)\n",
- "\n",
- " X_test = np.linspace(0, 1, 100)\n",
- " plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label=\"Model\")\n",
- " plt.plot(X_test, true_fun(X_test), label=\"True function\")\n",
- " plt.scatter(X, y, edgecolor='b', s=20, label=\"Samples\")\n",
- " plt.xlabel(\"x\")\n",
- " plt.ylabel(\"y\")\n",
- " plt.xlim((0, 1))\n",
- " plt.ylim((-2, 2))\n",
- " plt.legend(loc=\"best\")\n",
- " plt.title(\"Degree {}\\nMSE = {:.2e}(+/- {:.2e})\".format(\n",
- " degrees[i], -scores.mean(), scores.std()))\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "# Common imports\n",
- "import os\n",
- "import numpy as np\n",
- "import pandas as pd\n",
- "import matplotlib.pyplot as plt\n",
- "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
- "from sklearn.model_selection import train_test_split\n",
- "from sklearn.utils import resample\n",
- "from sklearn.metrics import mean_squared_error\n",
- "# Where to save the figures and data files\n",
- "PROJECT_ROOT_DIR = \"Results\"\n",
- "FIGURE_ID = \"Results/FigureFiles\"\n",
- "DATA_ID = \"DataFiles/\"\n",
- "\n",
- "if not os.path.exists(PROJECT_ROOT_DIR):\n",
- " os.mkdir(PROJECT_ROOT_DIR)\n",
- "\n",
- "if not os.path.exists(FIGURE_ID):\n",
- " os.makedirs(FIGURE_ID)\n",
- "\n",
- "if not os.path.exists(DATA_ID):\n",
- " os.makedirs(DATA_ID)\n",
- "\n",
- "def image_path(fig_id):\n",
- " return os.path.join(FIGURE_ID, fig_id)\n",
- "\n",
- "def data_path(dat_id):\n",
- " return os.path.join(DATA_ID, dat_id)\n",
- "\n",
- "def save_fig(fig_id):\n",
- " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
- "\n",
- "infile = open(data_path(\"EoS.csv\"),'r')\n",
- "\n",
- "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
- "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
- "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
- "EoS = EoS.dropna()\n",
- "Energies = EoS['Energy']\n",
- "Density = EoS['Density']\n",
- "# The design matrix now as function of various polytrops\n",
- "\n",
- "Maxpolydegree = 30\n",
- "X = np.zeros((len(Density),Maxpolydegree))\n",
+ "Maxpolydegree = 5\n",
+ "X = np.zeros((len(x),Maxpolydegree))\n",
"X[:,0] = 1.0\n",
- "testerror = np.zeros(Maxpolydegree)\n",
- "trainingerror = np.zeros(Maxpolydegree)\n",
- "polynomial = np.zeros(Maxpolydegree)\n",
- "\n",
- "trials = 100\n",
- "for polydegree in range(1, Maxpolydegree):\n",
- " polynomial[polydegree] = polydegree\n",
- " for degree in range(polydegree):\n",
- " X[:,degree] = Density**(degree/3.0)\n",
- "\n",
- "# loop over trials in order to estimate the expectation value of the MSE\n",
- " testerror[polydegree] = 0.0\n",
- " trainingerror[polydegree] = 0.0\n",
- " for samples in range(trials):\n",
- " x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n",
- " model = LinearRegression(fit_intercept=True).fit(x_train, y_train)\n",
- " ypred = model.predict(x_train)\n",
- " ytilde = model.predict(x_test)\n",
- " testerror[polydegree] += mean_squared_error(y_test, ytilde)\n",
- " trainingerror[polydegree] += mean_squared_error(y_train, ypred) \n",
- "\n",
- " testerror[polydegree] /= trials\n",
- " trainingerror[polydegree] /= trials\n",
- " print(\"Degree of polynomial: %3d\"% polynomial[polydegree])\n",
- " print(\"Mean squared error on training data: %.8f\" % trainingerror[polydegree])\n",
- " print(\"Mean squared error on test data: %.8f\" % testerror[polydegree])\n",
- "\n",
- "plt.plot(polynomial, np.log10(trainingerror), label='Training Error')\n",
- "plt.plot(polynomial, np.log10(testerror), label='Test Error')\n",
- "plt.xlabel('Polynomial degree')\n",
- "plt.ylabel('log10[MSE]')\n",
- "plt.legend()\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "# Common imports\n",
- "import os\n",
- "import numpy as np\n",
- "import pandas as pd\n",
- "import matplotlib.pyplot as plt\n",
- "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
- "from sklearn.metrics import mean_squared_error\n",
- "from sklearn.model_selection import KFold\n",
- "from sklearn.model_selection import cross_val_score\n",
- "\n",
- "\n",
- "# Where to save the figures and data files\n",
- "PROJECT_ROOT_DIR = \"Results\"\n",
- "FIGURE_ID = \"Results/FigureFiles\"\n",
- "DATA_ID = \"DataFiles/\"\n",
- "\n",
- "if not os.path.exists(PROJECT_ROOT_DIR):\n",
- " os.mkdir(PROJECT_ROOT_DIR)\n",
- "\n",
- "if not os.path.exists(FIGURE_ID):\n",
- " os.makedirs(FIGURE_ID)\n",
- "\n",
- "if not os.path.exists(DATA_ID):\n",
- " os.makedirs(DATA_ID)\n",
- "\n",
- "def image_path(fig_id):\n",
- " return os.path.join(FIGURE_ID, fig_id)\n",
- "\n",
- "def data_path(dat_id):\n",
- " return os.path.join(DATA_ID, dat_id)\n",
- "\n",
- "def save_fig(fig_id):\n",
- " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
- "\n",
- "infile = open(data_path(\"EoS.csv\"),'r')\n",
- "\n",
- "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
- "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
- "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
- "EoS = EoS.dropna()\n",
- "Energies = EoS['Energy']\n",
- "Density = EoS['Density']\n",
- "# The design matrix now as function of various polytrops\n",
- "\n",
- "Maxpolydegree = 30\n",
- "X = np.zeros((len(Density),Maxpolydegree))\n",
- "X[:,0] = 1.0\n",
- "estimated_mse_sklearn = np.zeros(Maxpolydegree)\n",
- "polynomial = np.zeros(Maxpolydegree)\n",
- "k =5\n",
- "kfold = KFold(n_splits = k)\n",
"\n",
"for polydegree in range(1, Maxpolydegree):\n",
- " polynomial[polydegree] = polydegree\n",
" for degree in range(polydegree):\n",
- " X[:,degree] = Density**(degree/3.0)\n",
- " OLS = LinearRegression()\n",
- "# loop over trials in order to estimate the expectation value of the MSE\n",
- " estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)\n",
- "#[:, np.newaxis]\n",
- " estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)\n",
+ " X[:,degree] = x**(degree)\n",
"\n",
- "plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')\n",
- "plt.xlabel('Polynomial degree')\n",
- "plt.ylabel('log10[MSE]')\n",
- "plt.legend()\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "import numpy as np\n",
- "import matplotlib.pyplot as plt\n",
- "from sklearn.model_selection import KFold\n",
- "from sklearn.linear_model import Ridge\n",
- "from sklearn.model_selection import cross_val_score\n",
- "from sklearn.preprocessing import PolynomialFeatures\n",
"\n",
- "# A seed just to ensure that the random numbers are the same for every run.\n",
- "np.random.seed(3155)\n",
- "# Generate the data.\n",
- "n = 100\n",
- "x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
- "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
- "# Decide degree on polynomial to fit\n",
- "poly = PolynomialFeatures(degree = 10)\n",
+ "# We split the data in test and training data\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
"\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.pinv(X_train.T @ X_train) @ X_train.T @ y_train\n",
+ "print(OLSbeta)\n",
+ "ypredictOLS = X_test @ OLSbeta\n",
+ "print(\"Test MSE OLS\")\n",
+ "print(MSE(y_test,ypredictOLS))\n",
+ "# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn\n",
"# Decide which values of lambda to use\n",
- "nlambdas = 500\n",
- "lambdas = np.logspace(-3, 5, nlambdas)\n",
- "# Initialize a KFold instance\n",
- "k = 5\n",
- "kfold = KFold(n_splits = k)\n",
- "estimated_mse_sklearn = np.zeros(nlambdas)\n",
- "i = 0\n",
- "for lmb in lambdas:\n",
- " ridge = Ridge(alpha = lmb)\n",
- " estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)\n",
- " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n",
- " i += 1\n",
+ "nlambdas = 4\n",
+ "MSERidgePredict = np.zeros(nlambdas)\n",
+ "MSELassoPredict = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-3, 1, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " # Make the fit using Ridge and Lasso\n",
+ " RegRidge = linear_model.Ridge(lmb,fit_intercept=False)\n",
+ " RegRidge.fit(X_train,y_train)\n",
+ " RegLasso = linear_model.Lasso(lmb,fit_intercept=False)\n",
+ " RegLasso.fit(X_train,y_train)\n",
+ " # and then make the prediction\n",
+ " ypredictRidge = RegRidge.predict(X_test)\n",
+ " ypredictLasso = RegLasso.predict(X_test)\n",
+ " # Compute the MSE and print it\n",
+ " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n",
+ " MSELassoPredict[i] = MSE(y_test,ypredictLasso)\n",
+ " print(lmb,RegRidge.coef_)\n",
+ " print(lmb,RegLasso.coef_)\n",
+ "# Now plot the results\n",
"plt.figure()\n",
- "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n",
+ "plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')\n",
+ "plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')\n",
"plt.xlabel('log10(lambda)')\n",
"plt.ylabel('MSE')\n",
"plt.legend()\n",
"plt.show()"
]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "How can we understand this? \n",
+ "\n",
+ "\n",
+ "\n",
+ "Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression. \n",
+ "\n",
+ "For ordinary least squares we postulated that the maximum likelihood for the doamin of events $\\boldsymbol{D}$ (one-dimensional case)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})],\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "is given by"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set $\\boldsymbol{\\beta}$ given a domain of events $\\boldsymbol{D}$? That is, how can we define the posterior probability"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Bayes' theorem comes to our rescue here since (omitting the normalization constant)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})\\propto p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})p(\\boldsymbol{\\beta}).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We have a model for $p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})$ but need one for the **prior** $p(\\boldsymbol{\\beta}$! \n",
+ "\n",
+ "\n",
+ "\n",
+ "With the posterior probability defined by a likelihood which we have\n",
+ "already modeled and an unknown prior, we are now ready to make\n",
+ "additional models for the prior.\n",
+ "\n",
+ "We can, based on our discussions of the variance of $\\boldsymbol{\\beta}$ and the mean value, assume that the prior for the values $\\boldsymbol{\\beta}$ is given by a Gaussian with mean value zero and variance $\\tau^2$, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Our posterior probability becomes then (omitting the normalization factor which is just a constant)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta\\vert\\boldsymbol{D})}=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can now optimize this quantity with respect to $\\boldsymbol{\\beta}$. As we\n",
+ "did for OLS, this is most conveniently done by taking the negative\n",
+ "logarithm of the posterior probability. Doing so and leaving out the\n",
+ "constants terms that do not depend on $\\beta$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{2\\tau^2}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and replacing $1/2\\tau^2$ with $\\lambda$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is our Ridge cost function! Nice, isn't it?\n",
+ "\n",
+ "\n",
+ "To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution ([Laplace in this case](https://en.wikipedia.org/wiki/Laplace_distribution)) with zero mean value, that is"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Our posterior probability becomes then (omitting the normalization factor which is just a constant)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Taking the negative\n",
+ "logarithm of the posterior probability and leaving out the\n",
+ "constants terms that do not depend on $\\beta$, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{\\tau}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and replacing $1/\\tau$ with $\\lambda$ we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is our Lasso cost function!"
+ ]
}
],
"metadata": {},
diff --git a/doc/LectureNotes/chapter3.ipynb b/doc/LectureNotes/chapter3.ipynb
index 5ede9f687..d7f8222d5 100644
--- a/doc/LectureNotes/chapter3.ipynb
+++ b/doc/LectureNotes/chapter3.ipynb
@@ -4,40 +4,78 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "# Ridge and Lasso Regression\n",
+ "# Resampling Methods\n",
"\n",
- "[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember10.mp4?vrtx=view-as-webpage)\n",
+ "## Introduction\n",
+ "\n",
+ "Resampling methods are an indispensable tool in modern\n",
+ "statistics. They involve repeatedly drawing samples from a training\n",
+ "set and refitting a model of interest on each sample in order to\n",
+ "obtain additional information about the fitted model. For example, in\n",
+ "order to estimate the variability of a linear regression fit, we can\n",
+ "repeatedly draw different samples from the training data, fit a linear\n",
+ "regression to each new sample, and then examine the extent to which\n",
+ "the resulting fits differ. Such an approach may allow us to obtain\n",
+ "information that would not be available from fitting the model only\n",
+ "once using the original training sample.\n",
+ "\n",
+ "Two resampling methods are often used in Machine Learning analyses,\n",
+ "1. The **bootstrap method**\n",
+ "\n",
+ "2. and **Cross-Validation**\n",
+ "\n",
+ "In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular\n",
+ "cross-validation and the bootstrap method. \n",
"\n",
"\n",
- "## The singular value decomposition\n",
- "\n",
- "The examples we have looked at so far are cases where we normally can\n",
- "invert the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$. Using a polynomial expansion as we\n",
- "did both for the masses and the fitting of the equation of state,\n",
- "leads to row vectors of the design matrix which are essentially\n",
- "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. \n",
+ "Resampling approaches can be computationally expensive, because they\n",
+ "involve fitting the same statistical method multiple times using\n",
+ "different subsets of the training data. However, due to recent\n",
+ "advances in computing power, the computational requirements of\n",
+ "resampling methods generally are not prohibitive. In this chapter, we\n",
+ "discuss two of the most commonly used resampling methods,\n",
+ "cross-validation and the bootstrap. Both methods are important tools\n",
+ "in the practical application of many statistical learning\n",
+ "procedures. For example, cross-validation can be used to estimate the\n",
+ "test error associated with a given statistical learning method in\n",
+ "order to evaluate its performance, or to select the appropriate level\n",
+ "of flexibility. The process of evaluating a model’s performance is\n",
+ "known as model assessment, whereas the process of selecting the proper\n",
+ "level of flexibility for a model is known as model selection. The\n",
+ "bootstrap is widely used.\n",
"\n",
"\n",
+ "* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods\n",
"\n",
- "This may\n",
- "however not the be case in general and a standard matrix inversion\n",
- "algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.\n",
+ "* The results can be analysed with the same statistical tools as we would use analysing experimental data.\n",
"\n",
- "There is however a way to partially circumvent this problem and also gain some insights about the ordinary least squares approach, and later shrinkage methods like Ridge and Lasso regressions. \n",
+ "* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n",
"\n",
- "This is given by the **Singular Value Decomposition** algorithm, perhaps\n",
- "the most powerful linear algebra algorithm. Let us look at a\n",
- "different example where we may have problems with the standard matrix\n",
- "inversion algorithm. Thereafter we dive into the math of the SVD.\n",
+ "## Reminder on Statistics\n",
"\n",
"\n",
+ "* As in other experiments, many numerical experiments have two classes of errors:\n",
"\n",
- "One of the typical problems we encounter with linear regression, in particular \n",
- "when the matrix $\\boldsymbol{X}$ (our so-called design matrix) is high-dimensional, \n",
- "are problems with near singular or singular matrices. The column vectors of $\\boldsymbol{X}$ \n",
- "may be linearly dependent, normally referred to as super-collinearity. \n",
- "This means that the matrix may be rank deficient and it is basically impossible to \n",
- "to model the data using linear regression. As an example, consider the matrix"
+ " * Statistical errors\n",
+ "\n",
+ " * Systematical errors\n",
+ "\n",
+ "\n",
+ "* Statistical errors can be estimated using standard tools from statistics\n",
+ "\n",
+ "* Systematical errors are method specific and must be treated differently from case to case. \n",
+ "\n",
+ "The\n",
+ "advantage of doing linear regression is that we actually end up with\n",
+ "analytical expressions for several statistical quantities. \n",
+ "Standard least squares and Ridge regression allow us to\n",
+ "derive quantities like the variance and other expectation values in a\n",
+ "rather straightforward way.\n",
+ "\n",
+ "\n",
+ "It is assumed that $\\varepsilon_i\n",
+ "\\sim \\mathcal{N}(0, \\sigma^2)$ and the $\\varepsilon_{i}$ are\n",
+ "independent, i.e.:"
]
},
{
@@ -45,17 +83,10 @@
"metadata": {},
"source": [
"$$\n",
- "\\begin{align*}\n",
- "\\mathbf{X} & = \\left[\n",
- "\\begin{array}{rrr}\n",
- "1 & -1 & 2\n",
- "\\\\\n",
- "1 & 0 & 1\n",
- "\\\\\n",
- "1 & 2 & -1\n",
- "\\\\\n",
- "1 & 1 & 0\n",
- "\\end{array} \\right]\n",
+ "\\begin{align*} \n",
+ "\\mbox{Cov}(\\varepsilon_{i_1},\n",
+ "\\varepsilon_{i_2}) & = \\left\\{ \\begin{array}{lcc} \\sigma^2 & \\mbox{if}\n",
+ "& i_1 = i_2, \\\\ 0 & \\mbox{if} & i_1 \\not= i_2. \\end{array} \\right.\n",
"\\end{align*}\n",
"$$"
]
@@ -64,14 +95,21 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The columns of $\\boldsymbol{X}$ are linearly dependent. We see this easily since the \n",
- "the first column is the row-wise sum of the other two columns. The rank (more correct,\n",
- "the column rank) of a matrix is the dimension of the space spanned by the\n",
- "column vectors. Hence, the rank of $\\mathbf{X}$ is equal to the number\n",
- "of linearly independent columns. In this particular case the matrix has rank 2.\n",
+ "The randomness of $\\varepsilon_i$ implies that\n",
+ "$\\mathbf{y}_i$ is also a random variable. In particular,\n",
+ "$\\mathbf{y}_i$ is normally distributed, because $\\varepsilon_i \\sim\n",
+ "\\mathcal{N}(0, \\sigma^2)$ and $\\mathbf{X}_{i,\\ast} \\, \\boldsymbol{\\beta}$ is a\n",
+ "non-random scalar. To specify the parameters of the distribution of\n",
+ "$\\mathbf{y}_i$ we need to calculate its first two moments. \n",
"\n",
- "Super-collinearity of an $(n \\times p)$-dimensional design matrix $\\mathbf{X}$ implies\n",
- "that the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this"
+ "Recall that $\\boldsymbol{X}$ is a matrix of dimensionality $n\\times p$. The\n",
+ "notation above $\\mathbf{X}_{i,\\ast}$ means that we are looking at the\n",
+ "row number $i$ and perform a sum over all values $p$.\n",
+ "\n",
+ "\n",
+ "The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off)\n",
+ "that there exists a function $f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim \\mathcal{N}(0, \\sigma^2)$\n",
+ "which describe our data"
]
},
{
@@ -79,13 +117,43 @@
"metadata": {},
"source": [
"$$\n",
- "\\begin{align*}\n",
- "\\boldsymbol{X} & = \\left[\n",
- "\\begin{array}{rr}\n",
- "1 & -1\n",
- "\\\\\n",
- "1 & -1\n",
- "\\end{array} \\right].\n",
+ "\\boldsymbol{y} = f(\\boldsymbol{x})+\\boldsymbol{\\varepsilon}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We approximate this function with our model from the solution of the linear regression equations, that is our\n",
+ "function $f$ is approximated by $\\boldsymbol{\\tilde{y}}$ where we want to minimize $(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2$, our MSE, with"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can calculate the expectation value of $\\boldsymbol{y}$ for a given element $i$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*} \n",
+ "\\mathbb{E}(y_i) & =\n",
+ "\\mathbb{E}(\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}) + \\mathbb{E}(\\varepsilon_i)\n",
+ "\\, \\, \\, = \\, \\, \\, \\mathbf{X}_{i, \\ast} \\, \\beta, \n",
"\\end{align*}\n",
"$$"
]
@@ -94,39 +162,8 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "We see easily that $\\mbox{det}(\\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \\times (-1) - 1 \\times (-1) = 0$. Hence, $\\mathbf{X}$ is singular and its inverse is undefined.\n",
- "This is equivalent to saying that the matrix $\\boldsymbol{X}$ has at least an eigenvalue which is zero.\n",
- "\n",
- "\n",
- "If our design matrix $\\boldsymbol{X}$ which enters the linear regression problem"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "
\n",
- "\n",
- "$$\n",
- "\\begin{equation}\n",
- "\\boldsymbol{\\beta} = (\\boldsymbol{X}^{T} \\boldsymbol{X})^{-1} \\boldsymbol{X}^{T} \\boldsymbol{y},\n",
- "\\label{_auto1} \\tag{1}\n",
- "\\end{equation}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "has linearly dependent column vectors, we will not be able to compute the inverse\n",
- "of $\\boldsymbol{X}^T\\boldsymbol{X}$ and we cannot find the parameters (estimators) $\\beta_i$. \n",
- "The estimators are only well-defined if $(\\boldsymbol{X}^{T}\\boldsymbol{X})^{-1}$ exits. \n",
- "This is more likely to happen when the matrix $\\boldsymbol{X}$ is high-dimensional. In this case it is likely to encounter a situation where \n",
- "the regression parameters $\\beta_i$ cannot be estimated.\n",
- "\n",
- "A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change"
+ "while\n",
+ "its variance is"
]
},
{
@@ -134,7 +171,18 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X}^{T} \\boldsymbol{X} \\rightarrow \\boldsymbol{X}^{T} \\boldsymbol{X}+\\lambda \\boldsymbol{I},\n",
+ "\\begin{align*} \\mbox{Var}(y_i) & = \\mathbb{E} \\{ [y_i\n",
+ "- \\mathbb{E}(y_i)]^2 \\} \\, \\, \\, = \\, \\, \\, \\mathbb{E} ( y_i^2 ) -\n",
+ "[\\mathbb{E}(y_i)]^2 \\\\ & = \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\,\n",
+ "\\beta + \\varepsilon_i )^2] - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \\\\ &\n",
+ "= \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2 \\varepsilon_i\n",
+ "\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} + \\varepsilon_i^2 ] - ( \\mathbf{X}_{i,\n",
+ "\\ast} \\, \\beta)^2 \\\\ & = ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2\n",
+ "\\mathbb{E}(\\varepsilon_i) \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} +\n",
+ "\\mathbb{E}(\\varepsilon_i^2 ) - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \n",
+ "\\\\ & = \\mathbb{E}(\\varepsilon_i^2 ) \\, \\, \\, = \\, \\, \\,\n",
+ "\\mbox{Var}(\\varepsilon_i) \\, \\, \\, = \\, \\, \\, \\sigma^2. \n",
+ "\\end{align*}\n",
"$$"
]
},
@@ -142,16 +190,11 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "where $\\boldsymbol{I}$ is the identity matrix. When we discuss **Ridge** regression this is actually what we end up evaluating. The parameter $\\lambda$ is called a hyperparameter. More about this later. \n",
+ "Hence, $y_i \\sim \\mathcal{N}( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}, \\sigma^2)$, that is $\\boldsymbol{y}$ follows a normal distribution with \n",
+ "mean value $\\boldsymbol{X}\\boldsymbol{\\beta}$ and variance $\\sigma^2$ (not be confused with the singular values of the SVD). \n",
"\n",
"\n",
- "\n",
- "\n",
- "\n",
- "From standard linear algebra we know that a square matrix $\\boldsymbol{X}$ can be diagonalized if and only it is \n",
- "a so-called [normal matrix](https://en.wikipedia.org/wiki/Normal_matrix), that is if $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$\n",
- "we have $\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ or if $\\boldsymbol{X}\\in {\\mathbb{C}}^{n\\times n}$ we have $\\boldsymbol{X}\\boldsymbol{X}^{\\dagger}=\\boldsymbol{X}^{\\dagger}\\boldsymbol{X}$.\n",
- "The matrix has then a set of eigenpairs"
+ "With the OLS expressions for the parameters $\\boldsymbol{\\beta}$ we can evaluate the expectation value"
]
},
{
@@ -159,7 +202,7 @@
"metadata": {},
"source": [
"$$\n",
- "(\\lambda_1,\\boldsymbol{u}_1),\\dots, (\\lambda_n,\\boldsymbol{u}_n),\n",
+ "\\mathbb{E}(\\boldsymbol{\\beta}) = \\mathbb{E}[ (\\mathbf{X}^{\\top} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbb{E}[ \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\mathbf{X}^{T}\\mathbf{X}\\boldsymbol{\\beta}=\\boldsymbol{\\beta}.\n",
"$$"
]
},
@@ -167,7 +210,11 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "and the eigenvalues are given by the diagonal matrix"
+ "This means that the estimator of the regression parameters is unbiased.\n",
+ "\n",
+ "We can also calculate the variance\n",
+ "\n",
+ "The variance of $\\boldsymbol{\\beta}$ is"
]
},
{
@@ -175,7 +222,26 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{\\Sigma}=\\mathrm{Diag}(\\lambda_1, \\dots,\\lambda_n).\n",
+ "\\begin{eqnarray*}\n",
+ "\\mbox{Var}(\\boldsymbol{\\beta}) & = & \\mathbb{E} \\{ [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})] [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})]^{T} \\}\n",
+ "\\\\\n",
+ "& = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} - \\boldsymbol{\\beta}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} - \\boldsymbol{\\beta}]^{T} \\}\n",
+ "\\\\\n",
+ "% & = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y}]^{T} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "% \\\\\n",
+ "% & = & \\mathbb{E} \\{ (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} \\, \\mathbf{Y}^{T} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "% \\\\\n",
+ "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\mathbb{E} \\{ \\mathbf{Y} \\, \\mathbf{Y}^{T} \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "\\\\\n",
+ "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\{ \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} + \\sigma^2 \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "% \\\\\n",
+ "% & = & (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^T \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T % \\mathbf{X})^{-1}\n",
+ "% \\\\\n",
+ "% & & + \\, \\, \\sigma^2 \\, (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\boldsymbol{\\beta}^T\n",
+ "\\\\\n",
+ "& = & \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} + \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n",
+ "\\, \\, \\, = \\, \\, \\, \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1},\n",
+ "\\end{eqnarray*}\n",
"$$"
]
},
@@ -183,7 +249,21 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The matrix $\\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\\boldsymbol{U}$"
+ "where we have used that $\\mathbb{E} (\\mathbf{Y} \\mathbf{Y}^{T}) =\n",
+ "\\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} +\n",
+ "\\sigma^2 \\, \\mathbf{I}_{nn}$. From $\\mbox{Var}(\\boldsymbol{\\beta}) = \\sigma^2\n",
+ "\\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}$, one obtains an estimate of the\n",
+ "variance of the estimate of the $j$-th regression coefficient:\n",
+ "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 \\sqrt{\n",
+ "[(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} }$. This may be used to\n",
+ "construct a confidence interval for the estimates.\n",
+ "\n",
+ "\n",
+ "In a similar way, we can obtain analytical expressions for say the\n",
+ "expectation values of the parameters $\\boldsymbol{\\beta}$ and their variance\n",
+ "when we employ Ridge regression, allowing us again to define a confidence interval. \n",
+ "\n",
+ "It is rather straightforward to show that"
]
},
{
@@ -191,7 +271,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "\\mathbb{E} \\big[ \\boldsymbol{\\beta}^{\\mathrm{Ridge}} \\big]=(\\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I}_{pp})^{-1} (\\mathbf{X}^{\\top} \\mathbf{X})\\boldsymbol{\\beta}^{\\mathrm{OLS}}.\n",
"$$"
]
},
@@ -199,9 +279,10 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "with $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ or $\\boldsymbol{U}\\boldsymbol{U}^{\\dagger}=\\boldsymbol{I}$.\n",
+ "We see clearly that \n",
+ "$\\mathbb{E} \\big[ \\boldsymbol{\\beta}^{\\mathrm{Ridge}} \\big] \\not= \\boldsymbol{\\beta}^{\\mathrm{OLS}}$ for any $\\lambda > 0$. We say then that the ridge estimator is biased.\n",
"\n",
- "Not all square matrices are diagonalizable. A matrix like the one discussed above"
+ "We can also compute the variance as"
]
},
{
@@ -209,10 +290,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X} = \\begin{bmatrix} \n",
- "1& -1 \\\\\n",
- "1& -1\\\\\n",
- "\\end{bmatrix}\n",
+ "\\mbox{Var}[\\boldsymbol{\\beta}^{\\mathrm{Ridge}}]=\\sigma^2[ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1} \\mathbf{X}^{T} \\mathbf{X} \\{ [ \\mathbf{X}^{\\top} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T},\n",
"$$"
]
},
@@ -220,23 +298,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "is not diagonalizable, it is a so-called [defective matrix](https://en.wikipedia.org/wiki/Defective_matrix). It is easy to see that the condition\n",
- "$\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ is not fulfilled. \n",
+ "and it is easy to see that if the parameter $\\lambda$ goes to infinity then the variance of Ridge parameters $\\boldsymbol{\\beta}$ goes to zero. \n",
"\n",
- "\n",
- "\n",
- "## The SVD, a Fantastic Algorithm\n",
- "\n",
- "\n",
- "However, and this is the strength of the SVD algorithm, any general\n",
- "matrix $\\boldsymbol{X}$ can be decomposed in terms of a diagonal matrix and\n",
- "two orthogonal/unitary matrices. The [Singular Value Decompostion\n",
- "(SVD) theorem](https://en.wikipedia.org/wiki/Singular_value_decomposition)\n",
- "states that a general $m\\times n$ matrix $\\boldsymbol{X}$ can be written in\n",
- "terms of a diagonal matrix $\\boldsymbol{\\Sigma}$ of dimensionality $m\\times n$\n",
- "and two orthognal matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$, where the first has\n",
- "dimensionality $m \\times m$ and the last dimensionality $n\\times n$.\n",
- "We have then"
+ "With this, we can compute the difference"
]
},
{
@@ -244,7 +308,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\n",
+ "\\mbox{Var}[\\boldsymbol{\\beta}^{\\mathrm{OLS}}]-\\mbox{Var}(\\boldsymbol{\\beta}^{\\mathrm{Ridge}})=\\sigma^2 [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}[ 2\\lambda\\mathbf{I} + \\lambda^2 (\\mathbf{X}^{T} \\mathbf{X})^{-1} ] \\{ [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T}.\n",
"$$"
]
},
@@ -252,7 +316,54 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "As an example, the above defective matrix can be decomposed as"
+ "The difference is non-negative definite since each component of the\n",
+ "matrix product is non-negative definite. \n",
+ "This means the variance we obtain with the standard OLS will always for $\\lambda > 0$ be larger than the variance of $\\boldsymbol{\\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. \n",
+ "\n",
+ "\n",
+ "\n",
+ "## Resampling methods\n",
+ "\n",
+ "With all these analytical equations for both the OLS and Ridge\n",
+ "regression, we will now outline how to assess a given model. This will\n",
+ "lead us to a discussion of the so-called bias-variance tradeoff (see\n",
+ "below) and so-called resampling methods.\n",
+ "\n",
+ "One of the quantities we have discussed as a way to measure errors is\n",
+ "the mean-squared error (MSE), mainly used for fitting of continuous\n",
+ "functions. Another choice is the absolute error.\n",
+ "\n",
+ "In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,\n",
+ "we discuss the\n",
+ "1. prediction error or simply the **test error** $\\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the \n",
+ "\n",
+ "2. training error $\\mathrm{Err_{Train}}$, which is the average loss over the training data.\n",
+ "\n",
+ "As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.\n",
+ "For a certain level of complexity the test error will reach minimum, before starting to increase again. The\n",
+ "training error reaches a saturation.\n",
+ "\n",
+ "\n",
+ "\n",
+ "Two famous\n",
+ "resampling methods are the **independent bootstrap** and **the jackknife**. \n",
+ "\n",
+ "The jackknife is a special case of the independent bootstrap. Still, the jackknife was made\n",
+ "popular prior to the independent bootstrap. And as the popularity of\n",
+ "the independent bootstrap soared, new variants, such as **the dependent bootstrap**.\n",
+ "\n",
+ "The Jackknife and independent bootstrap work for\n",
+ "independent, identically distributed random variables.\n",
+ "If these conditions are not\n",
+ "satisfied, the methods will fail. Yet, it should be said that if the data are\n",
+ "independent, identically distributed, and we only want to estimate the\n",
+ "variance of $\\overline{X}$ (which often is the case), then there is no\n",
+ "need for bootstrapping. \n",
+ "\n",
+ "\n",
+ "The Jackknife works by making many replicas of the estimator $\\widehat{\\theta}$. \n",
+ "The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\\boldsymbol{x} = (x_1,x_2,\\cdots,X_n)$. \n",
+ "Let $\\boldsymbol{x}_i$ denote the vector"
]
},
{
@@ -260,7 +371,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X} = \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& 1 \\\\ 1& -1\\\\ \\end{bmatrix} \\begin{bmatrix} 2& 0 \\\\ 0& 0\\\\ \\end{bmatrix} \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& -1 \\\\ 1& 1\\\\ \\end{bmatrix}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "\\boldsymbol{x}_i = (x_1,x_2,\\cdots,x_{i-1},x_{i+1},\\cdots,x_n),\n",
"$$"
]
},
@@ -268,45 +379,290 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "with eigenvalues $\\sigma_1=2$ and $\\sigma_2=0$. \n",
- "The SVD exits always! \n",
+ "which equals the vector $\\boldsymbol{x}$ with the exception that observation\n",
+ "number $i$ is left out. Using this notation, define\n",
+ "$\\widehat{\\theta}_i$ to be the estimator\n",
+ "$\\widehat{\\theta}$ computed using $\\vec{X}_i$."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from numpy import *\n",
+ "from numpy.random import randint, randn\n",
+ "from time import time\n",
"\n",
- "The SVD\n",
- "decomposition (singular values) gives eigenvalues \n",
- "$\\sigma_i\\geq\\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=p$, the\n",
- "eigenvalues (singular values) are zero.\n",
+ "def jackknife(data, stat):\n",
+ " n = len(data);t = zeros(n); inds = arange(n); t0 = time()\n",
+ " ## 'jackknifing' by leaving out an observation for each i \n",
+ " for i in range(n):\n",
+ " t[i] = stat(delete(data,i) )\n",
"\n",
- "In the general case, where our design matrix $\\boldsymbol{X}$ has dimension\n",
- "$n\\times p$, the matrix is thus decomposed into an $n\\times n$\n",
- "orthogonal matrix $\\boldsymbol{U}$, a $p\\times p$ orthogonal matrix $\\boldsymbol{V}$\n",
- "and a diagonal matrix $\\boldsymbol{\\Sigma}$ with $r=\\mathrm{min}(n,p)$\n",
- "singular values $\\sigma_i\\geq 0$ on the main diagonal and zeros filling\n",
- "the rest of the matrix. There are at most $p$ singular values\n",
- "assuming that $n > p$. In our regression examples for the nuclear\n",
- "masses and the equation of state this is indeed the case, while for\n",
- "the Ising model we have $p > n$. These are often cases that lead to\n",
- "near singular or singular matrices.\n",
+ " # analysis \n",
+ " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Jackknife Statistics :\")\n",
+ " print(\"original bias std. error\")\n",
+ " print(\"%8g %14g %15g\" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))\n",
"\n",
- "The columns of $\\boldsymbol{U}$ are called the left singular vectors while the columns of $\\boldsymbol{V}$ are the right singular vectors.\n",
+ " return t\n",
"\n",
- "## Economy-size SVD\n",
"\n",
- "If we assume that $n > p$, then our matrix $\\boldsymbol{U}$ has dimension $n\n",
- "\\times n$. The last $n-p$ columns of $\\boldsymbol{U}$ become however\n",
- "irrelevant in our calculations since they are multiplied with the\n",
- "zeros in $\\boldsymbol{\\Sigma}$.\n",
+ "# Returns mean of data samples \n",
+ "def stat(data):\n",
+ " return mean(data)\n",
"\n",
- "The economy-size decomposition removes extra rows or columns of zeros\n",
- "from the diagonal matrix of singular values, $\\boldsymbol{\\Sigma}$, along with the columns\n",
- "in either $\\boldsymbol{U}$ or $\\boldsymbol{V}$ that multiply those zeros in the expression. \n",
- "Removing these zeros and columns can improve execution time\n",
- "and reduce storage requirements without compromising the accuracy of\n",
- "the decomposition.\n",
"\n",
- "If $n > p$, we keep only the first $p$ columns of $\\boldsymbol{U}$ and $\\boldsymbol{\\Sigma}$ has dimension $p\\times p$. \n",
- "If $p > n$, then only the first $n$ columns of $\\boldsymbol{V}$ are computed and $\\boldsymbol{\\Sigma}$ has dimension $n\\times n$.\n",
- "The $n=p$ case is obvious, we retain the full SVD. \n",
- "In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy."
+ "mu, sigma = 100, 15\n",
+ "datapoints = 10000\n",
+ "x = mu + sigma*random.randn(datapoints)\n",
+ "# jackknife returns the data sample \n",
+ "t = jackknife(x, stat)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Bootstrap\n",
+ "\n",
+ "Bootstrapping is a nonparametric approach to statistical inference\n",
+ "that substitutes computation for more traditional distributional\n",
+ "assumptions and asymptotic results. Bootstrapping offers a number of\n",
+ "advantages: \n",
+ "1. The bootstrap is quite general, although there are some cases in which it fails. \n",
+ "\n",
+ "2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. \n",
+ "\n",
+ "3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. \n",
+ "\n",
+ "4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).\n",
+ "\n",
+ "Since $\\widehat{\\theta} = \\widehat{\\theta}(\\boldsymbol{X})$ is a function of random variables,\n",
+ "$\\widehat{\\theta}$ itself must be a random variable. Thus it has\n",
+ "a pdf, call this function $p(\\boldsymbol{t})$. The aim of the bootstrap is to\n",
+ "estimate $p(\\boldsymbol{t})$ by the relative frequency of\n",
+ "$\\widehat{\\theta}$. You can think of this as using a histogram\n",
+ "in the place of $p(\\boldsymbol{t})$. If the relative frequency closely\n",
+ "resembles $p(\\vec{t})$, then using numerics, it is straight forward to\n",
+ "estimate all the interesting parameters of $p(\\boldsymbol{t})$ using point\n",
+ "estimators. \n",
+ "\n",
+ "\n",
+ "\n",
+ "In the case that $\\widehat{\\theta}$ has\n",
+ "more than one component, and the components are independent, we use the\n",
+ "same estimator on each component separately. If the probability\n",
+ "density function of $X_i$, $p(x)$, had been known, then it would have\n",
+ "been straight forward to do this by: \n",
+ "1. Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \\cdots, X_n^*)$. \n",
+ "\n",
+ "2. Then using these numbers, we could compute a replica of $\\widehat{\\theta}$ called $\\widehat{\\theta}^*$. \n",
+ "\n",
+ "By repeated use of (1) and (2), many\n",
+ "estimates of $\\widehat{\\theta}$ could have been obtained. The\n",
+ "idea is to use the relative frequency of $\\widehat{\\theta}^*$\n",
+ "(think of a histogram) as an estimate of $p(\\boldsymbol{t})$.\n",
+ "\n",
+ "\n",
+ "But\n",
+ "unless there is enough information available about the process that\n",
+ "generated $X_1,X_2,\\cdots,X_n$, $p(x)$ is in general\n",
+ "unknown. Therefore, [Efron in 1979](https://projecteuclid.org/euclid.aos/1176344552) asked the\n",
+ "question: What if we replace $p(x)$ by the relative frequency\n",
+ "of the observation $X_i$; if we draw observations in accordance with\n",
+ "the relative frequency of the observations, will we obtain the same\n",
+ "result in some asymptotic sense? The answer is yes.\n",
+ "\n",
+ "\n",
+ "Instead of generating the histogram for the relative\n",
+ "frequency of the observation $X_i$, just draw the values\n",
+ "$(X_1^*,X_2^*,\\cdots,X_n^*)$ with replacement from the vector\n",
+ "$\\boldsymbol{X}$. \n",
+ "\n",
+ "\n",
+ "The independent bootstrap works like this: \n",
+ "\n",
+ "1. Draw with replacement $n$ numbers for the observed variables $\\boldsymbol{x} = (x_1,x_2,\\cdots,x_n)$. \n",
+ "\n",
+ "2. Define a vector $\\boldsymbol{x}^*$ containing the values which were drawn from $\\boldsymbol{x}$. \n",
+ "\n",
+ "3. Using the vector $\\boldsymbol{x}^*$ compute $\\widehat{\\theta}^*$ by evaluating $\\widehat \\theta$ under the observations $\\boldsymbol{x}^*$. \n",
+ "\n",
+ "4. Repeat this process $k$ times. \n",
+ "\n",
+ "When you are done, you can draw a histogram of the relative frequency\n",
+ "of $\\widehat \\theta^*$. This is your estimate of the probability\n",
+ "distribution $p(t)$. Using this probability distribution you can\n",
+ "estimate any statistics thereof. In principle you never draw the\n",
+ "histogram of the relative frequency of $\\widehat{\\theta}^*$. Instead\n",
+ "you use the estimators corresponding to the statistic of interest. For\n",
+ "example, if you are interested in estimating the variance of $\\widehat\n",
+ "\\theta$, apply the etsimator $\\widehat \\sigma^2$ to the values\n",
+ "$\\widehat \\theta ^*$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "The following code starts with a Gaussian distribution with mean value\n",
+ "$\\mu =100$ and variance $\\sigma=15$. We use this to generate the data\n",
+ "used in the bootstrap analysis. The bootstrap analysis returns a data\n",
+ "set after a given number of bootstrap operations (as many as we have\n",
+ "data points). This data set consists of estimated mean values for each\n",
+ "bootstrap operation. The histogram generated by the bootstrap method\n",
+ "shows that the distribution for these mean values is also a Gaussian,\n",
+ "centered around the mean value $\\mu=100$ but with standard deviation\n",
+ "$\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in\n",
+ "this case the same as the number of original data points). The value\n",
+ "of the standard deviation is what we expect from the central limit\n",
+ "theorem."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline\n",
+ "\n",
+ "from numpy import *\n",
+ "from numpy.random import randint, randn\n",
+ "from time import time\n",
+ "import matplotlib.mlab as mlab\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "# Returns mean of bootstrap samples \n",
+ "def stat(data):\n",
+ " return mean(data)\n",
+ "\n",
+ "# Bootstrap algorithm\n",
+ "def bootstrap(data, statistic, R):\n",
+ " t = zeros(R); n = len(data); inds = arange(n); t0 = time()\n",
+ " # non-parametric bootstrap \n",
+ " for i in range(R):\n",
+ " t[i] = statistic(data[randint(0,n,n)])\n",
+ "\n",
+ " # analysis \n",
+ " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Bootstrap Statistics :\")\n",
+ " print(\"original bias std. error\")\n",
+ " print(\"%8g %8g %14g %15g\" % (statistic(data), std(data),mean(t),std(t)))\n",
+ " return t\n",
+ "\n",
+ "\n",
+ "mu, sigma = 100, 15\n",
+ "datapoints = 10000\n",
+ "x = mu + sigma*random.randn(datapoints)\n",
+ "# bootstrap returns the data sample \n",
+ "t = bootstrap(x, stat, datapoints)\n",
+ "# the histogram of the bootstrapped data \n",
+ "n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)\n",
+ "\n",
+ "# add a 'best fit' line \n",
+ "y = mlab.normpdf( binsboot, mean(t), std(t))\n",
+ "lt = plt.plot(binsboot, y, 'r--', linewidth=1)\n",
+ "plt.xlabel('Smarts')\n",
+ "plt.ylabel('Probability')\n",
+ "plt.axis([99.5, 100.6, 0, 3.0])\n",
+ "plt.grid(True)\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Various steps in cross-validation\n",
+ "\n",
+ "When the repetitive splitting of the data set is done randomly,\n",
+ "samples may accidently end up in a fast majority of the splits in\n",
+ "either training or test set. Such samples may have an unbalanced\n",
+ "influence on either model building or prediction evaluation. To avoid\n",
+ "this $k$-fold cross-validation structures the data splitting. The\n",
+ "samples are divided into $k$ more or less equally sized exhaustive and\n",
+ "mutually exclusive subsets. In turn (at each split) one of these\n",
+ "subsets plays the role of the test set while the union of the\n",
+ "remaining subsets constitutes the training set. Such a splitting\n",
+ "warrants a balanced representation of each sample in both training and\n",
+ "test set over the splits. Still the division into the $k$ subsets\n",
+ "involves a degree of randomness. This may be fully excluded when\n",
+ "choosing $k=n$. This particular case is referred to as leave-one-out\n",
+ "cross-validation (LOOCV). \n",
+ "\n",
+ "\n",
+ "* Define a range of interest for the penalty parameter.\n",
+ "\n",
+ "* Divide the data set into training and test set comprising samples $\\{1, \\ldots, n\\} \\setminus i$ and $\\{ i \\}$, respectively.\n",
+ "\n",
+ "* Fit the linear regression model by means of ridge estimation for each $\\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\\boldsymbol{\\sigma}_{-i}^2(\\lambda)$, as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\boldsymbol{\\beta}_{-i}(\\lambda) & = ( \\boldsymbol{X}_{-i, \\ast}^{T}\n",
+ "\\boldsymbol{X}_{-i, \\ast} + \\lambda \\boldsymbol{I}_{pp})^{-1}\n",
+ "\\boldsymbol{X}_{-i, \\ast}^{T} \\boldsymbol{y}_{-i}\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "* Evaluate the prediction performance of these models on the test set by $\\log\\{L[y_i, \\boldsymbol{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}$. Or, by the prediction error $|y_i - \\boldsymbol{X}_{i, \\ast} \\boldsymbol{\\beta}_{-i}(\\lambda)|$, the relative error, the error squared or the R2 score function.\n",
+ "\n",
+ "* Repeat the first three steps such that each sample plays the role of the test set once.\n",
+ "\n",
+ "* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\frac{1}{n} \\sum_{i = 1}^n \\log\\{L[y_i, \\mathbf{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}.\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For the various values of $k$\n",
+ "\n",
+ "1. shuffle the dataset randomly.\n",
+ "\n",
+ "2. Split the dataset into $k$ groups.\n",
+ "\n",
+ "3. For each unique group:\n",
+ "\n",
+ "a. Decide which group to use as set for test data\n",
+ "\n",
+ "b. Take the remaining groups as a training data set\n",
+ "\n",
+ "c. Fit a model on the training set and evaluate it on the test set\n",
+ "\n",
+ "d. Retain the evaluation score and discard the model\n",
+ "\n",
+ "\n",
+ "5. Summarize the model using the sample of model evaluation scores\n",
+ "\n",
+ "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial."
]
},
{
@@ -319,60 +675,110 @@
"outputs": [],
"source": [
"import numpy as np\n",
- "# SVD inversion\n",
- "def SVDinv(A):\n",
- " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n",
- " SVD is numerically more stable than the inversion algorithms provided by\n",
- " numpy and scipy.linalg at the cost of being slower.\n",
- " '''\n",
- " U, s, VT = np.linalg.svd(A)\n",
- "# print('test U')\n",
- "# print( (np.transpose(U) @ U - U @np.transpose(U)))\n",
- "# print('test VT')\n",
- "# print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n",
- " print(U)\n",
- " print(s)\n",
- " print(VT)\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import KFold\n",
+ "from sklearn.linear_model import Ridge\n",
+ "from sklearn.model_selection import cross_val_score\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
"\n",
- " D = np.zeros((len(U),len(VT)))\n",
- " for i in range(0,len(VT)):\n",
- " D[i,i]=s[i]\n",
- " UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)\n",
- " return np.matmul(V,np.matmul(invD,UT))\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "np.random.seed(3155)\n",
+ "\n",
+ "# Generate the data.\n",
+ "nsamples = 100\n",
+ "x = np.random.randn(nsamples)\n",
+ "y = 3*x**2 + np.random.randn(nsamples)\n",
+ "\n",
+ "## Cross-validation on Ridge regression using KFold only\n",
+ "\n",
+ "# Decide degree on polynomial to fit\n",
+ "poly = PolynomialFeatures(degree = 6)\n",
+ "\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 500\n",
+ "lambdas = np.logspace(-3, 5, nlambdas)\n",
+ "\n",
+ "# Initialize a KFold instance\n",
+ "k = 5\n",
+ "kfold = KFold(n_splits = k)\n",
+ "\n",
+ "# Perform the cross-validation to estimate MSE\n",
+ "scores_KFold = np.zeros((nlambdas, k))\n",
+ "\n",
+ "i = 0\n",
+ "for lmb in lambdas:\n",
+ " ridge = Ridge(alpha = lmb)\n",
+ " j = 0\n",
+ " for train_inds, test_inds in kfold.split(x):\n",
+ " xtrain = x[train_inds]\n",
+ " ytrain = y[train_inds]\n",
+ "\n",
+ " xtest = x[test_inds]\n",
+ " ytest = y[test_inds]\n",
+ "\n",
+ " Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n",
+ " ridge.fit(Xtrain, ytrain[:, np.newaxis])\n",
+ "\n",
+ " Xtest = poly.fit_transform(xtest[:, np.newaxis])\n",
+ " ypred = ridge.predict(Xtest)\n",
+ "\n",
+ " scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n",
+ "\n",
+ " j += 1\n",
+ " i += 1\n",
"\n",
"\n",
- "X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])\n",
- "print(X)\n",
- "A = np.transpose(X) @ X\n",
- "print(A)\n",
- "# Brute force inversion of super-collinear matrix\n",
- "#B = np.linalg.inv(A)\n",
- "#print(B)\n",
- "C = SVDinv(A)\n",
- "print(C)"
+ "estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n",
+ "\n",
+ "## Cross-validation using cross_val_score from sklearn along with KFold\n",
+ "\n",
+ "# kfold is an instance initialized above as:\n",
+ "# kfold = KFold(n_splits = k)\n",
+ "\n",
+ "estimated_mse_sklearn = np.zeros(nlambdas)\n",
+ "i = 0\n",
+ "for lmb in lambdas:\n",
+ " ridge = Ridge(alpha = lmb)\n",
+ "\n",
+ " X = poly.fit_transform(x[:, np.newaxis])\n",
+ " estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n",
+ "\n",
+ " # cross_val_score return an array containing the estimated negative mse for every fold.\n",
+ " # we have to the the mean of every array in order to get an estimate of the mse of the model\n",
+ " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n",
+ "\n",
+ " i += 1\n",
+ "\n",
+ "## Plot and compare the slightly different ways to perform cross-validation\n",
+ "\n",
+ "plt.figure()\n",
+ "\n",
+ "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n",
+ "plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n",
+ "\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('mse')\n",
+ "\n",
+ "plt.legend()\n",
+ "\n",
+ "plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "The matrix $\\boldsymbol{X}$ has columns that are linearly dependent. The first\n",
- "column is the row-wise sum of the other two columns. The rank of a\n",
- "matrix (the column rank) is the dimension of space spanned by the\n",
- "column vectors. The rank of the matrix is the number of linearly\n",
- "independent columns, in this case just $2$. We see this from the\n",
- "singular values when running the above code. Running the standard\n",
- "inversion algorithm for matrix inversion with $\\boldsymbol{X}^T\\boldsymbol{X}$ results\n",
- "in the program terminating due to a singular matrix.\n",
+ "## The bias-variance tradeoff\n",
"\n",
"\n",
+ "We will discuss the bias-variance tradeoff in the context of\n",
+ "continuous predictions such as regression. However, many of the\n",
+ "intuitions and ideas discussed here also carry over to classification\n",
+ "tasks. Consider a dataset $\\mathcal{L}$ consisting of the data\n",
+ "$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$. \n",
"\n",
- "\n",
- "There are several interesting mathematical properties which will be\n",
- "relevant when we are going to discuss the differences between say\n",
- "ordinary least squares (OLS) and **Ridge** regression.\n",
- "\n",
- "We have from OLS that the parameters of the linear approximation are given by"
+ "Let us assume that the true data is generated from a noisy model"
]
},
{
@@ -380,7 +786,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}\n",
"$$"
]
},
@@ -388,7 +794,14 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The matrix to invert can be rewritten in terms of our SVD decomposition as"
+ "where $\\epsilon$ is normally distributed with mean zero and standard deviation $\\sigma^2$.\n",
+ "\n",
+ "In our derivation of the ordinary least squares method we defined then\n",
+ "an approximation to the function $f$ in terms of the parameters\n",
+ "$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n",
+ "that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$. \n",
+ "\n",
+ "Thereafter we found the parameters $\\boldsymbol{\\beta}$ by optimizing the means squared error via the so-called cost function"
]
},
{
@@ -396,7 +809,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X}^T\\boldsymbol{X} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n",
"$$"
]
},
@@ -404,7 +817,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Using the orthogonality properties of $\\boldsymbol{U}$ we have"
+ "We can rewrite this as"
]
},
{
@@ -412,7 +825,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X}^T\\boldsymbol{X} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T = \\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T,\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\frac{1}{n}\\sum_i(f_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\sigma^2.\n",
"$$"
]
},
@@ -420,9 +833,14 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "with $\\boldsymbol{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared. \n",
+ "The three terms represent the square of the bias of the learning\n",
+ "method, which can be thought of as the error caused by the simplifying\n",
+ "assumptions built into the method. The second term represents the\n",
+ "variance of the chosen model and finally the last terms is variance of\n",
+ "the error $\\boldsymbol{\\epsilon}$.\n",
"\n",
- "This means that"
+ "To derive this equation, we need to recall that the variance of $\\boldsymbol{y}$ and $\\boldsymbol{\\epsilon}$ are both equal to $\\sigma^2$. The mean value of $\\boldsymbol{\\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\\boldsymbol{\\tilde{y}}$.\n",
+ "We use a more compact notation in terms of the expectation value"
]
},
{
@@ -430,7 +848,7 @@
"metadata": {},
"source": [
"$$\n",
- "(\\boldsymbol{X}^T\\boldsymbol{X})\\boldsymbol{V} = \\boldsymbol{V}\\boldsymbol{D},\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}})^2\\right],\n",
"$$"
]
},
@@ -438,7 +856,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "that is the eigenvectors of $(\\boldsymbol{X}^T\\boldsymbol{X})$ are given by the columns of the right singular matrix of $\\boldsymbol{X}$ and the eigenvalues are the squared singular values. It is easy to show (show this) that"
+ "and adding and subtracting $\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]$ we get"
]
},
{
@@ -446,7 +864,7 @@
"metadata": {},
"source": [
"$$\n",
- "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U} = \\boldsymbol{U}\\boldsymbol{D},\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}}+\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right],\n",
"$$"
]
},
@@ -454,9 +872,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "that is, the eigenvectors of $(\\boldsymbol{X}\\boldsymbol{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same. \n",
- "\n",
- "Going back to our OLS equation we have"
+ "which, using the abovementioned expectation values can be rewritten as"
]
},
{
@@ -464,7 +880,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right]+\\mathrm{Var}\\left[\\boldsymbol{\\tilde{y}}\\right]+\\sigma^2,\n",
"$$"
]
},
@@ -472,642 +888,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "We will come back to this expression when we discuss Ridge regression. \n",
- "\n",
- "\n",
- "$$ \\tilde{y}^{OLS}=\\boldsymbol{X}\\hat{\\beta}^{OLS}=\\sum_{j=1}^p \\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y}$$ and for Ridge we have \n",
- "\n",
- "$$ \\tilde{y}^{Ridge}=\\boldsymbol{X}\\hat{\\beta}^{Ridge}=\\sum_{j=1}^p \\boldsymbol{u}_j\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{u}_j^T\\boldsymbol{y}$$ . \n",
- "\n",
- "It is indeed the economy-sized SVD, note the summation runs up tp $$p$$ only and not $$n$$. \n",
- "\n",
- "Here we have that $$\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T$$, with $$\\Sigma$$ being an $$ n\\times p$$ matrix and $$\\boldsymbol{V}$$ being a $$ p\\times p$$ matrix. We also have assumed here that $$ n > p$$. \n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "## Ridge and LASSO Regression\n",
- "\n",
- "[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember11.mp4?vrtx=view-as-webpage)\n",
- "\n",
- "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n",
- "our optimization problem is"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "or we can state it as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
- "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "where we have used the definition of a norm-2 vector, that is"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "By minimizing the above equation with respect to the parameters\n",
- "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n",
- "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n",
- "defining a new cost function to be optimized, that is"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
- "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which leads to the Ridge regression minimization problem where we\n",
- "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n",
- "a finite number larger than zero. By defining"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "we have a new optimization equation"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
- "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n",
- "\n",
- "Here we have defined the norm-1 as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Using the matrix-vector expression for Ridge regression,"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "by taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n",
- "a slightly modified matrix inversion problem which for finite values\n",
- "of $\\lambda$ does not suffer from singularity problems. We obtain"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with $t$ a finite positive number. \n",
- "\n",
- "We see that Ridge regression is nothing but the standard\n",
- "OLS with a modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The\n",
- "consequences, in particular for our discussion of the bias-variance tradeoff \n",
- "are rather interesting.\n",
- "\n",
- "Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U} = \\boldsymbol{U}\\boldsymbol{D}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "For Ridge regression this becomes"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$. \n",
- "\n",
- "\n",
- "Since $\\lambda \\geq 0$, it means that compared to OLS, we have"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n",
- "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n",
- "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n",
- "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n",
- "\\sigma_{i+1}$.\n",
- "\n",
- "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom.\n",
- "Actually, calculating the variance of $\\boldsymbol{X}\\boldsymbol{v}_j$ shows that this quantity is equal to $\\sigma_j^2/n$.\n",
- "With a parameter $\\lambda$ we can thus shrink the role of specific parameters. \n",
- "\n",
- "\n",
- "\n",
- "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In this case the standard OLS results in"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "and"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n",
- "the Ridge estimator converges to zero when the hyperparameter goes to\n",
- "infinity.\n",
- "\n",
- "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n",
- "\n",
- "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n",
- "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\n",
- "\n",
- "\n",
- "\n",
- "## A better understanding of regularization\n",
- "\n",
- "The parameter $\\lambda$ that we have introduced in the Ridge (and\n",
- "Lasso as well) regression is often called a regularization parameter\n",
- "or shrinkage parameter. It is common to call it a hyperparameter. What does it mean mathemtically?\n",
- "\n",
- "Here we will first look at how to analyze the difference between the\n",
- "standard OLS equations and the Ridge expressions in terms of a linear\n",
- "algebra analysis using the SVD algorithm. Thereafter, we will link\n",
- "(see the material on the bias-variance tradeoff below) these\n",
- "observation to the statisical analysis of the results. In particular\n",
- "we consider how the variance of the parameters $\\boldsymbol{\\beta}$ is\n",
- "affected by changing the parameter $\\lambda$.\n",
- "\n",
- "\n",
- "We have our design matrix\n",
- " $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. With the SVD we decompose it as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X} = \\boldsymbol{U\\Sigma V^T},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with $\\boldsymbol{U}\\in {\\mathbb{R}}^{n\\times n}$, $\\boldsymbol{\\Sigma}\\in {\\mathbb{R}}^{n\\times p}$\n",
- "and $\\boldsymbol{V}\\in {\\mathbb{R}}^{p\\times p}$.\n",
- "\n",
- "The matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$ are unitary/orthonormal matrices, that is in case the matrices are real we have $\\boldsymbol{U}^T\\boldsymbol{U}=\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ and $\\boldsymbol{V}^T\\boldsymbol{V}=\\boldsymbol{V}\\boldsymbol{V}^T=\\boldsymbol{I}$.\n",
- "\n",
- "\n",
- "\n",
- "## Introducing the Covariance and Correlation functions\n",
- "\n",
- "Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about\n",
- "the definition of the covariance and the correlation function. These are quantities \n",
- "\n",
- "Suppose we have defined two vectors\n",
- "$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
- " \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "where for example"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "With this definition and recalling that the variance is defined as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "we can rewrite the covariance matrix as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
- " \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n",
- " \\end{bmatrix}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The covariance takes values between zero and infinity and may thus\n",
- "lead to problems with loss of numerical precision for particularly\n",
- "large values. It is common to scale the covariance matrix by\n",
- "introducing instead the correlation matrix defined via the so-called\n",
- "correlation function"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]=\\frac{\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}]}{\\sqrt{\\mathrm{var}[\\boldsymbol{x}] \\mathrm{var}[\\boldsymbol{y}]}}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The correlation function is then given by values $\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]\n",
- "\\in [-1,1]$. This avoids eventual problems with too large values. We\n",
- "can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n",
- "and $\\boldsymbol{y}$ as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
- " \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In the above example this is the function we constructed using **pandas**.\n",
- "\n",
- "\n",
- "\n",
- "In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**\n",
- "we defined the design/feature matrix $\\boldsymbol{X}$ as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}=\\begin{bmatrix}\n",
- "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
- "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
- "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
- "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
- "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
- "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ refering to the column numbers and the\n",
- "entries $n$ being the row elements.\n",
- "We can rewrite the design/feature matrix in terms of its column vectors as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with a given vector"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{x}_i^T = \\begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \\dots & \\dots x_{n-1,i}\\end{bmatrix}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "With these definitions, we can now rewrite our $2\\times 2$\n",
- "correaltion/covariance matrix in terms of a moe general design/feature\n",
- "matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$\n",
- "covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i=0,1,\\dots,p-1$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
- "\\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}]\\\\\n",
- "\\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}]\\\\\n",
- "\\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}]\\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\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}]\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "and the correlation matrix"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
- "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}]\\\\\n",
- "\\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}]\\\\\n",
- "\\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}]\\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\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\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The Numpy function **np.cov** calculates the covariance elements using\n",
- "the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n",
- "the exact mean values. The following simple function uses the\n",
- "**np.vstack** function which takes each vector of dimension $1\\times n$\n",
- "and produces a $2\\times n$ matrix $\\boldsymbol{W}$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{W} = \\begin{bmatrix} x_0 & y_0 \\\\\n",
- " x_1 & y_1 \\\\\n",
- " x_2 & y_2\\\\\n",
- " \\dots & \\dots \\\\\n",
- " x_{n-2} & y_{n-2}\\\\\n",
- " x_{n-1} & y_{n-1} & \n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which in turn is converted into into the $2\\times 2$ covariance matrix\n",
- "$\\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate\n",
- "the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n",
- "function **np.mean(x)**. We can also extract the eigenvalues of the\n",
- "covariance matrix through the **np.linalg.eig()** function."
+ "that is the rewriting in terms of the so-called bias, the variance of the model $\\boldsymbol{\\tilde{y}}$ and the variance of $\\boldsymbol{\\epsilon}$."
]
},
{
@@ -1119,27 +900,60 @@
},
"outputs": [],
"source": [
- "# Importing various packages\n",
+ "import matplotlib.pyplot as plt\n",
"import numpy as np\n",
- "n = 100\n",
- "x = np.random.normal(size=n)\n",
- "print(np.mean(x))\n",
- "y = 4+3*x+np.random.normal(size=n)\n",
- "print(np.mean(y))\n",
- "W = np.vstack((x, y))\n",
- "C = np.cov(W)\n",
- "print(C)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The previous example can be converted into the correlation matrix by\n",
- "simply scaling the matrix elements with the variances. We should also\n",
- "subtract the mean values for each column. This leads to the following\n",
- "code which sets up the correlations matrix for the previous example in\n",
- "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)."
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.pipeline import make_pipeline\n",
+ "from sklearn.utils import resample\n",
+ "\n",
+ "np.random.seed(2018)\n",
+ "\n",
+ "n = 500\n",
+ "n_boostraps = 100\n",
+ "degree = 18 # A quite high value, just to show.\n",
+ "noise = 0.1\n",
+ "\n",
+ "# Make data set.\n",
+ "x = np.linspace(-1, 3, n).reshape(-1, 1)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)\n",
+ "\n",
+ "# Hold out some test data that is never used in training.\n",
+ "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
+ "\n",
+ "# Combine x transformation and model into one operation.\n",
+ "# Not neccesary, but convenient.\n",
+ "model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
+ "\n",
+ "# The following (m x n_bootstraps) matrix holds the column vectors y_pred\n",
+ "# for each bootstrap iteration.\n",
+ "y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
+ "for i in range(n_boostraps):\n",
+ " x_, y_ = resample(x_train, y_train)\n",
+ "\n",
+ " # Evaluate the new model on the same test data each time.\n",
+ " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
+ "\n",
+ "# Note: Expectations and variances taken w.r.t. different training\n",
+ "# data sets, hence the axis=1. Subsequent means are taken across the test data\n",
+ "# set in order to obtain a total value, but before this we have error/bias/variance\n",
+ "# calculated per data point in the test set.\n",
+ "# Note 2: The use of keepdims=True is important in the calculation of bias as this \n",
+ "# maintains the column vector form. Dropping this yields very unexpected results.\n",
+ "error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
+ "bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
+ "variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
+ "print('Error:', error)\n",
+ "print('Bias^2:', bias)\n",
+ "print('Var:', variance)\n",
+ "print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))\n",
+ "\n",
+ "plt.plot(x[::5, :], y[::5, :], label='f(x)')\n",
+ "plt.scatter(x_test, y_test, label='Data points')\n",
+ "plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')\n",
+ "plt.legend()\n",
+ "plt.show()"
]
},
{
@@ -1151,41 +965,89 @@
},
"outputs": [],
"source": [
+ "import matplotlib.pyplot as plt\n",
"import numpy as np\n",
- "n = 100\n",
- "# define two vectors \n",
- "x = np.random.random(size=n)\n",
- "y = 4+3*x+np.random.normal(size=n)\n",
- "#scaling the x and y vectors \n",
- "x = x - np.mean(x)\n",
- "y = y - np.mean(y)\n",
- "variance_x = np.sum(x@x)/n\n",
- "variance_y = np.sum(y@y)/n\n",
- "print(variance_x)\n",
- "print(variance_y)\n",
- "cov_xy = np.sum(x@y)/n\n",
- "cov_xx = np.sum(x@x)/n\n",
- "cov_yy = np.sum(y@y)/n\n",
- "C = np.zeros((2,2))\n",
- "C[0,0]= cov_xx/variance_x\n",
- "C[1,1]= cov_yy/variance_y\n",
- "C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n",
- "C[1,0]= C[0,1]\n",
- "print(C)"
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.pipeline import make_pipeline\n",
+ "from sklearn.utils import resample\n",
+ "\n",
+ "np.random.seed(2018)\n",
+ "\n",
+ "n = 40\n",
+ "n_boostraps = 100\n",
+ "maxdegree = 14\n",
+ "\n",
+ "\n",
+ "# Make data set.\n",
+ "x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
+ "error = np.zeros(maxdegree)\n",
+ "bias = np.zeros(maxdegree)\n",
+ "variance = np.zeros(maxdegree)\n",
+ "polydegree = np.zeros(maxdegree)\n",
+ "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
+ "\n",
+ "for degree in range(maxdegree):\n",
+ " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
+ " y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
+ " for i in range(n_boostraps):\n",
+ " x_, y_ = resample(x_train, y_train)\n",
+ " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
+ "\n",
+ " polydegree[degree] = degree\n",
+ " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
+ " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
+ " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
+ " print('Polynomial degree:', degree)\n",
+ " print('Error:', error[degree])\n",
+ " print('Bias^2:', bias[degree])\n",
+ " print('Var:', variance[degree])\n",
+ " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n",
+ "\n",
+ "plt.plot(polydegree, error, label='Error')\n",
+ "plt.plot(polydegree, bias, label='bias')\n",
+ "plt.plot(polydegree, variance, label='Variance')\n",
+ "plt.legend()\n",
+ "plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "We see that the matrix elements along the diagonal are one as they\n",
- "should be and that the matrix is symmetric. Furthermore, diagonalizing\n",
- "this matrix we easily see that it is a positive definite matrix.\n",
- "\n",
- "The above procedure with **numpy** can be made more compact if we use **pandas**.\n",
+ "The bias-variance tradeoff summarizes the fundamental tension in\n",
+ "machine learning, particularly supervised learning, between the\n",
+ "complexity of a model and the amount of training data needed to train\n",
+ "it. Since data is often limited, in practice it is often useful to\n",
+ "use a less-complex model with higher bias, that is a model whose asymptotic\n",
+ "performance is worse than another model because it is easier to\n",
+ "train and less sensitive to sampling noise arising from having a\n",
+ "finite-sized training dataset (smaller variance). \n",
"\n",
"\n",
- "We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code"
+ "\n",
+ "The above equations tell us that in\n",
+ "order to minimize the expected test error, we need to select a\n",
+ "statistical learning method that simultaneously achieves low variance\n",
+ "and low bias. Note that variance is inherently a nonnegative quantity,\n",
+ "and squared bias is also nonnegative. Hence, we see that the expected\n",
+ "test MSE can never lie below $Var(\\epsilon)$, the irreducible error.\n",
+ "\n",
+ "\n",
+ "What do we mean by the variance and bias of a statistical learning\n",
+ "method? The variance refers to the amount by which our model would change if we\n",
+ "estimated it using a different training data set. Since the training\n",
+ "data are used to fit the statistical learning method, different\n",
+ "training data sets will result in a different estimate. But ideally the\n",
+ "estimate for our model should not vary too much between training\n",
+ "sets. However, if a method has high variance then small changes in\n",
+ "the training data can result in large changes in the model. In general, more\n",
+ "flexible statistical methods have higher variance.\n",
+ "\n",
+ "\n",
+ "You may also find this recent [article](https://www.pnas.org/content/116/32/15849) of interest."
]
},
{
@@ -1197,26 +1059,77 @@
},
"outputs": [],
"source": [
+ "\"\"\"\n",
+ "============================\n",
+ "Underfitting vs. Overfitting\n",
+ "============================\n",
+ "\n",
+ "This example demonstrates the problems of underfitting and overfitting and\n",
+ "how we can use linear regression with polynomial features to approximate\n",
+ "nonlinear functions. The plot shows the function that we want to approximate,\n",
+ "which is a part of the cosine function. In addition, the samples from the\n",
+ "real function and the approximations of different models are displayed. The\n",
+ "models have polynomial features of different degrees. We can see that a\n",
+ "linear function (polynomial with degree 1) is not sufficient to fit the\n",
+ "training samples. This is called **underfitting**. A polynomial of degree 4\n",
+ "approximates the true function almost perfectly. However, for higher degrees\n",
+ "the model will **overfit** the training data, i.e. it learns the noise of the\n",
+ "training data.\n",
+ "We evaluate quantitatively **overfitting** / **underfitting** by using\n",
+ "cross-validation. We calculate the mean squared error (MSE) on the validation\n",
+ "set, the higher, the less likely the model generalizes correctly from the\n",
+ "training data.\n",
+ "\"\"\"\n",
+ "\n",
+ "print(__doc__)\n",
+ "\n",
"import numpy as np\n",
- "import pandas as pd\n",
- "n = 10\n",
- "x = np.random.normal(size=n)\n",
- "x = x - np.mean(x)\n",
- "y = 4+3*x+np.random.normal(size=n)\n",
- "y = y - np.mean(y)\n",
- "X = (np.vstack((x, y))).T\n",
- "print(X)\n",
- "Xpd = pd.DataFrame(X)\n",
- "print(Xpd)\n",
- "correlation_matrix = Xpd.corr()\n",
- "print(correlation_matrix)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "We expand this model to the Franke function discussed above."
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.pipeline import Pipeline\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "from sklearn.linear_model import LinearRegression\n",
+ "from sklearn.model_selection import cross_val_score\n",
+ "\n",
+ "\n",
+ "def true_fun(X):\n",
+ " return np.cos(1.5 * np.pi * X)\n",
+ "\n",
+ "np.random.seed(0)\n",
+ "\n",
+ "n_samples = 30\n",
+ "degrees = [1, 4, 15]\n",
+ "\n",
+ "X = np.sort(np.random.rand(n_samples))\n",
+ "y = true_fun(X) + np.random.randn(n_samples) * 0.1\n",
+ "\n",
+ "plt.figure(figsize=(14, 5))\n",
+ "for i in range(len(degrees)):\n",
+ " ax = plt.subplot(1, len(degrees), i + 1)\n",
+ " plt.setp(ax, xticks=(), yticks=())\n",
+ "\n",
+ " polynomial_features = PolynomialFeatures(degree=degrees[i],\n",
+ " include_bias=False)\n",
+ " linear_regression = LinearRegression()\n",
+ " pipeline = Pipeline([(\"polynomial_features\", polynomial_features),\n",
+ " (\"linear_regression\", linear_regression)])\n",
+ " pipeline.fit(X[:, np.newaxis], y)\n",
+ "\n",
+ " # Evaluate the models using crossvalidation\n",
+ " scores = cross_val_score(pipeline, X[:, np.newaxis], y,\n",
+ " scoring=\"neg_mean_squared_error\", cv=10)\n",
+ "\n",
+ " X_test = np.linspace(0, 1, 100)\n",
+ " plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label=\"Model\")\n",
+ " plt.plot(X_test, true_fun(X_test), label=\"True function\")\n",
+ " plt.scatter(X, y, edgecolor='b', s=20, label=\"Samples\")\n",
+ " plt.xlabel(\"x\")\n",
+ " plt.ylabel(\"y\")\n",
+ " plt.xlim((0, 1))\n",
+ " plt.ylim((-2, 2))\n",
+ " plt.legend(loc=\"best\")\n",
+ " plt.title(\"Degree {}\\nMSE = {:.2e}(+/- {:.2e})\".format(\n",
+ " degrees[i], -scores.mean(), scores.std()))\n",
+ "plt.show()"
]
},
{
@@ -1229,146 +1142,207 @@
"outputs": [],
"source": [
"# Common imports\n",
+ "import os\n",
"import numpy as np\n",
"import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.utils import resample\n",
+ "from sklearn.metrics import mean_squared_error\n",
+ "# Where to save the figures and data files\n",
+ "PROJECT_ROOT_DIR = \"Results\"\n",
+ "FIGURE_ID = \"Results/FigureFiles\"\n",
+ "DATA_ID = \"DataFiles/\"\n",
"\n",
+ "if not os.path.exists(PROJECT_ROOT_DIR):\n",
+ " os.mkdir(PROJECT_ROOT_DIR)\n",
"\n",
- "def FrankeFunction(x,y):\n",
- "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
- "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
- "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
- "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
- "\treturn term1 + term2 + term3 + term4\n",
+ "if not os.path.exists(FIGURE_ID):\n",
+ " os.makedirs(FIGURE_ID)\n",
"\n",
+ "if not os.path.exists(DATA_ID):\n",
+ " os.makedirs(DATA_ID)\n",
"\n",
- "def create_X(x, y, n ):\n",
- "\tif len(x.shape) > 1:\n",
- "\t\tx = np.ravel(x)\n",
- "\t\ty = np.ravel(y)\n",
+ "def image_path(fig_id):\n",
+ " return os.path.join(FIGURE_ID, fig_id)\n",
"\n",
- "\tN = len(x)\n",
- "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n",
- "\tX = np.ones((N,l))\n",
+ "def data_path(dat_id):\n",
+ " return os.path.join(DATA_ID, dat_id)\n",
"\n",
- "\tfor i in range(1,n+1):\n",
- "\t\tq = int((i)*(i+1)/2)\n",
- "\t\tfor k in range(i+1):\n",
- "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n",
+ "def save_fig(fig_id):\n",
+ " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
"\n",
- "\treturn X\n",
+ "infile = open(data_path(\"EoS.csv\"),'r')\n",
"\n",
+ "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
+ "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
+ "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
+ "EoS = EoS.dropna()\n",
+ "Energies = EoS['Energy']\n",
+ "Density = EoS['Density']\n",
+ "# The design matrix now as function of various polytrops\n",
"\n",
- "# Making meshgrid of datapoints and compute Franke's function\n",
- "n = 4\n",
- "N = 100\n",
- "x = np.sort(np.random.uniform(0, 1, N))\n",
- "y = np.sort(np.random.uniform(0, 1, N))\n",
- "z = FrankeFunction(x, y)\n",
- "X = create_X(x, y, n=n) \n",
+ "Maxpolydegree = 30\n",
+ "X = np.zeros((len(Density),Maxpolydegree))\n",
+ "X[:,0] = 1.0\n",
+ "testerror = np.zeros(Maxpolydegree)\n",
+ "trainingerror = np.zeros(Maxpolydegree)\n",
+ "polynomial = np.zeros(Maxpolydegree)\n",
"\n",
- "Xpd = pd.DataFrame(X)\n",
- "# subtract the mean values and set up the covariance matrix\n",
- "Xpd = Xpd - Xpd.mean()\n",
- "covariance_matrix = Xpd.cov()\n",
- "print(covariance_matrix)"
+ "trials = 100\n",
+ "for polydegree in range(1, Maxpolydegree):\n",
+ " polynomial[polydegree] = polydegree\n",
+ " for degree in range(polydegree):\n",
+ " X[:,degree] = Density**(degree/3.0)\n",
+ "\n",
+ "# loop over trials in order to estimate the expectation value of the MSE\n",
+ " testerror[polydegree] = 0.0\n",
+ " trainingerror[polydegree] = 0.0\n",
+ " for samples in range(trials):\n",
+ " x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n",
+ " model = LinearRegression(fit_intercept=True).fit(x_train, y_train)\n",
+ " ypred = model.predict(x_train)\n",
+ " ytilde = model.predict(x_test)\n",
+ " testerror[polydegree] += mean_squared_error(y_test, ytilde)\n",
+ " trainingerror[polydegree] += mean_squared_error(y_train, ypred) \n",
+ "\n",
+ " testerror[polydegree] /= trials\n",
+ " trainingerror[polydegree] /= trials\n",
+ " print(\"Degree of polynomial: %3d\"% polynomial[polydegree])\n",
+ " print(\"Mean squared error on training data: %.8f\" % trainingerror[polydegree])\n",
+ " print(\"Mean squared error on test data: %.8f\" % testerror[polydegree])\n",
+ "\n",
+ "plt.plot(polynomial, np.log10(trainingerror), label='Training Error')\n",
+ "plt.plot(polynomial, np.log10(testerror), label='Test Error')\n",
+ "plt.xlabel('Polynomial degree')\n",
+ "plt.ylabel('log10[MSE]')\n",
+ "plt.legend()\n",
+ "plt.show()"
]
},
{
- "cell_type": "markdown",
- "metadata": {},
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
"source": [
- "We note here that the covariance is zero for the first rows and\n",
- "columns since all matrix elements in the design matrix were set to one\n",
- "(we are fitting the function in terms of a polynomial of degree $n$).\n",
- "\n",
- "This means that the variance for these elements will be zero and will\n",
- "cause problems when we set up the correlation matrix. We can simply\n",
- "drop these elements and construct a correlation\n",
- "matrix without these elements. \n",
+ "# Common imports\n",
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.metrics import mean_squared_error\n",
+ "from sklearn.model_selection import KFold\n",
+ "from sklearn.model_selection import cross_val_score\n",
"\n",
"\n",
+ "# Where to save the figures and data files\n",
+ "PROJECT_ROOT_DIR = \"Results\"\n",
+ "FIGURE_ID = \"Results/FigureFiles\"\n",
+ "DATA_ID = \"DataFiles/\"\n",
"\n",
+ "if not os.path.exists(PROJECT_ROOT_DIR):\n",
+ " os.mkdir(PROJECT_ROOT_DIR)\n",
"\n",
- "We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\\boldsymbol{X}$ as"
+ "if not os.path.exists(FIGURE_ID):\n",
+ " os.makedirs(FIGURE_ID)\n",
+ "\n",
+ "if not os.path.exists(DATA_ID):\n",
+ " os.makedirs(DATA_ID)\n",
+ "\n",
+ "def image_path(fig_id):\n",
+ " return os.path.join(FIGURE_ID, fig_id)\n",
+ "\n",
+ "def data_path(dat_id):\n",
+ " return os.path.join(DATA_ID, dat_id)\n",
+ "\n",
+ "def save_fig(fig_id):\n",
+ " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
+ "\n",
+ "infile = open(data_path(\"EoS.csv\"),'r')\n",
+ "\n",
+ "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
+ "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
+ "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
+ "EoS = EoS.dropna()\n",
+ "Energies = EoS['Energy']\n",
+ "Density = EoS['Density']\n",
+ "# The design matrix now as function of various polytrops\n",
+ "\n",
+ "Maxpolydegree = 30\n",
+ "X = np.zeros((len(Density),Maxpolydegree))\n",
+ "X[:,0] = 1.0\n",
+ "estimated_mse_sklearn = np.zeros(Maxpolydegree)\n",
+ "polynomial = np.zeros(Maxpolydegree)\n",
+ "k =5\n",
+ "kfold = KFold(n_splits = k)\n",
+ "\n",
+ "for polydegree in range(1, Maxpolydegree):\n",
+ " polynomial[polydegree] = polydegree\n",
+ " for degree in range(polydegree):\n",
+ " X[:,degree] = Density**(degree/3.0)\n",
+ " OLS = LinearRegression()\n",
+ "# loop over trials in order to estimate the expectation value of the MSE\n",
+ " estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)\n",
+ "#[:, np.newaxis]\n",
+ " estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)\n",
+ "\n",
+ "plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')\n",
+ "plt.xlabel('Polynomial degree')\n",
+ "plt.ylabel('log10[MSE]')\n",
+ "plt.legend()\n",
+ "plt.show()"
]
},
{
- "cell_type": "markdown",
- "metadata": {},
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
"source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}=\\begin{bmatrix}\n",
- "x_{00} & x_{01}\\\\\n",
- "x_{10} & x_{11}\\\\\n",
- "\\end{bmatrix}=\\begin{bmatrix}\n",
- "\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n",
- "\\end{bmatrix}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "If we then compute the expectation value"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}=\\begin{bmatrix}\n",
- "x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\\\\n",
- "x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which is just"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\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] \\\\\n",
- " \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "where we wrote $$\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]$$ to indicate that this the covariance of the vectors $\\boldsymbol{x}$ of the design/feature matrix $\\boldsymbol{X}$.\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import KFold\n",
+ "from sklearn.linear_model import Ridge\n",
+ "from sklearn.model_selection import cross_val_score\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
"\n",
- "It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$.\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "np.random.seed(3155)\n",
+ "# Generate the data.\n",
+ "n = 100\n",
+ "x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
+ "# Decide degree on polynomial to fit\n",
+ "poly = PolynomialFeatures(degree = 10)\n",
"\n",
- "\n",
- "## Linking with SVD"
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 500\n",
+ "lambdas = np.logspace(-3, 5, nlambdas)\n",
+ "# Initialize a KFold instance\n",
+ "k = 5\n",
+ "kfold = KFold(n_splits = k)\n",
+ "estimated_mse_sklearn = np.zeros(nlambdas)\n",
+ "i = 0\n",
+ "for lmb in lambdas:\n",
+ " ridge = Ridge(alpha = lmb)\n",
+ " estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)\n",
+ " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n",
+ " i += 1\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
]
}
],