diff --git a/doc/pub/week35/html/week35-bs.html b/doc/pub/week35/html/week35-bs.html index 63ce1bc4a..02fc39355 100644 --- a/doc/pub/week35/html/week35-bs.html +++ b/doc/pub/week35/html/week35-bs.html @@ -1,15 +1,15 @@
- + - + -@@ -230,7 +325,7 @@ MathJax.Hub.Config({
-
@@ -254,7 +349,7 @@ MathJax.Hub.Config({
@@ -148,28 +148,28 @@ MathJax.Hub.Config({
-
Video of Lecture.
@@ -177,7 +177,7 @@ MathJax.Hub.Config({
Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \).
@@ -201,7 +201,7 @@ Similarly, Mehta et a
@@ -224,7 +224,7 @@ A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\ver
@@ -254,7 +254,7 @@ Linear regression gives us a set of analytical equations for the parameters \( \
@@ -284,7 +284,7 @@ so-called General linear models
+
@@ -306,7 +306,7 @@ where \( \epsilon_i \) is the error in our approximation.
@@ -327,7 +327,7 @@ $$
@@ -379,7 +379,7 @@ The above design matrix is called a Generalizing the fitting procedure as a linear algebra problem
+
@@ -410,7 +410,7 @@ $$
@@ -441,7 +441,7 @@ The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\e
@@ -471,7 +471,7 @@ our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predict
In our introductory notes we looked at the so-called liquid drop model. Let us remind ourselves about what we did by looking at the code.
@@ -481,7 +481,7 @@ We restate the parts of the code we are most interested in.
-
@@ -607,7 +607,7 @@ since when taking the first derivative with respect to the unknown parameters \(
@@ -672,7 +672,7 @@ $$
@@ -720,7 +720,7 @@ allow for the usage of direct linear algebra methods such as LU decomposi
The following matrix and vector relation will be useful here and for the rest of the course. Vectors are always written as boldfaced lower case letters and
@@ -753,7 +753,7 @@ $$
@@ -789,7 +789,7 @@ Let us now return to our nuclear binding energies and simply code the above equa
It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to
@@ -797,17 +797,17 @@ write
-
Alternatively, you can use the least squares functionality in Numpy as
-
@@ -815,7 +815,7 @@ And finally we plot our fit with and compare with data
-
We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of Scikit-Learn in the introductory slides.
@@ -840,7 +840,7 @@ Since we are not using Scikit-Learn here we can define our own \( R2 \) f
-
@@ -848,253 +848,33 @@ and we would be using it as
-
We can easily add our MSE score as
-
and finally the relative error as
-
-Normally, the response (dependent or outcome) variable \( y_i \) is the
-outcome of a numerical experiment or another type of experiment and is
-thus only an approximation to the true value. It is then always
-accompanied by an error estimate, often limited to a statistical error
-estimate given by the standard deviation discussed earlier. In the
-discussion here we will treat \( y_i \) as our exact value for the
-response variable.
-
-
-Introducing the standard deviation \( \sigma_i \) for each measurement
-\( y_i \), we define now the \( \chi^2 \) function (omitting the \( 1/n \) term)
-as
-
-
-In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring
-
-We can rewrite
-
-If we then introduce the matrix
-
-The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write
-
-For a linear fit (a first-order polynomial) we don't need to invert a matrix!!
-Defining
-
-we obtain
-
-
-This approach (different linear and non-linear regression) suffers
-often from both being underdetermined and overdetermined in the
-unknown coefficients \( \beta_i \). A better approach is to use the
-Singular Value Decomposition (SVD) method discussed below. Or using
-Lasso and Ridge regression. See below.
-
-
-
Before we continue, let us introduce yet another example. We are going to fit the
@@ -1119,12 +899,12 @@ hyperparameter \( \lambda \), also to be explained below.
-
It is normal in essentially all Machine Learning studies to split the
@@ -1239,7 +1019,7 @@ but now splitting the data into a training set and a test set.
-
The Boston housing
@@ -1340,12 +1120,12 @@ The features/predictors are
-
-
-
-
@@ -1387,7 +1167,7 @@ We can then visualize the data
-
-
From the above coorelation plot we can see that MEDV is strongly correlated to LSTAT and RM. We see also that RAD and TAX are stronly correlated, but we don't include this in our features together to avoid multi-colinearity
@@ -1411,7 +1191,7 @@ From the above coorelation plot we can see that MEDV is strongly correlat
-
-
@@ -1439,22 +1219,22 @@ We split the data into training and test sets
-
Then we use the linear regression functionality from Scikit-Learn
-
-
@@ -1529,7 +1309,7 @@ visualization.
@@ -1554,7 +1334,7 @@ ensures that all features are exactly between \( 0 \) and \( 1 \). The
The Normalizer scales each data
@@ -1581,12 +1361,12 @@ techniques.
-
-Video of Lecture and handwritten notes
+Lasso and Ridge regression
+
+
+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
+
+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
+
+If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem
+
+A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change
+
+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
+
+
+Not all square matrices are diagonalizable. A matrix like the one discussed above
+
+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
+
+
+As an example, the above defective matrix can be decomposed as
+
+
+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.
+
+
+
+
+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
+
+The matrix to invert can be rewritten in terms of our SVD decomposition as
+
+
+This means that
+
+Going back to our OLS equation we have
+
+It is indeed the economy-sized SVD, note the summation runs up tp
+Here we have that
+Video of Lecture and handwritten notes
More material will be added here, see handwritten notes also.
+Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is
+our optimization problem is
+
+By minimizing the above equation with respect to the parameters
+\( \boldsymbol{\beta} \) we could then obtain an analytical expression for the
+parameters \( \boldsymbol{\beta} \). We can add a regularization parameter \( \lambda \) by
+defining a new cost function to be optimized, that is
+
+
+which leads to the Ridge regression minimization problem where we
+require that \( \vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t \), where \( t \) is
+a finite number larger than zero. By defining
+
+
+we have a new optimization equation
+
+Here we have defined the norm-1 as
+
+Using the matrix-vector expression for Ridge regression,
+
+
+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
+
+
+with \( \boldsymbol{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 \( \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
+
+We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as
+
+For Ridge regression this becomes
+
+
+with the vectors \( \boldsymbol{u}_j \) being the columns of \( \boldsymbol{U} \).
+
+Since \( \lambda \geq 0 \), it means that compared to OLS, we have
+
+
+Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the
+orthonormal basis \( \boldsymbol{U} \), it then shrinks the coordinates by
+\( \frac{\sigma_j^2}{\sigma_j^2+\lambda} \). Recall that the SVD has
+eigenvalues ordered in a descending way, that is \( \sigma_i \geq
+\sigma_{i+1} \).
+
+
+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
+
+
+In this case the standard OLS results in
+
+and
+
+
+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.
+
+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
+
+
+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} \).
+
+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
+
+The covariance takes values between zero and infinity and may thus
+lead to problems with loss of numerical precision for particularly
+large values. It is common to scale the covariance matrix by
+introducing instead the correlation matrix defined via the so-called
+correlation function
+
+
+The 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
+
+
+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
+
+
+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 \)
+
+
+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 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.
+
+
+
+
+
+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).
+
+
+
+
+
+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
+
+
+
+
+We expand this model to the Franke function discussed above.
+
+
+
+
+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
+
+To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \)
+
+If we then compute the expectation value
+
+It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \).
+
@@ -184,21 +262,21 @@ MathJax.Hub.Config({
-
Video of Lecture.
@@ -206,7 +284,7 @@ MathJax.Hub.Config({
Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \).
@@ -229,7 +307,7 @@ Similarly, Mehta et a
@@ -254,7 +332,7 @@ A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\ver
@@ -287,7 +365,7 @@ Linear regression gives us a set of analytical equations for the parameters \( \
@@ -316,7 +394,7 @@ so-called General linear models
+
@@ -337,7 +415,7 @@ where \( \epsilon_i \) is the error in our approximation.
@@ -357,7 +435,7 @@ $$
@@ -400,7 +478,7 @@ The above design matrix is called a Generalizing the fitting procedure as a linear algebra problem
+
@@ -432,7 +510,7 @@ $$
@@ -460,7 +538,7 @@ The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\e
@@ -489,7 +567,7 @@ our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predict
In our introductory notes we looked at the so-called liquid drop model. Let us remind ourselves about what we did by looking at the code.
@@ -499,7 +577,7 @@ We restate the parts of the code we are most interested in.
-
@@ -616,7 +694,7 @@ since when taking the first derivative with respect to the unknown parameters \(
@@ -672,7 +750,7 @@ $$
@@ -716,7 +794,7 @@ allow for the usage of direct linear algebra methods such as LU decomposi
The following matrix and vector relation will be useful here and for the rest of the course. Vectors are always written as boldfaced lower case letters and
@@ -740,7 +818,7 @@ $$
@@ -771,7 +849,7 @@ Let us now return to our nuclear binding energies and simply code the above equa
It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to
@@ -779,17 +857,17 @@ write
-
Alternatively, you can use the least squares functionality in Numpy as
-
@@ -797,7 +875,7 @@ And finally we plot our fit with and compare with data
-
We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of Scikit-Learn in the introductory slides.
@@ -821,7 +899,7 @@ Since we are not using Scikit-Learn here we can define our own \( R2 \) f
-
@@ -829,231 +907,32 @@ and we would be using it as
-
We can easily add our MSE score as
-
and finally the relative error as
-
-
-
-Normally, the response (dependent or outcome) variable \( y_i \) is the
-outcome of a numerical experiment or another type of experiment and is
-thus only an approximation to the true value. It is then always
-accompanied by an error estimate, often limited to a statistical error
-estimate given by the standard deviation discussed earlier. In the
-discussion here we will treat \( y_i \) as our exact value for the
-response variable.
-
-
-Introducing the standard deviation \( \sigma_i \) for each measurement
-\( y_i \), we define now the \( \chi^2 \) function (omitting the \( 1/n \) term)
-as
-
-$$
-\chi^2(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\frac{1}{\boldsymbol{\Sigma^2}}\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\},
-$$
-
-where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements.
-
-
-
-
-
-
-In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0,
-$$
-
-which results in
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0,
-$$
-
-or in a matrix-vector form as
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right).
-$$
-
-where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \boldsymbol{b} \) with elements \( b_i = y_i/\sigma_i \).
-
-
-
-
-We can rewrite
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right),
-$$
-
-as
-$$
-\boldsymbol{A}^T\boldsymbol{b} = \boldsymbol{A}^T\boldsymbol{A}\boldsymbol{\beta},
-$$
-
-and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution
-$$
-\boldsymbol{\beta} =\left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}\boldsymbol{A}^T\boldsymbol{b}.
-$$
-
-
-
-
-If we then introduce the matrix
-$$
-\boldsymbol{H} = \left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1},
-$$
-
-we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \boldsymbol{H} \) are \( h_{ij} \))
-$$
-\beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik}
-$$
-
-We state without proof the expression for the uncertainty in the parameters \( \beta_j \) as (we leave this as an exercise)
-$$
-\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2,
-$$
-
-resulting in
-$$
-\sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}!
-$$
-
-
-The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write
-$$
-y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i.
-$$
-
-By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0,
-$$
-
-and
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0.
-$$
-
-
-
-
-For a linear fit (a first-order polynomial) we don't need to invert a matrix!!
-Defining
-$$
-\gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2},
-$$
-
-
-$$
-\gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2},
-$$
-
-
-$$
-\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right),
-$$
-
-
-$$
-\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2},
-$$
-
-
-$$
-\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2},
-$$
-
-
-we obtain
-
-$$
-\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2},
-$$
-
-
-$$
-\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}.
-$$
-
-
-This approach (different linear and non-linear regression) suffers
-often from both being underdetermined and overdetermined in the
-unknown coefficients \( \beta_i \). A better approach is to use the
-Singular Value Decomposition (SVD) method discussed below. Or using
-Lasso and Ridge regression. See below.
-
-
-
-
Before we continue, let us introduce yet another example. We are going to fit the
@@ -1078,12 +957,12 @@ hyperparameter \( \lambda \), also to be explained below.
-
It is normal in essentially all Machine Learning studies to split the
@@ -1198,7 +1077,7 @@ but now splitting the data into a training set and a test set.
-
-
The Boston housing
@@ -1297,12 +1176,12 @@ The features/predictors are
-
-
-
-
@@ -1344,7 +1223,7 @@ We can then visualize the data
-
-
From the above coorelation plot we can see that MEDV is strongly correlated to LSTAT and RM. We see also that RAD and TAX are stronly correlated, but we don't include this in our features together to avoid multi-colinearity
@@ -1368,7 +1247,7 @@ From the above coorelation plot we can see that MEDV is strongly correlat
-
-
@@ -1396,22 +1275,22 @@ We split the data into training and test sets
-
Then we use the linear regression functionality from Scikit-Learn
-
-
@@ -1488,7 +1367,7 @@ visualization.
@@ -1515,7 +1394,7 @@ ensures that all features are exactly between \( 0 \) and \( 1 \). The
The Normalizer scales each data
@@ -1543,12 +1422,12 @@ techniques.
-
-Video of Lecture and handwritten notes
+Lasso and Ridge regression
+
+
+
+
+
+
+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
+$$
+\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{align}
+\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y},
+\label{_auto1}
+\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.
+
+
+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
+$$
+\boldsymbol{X} = \begin{bmatrix}
+1& -1 \\
+1& -1\\
+\end{bmatrix}
+$$
+
+is not diagonalizable, it is a so-called defective matrix. It is easy to see that the condition
+\( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) is not fulfilled.
+
+
+
+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
+
+$$
+\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.
+
+
+
+
+
+
+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
+$$
+\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}={\bf X}\hat{\beta}^{OLS}=\sum_{j=1}^p {\bf u}_j{\bf u}_j^T{\bf y}$$ and for Ridge we have
+
+$$ \tilde{y}^{Ridge}={\bf X}\hat{\beta}^{Ridge}=\sum_{j=1}^p {\bf u}_j\frac{\sigma_j^2}{\sigma_j^2+\lambda}{\bf u}_j^T{\bf y}$$ .
+
+
+It is indeed the economy-sized SVD, note the summation runs up tp $$p$$ only and not $$n$$.
+
+
+Here we have that $${\bf X} = {\bf U}{\bf \Sigma}{\bf V}^T$$, with $$\Sigma$$ being an $$ n\times p$$ matrix and $${\bf V}$$ being a $$ p\times p$$ matrix. We also have assumed here that $$ n > p$$.
+
+
+
+Video of Lecture and handwritten notes
More material will be added here, see handwritten notes also.
+
+
+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,
+
+$$
+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.
+
+
+
+
+
+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} \).
+
+
+
+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
+
+$$
+\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 \)
+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 \)
+
+$$
+\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} \)
+
+$$
+\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},
+$$
+
+
+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.
+
+
+
+
+
+
+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).
+
+
+
+
+
+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
+
+
+
+
+We expand this model to the Franke function discussed above.
+
+
+
+
+
+
+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
+$$
+\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} \).
+
+
+
@@ -189,21 +267,21 @@ MathJax.Hub.Config({
-
Video of Lecture.
@@ -211,7 +289,7 @@ MathJax.Hub.Config({
Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \).
@@ -234,7 +312,7 @@ Similarly, Mehta et a
@@ -259,7 +337,7 @@ A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\ver
@@ -292,7 +370,7 @@ Linear regression gives us a set of analytical equations for the parameters \( \
@@ -321,7 +399,7 @@ so-called General linear models
+
@@ -342,7 +420,7 @@ where \( \epsilon_i \) is the error in our approximation.
@@ -362,7 +440,7 @@ $$
@@ -405,7 +483,7 @@ The above design matrix is called a Generalizing the fitting procedure as a linear algebra problem
+
@@ -437,7 +515,7 @@ $$
@@ -465,7 +543,7 @@ The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\e
@@ -494,7 +572,7 @@ our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predict
In our introductory notes we looked at the so-called liquid drop model. Let us remind ourselves about what we did by looking at the code.
@@ -504,7 +582,7 @@ We restate the parts of the code we are most interested in.
-
@@ -621,7 +699,7 @@ since when taking the first derivative with respect to the unknown parameters \(
@@ -677,7 +755,7 @@ $$
@@ -721,7 +799,7 @@ allow for the usage of direct linear algebra methods such as LU decomposi
The following matrix and vector relation will be useful here and for the rest of the course. Vectors are always written as boldfaced lower case letters and
@@ -745,7 +823,7 @@ $$
@@ -776,7 +854,7 @@ Let us now return to our nuclear binding energies and simply code the above equa
It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to
@@ -784,17 +862,17 @@ write
-
Alternatively, you can use the least squares functionality in Numpy as
-
@@ -802,11 +880,11 @@ And finally we plot our fit with and compare with data
-
We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of Scikit-Learn in the introductory slides.
@@ -826,7 +904,7 @@ Since we are not using Scikit-Learn here we can define our own \( R2 \) f
-
@@ -834,231 +912,32 @@ and we would be using it as
-
We can easily add our MSE score as
-
and finally the relative error as
-
-
-
-Normally, the response (dependent or outcome) variable \( y_i \) is the
-outcome of a numerical experiment or another type of experiment and is
-thus only an approximation to the true value. It is then always
-accompanied by an error estimate, often limited to a statistical error
-estimate given by the standard deviation discussed earlier. In the
-discussion here we will treat \( y_i \) as our exact value for the
-response variable.
-
-
-Introducing the standard deviation \( \sigma_i \) for each measurement
-\( y_i \), we define now the \( \chi^2 \) function (omitting the \( 1/n \) term)
-as
-
-$$
-\chi^2(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\frac{1}{\boldsymbol{\Sigma^2}}\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\},
-$$
-
-where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements.
-
-
-
-
-
-
-In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0,
-$$
-
-which results in
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0,
-$$
-
-or in a matrix-vector form as
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right).
-$$
-
-where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \boldsymbol{b} \) with elements \( b_i = y_i/\sigma_i \).
-
-
-
-
-We can rewrite
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right),
-$$
-
-as
-$$
-\boldsymbol{A}^T\boldsymbol{b} = \boldsymbol{A}^T\boldsymbol{A}\boldsymbol{\beta},
-$$
-
-and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution
-$$
-\boldsymbol{\beta} =\left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}\boldsymbol{A}^T\boldsymbol{b}.
-$$
-
-
-
-
-If we then introduce the matrix
-$$
-\boldsymbol{H} = \left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1},
-$$
-
-we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \boldsymbol{H} \) are \( h_{ij} \))
-$$
-\beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik}
-$$
-
-We state without proof the expression for the uncertainty in the parameters \( \beta_j \) as (we leave this as an exercise)
-$$
-\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2,
-$$
-
-resulting in
-$$
-\sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}!
-$$
-
-
-The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write
-$$
-y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i.
-$$
-
-By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0,
-$$
-
-and
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0.
-$$
-
-
-
-
-For a linear fit (a first-order polynomial) we don't need to invert a matrix!!
-Defining
-$$
-\gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2},
-$$
-
-
-$$
-\gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2},
-$$
-
-
-$$
-\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right),
-$$
-
-
-$$
-\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2},
-$$
-
-
-$$
-\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2},
-$$
-
-
-we obtain
-
-$$
-\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2},
-$$
-
-
-$$
-\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}.
-$$
-
-
-This approach (different linear and non-linear regression) suffers
-often from both being underdetermined and overdetermined in the
-unknown coefficients \( \beta_i \). A better approach is to use the
-Singular Value Decomposition (SVD) method discussed below. Or using
-Lasso and Ridge regression. See below.
-
-
-
-
Before we continue, let us introduce yet another example. We are going to fit the
@@ -1083,12 +962,12 @@ hyperparameter \( \lambda \), also to be explained below.
-
It is normal in essentially all Machine Learning studies to split the
@@ -1203,7 +1082,7 @@ but now splitting the data into a training set and a test set.
-
-
The Boston housing
@@ -1302,12 +1181,12 @@ The features/predictors are
-
-Why Linear Regression (aka Ordinary Least Squares and family)
+Why Linear Regression (aka Ordinary Least Squares and family), repeat from last week
Regression analysis, overarching aims
+Regression analysis, overarching aims
Regression analysis, overarching aims II
+Regression analysis, overarching aims II
Examples
+Examples
General linear models
Rewriting the fitting procedure as a linear algebra problem
+Rewriting the fitting procedure as a linear algebra problem
Rewriting the fitting procedure as a linear algebra problem, more details
+Rewriting the fitting procedure as a linear algebra problem, more details
Generalizing the fitting procedure as a linear algebra problem
Generalizing the fitting procedure as a linear algebra problem
+Generalizing the fitting procedure as a linear algebra problem
Optimizing our parameters
+Optimizing our parameters
Our model for the nuclear binding energies
+Our model for the nuclear binding energies
# Common imports
+
# Common imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
@@ -509,7 +509,7 @@ DATA_ID = "DataFiles/"
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
+ plt.savefig(image_path(fig_id) + ".png", format='png')
infile = open(data_path("MassEval2016.dat"),'r')
@@ -519,7 +519,7 @@ Masses = pd.read_fwf(infile, usecols=(2,
Optimizing our parameters, more details
+Optimizing our parameters, more details
Interpretations and optimizing our parameters
+Interpretations and optimizing our parameters
Interpretations and optimizing our parameters
+Interpretations and optimizing our parameters
Some useful matrix and vector expressions
+Some useful matrix and vector expressions
Interpretations and optimizing our parameters
+Interpretations and optimizing our parameters
Own code for Ordinary Least Squares
+Own code for Ordinary Least Squares
# matrix inversion to find beta
+
# matrix inversion to find beta
beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
# and then make the prediction
-ytilde = X @ beta
+ytilde = X @ beta
fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
+
fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
ytildenp = np.dot(fit,X.T)
Masses['Eapprox'] = ytilde
+
Masses['Eapprox'] = ytilde
# Generate a plot comparing the experimental with the fitted values values.
fig, ax = plt.subplots()
ax.set_xlabel(r'$A = N + Z$')
@@ -832,7 +832,7 @@ plt.show()
Adding error analysis and training set up
+Adding error analysis and training set up
def R2(y_data, y_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)
print(R2(Energies,ytilde))
+
print(R2(Energies,ytilde))
def MSE(y_data,y_model):
+
def MSE(y_data,y_model):
n = np.size(y_model)
return np.sum((y_data-y_model)**2)/n
-print(MSE(Energies,ytilde))
+print(MSE(Energies,ytilde))
def RelativeError(y_data,y_model):
+
def RelativeError(y_data,y_model):
return abs((y_data-y_model)/y_data)
-print(RelativeError(Energies, ytilde))
+print(RelativeError(Energies, ytilde))
The \( \chi^2 \) function
-
-$$
-\chi^2(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\frac{1}{\boldsymbol{\Sigma^2}}\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\},
-$$
-
-
-where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements.
-
-
-The \( \chi^2 \) function
-
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0,
-$$
-
-
-which results in
-
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0,
-$$
-
-
-or in a matrix-vector form as
-
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right).
-$$
-
-
-where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \boldsymbol{b} \) with elements \( b_i = y_i/\sigma_i \).
-The \( \chi^2 \) function
-
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right),
-$$
-
-
-as
-
-$$
-\boldsymbol{A}^T\boldsymbol{b} = \boldsymbol{A}^T\boldsymbol{A}\boldsymbol{\beta},
-$$
-
-
-and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution
-
-$$
-\boldsymbol{\beta} =\left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}\boldsymbol{A}^T\boldsymbol{b}.
-$$
-
-The \( \chi^2 \) function
-
-$$
-\boldsymbol{H} = \left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1},
-$$
-
-
-we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \boldsymbol{H} \) are \( h_{ij} \))
-
-$$
-\beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik}
-$$
-
-
-We state without proof the expression for the uncertainty in the parameters \( \beta_j \) as (we leave this as an exercise)
-
-$$
-\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2,
-$$
-
-
-resulting in
-
-$$
-\sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}!
-$$
-
-The \( \chi^2 \) function
-
-$$
-y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i.
-$$
-
-
-By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by
-
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0,
-$$
-
-
-and
-
-$$
-\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0.
-$$
-
-The \( \chi^2 \) function
-
-$$
-\gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2},
-$$
-
-
-
-$$
-\gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2},
-$$
-
-
-
-$$
-\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right),
-$$
-
-
-
-$$
-\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2},
-$$
-
-
-
-$$
-\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2},
-$$
-
-
-
-$$
-\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2},
-$$
-
-
-
-$$
-\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}.
-$$
-
-
-Fitting an Equation of State for Dense Nuclear Matter
+Fitting an Equation of State for Dense Nuclear Matter
The code
+The code
# Common imports
+
# Common imports
import os
import numpy as np
import pandas as pd
@@ -1154,7 +934,7 @@ DATA_ID = "DataFiles/"
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
+ plt.savefig(image_path(fig_id) + ".png", format='png')
infile = open(data_path("EoS.csv"),'r')
@@ -1177,12 +957,12 @@ clf = skl.LinearRegression().fit(X, Energies)
ytilde = clf.predict(X)
EoS['Eols'] = ytilde
# The mean squared error
-print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde))
+print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde))
# Explained variance score: 1 is perfect prediction
-print('Variance score: %.2f' % r2_score(Energies, ytilde))
+print('Variance score: %.2f' % r2_score(Energies, ytilde))
# Mean absolute error
-print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))
-print(clf.coef_, clf.intercept_)
+print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))
+print(clf.coef_, clf.intercept_)
# The Ridge regression with a hyperparameter lambda = 0.1
_lambda = 0.1
@@ -1190,12 +970,12 @@ clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies)
yridge = clf_ridge.predict(X)
EoS['Eridge'] = yridge
# The mean squared error
-print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge))
+print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge))
# Explained variance score: 1 is perfect prediction
-print('Variance score: %.2f' % r2_score(Energies, yridge))
+print('Variance score: %.2f' % r2_score(Energies, yridge))
# Mean absolute error
-print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))
-print(clf_ridge.coef_, clf_ridge.intercept_)
+print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))
+print(clf_ridge.coef_, clf_ridge.intercept_)
fig, ax = plt.subplots()
ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$')
@@ -1222,7 +1002,7 @@ below.
Splitting our Data in Training and Test data
+Splitting our Data in Training and Test data
import os
+
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
@@ -1265,7 +1045,7 @@ DATA_ID = "DataFiles/"
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
+ plt.savefig(image_path(fig_id) + ".png", format='png')
def R2(y_data, y_model):
return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
@@ -1293,22 +1073,22 @@ X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=# matrix inversion to find beta
beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)
# and then make the prediction
-ytilde = X_train @ beta
-print("Training R2")
-print(R2(y_train,ytilde))
-print("Training MSE")
-print(MSE(y_train,ytilde))
-ypredict = X_test @ beta
-print("Test R2")
-print(R2(y_test,ypredict))
-print("Test MSE")
-print(MSE(y_test,ypredict))
+ytilde = X_train @ beta
+print("Training R2")
+print(R2(y_train,ytilde))
+print("Training MSE")
+print(MSE(y_train,ytilde))
+ypredict = X_test @ beta
+print("Test R2")
+print(R2(y_test,ypredict))
+print("Test MSE")
+print(MSE(y_test,ypredict))
The Boston housing data example
+The Boston housing data example
Housing data, the code
+Housing data, the code
We start by importing the libraries
import numpy as np
+
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
@@ -1357,7 +1137,7 @@ and load the Boston Housing DataSet from Scikit-Learn
from sklearn.datasets import load_boston
+
from sklearn.datasets import load_boston
boston_dataset = load_boston()
@@ -1370,7 +1150,7 @@ Then we invoke Pandas
boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)
+
boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)
boston.head()
boston['MEDV'] = boston_dataset.target
# check for missing values in all the columns
+
# check for missing values in all the columns
boston.isnull().sum()
# set the size of the figure
+
# set the size of the figure
sns.set(rc={'figure.figsize':(11.7,8.27)})
# plot a histogram showing the distribution of the target values
@@ -1399,11 +1179,11 @@ It is now useful to look at the correlation matrix
# compute the pair wise correlation for all columns
+
# compute the pair wise correlation for all columns
correlation_matrix = boston.corr().round(2)
# use the heatmap function from seaborn to plot the correlation matrix
# annot = True to print the values inside the square
-sns.heatmap(data=correlation_matrix, annot=True)
+sns.heatmap(data=correlation_matrix, annot=True)
plt.figure(figsize=(20, 5))
+
plt.figure(figsize=(20, 5))
features = ['LSTAT', 'RM']
target = boston['MEDV']
@@ -1430,7 +1210,7 @@ Now we start training our model
X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])
+
X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])
Y = boston['MEDV']
from sklearn.model_selection import train_test_split
+
from sklearn.model_selection import train_test_split
# splits the training and test data set in 80% : 20%
# assign random_state to any value.This ensures consistency.
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=5)
-print(X_train.shape)
-print(X_test.shape)
-print(Y_train.shape)
-print(Y_test.shape)
+print(X_train.shape)
+print(X_test.shape)
+print(Y_train.shape)
+print(Y_test.shape)
from sklearn.linear_model import LinearRegression
+
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
lin_model = LinearRegression()
@@ -1466,11 +1246,11 @@ y_train_predict = lin_model.predict(X_train)
rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict)))
r2 = r2_score(Y_train, y_train_predict)
-print("The model performance for training set")
-print("--------------------------------------")
-print('RMSE is {}'.format(rmse))
-print('R2 score is {}'.format(r2))
-print("\n")
+print("The model performance for training set")
+print("--------------------------------------")
+print('RMSE is {}'.format(rmse))
+print('R2 score is {}'.format(r2))
+print("\n")
# model evaluation for testing set
@@ -1481,15 +1261,15 @@ rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict)))
# r-squared score of the model
r2 = r2_score(Y_test, y_test_predict)
-print("The model performance for testing set")
-print("--------------------------------------")
-print('RMSE is {}'.format(rmse))
-print('R2 score is {}'.format(r2))
+print("The model performance for testing set")
+print("--------------------------------------")
+print('RMSE is {}'.format(rmse))
+print('R2 score is {}'.format(r2))
# plotting the y_test vs y_pred
+
# plotting the y_test vs y_pred
# ideally should have been a straight line
plt.scatter(Y_test, y_test_predict)
plt.show()
@@ -1498,7 +1278,7 @@ plt.show()
Reducing the number of degrees of freedom, overarching view
+Reducing the number of degrees of freedom, overarching view
Preprocessing our data
+Preprocessing our data
More preprocessing
+More preprocessing
Simple preprocessing examples, Franke function and regression
+Simple preprocessing examples, Franke function and regression
# Common imports
+
# Common imports
import os
import numpy as np
import pandas as pd
@@ -1617,7 +1397,7 @@ DATA_ID = "DataFiles/"
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
+ plt.savefig(image_path(fig_id) + ".png", format='png')
def FrankeFunction(x,y):
@@ -1659,40 +1439,1076 @@ X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=# The mean squared error and R2 score
-print("MSE before scaling: {:.2f}".format(mean_squared_error(clf.predict(X_test), y_test)))
-print("R2 score before scaling {:.2f}".format(clf.score(X_test,y_test)))
+print("MSE before scaling: {:.2f}".format(mean_squared_error(clf.predict(X_test), y_test)))
+print("R2 score before scaling {:.2f}".format(clf.score(X_test,y_test)))
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
-print("Feature min values before scaling:\n {}".format(X_train.min(axis=0)))
-print("Feature max values before scaling:\n {}".format(X_train.max(axis=0)))
+print("Feature min values before scaling:\n {}".format(X_train.min(axis=0)))
+print("Feature max values before scaling:\n {}".format(X_train.max(axis=0)))
-print("Feature min values after scaling:\n {}".format(X_train_scaled.min(axis=0)))
-print("Feature max values after scaling:\n {}".format(X_train_scaled.max(axis=0)))
+print("Feature min values after scaling:\n {}".format(X_train_scaled.min(axis=0)))
+print("Feature max values after scaling:\n {}".format(X_train_scaled.max(axis=0)))
clf = skl.LinearRegression().fit(X_train_scaled, y_train)
-print("MSE after scaling: {:.2f}".format(mean_squared_error(clf.predict(X_test_scaled), y_test)))
-print("R2 score for scaled data: {:.2f}".format(clf.score(X_test_scaled,y_test)))
+print("MSE after scaling: {:.2f}".format(mean_squared_error(clf.predict(X_test_scaled), y_test)))
+print("R2 score for scaled data: {:.2f}".format(clf.score(X_test_scaled,y_test)))
Friday August 28
+Friday September 3
The singular value decomposition
+
+Linear Regression Problems
+
+
+$$
+\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*}
+$$
+
+
+
+$$
+\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.
+Fixing the singularity
+
+
+$$
+\begin{align}
+\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y},
+\tag{1}
+\end{align}
+$$
+
+
+has linearly dependent column vectors, we will not be able to compute the inverse
+of \( \boldsymbol{X}^T\boldsymbol{X} \) and we cannot find the parameters (estimators) \( \beta_i \).
+The estimators are only well-defined if \( (\boldsymbol{X}^{T}\boldsymbol{X})^{-1} \) exits.
+This is more likely to happen when the matrix \( \boldsymbol{X} \) is high-dimensional. In this case it is likely to encounter a situation where
+the regression parameters \( \beta_i \) cannot be estimated.
+
+
+$$
+\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
+
+
+$$
+(\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} \).
+
+
+$$
+\boldsymbol{X} = \begin{bmatrix}
+1& -1 \\
+1& -1\\
+\end{bmatrix}
+$$
+
+
+is not diagonalizable, it is a so-called defective matrix. It is easy to see that the condition
+\( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) is not fulfilled.
+The SVD, a Fantastic Algorithm
+
+
+$$
+\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T
+$$
+
+
+
+$$
+\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,
+$$
+
+
+Economy-size SVD
+
+Codes for 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)))
+ 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)
+
Mathematical Properties
+
+
+$$
+\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
+$$
+
+
+
+$$
+\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.
+
+
+$$
+(\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.
+
+
+$$
+\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}={\bf X}\hat{\beta}^{OLS}=\sum_{j=1}^p {\bf u}_j{\bf u}_j^T{\bf y}$$
+
and for Ridge we have
+
+
+$$ \tilde{y}^{Ridge}={\bf X}\hat{\beta}^{Ridge}=\sum_{j=1}^p {\bf u}_j\frac{\sigma_j^2}{\sigma_j^2+\lambda}{\bf u}_j^T{\bf y}$$
+
.
+
+
+$$p$$
+
only and not
+$$n$$
+
.
+
+
+$${\bf X} = {\bf U}{\bf \Sigma}{\bf V}^T$$
+
, with
+$$\Sigma$$
+
being an
+$$ n\times p$$
+
matrix and
+$${\bf V}$$
+
being a
+$$ p\times p$$
+
matrix. We also have assumed here that
+$$ n > p$$
+
.
+Friday September 12
+
+Ridge and LASSO Regression
+
+
+$$
+{\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}.
+$$
+
+
+
+$$
+{\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
+$$
+
+
+
+$$
+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,
+$$
+
+
+
+$$
+{\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.
+
+
+$$
+\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert.
+$$
+
+More on 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},
+$$
+
+
+
+$$
+\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
+$$
+
+
+
+$$
+\sum_{i=0}^{p-1} \beta_i^2 \leq t,
+$$
+
+
+
+$$
+(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}.
+$$
+
+
+
+$$
+\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}
+$$
+
+
+
+$$
+\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},
+$$
+
+
+Interpreting the Ridge results
+
+
+$$
+\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1.
+$$
+
+
+More interpretations
+
+
+$$
+\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}.
+$$
+
+
+
+$$
+\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\boldsymbol{y},
+$$
+
+
+
+$$
+\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}},
+$$
+
+
+A better understanding of regularization
+
+Decomposing the OLS and Ridge expressions
+
+
+$$
+\boldsymbol{X} = \boldsymbol{U\Sigma V^T},
+$$
+
+
+Introducing the Covariance and Correlation functions
+
+
+$$
+\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}.
+$$
+
+
+
+$$
+\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}.
+$$
+
+
+
+$$
+\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\
+ \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\
+ \end{bmatrix},
+$$
+
+
+Correlation Function and Design/Feature Matrix
+
+
+$$
+\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}.
+$$
+
+
+
+$$
+\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},
+$$
+
+Covariance Matrix Examples
+
+
+$$
+\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},
+$$
+
+
+# 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)
+
Correlation Matrix
+
+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)
+
Correlation Matrix with Pandas
+
+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)
+
Correlation Matrix with Pandas and the Franke function
+
+# 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)
+
Rewriting the Covariance and/or Correlation Matrix
+
+
+$$
+\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}].
+$$
+
+
+
+$$
+\boldsymbol{X}=\begin{bmatrix}
+x_{00} & x_{01}\\
+x_{10} & x_{11}\\
+\end{bmatrix}=\begin{bmatrix}
+\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\
+\end{bmatrix}.
+$$
+
+
+
+$$
+\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} \).
+
+Linking with SVD
+Week 35: Linear Regression and Review of Statistical Analysis and Probability Theory
Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression
Sep 16, 2020
Aug 31, 2021
-Plans for week 35, August 24-28
+Plans for week 35, August 24-28
-
-Thursday August 27
+Thursday August 27
-Why Linear Regression (aka Ordinary Least Squares and family)
+Why Linear Regression (aka Ordinary Least Squares and family), repeat from last week
-Regression analysis, overarching aims
+Regression analysis, overarching aims
-Regression analysis, overarching aims II
+Regression analysis, overarching aims II
-Examples
+Examples
General linear models
-Rewriting the fitting procedure as a linear algebra problem
+Rewriting the fitting procedure as a linear algebra problem
-Rewriting the fitting procedure as a linear algebra problem, more details
+Rewriting the fitting procedure as a linear algebra problem, more details
Generalizing the fitting procedure as a linear algebra problem
-Generalizing the fitting procedure as a linear algebra problem
+Generalizing the fitting procedure as a linear algebra problem
-Optimizing our parameters
+Optimizing our parameters
-Our model for the nuclear binding energies
+Our model for the nuclear binding energies
# Common imports
+
# Common imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
@@ -527,7 +605,7 @@ DATA_ID = "DataFiles/"
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
+ plt.savefig(image_path(fig_id) + ".png", format='png')
infile = open(data_path("MassEval2016.dat"),'r')
@@ -537,7 +615,7 @@ Masses = pd.read_fwf(infile, usecols=(2,
-Optimizing our parameters, more details
+Optimizing our parameters, more details
-Interpretations and optimizing our parameters
+Interpretations and optimizing our parameters
-Interpretations and optimizing our parameters
+Interpretations and optimizing our parameters
-Some useful matrix and vector expressions
+Some useful matrix and vector expressions
-Interpretations and optimizing our parameters
+Interpretations and optimizing our parameters
-Own code for Ordinary Least Squares
+Own code for Ordinary Least Squares
# matrix inversion to find beta
+
# matrix inversion to find beta
beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
# and then make the prediction
-ytilde = X @ beta
+ytilde = X @ beta
fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
+
fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
ytildenp = np.dot(fit,X.T)
Masses['Eapprox'] = ytilde
+
Masses['Eapprox'] = ytilde
# Generate a plot comparing the experimental with the fitted values values.
fig, ax = plt.subplots()
ax.set_xlabel(r'$A = N + Z$')
@@ -813,7 +891,7 @@ plt.show()
-Adding error analysis and training set up
+Adding error analysis and training set up
def R2(y_data, y_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)
print(R2(Energies,ytilde))
+
print(R2(Energies,ytilde))
def MSE(y_data,y_model):
+
def MSE(y_data,y_model):
n = np.size(y_model)
return np.sum((y_data-y_model)**2)/n
-print(MSE(Energies,ytilde))
+print(MSE(Energies,ytilde))
def RelativeError(y_data,y_model):
+
def RelativeError(y_data,y_model):
return abs((y_data-y_model)/y_data)
-print(RelativeError(Energies, ytilde))
+print(RelativeError(Energies, ytilde))
-The \( \chi^2 \) function
-
-
-The \( \chi^2 \) function
-
-
-The \( \chi^2 \) function
-
-
-The \( \chi^2 \) function
-
-
-The \( \chi^2 \) function
-
-
-The \( \chi^2 \) function
-
-
-Fitting an Equation of State for Dense Nuclear Matter
+Fitting an Equation of State for Dense Nuclear Matter
-The code
+The code
# Common imports
+
# Common imports
import os
import numpy as np
import pandas as pd
@@ -1113,7 +992,7 @@ DATA_ID = "DataFiles/"
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
+ plt.savefig(image_path(fig_id) + ".png", format='png')
infile = open(data_path("EoS.csv"),'r')
@@ -1136,12 +1015,12 @@ clf = skl.LinearRegression().fit(X, Energies)
ytilde = clf.predict(X)
EoS['Eols'] = ytilde
# The mean squared error
-print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde))
+print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde))
# Explained variance score: 1 is perfect prediction
-print('Variance score: %.2f' % r2_score(Energies, ytilde))
+print('Variance score: %.2f' % r2_score(Energies, ytilde))
# Mean absolute error
-print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))
-print(clf.coef_, clf.intercept_)
+print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))
+print(clf.coef_, clf.intercept_)
# The Ridge regression with a hyperparameter lambda = 0.1
_lambda = 0.1
@@ -1149,12 +1028,12 @@ clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies)
yridge = clf_ridge.predict(X)
EoS['Eridge'] = yridge
# The mean squared error
-print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge))
+print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge))
# Explained variance score: 1 is perfect prediction
-print('Variance score: %.2f' % r2_score(Energies, yridge))
+print('Variance score: %.2f' % r2_score(Energies, yridge))
# Mean absolute error
-print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))
-print(clf_ridge.coef_, clf_ridge.intercept_)
+print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))
+print(clf_ridge.coef_, clf_ridge.intercept_)
fig, ax = plt.subplots()
ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$')
@@ -1181,7 +1060,7 @@ below.
-Splitting our Data in Training and Test data
+Splitting our Data in Training and Test data
import os
+
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
@@ -1224,7 +1103,7 @@ DATA_ID = "DataFiles/"
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
+ plt.savefig(image_path(fig_id) + ".png", format='png')
def R2(y_data, y_model):
return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
@@ -1252,21 +1131,21 @@ X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=# matrix inversion to find beta
beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)
# and then make the prediction
-ytilde = X_train @ beta
-print("Training R2")
-print(R2(y_train,ytilde))
-print("Training MSE")
-print(MSE(y_train,ytilde))
-ypredict = X_test @ beta
-print("Test R2")
-print(R2(y_test,ypredict))
-print("Test MSE")
-print(MSE(y_test,ypredict))
+ytilde = X_train @ beta
+print("Training R2")
+print(R2(y_train,ytilde))
+print("Training MSE")
+print(MSE(y_train,ytilde))
+ypredict = X_test @ beta
+print("Test R2")
+print(R2(y_test,ypredict))
+print("Test MSE")
+print(MSE(y_test,ypredict))
The Boston housing data example
+The Boston housing data example
-Housing data, the code
+Housing data, the code
We start by importing the libraries
import numpy as np
+
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
@@ -1314,7 +1193,7 @@ and load the Boston Housing DataSet from Scikit-Learn
from sklearn.datasets import load_boston
+
from sklearn.datasets import load_boston
boston_dataset = load_boston()
@@ -1327,7 +1206,7 @@ Then we invoke Pandas
boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)
+
boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)
boston.head()
boston['MEDV'] = boston_dataset.target
# check for missing values in all the columns
+
# check for missing values in all the columns
boston.isnull().sum()
# set the size of the figure
+
# set the size of the figure
sns.set(rc={'figure.figsize':(11.7,8.27)})
# plot a histogram showing the distribution of the target values
@@ -1356,11 +1235,11 @@ It is now useful to look at the correlation matrix
# compute the pair wise correlation for all columns
+
# compute the pair wise correlation for all columns
correlation_matrix = boston.corr().round(2)
# use the heatmap function from seaborn to plot the correlation matrix
# annot = True to print the values inside the square
-sns.heatmap(data=correlation_matrix, annot=True)
+sns.heatmap(data=correlation_matrix, annot=True)
plt.figure(figsize=(20, 5))
+
plt.figure(figsize=(20, 5))
features = ['LSTAT', 'RM']
target = boston['MEDV']
@@ -1387,7 +1266,7 @@ Now we start training our model
X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])
+
X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])
Y = boston['MEDV']
from sklearn.model_selection import train_test_split
+
from sklearn.model_selection import train_test_split
# splits the training and test data set in 80% : 20%
# assign random_state to any value.This ensures consistency.
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=5)
-print(X_train.shape)
-print(X_test.shape)
-print(Y_train.shape)
-print(Y_test.shape)
+print(X_train.shape)
+print(X_test.shape)
+print(Y_train.shape)
+print(Y_test.shape)
from sklearn.linear_model import LinearRegression
+
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
lin_model = LinearRegression()
@@ -1423,11 +1302,11 @@ y_train_predict = lin_model.predict(X_train)
rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict)))
r2 = r2_score(Y_train, y_train_predict)
-print("The model performance for training set")
-print("--------------------------------------")
-print('RMSE is {}'.format(rmse))
-print('R2 score is {}'.format(r2))
-print("\n")
+print("The model performance for training set")
+print("--------------------------------------")
+print('RMSE is {}'.format(rmse))
+print('R2 score is {}'.format(r2))
+print("\n")
# model evaluation for testing set
@@ -1438,15 +1317,15 @@ rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict)))
# r-squared score of the model
r2 = r2_score(Y_test, y_test_predict)
-print("The model performance for testing set")
-print("--------------------------------------")
-print('RMSE is {}'.format(rmse))
-print('R2 score is {}'.format(r2))
+print("The model performance for testing set")
+print("--------------------------------------")
+print('RMSE is {}'.format(rmse))
+print('R2 score is {}'.format(r2))
# plotting the y_test vs y_pred
+
# plotting the y_test vs y_pred
# ideally should have been a straight line
plt.scatter(Y_test, y_test_predict)
plt.show()
@@ -1454,7 +1333,7 @@ plt.show()
-Reducing the number of degrees of freedom, overarching view
+Reducing the number of degrees of freedom, overarching view
-Preprocessing our data
+Preprocessing our data
-More preprocessing
+More preprocessing
-Simple preprocessing examples, Franke function and regression
+Simple preprocessing examples, Franke function and regression
# Common imports
+
# Common imports
import os
import numpy as np
import pandas as pd
@@ -1579,7 +1458,7 @@ DATA_ID = "DataFiles/"
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
+ plt.savefig(image_path(fig_id) + ".png", format='png')
def FrankeFunction(x,y):
@@ -1621,44 +1500,960 @@ X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=# The mean squared error and R2 score
-print("MSE before scaling: {:.2f}".format(mean_squared_error(clf.predict(X_test), y_test)))
-print("R2 score before scaling {:.2f}".format(clf.score(X_test,y_test)))
+print("MSE before scaling: {:.2f}".format(mean_squared_error(clf.predict(X_test), y_test)))
+print("R2 score before scaling {:.2f}".format(clf.score(X_test,y_test)))
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
-print("Feature min values before scaling:\n {}".format(X_train.min(axis=0)))
-print("Feature max values before scaling:\n {}".format(X_train.max(axis=0)))
+print("Feature min values before scaling:\n {}".format(X_train.min(axis=0)))
+print("Feature max values before scaling:\n {}".format(X_train.max(axis=0)))
-print("Feature min values after scaling:\n {}".format(X_train_scaled.min(axis=0)))
-print("Feature max values after scaling:\n {}".format(X_train_scaled.max(axis=0)))
+print("Feature min values after scaling:\n {}".format(X_train_scaled.min(axis=0)))
+print("Feature max values after scaling:\n {}".format(X_train_scaled.max(axis=0)))
clf = skl.LinearRegression().fit(X_train_scaled, y_train)
-print("MSE after scaling: {:.2f}".format(mean_squared_error(clf.predict(X_test_scaled), y_test)))
-print("R2 score for scaled data: {:.2f}".format(clf.score(X_test_scaled,y_test)))
+print("MSE after scaling: {:.2f}".format(mean_squared_error(clf.predict(X_test_scaled), y_test)))
+print("R2 score for scaled data: {:.2f}".format(clf.score(X_test_scaled,y_test)))
-Friday August 28
+Friday September 3
+
+The singular value decomposition
+
+
+
+Linear Regression Problems
+
+
+
+Fixing the singularity
+
+
+
+Basic math of the SVD
+
+
+
+The SVD, a Fantastic Algorithm
+
+
+
+Economy-size SVD
+
+
+
+Codes for 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)))
+ 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)
+
+
+Mathematical Properties
+
+
+
+Friday September 12
+
+
+
+Ridge and LASSO Regression
+
+
+
+More on Ridge Regression
+
+
+
+Interpreting the Ridge results
+
+
+
+More interpretations
+
+A better understanding of regularization
+
+
+
+Decomposing the OLS and Ridge expressions
+
+
+
+Introducing the Covariance and Correlation functions
+
+
+
+Correlation Function and Design/Feature Matrix
+
+
+
+Covariance Matrix Examples
+
+# 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)
+
+
+Correlation Matrix
+
+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)
+
+
+Correlation Matrix with Pandas
+
+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)
+
+
+Correlation Matrix with Pandas and the Franke function
+
+# 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)
+
+
+Rewriting the Covariance and/or Correlation Matrix
+
+
+
+Linking with SVD
+
Week 35: Linear Regression and Review of Statistical Analysis and Probability Theory
Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression
Sep 16, 2020
Aug 31, 2021
-Plans for week 35, August 24-28
+Plans for week 35, August 24-28
-
-Thursday August 27
+Thursday August 27
-Why Linear Regression (aka Ordinary Least Squares and family)
+Why Linear Regression (aka Ordinary Least Squares and family), repeat from last week
-Regression analysis, overarching aims
+Regression analysis, overarching aims
-Regression analysis, overarching aims II
+Regression analysis, overarching aims II
-Examples
+Examples
General linear models
-Rewriting the fitting procedure as a linear algebra problem
+Rewriting the fitting procedure as a linear algebra problem
-Rewriting the fitting procedure as a linear algebra problem, more details
+Rewriting the fitting procedure as a linear algebra problem, more details
Generalizing the fitting procedure as a linear algebra problem
-Generalizing the fitting procedure as a linear algebra problem
+Generalizing the fitting procedure as a linear algebra problem
-Optimizing our parameters
+Optimizing our parameters
-Our model for the nuclear binding energies
+Our model for the nuclear binding energies
# Common imports
+
# Common imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
@@ -532,7 +610,7 @@ DATA_ID = "
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
+ plt.savefig(image_path(fig_id) + ".png", format='png')
infile = open(data_path("MassEval2016.dat"),'r')
@@ -542,7 +620,7 @@ Masses = pd.=('N', 'Z', 'A', 'Element', 'Ebinding'),
widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),
header=39,
- index_col=False)
+ index_col=False)
# Extrapolated values are indicated by '#' in place of the decimal place, so
# the Ebinding column won't be numeric. Coerce to float and drop these entries.
@@ -585,7 +663,7 @@ throughout these lectures.
-Optimizing our parameters, more details
+Optimizing our parameters, more details
-Interpretations and optimizing our parameters
+Interpretations and optimizing our parameters
-Interpretations and optimizing our parameters
+Interpretations and optimizing our parameters
-Some useful matrix and vector expressions
+Some useful matrix and vector expressions
-Interpretations and optimizing our parameters
+Interpretations and optimizing our parameters
-Own code for Ordinary Least Squares
+Own code for Ordinary Least Squares
# matrix inversion to find beta
+
# matrix inversion to find beta
beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
# and then make the prediction
-ytilde = X @ beta
+ytilde = X @ beta
fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
+
fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
ytildenp = np.dot(fit,X.T)
Masses['Eapprox'] = ytilde
+
Masses['Eapprox'] = ytilde
# Generate a plot comparing the experimental with the fitted values values.
fig, ax = plt.subplots()
ax.set_xlabel(r'$A = N + Z$')
-ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$')
+ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$')
ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,
label='Ame2016')
ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',
@@ -818,7 +896,7 @@ plt.show()
-Adding error analysis and training set up
+Adding error analysis and training set up
def R2(y_data, y_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)
print(R2(Energies,ytilde))
+
print(R2(Energies,ytilde))
def MSE(y_data,y_model):
+
def MSE(y_data,y_model):
n = np.size(y_model)
return np.sum((y_data-y_model)**2)/n
-print(MSE(Energies,ytilde))
+print(MSE(Energies,ytilde))
def RelativeError(y_data,y_model):
+
def RelativeError(y_data,y_model):
return abs((y_data-y_model)/y_data)
-print(RelativeError(Energies, ytilde))
+print(RelativeError(Energies, ytilde))
-The \( \chi^2 \) function
-
-
-The \( \chi^2 \) function
-
-
-The \( \chi^2 \) function
-
-
-The \( \chi^2 \) function
-
-
-The \( \chi^2 \) function
-
-
-The \( \chi^2 \) function
-
-
-Fitting an Equation of State for Dense Nuclear Matter
+Fitting an Equation of State for Dense Nuclear Matter
-The code
+The code
# Common imports
+
# Common imports
import os
import numpy as np
import pandas as pd
@@ -1118,7 +997,7 @@ DATA_ID = "
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
+ plt.savefig(image_path(fig_id) + ".png", format='png')
infile = open(data_path("EoS.csv"),'r')
@@ -1141,12 +1020,12 @@ clf = skl.= clf.predict(X)
EoS['Eols'] = ytilde
# The mean squared error
-print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde))
+print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde))
# Explained variance score: 1 is perfect prediction
-print('Variance score: %.2f' % r2_score(Energies, ytilde))
+print('Variance score: %.2f' % r2_score(Energies, ytilde))
# Mean absolute error
-print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))
-print(clf.coef_, clf.intercept_)
+print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))
+print(clf.coef_, clf.intercept_)
# The Ridge regression with a hyperparameter lambda = 0.1
_lambda = 0.1
@@ -1154,15 +1033,15 @@ clf_ridge = skl
yridge = clf_ridge.predict(X)
EoS['Eridge'] = yridge
# The mean squared error
-print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge))
+print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge))
# Explained variance score: 1 is perfect prediction
-print('Variance score: %.2f' % r2_score(Energies, yridge))
+print('Variance score: %.2f' % r2_score(Energies, yridge))
# Mean absolute error
-print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))
-print(clf_ridge.coef_, clf_ridge.intercept_)
+print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))
+print(clf_ridge.coef_, clf_ridge.intercept_)
fig, ax = plt.subplots()
-ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$')
+ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$')
ax.set_ylabel(r'Energy per particle')
ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2,
label='Theoretical data')
@@ -1186,7 +1065,7 @@ below.
-Splitting our Data in Training and Test data
+Splitting our Data in Training and Test data
import os
+
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
@@ -1229,7 +1108,7 @@ DATA_ID = "
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
+ plt.savefig(image_path(fig_id) + ".png", format='png')
def R2(y_data, y_model):
return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
@@ -1257,21 +1136,21 @@ X_train, X_test, y_train, y_test = train_tes
# matrix inversion to find beta
beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)
# and then make the prediction
-ytilde = X_train @ beta
-print("Training R2")
-print(R2(y_train,ytilde))
-print("Training MSE")
-print(MSE(y_train,ytilde))
-ypredict = X_test @ beta
-print("Test R2")
-print(R2(y_test,ypredict))
-print("Test MSE")
-print(MSE(y_test,ypredict))
+ytilde = X_train @ beta
+print("Training R2")
+print(R2(y_train,ytilde))
+print("Training MSE")
+print(MSE(y_train,ytilde))
+ypredict = X_test @ beta
+print("Test R2")
+print(R2(y_test,ypredict))
+print("Test MSE")
+print(MSE(y_test,ypredict))
The Boston housing data example
+The Boston housing data example
-Housing data, the code
+Housing data, the code
We start by importing the libraries
import numpy as np
+
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
@@ -1319,7 +1198,7 @@ and load the Boston Housing DataSet from Scikit-Learn