diff --git a/doc/pub/Regression/html/._Regression-bs000.html b/doc/pub/Regression/html/._Regression-bs000.html index f2952f17c..cf5feb8ed 100644 --- a/doc/pub/Regression/html/._Regression-bs000.html +++ b/doc/pub/Regression/html/._Regression-bs000.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source
+-
@@ -457,7 +424,7 @@ MathJax.Hub.Config({
+
-Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) varies as function of another variable or a set of such variables \( \hat{x} =[x_0, x_1,\dots, x_p]^T \). -The first variable is called the dependent, the outcome or the response variable while the set of variables \( \hat{x} \) is called the independent variable, or the predictor variable or the explanatory variable. - -
-A regression model aims at finding a likelihood function \( p(y\vert \hat{x}) \), that is the conditional distribution for \( y \) with a given \( \hat{x} \). The estimation of \( p(y\vert \hat{x}) \) is made using a data set with +Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \).
@@ -454,7 +418,7 @@ A regression model aims at finding a likelihood function \( p(y\vert \hat{x}) \)
-Consider an experiment in which \( p \) characteristics of \( n \) samples are -measured. The data from this experiment are denoted \( \mathbf{X} \), with -\( \mathbf{X} \) as above. The matrix \( \mathbf{X} \) is called the design -matrix. Additional information of the samples is available in the -form of \( \mathbf{Y} \) (also as above). The variable \( \mathbf{Y} \) is -generally referred to as the response variable. The aim of -regression analysis is to explain \( \mathbf{Y} \) in terms of -\( \mathbf{X} \) through a functional relationship like \( Y_i = -f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of -\( f(\cdot) \) is available, it is common to assume a linear relationship -between \( \mathbf{X} \) and \( \mathbf{Y} \). This assumption gives rise to -the linear regression model where \( \beta = (\beta_1, \ldots, -\beta_p)^{\top} \) is the regression parameter. The parameter -\( \beta_j \), \( j=1, \ldots, p \), represents the effect size of covariate -\( j \) on the response. That is, for each unit change in covariate \( j \) -(while keeping the other covariates fixed) the observed change in the -response is equal to \( \beta_j \). +Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \). +The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable.
+A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with + +
-Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \hat{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \hat{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function.
-Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is -$$ -y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_i x_i^j+\epsilon_i, -$$ +Consider an experiment in which \( p \) characteristics of \( n \) samples are +measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix +\( \mathbf{X} \). -where \( \epsilon_i \) is the error in our approximation. +
+The matrix \( \mathbf{X} \) is called the design +matrix. Additional information of the samples is available in the +form of \( \boldsymbol{y} \) (also as above). The variable \( \boldsymbol{y} \) is +generally referred to as the response variable. The aim of +regression analysis is to explain \( \boldsymbol{y} \) in terms of +\( \boldsymbol{X} \) through a functional relationship like \( y_i = +f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of +\( f(\cdot) \) is available, it is common to assume a linear relationship +between \( \boldsymbol{X} \) and \( \boldsymbol{y} \). This assumption gives rise to +the linear regression model where \( \boldsymbol{\beta} = [\beta_0, \ldots, +\beta_{p-1}]^{T} \) are the regression parameters. + +
+Linear regression gives us a set of analytical equations for the parameters \( \beta_j \).
-For every set of values \( y_i,x_i \) we have thus the corresponding set of equations +In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), +consider the model we discussed for describing nuclear binding energies. + +
+There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. +Assuming $$ -\begin{align*} -y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ -y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ -y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_1x_{n-1}^{n-1}+\epsilon_{n-1}.\\ -\end{align*} +BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, $$ + +we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms. +This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a +\( p\times n \) matrix \( \boldsymbol{X} \). + +
+Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the +so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \) + +
-Defining the vectors +Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function. + +
+Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is $$ -\hat{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, +y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, $$ -and -$$ -\hat{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, -$$ +where \( \epsilon_i \) is the error in our approximation. -and -$$ -\hat{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, -$$ - -and the matrix -$$ -\hat{X}= -\begin{bmatrix} -1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ -1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ -1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ -\end{bmatrix} -$$ - -we can rewrite our equations as -$$ -\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}. -$$ +
-We are obviously not limited to the above polynomial. We could replace the various powers of \( x \) with elements of Fourier series, that is, instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j x_i)} \), or time series or other orthogonal functions. -For every set of values \( y_i,x_i \) we can then generalize the equations to +For every set of values \( y_i,x_i \) we have thus the corresponding set of equations $$ \begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ +y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ +y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ +y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ \dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\ +y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\ \end{align*} $$
-We redefine in turn the matrix \( \hat{X} \) as +Defining the vectors $$ -\hat{X}= +\boldsymbol{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, +$$ + +and +$$ +\boldsymbol{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, +$$ + +and +$$ +\boldsymbol{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, +$$ + +and the design matrix +$$ +\boldsymbol{X}= \begin{bmatrix} -x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ -x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ -x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ +1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ +1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ +1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ \dots& \dots &\dots& \dots & \dots &\dots\\ -x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ +1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ \end{bmatrix} $$ -and without loss of generality we rewrite again our equations as +we can rewrite our equations as $$ -\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}. +\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. $$ -The left-hand side of this equation forms know. Our error vector \( \hat{\epsilon} \) and the parameter vector \( \hat{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values? +The above design matrix is called a Vandermonde matrix.
-We have defined the matrix \( \hat{X} \) + +
+We are obviously not limited to the above polynomial expansions. We +could replace the various powers of \( x \) with elements of Fourier +series or instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j +x_i)} \), or time series or other orthogonal functions. For every set +of values \( y_i,x_i \) we can then generalize the equations to + $$ \begin{align*} y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ +y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ \dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ +y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ \dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\ +y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ \end{align*} $$ + +
+Note that we have \( p=n \) here. The matrix is symmetric. This is generally not the case!
-We well use this matrix to define the approximation \( \hat{\tilde{y}} \) via the unknown quantity \( \hat{\beta} \) as +We redefine in turn the matrix \( \boldsymbol{X} \) as $$ -\hat{\tilde{y}}= \hat{X}\hat{\beta}, +\boldsymbol{X}= +\begin{bmatrix} +x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ +x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ +x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ +\dots& \dots &\dots& \dots & \dots &\dots\\ +x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ +\end{bmatrix} $$ -and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parametrized values \( \tilde{y}_i \), namely +and without loss of generality we rewrite again our equations as $$ -Q(\hat{\beta})=\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\left(\hat{y}-\hat{\tilde{y}}\right)^T\left(\hat{y}-\hat{\tilde{y}}\right), +\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. $$ -or using the matrix \( \hat{X} \) as -$$ -Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right). -$$ +The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values?
-The function +We have defined the matrix \( \boldsymbol{X} \) via the equations $$ -Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right), +\begin{align*} +y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ +y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ +y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ +\dots & \dots \\ +y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ +\dots & \dots \\ +y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ +\end{align*} $$ -can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value of for example a numerical experiment. When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value -$$ -y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, -$$ - -where \( \langle y_i \rangle \) is the mean value. Keep in mind also that till now we have treated \( y_i \) as the exact value. Normally, the response (dependent or outcome) variable \( y_i \) 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. -
-In order to find the parameters \( \beta_i \) we will then minimize the spread of \( Q(\hat{\beta}) \) by requiring -$$ -\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, -$$ - -which results in -$$ -\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, -$$ - -or in a matrix-vector form as -$$ -\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right). -$$ +As we noted above, we stayed with a system with the design matrix + \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \), that is we have \( p=n \). For reasons to come later (algorithmic arguments) we will hereafter define +our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors refering to the column numbers and the entries \( n \) being the row elements.
-We can rewrite -$$ -\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right), -$$ - -as -$$ -\hat{X}^T\hat{y} = \hat{X}^T\hat{X}\hat{\beta}, -$$ - -and if the matrix \( \hat{X}^T\hat{X} \) is invertible we have the solution -$$ -\hat{\beta} =\left(\hat{X}^T\hat{X}\right)^{-1}\hat{X}^T\hat{y}. -$$ +
-
+We restate the parts of the code we are most interested in. +
+ + +
# Common imports
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from IPython.display import display
+import os
+
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
+
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
+
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
+
+infile = open(data_path("MassEval2016.dat"),'r')
+
+
+# Read the experimental data with Pandas
+Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
+ names=('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)
+
+# 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.
+Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')
+Masses = Masses.dropna()
+# Convert from keV to MeV.
+Masses['Ebinding'] /= 1000
+
+# Group the DataFrame by nucleon number, A.
+Masses = Masses.groupby('A')
+# Find the rows of the grouped DataFrame with the maximum binding energy.
+Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
+A = Masses['A']
+Z = Masses['Z']
+N = Masses['N']
+Element = Masses['Element']
+Energies = Masses['Ebinding']
+
+# Now we set up the design matrix X
+X = np.zeros((len(A),5))
+X[:,0] = 1
+X[:,1] = A
+X[:,2] = A**(2.0/3.0)
+X[:,3] = A**(-1.0/3.0)
+X[:,4] = A**(-1.0)
+# Then nice printout using pandas
+DesignMatrix = pd.DataFrame(X)
+DesignMatrix.index = A
+DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
+display(DesignMatrix)
++With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as +$$ +\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, +$$ + +throughout these lectures.
@@ -464,7 +495,7 @@ $$
-The residuals \( \hat{\epsilon} \) are in turn given by +With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as $$ -\hat{\epsilon} = \hat{y}-\hat{\tilde{y}} = \hat{y}-\hat{X}\hat{\beta}, +\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, $$ -and with +and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely $$ -\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0, +C(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, $$ -we have +or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as $$ -\hat{X}^T\hat{\epsilon}=\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0, +C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)\right\}. $$ -meaning that the solution for \( \hat{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. +This function is one possible way to define the so-called cost function.
+It is also common to define +the function \( Q \) as + +$$ +C(\boldsymbol{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, +$$ + +since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out.
-Normally, the response (dependent or outcome) variable \( y_i \) 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. +The function +$$ +C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}, +$$ + +can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. +When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value (see exercises) +$$ +y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, +$$
-Introducing the standard deviation \( \sigma_i \) for each measurement \( y_i \), we define now the \( \chi^2 \) function as +where \( \langle y_i \rangle \) is the mean value. Keep in mind also that +till now we have treated \( y_i \) as the exact value. Normally, the +response (dependent or outcome) variable \( y_i \) 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. + +
+In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem $$ -\chi^2(\hat{\beta})=\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\left(\hat{y}-\hat{\tilde{y}}\right)^T\frac{1}{\hat{\Sigma^2}}\left(\hat{y}-\hat{\tilde{y}}\right), +{\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\}. $$ -where the matrix \( \hat{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements. +In practical terms it means we will require +$$ +\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, +$$ + +which results in +$$ +\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, +$$ + +or in a matrix-vector form as +$$ +\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right). +$$
+We can rewrite +$$ +\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right), +$$ + +as +$$ +\boldsymbol{X}^T\boldsymbol{y} = \boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}, +$$ + +and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution +$$ +\boldsymbol{\beta} =\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +$$
-In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\hat{\beta}) \) by requiring -$$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \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, -$$ +We note also that since our design matrix is defined as \( \boldsymbol{X}\in +{\mathbb{R}}^{n\times p} \), the product \( \boldsymbol{X}^T\boldsymbol{X} \in +{\mathbb{R}}^{p\times p} \). In the above case we have that \( p \ll n \), +in our case \( p=5 \) meaning that we end up with inverting a small +\( 5\times 5 \) matrix. This is a rather common situation, in many cases we end up with low-dimensional +matrices to invert. The methods discussed here and for many other +supervised learning algorithms like classification with logistic +regression or support vector machines, exhibit dimensionalities which +allow for the usage of direct linear algebra methods such as LU decomposition or Singular Value Decomposition (SVD) for finding the inverse of the matrix +\( \boldsymbol{X}^T\boldsymbol{X} \). -which results in -$$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = -2\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(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right). -$$ - -where we have defined the matrix \( \hat{A} =\hat{X}/\hat{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \hat{b} \) with elements \( b_i = y_i/\sigma_i \). +
+The residuals \( \boldsymbol{\epsilon} \) are in turn given by +$$ +\boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}, +$$ + +and with +$$ +\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, +$$ + +we have +$$ +\boldsymbol{X}^T\boldsymbol{\epsilon}=\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, +$$ + +meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.
-We can rewrite -$$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right), -$$ - -as -$$ -\hat{A}^T\hat{b} = \hat{A}^T\hat{A}\hat{\beta}, -$$ - -and if the matrix \( \hat{A}^T\hat{A} \) is invertible we have the solution -$$ -\hat{\beta} =\left(\hat{A}^T\hat{A}\right)^{-1}\hat{A}^T\hat{b}. -$$
+Let us now return to our nuclear binding energies and simply code the above equations. +
@@ -464,7 +436,7 @@ $$
+
-If we then introduce the matrix -$$ -\hat{H} = \left(\hat{A}^T\hat{A}\right)^{-1}, -$$ +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 +write +
-we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \hat{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}! -$$ -
# 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
++Alternatively, you can use the least squares functionality in Numpy as +
+ +
fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
+ytildenp = np.dot(fit,X.T)
++And finally we plot our fit with and compare with data +
+ +
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.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',
+ label='Fit')
+ax.legend()
+save_fig("Masses2016OLS")
+plt.show()
+
@@ -469,7 +446,7 @@ $$
-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. -$$ +
+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. +Since we are not using _Scikit-Learn here we can define our own \( R2 \) function as +
-and -$$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. -$$ -
def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
++and we would be using it as +
+ +
print(R2(Energies,ytilde))
++We can easily add our MSE score as +
+ +
def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+print(MSE(Energies,ytilde))
++and finally the relative error as +
+ + +
def RelativeError(y_data,y_model):
+ return abs((y_data-y_model)/y_data)
+print(RelativeError(Energies, ytilde))
+
@@ -462,7 +445,7 @@ $$
-For a linear fit 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}. -$$ +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.
-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.
+
+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, +$$ - -
import numpy as np
-print(np.c_[np.array([1,2,3]), np.array([4,5,6])])
-print(np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])])
-+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, +$$ - -
# Importing various packages
-from random import random, seed
-import numpy as np
-import matplotlib.pyplot as plt
+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).
+$$
-x = 2*np.random.rand(100,1)
-y = 4+3*x+np.random.randn(100,1)
+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 see that, as expected, a linear fit gives a seemingly (from the graph) good representation of the data.
@@ -477,7 +433,7 @@ We see that, as expected, a linear fit gives a seemingly (from the graph) good r
-We can repeat the above algorithm using scikit-learn as follows -
+We can rewrite +$$ +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right), +$$ - -
# Importing various packages
-from random import random, seed
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression
+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}.
+$$
+
@@ -468,7 +431,7 @@ plt.show()
-We start with perhaps our simplest possible example, using scikit-learn to perform linear regression analysis on a data set produced by us. -What follows is a simple Python code where we have defined function \( y \) in terms of the variable \( x \). Both are defined as vectors of dimension \( 1\times 100 \). The entries to the vector \( \hat{x} \) are given by random numbers generated with a uniform distribution with entries \( x_i \in [0,1] \) (more about probability distribution functions later). These values are then used to define a function \( y(x) \) (tabulated again as a vector) with a linear dependence on \( x \) plus a random noise added via the normal distribution. - -
-The Numpy functions are imported used the import numpy as np -statement and the random number generator for the uniform distribution -is called using the function np.random.rand(), where we specificy -that we want \( 100 \) random variables. Using Numpy we define -automatically an array with the specified number of elements, \( 100 \) in -our case. With the Numpy function randn() we can compute random -numbers with the normal distribution (mean value \( \mu \) equal to zero and -variance \( \sigma^2 \) set to one) and produce the values of \( y \) assuming a linear -dependence as function of \( x \) - +If we then introduce the matrix $$ -y = 2x+N(0,1), +\boldsymbol{H} = \left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}, $$ -
-where \( N(0,1) \) represents random numbers generated by the normal -distribution. From scikit-learn we import then the -LinearRegression functionality and make a prediction \( \tilde{y} = -\alpha + \beta x \) using the function fit(x,y). We call the set of -data \( (\hat{x},\hat{y}) \) for our training data. The Python package -scikit-learn has also a functionality which extracts the above -fitting parameters \( \alpha \) and \( \beta \) (see below). Later we will -distinguish between training data and test data. +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} +$$ -
-For plotting we use the Python package -matplotlib which produces publication -quality figures. Feel free to explore the extensive -gallery of examples. In -this example we plot our original values of \( x \) and \( y \) as well as the -prediction ypredict (\( \tilde{y} \)), which attempts at fitting our -data with a straight line. +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, +$$ -
-The Python code follows here. -
+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}! +$$ +
# Importing various packages
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression
-x = np.random.rand(100,1)
-y = 2*x+np.random.randn(100,1)
-linreg = LinearRegression()
-linreg.fit(x,y)
-xnew = np.array([[0],[1]])
-ypredict = linreg.predict(xnew)
-
-plt.plot(xnew, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0,1.0,0, 5.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Simple Linear Regression')
-plt.show()
-
@@ -505,7 +436,7 @@ plt.show()
-This example serves several aims. It allows us to demonstrate several -aspects of data analysis and later machine learning algorithms. The -immediate visualization shows that our linear fit is not -impressive. It goes through the data points, but there are many -outliers which are not reproduced by our linear regression. We could -now play around with this small program and change for example the -factor in front of \( x \) and the normal distribution. Try to change the -function \( y \) to - +
+The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write $$ -y = 10x+0.01 \times N(0,1), +y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. $$ -
-where \( x \) is defined as before. +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. +$$ +
@@ -459,7 +429,7 @@ where \( x \) is defined as before.
-Does the fit look better? Indeed, by -reducing the role of the normal distribution we see immediately that -our linear prediction seemingly reproduces better the training -set. However, this testing 'by the eye' is obviouly not satisfactory in the -long run. Here we have only defined the training data and our model, and -have not discussed a more rigorous approach to the cost function. +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. + +
+
@@ -450,7 +463,7 @@ have not discussed a more rigorous approach to the cost function.
-We need more rigorous criteria in defining whether we have succeeded or -not in modeling our training data. You will be surprised to see that -many scientists seldomly venture beyond this 'by the eye' approach. A -standard approach for the cost function is the so-called \( \chi^2 \) -function - -$$ \chi^2 = \frac{1}{n} -\sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2}, -$$ +Before we continue, let us introduce yet another example. We are going to fit the +nuclear equation of state using results from many-body calculations. +The equation of state we have made available here, as function of +density, has been derived using modern nucleon-nucleon potentials with +the addition of three-body +forces. This +time the file is presented as a standard csv file.
-where \( \sigma_i^2 \) is the variance (to be defined later) of the entry -\( y_i \). We may not know the explicit value of \( \sigma_i^2 \), it serves -however the aim of scaling the equations and make the cost function -dimensionless. +The beginning of the Python code here is similar to what you have seen before, +with the same initializations and declarations. We use also pandas +again, rather extensively in order to organize our data. + +
+The difference now is that we use Scikit-Learn's regression tools +instead of our own matrix inversion implementation. Furthermore, we +sneak in Ridge regression (to be discussed below) which includes a +hyperparameter \( \lambda \), also to be explained below.
@@ -459,7 +429,7 @@ dimensionless.
-Minimizing the cost function is a central aspect of -our discussions to come. Finding its minima as function of the model -parameters (\( \alpha \) and \( \beta \) in our case) will be a recurring -theme in these series of lectures. Essentially all machine learning -algorithms we will discuss center around the minimization of the -chosen cost function. This depends in turn on our specific -model for describing the data, a typical situation in supervised -learning. Automatizing the search for the minima of the cost function is a -central ingredient in all algorithms. Typical methods which are -employed are various variants of gradient methods. These will be -discussed in more detail later. Again, you'll be surprised to hear that -many practitioners minimize the above function ''by the eye', popularly dubbed as -'chi by the eye'. That is, change a parameter and see (visually and numerically) that -the \( \chi^2 \) function becomes smaller. + + +
# Common imports
+import os
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+import matplotlib.pyplot as plt
+import sklearn.linear_model as skl
+from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
+
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
+
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
+
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
+
+infile = open(data_path("EoS.csv"),'r')
+
+# Read the EoS data as csv file and organize the data into two arrays with density and energies
+EoS = pd.read_csv(infile, names=('Density', 'Energy'))
+EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
+EoS = EoS.dropna()
+Energies = EoS['Energy']
+Density = EoS['Density']
+# The design matrix now as function of various polytrops
+X = np.zeros((len(Density),4))
+X[:,3] = Density**(4.0/3.0)
+X[:,2] = Density
+X[:,1] = Density**(2.0/3.0)
+X[:,0] = 1
+
+# We use now Scikit-Learn's linear regressor and ridge regressor
+# OLS part
+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))
+# Explained variance score: 1 is perfect prediction
+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_)
+
+# The Ridge regression with a hyperparameter lambda = 0.1
+_lambda = 0.1
+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))
+# Explained variance score: 1 is perfect prediction
+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_)
+
+fig, ax = plt.subplots()
+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')
+ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',
+ label='OLS')
+ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g',
+ label='Ridge $\lambda = 0.1$')
+ax.legend()
+save_fig("EoSfitting")
+plt.show()
++The above simple polynomial in density \( \rho \) gives an excellent fit +to the data. Can you give an interpretation of the various powers of \( \rho \)? + +
+We note also that there is a small deviation between the +standard OLS and the Ridge regression at higher densities. We discuss this in more detail +below.
@@ -458,7 +507,7 @@ the \( \chi^2 \) function becomes smaller.
-There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define -the relative error as +It is normal in essentially all Machine Learning studies to split the +data in a training set and a test set (sometimes also an additional +validation set). Scikit-Learn has an own function for this. There +is no explicit recipe for how much data should be included as training +data and say test data. An accepted rule of thumb is to use +approximately \( 2/3 \) to \( 4/5 \) of the data as training data. We will +postpone a discussion of this splitting to the end of these notes and +our discussion of the so-called bias-variance tradeoff. Here we +limit ourselves to repeat the above equation of state fitting example +but now splitting the data into a training set and a test set. -$$ -\epsilon_{\mathrm{relative}}= \frac{\vert \hat{y} -\hat{\tilde{y}}\vert}{\vert \hat{y}\vert}. -$$ - -We can modify easily the above Python code and plot the relative error instead
-
import numpy as np
+import os
+import numpy as np
+import pandas as pd
import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression
+from sklearn.model_selection import train_test_split
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
-x = np.random.rand(100,1)
-y = 5*x+0.01*np.random.randn(100,1)
-linreg = LinearRegression()
-linreg.fit(x,y)
-ypredict = linreg.predict(x)
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
-plt.plot(x, np.abs(ypredict-y)/abs(y), "ro")
-plt.axis([0,1.0,0.0, 0.5])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$\epsilon_{\mathrm{relative}}$')
-plt.title(r'Relative error')
-plt.show()
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
+
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+infile = open(data_path("EoS.csv"),'r')
+
+# Read the EoS data as csv file and organized into two arrays with density and energies
+EoS = pd.read_csv(infile, names=('Density', 'Energy'))
+EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
+EoS = EoS.dropna()
+Energies = EoS['Energy']
+Density = EoS['Density']
+# The design matrix now as function of various polytrops
+X = np.zeros((len(Density),5))
+X[:,0] = 1
+X[:,1] = Density**(2.0/3.0)
+X[:,2] = Density
+X[:,3] = Density**(4.0/3.0)
+X[:,4] = Density**(5.0/3.0)
+# We split the data in test and training data
+X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
+# 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))
-
-Depending on the parameter in front of the normal distribution, we may
-have a small or larger relative error. Try to play around with
-different training data sets and study (graphically) the value of the
-relative error.
-
@@ -477,7 +489,7 @@ relative error.
-As mentioned above, scikit-learn has an impressive functionality. -We can for example extract the values of \( \alpha \) and \( \beta \) and -their error estimates, or the variance and standard deviation and many -other properties from the statistical data analysis. +
-Here we show an -example of the functionality of scikit-learn. +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. This may +however not the be case in general and a standard matrix inversion +algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit +the coupling constant of the widely used Ising model. +There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. +
+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. + +
+
import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression
-from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error
-x = np.random.rand(100,1)
-y = 2.0+ 5*x+0.5*np.random.randn(100,1)
-linreg = LinearRegression()
-linreg.fit(x,y)
-ypredict = linreg.predict(x)
-print('The intercept alpha: \n', linreg.intercept_)
-print('Coefficient beta : \n', linreg.coef_)
-# The mean squared error
-print("Mean squared error: %.2f" % mean_squared_error(y, ypredict))
-# Explained variance score: 1 is perfect prediction
-print('Variance score: %.2f' % r2_score(y, ypredict))
-# Mean squared log error
-print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) )
-# Mean absolute error
-print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict))
-plt.plot(x, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0.0,1.0,1.5, 7.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Linear Regression fit ')
-plt.show()
-
@@ -482,7 +436,7 @@ plt.show()
-The function coef gives us the parameter \( \beta \) of our fit while intercept yields -\( \alpha \). Depending on the constant in front of the normal distribution, we get values near or far from \( alpha =2 \) and \( \beta =5 \). Try to play around with different parameters in front of the normal distribution. The function meansquarederror gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as -$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +The one-dimensional Ising model with nearest neighbor interaction, no +external field and a constant coupling constant \( J \) is given by + +$$ +\begin{align} + H = -J \sum_{k}^L s_k s_{k + 1}, +\tag{1} +\end{align} $$
-The smaller the value, the better the fit. Ideally we would like to -have an MSE equal zero. The attentive reader has probably recognized -this function as being similar to the \( \chi^2 \) function defined above. +where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins +in the system is determined by \( L \). For the one-dimensional system +there is no phase transition. + +
+We will look at a system of \( L = 40 \) spins with a coupling constant of +\( J = 1 \). To get enough training data we will generate 10000 states +with their respective energies. + +
+ + +
import numpy as np
+import matplotlib.pyplot as plt
+from mpl_toolkits.axes_grid1 import make_axes_locatable
+import seaborn as sns
+import scipy.linalg as scl
+from sklearn.model_selection import train_test_split
+import tqdm
+sns.set(color_codes=True)
+cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
+
+L = 40
+n = int(1e4)
+
+spins = np.random.choice([-1, 1], size=(n, L))
+J = 1.0
+
+energies = np.zeros(n)
+
+for i in range(n):
+ energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
++Here we use ordinary least squares +regression to predict the energy for the nearest neighbor +one-dimensional Ising model on a ring, i.e., the endpoints wrap +around. We will use linear regression to fit a value for +the coupling constant to achieve this.
@@ -454,7 +461,7 @@ this function as being similar to the \( \chi^2 \) function defined above.
-The r2score function computes \( R^2 \), the coefficient of -determination. It provides a measure of how well future samples are -likely to be predicted by the model. Best possible score is 1.0 and it -can be negative (because the model can be arbitrarily worse). A -constant model that always predicts the expected value of \( \hat{y} \), -disregarding the input features, would get a \( R^2 \) score of \( 0.0 \). +A more general form for the one-dimensional Ising model is + +$$ +\begin{align} + H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. +\tag{2} +\end{align} +$$
-If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +Here we allow for interactions beyond the nearest neighbors and a state dependent +coupling constant. This latter expression can be formulated as +a matrix-product $$ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, +\begin{align} + \boldsymbol{H} = \boldsymbol{X} J, +\tag{3} +\end{align} $$ -where we have defined the mean value of \( \hat{y} \) as +
+where \( X_{jk} = s_j s_k \) and \( J \) is a matrix which consists of the +elements \( -J_{jk} \). This form of writing the energy fits perfectly +with the form utilized in linear regression, that is + $$ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\begin{align} + \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}, +\tag{4} +\end{align} $$ +
+We split the data in training and test data as discussed in the previous example + +
+ + +
X = np.zeros((n, L ** 2))
+for i in range(n):
+ X[i] = np.outer(spins[i], spins[i]).ravel()
+y = energies
+X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
+
@@ -461,7 +454,7 @@ $$
-Another quantity will meet again in our discussions of regression analysis is - mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the \( l1 \)-norm loss. In our discussion above we presented the relative error. -The MAE is defined as follows -$$ -\text{MAE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1} \left| y_i - \tilde{y}_i \right|. -$$ +In the ordinary least squares method we choose the cost function -Finally we present the -squared logarithmic (quadratic) error $$ -\text{MSLE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n - 1} (\log_e (1 + y_i) - \log_e (1 + \tilde{y}_i) )^2, +\begin{align} + C(\boldsymbol{X}, \boldsymbol{\beta})= \frac{1}{n}\left\{(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})\right\}. +\tag{5} +\end{align} $$
-where \( \log_e (x) \) stands for the natural logarithm of \( x \). This error -estimate is best to use when targets having exponential growth, such -as population counts, average sales of a commodity over a span of -years etc. +We then find the extremal point of \( C \) by taking the derivative with respect to \( \boldsymbol{\beta} \) as discussed above. +This yields the expression for \( \boldsymbol{\beta} \) to be +$$ + \boldsymbol{\beta} = \frac{\boldsymbol{X}^T \boldsymbol{y}}{\boldsymbol{X}^T \boldsymbol{X}}, +$$ + +
+which immediately imposes some requirements on \( \boldsymbol{X} \) as there must exist +an inverse of \( \boldsymbol{X}^T \boldsymbol{X} \). If the expression we are modeling contains an +intercept, i.e., a constant term, we must make sure that the +first column of \( \boldsymbol{X} \) consists of \( 1 \). We do this here + +
+ + +
X_train_own = np.concatenate(
+ (np.ones(len(X_train))[:, np.newaxis], X_train),
+ axis=1
+)
+X_test_own = np.concatenate(
+ (np.ones(len(X_test))[:, np.newaxis], X_test),
+ axis=1
+)
++ + +
def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray:
+ return scl.inv(x.T @ x) @ (x.T @ y)
+beta = ols_inv(X_train_own, y_train)
+
@@ -462,7 +452,7 @@ years etc.
-We will discuss in more -detail these and other functions in the various lectures. We conclude this part with another example. Instead of -a linear \( x \)-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn. -Add description of the various python commands. +Doing the inversion directly turns out to be a bad idea since the matrix +\( \boldsymbol{X}^T\boldsymbol{X} \) is singular. An alternative approach is to use the singular +value decomposition. Using the definition of the Moore-Penrose +pseudoinverse we can write the equation for \( \boldsymbol{\beta} \) as + +$$ + \boldsymbol{\beta} = \boldsymbol{X}^{+}\boldsymbol{y}, +$$ + +
+where the pseudoinverse of \( \boldsymbol{X} \) is given by + +$$ + \boldsymbol{X}^{+} = \frac{\boldsymbol{X}^T}{\boldsymbol{X}^T\boldsymbol{X}}. +$$ + +
+Using singular value decomposition we can decompose the matrix \( \boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma} \boldsymbol{V}^T \), +where \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal(unitary) matrices and \( \boldsymbol{\Sigma} \) contains the singular values (more details below). +where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for +\( \omega \) to +$$ +\begin{align} + \boldsymbol{\beta} = \boldsymbol{V}\boldsymbol{\Sigma}^{+} \boldsymbol{U}^T \boldsymbol{y}. +\tag{6} +\end{align} +$$ + +
+Note that solving this equation by actually doing the pseudoinverse +(which is what we will do) is not a good idea as this operation scales +as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a +general matrix. Instead, doing \( QR \)-factorization and solving the +linear system as an equation would reduce this down to +\( \mathcal{O}(n^2) \) operations.
-
import matplotlib.pyplot as plt
-import numpy as np
-import random
-from sklearn.linear_model import Ridge
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.pipeline import make_pipeline
-from sklearn.linear_model import LinearRegression
-
-x=np.linspace(0.02,0.98,200)
-noise = np.asarray(random.sample((range(200)),200))
-y=x**3*noise
-yn=x**3*100
-poly3 = PolynomialFeatures(degree=3)
-X = poly3.fit_transform(x[:,np.newaxis])
-clf3 = LinearRegression()
-clf3.fit(X,y)
-
-Xplot=poly3.fit_transform(x[:,np.newaxis])
-poly3_plot=plt.plot(x, clf3.predict(Xplot), label='Cubic Fit')
-plt.plot(x,yn, color='red', label="True Cubic")
-plt.scatter(x, y, label='Data', color='orange', s=15)
-plt.legend()
-plt.show()
-
-def error(a):
- for i in y:
- err=(y-yn)/yn
- return abs(np.sum(err))/len(err)
-
-print (error(y))
+def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray:
+ u, s, v = scl.svd(x)
+ return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
-Using R, we can perform similar studies.
+
+
+
beta = ols_svd(X_train_own,y_train)
+
+
+When extracting the \( J \)-matrix we need to make sure that we remove the intercept, as is done here
+
+
+
+
+
J = beta[1:].reshape(L, L)
+
+
+A way of looking at the coefficients in \( J \) is to plot the matrices as images.
+
+
+
+
+
fig = plt.figure(figsize=(20, 14))
+im = plt.imshow(J, **cmap_args)
+plt.title("OLS", fontsize=18)
+plt.xticks(fontsize=18)
+plt.yticks(fontsize=18)
+cb = fig.colorbar(im)
+cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
+plt.show()
+
+
+It is interesting to note that OLS
+considers both \( J_{j, j + 1} = -0.5 \) and \( J_{j, j - 1} = -0.5 \) as
+valid matrix elements for \( J \).
+In our discussion below on hyperparameters and Ridge and Lasso regression we will see that
+this problem can be removed, partly and only with Lasso regression.
+
+
+In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD?
@@ -485,7 +491,7 @@ Using R, we can perform similar studies.
+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*} +$$ - -
# Importing various packages
-from math import exp, sqrt
-from random import random, seed
-import numpy as np
-import matplotlib.pyplot as plt
+
+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.
-m = 100
-x = 2*np.random.rand(m,1)+4.
-y = 4+3*x*x+ +x-np.random.randn(m,1)
+
+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*}
+$$
-xb = np.c_[np.ones((m,1)), x]
-theta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
-xnew = np.array([[0],[2]])
-xbnew = np.c_[np.ones((2,1)), xnew]
-ypredict = xbnew.dot(theta)
+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.
-plt.plot(xnew, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0,2.0,0, 15.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Random numbers ')
-plt.show()
-
@@ -468,7 +455,7 @@ plt.show()
- + -
-Before we proceed, and to link with our discussions of Bayesian statistics to come, it is useful the derive the standard regression analysis equations using a statistical interpretation. This allows us also to derive quantities like the variance and other expectation values in a rather straightforward way. +If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem +$$ +\begin{align} +\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y}, +\tag{7} +\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.
-It is assumed that \( \varepsilon_i -\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are -independent, i.e.: +A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change $$ -\begin{align*} -\mbox{Cov}(\varepsilon_{i_1}, -\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if} -& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right. -\end{align*} +\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I}, $$ -The randomness of \( \varepsilon_i \) implies that -\( \mathbf{Y}_i \) is also a random variable. In particular, -\( \mathbf{Y}_i \) is normally distributed, because \( \varepsilon_i \sim -\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \beta \) is a -non-random scalar. To specify the parameters of the distribution of -\( \mathbf{Y}_i \) we need to calculate its first two moments. +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.
@@ -464,7 +432,7 @@ non-random scalar. To specify the parameters of the distribution of
-Its expectation equals: +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 + $$ -\begin{align*} -\mathbb{E}(Y_i) & = -\mathbb{E}(\mathbf{X}_{i, \ast} \, \beta) + \mathbb{E}(\varepsilon_i) -\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta, -\end{align*} +(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n), $$ -while -its variance is +and the eigenvalues are given by the diagonal matrix $$ -\begin{align*} \mbox{Var}(Y_i) & = \mathbb{E} \{ [Y_i -- \mathbb{E}(Y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( Y_i^2 ) - -[\mathbb{E}(Y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, -\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \beta)^2 \\ & -= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 \varepsilon_i -\mathbf{X}_{i, \ast} \, \beta + \varepsilon_i^2 ] - ( \mathbf{X}_{i, -\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 -\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \beta + -\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \beta)^2 -\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \, -\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2. -\end{align*} +\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). $$ -Hence, \( Y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \beta, \sigma^2) \). +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.
@@ -471,7 +443,7 @@ Hence, \( Y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \beta, \sigma^2) \).
+
-A general -\( m\times n \) matrix \( \hat{A} \) can be written in terms of a diagonal -matrix \( \hat{D} \) of dimensionality \( n\times n \) and two orthognal -matrices \( \hat{U} \) and \( \hat{V} \), where the first has dimensionality -\( m \times m \) and the last dimensionality \( n\times n \). -We have then -$$ -\hat{A} = \hat{U}\hat{D}\hat{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!
@@ -459,7 +435,7 @@ $$
-One of the typical problems we encounter with linear regression, in particular -when the matrix \( \hat{X} \) (our so-called design matrix) is high-dimensional, -are problems with near singular or singular matrices. The column vectors of \( \hat{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 +Consider the following matrix which can be SVD decomposed as + $$ -\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*} +\boldsymbol{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T. $$
-The columns of \( \hat{X} \) are linearly dependent. We se 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. +This is a \( 3\times 2 \) matrix which is decomposed in terms of a +\( 3\times 3 \) matrix \( \boldsymbol{U} \), and a \( 2\times 2 \) matrix \( \boldsymbol{V} \). It is easy to see +that \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal (how?).
-Super-collinearity of an \( (n \times p) \)-dimensional design matrix \( \mathbf{X} \) implies -that the inverse of the matrix \( \hat{X}^T\hat{x} \) (the matrix we needto 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*} -\hat{X} & = \left[ -\begin{array}{rr} -1 & -1 -\\ -1 & -1 -\end{array} \right]. -\end{align*} -$$ +And the SVD +decomposition (singular values) gives eigenvalues +\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=2 \), the +eigenvalues (singular values) are zero. -We see easily that \( \mbox{det}(\hat{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 \( \hat{X} \) has at least an eigenvalue which is 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\lg 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.
@@ -488,7 +442,7 @@ This is equivalent to saying that the matrix \( \hat{X} \) has at least an eigen
-If our design matrix \( \hat{X} \) which enters the linear regression problem -$$ -\begin{align} -\hat{\beta} & = (\hat{X}^{T} \hat{X})^{-1} \hat{X}^{T} \hat{y}, -\tag{1} -\end{align} -$$ - -has linearly dependent column vectors, we will not be able to compute the inverse -of \( \hat{X}^T\hat{X} \) and we cannot find the parameters (estimators) \( \beta_i \). -The estimators are only well-defined if \( (\hat{X}^{T}\hat{X})^{-1} \) exits. -This is more likely to happen when the matrix \( \hat{X} \) is high-dimensional. In this case it is likely to encounter a situation where -the regression parameters \( \beta_i \) cannot be estimated. +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 ad hoc approach which was introduced in the 70s was simply to add a diagonal component to the matrix to invert, that is we change -$$ -\hat{X}^{T} \hat{X} \rightarrow \hat{X}^{T} \hat{X}+\lambda \hat{I}, -$$ +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. -where \( \hat{I} \) is the identity matrix. +
+If \( n > p \), we keep only the first \( p \) columns of \( \boldsymbol{U} \) and \( \boldsymbol{\Sigma} \) has dimension \( p\times p \). +If \( p > n \), then only the first \( n \) columns of \( \boldsymbol{V} \) are computed and \( \boldsymbol{\Sigma} \) has dimension \( n\times n \). +The \( n=p \) case is obvious, we retain the full SVD. +In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.
@@ -465,7 +429,7 @@ where \( \hat{I} \) is the identity matrix.
-We start by considering the case -\( f(x)=2x \). +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.
-Then the data is clearly generated by a model that is contained within -all three model classes we are using to make predictions (linear -models, third order polynomials, and tenth order polynomials). +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}. +$$
-Run the code for the following cases: +The matrix to invert can be rewritten in terms of our SVD decomposition as -
+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.
@@ -464,7 +456,7 @@ Summarize what you have learned about the relationship between model complexity
-Thus far, we have considered the case where the data is generated using a model contained in the model class. Now consider \( f(x)=2x-10x^5+15x^{10} \) . Notice that the for linear and third-order polynomial the true model \( f(x) \) is not contained in model class. +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\}. +$$ -
+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. +$$
@@ -452,7 +462,7 @@ Summarize what you think you learned about the relationship of knowing the true
+Using the matrix-vector expression for Ridge regression, - -
import numpy as np
-import sklearn as sk
-from sklearn import datasets, linear_model
-from sklearn.preprocessing import PolynomialFeatures
+$$
+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},
+$$
-import matplotlib as mpl
-from matplotlib import pyplot as plt
+
+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
-%matplotlib notebook
+$$
+\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
+$$
-# The Training Data
+
+with \( \boldsymbol{I} \) being a \( p\times p \) identity matrix with the constraint that
-N_train=100
+$$
+\sum_{i=0}^{p-1} \beta_i^2 \leq t,
+$$
-sigma_train=1;
+
+with \( t \) a finite positive number.
-# Train on integers
-x=np.linspace(0.05,0.95,N_train)
-# Draw random noise
-s = sigma_train*np.random.randn(N_train)
+
+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
+are rather interesting.
-#linear
-y=2*x+s
+
+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}.
+$$
-#Tenth Order
-#y=2*x-10*x**5+15*x**10+s
+
+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}
+$$
-p1=plt.plot(x,y, "o",ms=15, label='Training')
+
+For Ridge regression this becomes
-#Linear Regression
-# Create linear regression object
-clf = linear_model.LinearRegression()
+$$
+\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},
+$$
-# Train the model using the training sets
-clf.fit(x[:, np.newaxis], y)
-# The coefficients
+
+with the vectors \( \boldsymbol{u}_j \) being the columns of \( \boldsymbol{U} \).
-xplot=np.linspace(0.02,0.98,200)
-linear_plot=plt.plot(xplot, clf.predict(xplot[:, np.newaxis]),label='Linear')
-
-#Polynomial Regression
-
-
-poly3 = PolynomialFeatures(degree=3)
-X = poly3.fit_transform(x[:,np.newaxis])
-clf3 = linear_model.LinearRegression()
-clf3.fit(X,y)
-
-
-Xplot=poly3.fit_transform(xplot[:,np.newaxis])
-poly3_plot=plt.plot(xplot, clf3.predict(Xplot), label='Poly 3')
-
-
-
-#poly5 = PolynomialFeatures(degree=5)
-#X = poly5.fit_transform(x[:,np.newaxis])
-#clf5 = linear_model.LinearRegression()
-#clf5.fit(X,y)
-
-#Xplot=poly5.fit_transform(xplot[:,np.newaxis])
-#plt.plot(xplot, clf5.predict(Xplot), 'r--',linewidth=1)
-
-poly10 = PolynomialFeatures(degree=10)
-X = poly10.fit_transform(x[:,np.newaxis])
-clf10 = linear_model.LinearRegression()
-clf10.fit(X,y)
-
-Xplot=poly10.fit_transform(xplot[:,np.newaxis])
-poly10_plot=plt.plot(xplot, clf10.predict(Xplot), label='Poly 10')
-
-axes = plt.gca()
-axes.set_ylim([-7,7])
-
-handles, labels=axes.get_legend_handles_labels()
-plt.legend(handles,labels, loc='lower center')
-plt.xlabel("$x$")
-plt.ylabel("$y$")
-Title="$N=$"+str(N_train)+", $\sigma=$"+str(sigma_train)
-plt.title(Title+" (train)")
-plt.tight_layout()
-plt.show()
-
@@ -527,7 +463,7 @@ plt.show()
- + + +
+Since \( \lambda \geq 0 \), it means that compared to OLS, we have - -
# Generate Test Data
+$$
+\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1.
+$$
-#Number of test data
-N_test=20
+
+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} \).
-sigma_test=sigma_train
+
+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.
-max_x=1.2
-x_test=max_x*np.random.random(N_test)
-# Draw random noise
-s_test = sigma_test*np.random.randn(N_test)
-
-#Linear
-y_test=2*x_test+s_test
-#Tenth order
-#y_test=2*x_test-10*x_test**5+15*x_test**10+s_test
-
-#Make design matrices for prediction
-x_plot=np.linspace(0,max_x, 200)
-X3 = poly3.fit_transform(x_plot[:,np.newaxis])
-X10 = poly10.fit_transform(x_plot[:,np.newaxis])
-
-%matplotlib notebook
-
-fig = plt.figure()
-p1=plt.plot(x_test,y_test.transpose(), 'o', ms=12, label='data')
-p2=plt.plot(x_plot,clf.predict(x_plot[:,np.newaxis]), label='linear')
-p3=plt.plot(x_plot,clf3.predict(X3), label='3rd order')
-p10=plt.plot(x_plot,clf10.predict(X10), label='10th order')
-
-
-plt.legend(loc=2)
-plt.xlabel('$x$')
-plt.ylabel('$y$')
-plt.legend(loc='best')
-plt.title(Title+" (pred.)")
-plt.tight_layout()
-plt.show()
-
@@ -483,7 +428,7 @@ plt.show()
-In Ridge regression and the subsequent discussion of its properties -the bias or penalty parameter is considered known or `given'. In -practice, it is unknown and the user needs to make an informed -decision on its value. How do we do that? Much of the same considerations apply to the Lasso method. +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.
@@ -448,7 +441,7 @@ decision on its value. How do we do that? Much of the same considerations apply
+Before we proceed, we need to rethink what we have been doing. In our +eager to fit the data, we have omitted several important elements in +our regression analysis. In what follows we will - -
import matplotlib.pyplot as plt
-import numpy as np
-from sklearn import linear_model
-from sklearn.linear_model import LinearRegression
-from sklearn.metrics import mean_squared_error, r2_score
+
+- look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff
+- introduce resampling techniques like cross-validation, bootstrapping and jackknife and more
+
-#creating data with random noise
-x=np.arange(50)
+This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods.
-delta=np.random.uniform(-2.5,2.5, size=(50))
-np.random.shuffle(delta)
-y =0.5*x+5+delta
-
-#arranging data into 2x50 matrix
-a=np.array(x) #inputs
-b=np.array(y) #outputs
-
-#Split into training and test
-X_train=a[:37, np.newaxis]
-X_test=a[37:, np.newaxis]
-y_train=b[:37]
-y_test=b[37:]
-
-print ("X_train: ", X_train.shape)
-print ("y_train: ", y_train.shape)
-print ("X_test: ", X_test.shape)
-print ("y_test: ", y_test.shape)
-
-print ("------------------------------------")
-
-print ("Ordinary Least Squares")
-#Add Ordinary Least Squares fit
-reg=LinearRegression()
-reg.fit(X_train, y_train)
-pred=reg.predict(X_test)
-print ("Prediction Shape: ", pred.shape)
-
-print('Coefficients: \n', reg.coef_)
-# The mean squared error
-print("Mean squared error: %.2f"
- % mean_squared_error(y_test, pred))
-# Explained variance score: 1 is perfect prediction
-print('Variance score: %.2f' % r2_score(y_test, pred))
-
-#plot
-plt.scatter(X_test,y_test,color='green', label="Training Data")
-plt.plot(X_test, pred, color='black', label="Fit Line")
-plt.legend()
-plt.show()
-
-print ("------------------------------------")
-
-print ("Ridge Regression")
-
-ridge=linear_model.RidgeCV(alphas=[0.1,1.0,10.0])
-ridge.fit(X_train,y_train)
-print ("Ridge Coefficient: ",ridge.coef_)
-print ("Ridge Intercept: ", ridge.intercept_)
-#Look into graphing with Ridge fit
-
-print ("------------------------------------")
-
-print ("Lasso")
-lasso=linear_model.Lasso(alpha=0.1)
-lasso.fit(X_train,y_train)
-predl=lasso.predict(X_test)
-print("Lasso Coefficient: ", lasso.coef_)
-print("Lasso Intercept: ", lasso.intercept_)
-plt.scatter(X_test,y_test,color='green', label="Training Data")
-plt.plot(X_test, predl, color='blue', label="Lasso")
-plt.legend()
-plt.show()
-
@@ -518,7 +421,7 @@ plt.show()
- - -
import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.linear_model import Ridge
-from sklearn.metrics import r2_score
-
-np.random.seed(4155)
-
-n_samples = 100
-
-x = np.random.rand(n_samples,1)
-y = 5*x*x + 0.1*np.random.rand(n_samples,1)
-
-# Centering x and y.
-x_ = x - np.mean(x)
-y_ = y - np.mean(y) # beta_0 = mean(y)
-
-X = np.c_[np.ones((n_samples,1)), x, x**2]
-X_ = np.c_[x_, x_**2]
+Resampling methods
+
+
+
+Resampling methods are an indispensable tool in modern
+statistics. They involve repeatedly drawing samples from a training
+set and refitting a model of interest on each sample in order to
+obtain additional information about the fitted model. For example, in
+order to estimate the variability of a linear regression fit, we can
+repeatedly draw different samples from the training data, fit a linear
+regression to each new sample, and then examine the extent to which
+the resulting fits differ. Such an approach may allow us to obtain
+information that would not be available from fitting the model only
+once using the original training sample.
+
+
-### 1.
-lmb_values = [1e-4, 1e-3, 1e-2, 10, 1e2, 1e4]
-num_values = len(lmb_values)
-
-## Ridge-regression of centered and not centered data
-beta_ridge = np.zeros((3,num_values))
-beta_ridge_centered = np.zeros((3,num_values))
-
-I3 = np.eye(3)
-I2 = np.eye(2)
-
-for i,lmb in enumerate(lmb_values):
- beta_ridge[:,i] = (np.linalg.inv( X.T @ X + lmb*I3) @ X.T @ y).flatten()
- beta_ridge_centered[1:,i] = (np.linalg.inv( X_.T @ X_ + lmb*I2) @ X_.T @ y_).flatten()
-
-# sett beta_0 = np.mean(y)
-beta_ridge_centered[0,:] = np.mean(y)
-
-## OLS (ordinary least squares) solution
-beta_ls = np.linalg.inv( X.T @ X ) @ X.T @ y
-
-## Evaluate the models
-pred_ls = X @ beta_ls
-pred_ridge = X @ beta_ridge
-pred_ridge_centered = X_ @ beta_ridge_centered[1:] + beta_ridge_centered[0,:]
-
-## Plot the results
-
-# Sorting
-sort_ind = np.argsort(x[:,0])
-
-x_plot = x[sort_ind,0]
-x_centered_plot = x_[sort_ind,0]
-
-pred_ls_plot = pred_ls[sort_ind,0]
-pred_ridge_plot = pred_ridge[sort_ind,:]
-pred_ridge_centered_plot = pred_ridge_centered[sort_ind,:]
-
-# Plott not centered
-plt.plot(x_plot,pred_ls_plot,label='ls')
-
-for i in range(num_values):
- plt.plot(x_plot,pred_ridge_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])
-
-plt.plot(x,y,'ro')
-
-plt.title('linear regression on un-centered data')
-plt.legend()
-
-# Plott centered
-plt.figure()
-
-for i in range(num_values):
- plt.plot(x_centered_plot,pred_ridge_centered_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])
-
-plt.plot(x_,y,'ro')
-
-plt.title('linear regression on centered data')
-plt.legend()
-
-
-# 2.
-
-pred_ridge_scikit = np.zeros((n_samples,num_values))
-for i,lmb in enumerate(lmb_values):
- pred_ridge_scikit[:,i] = (Ridge(alpha=lmb,fit_intercept=False).fit(X,y).predict(X)).flatten() # fit_intercept=False fordi bias er allerede i X
-
-plt.figure()
-
-plt.plot(x_plot,pred_ls_plot,label='ls')
-
-for i in range(num_values):
- plt.plot(x_plot,pred_ridge_scikit[sort_ind,i],label='scikit-ridge, lmb=%g'%lmb_values[i])
-
-plt.plot(x,y,'ro')
-plt.legend()
-plt.title('linear regression using scikit')
-
-plt.show()
-
-### R2-score of the results
-for i in range(num_values):
- print('lambda = %g'%lmb_values[i])
- print('r2 for scikit: %g'%r2_score(y,pred_ridge_scikit[:,i]))
- print('r2 for own code, not centered: %g'%r2_score(y,pred_ridge[:,i]))
- print('r2 for own, centered: %g\n'%r2_score(y,pred_ridge_centered[:,i]))
-
@@ -551,7 +425,7 @@ plt.show()
-Resampling methods are an indispensable tool in modern -statistics. They involve repeatedly drawing samples from a training -set and refitting a model of interest on each sample in order to -obtain additional information about the fitted model. For example, in -order to estimate the variability of a linear regression fit, we can -repeatedly draw different samples from the training data, fit a linear -regression to each new sample, and then examine the extent to which -the resulting fits differ. Such an approach may allow us to obtain -information that would not be available from fitting the model only -once using the original training sample. + +
+Resampling approaches can be computationally expensive, because they +involve fitting the same statistical method multiple times using +different subsets of the training data. However, due to recent +advances in computing power, the computational requirements of +resampling methods generally are not prohibitive. In this chapter, we +discuss two of the most commonly used resampling methods, +cross-validation and the bootstrap. Both methods are important tools +in the practical application of many statistical learning +procedures. For example, cross-validation can be used to estimate the +test error associated with a given statistical learning method in +order to evaluate its performance, or to select the appropriate level +of flexibility. The process of evaluating a model’s performance is +known as model assessment, whereas the process of selecting the proper +level of flexibility for a model is known as model selection. The +bootstrap is widely used. + +
-Resampling approaches can be computationally expensive, because they -involve fitting the same statistical method multiple times using -different subsets of the training data. However, due to recent -advances in computing power, the computational requirements of -resampling methods generally are not prohibitive. In this chapter, we -discuss two of the most commonly used resampling methods, -cross-validation and the bootstrap. Both methods are important tools -in the practical application of many statistical learning -procedures. For example, cross-validation can be used to estimate the -test error associated with a given statistical learning method in -order to evaluate its performance, or to select the appropriate level -of flexibility. The process of evaluating a model’s performance is -known as model assessment, whereas the process of selecting the proper -level of flexibility for a model is known as model selection. The -bootstrap is widely used. + +
+The probability distribution function (PDF) is a function +\( p(x) \) on the domain which, in the discrete case, gives us the +probability or relative frequency with which these values of \( X \) occur: +$$ +p(x) = \mathrm{prob}(X=x) +$$ -
-The probability distribution function (PDF) is a function -\( p(x) \) on the domain which, in the discrete case, gives us the -probability or relative frequency with which these values of \( X \) occur: +A particularly useful class of special expectation values are the +moments. The \( n \)-th moment of the PDF \( p \) is defined as +follows: $$ -p(x) = \mathrm{prob}(X=x) +\langle x^n\rangle \equiv \int\! x^n p(x)\,dx $$ -In the continuous case, the PDF does not directly depict the -actual probability. Instead we define the probability for the -stochastic variable to assume any value on an infinitesimal interval -around \( x \) to be \( p(x)dx \). The continuous function \( p(x) \) then gives us -the density of the probability rather than the probability -itself. The probability for a stochastic variable to assume any value -on a non-infinitesimal interval \( [a,\,b] \) is then just the integral: +The zero-th moment \( \langle 1\rangle \) is just the normalization condition of +\( p \). The first moment, \( \langle x\rangle \), is called the mean of \( p \) +and often denoted by the letter \( \mu \): $$ -\mathrm{prob}(a\leq X\leq b) = \int_a^b p(x)dx +\langle x\rangle = \mu \equiv \int\! x p(x)\,dx $$ - -Qualitatively speaking, a stochastic variable represents the values of -numbers chosen as if by chance from some specified PDF so that the -selection of a large set of these numbers reproduces this PDF.
-A particularly useful class of special expectation values are the -moments. The \( n \)-th moment of the PDF \( p \) is defined as -follows: +A special version of the moments is the set of central moments, +the n-th central moment defined as: $$ -\langle x^n\rangle \equiv \int\! x^n p(x)\,dx +\langle (x-\langle x \rangle )^n\rangle \equiv \int\! (x-\langle x\rangle)^n p(x)\,dx $$ -The zero-th moment \( \langle 1\rangle \) is just the normalization condition of -\( p \). The first moment, \( \langle x\rangle \), is called the mean of \( p \) -and often denoted by the letter \( \mu \): +The zero-th and first central moments are both trivial, equal \( 1 \) and +\( 0 \), respectively. But the second central moment, known as the +variance of \( p \), is of particular interest. For the stochastic +variable \( X \), the variance is denoted as \( \sigma^2_X \) or \( \mathrm{var}(X) \): $$ -\langle x\rangle = \mu \equiv \int\! x p(x)\,dx +\begin{align} +\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle = +\int\! (x-\langle x\rangle)^2 p(x)\,dx +\tag{8}\\ +& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} + + \langle x\rangle^2\right)p(x)\,dx +\tag{9}\\ +& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2 +\tag{10}\\ +& = \langle x^2\rangle - \langle x\rangle^2 +\tag{11} +\end{align} $$ + +The square root of the variance, \( \sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle} \) is called the standard deviation of \( p \). It is clearly just the RMS (root-mean-square) +value of the deviation of the PDF from its mean value, interpreted +qualitatively as the spread of \( p \) around its mean.
-A special version of the moments is the set of central moments, -the n-th central moment defined as: -$$ -\langle (x-\langle x \rangle )^n\rangle \equiv \int\! (x-\langle x\rangle)^n p(x)\,dx -$$ - -The zero-th and first central moments are both trivial, equal \( 1 \) and -\( 0 \), respectively. But the second central moment, known as the -variance of \( p \), is of particular interest. For the stochastic -variable \( X \), the variance is denoted as \( \sigma^2_X \) or \( \mathrm{var}(X) \): +Another important quantity is the so called covariance, a variant of +the above defined variance. Consider again the set \( \{X_i\} \) of \( n \) +stochastic variables (not necessarily uncorrelated) with the +multivariate PDF \( P(x_1,\dots,x_n) \). The covariance of two +of the stochastic variables, \( X_i \) and \( X_j \), is defined as follows: $$ \begin{align} -\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle = -\int\! (x-\langle x\rangle)^2 p(x)\,dx -\tag{2}\\ -& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} + - \langle x\rangle^2\right)p(x)\,dx -\tag{3}\\ -& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2 -\tag{4}\\ -& = \langle x^2\rangle - \langle x\rangle^2 -\tag{5} +\mathrm{cov}(X_i,\,X_j) &\equiv \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle +\nonumber\\ +&= +\int\!\cdots\!\int\!(x_i-\langle x_i \rangle)(x_j-\langle x_j \rangle)\, +P(x_1,\dots,x_n)\,dx_1\dots dx_n +\tag{12} \end{align} $$ -The square root of the variance, \( \sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle} \) is called the standard deviation of \( p \). It is clearly just the RMS (root-mean-square) -value of the deviation of the PDF from its mean value, interpreted -qualitatively as the spread of \( p \) around its mean. +with +$$ +\langle x_i\rangle = +\int\!\cdots\!\int\!x_i\,P(x_1,\dots,x_n)\,dx_1\dots dx_n +$$
-Another important quantity is the so called covariance, a variant of -the above defined variance. Consider again the set \( \{X_i\} \) of \( n \) -stochastic variables (not necessarily uncorrelated) with the -multivariate PDF \( P(x_1,\dots,x_n) \). The covariance of two -of the stochastic variables, \( X_i \) and \( X_j \), is defined as follows: +If we consider the above covariance as a matrix \( C_{ij}=\mathrm{cov}(X_i,\,X_j) \), then the diagonal elements are just the familiar +variances, \( C_{ii} = \mathrm{cov}(X_i,\,X_i) = \mathrm{var}(X_i) \). It turns out that +all the off-diagonal elements are zero if the stochastic variables are +uncorrelated. This is easy to show, keeping in mind the linearity of +the expectation value. Consider the stochastic variables \( X_i \) and +\( X_j \), (\( i\neq j \)): $$ \begin{align} -\mathrm{cov}(X_i,\,X_j) &\equiv \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\nonumber\\ -&= -\int\!\cdots\!\int\!(x_i-\langle x_i \rangle)(x_j-\langle x_j \rangle)\, -P(x_1,\dots,x_n)\,dx_1\dots dx_n -\tag{6} +\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle +\tag{13}\\ +&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle +\tag{14}\\ +&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle + +\langle \langle x_i\rangle\langle x_j\rangle\rangle +\tag{15}\\ +&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + +\langle x_i\rangle\langle x_j\rangle +\tag{16}\\ +&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle +\tag{17} \end{align} $$ - -with -$$ -\langle x_i\rangle = -\int\!\cdots\!\int\!x_i\,P(x_1,\dots,x_n)\,dx_1\dots dx_n -$$
-If we consider the above covariance as a matrix \( C_{ij}=\mathrm{cov}(X_i,\,X_j) \), then the diagonal elements are just the familiar -variances, \( C_{ii} = \mathrm{cov}(X_i,\,X_i) = \mathrm{var}(X_i) \). It turns out that -all the off-diagonal elements are zero if the stochastic variables are -uncorrelated. This is easy to show, keeping in mind the linearity of -the expectation value. Consider the stochastic variables \( X_i \) and -\( X_j \), (\( i\neq j \)): +If \( X_i \) and \( X_j \) are independent, we get +\( \langle x_i x_j\rangle =\langle x_i\rangle\langle x_j\rangle \), resulting in \( \mathrm{cov}(X_i, X_j) = 0\ \ (i\neq j) \). + +
+Also useful for us is the covariance of linear combinations of +stochastic variables. Let \( \{X_i\} \) and \( \{Y_i\} \) be two sets of +stochastic variables. Let also \( \{a_i\} \) and \( \{b_i\} \) be two sets of +scalars. Consider the linear combination: $$ -\begin{align} -\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\tag{7}\\ -&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle -\tag{8}\\ -&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle + -\langle \langle x_i\rangle\langle x_j\rangle\rangle -\tag{9}\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + -\langle x_i\rangle\langle x_j\rangle -\tag{10}\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle -\tag{11} -\end{align} +U = \sum_i a_i X_i \qquad V = \sum_j b_j Y_j +$$ + +By the linearity of the expectation value +$$ +\mathrm{cov}(U, V) = \sum_{i,j}a_i b_j \mathrm{cov}(X_i, Y_j) $$
-If \( X_i \) and \( X_j \) are independent, we get -\( \langle x_i x_j\rangle =\langle x_i\rangle\langle x_j\rangle \), resulting in \( \mathrm{cov}(X_i, X_j) = 0\ \ (i\neq j) \). - -
-Also useful for us is the covariance of linear combinations of -stochastic variables. Let \( \{X_i\} \) and \( \{Y_i\} \) be two sets of -stochastic variables. Let also \( \{a_i\} \) and \( \{b_i\} \) be two sets of -scalars. Consider the linear combination: +Now, since the variance is just \( \mathrm{var}(X_i) = \mathrm{cov}(X_i, X_i) \), we get +the variance of the linear combination \( U = \sum_i a_i X_i \): $$ -U = \sum_i a_i X_i \qquad V = \sum_j b_j Y_j +\begin{equation} +\mathrm{var}(U) = \sum_{i,j}a_i a_j \mathrm{cov}(X_i, X_j) +\tag{18} +\end{equation} $$ -By the linearity of the expectation value +And in the special case when the stochastic variables are +uncorrelated, the off-diagonal elements of the covariance are as we +know zero, resulting in: $$ -\mathrm{cov}(U, V) = \sum_{i,j}a_i b_j \mathrm{cov}(X_i, Y_j) +\mathrm{var}(U) = \sum_i a_i^2 \mathrm{cov}(X_i, X_i) = \sum_i a_i^2 \mathrm{var}(X_i) $$ + +$$ +\mathrm{var}(\sum_i a_i X_i) = \sum_i a_i^2 \mathrm{var}(X_i) +$$ + +which will become very useful in our study of the error in the mean +value of a set of measurements.
-Now, since the variance is just \( \mathrm{var}(X_i) = \mathrm{cov}(X_i, X_i) \), we get -the variance of the linear combination \( U = \sum_i a_i X_i \): +A stochastic process is a process that produces sequentially a +chain of values: $$ -\begin{equation} -\mathrm{var}(U) = \sum_{i,j}a_i a_j \mathrm{cov}(X_i, X_j) -\tag{12} -\end{equation} +\{x_1, x_2,\dots\,x_k,\dots\}. $$ -And in the special case when the stochastic variables are -uncorrelated, the off-diagonal elements of the covariance are as we -know zero, resulting in: -$$ -\mathrm{var}(U) = \sum_i a_i^2 \mathrm{cov}(X_i, X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -$$ - -$$ -\mathrm{var}(\sum_i a_i X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -$$ - -which will become very useful in our study of the error in the mean -value of a set of measurements. +We will call these +values our measurements and the entire set as our measured +sample. The action of measuring all the elements of a sample +we will call a stochastic experiment since, operationally, +they are often associated with results of empirical observation of +some physical or mathematical phenomena; precisely an experiment. We +assume that these values are distributed according to some +PDF \( p_X^{\phantom X}(x) \), where \( X \) is just the formal symbol for the +stochastic variable whose PDF is \( p_X^{\phantom X}(x) \). Instead of +trying to determine the full distribution \( p \) we are often only +interested in finding the few lowest moments, like the mean +\( \mu_X^{\phantom X} \) and the variance \( \sigma_X^{\phantom X} \).
- + -
-A stochastic process is a process that produces sequentially a -chain of values: +In practical situations a sample is always of finite size. Let that +size be \( n \). The expectation value of a sample, the sample mean, is then defined as follows: $$ -\{x_1, x_2,\dots\,x_k,\dots\}. +\bar{x}_n \equiv \frac{1}{n}\sum_{k=1}^n x_k $$ -We will call these -values our measurements and the entire set as our measured -sample. The action of measuring all the elements of a sample -we will call a stochastic experiment since, operationally, -they are often associated with results of empirical observation of -some physical or mathematical phenomena; precisely an experiment. We -assume that these values are distributed according to some -PDF \( p_X^{\phantom X}(x) \), where \( X \) is just the formal symbol for the -stochastic variable whose PDF is \( p_X^{\phantom X}(x) \). Instead of -trying to determine the full distribution \( p \) we are often only -interested in finding the few lowest moments, like the mean -\( \mu_X^{\phantom X} \) and the variance \( \sigma_X^{\phantom X} \). +The sample variance is: +$$ +\mathrm{var}(x) \equiv \frac{1}{n}\sum_{k=1}^n (x_k - \bar{x}_n)^2 +$$ + +its square root being the standard deviation of the sample. The +sample covariance is: +$$ +\mathrm{cov}(x)\equiv\frac{1}{n}\sum_{kl}(x_k - \bar{x}_n)(x_l - \bar{x}_n) +$$
- + -
-In practical situations a sample is always of finite size. Let that -size be \( n \). The expectation value of a sample, the sample mean, is then defined as follows: -$$ -\bar{x}_n \equiv \frac{1}{n}\sum_{k=1}^n x_k -$$ +Note that the sample variance is the sample covariance without the +cross terms. In a similar manner as the covariance in Eq. (12) is a measure of the correlation between +two stochastic variables, the above defined sample covariance is a +measure of the sequential correlation between succeeding measurements +of a sample. -The sample variance is: -$$ -\mathrm{var}(x) \equiv \frac{1}{n}\sum_{k=1}^n (x_k - \bar{x}_n)^2 -$$ - -its square root being the standard deviation of the sample. The -sample covariance is: -$$ -\mathrm{cov}(x)\equiv\frac{1}{n}\sum_{kl}(x_k - \bar{x}_n)(x_l - \bar{x}_n) -$$ +
+These quantities, being known experimental values, differ +significantly from and must not be confused with the similarly named +quantities for stochastic variables, mean \( \mu_X \), variance \( \mathrm{var}(X) \) +and covariance \( \mathrm{cov}(X,Y) \).
-Note that the sample variance is the sample covariance without the -cross terms. In a similar manner as the covariance in Eq. (6) is a measure of the correlation between -two stochastic variables, the above defined sample covariance is a -measure of the sequential correlation between succeeding measurements -of a sample. +The law of large numbers +states that as the size of our sample grows to infinity, the sample +mean approaches the true mean \( \mu_X^{\phantom X} \) of the chosen PDF: +$$ +\lim_{n\to\infty}\bar{x}_n = \mu_X^{\phantom X} +$$ + +The sample mean \( \bar{x}_n \) works therefore as an estimate of the true +mean \( \mu_X^{\phantom X} \).
-These quantities, being known experimental values, differ -significantly from and must not be confused with the similarly named -quantities for stochastic variables, mean \( \mu_X \), variance \( \mathrm{var}(X) \) -and covariance \( \mathrm{cov}(X,Y) \). +What we need to find out is how good an approximation \( \bar{x}_n \) is to +\( \mu_X^{\phantom X} \). In any stochastic measurement, an estimated +mean is of no use to us without a measure of its error. A quantity +that tells us how well we can reproduce it in another experiment. We +are therefore interested in the PDF of the sample mean itself. Its +standard deviation will be a measure of the spread of sample means, +and we will simply call it the error of the sample mean, or +just sample error, and denote it by \( \mathrm{err}_X^{\phantom X} \). In +practice, we will only be able to produce an estimate of the +sample error since the exact value would require the knowledge of the +true PDFs behind, which we usually do not have.
-The law of large numbers -states that as the size of our sample grows to infinity, the sample -mean approaches the true mean \( \mu_X^{\phantom X} \) of the chosen PDF: +Let us first take a look at what happens to the sample error as the +size of the sample grows. In a sample, each of the measurements \( x_i \) +can be associated with its own stochastic variable \( X_i \). The +stochastic variable \( \overline X_n \) for the sample mean \( \bar{x}_n \) is +then just a linear combination, already familiar to us: $$ -\lim_{n\to\infty}\bar{x}_n = \mu_X^{\phantom X} +\overline X_n = \frac{1}{n}\sum_{i=1}^n X_i $$ -The sample mean \( \bar{x}_n \) works therefore as an estimate of the true -mean \( \mu_X^{\phantom X} \). - -
-What we need to find out is how good an approximation \( \bar{x}_n \) is to -\( \mu_X^{\phantom X} \). In any stochastic measurement, an estimated -mean is of no use to us without a measure of its error. A quantity -that tells us how well we can reproduce it in another experiment. We -are therefore interested in the PDF of the sample mean itself. Its -standard deviation will be a measure of the spread of sample means, -and we will simply call it the error of the sample mean, or -just sample error, and denote it by \( \mathrm{err}_X^{\phantom X} \). In -practice, we will only be able to produce an estimate of the -sample error since the exact value would require the knowledge of the -true PDFs behind, which we usually do not have. +All the coefficients are just equal \( 1/n \). The PDF of \( \overline X_n \), +denoted by \( p_{\overline X_n}(x) \) is the desired PDF of the sample +means.
-Let us first take a look at what happens to the sample error as the -size of the sample grows. In a sample, each of the measurements \( x_i \) -can be associated with its own stochastic variable \( X_i \). The -stochastic variable \( \overline X_n \) for the sample mean \( \bar{x}_n \) is -then just a linear combination, already familiar to us: +The probability density of obtaining a sample mean \( \bar x_n \) +is the product of probabilities of obtaining arbitrary values \( x_1, +x_2,\dots,x_n \) with the constraint that the mean of the set \( \{x_i\} \) +is \( \bar x_n \): $$ -\overline X_n = \frac{1}{n}\sum_{i=1}^n X_i +p_{\overline X_n}(x) = \int p_X^{\phantom X}(x_1)\cdots +\int p_X^{\phantom X}(x_n)\ +\delta\!\left(x - \frac{x_1+x_2+\dots+x_n}{n}\right)dx_n \cdots dx_1 $$ -All the coefficients are just equal \( 1/n \). The PDF of \( \overline X_n \), -denoted by \( p_{\overline X_n}(x) \) is the desired PDF of the sample -means. +And in particular we are interested in its variance \( \mathrm{var}(\overline X_n) \).
-The probability density of obtaining a sample mean \( \bar x_n \) -is the product of probabilities of obtaining arbitrary values \( x_1, -x_2,\dots,x_n \) with the constraint that the mean of the set \( \{x_i\} \) -is \( \bar x_n \): +It is generally not possible to express \( p_{\overline X_n}(x) \) in a +closed form given an arbitrary PDF \( p_X^{\phantom X} \) and a number +\( n \). But for the limit \( n\to\infty \) it is possible to make an +approximation. The very important result is called the central limit theorem. It tells us that as \( n \) goes to infinity, +\( p_{\overline X_n}(x) \) approaches a Gaussian distribution whose mean +and variance equal the true mean and variance, \( \mu_{X}^{\phantom X} \) +and \( \sigma_{X}^{2} \), respectively: $$ -p_{\overline X_n}(x) = \int p_X^{\phantom X}(x_1)\cdots -\int p_X^{\phantom X}(x_n)\ -\delta\!\left(x - \frac{x_1+x_2+\dots+x_n}{n}\right)dx_n \cdots dx_1 +\begin{equation} +\lim_{n\to\infty} p_{\overline X_n}(x) = +\left(\frac{n}{2\pi\mathrm{var}(X)}\right)^{1/2} +e^{-\frac{n(x-\bar x_n)^2}{2\mathrm{var}(X)}} +\tag{19} +\end{equation} $$ - -And in particular we are interested in its variance \( \mathrm{var}(\overline X_n) \).
-It is generally not possible to express \( p_{\overline X_n}(x) \) in a -closed form given an arbitrary PDF \( p_X^{\phantom X} \) and a number -\( n \). But for the limit \( n\to\infty \) it is possible to make an -approximation. The very important result is called the central limit theorem. It tells us that as \( n \) goes to infinity, -\( p_{\overline X_n}(x) \) approaches a Gaussian distribution whose mean -and variance equal the true mean and variance, \( \mu_{X}^{\phantom X} \) -and \( \sigma_{X}^{2} \), respectively: +The desired variance +\( \mathrm{var}(\overline X_n) \), i.e. the sample error squared +\( \mathrm{err}_X^2 \), is given by: $$ \begin{equation} -\lim_{n\to\infty} p_{\overline X_n}(x) = -\left(\frac{n}{2\pi\mathrm{var}(X)}\right)^{1/2} -e^{-\frac{n(x-\bar x_n)^2}{2\mathrm{var}(X)}} -\tag{13} +\mathrm{err}_X^2 = \mathrm{var}(\overline X_n) = \frac{1}{n^2} +\sum_{ij} \mathrm{cov}(X_i, X_j) +\tag{20} \end{equation} $$ + +We see now that in order to calculate the exact error of the sample +with the above expression, we would need the true means +\( \mu_{X_i}^{\phantom X} \) of the stochastic variables \( X_i \). To +calculate these requires that we know the true multivariate PDF of all +the \( X_i \). But this PDF is unknown to us, we have only got the measurements of +one sample. The best we can do is to let the sample itself be an +estimate of the PDF of each of the \( X_i \), estimating all properties of +\( X_i \) through the measurements of the sample.
-The desired variance -\( \mathrm{var}(\overline X_n) \), i.e. the sample error squared -\( \mathrm{err}_X^2 \), is given by: +Our estimate of \( \mu_{X_i}^{\phantom X} \) is then the sample mean \( \bar x \) +itself, in accordance with the the central limit theorem: $$ -\begin{equation} -\mathrm{err}_X^2 = \mathrm{var}(\overline X_n) = \frac{1}{n^2} -\sum_{ij} \mathrm{cov}(X_i, X_j) -\tag{14} -\end{equation} +\mu_{X_i}^{\phantom X} = \langle x_i\rangle \approx \frac{1}{n}\sum_{k=1}^n x_k = \bar x $$ -We see now that in order to calculate the exact error of the sample -with the above expression, we would need the true means -\( \mu_{X_i}^{\phantom X} \) of the stochastic variables \( X_i \). To -calculate these requires that we know the true multivariate PDF of all -the \( X_i \). But this PDF is unknown to us, we have only got the measurements of -one sample. The best we can do is to let the sample itself be an -estimate of the PDF of each of the \( X_i \), estimating all properties of -\( X_i \) through the measurements of the sample. +Using \( \bar x \) in place of \( \mu_{X_i}^{\phantom X} \) we can give an +estimate of the covariance in Eq. (20) +$$ +\mathrm{cov}(X_i, X_j) = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle +\approx\langle (x_i - \bar x)(x_j - \bar{x})\rangle, +$$ + +resulting in +$$ +\frac{1}{n} \sum_{l}^n \left(\frac{1}{n}\sum_{k}^n (x_k -\bar x_n)(x_l - \bar x_n)\right)=\frac{1}{n}\frac{1}{n} \sum_{kl} (x_k -\bar x_n)(x_l - \bar x_n)=\frac{1}{n}\mathrm{cov}(x) +$$
-Our estimate of \( \mu_{X_i}^{\phantom X} \) is then the sample mean \( \bar x \) -itself, in accordance with the the central limit theorem: +By the same procedure we can use the sample variance as an +estimate of the variance of any of the stochastic variables \( X_i \) $$ -\mu_{X_i}^{\phantom X} = \langle x_i\rangle \approx \frac{1}{n}\sum_{k=1}^n x_k = \bar x +\mathrm{var}(X_i)=\langle x_i - \langle x_i\rangle\rangle \approx \langle x_i - \bar x_n\rangle\nonumber, $$ -Using \( \bar x \) in place of \( \mu_{X_i}^{\phantom X} \) we can give an -estimate of the covariance in Eq. (14) +which is approximated as $$ -\mathrm{cov}(X_i, X_j) = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\approx\langle (x_i - \bar x)(x_j - \bar{x})\rangle, +\begin{equation} +\mathrm{var}(X_i)\approx \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)=\mathrm{var}(x) +\tag{21} +\end{equation} $$ -resulting in -$$ -\frac{1}{n} \sum_{l}^n \left(\frac{1}{n}\sum_{k}^n (x_k -\bar x_n)(x_l - \bar x_n)\right)=\frac{1}{n}\frac{1}{n} \sum_{kl} (x_k -\bar x_n)(x_l - \bar x_n)=\frac{1}{n}\mathrm{cov}(x) +
+Now we can calculate an estimate of the error +\( \mathrm{err}_X^{\phantom X} \) of the sample mean \( \bar x_n \): $$ +\begin{align} +\mathrm{err}_X^2 +&=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) \nonumber \\ +&\approx&\frac{1}{n^2}\sum_{ij}\frac{1}{n}\mathrm{cov}(x) =\frac{1}{n^2}n^2\frac{1}{n}\mathrm{cov}(x)\nonumber\\ +&=\frac{1}{n}\mathrm{cov}(x) +\tag{22} +\end{align} +$$ + +which is nothing but the sample covariance divided by the number of +measurements in the sample.
-By the same procedure we can use the sample variance as an -estimate of the variance of any of the stochastic variables \( X_i \) + +
+In the special case that the measurements of the sample are +uncorrelated (equivalently the stochastic variables \( X_i \) are +uncorrelated) we have that the off-diagonal elements of the covariance +are zero. This gives the following estimate of the sample error: $$ -\mathrm{var}(X_i)=\langle x_i - \langle x_i\rangle\rangle \approx \langle x_i - \bar x_n\rangle\nonumber, +\mathrm{err}_X^2=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) = +\frac{1}{n^2} \sum_i \mathrm{var}(X_i), $$ -which is approximated as +resulting in $$ \begin{equation} -\mathrm{var}(X_i)\approx \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)=\mathrm{var}(x) -\tag{15} +\mathrm{err}_X^2\approx \frac{1}{n^2} \sum_i \mathrm{var}(x)= \frac{1}{n}\mathrm{var}(x) +\tag{23} \end{equation} $$ -
-Now we can calculate an estimate of the error -\( \mathrm{err}_X^{\phantom X} \) of the sample mean \( \bar x_n \): -$$ -\begin{align} -\mathrm{err}_X^2 -&=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) \nonumber \\ -&\approx&\frac{1}{n^2}\sum_{ij}\frac{1}{n}\mathrm{cov}(x) =\frac{1}{n^2}n^2\frac{1}{n}\mathrm{cov}(x)\nonumber\\ -&=\frac{1}{n}\mathrm{cov}(x) -\tag{16} -\end{align} -$$ - -which is nothing but the sample covariance divided by the number of -measurements in the sample. +where in the second step we have used Eq. (21). +The error of the sample is then just its standard deviation divided by +the square root of the number of measurements the sample contains. +This is a very useful formula which is easy to compute. It acts as a +first approximation to the error, but in numerical experiments, we +cannot overlook the always present correlations.
- -
-In the special case that the measurements of the sample are -uncorrelated (equivalently the stochastic variables \( X_i \) are -uncorrelated) we have that the off-diagonal elements of the covariance -are zero. This gives the following estimate of the sample error: +For computational purposes one usually splits up the estimate of +\( \mathrm{err}_X^2 \), given by Eq. (22), into two +parts $$ -\mathrm{err}_X^2=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) = -\frac{1}{n^2} \sum_i \mathrm{var}(X_i), +\mathrm{err}_X^2 = \frac{1}{n}\mathrm{var}(x) + \frac{1}{n}(\mathrm{cov}(x)-\mathrm{var}(x)), $$ -resulting in +which equals $$ \begin{equation} -\mathrm{err}_X^2\approx \frac{1}{n^2} \sum_i \mathrm{var}(x)= \frac{1}{n}\mathrm{var}(x) -\tag{17} +\frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) +\tag{24} \end{equation} $$ -where in the second step we have used Eq. (15). -The error of the sample is then just its standard deviation divided by -the square root of the number of measurements the sample contains. -This is a very useful formula which is easy to compute. It acts as a -first approximation to the error, but in numerical experiments, we -cannot overlook the always present correlations. +The first term is the same as the error in the uncorrelated case, +Eq. (23). This means that the second +term accounts for the error correction due to correlation between the +measurements. For uncorrelated measurements this second term is zero.
-For computational purposes one usually splits up the estimate of -\( \mathrm{err}_X^2 \), given by Eq. (16), into two -parts +Computationally the uncorrelated first term is much easier to treat +efficiently than the second. $$ -\mathrm{err}_X^2 = \frac{1}{n}\mathrm{var}(x) + \frac{1}{n}(\mathrm{cov}(x)-\mathrm{var}(x)), +\mathrm{var}(x) = \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)^2 = +\left(\frac{1}{n}\sum_{k=1}^n x_k^2\right) - \bar x_n^2 $$ -which equals -$$ -\begin{equation} -\frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) -\tag{18} -\end{equation} -$$ - -The first term is the same as the error in the uncorrelated case, -Eq. (17). This means that the second -term accounts for the error correction due to correlation between the -measurements. For uncorrelated measurements this second term is zero. +We just accumulate separately the values \( x^2 \) and \( x \) for every +measurement \( x \) we receive. The correlation term, though, has to be +calculated at the end of the experiment since we need all the +measurements to calculate the cross terms. Therefore, all measurements +have to be stored throughout the experiment.
-Computationally the uncorrelated first term is much easier to treat -efficiently than the second. +Let us analyze the problem by splitting up the correlation term into +partial sums of the form: $$ -\mathrm{var}(x) = \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)^2 = -\left(\frac{1}{n}\sum_{k=1}^n x_k^2\right) - \bar x_n^2 +f_d = \frac{1}{n-d}\sum_{k=1}^{n-d}(x_k - \bar x_n)(x_{k+d} - \bar x_n) $$ -We just accumulate separately the values \( x^2 \) and \( x \) for every -measurement \( x \) we receive. The correlation term, though, has to be -calculated at the end of the experiment since we need all the -measurements to calculate the cross terms. Therefore, all measurements -have to be stored throughout the experiment. +The correlation term of the error can now be rewritten in terms of +\( f_d \) +$$ +\frac{2}{n}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) = +2\sum_{d=1}^{n-1} f_d +$$ + +The value of \( f_d \) reflects the correlation between measurements +separated by the distance \( d \) in the sample samples. Notice that for +\( d=0 \), \( f \) is just the sample variance, \( \mathrm{var}(x) \). If we divide \( f_d \) +by \( \mathrm{var}(x) \), we arrive at the so called autocorrelation function +$$ +\kappa_d = \frac{f_d}{\mathrm{var}(x)} +$$ + +which gives us a useful measure of pairwise correlations +starting always at \( 1 \) for \( d=0 \).
-Let us analyze the problem by splitting up the correlation term into -partial sums of the form: +The sample error (see eq. (24)) can now be +written in terms of the autocorrelation function: $$ -f_d = \frac{1}{n-d}\sum_{k=1}^{n-d}(x_k - \bar x_n)(x_{k+d} - \bar x_n) +\begin{align} +\mathrm{err}_X^2 &= +\frac{1}{n}\mathrm{var}(x)+\frac{2}{n}\cdot\mathrm{var}(x)\sum_{d=1}^{n-1} +\frac{f_d}{\mathrm{var}(x)}\nonumber\\ &=& +\left(1+2\sum_{d=1}^{n-1}\kappa_d\right)\frac{1}{n}\mathrm{var}(x)\nonumber\\ +&=\frac{\tau}{n}\cdot\mathrm{var}(x) +\tag{25} +\end{align} $$ -The correlation term of the error can now be rewritten in terms of -\( f_d \) +and we see that \( \mathrm{err}_X \) can be expressed in terms the +uncorrelated sample variance times a correction factor \( \tau \) which +accounts for the correlation between measurements. We call this +correction factor the autocorrelation time: $$ -\frac{2}{n}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) = -2\sum_{d=1}^{n-1} f_d +\begin{equation} +\tau = 1+2\sum_{d=1}^{n-1}\kappa_d +\tag{26} +\end{equation} $$ - -The value of \( f_d \) reflects the correlation between measurements -separated by the distance \( d \) in the sample samples. Notice that for -\( d=0 \), \( f \) is just the sample variance, \( \mathrm{var}(x) \). If we divide \( f_d \) -by \( \mathrm{var}(x) \), we arrive at the so called autocorrelation function -$$ -\kappa_d = \frac{f_d}{\mathrm{var}(x)} -$$ - -which gives us a useful measure of pairwise correlations -starting always at \( 1 \) for \( d=0 \).
-The sample error (see eq. (18)) can now be -written in terms of the autocorrelation function: +For a correlation free experiment, \( \tau \) +equals 1. From the point of view of +eq. (25) we can interpret a sequential +correlation as an effective reduction of the number of measurements by +a factor \( \tau \). The effective number of measurements becomes: $$ -\begin{align} -\mathrm{err}_X^2 &= -\frac{1}{n}\mathrm{var}(x)+\frac{2}{n}\cdot\mathrm{var}(x)\sum_{d=1}^{n-1} -\frac{f_d}{\mathrm{var}(x)}\nonumber\\ &=& -\left(1+2\sum_{d=1}^{n-1}\kappa_d\right)\frac{1}{n}\mathrm{var}(x)\nonumber\\ -&=\frac{\tau}{n}\cdot\mathrm{var}(x) -\tag{19} -\end{align} +n_\mathrm{eff} = \frac{n}{\tau} $$ -and we see that \( \mathrm{err}_X \) can be expressed in terms the -uncorrelated sample variance times a correction factor \( \tau \) which -accounts for the correlation between measurements. We call this -correction factor the autocorrelation time: -$$ -\begin{equation} -\tau = 1+2\sum_{d=1}^{n-1}\kappa_d -\tag{20} -\end{equation} -$$ +To neglect the autocorrelation time \( \tau \) will always cause our +simple uncorrelated estimate of \( \mathrm{err}_X^2\approx \mathrm{var}(x)/n \) to +be less than the true sample error. The estimate of the error will be +too good. On the other hand, the calculation of the full +autocorrelation time poses an efficiency problem if the set of +measurements is very large.
- + -
-For a correlation free experiment, \( \tau \) -equals 1. From the point of view of -eq. (19) we can interpret a sequential -correlation as an effective reduction of the number of measurements by -a factor \( \tau \). The effective number of measurements becomes: +
+Finally, we are going to discuss several statistical properties which can be obtained in terms of analytical expressions. +The +advantage of doing linear regression is that we actually end up with +analytical expressions for several statistical quantities. +Standard least squares and Ridge regression allow us to +derive quantities like the variance and other expectation values in a +rather straightforward way. + +
+It is assumed that \( \varepsilon_i +\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are +independent, i.e.: $$ -n_\mathrm{eff} = \frac{n}{\tau} +\begin{align*} +\mbox{Cov}(\varepsilon_{i_1}, +\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if} +& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right. +\end{align*} $$ -To neglect the autocorrelation time \( \tau \) will always cause our -simple uncorrelated estimate of \( \mathrm{err}_X^2\approx \mathrm{var}(x)/n \) to -be less than the true sample error. The estimate of the error will be -too good. On the other hand, the calculation of the full -autocorrelation time poses an efficiency problem if the set of -measurements is very large. -
+Recall that \( \boldsymbol{X} \) is a matrix of dimensionality \( n\times p \). The +notation above \( \mathbf{X}_{i,\ast} \) means that we are looking at the +row number \( i \) and perform a sum over all values \( p \).
@@ -463,7 +442,7 @@ measurements is very large.
-A popular strategy is to choose a penalty parameter that yields a good -but parsimonious model. Information criteria measure the balance -between model fit and model complexity. One possibility is Aikaike's -information criterion (AIC). -The AIC measures model fit by the log-likelihood -and model complexity is measured by the number of parameters used by -the model. The number of model parameters in regular regression simply -corresponds to the number of covariates in the model. Or, by the -degrees of freedom consumed by the model, which is equivalent to the -trace of the hat matrix. For ridge regression it thus seems natural to -define model complexity analogously by the trace of the ridge hat -matrix. This yields the AIC for the linear regression model with ridge -estimates: - +The assumption we have made here can be summarized as (and this is going to useful when we discuss the bias-variance trade off) +that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \) +which describes our data $$ -\begin{align*} -\mbox{AIC}(\lambda) & = 2 \, p - 2 \log(\hat{L}) -\\ -& = 2 \, \mbox{tr} [\mathbf{H}(\lambda)] - 2 \log\{L[\hat{\beta}(\lambda), \hat{\sigma}^2(\lambda)]\} -\\ -& = 2 \, \sum_{j=1}^p \frac{d_{jj}^2}{d_{jj}^2 + \lambda} -+ 2 n \, \log[\sqrt{2 \, \pi} \, \hat{\sigma}(\lambda)] + \frac{1}{\hat{\sigma}^2(\lambda)} \sum_{i=1}^n [y_i - \mathbf{X}_{i, \ast} \, \hat{\beta}(\lambda)]^2. -\end{align*} +\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon} $$ -The value of \( \lambda \) which minimizes \( \mbox{AIC}(\lambda) \) corresponds to the `optimal' balance of model complexity and overfitting. +
+We approximate this function with our model from the solution of the linear regression equations, that is our +function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we want to minimize \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), our MSE, with +$$ +\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}. +$$
@@ -470,7 +424,7 @@ The value of \( \lambda \) which minimizes \( \mbox{AIC}(\lambda) \) corresponds
- + -
-Instead of choosing the penalty parameter to balance model fit with -model complexity, cross-validation requires it (i.e. the penalty -parameter) to yield a model with good prediction -performance. Commonly, this performance is evaluated on novel -data. Novel data need not be easy to come by and one has to make do -with the data at hand. The setting of `original' and novel data is -then mimicked by sample splitting: the data set is divided into two -(groups of samples). One of these two data sets, called the training -set, plays the role of `original' data on which the model is -built. The second of these data sets, called the test set, plays the -role of the `novel' data and is used to evaluate the prediction -performance (often operationalized as the log-likelihood or the -prediction error or its square or the R2 score) of the model built on the training data set. This -procedure (model building and prediction evaluation on training and -test set, respectively) is done for a collection of possible penalty -parameter choices. The penalty parameter that yields the model with -the best prediction performance is to be preferred. The thus obtained -performance evaluation depends on the actual split of the data set. To -remove this dependence the data set is split many times into a -training and test set. For each split the model parameters are -estimated for all choices of \( \lambda \) using the training data and -estimated parameters are evaluated on the corresponding test set. The -penalty parameter that on average over the test sets performs best (in -some sense) is then selected. +We can calculate the expectation value of \( \boldsymbol{y} \) for a given element \( i \) +$$ +\begin{align*} +\mathbb{E}(y_i) & = +\mathbb{E}(\mathbf{X}_{i, \ast} \, \boldsymbol{\beta}) + \mathbb{E}(\varepsilon_i) +\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta, +\end{align*} +$$ + +while +its variance is +$$ +\begin{align*} \mbox{Var}(y_i) & = \mathbb{E} \{ [y_i +- \mathbb{E}(y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( y_i^2 ) - +[\mathbb{E}(y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, +\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 \\ & += \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 \varepsilon_i +\mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + \varepsilon_i^2 ] - ( \mathbf{X}_{i, +\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 +\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + +\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 +\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \, +\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2. +\end{align*} +$$ + +Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with +mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \) (not be confused with the singular values of the SVD).
@@ -468,7 +439,7 @@ some sense) is then selected.
-The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks: +With the OLS expressions for the parameters \( \boldsymbol{\beta} \) we can evaluate the expectation value +$$ +\mathbb{E}(\boldsymbol{\beta}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}. +$$ -
+We can also calculate the variance + +
+The variance of \( \boldsymbol{\beta} \) is +$$ +\begin{eqnarray*} +\mbox{Var}(\boldsymbol{\beta}) & = & \mathbb{E} \{ [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})] [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})]^{T} \} +\\ +& = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}]^{T} \} +\\ +% & = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}]^{T} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +% & = & \mathbb{E} \{ (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} \, \mathbf{Y}^{T} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \mathbb{E} \{ \mathbf{Y} \, \mathbf{Y}^{T} \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +\\ +& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +% & = & (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1} +% \\ +% & & + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \boldsymbol{\beta} \boldsymbol{\beta}^T +\\ +& = & \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}, +\end{eqnarray*} +$$ + +
+where we have used that \( \mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) = +\mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + +\sigma^2 \, \mathbf{I}_{nn} \). From \( \mbox{Var}(\boldsymbol{\beta}) = \sigma^2 +\, (\mathbf{X}^{T} \mathbf{X})^{-1} \), one obtains an estimate of the +variance of the estimate of the \( j \)-th regression coefficient: +\( \hat{\sigma}^2 (\hat{\beta}_j ) = \hat{\sigma}^2 \sqrt{ +[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} } \). This may be used to +construct a confidence interval for the estimates. + +
+In a similar way, we cna obtain analytical expressions for say the +expectation values of the parameters \( \boldsymbol{\beta} \) and their variance +when we employ Ridge regression, and thereby a confidence interval. + +
+It is rather straightforward to show that +$$ +\mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\boldsymbol{\beta}^{\mathrm{OLS}}. +$$ + +We see clearly that +\( \mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big] \not= \boldsymbol{\beta}^{\mathrm{OLS}} \) for any \( \lambda > 0 \). We say then that the ridge estimator is biased. + +
+We can also compute the variance as + +$$ +\mbox{Var}[\boldsymbol{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}, +$$ + +and it is easy to see that if the parameter \( \lambda \) goes to infinity then the variance of Ridge parameters \( \boldsymbol{\beta} \) goes to zero. + +
+With this, we can compute the difference + +$$ +\mbox{Var}[\boldsymbol{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\boldsymbol{\beta}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}. +$$ + +The difference is non-negative definite since each component of the +matrix product is non-negative definite. +This means the variance we obtain with the standard OLS will always for \( \lambda > 0 \) be larger than the variance of \( \boldsymbol{\beta} \) obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. + +
-When the repetitive splitting of the data set is done randomly, -samples may accidently end up in a fast majority of the splits in -either training or test set. Such samples may have an unbalanced -influence on either model building or prediction evaluation. To avoid -this \( k \)-fold cross-validation structures the data splitting. The -samples are divided into \( k \) more or less equally sized exhaustive and -mutually exclusive subsets. In turn (at each split) one of these -subsets plays the role of the test set while the union of the -remaining subsets constitutes the training set. Such a splitting -warrants a balanced representation of each sample in both training and -test set over the splits. Still the division into the \( k \) subsets -involves a degree of randomness. This may be fully excluded when -choosing \( k=n \). This particular case is referred to as leave-one-out -cross-validation (LOOCV). +Instead of choosing the penalty parameter to balance model fit with +model complexity, cross-validation requires it (i.e. the penalty +parameter) to yield a model with good prediction +performance. Commonly, this performance is evaluated on novel +data. Novel data need not be easy to come by and one has to make do +with the data at hand. + +
+The setting of original and novel data is +then mimicked by sample splitting: the data set is divided into two +(groups of samples). One of these two data sets, called the +training set, plays the role of original data on which the model is +built. The second of these data sets, called the test set, plays the +role of the novel data and is used to evaluate the prediction +performance (often operationalized as the log-likelihood or the +prediction error or its square or the R2 score) of the model built on the training data set. This +procedure (model building and prediction evaluation on training and +test set, respectively) is done for a collection of possible penalty +parameter choices. The penalty parameter that yields the model with +the best prediction performance is to be preferred. The thus obtained +performance evaluation depends on the actual split of the data set. To +remove this dependence the data set is split many times into a +training and test set. For each split the model parameters are +estimated for all choices of \( \lambda \) using the training data and +estimated parameters are evaluated on the corresponding test set. The +penalty parameter that on average over the test sets performs best (in +some sense) is then selected.
@@ -458,7 +438,7 @@ cross-validation (LOOCV).
- + -
+The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks:
@@ -473,7 +416,7 @@ $$
- + -
-Another approach in the LOOCV scheme is to the use the so-called Predicted Residual Error Sum of Squares (PRESS). +
-We can define the optimal penalty parameter to minimize -$$ -\begin{align*} -\lambda_{\mbox{{\tiny opt}}} = \arg \min_{\lambda} \frac{1}{n} \sum_{i=1}^n [y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)]^2. -\end{align*} -$$ - -
-The LOOCV prediction performance can be -expressed analytically in terms of the known quantities derived from -the design matrix and the parameters \( \beta \). -
@@ -462,7 +425,7 @@ the design matrix and the parameters \( \beta \).
- + -
-Two famous -resampling methods are the independent bootstrap and the jackknife. +
-The jackknife is a special case of the independent bootstrap. Still, the jackknife was made -popular prior to the independent bootstrap. And as the popularity of -the independent bootstrap soared, new variants, such as the dependent bootstrap. +$$ +\begin{align*} +\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T} +\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1} +\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i} +\end{align*} +$$ -
-The Jackknife and independent bootstrap work for -independent, identically distributed random variables. -If these conditions are not -satisfied, the methods will fail. Yet, it should be said that if the data are -independent, identically distributed, and we only want to estimate the -variance of \( \overline{X} \) (which often is the case), then there is no -need for bootstrapping. -
+
diff --git a/doc/pub/Regression/html/._Regression-bs079.html b/doc/pub/Regression/html/._Regression-bs079.html index 085b050b8..79e1d53f1 100644 --- a/doc/pub/Regression/html/._Regression-bs079.html +++ b/doc/pub/Regression/html/._Regression-bs079.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source +
-The Jackknife works by making many replicas of the estimator \( \widehat{\theta} \). -The jackknife is a resampling method, we explained that this happens by scrambling the data in some way. When using the jackknife, this is done by systematically leaving out one observation from the vector of observed values \( \hat{x} = (x_1,x_2,\cdots,X_n) \). -Let \( \hat{x}_i \) denote the vector -$$ -\hat{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), -$$ +Two famous +resampling methods are the independent bootstrap and the jackknife.
-which equals the vector \( \hat{x} \) with the exception that observation -number \( i \) is left out. Using this notation, define -\( \widehat{\theta}_i \) to be the estimator -\( \widehat{\theta} \) computed using \( \vec{X}_i \). +The jackknife is a special case of the independent bootstrap. Still, the jackknife was made +popular prior to the independent bootstrap. And as the popularity of +the independent bootstrap soared, new variants, such as the dependent bootstrap. + +
+The Jackknife and independent bootstrap work for +independent, identically distributed random variables. +If these conditions are not +satisfied, the methods will fail. Yet, it should be said that if the data are +independent, identically distributed, and we only want to estimate the +variance of \( \overline{X} \) (which often is the case), then there is no +need for bootstrapping.
@@ -456,7 +427,7 @@ number \( i \) is left out. Using this notation, define
-To get an estimate for the bias and -standard error of \( \widehat{\theta} \), use the following -estimators for each component of \( \widehat{\theta} \) +The Jackknife works by making many replicas of the estimator \( \widehat{\theta} \). +The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \( \boldsymbol{x} = (x_1,x_2,\cdots,X_n) \). +Let \( \boldsymbol{x}_i \) denote the vector +$$ +\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), +$$ -$$ -\widehat{\mathrm{Bias}}(\widehat \theta,\theta) = (n-1)\left( - \widehat{\theta} + \frac{1}{n}\sum_{i=1}^{n} \widehat \theta_i \right) \qquad \text{and} \qquad \widehat{\sigma}^2_{\widehat{\theta} } = \frac{n-1}{n}\sum_{i=1}^{n}( \widehat{\theta}_i - \frac{1}{n}\sum_{j=1}^{n}\widehat \theta_j )^2. -$$ +
+which equals the vector \( \boldsymbol{x} \) with the exception that observation +number \( i \) is left out. Using this notation, define +\( \widehat{\theta}_i \) to be the estimator +\( \widehat{\theta} \) computed using \( \vec{X}_i \).
@@ -451,7 +423,7 @@ $$
-Since \( \widehat{\theta} = \widehat{\theta}(\hat{X}) \) is a function of random variables, +Since \( \widehat{\theta} = \widehat{\theta}(\boldsymbol{X}) \) is a function of random variables, \( \widehat{\theta} \) itself must be a random variable. Thus it has -a pdf, call this function \( p(\hat{t}) \). The aim of the bootstrap is to -estimate \( p(\hat{t}) \) by the relative frequency of +a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to +estimate \( p(\boldsymbol{t}) \) by the relative frequency of \( \widehat{\theta} \). You can think of this as using a histogram -in the place of \( p(\hat{t}) \). If the relative frequency closely +in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely resembles \( p(\vec{t}) \), then using numerics, it is straight forward to -estimate all the interesting parameters of \( p(\hat{t}) \) using point +estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point estimators.
@@ -453,7 +420,7 @@ estimators.
@@ -459,7 +426,7 @@ idea is to use the relative frequency of \( \widehat{\theta}^* \)
@@ -458,7 +425,7 @@ frequency of the observation \( X_i \), just draw the values
@@ -454,7 +429,7 @@ When you are done, you can draw a histogram of the relative frequency of \( \wid
+The following code starts with a Gaussian distribution with mean value +\( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data +used in the bootstrap analysis. The bootstrap analysis returns a data +set after a given number of bootstrap operations (as many as we have +data points). This data set consists of estimated mean values for each +bootstrap operation. The histogram generated by the bootstrap method +shows that the distribution for these mean values is also a Gaussian, +centered around the mean value \( \mu=100 \) but with standard deviation +\( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in +this case the same as the number of original data points). The value +of the standard deviation is what we expect from the central limit +theorem. +
@@ -429,30 +410,29 @@ The following code starts with a Gaussian distribution with mean value \( \mu =1 def stat(data): return mean(data) -# Bootstrap algorithm +# Bootstrap algorithm def bootstrap(data, statistic, R): t = zeros(R); n = len(data); inds = arange(n); t0 = time() - - # non-parametric bootstrap + # non-parametric bootstrap for i in range(R): t[i] = statistic(data[randint(0,n,n)]) - # analysis + # analysis print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :") print("original bias std. error") - print("%8g %8g %14g %15g" % (statistic(data), std(data),\ - mean(t), \ - std(t))) + print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t))) return t mu, sigma = 100, 15 datapoints = 10000 x = mu + sigma*random.randn(datapoints) -# bootstrap returns the data sample t = bootstrap(x, stat, datapoints) -# the histogram of the bootstrapped data n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) +# bootstrap returns the data sample +t = bootstrap(x, stat, datapoints) +# the histogram of the bootstrapped data +n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) -# add a 'best fit' line +# add a 'best fit' line y = mlab.normpdf( binsboot, mean(t), std(t)) lt = plt.plot(binsboot, y, 'r--', linewidth=1) plt.xlabel('Smarts') @@ -488,7 +468,7 @@ plt.show()
-The blocking method was made popular by Flyvbjerg and Pedersen (1989) -and has become one of the standard ways to estimate -\( V(\widehat{\theta}) \) for exactly one \( \widehat{\theta} \), namely -\( \widehat{\theta} = \overline{X} \). - +The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial.
-Assume \( n = 2^d \) for some integer \( d>1 \) and \( X_1,X_2,\cdots, X_n \) is a stationary time series to begin with. -Moreover, assume that the time series is asymptotically uncorrelated. We switch to vector notation by arranging \( X_1,X_2,\cdots,X_n \) in an \( n \)-tuple. Define: -$$ -\begin{align*} -\hat{X} = (X_1,X_2,\cdots,X_n). -\end{align*} -$$ -
-The strength of the blocking method is when the number of -observations, \( n \) is large. For large \( n \), the complexity of dependent -bootstrapping scales poorly, but the blocking method does not, -moreover, it becomes more accurate the larger \( n \) is. + +
import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.model_selection import KFold
+from sklearn.linear_model import Ridge
+from sklearn.model_selection import cross_val_score
+from sklearn.preprocessing import PolynomialFeatures
+# A seed just to ensure that the random numbers are the same for every run.
+# Useful for eventual debugging.
+np.random.seed(3155)
+
+# Generate the data.
+nsamples = 100
+x = np.random.randn(nsamples)
+y = 3*x**2 + np.random.randn(nsamples)
+
+## Cross-validation on Ridge regression using KFold only
+
+# Decide degree on polynomial to fit
+poly = PolynomialFeatures(degree = 6)
+
+# Decide which values of lambda to use
+nlambdas = 500
+lambdas = np.logspace(-3, 5, nlambdas)
+
+# Initialize a KFold instance
+k = 5
+kfold = KFold(n_splits = k)
+
+# Perform the cross-validation to estimate MSE
+scores_KFold = np.zeros((nlambdas, k))
+
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
+ j = 0
+ for train_inds, test_inds in kfold.split(x):
+ xtrain = x[train_inds]
+ ytrain = y[train_inds]
+
+ xtest = x[test_inds]
+ ytest = y[test_inds]
+
+ Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
+ ridge.fit(Xtrain, ytrain[:, np.newaxis])
+
+ Xtest = poly.fit_transform(xtest[:, np.newaxis])
+ ypred = ridge.predict(Xtest)
+
+ scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
+
+ j += 1
+ i += 1
+
+
+estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
+
+## Cross-validation using cross_val_score from sklearn along with KFold
+
+# kfold is an instance initialized above as:
+# kfold = KFold(n_splits = k)
+
+estimated_mse_sklearn = np.zeros(nlambdas)
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
+
+ X = poly.fit_transform(x[:, np.newaxis])
+ estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
+
+ # cross_val_score return an array containing the estimated negative mse for every fold.
+ # we have to the the mean of every array in order to get an estimate of the mse of the model
+ estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
+
+ i += 1
+
+## Plot and compare the slightly different ways to perform cross-validation
+
+plt.figure()
+
+plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
+plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
+
+plt.xlabel('log10(lambda)')
+plt.ylabel('mse')
+
+plt.legend()
+
+plt.show()
+
@@ -463,7 +504,7 @@ moreover, it becomes more accurate the larger \( n \) is.
+We will discuss the bias-variance tradeoff in the context of +continuous predictions such as regression. However, many of the +intuitions and ideas discussed here also carry over to classification +tasks. Consider a dataset \( \mathcal{L} \) consisting of the data +\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \). + +
+Let us assume that the true data is generated from a noisy model $$ -\begin{align} -(\vec{X}_0)_k &\equiv (\vec{X})_k \nonumber \\ -(\vec{X}_{i+1})_k &\equiv \frac{1}{2}\Big( (\vec{X}_i)_{2k-1} + -(\vec{X}_i)_{2k} \Big) \qquad \text{for all} \qquad 1 \leq i \leq d-1 -\tag{21} -\end{align} +\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon} $$
-The quantity \( \vec{X}_k \) is -subject to \( k \) blocking transformations. We now have \( d \) vectors -\( \vec{X}_0, \vec{X}_1,\cdots,\vec X_{d-1} \) containing the subsequent -averages of observations. It turns out that if the components of -\( \vec{X} \) is a stationary time series, then the components of -\( \vec{X}_i \) is a stationary time series for all \( 0 \leq i \leq d-1 \) +where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \).
-We can then compute the autocovariance, the variance, sample mean, and -number of observations for each \( i \). -Let \( \gamma_i, \sigma_i^2, -\overline{X}_i \) denote the autocovariance, variance and average of the -elements of \( \vec{X}_i \) and let \( n_i \) be the number of elements of -\( \vec{X}_i \). It follows by induction that \( n_i = n/2^i \). +In our derivation of the ordinary least squares method we defined then +an approximation to the function \( f \) in terms of the parameters +\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model, +that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \). + +
+Thereafter we found the parameters \( \boldsymbol{\beta} \) by optimizing the means squared error via the so-called cost function +$$ +C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]. +$$ + +
+We can rewrite this as +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2. +$$ + +
+The three terms represent the square of the bias of the learning +method, which can be thought of as the error caused by the simplifying +assumptions built into the method. The second term represents the +variance of the chosen model and finally the last terms is variance of +the error \( \boldsymbol{\epsilon} \). + +
+To derive this equation, we need to recall that the variance of \( \boldsymbol{y} \) and \( \boldsymbol{\epsilon} \) are both equal to \( \sigma^2 \). The mean value of \( \boldsymbol{\epsilon} \) is by definition equal to zero. Furthermore, the function \( f \) is not a stochastics variable, idem for \( \boldsymbol{\tilde{y}} \). +We use a more compact notation in terms of the expectation value +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right], +$$ + +and adding and subtracting \( \mathbb{E}\left[\boldsymbol{\tilde{y}}\right] \) we get +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right], +$$ + +which, using the abovementioned expectation values can be rewritten as +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2, +$$ + +that is the rewriting in terms of the so-called bias, the variance of the model \( \boldsymbol{\tilde{y}} \) and the variance of \( \boldsymbol{\epsilon} \).
@@ -474,7 +470,7 @@ elements of \( \vec{X}_i \) and let \( n_i \) be the number of elements of
-Using the -definition of the blocking transformation and the distributive -property of the covariance, it is clear that since \( h =|i-j| \) -we can define -$$ -\begin{align} -\gamma_{k+1}(h) &= cov\left( ({X}_{k+1})_{i}, ({X}_{k+1})_{j} \right) \nonumber \\ -&= \frac{1}{4}cov\left( ({X}_{k})_{2i-1} + ({X}_{k})_{2i}, ({X}_{k})_{2j-1} + ({X}_{k})_{2j} \right) \nonumber \\ -&= \frac{1}{2}\gamma_{k}(2h) + \frac{1}{2}\gamma_k(2h+1) \hspace{0.1cm} \mathrm{h = 0} -\tag{22}\\ -&=\frac{1}{4}\gamma_k(2h-1) + \frac{1}{2}\gamma_k(2h) + \frac{1}{4}\gamma_k(2h+1) \quad \mathrm{else} -\tag{23} -\end{align} -$$ -
-The quantity \( \hat{X} \) is asymptotic uncorrelated by assumption, \( \hat{X}_k \) is also asymptotic uncorrelated. Let's turn our attention to the variance of the sample mean \( V(\overline{X}) \). + +
import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+np.random.seed(2018)
+
+n = 500
+n_boostraps = 100
+degree = 18 # A quite high value, just to show.
+noise = 0.1
+
+# Make data set.
+x = np.linspace(-1, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)
+
+# Hold out some test data that is never used in training.
+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+# Combine x transformation and model into one operation.
+# Not neccesary, but convenient.
+model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
+
+# The following (m x n_bootstraps) matrix holds the column vectors y_pred
+# for each bootstrap iteration.
+y_pred = np.empty((y_test.shape[0], n_boostraps))
+for i in range(n_boostraps):
+ x_, y_ = resample(x_train, y_train)
+
+ # Evaluate the new model on the same test data each time.
+ y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
+
+# Note: Expectations and variances taken w.r.t. different training
+# data sets, hence the axis=1. Subsequent means are taken across the test data
+# set in order to obtain a total value, but before this we have error/bias/variance
+# calculated per data point in the test set.
+# Note 2: The use of keepdims=True is important in the calculation of bias as this
+# maintains the column vector form. Dropping this yields very unexpected results.
+error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+print('Error:', error)
+print('Bias^2:', bias)
+print('Var:', variance)
+print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))
+
+plt.plot(x[::5, :], y[::5, :], label='f(x)')
+plt.scatter(x_test, y_test, label='Data points')
+plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')
+plt.legend()
+plt.show()
+
@@ -460,8 +465,6 @@ The quantity \( \hat{X} \) is asymptotic uncorrelated by assumption, \( \hat{X}_
-The term \( e_k \) is called the truncation error: -$$ -\begin{equation} -e_k = \frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h). -\tag{25} -\end{equation} -$$ + +
import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
-We can show that \( V(\overline{X}_i) = V(\overline{X}_j) \) for all \( 0 \leq i \leq d-1 \) and \( 0 \leq j \leq d-1 \).
+np.random.seed(2018)
+n = 40
+n_boostraps = 100
+maxdegree = 14
+
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+for degree in range(maxdegree):
+ model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
+ y_pred = np.empty((y_test.shape[0], n_boostraps))
+ for i in range(n_boostraps):
+ x_, y_ = resample(x_train, y_train)
+ y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
+
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+ variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+ print('Polynomial degree:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.plot(polydegree, np.log10(error), label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+plt.show()
+
@@ -457,9 +456,6 @@ We can show that \( V(\overline{X}_i) = V(\overline{X}_j) \) for all \( 0 \leq i
- + -
-We can then wrap up -$$ -\begin{align} -n_{j+1} \overline{X}_{j+1} &= \sum_{i=1}^{n_{j+1}} (\hat{X}_{j+1})_i = \frac{1}{2}\sum_{i=1}^{n_{j}/2} (\hat{X}_{j})_{2i-1} + (\hat{X}_{j})_{2i} \nonumber \\ -&= \frac{1}{2}\left[ (\hat{X}_j)_1 + (\hat{X}_j)_2 + \cdots + (\hat{X}_j)_{n_j} \right] = \underbrace{\frac{n_j}{2}}_{=n_{j+1}} \overline{X}_j = n_{j+1}\overline{X}_j. -\tag{26} -\end{align} -$$ - -By repeated use of this equation we get \( V(\overline{X}_i) = V(\overline{X}_0) = V(\overline{X}) \) for all \( 0 \leq i \leq d-1 \). This has the consequence that -$$ -\begin{align} -V(\overline{X}) = \frac{\sigma_k^2}{n_k} + e_k \qquad \text{for all} \qquad 0 \leq k \leq d-1. \tag{27} -\end{align} -$$ +The bias-variance tradeoff summarizes the fundamental tension in +machine learning, particularly supervised learning, between the +complexity of a model and the amount of training data needed to train +it. Since data is often limited, in practice it is often useful to +use a less-complex model with higher bias, that is a model whose asymptotic +performance is worse than another model because it is easier to +train and less sensitive to sampling noise arising from having a +finite-sized training dataset (smaller variance).
-Fyvbjerg and Petersen demonstrated that the sequence -\( \{e_k\}_{k=0}^{d-1} \) is decreasing, and conjecture that the term -\( e_k \) can be made as small as we would like by making \( k \) (and hence -\( d \)) sufficiently large. The sequence is decreasing (Master of Science thesis by Marius Jonsson, UiO 2018). -It means we can apply blocking transformations until -\( e_k \) is sufficiently small, and then estimate \( V(\overline{X}) \) by -\( \widehat{\sigma}^2_k/n_k \). +The above equations tell us that in +order to minimize the expected test error, we need to select a +statistical learning method that simultaneously achieves low variance +and low bias. Note that variance is inherently a nonnegative quantity, +and squared bias is also nonnegative. Hence, we see that the expected +test MSE can never lie below \( Var(\epsilon) \), the irreducible error. + +
+What do we mean by the variance and bias of a statistical learning +method? The variance refers to the amount by which our model would change if we +estimated it using a different training data set. Since the training +data are used to fit the statistical learning method, different +training data sets will result in a different estimate. But ideally the +estimate for our model should not vary too much between training +sets. However, if a method has high variance then small changes in +the training data can result in large changes in the model. In general, more +flexible statistical methods have higher variance.
@@ -465,10 +435,6 @@ It means we can apply blocking transformations until
-
from sys import argv
-from os import mkdir, path
-import time
+"""
+============================
+Underfitting vs. Overfitting
+============================
+
+This example demonstrates the problems of underfitting and overfitting and
+how we can use linear regression with polynomial features to approximate
+nonlinear functions. The plot shows the function that we want to approximate,
+which is a part of the cosine function. In addition, the samples from the
+real function and the approximations of different models are displayed. The
+models have polynomial features of different degrees. We can see that a
+linear function (polynomial with degree 1) is not sufficient to fit the
+training samples. This is called **underfitting**. A polynomial of degree 4
+approximates the true function almost perfectly. However, for higher degrees
+the model will **overfit** the training data, i.e. it learns the noise of the
+training data.
+We evaluate quantitatively **overfitting** / **underfitting** by using
+cross-validation. We calculate the mean squared error (MSE) on the validation
+set, the higher, the less likely the model generalizes correctly from the
+training data.
+"""
+
+print(__doc__)
+
import numpy as np
import matplotlib.pyplot as plt
-from matplotlib.ticker import FormatStrFormatter
-from matplotlib.font_manager import FontProperties
-
-# Timing Decorator
-def timeFunction(f):
- def wrap(*args):
- time1 = time.time()
- ret = f(*args)
- time2 = time.time()
- print '%s Function Took: \t %0.3f s' % (f.func_name.title(), (time2-time1))
- return ret
- return wrap
-
-class dataAnalysisClass:
- # General Init functions
- def __init__(self, fileName, size=0):
- self.inputFileName = fileName
- self.loadData(size)
- self.createOutputFolder()
- self.avg = np.average(self.data)
- self.var = np.var(self.data)
- self.std = np.std(self.data)
-
- def loadData(self, size=0):
- if size != 0:
- with open(self.inputFileName) as inputFile:
- self.data = np.zeros(size)
- for x in xrange(size):
- self.data[x] = float(next(inputFile))
- else:
- self.data = np.loadtxt(self.inputFileName)
-
- # Statistical Analysis with Multiple Methods
- def runAllAnalyses(self):
- if len(self.data) <= 100000:
- print "Autocorrelation..."
- self.autocorrelation()
- print "Bootstrap..."
- self.bootstrap()
- print "Jackknife..."
- self.jackknife()
- print "Blocking..."
- self.blocking()
-
- # Standard Autocorrelation
- @timeFunction
- def autocorrelation(self):
- self.acf = np.zeros(len(self.data)/2)
- for k in range(0, len(self.data)/2):
- self.acf[k] = np.corrcoef(np.array([self.data[0:len(self.data)-k], \
- self.data[k:len(self.data)]]))[0,1]
-
- # Bootstrap
- @timeFunction
- def bootstrap(self, nBoots = 1000):
- bootVec = np.zeros(nBoots)
- for k in range(0,nBoots):
- bootVec[k] = np.average(np.random.choice(self.data, len(self.data)))
- self.bootAvg = np.average(bootVec)
- self.bootVar = np.var(bootVec)
- self.bootStd = np.std(bootVec)
-
- # Jackknife
- @timeFunction
- def jackknife(self):
- jackknVec = np.zeros(len(self.data))
- for k in range(0,len(self.data)):
- jackknVec[k] = np.average(np.delete(self.data, k))
- self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg)
- self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec)
- self.jackknStd = np.sqrt(self.jackknVar)
-
- # Blocking
- @timeFunction
- def blocking(self, blockSizeMax = 500):
- blockSizeMin = 1
-
- self.blockSizes = []
- self.meanVec = []
- self.varVec = []
-
- for i in range(blockSizeMin, blockSizeMax):
- if(len(self.data) % i != 0):
- pass#continue
- blockSize = i
- meanTempVec = []
- varTempVec = []
- startPoint = 0
- endPoint = blockSize
-
- while endPoint <= len(self.data):
- meanTempVec.append(np.average(self.data[startPoint:endPoint]))
- startPoint = endPoint
- endPoint += blockSize
- mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec)
- self.meanVec.append(mean)
- self.varVec.append(var)
- self.blockSizes.append(blockSize)
-
- self.blockingAvg = np.average(self.meanVec[-200:])
- self.blockingVar = (np.average(self.varVec[-200:]))
- self.blockingStd = np.sqrt(self.blockingVar)
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.linear_model import LinearRegression
+from sklearn.model_selection import cross_val_score
+def true_fun(X):
+ return np.cos(1.5 * np.pi * X)
- # Plot of Data, Autocorrelation Function and Histogram
- def plotAll(self):
- self.createOutputFolder()
- if len(self.data) <= 100000:
- self.plotAutocorrelation()
- self.plotData()
- self.plotHistogram()
- self.plotBlocking()
+np.random.seed(0)
- # Create Output Plots Folder
- def createOutputFolder(self):
- self.outName = self.inputFileName[:-4]
- if not path.exists(self.outName):
- mkdir(self.outName)
+n_samples = 30
+degrees = [1, 4, 15]
- # Plot the Dataset, Mean and Std
- def plotData(self):
- # Far away plot
- font = {'fontname':'serif'}
- plt.plot(range(0, len(self.data)), self.data, 'r-', linewidth=1)
- plt.plot([0, len(self.data)], [self.avg, self.avg], 'b-', linewidth=1)
- plt.plot([0, len(self.data)], [self.avg + self.std, self.avg + self.std], 'g--', linewidth=1)
- plt.plot([0, len(self.data)], [self.avg - self.std, self.avg - self.std], 'g--', linewidth=1)
- plt.ylim(self.avg - 5*self.std, self.avg + 5*self.std)
- plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.4f'))
- plt.xlim(0, len(self.data))
- plt.ylabel(self.outName.title() + ' Monte Carlo Evolution', **font)
- plt.xlabel('MonteCarlo History', **font)
- plt.title(self.outName.title(), **font)
- plt.savefig(self.outName + "/data.eps")
- plt.savefig(self.outName + "/data.png")
- plt.clf()
+X = np.sort(np.random.rand(n_samples))
+y = true_fun(X) + np.random.randn(n_samples) * 0.1
- # Plot Histogram of Dataset and Gaussian around it
- def plotHistogram(self):
- binNumber = 50
- font = {'fontname':'serif'}
- count, bins, ignore = plt.hist(self.data, bins=np.linspace(self.avg - 5*self.std, self.avg + 5*self.std, binNumber))
- plt.plot([self.avg, self.avg], [0,np.max(count)+10], 'b-', linewidth=1)
- plt.ylim(0,np.max(count)+10)
- plt.ylabel(self.outName.title() + ' Histogram', **font)
- plt.xlabel(self.outName.title() , **font)
- plt.title('Counts', **font)
+plt.figure(figsize=(14, 5))
+for i in range(len(degrees)):
+ ax = plt.subplot(1, len(degrees), i + 1)
+ plt.setp(ax, xticks=(), yticks=())
- #gaussian
- norm = 0
- for i in range(0,len(bins)-1):
- norm += (bins[i+1]-bins[i])*count[i]
- plt.plot(bins, norm/(self.std * np.sqrt(2 * np.pi)) * np.exp( - (bins - self.avg)**2 / (2 * self.std**2) ), linewidth=1, color='r')
- plt.savefig(self.outName + "/hist.eps")
- plt.savefig(self.outName + "/hist.png")
- plt.clf()
+ polynomial_features = PolynomialFeatures(degree=degrees[i],
+ include_bias=False)
+ linear_regression = LinearRegression()
+ pipeline = Pipeline([("polynomial_features", polynomial_features),
+ ("linear_regression", linear_regression)])
+ pipeline.fit(X[:, np.newaxis], y)
- # Plot the Autocorrelation Function
- def plotAutocorrelation(self):
- font = {'fontname':'serif'}
- plt.plot(range(1, len(self.data)/2), self.acf[1:], 'r-')
- plt.ylim(-1, 1)
- plt.xlim(0, len(self.data)/2)
- plt.ylabel('Autocorrelation Function', **font)
- plt.xlabel('Lag', **font)
- plt.title('Autocorrelation', **font)
- plt.savefig(self.outName + "/autocorrelation.eps")
- plt.savefig(self.outName + "/autocorrelation.png")
- plt.clf()
+ # Evaluate the models using crossvalidation
+ scores = cross_val_score(pipeline, X[:, np.newaxis], y,
+ scoring="neg_mean_squared_error", cv=10)
- def plotBlocking(self):
- font = {'fontname':'serif'}
- plt.plot(self.blockSizes, self.varVec, 'r-')
- plt.ylabel('Variance', **font)
- plt.xlabel('Block Size', **font)
- plt.title('Blocking', **font)
- plt.savefig(self.outName + "/blocking.eps")
- plt.savefig(self.outName + "/blocking.png")
- plt.clf()
-
- # Print Stuff to the Terminal
- def printOutput(self):
- print "\nSample Size: \t", len(self.data)
- print "\n=========================================\n"
- print "Sample Average: \t", self.avg
- print "Sample Variance:\t", self.var
- print "Sample Std: \t", self.std
- print "\n=========================================\n"
- print "Bootstrap Average: \t", self.bootAvg
- print "Bootstrap Variance:\t", self.bootVar
- print "Bootstrap Error: \t", self.bootStd
- print "\n=========================================\n"
- print "Jackknife Average: \t", self.jackknAvg
- print "Jackknife Variance:\t", self.jackknVar
- print "Jackknife Error: \t", self.jackknStd
- print "\n=========================================\n"
- print "Blocking Average: \t", self.blockingAvg
- print "Blocking Variance:\t", self.blockingVar
- print "Blocking Error: \t", self.blockingStd, "\n"
-
-# Initialize the class
-if len(argv) > 2:
- dataAnalysis = dataAnalysisClass(argv[1], int(argv[2]))
-else:
- dataAnalysis = dataAnalysisClass(argv[1])
-
-# Run Analyses
-dataAnalysis.runAllAnalyses()
-
-# Plot the data
-dataAnalysis.plotAll()
-
-# Print Some Output
-dataAnalysis.printOutput()
+ X_test = np.linspace(0, 1, 100)
+ plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
+ plt.plot(X_test, true_fun(X_test), label="True function")
+ plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
+ plt.xlabel("x")
+ plt.ylabel("y")
+ plt.xlim((0, 1))
+ plt.ylim((-2, 2))
+ plt.legend(loc="best")
+ plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
+ degrees[i], -scores.mean(), scores.std()))
+plt.show()
@@ -662,11 +479,6 @@ dataAnalysis.printOutput()
-We begin with an unknown function \( y=f(x) \) and fix a \emph{hypothesis set} - \( \mathcal{H} \) consisting of all functions we are willing to consider, - defined also on the domain of \( f \). This set may be uncountably - infinite (e.g. if there are real-valued parameters to fit). -The - choice of which functions to include in \( \mathcal{H} \) usually depends - on our intuition about the problem of interest. The function \( f(x) \) - produces a set of pairs \( (x_i,y_i) \), \( i=1\dots N \), which serve as the - observable data. Our goal is to select a function from the hypothesis - set \( h\in\mathcal{H} \) which approximates \( f(x) \) as best as possible, - namely, we would like to find \( h\in\mathcal{H} \) such that \( h\approx - f \) in some strict mathematical sense which we specify below. If this - is possible, we say that we \emph{learned} \( f(x) \). But if the - function \( f(x) \) can, in principle, take any value on - \emph{unobserved} inputs, how is it possible to learn in any - meaningful sense? +Let us bring back the Ising model again, but now with an additional +focus on Ridge and Lasso regression as well. We repeat some of the +basic parts of the Ising model and the setup of the training and test +data. The one-dimensional Ising model with nearest neighbor +interaction, no external field and a constant coupling constant \( J \) is +given by + +$$ +\begin{align} + H = -J \sum_{k}^L s_k s_{k + 1}, +\tag{27} +\end{align} +$$ + +where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins in the system is determined by \( L \). For the one-dimensional system there is no phase transition. + +
+We will look at a system of \( L = 40 \) spins with a coupling constant of \( J = 1 \). To get enough training data we will generate 10000 states with their respective energies. + +
+ + +
import numpy as np
+import matplotlib.pyplot as plt
+from mpl_toolkits.axes_grid1 import make_axes_locatable
+import seaborn as sns
+import scipy.linalg as scl
+from sklearn.model_selection import train_test_split
+import sklearn.linear_model as skl
+import tqdm
+sns.set(color_codes=True)
+cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
+
+L = 40
+n = int(1e4)
+
+spins = np.random.choice([-1, 1], size=(n, L))
+J = 1.0
+
+energies = np.zeros(n)
+
+for i in range(n):
+ energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
++A more general form for the one-dimensional Ising model is + +$$ +\begin{align} + H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. +\tag{28} +\end{align} +$$ + +
+Here we allow for interactions beyond the nearest neighbors and a more +adaptive coupling matrix. This latter expression can be formulated as +a matrix-product on the form +$$ +\begin{align} + H = X J, +\tag{29} +\end{align} +$$ + +
+where \( X_{jk} = s_j s_k \) and \( J \) is the matrix consisting of the +elements \( -J_{jk} \). This form of writing the energy fits perfectly +with the form utilized in linear regression, viz. +$$ +\begin{align} + \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}. +\tag{30} +\end{align} +$$ + +We organize the data as we did above +
+ + +
X = np.zeros((n, L ** 2))
+for i in range(n):
+ X[i] = np.outer(spins[i], spins[i]).ravel()
+y = energies
+X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.96)
+
+X_train_own = np.concatenate(
+ (np.ones(len(X_train))[:, np.newaxis], X_train),
+ axis=1
+)
+
+X_test_own = np.concatenate(
+ (np.ones(len(X_test))[:, np.newaxis], X_test),
+ axis=1
+)
++We will do all fitting with Scikit-Learn, + +
+ + +
clf = skl.LinearRegression().fit(X_train, y_train)
++When extracting the \( J \)-matrix we make sure to remove the intercept +
+ + +
J_sk = clf.coef_.reshape(L, L)
++And then we plot the results +
+ + +
fig = plt.figure(figsize=(20, 14))
+im = plt.imshow(J_sk, **cmap_args)
+plt.title("LinearRegression from Scikit-learn", fontsize=18)
+plt.xticks(fontsize=18)
+plt.yticks(fontsize=18)
+cb = fig.colorbar(im)
+cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
+plt.show()
++The results perfectly with our previous discussion where we used our own code.
@@ -455,12 +533,6 @@ The
- + -
-We will discuss the bias-variance tradeoff in the context of continuous predictions such as regression. However, many of the intuitions and ideas discussed here also carry over to classification tasks. Consider a dataset \( \mathcal{L} \) consisting of the data \( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=1\ldots N\} \). Let us assume that the true data is generated from a noisy model +Having explored the ordinary least squares we move on to ridge +regression. In ridge regression we include a regularizer. This +involves a new cost function which leads to a new estimate for the +weights \( \boldsymbol{\beta} \). This results in a penalized regression problem. The +cost function is given by + $$ -y=f(\boldsymbol{x}) + \epsilon +\begin{align} + C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \boldsymbol{\beta}^T\boldsymbol{\beta}. +\tag{31} +\end{align} $$ -where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma_\epsilon \). +
+ +
_lambda = 0.1
+clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)
+J_ridge_sk = clf_ridge.coef_.reshape(L, L)
+fig = plt.figure(figsize=(20, 14))
+im = plt.imshow(J_ridge_sk, **cmap_args)
+plt.title("Ridge from Scikit-learn", fontsize=18)
+plt.xticks(fontsize=18)
+plt.yticks(fontsize=18)
+cb = fig.colorbar(im)
+cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
+
+plt.show()
+
@@ -444,13 +433,6 @@ where \( \epsilon \) is normally distributed with mean zero and standard deviati
-We have a statistical procedure (e.g. least-squares regression) for -forming a predictor \( \hat{g}_{\mathcal{L}}(\boldsymbol{x}) \) that gives the -prediction of our model for a new data point \( \boldsymbol{x} \). This estimator -is chosen by minimizing a cost function which we take to be the -squared error +In the Least Absolute Shrinkage and Selection Operator (LASSO)-method we get a third cost function. $$ - \mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) = \sum_i (y_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2. +\begin{align} + C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \sqrt{\boldsymbol{\beta}^T\boldsymbol{\beta}}. +\tag{32} +\end{align} $$ +
+Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-Learn. + +
+ + +
clf_lasso = skl.Lasso(alpha=_lambda).fit(X_train, y_train)
+J_lasso_sk = clf_lasso.coef_.reshape(L, L)
+fig = plt.figure(figsize=(20, 14))
+im = plt.imshow(J_lasso_sk, **cmap_args)
+plt.title("Lasso from Scikit-learn", fontsize=18)
+plt.xticks(fontsize=18)
+plt.yticks(fontsize=18)
+cb = fig.colorbar(im)
+cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
+
+plt.show()
++It is quite striking how LASSO breaks the symmetry of the coupling +constant as opposed to ridge and OLS. We get a sparse solution with +\( J_{j, j + 1} = -1 \). +
@@ -446,14 +435,6 @@ $$
-We are interested in the generalization error on all data drawn from -the true model, not just the error on the particular training dataset -\( \mathcal{L} \) that we have in hand. This is just the expectation of -the cost function over many different data sets -\( \{\mathcal{L}_j\} \). Denote this expectation value by -\( E_{\mathcal{L}} \). In other words, we can view \( \hat{g}_{\mathcal{L}} \) -as a stochastic functional that depends on the dataset \( \mathcal{L} \) -and we can think of \( E_{\mathcal{L}} \) as the expected value of the -functional if we drew an infinite number of datasets \( \{\mathcal{L}_1, -\mathcal{L}_2, \ldots \} \). +We see how the different models perform for a different set of values for \( \lambda \). + +
+ + +
lambdas = np.logspace(-4, 5, 10)
+
+train_errors = {
+ "ols_sk": np.zeros(lambdas.size),
+ "ridge_sk": np.zeros(lambdas.size),
+ "lasso_sk": np.zeros(lambdas.size)
+}
+
+test_errors = {
+ "ols_sk": np.zeros(lambdas.size),
+ "ridge_sk": np.zeros(lambdas.size),
+ "lasso_sk": np.zeros(lambdas.size)
+}
+
+plot_counter = 1
+
+fig = plt.figure(figsize=(32, 54))
+
+for i, _lambda in enumerate(tqdm.tqdm(lambdas)):
+ for key, method in zip(
+ ["ols_sk", "ridge_sk", "lasso_sk"],
+ [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)]
+ ):
+ method = method.fit(X_train, y_train)
+
+ train_errors[key][i] = method.score(X_train, y_train)
+ test_errors[key][i] = method.score(X_test, y_test)
+
+ omega = method.coef_.reshape(L, L)
+
+ plt.subplot(10, 5, plot_counter)
+ plt.imshow(omega, **cmap_args)
+ plt.title(r"%s, $\lambda = %.4f$" % (key, _lambda))
+ plot_counter += 1
+
+plt.show()
++We see that LASSO reaches a good solution for low +values of \( \lambda \), but will "wither" when we increase \( \lambda \) too +much. Ridge is more stable over a larger range of values for +\( \lambda \), but eventually also fades away.
@@ -446,15 +450,6 @@ functional if we drew an infinite number of datasets \( \{\mathcal{L}_1,
-We would also like to average over different instances of the -"noise" \( \epsilon \) and we denote the expectation value over the -noise by \( E_\epsilon \). Thus, we can decompose the expected -generalization error as - -$$ -\begin{align} -E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ]&= E_\mathcal{L,\epsilon}\left[ \sum_i ({y}_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2 \right] \nonumber \\ - &= E_\mathcal{L, \epsilon}\left[ \sum_{i}({y}_i -f(\boldsymbol{x}_i) +f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2\right] \nonumber \\ - &= \sum_i E_\epsilon[ ({y}_i -f(\boldsymbol{x}_i))^2 ]+ E_\mathcal{L, \epsilon}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] + 2E_\epsilon[{y}_i -f(\boldsymbol{x}_i)]E_\mathcal{L}[f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i)] \nonumber \\ - &=\sum_i \sigma_\epsilon^2 + E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2], -\tag{28} -\end{align} -$$ +To determine which value of \( \lambda \) is best we plot the accuracy of +the models when predicting the training and the testing set. We expect +the accuracy of the training set to be quite good, but if the accuracy +of the testing set is much lower this tells us that we might be +subject to an overfit model. The ideal scenario is an accuracy on the +testing set that is close to the accuracy of the training set.
-where in the last line we used the fact that our noise has zero mean -and variance \( \sigma_\epsilon^2 \) and the sum over \( i \) applies to all -terms. + + +
fig = plt.figure(figsize=(20, 14))
+
+colors = {
+ "ols_sk": "r",
+ "ridge_sk": "y",
+ "lasso_sk": "c"
+}
+
+for key in train_errors:
+ plt.semilogx(
+ lambdas,
+ train_errors[key],
+ colors[key],
+ label="Train {0}".format(key),
+ linewidth=4.0
+ )
+
+for key in test_errors:
+ plt.semilogx(
+ lambdas,
+ test_errors[key],
+ colors[key] + "--",
+ label="Test {0}".format(key),
+ linewidth=4.0
+ )
+plt.legend(loc="best", fontsize=18)
+plt.xlabel(r"$\lambda$", fontsize=18)
+plt.ylabel(r"$R^2$", fontsize=18)
+plt.tick_params(labelsize=18)
+plt.show()
++From the above figure we can see that LASSO with \( \lambda = 10^{-2} \) +achieves a very good accuracy on the test set. This by far surpasses the +other models for all values of \( \lambda \).
@@ -454,16 +447,6 @@ terms.
-It is also helpful to further decompose the second term as -follows: +We will generate our own dataset for a function \( y(x) \) where \( x \in [0,1] \) and defined by random numbers computed with the uniform distribution. The function \( y \) is a quadratic polynomial in \( x \) with added stochastic noise according to the normal distribution \( \cal {N}(0,1) \). +The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points). +
+ +
x = np.random.rand(100,1)
+y = 5*x*x+0.1*np.random.randn(100,1)
++You can use the functionality included in scikit-learn. If you feel +for it, you can use your own program and define functions which +compute the above two functions. Discuss the meaning of these +results. Try also to vary the coefficient in front of the added +stochastic noise term and discuss the quality of the fits. + +
+Show that the variance of the parameters \( \beta \) in the linear regression method (chapter 3, equation (3.8) of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer) is given as + +$$ +\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2, +$$ + +with +$$ +\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2, +$$ + +where we have assumed that we fit a function of degree \( p-1 \) (for example a polynomial in \( x \)). + +
+This exercise is a continuation of exercise 1. We will +use the same function to generate our data set, still staying with a +simple function \( y(x) \) which we want to fit using linear regression, +but now extending the analysis to include the Ridge and the Lasso +regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods. + +
+We will thus again generate our own dataset for a function \( y(x) \) where +\( x \in [0,1] \) and defined by random numbers computed with the uniform +distribution. The function \( y \) is a quadratic polynomial in \( x \) with +added stochastic noise according to the normal distribution \( \cal{N}(0,1) \). + +
+The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points). +
+ + +
x = np.random.rand(100,1)
+y = 5*x*x+0.1*np.random.randn(100,1)
++We will study how +to fit polynomials to a specific two-dimensional function called +Franke's +function. This +is a function which has been widely used when testing various interpolation and fitting +algorithms. Furthermore, after having established the model and the +method, we will employ resamling techniques such as the cross-validation and/or +the bootstrap methods, in order to perform a proper assessment of our models. + +
+The Franke function, which is a weighted sum of four exponentials reads as follows +$$ +\begin{align*} +f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\ +&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }. +\end{align*} +$$ + +
+The function will be defined for \( x,y\in [0,1] \). Our first step will +be to perform an OLS regression analysis of this function, trying out +a polynomial fit with an \( x \) and \( y \) dependence of the form \( [x, y, +x^2, y^2, xy, \dots] \). We will also include cross-validation and +bootstrap as resampling techniques. As in homeworks 1 and 2, we +can use a uniform distribution to set up the arrays of values for \( x \) +and \( y \), or as in the example below just a fix values for \( x \) and \( y \) with a given step size. +In this case we will have two predictors and need to fit a +function (for example a polynomial) of \( x \) and \( y \). Thereafter we will +repeat much of the same procedure using the the Ridge and +Lasso regression methods, introducing thus a dependence on the bias +(penalty) \( \lambda \). + +
+The Python fucntion for the Franke function is included here (it performs also a three-dimensional plot of it) +
+ + +
from mpl_toolkits.mplot3d import Axes3D
+import matplotlib.pyplot as plt
+from matplotlib import cm
+from matplotlib.ticker import LinearLocator, FormatStrFormatter
+import numpy as np
+from random import random, seed
+
+fig = plt.figure()
+ax = fig.gca(projection='3d')
+
+# Make data.
+x = np.arange(0, 1, 0.05)
+y = np.arange(0, 1, 0.05)
+x, y = np.meshgrid(x,y)
+
+
+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
+
+
+z = FrankeFunction(x, y)
+
+# Plot the surface.
+surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
+ linewidth=0, antialiased=False)
+
+# Customize the z axis.
+ax.set_zlim(-0.10, 1.40)
+ax.zaxis.set_major_locator(LinearLocator(10))
+ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
+
+# Add a color bar which maps values to colors.
+fig.colorbar(surf, shrink=0.5, aspect=5)
+
+plt.show()
++We will thus again generate our own dataset for a function \( \mathrm{FrankeFunction}(x,y) \) where +\( x,y \in [0,1] \) could be defined by random numbers computed with the uniform +distribution. The function \( f(x,y) \) is the Franke function. You should explore also the addition +an added stochastic noise to this function using the normal distribution \( \cal{N}(0,1) \). + +
+Write your own code (using either a matrix inversion or a singular value decomposition from e.g., numpy ) or use your code from exercises 1 and 3 +and perform a standard least square regression analysis using polynomials in \( x \) and \( y \) up to fifth order. Find the confidence intervals of the parameters \( \beta \) by computing their variances, evaluate the Mean Squared error (MSE) +$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +$$ + +and the \( R^2 \) score function. +If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +$$ +R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, +$$ + +where we have defined the mean value of \( \hat{y} \) as +$$ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +$$ + +
+Perform a resampling of the data where you split the data in training data and test data. Implement the \( k \)-fold cross-validation algorithm and/or the bootstrap algorithm +and evaluate again the MSE and the \( R^2 \) functions resulting from the test data. Evaluate also the bias and variance of the final models. + +
+Write then your own code for the Ridge method, either using matrix +inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the +previous exercise (for the same polynomials and include resampling +techniques) but now for different values of \( \lambda \). Compare and +analyze your results with those obtained with standard OLS. Study the +dependence on \( \lambda \) while also varying eventually the strength of +the noise in your expression for \( \mathrm{FrankeFunction}(x,y) \). + +
+Then perform the same studies but now with Lasso regression. Use the functionalities of +scikit-learn. Give a critical discussion of the three methods and a +judgement of which model fits the data best. +
-
@@ -457,7 +424,7 @@ MathJax.Hub.Config({
-
-Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) varies as function of another variable or a set of such variables \( \hat{x} =[x_0, x_1,\dots, x_p]^T \). -The first variable is called the dependent, the outcome or the response variable while the set of variables \( \hat{x} \) is called the independent variable, or the predictor variable or the explanatory variable. +
-A regression model aims at finding a likelihood function \( p(y\vert \hat{x}) \), that is the conditional distribution for \( y \) with a given \( \hat{x} \). The estimation of \( p(y\vert \hat{x}) \) is made using a data set with +Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \).
- The goal of the regression analysis is to extract/exploit relationship between \( y_i \) and \( \hat{x}_i \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions .
+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.
+
+
+
+
+Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \).
+The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable.
+
+
+A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with
+
+
+
+ The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{X} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.
Consider an experiment in which \( p \) characteristics of \( n \) samples are
-measured. The data from this experiment are denoted \( \mathbf{X} \), with
-\( \mathbf{X} \) as above. The matrix \( \mathbf{X} \) is called the design
+measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix
+\( \mathbf{X} \).
+
+
+The matrix \( \mathbf{X} \) is called the design
matrix. Additional information of the samples is available in the
-form of \( \mathbf{Y} \) (also as above). The variable \( \mathbf{Y} \) is
+form of \( \boldsymbol{y} \) (also as above). The variable \( \boldsymbol{y} \) is
generally referred to as the response variable. The aim of
-regression analysis is to explain \( \mathbf{Y} \) in terms of
-\( \mathbf{X} \) through a functional relationship like \( Y_i =
+regression analysis is to explain \( \boldsymbol{y} \) in terms of
+\( \boldsymbol{X} \) through a functional relationship like \( y_i =
f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of
\( f(\cdot) \) is available, it is common to assume a linear relationship
-between \( \mathbf{X} \) and \( \mathbf{Y} \). This assumption gives rise to
-the linear regression model where \( \beta = (\beta_1, \ldots,
-\beta_p)^{\top} \) is the regression parameter. The parameter
-\( \beta_j \), \( j=1, \ldots, p \), represents the effect size of covariate
-\( j \) on the response. That is, for each unit change in covariate \( j \)
-(while keeping the other covariates fixed) the observed change in the
-response is equal to \( \beta_j \).
+between \( \boldsymbol{X} \) and \( \boldsymbol{y} \). This assumption gives rise to
+the linear regression model where \( \boldsymbol{\beta} = [\beta_0, \ldots,
+\beta_{p-1}]^{T} \) are the regression parameters.
+
+
+Linear regression gives us a set of analytical equations for the parameters \( \beta_j \).
-Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \hat{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \hat{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function.
+In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \),
+consider the model we discussed for describing nuclear binding energies.
+
+
+There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model.
+Assuming
+
+Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the
+so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \)
+
+
+
+Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function.
Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is
@@ -244,7 +300,7 @@ y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\
y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\
y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\
\dots & \dots \\
-y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_1x_{n-1}^{n-1}+\epsilon_{n-1}.\\
+y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\
\end{align*}
$$
Defining the vectors
-We are obviously not limited to the above polynomial. We could replace the various powers of \( x \) with elements of Fourier series, that is, instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j x_i)} \), or time series or other orthogonal functions.
-For every set of values \( y_i,x_i \) we can then generalize the equations to
+We are obviously not limited to the above polynomial expansions. We
+could replace the various powers of \( x \) with elements of Fourier
+series or instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j
+x_i)} \), or time series or other orthogonal functions. For every set
+of values \( y_i,x_i \) we can then generalize the equations to
+
+Note that we have \( p=n \) here. The matrix is symmetric. This is generally not the case!
-We redefine in turn the matrix \( \hat{X} \) as
+We redefine in turn the matrix \( \boldsymbol{X} \) as
-We have defined the matrix \( \hat{X} \)
+We have defined the matrix \( \boldsymbol{X} \) via the equations
+As we noted above, we stayed with a system with the design matrix
+ \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \), that is we have \( p=n \). For reasons to come later (algorithmic arguments) we will hereafter define
+our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors refering to the column numbers and the entries \( n \) being the row elements.
+
+
+In our introductory notes we looked at the so-called liguid drop model. Let us remind ourselves about what we did by looking at the code.
+
+
+We restate the parts of the code we are most interested in.
+
+
+
+
+With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as
+
-We well use this matrix to define the approximation \( \hat{\tilde{y}} \) via the unknown quantity \( \hat{\beta} \) as
+With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as
+It is also common to define
+the function \( Q \) as
+
+
The function
+where \( \langle y_i \rangle \) is the mean value. Keep in mind also that
+till now we have treated \( y_i \) as the exact value. Normally, the
+response (dependent or outcome) variable \( y_i \) 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.
-In order to find the parameters \( \beta_i \) we will then minimize the spread of \( Q(\hat{\beta}) \) by requiring
+In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem
We can rewrite
+We note also that since our design matrix is defined as \( \boldsymbol{X}\in
+{\mathbb{R}}^{n\times p} \), the product \( \boldsymbol{X}^T\boldsymbol{X} \in
+{\mathbb{R}}^{p\times p} \). In the above case we have that \( p \ll n \),
+in our case \( p=5 \) meaning that we end up with inverting a small
+\( 5\times 5 \) matrix. This is a rather common situation, in many cases we end up with low-dimensional
+matrices to invert. The methods discussed here and for many other
+supervised learning algorithms like classification with logistic
+regression or support vector machines, exhibit dimensionalities which
+allow for the usage of direct linear algebra methods such as LU decomposition or Singular Value Decomposition (SVD) for finding the inverse of the matrix
+\( \boldsymbol{X}^T\boldsymbol{X} \).
+
-The residuals \( \hat{\epsilon} \) are in turn given by
+The residuals \( \boldsymbol{\epsilon} \) are in turn given by
+Let us now return to our nuclear binding energies and simply code the above equations.
+
+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
+write
+
+
+
+
+Alternatively, you can use the least squares functionality in Numpy as
+
+
+
+
+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.
+Since we are not using _Scikit-Learn here we can define our own \( R2 \) function as
+
+
+
+
+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
+
+
-Normally, the response (dependent or outcome) variable \( y_i \) 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 as
-
+In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring
-In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\hat{\beta}) \) by requiring
-
We can rewrite
If we then introduce the matrix
@@ -655,14 +959,14 @@ $$
By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by
-For a linear fit we don't need to invert a matrix!!
+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.
+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
+nuclear equation of state using results from many-body calculations.
+The equation of state we have made available here, as function of
+density, has been derived using modern nucleon-nucleon potentials with
+the addition of three-body
+forces. This
+time the file is presented as a standard csv file.
+
+
+The beginning of the Python code here is similar to what you have seen before,
+with the same initializations and declarations. We use also pandas
+again, rather extensively in order to organize our data.
+
+
+The difference now is that we use Scikit-Learn's regression tools
+instead of our own matrix inversion implementation. Furthermore, we
+sneak in Ridge regression (to be discussed below) which includes a
+hyperparameter \( \lambda \), also to be explained below.
+
-
-
-
-
-We see that, as expected, a linear fit gives a seemingly (from the graph) good representation of the data.
-
-
-
-
-We can repeat the above algorithm using scikit-learn as follows
-
-
-
-
-We start with perhaps our simplest possible example, using scikit-learn to perform linear regression analysis on a data set produced by us.
-What follows is a simple Python code where we have defined function \( y \) in terms of the variable \( x \). Both are defined as vectors of dimension \( 1\times 100 \). The entries to the vector \( \hat{x} \) are given by random numbers generated with a uniform distribution with entries \( x_i \in [0,1] \) (more about probability distribution functions later). These values are then used to define a function \( y(x) \) (tabulated again as a vector) with a linear dependence on \( x \) plus a random noise added via the normal distribution.
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
-
-The Numpy functions are imported used the import numpy as np
-statement and the random number generator for the uniform distribution
-is called using the function np.random.rand(), where we specificy
-that we want \( 100 \) random variables. Using Numpy we define
-automatically an array with the specified number of elements, \( 100 \) in
-our case. With the Numpy function randn() we can compute random
-numbers with the normal distribution (mean value \( \mu \) equal to zero and
-variance \( \sigma^2 \) set to one) and produce the values of \( y \) assuming a linear
-dependence as function of \( x \)
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
-
-where \( N(0,1) \) represents random numbers generated by the normal
-distribution. From scikit-learn we import then the
-LinearRegression functionality and make a prediction \( \tilde{y} =
-\alpha + \beta x \) using the function fit(x,y). We call the set of
-data \( (\hat{x},\hat{y}) \) for our training data. The Python package
-scikit-learn has also a functionality which extracts the above
-fitting parameters \( \alpha \) and \( \beta \) (see below). Later we will
-distinguish between training data and test data.
+infile = open(data_path("EoS.csv"),'r')
-
-For plotting we use the Python package
-matplotlib which produces publication
-quality figures. Feel free to explore the extensive
-gallery of examples. In
-this example we plot our original values of \( x \) and \( y \) as well as the
-prediction ypredict (\( \tilde{y} \)), which attempts at fitting our
-data with a straight line.
+# Read the EoS data as csv file and organize the data into two arrays with density and energies
+EoS = pd.read_csv(infile, names=('Density', 'Energy'))
+EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
+EoS = EoS.dropna()
+Energies = EoS['Energy']
+Density = EoS['Density']
+# The design matrix now as function of various polytrops
+X = np.zeros((len(Density),4))
+X[:,3] = Density**(4.0/3.0)
+X[:,2] = Density
+X[:,1] = Density**(2.0/3.0)
+X[:,0] = 1
-
-The Python code follows here.
-
-
-
-
-This example serves several aims. It allows us to demonstrate several
-aspects of data analysis and later machine learning algorithms. The
-immediate visualization shows that our linear fit is not
-impressive. It goes through the data points, but there are many
-outliers which are not reproduced by our linear regression. We could
-now play around with this small program and change for example the
-factor in front of \( x \) and the normal distribution. Try to change the
-function \( y \) to
-
-
-where \( x \) is defined as before.
-
-Does the fit look better? Indeed, by
-reducing the role of the normal distribution we see immediately that
-our linear prediction seemingly reproduces better the training
-set. However, this testing 'by the eye' is obviouly not satisfactory in the
-long run. Here we have only defined the training data and our model, and
-have not discussed a more rigorous approach to the cost function.
-
-We need more rigorous criteria in defining whether we have succeeded or
-not in modeling our training data. You will be surprised to see that
-many scientists seldomly venture beyond this 'by the eye' approach. A
-standard approach for the cost function is the so-called \( \chi^2 \)
-function
-
-
-where \( \sigma_i^2 \) is the variance (to be defined later) of the entry
-\( y_i \). We may not know the explicit value of \( \sigma_i^2 \), it serves
-however the aim of scaling the equations and make the cost function
-dimensionless.
-
-Minimizing the cost function is a central aspect of
-our discussions to come. Finding its minima as function of the model
-parameters (\( \alpha \) and \( \beta \) in our case) will be a recurring
-theme in these series of lectures. Essentially all machine learning
-algorithms we will discuss center around the minimization of the
-chosen cost function. This depends in turn on our specific
-model for describing the data, a typical situation in supervised
-learning. Automatizing the search for the minima of the cost function is a
-central ingredient in all algorithms. Typical methods which are
-employed are various variants of gradient methods. These will be
-discussed in more detail later. Again, you'll be surprised to hear that
-many practitioners minimize the above function ''by the eye', popularly dubbed as
-'chi by the eye'. That is, change a parameter and see (visually and numerically) that
-the \( \chi^2 \) function becomes smaller.
-
-There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define
-the relative error as
-
-
-
-
-
-Depending on the parameter in front of the normal distribution, we may
-have a small or larger relative error. Try to play around with
-different training data sets and study (graphically) the value of the
-relative error.
-
-As mentioned above, scikit-learn has an impressive functionality.
-We can for example extract the values of \( \alpha \) and \( \beta \) and
-their error estimates, or the variance and standard deviation and many
-other properties from the statistical data analysis.
-
-
-Here we show an
-example of the functionality of scikit-learn.
-
-
-
-
+The above simple polynomial in density \( \rho \) gives an excellent fit
+to the data. Can you give an interpretation of the various powers of \( \rho \)?
+
+
+We note also that there is a small deviation between the
+standard OLS and the Ridge regression at higher densities. We discuss this in more detail
+below.
-The function coef gives us the parameter \( \beta \) of our fit while intercept yields
-\( \alpha \). Depending on the constant in front of the normal distribution, we get values near or far from \( alpha =2 \) and \( \beta =5 \). Try to play around with different parameters in front of the normal distribution. The function meansquarederror gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as
-
-The smaller the value, the better the fit. Ideally we would like to
-have an MSE equal zero. The attentive reader has probably recognized
-this function as being similar to the \( \chi^2 \) function defined above.
-
-The r2score function computes \( R^2 \), the coefficient of
-determination. It provides a measure of how well future samples are
-likely to be predicted by the model. Best possible score is 1.0 and it
-can be negative (because the model can be arbitrarily worse). A
-constant model that always predicts the expected value of \( \hat{y} \),
-disregarding the input features, would get a \( R^2 \) score of \( 0.0 \).
-
-
-If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as
-
-Another quantity will meet again in our discussions of regression analysis is
- mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the \( l1 \)-norm loss. In our discussion above we presented the relative error.
-The MAE is defined as follows
-
-where \( \log_e (x) \) stands for the natural logarithm of \( x \). This error
-estimate is best to use when targets having exponential growth, such
-as population counts, average sales of a commodity over a span of
-years etc.
-
-We will discuss in more
-detail these and other functions in the various lectures. We conclude this part with another example. Instead of
-a linear \( x \)-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn.
-Add description of the various python commands.
+It is normal in essentially all Machine Learning studies to split the
+data in a training set and a test set (sometimes also an additional
+validation set). Scikit-Learn has an own function for this. There
+is no explicit recipe for how much data should be included as training
+data and say test data. An accepted rule of thumb is to use
+approximately \( 2/3 \) to \( 4/5 \) of the data as training data. We will
+postpone a discussion of this splitting to the end of these notes and
+our discussion of the so-called bias-variance tradeoff. Here we
+limit ourselves to repeat the above equation of state fitting example
+but now splitting the data into a training set and a test set.
-
-Using R, we can perform similar studies.
-
-
-
-
-Before we proceed, and to link with our discussions of Bayesian statistics to come, it is useful the derive the standard regression analysis equations using a statistical interpretation. This allows us also to derive quantities like the variance and other expectation values in a rather straightforward way.
-
-
-It is assumed that \( \varepsilon_i
-\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are
-independent, i.e.:
-
-Its expectation equals:
-
-A general
-\( m\times n \) matrix \( \hat{A} \) can be written in terms of a diagonal
-matrix \( \hat{D} \) of dimensionality \( n\times n \) and two orthognal
-matrices \( \hat{U} \) and \( \hat{V} \), where the first has dimensionality
-\( m \times m \) and the last dimensionality \( n\times n \).
-We have then
-
+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.
+
+
+The one-dimensional Ising model with nearest neighbor interaction, no
+external field and a constant coupling constant \( J \) is given by
+
+
+where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins
+in the system is determined by \( L \). For the one-dimensional system
+there is no phase transition.
+
+
+We will look at a system of \( L = 40 \) spins with a coupling constant of
+\( J = 1 \). To get enough training data we will generate 10000 states
+with their respective energies.
+
+
+
+
+
+Here we use ordinary least squares
+regression to predict the energy for the nearest neighbor
+one-dimensional Ising model on a ring, i.e., the endpoints wrap
+around. We will use linear regression to fit a value for
+the coupling constant to achieve this.
+
+A more general form for the one-dimensional Ising model is
+
+
+Here we allow for interactions beyond the nearest neighbors and a state dependent
+coupling constant. This latter expression can be formulated as
+a matrix-product
+
+where \( X_{jk} = s_j s_k \) and \( J \) is a matrix which consists of the
+elements \( -J_{jk} \). This form of writing the energy fits perfectly
+with the form utilized in linear regression, that is
+
+
+We split the data in training and test data as discussed in the previous example
+
+
+
+
+
+In the ordinary least squares method we choose the cost function
+
+
+We then find the extremal point of \( C \) by taking the derivative with respect to \( \boldsymbol{\beta} \) as discussed above.
+This yields the expression for \( \boldsymbol{\beta} \) to be
+
+
+which immediately imposes some requirements on \( \boldsymbol{X} \) as there must exist
+an inverse of \( \boldsymbol{X}^T \boldsymbol{X} \). If the expression we are modeling contains an
+intercept, i.e., a constant term, we must make sure that the
+first column of \( \boldsymbol{X} \) consists of \( 1 \). We do this here
+
+
+
+
+
+
+
+
+Doing the inversion directly turns out to be a bad idea since the matrix
+\( \boldsymbol{X}^T\boldsymbol{X} \) is singular. An alternative approach is to use the singular
+value decomposition. Using the definition of the Moore-Penrose
+pseudoinverse we can write the equation for \( \boldsymbol{\beta} \) as
+
+
+where the pseudoinverse of \( \boldsymbol{X} \) is given by
+
+
+Using singular value decomposition we can decompose the matrix \( \boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma} \boldsymbol{V}^T \),
+where \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal(unitary) matrices and \( \boldsymbol{\Sigma} \) contains the singular values (more details below).
+where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for
+\( \omega \) to
+
+Note that solving this equation by actually doing the pseudoinverse
+(which is what we will do) is not a good idea as this operation scales
+as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a
+general matrix. Instead, doing \( QR \)-factorization and solving the
+linear system as an equation would reduce this down to
+\( \mathcal{O}(n^2) \) operations.
+
+
+
+
+
+
+
+
+When extracting the \( J \)-matrix we need to make sure that we remove the intercept, as is done here
+
+
+
+
+
+A way of looking at the coefficients in \( J \) is to plot the matrices as images.
+
+
+
+
+
+It is interesting to note that OLS
+considers both \( J_{j, j + 1} = -0.5 \) and \( J_{j, j - 1} = -0.5 \) as
+valid matrix elements for \( J \).
+In our discussion below on hyperparameters and Ridge and Lasso regression we will see that
+this problem can be removed, partly and only with Lasso regression.
+
+
+In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD?
+
One of the typical problems we encounter with linear regression, in particular
-when the matrix \( \hat{X} \) (our so-called design matrix) is high-dimensional,
-are problems with near singular or singular matrices. The column vectors of \( \hat{X} \)
+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
@@ -1309,7 +1569,7 @@ $$
-The columns of \( \hat{X} \) are linearly dependent. We se this easily since the
+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
@@ -1317,11 +1577,11 @@ 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 \( \hat{X}^T\hat{x} \) (the matrix we needto 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
+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 \( \hat{X} \) which enters the linear regression problem
+If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem
-The ad hoc approach which was introduced in the 70s was simply to add a diagonal component to the matrix to invert, that is we change
+A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change
-We start by considering the case
-\( f(x)=2x \).
+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
+
+
-Then the data is clearly generated by a model that is contained within
-all three model classes we are using to make predictions (linear
-models, third order polynomials, and tenth order polynomials).
+Not all square matrices are diagonalizable. A matrix like the one discussed above
+
-Run the code for the following cases:
+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 \( n\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!
+
+Consider the following matrix which can be SVD decomposed as
+
+
+This is a \( 3\times 2 \) matrix which is decomposed in terms of a
+\( 3\times 3 \) matrix \( \boldsymbol{U} \), and a \( 2\times 2 \) matrix \( \boldsymbol{V} \). It is easy to see
+that \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal (how?).
+
+
+And the SVD
+decomposition (singular values) gives eigenvalues
+\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=2 \), 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\lg 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.
+
+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
+
+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
+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.
+
+Before we proceed, we need to rethink what we have been doing. In our
+eager to fit the data, we have omitted several important elements in
+our regression analysis. In what follows we will
-Repeat the exercises above for \( f(x)=2x \) , \( Ntrain=100 \) , and \( \sigma=1 \) . What changes?
-Summarize what you have learned about the relationship between model complexity (number of parameters), goodness of fit on training data, and the ability to predict well.
+This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods.
-Thus far, we have considered the case where the data is generated using a model contained in the model class. Now consider \( f(x)=2x-10x^5+15x^{10} \) . Notice that the for linear and third-order polynomial the true model \( f(x) \) is not contained in model class.
-
-
-
-Summarize what you think you learned about the relationship of knowing the true model class and predictive power.
-
-
-
-
-
-
-
-In Ridge regression and the subsequent discussion of its properties
-the bias or penalty parameter is considered known or `given'. In
-practice, it is unknown and the user needs to make an informed
-decision on its value. How do we do that? Much of the same considerations apply to the Lasso method.
-
-
-
-
-
-
-
@@ -1778,7 +2089,7 @@ once using the original training sample.
@@ -1797,20 +2108,19 @@ of flexibility. The process of evaluating a model’s performance is
known as model assessment, whereas the process of selecting the proper
level of flexibility for a model is known as model selection. The
bootstrap is widely used.
+
+
@@ -1874,7 +2182,7 @@ selection of a large set of these numbers reproduces this PDF.
@@ -1900,7 +2208,7 @@ $$
@@ -1921,14 +2229,14 @@ $$
\begin{align}
\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle =
\int\! (x-\langle x\rangle)^2 p(x)\,dx
-\tag{2}\\
+\tag{8}\\
& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} +
\langle x\rangle^2\right)p(x)\,dx
-\tag{3}\\
+\tag{9}\\
& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2
-\tag{4}\\
+\tag{10}\\
& = \langle x^2\rangle - \langle x\rangle^2
-\tag{5}
+\tag{11}
\end{align}
$$
@@ -1958,7 +2266,7 @@ $$
&=
\int\!\cdots\!\int\!(x_i-\langle x_i \rangle)(x_j-\langle x_j \rangle)\,
P(x_1,\dots,x_n)\,dx_1\dots dx_n
-\tag{6}
+\tag{12}
\end{align}
$$
@@ -1989,17 +2297,17 @@ the expectation value. Consider the stochastic variables \( X_i \) and
$$
\begin{align}
\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle
-\tag{7}\\
+\tag{13}\\
&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle
-\tag{8}\\
+\tag{14}\\
&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle +
\langle \langle x_i\rangle\langle x_j\rangle\rangle
-\tag{9}\\
+\tag{15}\\
&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle +
\langle x_i\rangle\langle x_j\rangle
-\tag{10}\\
+\tag{16}\\
&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle
-\tag{11}
+\tag{17}
\end{align}
$$
@@ -2037,7 +2345,7 @@ $$
@@ -2047,7 +2355,7 @@ the variance of the linear combination \( U = \sum_i a_i X_i \):
$$
\begin{equation}
\mathrm{var}(U) = \sum_{i,j}a_i a_j \mathrm{cov}(X_i, X_j)
-\tag{12}
+\tag{18}
\end{equation}
$$
@@ -2103,7 +2411,7 @@ interested in finding the few lowest moments, like the mean
@@ -2134,12 +2442,12 @@ $$
Note that the sample variance is the sample covariance without the
-cross terms. In a similar manner as the covariance in Eq. (6) is a measure of the correlation between
+cross terms. In a similar manner as the covariance in Eq. (12) is a measure of the correlation between
two stochastic variables, the above defined sample covariance is a
measure of the sequential correlation between succeeding measurements
of a sample.
@@ -2154,7 +2462,7 @@ and covariance \( \mathrm{cov}(X,Y) \).
@@ -2187,7 +2495,7 @@ true PDFs behind, which we usually do not have.
@@ -2210,7 +2518,7 @@ means.
@@ -2232,7 +2540,7 @@ And in particular we are interested in its variance \( \mathrm{var}(\overline X_
@@ -2249,7 +2557,7 @@ $$
\lim_{n\to\infty} p_{\overline X_n}(x) =
\left(\frac{n}{2\pi\mathrm{var}(X)}\right)^{1/2}
e^{-\frac{n(x-\bar x_n)^2}{2\mathrm{var}(X)}}
-\tag{13}
+\tag{19}
\end{equation}
$$
@@ -2270,7 +2578,7 @@ $$
\begin{equation}
\mathrm{err}_X^2 = \mathrm{var}(\overline X_n) = \frac{1}{n^2}
\sum_{ij} \mathrm{cov}(X_i, X_j)
-\tag{14}
+\tag{20}
\end{equation}
$$
@@ -2301,7 +2609,7 @@ $$
@@ -2337,7 +2645,7 @@ which is approximated as
$$
\begin{equation}
\mathrm{var}(X_i)\approx \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)=\mathrm{var}(x)
-\tag{15}
+\tag{21}
\end{equation}
$$
@@ -2384,12 +2692,12 @@ resulting in
$$
\begin{equation}
\mathrm{err}_X^2\approx \frac{1}{n^2} \sum_i \mathrm{var}(x)= \frac{1}{n}\mathrm{var}(x)
-\tag{17}
+\tag{23}
\end{equation}
$$
For computational purposes one usually splits up the estimate of
-\( \mathrm{err}_X^2 \), given by Eq. (16), into two
+\( \mathrm{err}_X^2 \), given by Eq. (22), into two
parts
@@ -2455,7 +2763,7 @@ have to be stored throughout the experiment.
@@ -2493,11 +2801,11 @@ starting always at \( 1 \) for \( d=0 \).
-The sample error (see eq. (18)) can now be
+The sample error (see eq. (24)) can now be
written in terms of the autocorrelation function:
For a correlation free experiment, \( \tau \)
equals 1. From the point of view of
-eq. (19) we can interpret a sequential
+eq. (25) we can interpret a sequential
correlation as an effective reduction of the number of measurements by
a factor \( \tau \). The effective number of measurements becomes:
-A popular strategy is to choose a penalty parameter that yields a good
-but parsimonious model. Information criteria measure the balance
-between model fit and model complexity. One possibility is Aikaike's
-information criterion (AIC).
-The AIC measures model fit by the log-likelihood
-and model complexity is measured by the number of parameters used by
-the model. The number of model parameters in regular regression simply
-corresponds to the number of covariates in the model. Or, by the
-degrees of freedom consumed by the model, which is equivalent to the
-trace of the hat matrix. For ridge regression it thus seems natural to
-define model complexity analogously by the trace of the ridge hat
-matrix. This yields the AIC for the linear regression model with ridge
-estimates:
+Finally, we are going to discuss several statistical properties which can be obtained in terms of analytical expressions.
+The
+advantage of doing linear regression is that we actually end up with
+analytical expressions for several statistical quantities.
+Standard least squares and Ridge regression allow us to
+derive quantities like the variance and other expectation values in a
+rather straightforward way.
+
+It is assumed that \( \varepsilon_i
+\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are
+independent, i.e.:
+Recall that \( \boldsymbol{X} \) is a matrix of dimensionality \( n\times p \). The
+notation above \( \mathbf{X}_{i,\ast} \) means that we are looking at the
+row number \( i \) and perform a sum over all values \( p \).
+The assumption we have made here can be summarized as (and this is going to useful when we discuss the bias-variance trade off)
+that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \)
+which describes our data
+
+We approximate this function with our model from the solution of the linear regression equations, that is our
+function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we want to minimize \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), our MSE, with
+
+We can calculate the expectation value of \( \boldsymbol{y} \) for a given element \( i \)
+
+With the OLS expressions for the parameters \( \boldsymbol{\beta} \) we can evaluate the expectation value
+
+We can also calculate the variance
+
+
+The variance of \( \boldsymbol{\beta} \) is
+
+where we have used that \( \mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) =
+\mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} +
+\sigma^2 \, \mathbf{I}_{nn} \). From \( \mbox{Var}(\boldsymbol{\beta}) = \sigma^2
+\, (\mathbf{X}^{T} \mathbf{X})^{-1} \), one obtains an estimate of the
+variance of the estimate of the \( j \)-th regression coefficient:
+\( \hat{\sigma}^2 (\hat{\beta}_j ) = \hat{\sigma}^2 \sqrt{
+[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} } \). This may be used to
+construct a confidence interval for the estimates.
+
+
+In a similar way, we cna obtain analytical expressions for say the
+expectation values of the parameters \( \boldsymbol{\beta} \) and their variance
+when we employ Ridge regression, and thereby a confidence interval.
+
+
+It is rather straightforward to show that
+
+We can also compute the variance as
+
+
+With this, we can compute the difference
+
+
Instead of choosing the penalty parameter to balance model fit with
@@ -2598,12 +3069,15 @@ model complexity, cross-validation requires it (i.e. the penalty
parameter) to yield a model with good prediction
performance. Commonly, this performance is evaluated on novel
data. Novel data need not be easy to come by and one has to make do
-with the data at hand. The setting of `original' and novel data is
+with the data at hand.
+
+
+The setting of original and novel data is
then mimicked by sample splitting: the data set is divided into two
-(groups of samples). One of these two data sets, called the training
-set, plays the role of `original' data on which the model is
+(groups of samples). One of these two data sets, called the
+training set, plays the role of original data on which the model is
built. The second of these data sets, called the test set, plays the
-role of the `novel' data and is used to evaluate the prediction
+role of the novel data and is used to evaluate the prediction
performance (often operationalized as the log-likelihood or the
prediction error or its square or the R2 score) of the model built on the training data set. This
procedure (model building and prediction evaluation on training and
@@ -2621,7 +3095,7 @@ some sense) is then selected.
The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks:
@@ -2634,7 +3108,7 @@ The validation set approach is conceptually simple and is easy to implement. But
When the repetitive splitting of the data set is done randomly,
@@ -2655,33 +3129,33 @@ cross-validation (LOOCV).
-Another approach in the LOOCV scheme is to the use the so-called Predicted Residual Error Sum of Squares (PRESS).
-
-
-We can define the optimal penalty parameter to minimize
-
-The LOOCV prediction performance can be
-expressed analytically in terms of the known quantities derived from
-the design matrix and the parameters \( \beta \).
-
Two famous
@@ -2742,42 +3191,26 @@ need for bootstrapping.
The Jackknife works by making many replicas of the estimator \( \widehat{\theta} \).
-The jackknife is a resampling method, we explained that this happens by scrambling the data in some way. When using the jackknife, this is done by systematically leaving out one observation from the vector of observed values \( \hat{x} = (x_1,x_2,\cdots,X_n) \).
-Let \( \hat{x}_i \) denote the vector
+The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \( \boldsymbol{x} = (x_1,x_2,\cdots,X_n) \).
+Let \( \boldsymbol{x}_i \) denote the vector
-which equals the vector \( \hat{x} \) with the exception that observation
+which equals the vector \( \boldsymbol{x} \) with the exception that observation
number \( i \) is left out. Using this notation, define
\( \widehat{\theta}_i \) to be the estimator
\( \widehat{\theta} \) computed using \( \vec{X}_i \).
-To get an estimate for the bias and
-standard error of \( \widehat{\theta} \), use the following
-estimators for each component of \( \widehat{\theta} \)
-
-
@@ -2841,14 +3274,14 @@ advantages:
-Since \( \widehat{\theta} = \widehat{\theta}(\hat{X}) \) is a function of random variables,
+Since \( \widehat{\theta} = \widehat{\theta}(\boldsymbol{X}) \) is a function of random variables,
\( \widehat{\theta} \) itself must be a random variable. Thus it has
-a pdf, call this function \( p(\hat{t}) \). The aim of the bootstrap is to
-estimate \( p(\hat{t}) \) by the relative frequency of
+a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to
+estimate \( p(\boldsymbol{t}) \) by the relative frequency of
\( \widehat{\theta} \). You can think of this as using a histogram
-in the place of \( p(\hat{t}) \). If the relative frequency closely
+in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely
resembles \( p(\vec{t}) \), then using numerics, it is straight forward to
-estimate all the interesting parameters of \( p(\hat{t}) \) using point
+estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point
estimators.
-When you are done, you can draw a histogram of the relative frequency of \( \widehat \theta^* \). This is your estimate of the probability distribution \( p(t) \). Using this probability distribution you can estimate any statistics thereof. In principle you never draw the histogram of the relative frequency of \( \widehat{\theta}^* \). Instead you use the estimators corresponding to the statistic of interest. For example, if you are interested in estimating the variance of \( \widehat \theta \), apply the etsimator \( \widehat \sigma^2 \) to the values \( \widehat \theta ^* \).
+When you are done, you can draw a histogram of the relative frequency
+of \( \widehat \theta^* \). This is your estimate of the probability
+distribution \( p(t) \). Using this probability distribution you can
+estimate any statistics thereof. In principle you never draw the
+histogram of the relative frequency of \( \widehat{\theta}^* \). Instead
+you use the estimators corresponding to the statistic of interest. For
+example, if you are interested in estimating the variance of \( \widehat
+\theta \), apply the etsimator \( \widehat \sigma^2 \) to the values
+\( \widehat \theta ^* \).
+The following code starts with a Gaussian distribution with mean value
+\( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data
+used in the bootstrap analysis. The bootstrap analysis returns a data
+set after a given number of bootstrap operations (as many as we have
+data points). This data set consists of estimated mean values for each
+bootstrap operation. The histogram generated by the bootstrap method
+shows that the distribution for these mean values is also a Gaussian,
+centered around the mean value \( \mu=100 \) but with standard deviation
+\( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in
+this case the same as the number of original data points). The value
+of the standard deviation is what we expect from the central limit
+theorem.
+
@@ -2931,30 +3386,29 @@ The following code starts with a Gaussian distribution with mean value \( \mu =1
def stat(data):
return mean(data)
-# Bootstrap algorithm
+# Bootstrap algorithm
def bootstrap(data, statistic, R):
t = zeros(R); n = len(data); inds = arange(n); t0 = time()
-
- # non-parametric bootstrap
+ # non-parametric bootstrap
for i in range(R):
t[i] = statistic(data[randint(0,n,n)])
- # analysis
+ # analysis
print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
print("original bias std. error")
- print("%8g %8g %14g %15g" % (statistic(data), std(data),\
- mean(t), \
- std(t)))
+ print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
return t
mu, sigma = 100, 15
datapoints = 10000
x = mu + sigma*random.randn(datapoints)
-# bootstrap returns the data sample t = bootstrap(x, stat, datapoints)
-# the histogram of the bootstrapped data n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
+# bootstrap returns the data sample
+t = bootstrap(x, stat, datapoints)
+# the histogram of the bootstrapped data
+n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
-# add a 'best fit' line
+# add a 'best fit' line
y = mlab.normpdf( binsboot, mean(t), std(t))
lt = plt.plot(binsboot, y, 'r--', linewidth=1)
plt.xlabel('Smarts')
@@ -2968,557 +3422,314 @@ plt.show()
-The blocking method was made popular by Flyvbjerg and Pedersen (1989)
-and has become one of the standard ways to estimate
-\( V(\widehat{\theta}) \) for exactly one \( \widehat{\theta} \), namely
-\( \widehat{\theta} = \overline{X} \).
-
-
-Assume \( n = 2^d \) for some integer \( d>1 \) and \( X_1,X_2,\cdots, X_n \) is a stationary time series to begin with.
-Moreover, assume that the time series is asymptotically uncorrelated. We switch to vector notation by arranging \( X_1,X_2,\cdots,X_n \) in an \( n \)-tuple. Define:
-
-The strength of the blocking method is when the number of
-observations, \( n \) is large. For large \( n \), the complexity of dependent
-bootstrapping scales poorly, but the blocking method does not,
-moreover, it becomes more accurate the larger \( n \) is.
-
-The quantity \( \vec{X}_k \) is
-subject to \( k \) blocking transformations. We now have \( d \) vectors
-\( \vec{X}_0, \vec{X}_1,\cdots,\vec X_{d-1} \) containing the subsequent
-averages of observations. It turns out that if the components of
-\( \vec{X} \) is a stationary time series, then the components of
-\( \vec{X}_i \) is a stationary time series for all \( 0 \leq i \leq d-1 \)
-
-
-We can then compute the autocovariance, the variance, sample mean, and
-number of observations for each \( i \).
-Let \( \gamma_i, \sigma_i^2,
-\overline{X}_i \) denote the autocovariance, variance and average of the
-elements of \( \vec{X}_i \) and let \( n_i \) be the number of elements of
-\( \vec{X}_i \). It follows by induction that \( n_i = n/2^i \).
-
-Using the
-definition of the blocking transformation and the distributive
-property of the covariance, it is clear that since \( h =|i-j| \)
-we can define
-
-The quantity \( \hat{X} \) is asymptotic uncorrelated by assumption, \( \hat{X}_k \) is also asymptotic uncorrelated. Let's turn our attention to the variance of the sample mean \( V(\overline{X}) \).
-
-We can then wrap up
-
-Fyvbjerg and Petersen demonstrated that the sequence
-\( \{e_k\}_{k=0}^{d-1} \) is decreasing, and conjecture that the term
-\( e_k \) can be made as small as we would like by making \( k \) (and hence
-\( d \)) sufficiently large. The sequence is decreasing (Master of Science thesis by Marius Jonsson, UiO 2018).
-It means we can apply blocking transformations until
-\( e_k \) is sufficiently small, and then estimate \( V(\overline{X}) \) by
-\( \widehat{\sigma}^2_k/n_k \).
-
-
-We begin with an unknown function \( y=f(x) \) and fix a \emph{hypothesis set}
- \( \mathcal{H} \) consisting of all functions we are willing to consider,
- defined also on the domain of \( f \). This set may be uncountably
- infinite (e.g. if there are real-valued parameters to fit).
-The
- choice of which functions to include in \( \mathcal{H} \) usually depends
- on our intuition about the problem of interest. The function \( f(x) \)
- produces a set of pairs \( (x_i,y_i) \), \( i=1\dots N \), which serve as the
- observable data. Our goal is to select a function from the hypothesis
- set \( h\in\mathcal{H} \) which approximates \( f(x) \) as best as possible,
- namely, we would like to find \( h\in\mathcal{H} \) such that \( h\approx
- f \) in some strict mathematical sense which we specify below. If this
- is possible, we say that we \emph{learned} \( f(x) \). But if the
- function \( f(x) \) can, in principle, take any value on
- \emph{unobserved} inputs, how is it possible to learn in any
- meaningful sense?
+We will discuss the bias-variance tradeoff in the context of
+continuous predictions such as regression. However, many of the
+intuitions and ideas discussed here also carry over to classification
+tasks. Consider a dataset \( \mathcal{L} \) consisting of the data
+\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \).
+
+
+Let us assume that the true data is generated from a noisy model
+
+
+where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \).
+
+
+In our derivation of the ordinary least squares method we defined then
+an approximation to the function \( f \) in terms of the parameters
+\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model,
+that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \).
+
+
+Thereafter we found the parameters \( \boldsymbol{\beta} \) by optimizing the means squared error via the so-called cost function
+
+We can rewrite this as
+
+The three terms represent the square of the bias of the learning
+method, which can be thought of as the error caused by the simplifying
+assumptions built into the method. The second term represents the
+variance of the chosen model and finally the last terms is variance of
+the error \( \boldsymbol{\epsilon} \).
+
+
+To derive this equation, we need to recall that the variance of \( \boldsymbol{y} \) and \( \boldsymbol{\epsilon} \) are both equal to \( \sigma^2 \). The mean value of \( \boldsymbol{\epsilon} \) is by definition equal to zero. Furthermore, the function \( f \) is not a stochastics variable, idem for \( \boldsymbol{\tilde{y}} \).
+We use a more compact notation in terms of the expectation value
+
-We will discuss the bias-variance tradeoff in the context of continuous predictions such as regression. However, many of the intuitions and ideas discussed here also carry over to classification tasks. Consider a dataset \( \mathcal{L} \) consisting of the data \( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=1\ldots N\} \). Let us assume that the true data is generated from a noisy model
-
-We have a statistical procedure (e.g. least-squares regression) for
-forming a predictor \( \hat{g}_{\mathcal{L}}(\boldsymbol{x}) \) that gives the
-prediction of our model for a new data point \( \boldsymbol{x} \). This estimator
-is chosen by minimizing a cost function which we take to be the
-squared error
-
-We are interested in the generalization error on all data drawn from
-the true model, not just the error on the particular training dataset
-\( \mathcal{L} \) that we have in hand. This is just the expectation of
-the cost function over many different data sets
-\( \{\mathcal{L}_j\} \). Denote this expectation value by
-\( E_{\mathcal{L}} \). In other words, we can view \( \hat{g}_{\mathcal{L}} \)
-as a stochastic functional that depends on the dataset \( \mathcal{L} \)
-and we can think of \( E_{\mathcal{L}} \) as the expected value of the
-functional if we drew an infinite number of datasets \( \{\mathcal{L}_1,
-\mathcal{L}_2, \ldots \} \).
-
-We would also like to average over different instances of the
-"noise" \( \epsilon \) and we denote the expectation value over the
-noise by \( E_\epsilon \). Thus, we can decompose the expected
-generalization error as
-
-
-where in the last line we used the fact that our noise has zero mean
-and variance \( \sigma_\epsilon^2 \) and the sum over \( i \) applies to all
-terms.
-
-It is also helpful to further decompose the second term as
-follows:
-
-
-The first term is called the bias
-
-and measures how much our estimator fluctuates due to finite-sample effects. Combining these expressions, we see that the expected out-of-sample error of our model can be decomposed as
-
The bias-variance tradeoff summarizes the fundamental tension in
machine learning, particularly supervised learning, between the
complexity of a model and the amount of training data needed to train
it. Since data is often limited, in practice it is often useful to
-use a less-complex model with higher bias – a model whose asymptotic
-performance is worse than another model – because it is easier to
+use a less-complex model with higher bias, that is a model whose asymptotic
+performance is worse than another model because it is easier to
train and less sensitive to sampling noise arising from having a
finite-sized training dataset (smaller variance).
-
The above equations tell us that in
@@ -3542,16 +3753,101 @@ flexible statistical methods have higher variance.
+
+
+
-The one-dimensional Ising model with nearest neighbor interaction, no external field and a constant coupling constant \( J \) is given by
+Let us bring back the Ising model again, but now with an additional
+focus on Ridge and Lasso regression as well. We repeat some of the
+basic parts of the Ising model and the setup of the training and test
+data. The one-dimensional Ising model with nearest neighbor
+interaction, no external field and a constant coupling constant \( J \) is
+given by
-Here we use linear (ordinary least squares), ridge and LASSO
-regression to predict the energy in the nearest neighbor
-one-dimensional Ising model on a ring, i.e., the endpoints wrap
-around. We will use the linear regression models to fit a value for
-the coupling constant to achieve this.
-
A more general form for the one-dimensional Ising model is
@@ -3605,7 +3889,7 @@ A more general form for the one-dimensional Ising model is
$$
\begin{align}
H = - \sum_j^L \sum_k^L s_j s_k J_{jk}.
-\tag{31}
+\tag{28}
\end{align}
$$
@@ -3655,169 +3940,8 @@ X_test_own = np.concatenate(
axis=1
)
-The problem at hand is to try to fit the equation
-
-where \( f(x) \) is some unknown function of the data \( x \) and \( \epsilon \)
-is normally distributed with mean zero noise with standard deviation
-\( \sigma_{\epsilon} \). Our job is to try to find a predictor which
-estimates the function \( f(x) \). In linear regression we assume that we
-can formulate the problem as
-
-
-where \( X \) and \( \omega \) are now matrices. Our job at hand is now to
-find a cost function \( C \), which we wish to minimize in order to find
-the best estimate of \( \omega \).
-
-In the ordinary least squares method we choose the cost function
-
-which immediately imposes some requirements on \( X \) as there must exist
-an inverse of \( X^T X \). If the expression we are modelling contains an
-intercept, i.e., a constant expression we must make sure that the
-first column of \( X \) consists of \( 1 \).
-
-
-
-
-
-Using singular value decomposition we have that \( X = U\Sigma V^T \),
-where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for
-\( \omega \) to
-
-Note that solving this equation by actually doing the pseudoinverse
-(which is what we will do) is not a good idea as this operation scales
-as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a
-general matrix. Instead, doing \( QR \)-factorization and solving the
-linear system as an equation would reduce this down to
-\( \mathcal{O}(n^2) \) operations.
-
-
-
-
-
-Before passing in the data to the function we append a column with ones to the training data.
-
-
-
-
-
-Next we fit a
@@ -3825,29 +3949,18 @@ Next we fit a
-Extracting the \( J \)-matrix from both our own method and the Scikit-learn model where we make sure to remove the intercept.
-
+When extracting the \( J \)-matrix we make sure to remove the intercept
-
-A way of looking at the coefficients in \( J \) is to plot the matrices as images.
-
+And then we plot the results
Having explored the ordinary least squares we move on to ridge
regression. In ridge regression we include a regularizer. This
involves a new cost function which leads to a new estimate for the
-weights \( \omega \). This results in a penalized regression problem. The
+weights \( \boldsymbol{\beta} \). This results in a penalized regression problem. The
cost function is given by
-where \( \omega_{\text{LS}} \) is the weights from ordinary least
-squares. The last assumption assumes that \( X \) is orthogonal, which it
-is not. We will therefore resort to solving the equation as it stands
-on the left hand side.
-
-
In the Least Absolute Shrinkage and Selection Operator (LASSO)-method we get a third cost function.
+
+Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-Learn.
@@ -3975,44 +4053,7 @@ constant as opposed to ridge and OLS. We get a sparse solution with
-In order to judge which model performs best at varying values of \( \lambda \) (for ridge and LASSO) we compute \( R^2 \) which is given by
-
-
-
-
-
-This is the same metric used by Scikit-learn for their regression models when scoring.
-
-
-
-
We see how the different models perform for a different set of values for \( \lambda \).
@@ -4023,17 +4064,13 @@ We see how the different models perform for a different set of values for \( \la
To determine which value of \( \lambda \) is best we plot the accuracy of
@@ -4110,8 +4123,6 @@ testing set that is close to the accuracy of the training set.
From the above figure we can see that LASSO with \( \lambda = 10^{-2} \)
-achieve a very good accuracy on the test set. This by far surpases the
+achieves a very good accuracy on the test set. This by far surpasses the
other models for all values of \( \lambda \).
+
+We will generate our own dataset for a function \( y(x) \) where \( x \in [0,1] \) and defined by random numbers computed with the uniform distribution. The function \( y \) is a quadratic polynomial in \( x \) with added stochastic noise according to the normal distribution \( \cal {N}(0,1) \).
+The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points).
+
+
+
+
+You can use the functionality included in scikit-learn. If you feel
+for it, you can use your own program and define functions which
+compute the above two functions. Discuss the meaning of these
+results. Try also to vary the coefficient in front of the added
+stochastic noise term and discuss the quality of the fits.
+
+
+Show that the variance of the parameters \( \beta \) in the linear regression method (chapter 3, equation (3.8) of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer) is given as
+
+
+This exercise is a continuation of exercise 1. We will
+use the same function to generate our data set, still staying with a
+simple function \( y(x) \) which we want to fit using linear regression,
+but now extending the analysis to include the Ridge and the Lasso
+regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods.
+
+
+We will thus again generate our own dataset for a function \( y(x) \) where
+\( x \in [0,1] \) and defined by random numbers computed with the uniform
+distribution. The function \( y \) is a quadratic polynomial in \( x \) with
+added stochastic noise according to the normal distribution \( \cal{N}(0,1) \).
+
+
+The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points).
+
+
+
+
+We will study how
+to fit polynomials to a specific two-dimensional function called
+Franke's
+function. This
+is a function which has been widely used when testing various interpolation and fitting
+algorithms. Furthermore, after having established the model and the
+method, we will employ resamling techniques such as the cross-validation and/or
+the bootstrap methods, in order to perform a proper assessment of our models.
+
+
+The Franke function, which is a weighted sum of four exponentials reads as follows
+
+The function will be defined for \( x,y\in [0,1] \). Our first step will
+be to perform an OLS regression analysis of this function, trying out
+a polynomial fit with an \( x \) and \( y \) dependence of the form \( [x, y,
+x^2, y^2, xy, \dots] \). We will also include cross-validation and
+bootstrap as resampling techniques. As in homeworks 1 and 2, we
+can use a uniform distribution to set up the arrays of values for \( x \)
+and \( y \), or as in the example below just a fix values for \( x \) and \( y \) with a given step size.
+In this case we will have two predictors and need to fit a
+function (for example a polynomial) of \( x \) and \( y \). Thereafter we will
+repeat much of the same procedure using the the Ridge and
+Lasso regression methods, introducing thus a dependence on the bias
+(penalty) \( \lambda \).
+
+
+The Python fucntion for the Franke function is included here (it performs also a three-dimensional plot of it)
+
+
+
+
+We will thus again generate our own dataset for a function \( \mathrm{FrankeFunction}(x,y) \) where
+\( x,y \in [0,1] \) could be defined by random numbers computed with the uniform
+distribution. The function \( f(x,y) \) is the Franke function. You should explore also the addition
+an added stochastic noise to this function using the normal distribution \( \cal{N}(0,1) \).
+
+
+Write your own code (using either a matrix inversion or a singular value decomposition from e.g., numpy ) or use your code from exercises 1 and 3
+and perform a standard least square regression analysis using polynomials in \( x \) and \( y \) up to fifth order. Find the confidence intervals of the parameters \( \beta \) by computing their variances, evaluate the Mean Squared error (MSE)
+
+Perform a resampling of the data where you split the data in training data and test data. Implement the \( k \)-fold cross-validation algorithm and/or the bootstrap algorithm
+and evaluate again the MSE and the \( R^2 \) functions resulting from the test data. Evaluate also the bias and variance of the final models.
+
+
+Write then your own code for the Ridge method, either using matrix
+inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the
+previous exercise (for the same polynomials and include resampling
+techniques) but now for different values of \( \lambda \). Compare and
+analyze your results with those obtained with standard OLS. Study the
+dependence on \( \lambda \) while also varying eventually the strength of
+the noise in your expression for \( \mathrm{FrankeFunction}(x,y) \).
+
+
+Then perform the same studies but now with Lasso regression. Use the functionalities of
+scikit-learn. Give a critical discussion of the three methods and a
+judgement of which model fits the data best.
+
-
+Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \).
+
+
+
-Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) varies as function of another variable or a set of such variables \( \hat{x} =[x_0, x_1,\dots, x_p]^T \).
-The first variable is called the dependent, the outcome or the response variable while the set of variables \( \hat{x} \) is called the independent variable, or the predictor variable or the explanatory variable.
+Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \).
+The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable.
-A regression model aims at finding a likelihood function \( p(y\vert \hat{x}) \), that is the conditional distribution for \( y \) with a given \( \hat{x} \). The estimation of \( p(y\vert \hat{x}) \) is made using a data set with
+A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with
Consider an experiment in which \( p \) characteristics of \( n \) samples are
-measured. The data from this experiment are denoted \( \mathbf{X} \), with
-\( \mathbf{X} \) as above. The matrix \( \mathbf{X} \) is called the design
+measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix
+\( \mathbf{X} \).
+
+
+The matrix \( \mathbf{X} \) is called the design
matrix. Additional information of the samples is available in the
-form of \( \mathbf{Y} \) (also as above). The variable \( \mathbf{Y} \) is
+form of \( \boldsymbol{y} \) (also as above). The variable \( \boldsymbol{y} \) is
generally referred to as the response variable. The aim of
-regression analysis is to explain \( \mathbf{Y} \) in terms of
-\( \mathbf{X} \) through a functional relationship like \( Y_i =
+regression analysis is to explain \( \boldsymbol{y} \) in terms of
+\( \boldsymbol{X} \) through a functional relationship like \( y_i =
f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of
\( f(\cdot) \) is available, it is common to assume a linear relationship
-between \( \mathbf{X} \) and \( \mathbf{Y} \). This assumption gives rise to
-the linear regression model where \( \beta = (\beta_1, \ldots,
-\beta_p)^{\top} \) is the regression parameter. The parameter
-\( \beta_j \), \( j=1, \ldots, p \), represents the effect size of covariate
-\( j \) on the response. That is, for each unit change in covariate \( j \)
-(while keeping the other covariates fixed) the observed change in the
-response is equal to \( \beta_j \).
+between \( \boldsymbol{X} \) and \( \boldsymbol{y} \). This assumption gives rise to
+the linear regression model where \( \boldsymbol{\beta} = [\beta_0, \ldots,
+\beta_{p-1}]^{T} \) are the regression parameters.
+
+
+Linear regression gives us a set of analytical equations for the parameters \( \beta_j \).
-Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \hat{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \hat{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function.
+In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \),
+consider the model we discussed for describing nuclear binding energies.
+
+
+There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model.
+Assuming
+$$
+BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1},
+$$
+
+we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms.
+This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a
+\( p\times n \) matrix \( \boldsymbol{X} \).
+
+
+Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the
+so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \)
+
+
+
+
+Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function.
Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is
$$
-y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_i x_i^j+\epsilon_i,
+y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i,
$$
where \( \epsilon_i \) is the error in our approximation.
@@ -392,7 +423,7 @@ where \( \epsilon_i \) is the error in our approximation.
@@ -403,7 +434,7 @@ y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\
y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\
y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\
\dots & \dots \\
-y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_1x_{n-1}^{n-1}+\epsilon_{n-1}.\\
+y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\
\end{align*}
$$
Defining the vectors
$$
-\hat{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T,
+\boldsymbol{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T,
$$
and
$$
-\hat{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T,
+\boldsymbol{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T,
$$
and
$$
-\hat{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T,
+\boldsymbol{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T,
$$
-and the matrix
+and the design matrix
$$
-\hat{X}=
+\boldsymbol{X}=
\begin{bmatrix}
1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\
1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\
@@ -445,20 +476,28 @@ $$
we can rewrite our equations as
$$
-\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}.
+\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}.
$$
+
+The above design matrix is called a Vandermonde matrix.
-We are obviously not limited to the above polynomial. We could replace the various powers of \( x \) with elements of Fourier series, that is, instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j x_i)} \), or time series or other orthogonal functions.
-For every set of values \( y_i,x_i \) we can then generalize the equations to
+
+
+We are obviously not limited to the above polynomial expansions. We
+could replace the various powers of \( x \) with elements of Fourier
+series or instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j
+x_i)} \), or time series or other orthogonal functions. For every set
+of values \( y_i,x_i \) we can then generalize the equations to
+
$$
\begin{align*}
y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\
@@ -467,22 +506,25 @@ y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilo
\dots & \dots \\
y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\
\dots & \dots \\
-y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\
+y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\
\end{align*}
$$
+
+
+Note that we have \( p=n \) here. The matrix is symmetric. This is generally not the case!
-We redefine in turn the matrix \( \hat{X} \) as
+We redefine in turn the matrix \( \boldsymbol{X} \) as
$$
-\hat{X}=
+\boldsymbol{X}=
\begin{bmatrix}
x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\
x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\
@@ -494,21 +536,21 @@ $$
and without loss of generality we rewrite again our equations as
$$
-\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}.
+\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}.
$$
-The left-hand side of this equation forms know. Our error vector \( \hat{\epsilon} \) and the parameter vector \( \hat{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values?
+The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values?
-We have defined the matrix \( \hat{X} \)
+We have defined the matrix \( \boldsymbol{X} \) via the equations
$$
\begin{align*}
y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\
@@ -517,69 +559,196 @@ y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilo
\dots & \dots \\
y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\
\dots & \dots \\
-y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\
+y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\
\end{align*}
$$
+
+
+As we noted above, we stayed with a system with the design matrix
+ \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \), that is we have \( p=n \). For reasons to come later (algorithmic arguments) we will hereafter define
+our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors refering to the column numbers and the entries \( n \) being the row elements.
+
+
+In our introductory notes we looked at the so-called liguid drop model. Let us remind ourselves about what we did by looking at the code.
+
+
+We restate the parts of the code we are most interested in.
+
+
+
+
+With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as
+$$
+\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta},
+$$
+
+throughout these lectures.
+
+
+
-We well use this matrix to define the approximation \( \hat{\tilde{y}} \) via the unknown quantity \( \hat{\beta} \) as
+With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as
$$
-\hat{\tilde{y}}= \hat{X}\hat{\beta},
+\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta},
$$
-and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parametrized values \( \tilde{y}_i \), namely
+and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely
$$
-Q(\hat{\beta})=\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\left(\hat{y}-\hat{\tilde{y}}\right)^T\left(\hat{y}-\hat{\tilde{y}}\right),
+C(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\},
$$
-or using the matrix \( \hat{X} \) as
+or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as
$$
-Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right).
+C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)\right\}.
$$
+
+This function is one possible way to define the so-called cost function.
+
+
+It is also common to define
+the function \( Q \) as
+
+$$
+C(\boldsymbol{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2,
+$$
+
+since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out.
+
The function
$$
-Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right),
+C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\},
$$
-can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value of for example a numerical experiment. When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value
+can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value.
+When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value (see exercises)
$$
y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i,
$$
-where \( \langle y_i \rangle \) is the mean value. Keep in mind also that till now we have treated \( y_i \) as the exact value. Normally, the response (dependent or outcome) variable \( y_i \) 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.
+
+where \( \langle y_i \rangle \) is the mean value. Keep in mind also that
+till now we have treated \( y_i \) as the exact value. Normally, the
+response (dependent or outcome) variable \( y_i \) 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.
-In order to find the parameters \( \beta_i \) we will then minimize the spread of \( Q(\hat{\beta}) \) by requiring
+In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem
$$
-\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0,
+{\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\}.
+$$
+
+In practical terms it means we will require
+$$
+\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0,
$$
which results in
$$
-\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0,
+\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0,
$$
or in a matrix-vector form as
$$
-\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right).
+\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right).
$$
@@ -589,25 +758,37 @@ $$
We can rewrite
$$
-\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right),
+\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right),
$$
as
$$
-\hat{X}^T\hat{y} = \hat{X}^T\hat{X}\hat{\beta},
+\boldsymbol{X}^T\boldsymbol{y} = \boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta},
$$
-and if the matrix \( \hat{X}^T\hat{X} \) is invertible we have the solution
+and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution
$$
-\hat{\beta} =\left(\hat{X}^T\hat{X}\right)^{-1}\hat{X}^T\hat{y}.
+\boldsymbol{\beta} =\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
$$
+
+We note also that since our design matrix is defined as \( \boldsymbol{X}\in
+{\mathbb{R}}^{n\times p} \), the product \( \boldsymbol{X}^T\boldsymbol{X} \in
+{\mathbb{R}}^{p\times p} \). In the above case we have that \( p \ll n \),
+in our case \( p=5 \) meaning that we end up with inverting a small
+\( 5\times 5 \) matrix. This is a rather common situation, in many cases we end up with low-dimensional
+matrices to invert. The methods discussed here and for many other
+supervised learning algorithms like classification with logistic
+regression or support vector machines, exhibit dimensionalities which
+allow for the usage of direct linear algebra methods such as LU decomposition or Singular Value Decomposition (SVD) for finding the inverse of the matrix
+\( \boldsymbol{X}^T\boldsymbol{X} \).
+
-The residuals \( \hat{\epsilon} \) are in turn given by
+The residuals \( \boldsymbol{\epsilon} \) are in turn given by
$$
-\hat{\epsilon} = \hat{y}-\hat{\tilde{y}} = \hat{y}-\hat{X}\hat{\beta},
+\boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta},
$$
and with
$$
-\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0,
+\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0,
$$
we have
$$
-\hat{X}^T\hat{\epsilon}=\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0,
+\boldsymbol{X}^T\boldsymbol{\epsilon}=\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0,
$$
-meaning that the solution for \( \hat{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.
+meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.
+
+
+
+Let us now return to our nuclear binding energies and simply code the above equations.
+
+
+
+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
+write
+
+
+
+
+Alternatively, you can use the least squares functionality in Numpy as
+
+
+
+
+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.
+Since we are not using _Scikit-Learn here we can define our own \( R2 \) function as
+
+
+
+
+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.
-Normally, the response (dependent or outcome) variable \( y_i \) 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 as
+In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring
$$
-\chi^2(\hat{\beta})=\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\left(\hat{y}-\hat{\tilde{y}}\right)^T\frac{1}{\hat{\Sigma^2}}\left(\hat{y}-\hat{\tilde{y}}\right),
-$$
-
-where the matrix \( \hat{\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(\hat{\beta}) \) by requiring
-$$
-\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \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,
+\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(\hat{\beta})}{\partial \beta_j} = -2\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,
+\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(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right).
+\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 \( \hat{A} =\hat{X}/\hat{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \hat{b} \) with elements \( b_i = y_i/\sigma_i \).
+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 \).
@@ -702,17 +978,17 @@ where we have defined the matrix \( \hat{A} =\hat{X}/\hat{\Sigma} \) with matrix
We can rewrite
$$
-\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right),
+\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right),
$$
as
$$
-\hat{A}^T\hat{b} = \hat{A}^T\hat{A}\hat{\beta},
+\boldsymbol{A}^T\boldsymbol{b} = \boldsymbol{A}^T\boldsymbol{A}\boldsymbol{\beta},
$$
-and if the matrix \( \hat{A}^T\hat{A} \) is invertible we have the solution
+and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution
$$
-\hat{\beta} =\left(\hat{A}^T\hat{A}\right)^{-1}\hat{A}^T\hat{b}.
+\boldsymbol{\beta} =\left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}\boldsymbol{A}^T\boldsymbol{b}.
$$
@@ -728,10 +1004,10 @@ $$
If we then introduce the matrix
$$
-\hat{H} = \left(\hat{A}^T\hat{A}\right)^{-1},
+\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 \( \hat{H} \) are \( h_{ij} \))
+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}
$$
@@ -751,7 +1027,7 @@ $$
@@ -762,12 +1038,12 @@ $$
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(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0,
+\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(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0.
+\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 we don't need to invert a matrix!!
+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},
@@ -792,570 +1068,539 @@ $$
\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.
+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
+nuclear equation of state using results from many-body calculations.
+The equation of state we have made available here, as function of
+density, has been derived using modern nucleon-nucleon potentials with
+the addition of three-body
+forces. This
+time the file is presented as a standard csv file.
+
+
+The beginning of the Python code here is similar to what you have seen before,
+with the same initializations and declarations. We use also pandas
+again, rather extensively in order to organize our data.
+
+
+The difference now is that we use Scikit-Learn's regression tools
+instead of our own matrix inversion implementation. Furthermore, we
+sneak in Ridge regression (to be discussed below) which includes a
+hyperparameter \( \lambda \), also to be explained below.
+
+
+
-
-
-
-
-We see that, as expected, a linear fit gives a seemingly (from the graph) good representation of the data.
-
-
-
-We can repeat the above algorithm using scikit-learn as follows
-
-
-
-
-
-We start with perhaps our simplest possible example, using scikit-learn to perform linear regression analysis on a data set produced by us.
-What follows is a simple Python code where we have defined function \( y \) in terms of the variable \( x \). Both are defined as vectors of dimension \( 1\times 100 \). The entries to the vector \( \hat{x} \) are given by random numbers generated with a uniform distribution with entries \( x_i \in [0,1] \) (more about probability distribution functions later). These values are then used to define a function \( y(x) \) (tabulated again as a vector) with a linear dependence on \( x \) plus a random noise added via the normal distribution.
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
-
-The Numpy functions are imported used the import numpy as np
-statement and the random number generator for the uniform distribution
-is called using the function np.random.rand(), where we specificy
-that we want \( 100 \) random variables. Using Numpy we define
-automatically an array with the specified number of elements, \( 100 \) in
-our case. With the Numpy function randn() we can compute random
-numbers with the normal distribution (mean value \( \mu \) equal to zero and
-variance \( \sigma^2 \) set to one) and produce the values of \( y \) assuming a linear
-dependence as function of \( x \)
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
-$$
-y = 2x+N(0,1),
-$$
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
-
-where \( N(0,1) \) represents random numbers generated by the normal
-distribution. From scikit-learn we import then the
-LinearRegression functionality and make a prediction \( \tilde{y} =
-\alpha + \beta x \) using the function fit(x,y). We call the set of
-data \( (\hat{x},\hat{y}) \) for our training data. The Python package
-scikit-learn has also a functionality which extracts the above
-fitting parameters \( \alpha \) and \( \beta \) (see below). Later we will
-distinguish between training data and test data.
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
-
-For plotting we use the Python package
-matplotlib which produces publication
-quality figures. Feel free to explore the extensive
-gallery of examples. In
-this example we plot our original values of \( x \) and \( y \) as well as the
-prediction ypredict (\( \tilde{y} \)), which attempts at fitting our
-data with a straight line.
+infile = open(data_path("EoS.csv"),'r')
-
-The Python code follows here.
-
+# Read the EoS data as csv file and organize the data into two arrays with density and energies
+EoS = pd.read_csv(infile, names=('Density', 'Energy'))
+EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
+EoS = EoS.dropna()
+Energies = EoS['Energy']
+Density = EoS['Density']
+# The design matrix now as function of various polytrops
+X = np.zeros((len(Density),4))
+X[:,3] = Density**(4.0/3.0)
+X[:,2] = Density
+X[:,1] = Density**(2.0/3.0)
+X[:,0] = 1
-
-
-
-This example serves several aims. It allows us to demonstrate several
-aspects of data analysis and later machine learning algorithms. The
-immediate visualization shows that our linear fit is not
-impressive. It goes through the data points, but there are many
-outliers which are not reproduced by our linear regression. We could
-now play around with this small program and change for example the
-factor in front of \( x \) and the normal distribution. Try to change the
-function \( y \) to
-
-$$
-y = 10x+0.01 \times N(0,1),
-$$
-
-
-where \( x \) is defined as before.
-
-
-
-Does the fit look better? Indeed, by
-reducing the role of the normal distribution we see immediately that
-our linear prediction seemingly reproduces better the training
-set. However, this testing 'by the eye' is obviouly not satisfactory in the
-long run. Here we have only defined the training data and our model, and
-have not discussed a more rigorous approach to the cost function.
-
-
-
-We need more rigorous criteria in defining whether we have succeeded or
-not in modeling our training data. You will be surprised to see that
-many scientists seldomly venture beyond this 'by the eye' approach. A
-standard approach for the cost function is the so-called \( \chi^2 \)
-function
-
-$$ \chi^2 = \frac{1}{n}
-\sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2},
-$$
-
-
-where \( \sigma_i^2 \) is the variance (to be defined later) of the entry
-\( y_i \). We may not know the explicit value of \( \sigma_i^2 \), it serves
-however the aim of scaling the equations and make the cost function
-dimensionless.
-
-
-
-Minimizing the cost function is a central aspect of
-our discussions to come. Finding its minima as function of the model
-parameters (\( \alpha \) and \( \beta \) in our case) will be a recurring
-theme in these series of lectures. Essentially all machine learning
-algorithms we will discuss center around the minimization of the
-chosen cost function. This depends in turn on our specific
-model for describing the data, a typical situation in supervised
-learning. Automatizing the search for the minima of the cost function is a
-central ingredient in all algorithms. Typical methods which are
-employed are various variants of gradient methods. These will be
-discussed in more detail later. Again, you'll be surprised to hear that
-many practitioners minimize the above function ''by the eye', popularly dubbed as
-'chi by the eye'. That is, change a parameter and see (visually and numerically) that
-the \( \chi^2 \) function becomes smaller.
-
-
-
-There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define
-the relative error as
-
-$$
-\epsilon_{\mathrm{relative}}= \frac{\vert \hat{y} -\hat{\tilde{y}}\vert}{\vert \hat{y}\vert}.
-$$
-
-We can modify easily the above Python code and plot the relative error instead
-
-
-
-
-Depending on the parameter in front of the normal distribution, we may
-have a small or larger relative error. Try to play around with
-different training data sets and study (graphically) the value of the
-relative error.
-
-
-
-As mentioned above, scikit-learn has an impressive functionality.
-We can for example extract the values of \( \alpha \) and \( \beta \) and
-their error estimates, or the variance and standard deviation and many
-other properties from the statistical data analysis.
-
-
-Here we show an
-example of the functionality of scikit-learn.
-
-
-
-
-
-The function coef gives us the parameter \( \beta \) of our fit while intercept yields
-\( \alpha \). Depending on the constant in front of the normal distribution, we get values near or far from \( alpha =2 \) and \( \beta =5 \). Try to play around with different parameters in front of the normal distribution. The function meansquarederror gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as
-$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
-\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
-$$
-
-
-The smaller the value, the better the fit. Ideally we would like to
-have an MSE equal zero. The attentive reader has probably recognized
-this function as being similar to the \( \chi^2 \) function defined above.
+We note also that there is a small deviation between the
+standard OLS and the Ridge regression at higher densities. We discuss this in more detail
+below.
-The r2score function computes \( R^2 \), the coefficient of
-determination. It provides a measure of how well future samples are
-likely to be predicted by the model. Best possible score is 1.0 and it
-can be negative (because the model can be arbitrarily worse). A
-constant model that always predicts the expected value of \( \hat{y} \),
-disregarding the input features, would get a \( R^2 \) score of \( 0.0 \).
-
-
-If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as
-$$
-R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
-$$
-
-where we have defined the mean value of \( \hat{y} \) as
-$$
-\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
-$$
-
-
-
-Another quantity will meet again in our discussions of regression analysis is
- mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the \( l1 \)-norm loss. In our discussion above we presented the relative error.
-The MAE is defined as follows
-$$
-\text{MAE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1} \left| y_i - \tilde{y}_i \right|.
-$$
-
-Finally we present the
-squared logarithmic (quadratic) error
-$$
-\text{MSLE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n - 1} (\log_e (1 + y_i) - \log_e (1 + \tilde{y}_i) )^2,
-$$
-
-
-where \( \log_e (x) \) stands for the natural logarithm of \( x \). This error
-estimate is best to use when targets having exponential growth, such
-as population counts, average sales of a commodity over a span of
-years etc.
-
-
-
-We will discuss in more
-detail these and other functions in the various lectures. We conclude this part with another example. Instead of
-a linear \( x \)-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn.
-Add description of the various python commands.
+It is normal in essentially all Machine Learning studies to split the
+data in a training set and a test set (sometimes also an additional
+validation set). Scikit-Learn has an own function for this. There
+is no explicit recipe for how much data should be included as training
+data and say test data. An accepted rule of thumb is to use
+approximately \( 2/3 \) to \( 4/5 \) of the data as training data. We will
+postpone a discussion of this splitting to the end of these notes and
+our discussion of the so-called bias-variance tradeoff. Here we
+limit ourselves to repeat the above equation of state fitting example
+but now splitting the data into a training set and a test set.
-
-Using R, we can perform similar studies.
-
-
-
-
-
-
-
-
-
-Before we proceed, and to link with our discussions of Bayesian statistics to come, it is useful the derive the standard regression analysis equations using a statistical interpretation. This allows us also to derive quantities like the variance and other expectation values in a rather straightforward way.
-
-
-It is assumed that \( \varepsilon_i
-\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are
-independent, i.e.:
-$$
-\begin{align*}
-\mbox{Cov}(\varepsilon_{i_1},
-\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if}
-& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right.
-\end{align*}
-$$
-
-The randomness of \( \varepsilon_i \) implies that
-\( \mathbf{Y}_i \) is also a random variable. In particular,
-\( \mathbf{Y}_i \) is normally distributed, because \( \varepsilon_i \sim
-\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \beta \) is a
-non-random scalar. To specify the parameters of the distribution of
-\( \mathbf{Y}_i \) we need to calculate its first two moments.
-
-Its expectation equals:
-$$
-\begin{align*}
-\mathbb{E}(Y_i) & =
-\mathbb{E}(\mathbf{X}_{i, \ast} \, \beta) + \mathbb{E}(\varepsilon_i)
-\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta,
-\end{align*}
-$$
-
-while
-its variance is
-$$
-\begin{align*} \mbox{Var}(Y_i) & = \mathbb{E} \{ [Y_i
-- \mathbb{E}(Y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( Y_i^2 ) -
-[\mathbb{E}(Y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \,
-\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \beta)^2 \\ &
-= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 \varepsilon_i
-\mathbf{X}_{i, \ast} \, \beta + \varepsilon_i^2 ] - ( \mathbf{X}_{i,
-\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2
-\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \beta +
-\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \beta)^2
-\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \,
-\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2.
-\end{align*}
-$$
-
-Hence, \( Y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \beta, \sigma^2) \).
-
-
-
-A general
-\( m\times n \) matrix \( \hat{A} \) can be written in terms of a diagonal
-matrix \( \hat{D} \) of dimensionality \( n\times n \) and two orthognal
-matrices \( \hat{U} \) and \( \hat{V} \), where the first has dimensionality
-\( m \times m \) and the last dimensionality \( n\times n \).
-We have then
-$$
-\hat{A} = \hat{U}\hat{D}\hat{V}^T
-$$
+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. This may
+however not the be case in general and a standard matrix inversion
+algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit
+the coupling constant of the widely used Ising model.
+There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach.
+
+
+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.
+
+
+The one-dimensional Ising model with nearest neighbor interaction, no
+external field and a constant coupling constant \( J \) is given by
+
+$$
+\begin{align}
+ H = -J \sum_{k}^L s_k s_{k + 1},
+\label{_auto1}
+\end{align}
+$$
+
+
+where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins
+in the system is determined by \( L \). For the one-dimensional system
+there is no phase transition.
+
+
+We will look at a system of \( L = 40 \) spins with a coupling constant of
+\( J = 1 \). To get enough training data we will generate 10000 states
+with their respective energies.
+
+
+
+
+
+Here we use ordinary least squares
+regression to predict the energy for the nearest neighbor
+one-dimensional Ising model on a ring, i.e., the endpoints wrap
+around. We will use linear regression to fit a value for
+the coupling constant to achieve this.
+
+
+
+A more general form for the one-dimensional Ising model is
+
+$$
+\begin{align}
+ H = - \sum_j^L \sum_k^L s_j s_k J_{jk}.
+\label{_auto2}
+\end{align}
+$$
+
+
+Here we allow for interactions beyond the nearest neighbors and a state dependent
+coupling constant. This latter expression can be formulated as
+a matrix-product
+$$
+\begin{align}
+ \boldsymbol{H} = \boldsymbol{X} J,
+\label{_auto3}
+\end{align}
+$$
+
+
+where \( X_{jk} = s_j s_k \) and \( J \) is a matrix which consists of the
+elements \( -J_{jk} \). This form of writing the energy fits perfectly
+with the form utilized in linear regression, that is
+
+$$
+\begin{align}
+ \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon},
+\label{_auto4}
+\end{align}
+$$
+
+
+We split the data in training and test data as discussed in the previous example
+
+
+
+
+
+
+In the ordinary least squares method we choose the cost function
+
+$$
+\begin{align}
+ C(\boldsymbol{X}, \boldsymbol{\beta})= \frac{1}{n}\left\{(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})\right\}.
+\label{_auto5}
+\end{align}
+$$
+
+
+We then find the extremal point of \( C \) by taking the derivative with respect to \( \boldsymbol{\beta} \) as discussed above.
+This yields the expression for \( \boldsymbol{\beta} \) to be
+
+$$
+ \boldsymbol{\beta} = \frac{\boldsymbol{X}^T \boldsymbol{y}}{\boldsymbol{X}^T \boldsymbol{X}},
+$$
+
+
+which immediately imposes some requirements on \( \boldsymbol{X} \) as there must exist
+an inverse of \( \boldsymbol{X}^T \boldsymbol{X} \). If the expression we are modeling contains an
+intercept, i.e., a constant term, we must make sure that the
+first column of \( \boldsymbol{X} \) consists of \( 1 \). We do this here
+
+
+
+
+
+
+
+
+
+Doing the inversion directly turns out to be a bad idea since the matrix
+\( \boldsymbol{X}^T\boldsymbol{X} \) is singular. An alternative approach is to use the singular
+value decomposition. Using the definition of the Moore-Penrose
+pseudoinverse we can write the equation for \( \boldsymbol{\beta} \) as
+
+$$
+ \boldsymbol{\beta} = \boldsymbol{X}^{+}\boldsymbol{y},
+$$
+
+
+where the pseudoinverse of \( \boldsymbol{X} \) is given by
+
+$$
+ \boldsymbol{X}^{+} = \frac{\boldsymbol{X}^T}{\boldsymbol{X}^T\boldsymbol{X}}.
+$$
+
+
+Using singular value decomposition we can decompose the matrix \( \boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma} \boldsymbol{V}^T \),
+where \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal(unitary) matrices and \( \boldsymbol{\Sigma} \) contains the singular values (more details below).
+where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for
+\( \omega \) to
+$$
+\begin{align}
+ \boldsymbol{\beta} = \boldsymbol{V}\boldsymbol{\Sigma}^{+} \boldsymbol{U}^T \boldsymbol{y}.
+\label{_auto6}
+\end{align}
+$$
+
+
+Note that solving this equation by actually doing the pseudoinverse
+(which is what we will do) is not a good idea as this operation scales
+as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a
+general matrix. Instead, doing \( QR \)-factorization and solving the
+linear system as an equation would reduce this down to
+\( \mathcal{O}(n^2) \) operations.
+
+
+
+
+
+
+
+
+When extracting the \( J \)-matrix we need to make sure that we remove the intercept, as is done here
+
+
+
+
+
+A way of looking at the coefficients in \( J \) is to plot the matrices as images.
+
+
+
+
+
+It is interesting to note that OLS
+considers both \( J_{j, j + 1} = -0.5 \) and \( J_{j, j - 1} = -0.5 \) as
+valid matrix elements for \( J \).
+In our discussion below on hyperparameters and Ridge and Lasso regression we will see that
+this problem can be removed, partly and only with Lasso regression.
+
+
+In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD?
+
+
+
One of the typical problems we encounter with linear regression, in particular
-when the matrix \( \hat{X} \) (our so-called design matrix) is high-dimensional,
-are problems with near singular or singular matrices. The column vectors of \( \hat{X} \)
+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
@@ -1375,7 +1620,7 @@ $$
$$
-The columns of \( \hat{X} \) are linearly dependent. We se this easily since the
+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
@@ -1383,10 +1628,10 @@ 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 \( \hat{X}^T\hat{x} \) (the matrix we needto 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
+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*}
-\hat{X} & = \left[
+\boldsymbol{X} & = \left[
\begin{array}{rr}
1 & -1
\\
@@ -1395,425 +1640,421 @@ $$
\end{align*}
$$
-We see easily that \( \mbox{det}(\hat{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 \( \hat{X} \) has at least an eigenvalue which is zero.
+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 \( \hat{X} \) which enters the linear regression problem
+If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem
$$
\begin{align}
-\hat{\beta} & = (\hat{X}^{T} \hat{X})^{-1} \hat{X}^{T} \hat{y},
-\label{_auto1}
+\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y},
+\label{_auto7}
\end{align}
$$
has linearly dependent column vectors, we will not be able to compute the inverse
-of \( \hat{X}^T\hat{X} \) and we cannot find the parameters (estimators) \( \beta_i \).
-The estimators are only well-defined if \( (\hat{X}^{T}\hat{X})^{-1} \) exits.
-This is more likely to happen when the matrix \( \hat{X} \) is high-dimensional. In this case it is likely to encounter a situation where
+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.
-The ad hoc approach which was introduced in the 70s was simply to add a diagonal component to the matrix to invert, that is we change
+A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change
$$
-\hat{X}^{T} \hat{X} \rightarrow \hat{X}^{T} \hat{X}+\lambda \hat{I},
+\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I},
$$
-where \( \hat{I} \) is the identity matrix.
+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.
-We start by considering the case
-\( f(x)=2x \).
+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} \).
-Then the data is clearly generated by a model that is contained within
-all three model classes we are using to make predictions (linear
-models, third order polynomials, and tenth order polynomials).
+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.
-Run the code for the following cases:
+
+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 \( n\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!
+
+
+
+Consider the following matrix which can be SVD decomposed as
+
+$$
+\boldsymbol{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T.
+$$
+
+
+This is a \( 3\times 2 \) matrix which is decomposed in terms of a
+\( 3\times 3 \) matrix \( \boldsymbol{U} \), and a \( 2\times 2 \) matrix \( \boldsymbol{V} \). It is easy to see
+that \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal (how?).
+
+
+And the SVD
+decomposition (singular values) gives eigenvalues
+\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=2 \), 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\lg 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.
+
+
+
+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.
+
+
+
+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
+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.
+
+
+
+Before we proceed, we need to rethink what we have been doing. In our
+eager to fit the data, we have omitted several important elements in
+our regression analysis. In what follows we will
-Thus far, we have considered the case where the data is generated using a model contained in the model class. Now consider \( f(x)=2x-10x^5+15x^{10} \) . Notice that the for linear and third-order polynomial the true model \( f(x) \) is not contained in model class.
-
-
-
-
-
-
-
-
-
-
-
-
-
-In Ridge regression and the subsequent discussion of its properties
-the bias or penalty parameter is considered known or `given'. In
-practice, it is unknown and the user needs to make an informed
-decision on its value. How do we do that? Much of the same considerations apply to the Lasso method.
-
-
-
-
-
-
-
-
-
-
-
@@ -1833,9 +2074,11 @@ once using the original training sample.
+
Resampling approaches can be computationally expensive, because they
involve fitting the same statistical method multiple times using
@@ -1852,21 +2095,23 @@ of flexibility. The process of evaluating a model’s performance is
known as model assessment, whereas the process of selecting the proper
level of flexibility for a model is known as model selection. The
bootstrap is widely used.
+
+
@@ -1927,7 +2172,7 @@ selection of a large set of these numbers reproduces this PDF.
@@ -1950,7 +2195,7 @@ $$
@@ -1968,14 +2213,14 @@ $$
\begin{align}
\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle =
\int\! (x-\langle x\rangle)^2 p(x)\,dx
-\label{_auto2}\\
+\label{_auto8}\\
& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} +
\langle x\rangle^2\right)p(x)\,dx
-\label{_auto3}\\
+\label{_auto9}\\
& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2
-\label{_auto4}\\
+\label{_auto10}\\
& = \langle x^2\rangle - \langle x\rangle^2
-\label{_auto5}
+\label{_auto11}
\end{align}
$$
@@ -1988,7 +2233,7 @@ qualitatively as the spread of \( p \) around its mean.
@@ -2019,7 +2264,7 @@ $$
@@ -2032,17 +2277,17 @@ the expectation value. Consider the stochastic variables \( X_i \) and
$$
\begin{align}
\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle
-\label{_auto6}\\
+\label{_auto12}\\
&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle
-\label{_auto7}\\
+\label{_auto13}\\
&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle +
\langle \langle x_i\rangle\langle x_j\rangle\rangle
-\label{_auto8}\\
+\label{_auto14}\\
&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle +
\langle x_i\rangle\langle x_j\rangle
-\label{_auto9}\\
+\label{_auto15}\\
&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle
-\label{_auto10}
+\label{_auto16}
\end{align}
$$
@@ -2077,7 +2322,7 @@ $$
@@ -2109,7 +2354,7 @@ value of a set of measurements.
@@ -2137,7 +2382,7 @@ interested in finding the few lowest moments, like the mean
-
@@ -2163,7 +2408,7 @@ $$
@@ -2184,7 +2429,7 @@ and covariance \( \mathrm{cov}(X,Y) \).
@@ -2216,7 +2461,7 @@ true PDFs behind, which we usually do not have.
@@ -2238,7 +2483,7 @@ means.
@@ -2259,7 +2504,7 @@ And in particular we are interested in its variance \( \mathrm{var}(\overline X_
@@ -2284,7 +2529,7 @@ $$
@@ -2313,7 +2558,7 @@ estimate of the PDF of each of the \( X_i \), estimating all properties of
@@ -2340,7 +2585,7 @@ $$
@@ -2379,7 +2624,7 @@ measurements in the sample.
@@ -2414,7 +2659,7 @@ cannot overlook the always present correlations.
@@ -2443,7 +2688,7 @@ measurements. For uncorrelated measurements this second term is zero.
@@ -2465,7 +2710,7 @@ have to be stored throughout the experiment.
@@ -2498,7 +2743,7 @@ starting always at \( 1 \) for \( d=0 \).
@@ -2531,7 +2776,7 @@ $$
@@ -2554,42 +2799,187 @@ measurements is very large.
-
-A popular strategy is to choose a penalty parameter that yields a good
-but parsimonious model. Information criteria measure the balance
-between model fit and model complexity. One possibility is Aikaike's
-information criterion (AIC).
-The AIC measures model fit by the log-likelihood
-and model complexity is measured by the number of parameters used by
-the model. The number of model parameters in regular regression simply
-corresponds to the number of covariates in the model. Or, by the
-degrees of freedom consumed by the model, which is equivalent to the
-trace of the hat matrix. For ridge regression it thus seems natural to
-define model complexity analogously by the trace of the ridge hat
-matrix. This yields the AIC for the linear regression model with ridge
-estimates:
+Finally, we are going to discuss several statistical properties which can be obtained in terms of analytical expressions.
+The
+advantage of doing linear regression is that we actually end up with
+analytical expressions for several statistical quantities.
+Standard least squares and Ridge regression allow us to
+derive quantities like the variance and other expectation values in a
+rather straightforward way.
+
+It is assumed that \( \varepsilon_i
+\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are
+independent, i.e.:
$$
-\begin{align*}
-\mbox{AIC}(\lambda) & = 2 \, p - 2 \log(\hat{L})
-\\
-& = 2 \, \mbox{tr} [\mathbf{H}(\lambda)] - 2 \log\{L[\hat{\beta}(\lambda), \hat{\sigma}^2(\lambda)]\}
-\\
-& = 2 \, \sum_{j=1}^p \frac{d_{jj}^2}{d_{jj}^2 + \lambda}
-+ 2 n \, \log[\sqrt{2 \, \pi} \, \hat{\sigma}(\lambda)] + \frac{1}{\hat{\sigma}^2(\lambda)} \sum_{i=1}^n [y_i - \mathbf{X}_{i, \ast} \, \hat{\beta}(\lambda)]^2.
+\begin{align*}
+\mbox{Cov}(\varepsilon_{i_1},
+\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if}
+& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right.
+\end{align*}
+$$
+
+The randomness of \( \varepsilon_i \) implies that
+\( \mathbf{y}_i \) is also a random variable. In particular,
+\( \mathbf{y}_i \) is normally distributed, because \( \varepsilon_i \sim
+\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \boldsymbol{\beta} \) is a
+non-random scalar. To specify the parameters of the distribution of
+\( \mathbf{y}_i \) we need to calculate its first two moments.
+
+
+Recall that \( \boldsymbol{X} \) is a matrix of dimensionality \( n\times p \). The
+notation above \( \mathbf{X}_{i,\ast} \) means that we are looking at the
+row number \( i \) and perform a sum over all values \( p \).
+
+
+
+The assumption we have made here can be summarized as (and this is going to useful when we discuss the bias-variance trade off)
+that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \)
+which describes our data
+$$
+\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon}
+$$
+
+
+We approximate this function with our model from the solution of the linear regression equations, that is our
+function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we want to minimize \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), our MSE, with
+$$
+\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}.
+$$
+
+
+
+We can calculate the expectation value of \( \boldsymbol{y} \) for a given element \( i \)
+$$
+\begin{align*}
+\mathbb{E}(y_i) & =
+\mathbb{E}(\mathbf{X}_{i, \ast} \, \boldsymbol{\beta}) + \mathbb{E}(\varepsilon_i)
+\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta,
+\end{align*}
+$$
+
+while
+its variance is
+$$
+\begin{align*} \mbox{Var}(y_i) & = \mathbb{E} \{ [y_i
+- \mathbb{E}(y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( y_i^2 ) -
+[\mathbb{E}(y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \,
+\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 \\ &
+= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 \varepsilon_i
+\mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + \varepsilon_i^2 ] - ( \mathbf{X}_{i,
+\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2
+\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \boldsymbol{\beta} +
+\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2
+\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \,
+\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2.
\end{align*}
$$
-The value of \( \lambda \) which minimizes \( \mbox{AIC}(\lambda) \) corresponds to the `optimal' balance of model complexity and overfitting.
+Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with
+mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \) (not be confused with the singular values of the SVD).
+
+
+
+With the OLS expressions for the parameters \( \boldsymbol{\beta} \) we can evaluate the expectation value
+$$
+\mathbb{E}(\boldsymbol{\beta}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}.
+$$
+
+This means that the estimator of the regression parameters is unbiased.
+
+
+We can also calculate the variance
+
+
+The variance of \( \boldsymbol{\beta} \) is
+$$
+\begin{eqnarray*}
+\mbox{Var}(\boldsymbol{\beta}) & = & \mathbb{E} \{ [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})] [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})]^{T} \}
+\\
+& = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}]^{T} \}
+\\
+% & = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}]^{T} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+% \\
+% & = & \mathbb{E} \{ (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} \, \mathbf{Y}^{T} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+% \\
+& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \mathbb{E} \{ \mathbf{Y} \, \mathbf{Y}^{T} \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+\\
+& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+% \\
+% & = & (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1}
+% \\
+% & & + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \boldsymbol{\beta} \boldsymbol{\beta}^T
+\\
+& = & \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1},
+\end{eqnarray*}
+$$
+
+
+where we have used that \( \mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) =
+\mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} +
+\sigma^2 \, \mathbf{I}_{nn} \). From \( \mbox{Var}(\boldsymbol{\beta}) = \sigma^2
+\, (\mathbf{X}^{T} \mathbf{X})^{-1} \), one obtains an estimate of the
+variance of the estimate of the \( j \)-th regression coefficient:
+\( \hat{\sigma}^2 (\hat{\beta}_j ) = \hat{\sigma}^2 \sqrt{
+[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} } \). This may be used to
+construct a confidence interval for the estimates.
+
+
+In a similar way, we cna obtain analytical expressions for say the
+expectation values of the parameters \( \boldsymbol{\beta} \) and their variance
+when we employ Ridge regression, and thereby a confidence interval.
+
+
+It is rather straightforward to show that
+$$
+\mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\boldsymbol{\beta}^{\mathrm{OLS}}.
+$$
+
+We see clearly that
+\( \mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big] \not= \boldsymbol{\beta}^{\mathrm{OLS}} \) for any \( \lambda > 0 \). We say then that the ridge estimator is biased.
+
+
+We can also compute the variance as
+
+$$
+\mbox{Var}[\boldsymbol{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T},
+$$
+
+and it is easy to see that if the parameter \( \lambda \) goes to infinity then the variance of Ridge parameters \( \boldsymbol{\beta} \) goes to zero.
+
+
+With this, we can compute the difference
+
+$$
+\mbox{Var}[\boldsymbol{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\boldsymbol{\beta}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}.
+$$
+
+The difference is non-negative definite since each component of the
+matrix product is non-negative definite.
+This means the variance we obtain with the standard OLS will always for \( \lambda > 0 \) be larger than the variance of \( \boldsymbol{\beta} \) obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below.
-
Instead of choosing the penalty parameter to balance model fit with
@@ -2597,12 +2987,15 @@ model complexity, cross-validation requires it (i.e. the penalty
parameter) to yield a model with good prediction
performance. Commonly, this performance is evaluated on novel
data. Novel data need not be easy to come by and one has to make do
-with the data at hand. The setting of `original' and novel data is
+with the data at hand.
+
+
+The setting of original and novel data is
then mimicked by sample splitting: the data set is divided into two
-(groups of samples). One of these two data sets, called the training
-set, plays the role of `original' data on which the model is
+(groups of samples). One of these two data sets, called the
+training set, plays the role of original data on which the model is
built. The second of these data sets, called the test set, plays the
-role of the `novel' data and is used to evaluate the prediction
+role of the novel data and is used to evaluate the prediction
performance (often operationalized as the log-likelihood or the
prediction error or its square or the R2 score) of the model built on the training data set. This
procedure (model building and prediction evaluation on training and
@@ -2620,7 +3013,7 @@ some sense) is then selected.
The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks:
@@ -2632,7 +3025,7 @@ The validation set approach is conceptually simple and is easy to implement. But
-
When the repetitive splitting of the data set is done randomly,
@@ -2653,32 +3046,32 @@ cross-validation (LOOCV).
-
-Another approach in the LOOCV scheme is to the use the so-called Predicted Residual Error Sum of Squares (PRESS).
-
-
-We can define the optimal penalty parameter to minimize
-$$
-\begin{align*}
-\lambda_{\mbox{{\tiny opt}}} = \arg \min_{\lambda} \frac{1}{n} \sum_{i=1}^n [y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)]^2.
-\end{align*}
-$$
-
-
-The LOOCV prediction performance can be
-expressed analytically in terms of the known quantities derived from
-the design matrix and the parameters \( \beta \).
-
-
Two famous
@@ -2736,18 +3105,18 @@ need for bootstrapping.
The Jackknife works by making many replicas of the estimator \( \widehat{\theta} \).
-The jackknife is a resampling method, we explained that this happens by scrambling the data in some way. When using the jackknife, this is done by systematically leaving out one observation from the vector of observed values \( \hat{x} = (x_1,x_2,\cdots,X_n) \).
-Let \( \hat{x}_i \) denote the vector
+The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \( \boldsymbol{x} = (x_1,x_2,\cdots,X_n) \).
+Let \( \boldsymbol{x}_i \) denote the vector
$$
-\hat{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n),
+\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n),
$$
-which equals the vector \( \hat{x} \) with the exception that observation
+which equals the vector \( \boldsymbol{x} \) with the exception that observation
number \( i \) is left out. Using this notation, define
\( \widehat{\theta}_i \) to be the estimator
\( \widehat{\theta} \) computed using \( \vec{X}_i \).
@@ -2755,20 +3124,6 @@ number \( i \) is left out. Using this notation, define
-To get an estimate for the bias and
-standard error of \( \widehat{\theta} \), use the following
-estimators for each component of \( \widehat{\theta} \)
-
-$$
-\widehat{\mathrm{Bias}}(\widehat \theta,\theta) = (n-1)\left( - \widehat{\theta} + \frac{1}{n}\sum_{i=1}^{n} \widehat \theta_i \right) \qquad \text{and} \qquad \widehat{\sigma}^2_{\widehat{\theta} } = \frac{n-1}{n}\sum_{i=1}^{n}( \widehat{\theta}_i - \frac{1}{n}\sum_{j=1}^{n}\widehat \theta_j )^2.
-$$
-
-
-
@@ -2829,14 +3184,14 @@ advantages:
-Since \( \widehat{\theta} = \widehat{\theta}(\hat{X}) \) is a function of random variables,
+Since \( \widehat{\theta} = \widehat{\theta}(\boldsymbol{X}) \) is a function of random variables,
\( \widehat{\theta} \) itself must be a random variable. Thus it has
-a pdf, call this function \( p(\hat{t}) \). The aim of the bootstrap is to
-estimate \( p(\hat{t}) \) by the relative frequency of
+a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to
+estimate \( p(\boldsymbol{t}) \) by the relative frequency of
\( \widehat{\theta} \). You can think of this as using a histogram
-in the place of \( p(\hat{t}) \). If the relative frequency closely
+in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely
resembles \( p(\vec{t}) \), then using numerics, it is straight forward to
-estimate all the interesting parameters of \( p(\hat{t}) \) using point
+estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point
estimators.
@@ -2859,7 +3214,7 @@ been straight forward to do this by:
By repeated use of (1) and (2), many
estimates of \( \widehat{\theta} \) could have been obtained. The
idea is to use the relative frequency of \( \widehat{\theta}^* \)
-(think of a histogram) as an estimate of \( p(\hat{t}) \).
+(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \).
+The following code starts with a Gaussian distribution with mean value
+\( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data
+used in the bootstrap analysis. The bootstrap analysis returns a data
+set after a given number of bootstrap operations (as many as we have
+data points). This data set consists of estimated mean values for each
+bootstrap operation. The histogram generated by the bootstrap method
+shows that the distribution for these mean values is also a Gaussian,
+centered around the mean value \( \mu=100 \) but with standard deviation
+\( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in
+this case the same as the number of original data points). The value
+of the standard deviation is what we expect from the central limit
+theorem.
+
@@ -2917,30 +3294,29 @@ The following code starts with a Gaussian distribution with mean value \( \mu =1
def stat(data):
return mean(data)
-# Bootstrap algorithm
+# Bootstrap algorithm
def bootstrap(data, statistic, R):
t = zeros(R); n = len(data); inds = arange(n); t0 = time()
-
- # non-parametric bootstrap
+ # non-parametric bootstrap
for i in range(R):
t[i] = statistic(data[randint(0,n,n)])
- # analysis
+ # analysis
print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
print("original bias std. error")
- print("%8g %8g %14g %15g" % (statistic(data), std(data),\
- mean(t), \
- std(t)))
+ print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
return t
mu, sigma = 100, 15
datapoints = 10000
x = mu + sigma*random.randn(datapoints)
-# bootstrap returns the data sample t = bootstrap(x, stat, datapoints)
-# the histogram of the bootstrapped data n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
+# bootstrap returns the data sample
+t = bootstrap(x, stat, datapoints)
+# the histogram of the bootstrapped data
+n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
-# add a 'best fit' line
+# add a 'best fit' line
y = mlab.normpdf( binsboot, mean(t), std(t))
lt = plt.plot(binsboot, y, 'r--', linewidth=1)
plt.xlabel('Smarts')
@@ -2953,529 +3329,300 @@ plt.show()
-The blocking method was made popular by Flyvbjerg and Pedersen (1989)
-and has become one of the standard ways to estimate
-\( V(\widehat{\theta}) \) for exactly one \( \widehat{\theta} \), namely
-\( \widehat{\theta} = \overline{X} \).
-
-
-Assume \( n = 2^d \) for some integer \( d>1 \) and \( X_1,X_2,\cdots, X_n \) is a stationary time series to begin with.
-Moreover, assume that the time series is asymptotically uncorrelated. We switch to vector notation by arranging \( X_1,X_2,\cdots,X_n \) in an \( n \)-tuple. Define:
-$$
-\begin{align*}
-\hat{X} = (X_1,X_2,\cdots,X_n).
-\end{align*}
-$$
-
-
-The strength of the blocking method is when the number of
-observations, \( n \) is large. For large \( n \), the complexity of dependent
-bootstrapping scales poorly, but the blocking method does not,
-moreover, it becomes more accurate the larger \( n \) is.
-
-
-
-The quantity \( \vec{X}_k \) is
-subject to \( k \) blocking transformations. We now have \( d \) vectors
-\( \vec{X}_0, \vec{X}_1,\cdots,\vec X_{d-1} \) containing the subsequent
-averages of observations. It turns out that if the components of
-\( \vec{X} \) is a stationary time series, then the components of
-\( \vec{X}_i \) is a stationary time series for all \( 0 \leq i \leq d-1 \)
-
-
-We can then compute the autocovariance, the variance, sample mean, and
-number of observations for each \( i \).
-Let \( \gamma_i, \sigma_i^2,
-\overline{X}_i \) denote the autocovariance, variance and average of the
-elements of \( \vec{X}_i \) and let \( n_i \) be the number of elements of
-\( \vec{X}_i \). It follows by induction that \( n_i = n/2^i \).
-
-
-
-Using the
-definition of the blocking transformation and the distributive
-property of the covariance, it is clear that since \( h =|i-j| \)
-we can define
-$$
-\begin{align}
-\gamma_{k+1}(h) &= cov\left( ({X}_{k+1})_{i}, ({X}_{k+1})_{j} \right) \nonumber \\
-&= \frac{1}{4}cov\left( ({X}_{k})_{2i-1} + ({X}_{k})_{2i}, ({X}_{k})_{2j-1} + ({X}_{k})_{2j} \right) \nonumber \\
-&= \frac{1}{2}\gamma_{k}(2h) + \frac{1}{2}\gamma_k(2h+1) \hspace{0.1cm} \mathrm{h = 0}
-\label{_auto12}\\
-&=\frac{1}{4}\gamma_k(2h-1) + \frac{1}{2}\gamma_k(2h) + \frac{1}{4}\gamma_k(2h+1) \quad \mathrm{else}
-\label{_auto13}
-\end{align}
-$$
-
-
-The quantity \( \hat{X} \) is asymptotic uncorrelated by assumption, \( \hat{X}_k \) is also asymptotic uncorrelated. Let's turn our attention to the variance of the sample mean \( V(\overline{X}) \).
-
-
-
-
-We can then wrap up
-$$
-\begin{align}
-n_{j+1} \overline{X}_{j+1} &= \sum_{i=1}^{n_{j+1}} (\hat{X}_{j+1})_i = \frac{1}{2}\sum_{i=1}^{n_{j}/2} (\hat{X}_{j})_{2i-1} + (\hat{X}_{j})_{2i} \nonumber \\
-&= \frac{1}{2}\left[ (\hat{X}_j)_1 + (\hat{X}_j)_2 + \cdots + (\hat{X}_j)_{n_j} \right] = \underbrace{\frac{n_j}{2}}_{=n_{j+1}} \overline{X}_j = n_{j+1}\overline{X}_j.
-\label{_auto16}
-\end{align}
-$$
-
-By repeated use of this equation we get \( V(\overline{X}_i) = V(\overline{X}_0) = V(\overline{X}) \) for all \( 0 \leq i \leq d-1 \). This has the consequence that
-$$
-\begin{align}
-V(\overline{X}) = \frac{\sigma_k^2}{n_k} + e_k \qquad \text{for all} \qquad 0 \leq k \leq d-1. \label{eq:convergence}
-\end{align}
-$$
-
-
-Fyvbjerg and Petersen demonstrated that the sequence
-\( \{e_k\}_{k=0}^{d-1} \) is decreasing, and conjecture that the term
-\( e_k \) can be made as small as we would like by making \( k \) (and hence
-\( d \)) sufficiently large. The sequence is decreasing (Master of Science thesis by Marius Jonsson, UiO 2018).
-It means we can apply blocking transformations until
-\( e_k \) is sufficiently small, and then estimate \( V(\overline{X}) \) by
-\( \widehat{\sigma}^2_k/n_k \).
-
-
-
-
-We begin with an unknown function \( y=f(x) \) and fix a \emph{hypothesis set}
- \( \mathcal{H} \) consisting of all functions we are willing to consider,
- defined also on the domain of \( f \). This set may be uncountably
- infinite (e.g. if there are real-valued parameters to fit).
-The
- choice of which functions to include in \( \mathcal{H} \) usually depends
- on our intuition about the problem of interest. The function \( f(x) \)
- produces a set of pairs \( (x_i,y_i) \), \( i=1\dots N \), which serve as the
- observable data. Our goal is to select a function from the hypothesis
- set \( h\in\mathcal{H} \) which approximates \( f(x) \) as best as possible,
- namely, we would like to find \( h\in\mathcal{H} \) such that \( h\approx
- f \) in some strict mathematical sense which we specify below. If this
- is possible, we say that we \emph{learned} \( f(x) \). But if the
- function \( f(x) \) can, in principle, take any value on
- \emph{unobserved} inputs, how is it possible to learn in any
- meaningful sense?
+We will discuss the bias-variance tradeoff in the context of
+continuous predictions such as regression. However, many of the
+intuitions and ideas discussed here also carry over to classification
+tasks. Consider a dataset \( \mathcal{L} \) consisting of the data
+\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \).
+
+Let us assume that the true data is generated from a noisy model
+
+$$
+\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon}
+$$
+
+
+where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \).
+
+
+In our derivation of the ordinary least squares method we defined then
+an approximation to the function \( f \) in terms of the parameters
+\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model,
+that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \).
+
+
+Thereafter we found the parameters \( \boldsymbol{\beta} \) by optimizing the means squared error via the so-called cost function
+$$
+C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right].
+$$
+
+
+We can rewrite this as
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2.
+$$
+
+
+The three terms represent the square of the bias of the learning
+method, which can be thought of as the error caused by the simplifying
+assumptions built into the method. The second term represents the
+variance of the chosen model and finally the last terms is variance of
+the error \( \boldsymbol{\epsilon} \).
+
+
+To derive this equation, we need to recall that the variance of \( \boldsymbol{y} \) and \( \boldsymbol{\epsilon} \) are both equal to \( \sigma^2 \). The mean value of \( \boldsymbol{\epsilon} \) is by definition equal to zero. Furthermore, the function \( f \) is not a stochastics variable, idem for \( \boldsymbol{\tilde{y}} \).
+We use a more compact notation in terms of the expectation value
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right],
+$$
+
+and adding and subtracting \( \mathbb{E}\left[\boldsymbol{\tilde{y}}\right] \) we get
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right],
+$$
+
+which, using the abovementioned expectation values can be rewritten as
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2,
+$$
+
+that is the rewriting in terms of the so-called bias, the variance of the model \( \boldsymbol{\tilde{y}} \) and the variance of \( \boldsymbol{\epsilon} \).
+
+
+
+
+
+
+
+
+
+
-
-We will discuss the bias-variance tradeoff in the context of continuous predictions such as regression. However, many of the intuitions and ideas discussed here also carry over to classification tasks. Consider a dataset \( \mathcal{L} \) consisting of the data \( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=1\ldots N\} \). Let us assume that the true data is generated from a noisy model
-$$
-y=f(\boldsymbol{x}) + \epsilon
-$$
-
-where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma_\epsilon \).
-
-
-
-We have a statistical procedure (e.g. least-squares regression) for
-forming a predictor \( \hat{g}_{\mathcal{L}}(\boldsymbol{x}) \) that gives the
-prediction of our model for a new data point \( \boldsymbol{x} \). This estimator
-is chosen by minimizing a cost function which we take to be the
-squared error
-
-$$
- \mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) = \sum_i (y_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2.
-$$
-
-
-
-We are interested in the generalization error on all data drawn from
-the true model, not just the error on the particular training dataset
-\( \mathcal{L} \) that we have in hand. This is just the expectation of
-the cost function over many different data sets
-\( \{\mathcal{L}_j\} \). Denote this expectation value by
-\( E_{\mathcal{L}} \). In other words, we can view \( \hat{g}_{\mathcal{L}} \)
-as a stochastic functional that depends on the dataset \( \mathcal{L} \)
-and we can think of \( E_{\mathcal{L}} \) as the expected value of the
-functional if we drew an infinite number of datasets \( \{\mathcal{L}_1,
-\mathcal{L}_2, \ldots \} \).
-
-
-
-We would also like to average over different instances of the
-"noise" \( \epsilon \) and we denote the expectation value over the
-noise by \( E_\epsilon \). Thus, we can decompose the expected
-generalization error as
-
-$$
-\begin{align}
-E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ]&= E_\mathcal{L,\epsilon}\left[ \sum_i ({y}_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2 \right] \nonumber \\
- &= E_\mathcal{L, \epsilon}\left[ \sum_{i}({y}_i -f(\boldsymbol{x}_i) +f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2\right] \nonumber \\
- &= \sum_i E_\epsilon[ ({y}_i -f(\boldsymbol{x}_i))^2 ]+ E_\mathcal{L, \epsilon}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] + 2E_\epsilon[{y}_i -f(\boldsymbol{x}_i)]E_\mathcal{L}[f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i)] \nonumber \\
- &=\sum_i \sigma_\epsilon^2 + E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2],
-\label{_auto17}
-\end{align}
-$$
-
-
-where in the last line we used the fact that our noise has zero mean
-and variance \( \sigma_\epsilon^2 \) and the sum over \( i \) applies to all
-terms.
-
-
-
-It is also helpful to further decompose the second term as
-follows:
-
-$$
-\begin{align}
-E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] &=E_\mathcal{L}[(f(\mathbf{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]+ E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] \nonumber \\
-&=E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] + E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] \nonumber \\
-&+2E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])] \nonumber \\
-&=(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2+E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2].
-\label{_auto18}
-\end{align}
-$$
-
-
-
-The first term is called the bias
-$$
-Bias^2= \sum_i (f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2
-$$
-
-and measures the deviation of the expectation value of our estimator (i.e. the asymptotic value of our estimator in the infinite data limit) from the true value.
-
-
-
-and measures how much our estimator fluctuates due to finite-sample effects. Combining these expressions, we see that the expected out-of-sample error of our model can be decomposed as
-$$
-E_\mathrm{out}=E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ] = Bias^2 + Var + Noise.
-$$
+
The bias-variance tradeoff summarizes the fundamental tension in
machine learning, particularly supervised learning, between the
complexity of a model and the amount of training data needed to train
it. Since data is often limited, in practice it is often useful to
-use a less-complex model with higher bias – a model whose asymptotic
-performance is worse than another model – because it is easier to
+use a less-complex model with higher bias, that is a model whose asymptotic
+performance is worse than another model because it is easier to
train and less sensitive to sampling noise arising from having a
finite-sized training dataset (smaller variance).
-
-
-
-
The above equations tell us that in
order to minimize the expected test error, we need to select a
@@ -3498,15 +3645,99 @@ flexible statistical methods have higher variance.
+
+
+
+
-The one-dimensional Ising model with nearest neighbor interaction, no external field and a constant coupling constant \( J \) is given by
+Let us bring back the Ising model again, but now with an additional
+focus on Ridge and Lasso regression as well. We repeat some of the
+basic parts of the Ising model and the setup of the training and test
+data. The one-dimensional Ising model with nearest neighbor
+interaction, no external field and a constant coupling constant \( J \) is
+given by
$$
\begin{align}
H = -J \sum_{k}^L s_k s_{k + 1},
-\label{_auto19}
+\label{_auto17}
\end{align}
$$
@@ -3540,25 +3771,13 @@ energies = np.zeros(n)
for i in range(n):
energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
-Here we use linear (ordinary least squares), ridge and LASSO
-regression to predict the energy in the nearest neighbor
-one-dimensional Ising model on a ring, i.e., the endpoints wrap
-around. We will use the linear regression models to fit a value for
-the coupling constant to achieve this.
-
-
-
A more general form for the one-dimensional Ising model is
$$
\begin{align}
H = - \sum_j^L \sum_k^L s_j s_k J_{jk}.
-\label{_auto20}
+\label{_auto18}
\end{align}
$$
@@ -3569,7 +3788,7 @@ a matrix-product on the form
$$
\begin{align}
H = X J,
-\label{_auto21}
+\label{_auto19}
\end{align}
$$
@@ -3579,11 +3798,12 @@ elements \( -J_{jk} \). This form of writing the energy fits perfectly
with the form utilized in linear regression, viz.
$$
\begin{align}
- y = X\omega + \epsilon,
-\label{_auto22}
+ \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}.
+\label{_auto20}
\end{align}
$$
+We organize the data as we did above
@@ -3604,149 +3824,7 @@ X_test_own = np.concatenate(
)
-
-The problem at hand is to try to fit the equation
-$$
-\begin{align}
- y = f(x) + \epsilon,
-\label{_auto23}
-\end{align}
-$$
-
-
-where \( f(x) \) is some unknown function of the data \( x \) and \( \epsilon \)
-is normally distributed with mean zero noise with standard deviation
-\( \sigma_{\epsilon} \). Our job is to try to find a predictor which
-estimates the function \( f(x) \). In linear regression we assume that we
-can formulate the problem as
-
-$$
-\begin{align}
- y = X\omega + \epsilon,
-\label{_auto24}
-\end{align}
-$$
-
-
-where \( X \) and \( \omega \) are now matrices. Our job at hand is now to
-find a cost function \( C \), which we wish to minimize in order to find
-the best estimate of \( \omega \).
-
-
-
-In the ordinary least squares method we choose the cost function
-$$
-\begin{align}
- C(X, \omega) = ||X\omega - y||^2
- = (X\omega - y)^T(X\omega - y)
-\label{_auto25}
-\end{align}
-$$
-
-We then find the extremal point of \( C \) by taking the derivative with respect to \( \omega \) and setting it to zero, i.e.,
-
-$$
-\begin{align}
- \dfrac{\mathrm{d}C}{\mathrm{d}\omega}
- = 0.
-\label{_auto26}
-\end{align}
-$$
-
-This yields the expression for \( \omega \) to be
-$$
-\begin{align}
- \omega = \frac{X^T y}{X^T X},
-\label{_auto27}
-\end{align}
-$$
-
-
-which immediately imposes some requirements on \( X \) as there must exist
-an inverse of \( X^T X \). If the expression we are modelling contains an
-intercept, i.e., a constant expression we must make sure that the
-first column of \( X \) consists of \( 1 \).
-
-
-
-
-
-
-Using singular value decomposition we have that \( X = U\Sigma V^T \),
-where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for
-\( \omega \) to
-$$
-\begin{align}
- \omega = V\Sigma^{+} U^T y.
-\label{_auto30}
-\end{align}
-$$
-
-
-Note that solving this equation by actually doing the pseudoinverse
-(which is what we will do) is not a good idea as this operation scales
-as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a
-general matrix. Instead, doing \( QR \)-factorization and solving the
-linear system as an equation would reduce this down to
-\( \mathcal{O}(n^2) \) operations.
-
-
-
-
-
-Before passing in the data to the function we append a column with ones to the training data.
-
-
-
-
-
-
-Next we fit a
@@ -3754,29 +3832,18 @@ Next we fit a
-Extracting the \( J \)-matrix from both our own method and the Scikit-learn model where we make sure to remove the intercept.
-
+When extracting the \( J \)-matrix we make sure to remove the intercept
-
-A way of looking at the coefficients in \( J \) is to plot the matrices as images.
-
+And then we plot the results
Having explored the ordinary least squares we move on to ridge
regression. In ridge regression we include a regularizer. This
involves a new cost function which leads to a new estimate for the
-weights \( \omega \). This results in a penalized regression problem. The
+weights \( \boldsymbol{\beta} \). This results in a penalized regression problem. The
cost function is given by
$$
\begin{align}
- C(X, \omega; \lambda) = ||X\omega - y||^2 + \lambda ||\omega||^2
- = (X\omega - y)^T(X\omega - y) + \lambda \omega^T\omega.
-\label{_auto31}
+ C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \boldsymbol{\beta}^T\boldsymbol{\beta}.
+\label{_auto21}
\end{align}
$$
-Finding the extremum of this function yields the weights
-
-$$
-\begin{align}
- \omega(\lambda) = \frac{X^Ty}{X^TX + \lambda} \to \frac{\omega_{\text{LS}}}{1 + \lambda},
-\label{_auto32}
-\end{align}
-$$
-
-
-where \( \omega_{\text{LS}} \) is the weights from ordinary least
-squares. The last assumption assumes that \( X \) is orthogonal, which it
-is not. We will therefore resort to solving the equation as it stands
-on the left hand side.
-
-
In the Least Absolute Shrinkage and Selection Operator (LASSO)-method we get a third cost function.
+
$$
\begin{align}
- C(X, \omega; \lambda) =
- ||X\omega - y||^2 + \lambda ||\omega||
- = (X\omega - y)^T(X\omega - y) + \lambda \sqrt{\omega^T\omega}.
-\label{_auto33}
+ C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \sqrt{\boldsymbol{\beta}^T\boldsymbol{\beta}}.
+\label{_auto22}
\end{align}
$$
-Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-learn.
+
+Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-Learn.
@@ -3897,41 +3931,7 @@ constant as opposed to ridge and OLS. We get a sparse solution with
-In order to judge which model performs best at varying values of \( \lambda \) (for ridge and LASSO) we compute \( R^2 \) which is given by
-
-$$
-\begin{align}
- R^2 = 1 - \frac{(y - \hat{y})^2}{(y - \bar{y})^2},
-\label{_auto34}
-\end{align}
-$$
-
-where \( y \) is a vector with the true values of the energy, \( \hat{y} \) is the predicted values of \( y \) from the models and \( \bar{y} \) is the mean of \( \hat{y} \).
-
-
-
-
-
-This is the same metric used by Scikit-learn for their regression models when scoring.
-
-
-
-
-
We see how the different models perform for a different set of values for \( \lambda \).
@@ -3942,17 +3942,13 @@ We see how the different models perform for a different set of values for \( \la
To determine which value of \( \lambda \) is best we plot the accuracy of
@@ -4029,8 +4001,6 @@ testing set that is close to the accuracy of the training set.
From the above figure we can see that LASSO with \( \lambda = 10^{-2} \)
-achieve a very good accuracy on the test set. This by far surpases the
+achieves a very good accuracy on the test set. This by far surpasses the
other models for all values of \( \lambda \).
+
+
+We will generate our own dataset for a function \( y(x) \) where \( x \in [0,1] \) and defined by random numbers computed with the uniform distribution. The function \( y \) is a quadratic polynomial in \( x \) with added stochastic noise according to the normal distribution \( \cal {N}(0,1) \).
+The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points).
+
+
+
+
+You can use the functionality included in scikit-learn. If you feel
+for it, you can use your own program and define functions which
+compute the above two functions. Discuss the meaning of these
+results. Try also to vary the coefficient in front of the added
+stochastic noise term and discuss the quality of the fits.
+
+
+Show that the variance of the parameters \( \beta \) in the linear regression method (chapter 3, equation (3.8) of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer) is given as
+
+$$
+\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2,
+$$
+
+with
+$$
+\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2,
+$$
+
+where we have assumed that we fit a function of degree \( p-1 \) (for example a polynomial in \( x \)).
+
+
+This exercise is a continuation of exercise 1. We will
+use the same function to generate our data set, still staying with a
+simple function \( y(x) \) which we want to fit using linear regression,
+but now extending the analysis to include the Ridge and the Lasso
+regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods.
+
+
+We will thus again generate our own dataset for a function \( y(x) \) where
+\( x \in [0,1] \) and defined by random numbers computed with the uniform
+distribution. The function \( y \) is a quadratic polynomial in \( x \) with
+added stochastic noise according to the normal distribution \( \cal{N}(0,1) \).
+
+
+The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points).
+
+
+
+
+We will study how
+to fit polynomials to a specific two-dimensional function called
+Franke's
+function. This
+is a function which has been widely used when testing various interpolation and fitting
+algorithms. Furthermore, after having established the model and the
+method, we will employ resamling techniques such as the cross-validation and/or
+the bootstrap methods, in order to perform a proper assessment of our models.
+
+
+The Franke function, which is a weighted sum of four exponentials reads as follows
+$$
+\begin{align*}
+f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\
+&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }.
+\end{align*}
+$$
+
+
+The function will be defined for \( x,y\in [0,1] \). Our first step will
+be to perform an OLS regression analysis of this function, trying out
+a polynomial fit with an \( x \) and \( y \) dependence of the form \( [x, y,
+x^2, y^2, xy, \dots] \). We will also include cross-validation and
+bootstrap as resampling techniques. As in homeworks 1 and 2, we
+can use a uniform distribution to set up the arrays of values for \( x \)
+and \( y \), or as in the example below just a fix values for \( x \) and \( y \) with a given step size.
+In this case we will have two predictors and need to fit a
+function (for example a polynomial) of \( x \) and \( y \). Thereafter we will
+repeat much of the same procedure using the the Ridge and
+Lasso regression methods, introducing thus a dependence on the bias
+(penalty) \( \lambda \).
+
+
+The Python fucntion for the Franke function is included here (it performs also a three-dimensional plot of it)
+
+
+
+
+We will thus again generate our own dataset for a function \( \mathrm{FrankeFunction}(x,y) \) where
+\( x,y \in [0,1] \) could be defined by random numbers computed with the uniform
+distribution. The function \( f(x,y) \) is the Franke function. You should explore also the addition
+an added stochastic noise to this function using the normal distribution \( \cal{N}(0,1) \).
+
+
+Write your own code (using either a matrix inversion or a singular value decomposition from e.g., numpy ) or use your code from exercises 1 and 3
+and perform a standard least square regression analysis using polynomials in \( x \) and \( y \) up to fifth order. Find the confidence intervals of the parameters \( \beta \) by computing their variances, evaluate the Mean Squared error (MSE)
+$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
+\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
+$$
+
+and the \( R^2 \) score function.
+If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as
+$$
+R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
+$$
+
+where we have defined the mean value of \( \hat{y} \) as
+$$
+\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
+$$
+
+
+Perform a resampling of the data where you split the data in training data and test data. Implement the \( k \)-fold cross-validation algorithm and/or the bootstrap algorithm
+and evaluate again the MSE and the \( R^2 \) functions resulting from the test data. Evaluate also the bias and variance of the final models.
+
+
+Write then your own code for the Ridge method, either using matrix
+inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the
+previous exercise (for the same polynomials and include resampling
+techniques) but now for different values of \( \lambda \). Compare and
+analyze your results with those obtained with standard OLS. Study the
+dependence on \( \lambda \) while also varying eventually the strength of
+the noise in your expression for \( \mathrm{FrankeFunction}(x,y) \).
+
+
+Then perform the same studies but now with Lasso regression. Use the functionalities of
+scikit-learn. Give a critical discussion of the three methods and a
+judgement of which model fits the data best.
+
-
+Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \).
+
+
+
-Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) varies as function of another variable or a set of such variables \( \hat{x} =[x_0, x_1,\dots, x_p]^T \).
-The first variable is called the dependent, the outcome or the response variable while the set of variables \( \hat{x} \) is called the independent variable, or the predictor variable or the explanatory variable.
+Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \).
+The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable.
-A regression model aims at finding a likelihood function \( p(y\vert \hat{x}) \), that is the conditional distribution for \( y \) with a given \( \hat{x} \). The estimation of \( p(y\vert \hat{x}) \) is made using a data set with
+A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with
Consider an experiment in which \( p \) characteristics of \( n \) samples are
-measured. The data from this experiment are denoted \( \mathbf{X} \), with
-\( \mathbf{X} \) as above. The matrix \( \mathbf{X} \) is called the design
+measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix
+\( \mathbf{X} \).
+
+
+The matrix \( \mathbf{X} \) is called the design
matrix. Additional information of the samples is available in the
-form of \( \mathbf{Y} \) (also as above). The variable \( \mathbf{Y} \) is
+form of \( \boldsymbol{y} \) (also as above). The variable \( \boldsymbol{y} \) is
generally referred to as the response variable. The aim of
-regression analysis is to explain \( \mathbf{Y} \) in terms of
-\( \mathbf{X} \) through a functional relationship like \( Y_i =
+regression analysis is to explain \( \boldsymbol{y} \) in terms of
+\( \boldsymbol{X} \) through a functional relationship like \( y_i =
f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of
\( f(\cdot) \) is available, it is common to assume a linear relationship
-between \( \mathbf{X} \) and \( \mathbf{Y} \). This assumption gives rise to
-the linear regression model where \( \beta = (\beta_1, \ldots,
-\beta_p)^{\top} \) is the regression parameter. The parameter
-\( \beta_j \), \( j=1, \ldots, p \), represents the effect size of covariate
-\( j \) on the response. That is, for each unit change in covariate \( j \)
-(while keeping the other covariates fixed) the observed change in the
-response is equal to \( \beta_j \).
+between \( \boldsymbol{X} \) and \( \boldsymbol{y} \). This assumption gives rise to
+the linear regression model where \( \boldsymbol{\beta} = [\beta_0, \ldots,
+\beta_{p-1}]^{T} \) are the regression parameters.
+
+
+Linear regression gives us a set of analytical equations for the parameters \( \beta_j \).
-Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \hat{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \hat{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function.
+In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \),
+consider the model we discussed for describing nuclear binding energies.
+
+
+There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model.
+Assuming
+$$
+BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1},
+$$
+
+we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms.
+This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a
+\( p\times n \) matrix \( \boldsymbol{X} \).
+
+
+Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the
+so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \)
+
+
+
+
+Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function.
Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is
$$
-y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_i x_i^j+\epsilon_i,
+y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i,
$$
where \( \epsilon_i \) is the error in our approximation.
@@ -397,7 +428,7 @@ where \( \epsilon_i \) is the error in our approximation.
@@ -408,7 +439,7 @@ y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\
y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\
y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\
\dots & \dots \\
-y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_1x_{n-1}^{n-1}+\epsilon_{n-1}.\\
+y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\
\end{align*}
$$
Defining the vectors
$$
-\hat{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T,
+\boldsymbol{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T,
$$
and
$$
-\hat{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T,
+\boldsymbol{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T,
$$
and
$$
-\hat{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T,
+\boldsymbol{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T,
$$
-and the matrix
+and the design matrix
$$
-\hat{X}=
+\boldsymbol{X}=
\begin{bmatrix}
1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\
1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\
@@ -450,20 +481,28 @@ $$
we can rewrite our equations as
$$
-\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}.
+\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}.
$$
+
+The above design matrix is called a Vandermonde matrix.
-We are obviously not limited to the above polynomial. We could replace the various powers of \( x \) with elements of Fourier series, that is, instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j x_i)} \), or time series or other orthogonal functions.
-For every set of values \( y_i,x_i \) we can then generalize the equations to
+
+
+We are obviously not limited to the above polynomial expansions. We
+could replace the various powers of \( x \) with elements of Fourier
+series or instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j
+x_i)} \), or time series or other orthogonal functions. For every set
+of values \( y_i,x_i \) we can then generalize the equations to
+
$$
\begin{align*}
y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\
@@ -472,22 +511,25 @@ y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilo
\dots & \dots \\
y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\
\dots & \dots \\
-y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\
+y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\
\end{align*}
$$
+
+
+Note that we have \( p=n \) here. The matrix is symmetric. This is generally not the case!
-We redefine in turn the matrix \( \hat{X} \) as
+We redefine in turn the matrix \( \boldsymbol{X} \) as
$$
-\hat{X}=
+\boldsymbol{X}=
\begin{bmatrix}
x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\
x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\
@@ -499,21 +541,21 @@ $$
and without loss of generality we rewrite again our equations as
$$
-\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}.
+\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}.
$$
-The left-hand side of this equation forms know. Our error vector \( \hat{\epsilon} \) and the parameter vector \( \hat{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values?
+The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values?
-We have defined the matrix \( \hat{X} \)
+We have defined the matrix \( \boldsymbol{X} \) via the equations
$$
\begin{align*}
y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\
@@ -522,69 +564,196 @@ y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilo
\dots & \dots \\
y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\
\dots & \dots \\
-y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\
+y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\
\end{align*}
$$
+
+
+As we noted above, we stayed with a system with the design matrix
+ \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \), that is we have \( p=n \). For reasons to come later (algorithmic arguments) we will hereafter define
+our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors refering to the column numbers and the entries \( n \) being the row elements.
+
+
+In our introductory notes we looked at the so-called liguid drop model. Let us remind ourselves about what we did by looking at the code.
+
+
+We restate the parts of the code we are most interested in.
+
+
+
+
+With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as
+$$
+\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta},
+$$
+
+throughout these lectures.
+
+
+
-We well use this matrix to define the approximation \( \hat{\tilde{y}} \) via the unknown quantity \( \hat{\beta} \) as
+With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as
$$
-\hat{\tilde{y}}= \hat{X}\hat{\beta},
+\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta},
$$
-and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parametrized values \( \tilde{y}_i \), namely
+and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely
$$
-Q(\hat{\beta})=\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\left(\hat{y}-\hat{\tilde{y}}\right)^T\left(\hat{y}-\hat{\tilde{y}}\right),
+C(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\},
$$
-or using the matrix \( \hat{X} \) as
+or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as
$$
-Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right).
+C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)\right\}.
$$
+
+This function is one possible way to define the so-called cost function.
+
+
+It is also common to define
+the function \( Q \) as
+
+$$
+C(\boldsymbol{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2,
+$$
+
+since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out.
+
The function
$$
-Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right),
+C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\},
$$
-can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value of for example a numerical experiment. When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value
+can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value.
+When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value (see exercises)
$$
y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i,
$$
-where \( \langle y_i \rangle \) is the mean value. Keep in mind also that till now we have treated \( y_i \) as the exact value. Normally, the response (dependent or outcome) variable \( y_i \) 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.
+
+where \( \langle y_i \rangle \) is the mean value. Keep in mind also that
+till now we have treated \( y_i \) as the exact value. Normally, the
+response (dependent or outcome) variable \( y_i \) 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.
-In order to find the parameters \( \beta_i \) we will then minimize the spread of \( Q(\hat{\beta}) \) by requiring
+In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem
$$
-\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0,
+{\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\}.
+$$
+
+In practical terms it means we will require
+$$
+\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0,
$$
which results in
$$
-\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0,
+\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0,
$$
or in a matrix-vector form as
$$
-\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right).
+\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right).
$$
@@ -594,25 +763,37 @@ $$
We can rewrite
$$
-\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right),
+\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right),
$$
as
$$
-\hat{X}^T\hat{y} = \hat{X}^T\hat{X}\hat{\beta},
+\boldsymbol{X}^T\boldsymbol{y} = \boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta},
$$
-and if the matrix \( \hat{X}^T\hat{X} \) is invertible we have the solution
+and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution
$$
-\hat{\beta} =\left(\hat{X}^T\hat{X}\right)^{-1}\hat{X}^T\hat{y}.
+\boldsymbol{\beta} =\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
$$
+
+We note also that since our design matrix is defined as \( \boldsymbol{X}\in
+{\mathbb{R}}^{n\times p} \), the product \( \boldsymbol{X}^T\boldsymbol{X} \in
+{\mathbb{R}}^{p\times p} \). In the above case we have that \( p \ll n \),
+in our case \( p=5 \) meaning that we end up with inverting a small
+\( 5\times 5 \) matrix. This is a rather common situation, in many cases we end up with low-dimensional
+matrices to invert. The methods discussed here and for many other
+supervised learning algorithms like classification with logistic
+regression or support vector machines, exhibit dimensionalities which
+allow for the usage of direct linear algebra methods such as LU decomposition or Singular Value Decomposition (SVD) for finding the inverse of the matrix
+\( \boldsymbol{X}^T\boldsymbol{X} \).
+
-The residuals \( \hat{\epsilon} \) are in turn given by
+The residuals \( \boldsymbol{\epsilon} \) are in turn given by
$$
-\hat{\epsilon} = \hat{y}-\hat{\tilde{y}} = \hat{y}-\hat{X}\hat{\beta},
+\boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta},
$$
and with
$$
-\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0,
+\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0,
$$
we have
$$
-\hat{X}^T\hat{\epsilon}=\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0,
+\boldsymbol{X}^T\boldsymbol{\epsilon}=\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0,
$$
-meaning that the solution for \( \hat{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.
+meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.
+
+
+
+Let us now return to our nuclear binding energies and simply code the above equations.
+
+
+
+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
+write
+
+
+
+
+Alternatively, you can use the least squares functionality in Numpy as
+
+
+
+
+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.
+Since we are not using _Scikit-Learn here we can define our own \( R2 \) function as
+
+
+
+
+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.
-Normally, the response (dependent or outcome) variable \( y_i \) 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 as
+In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring
$$
-\chi^2(\hat{\beta})=\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\left(\hat{y}-\hat{\tilde{y}}\right)^T\frac{1}{\hat{\Sigma^2}}\left(\hat{y}-\hat{\tilde{y}}\right),
-$$
-
-where the matrix \( \hat{\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(\hat{\beta}) \) by requiring
-$$
-\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \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,
+\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(\hat{\beta})}{\partial \beta_j} = -2\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,
+\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(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right).
+\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 \( \hat{A} =\hat{X}/\hat{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \hat{b} \) with elements \( b_i = y_i/\sigma_i \).
+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 \).
@@ -707,17 +983,17 @@ where we have defined the matrix \( \hat{A} =\hat{X}/\hat{\Sigma} \) with matrix
We can rewrite
$$
-\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right),
+\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right),
$$
as
$$
-\hat{A}^T\hat{b} = \hat{A}^T\hat{A}\hat{\beta},
+\boldsymbol{A}^T\boldsymbol{b} = \boldsymbol{A}^T\boldsymbol{A}\boldsymbol{\beta},
$$
-and if the matrix \( \hat{A}^T\hat{A} \) is invertible we have the solution
+and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution
$$
-\hat{\beta} =\left(\hat{A}^T\hat{A}\right)^{-1}\hat{A}^T\hat{b}.
+\boldsymbol{\beta} =\left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}\boldsymbol{A}^T\boldsymbol{b}.
$$
@@ -733,10 +1009,10 @@ $$
If we then introduce the matrix
$$
-\hat{H} = \left(\hat{A}^T\hat{A}\right)^{-1},
+\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 \( \hat{H} \) are \( h_{ij} \))
+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}
$$
@@ -756,7 +1032,7 @@ $$
@@ -767,12 +1043,12 @@ $$
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(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0,
+\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(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0.
+\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 we don't need to invert a matrix!!
+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},
@@ -797,570 +1073,539 @@ $$
\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.
+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
+nuclear equation of state using results from many-body calculations.
+The equation of state we have made available here, as function of
+density, has been derived using modern nucleon-nucleon potentials with
+the addition of three-body
+forces. This
+time the file is presented as a standard csv file.
+
+
+The beginning of the Python code here is similar to what you have seen before,
+with the same initializations and declarations. We use also pandas
+again, rather extensively in order to organize our data.
+
+
+The difference now is that we use Scikit-Learn's regression tools
+instead of our own matrix inversion implementation. Furthermore, we
+sneak in Ridge regression (to be discussed below) which includes a
+hyperparameter \( \lambda \), also to be explained below.
+
+
+
-
-
-
-
-We see that, as expected, a linear fit gives a seemingly (from the graph) good representation of the data.
-
-
-
-We can repeat the above algorithm using scikit-learn as follows
-
-
-
-
-
-We start with perhaps our simplest possible example, using scikit-learn to perform linear regression analysis on a data set produced by us.
-What follows is a simple Python code where we have defined function \( y \) in terms of the variable \( x \). Both are defined as vectors of dimension \( 1\times 100 \). The entries to the vector \( \hat{x} \) are given by random numbers generated with a uniform distribution with entries \( x_i \in [0,1] \) (more about probability distribution functions later). These values are then used to define a function \( y(x) \) (tabulated again as a vector) with a linear dependence on \( x \) plus a random noise added via the normal distribution.
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
-
-The Numpy functions are imported used the import numpy as np
-statement and the random number generator for the uniform distribution
-is called using the function np.random.rand(), where we specificy
-that we want \( 100 \) random variables. Using Numpy we define
-automatically an array with the specified number of elements, \( 100 \) in
-our case. With the Numpy function randn() we can compute random
-numbers with the normal distribution (mean value \( \mu \) equal to zero and
-variance \( \sigma^2 \) set to one) and produce the values of \( y \) assuming a linear
-dependence as function of \( x \)
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
-$$
-y = 2x+N(0,1),
-$$
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
-
-where \( N(0,1) \) represents random numbers generated by the normal
-distribution. From scikit-learn we import then the
-LinearRegression functionality and make a prediction \( \tilde{y} =
-\alpha + \beta x \) using the function fit(x,y). We call the set of
-data \( (\hat{x},\hat{y}) \) for our training data. The Python package
-scikit-learn has also a functionality which extracts the above
-fitting parameters \( \alpha \) and \( \beta \) (see below). Later we will
-distinguish between training data and test data.
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
-
-For plotting we use the Python package
-matplotlib which produces publication
-quality figures. Feel free to explore the extensive
-gallery of examples. In
-this example we plot our original values of \( x \) and \( y \) as well as the
-prediction ypredict (\( \tilde{y} \)), which attempts at fitting our
-data with a straight line.
+infile = open(data_path("EoS.csv"),'r')
-
-The Python code follows here.
-
+# Read the EoS data as csv file and organize the data into two arrays with density and energies
+EoS = pd.read_csv(infile, names=('Density', 'Energy'))
+EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
+EoS = EoS.dropna()
+Energies = EoS['Energy']
+Density = EoS['Density']
+# The design matrix now as function of various polytrops
+X = np.zeros((len(Density),4))
+X[:,3] = Density**(4.0/3.0)
+X[:,2] = Density
+X[:,1] = Density**(2.0/3.0)
+X[:,0] = 1
-
-
-
-This example serves several aims. It allows us to demonstrate several
-aspects of data analysis and later machine learning algorithms. The
-immediate visualization shows that our linear fit is not
-impressive. It goes through the data points, but there are many
-outliers which are not reproduced by our linear regression. We could
-now play around with this small program and change for example the
-factor in front of \( x \) and the normal distribution. Try to change the
-function \( y \) to
-
-$$
-y = 10x+0.01 \times N(0,1),
-$$
-
-
-where \( x \) is defined as before.
-
-
-
-Does the fit look better? Indeed, by
-reducing the role of the normal distribution we see immediately that
-our linear prediction seemingly reproduces better the training
-set. However, this testing 'by the eye' is obviouly not satisfactory in the
-long run. Here we have only defined the training data and our model, and
-have not discussed a more rigorous approach to the cost function.
-
-
-
-We need more rigorous criteria in defining whether we have succeeded or
-not in modeling our training data. You will be surprised to see that
-many scientists seldomly venture beyond this 'by the eye' approach. A
-standard approach for the cost function is the so-called \( \chi^2 \)
-function
-
-$$ \chi^2 = \frac{1}{n}
-\sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2},
-$$
-
-
-where \( \sigma_i^2 \) is the variance (to be defined later) of the entry
-\( y_i \). We may not know the explicit value of \( \sigma_i^2 \), it serves
-however the aim of scaling the equations and make the cost function
-dimensionless.
-
-
-
-Minimizing the cost function is a central aspect of
-our discussions to come. Finding its minima as function of the model
-parameters (\( \alpha \) and \( \beta \) in our case) will be a recurring
-theme in these series of lectures. Essentially all machine learning
-algorithms we will discuss center around the minimization of the
-chosen cost function. This depends in turn on our specific
-model for describing the data, a typical situation in supervised
-learning. Automatizing the search for the minima of the cost function is a
-central ingredient in all algorithms. Typical methods which are
-employed are various variants of gradient methods. These will be
-discussed in more detail later. Again, you'll be surprised to hear that
-many practitioners minimize the above function ''by the eye', popularly dubbed as
-'chi by the eye'. That is, change a parameter and see (visually and numerically) that
-the \( \chi^2 \) function becomes smaller.
-
-
-
-There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define
-the relative error as
-
-$$
-\epsilon_{\mathrm{relative}}= \frac{\vert \hat{y} -\hat{\tilde{y}}\vert}{\vert \hat{y}\vert}.
-$$
-
-We can modify easily the above Python code and plot the relative error instead
-
-
-
-
-Depending on the parameter in front of the normal distribution, we may
-have a small or larger relative error. Try to play around with
-different training data sets and study (graphically) the value of the
-relative error.
-
-
-
-As mentioned above, scikit-learn has an impressive functionality.
-We can for example extract the values of \( \alpha \) and \( \beta \) and
-their error estimates, or the variance and standard deviation and many
-other properties from the statistical data analysis.
-
-
-Here we show an
-example of the functionality of scikit-learn.
-
-
-
-
-
-The function coef gives us the parameter \( \beta \) of our fit while intercept yields
-\( \alpha \). Depending on the constant in front of the normal distribution, we get values near or far from \( alpha =2 \) and \( \beta =5 \). Try to play around with different parameters in front of the normal distribution. The function meansquarederror gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as
-$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
-\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
-$$
-
-
-The smaller the value, the better the fit. Ideally we would like to
-have an MSE equal zero. The attentive reader has probably recognized
-this function as being similar to the \( \chi^2 \) function defined above.
+We note also that there is a small deviation between the
+standard OLS and the Ridge regression at higher densities. We discuss this in more detail
+below.
-The r2score function computes \( R^2 \), the coefficient of
-determination. It provides a measure of how well future samples are
-likely to be predicted by the model. Best possible score is 1.0 and it
-can be negative (because the model can be arbitrarily worse). A
-constant model that always predicts the expected value of \( \hat{y} \),
-disregarding the input features, would get a \( R^2 \) score of \( 0.0 \).
-
-
-If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as
-$$
-R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
-$$
-
-where we have defined the mean value of \( \hat{y} \) as
-$$
-\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
-$$
-
-
-
-Another quantity will meet again in our discussions of regression analysis is
- mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the \( l1 \)-norm loss. In our discussion above we presented the relative error.
-The MAE is defined as follows
-$$
-\text{MAE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1} \left| y_i - \tilde{y}_i \right|.
-$$
-
-Finally we present the
-squared logarithmic (quadratic) error
-$$
-\text{MSLE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n - 1} (\log_e (1 + y_i) - \log_e (1 + \tilde{y}_i) )^2,
-$$
-
-
-where \( \log_e (x) \) stands for the natural logarithm of \( x \). This error
-estimate is best to use when targets having exponential growth, such
-as population counts, average sales of a commodity over a span of
-years etc.
-
-
-
-We will discuss in more
-detail these and other functions in the various lectures. We conclude this part with another example. Instead of
-a linear \( x \)-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn.
-Add description of the various python commands.
+It is normal in essentially all Machine Learning studies to split the
+data in a training set and a test set (sometimes also an additional
+validation set). Scikit-Learn has an own function for this. There
+is no explicit recipe for how much data should be included as training
+data and say test data. An accepted rule of thumb is to use
+approximately \( 2/3 \) to \( 4/5 \) of the data as training data. We will
+postpone a discussion of this splitting to the end of these notes and
+our discussion of the so-called bias-variance tradeoff. Here we
+limit ourselves to repeat the above equation of state fitting example
+but now splitting the data into a training set and a test set.
-
-Using R, we can perform similar studies.
-
-
-
-
-
-
-
-
-
-Before we proceed, and to link with our discussions of Bayesian statistics to come, it is useful the derive the standard regression analysis equations using a statistical interpretation. This allows us also to derive quantities like the variance and other expectation values in a rather straightforward way.
-
-
-It is assumed that \( \varepsilon_i
-\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are
-independent, i.e.:
-$$
-\begin{align*}
-\mbox{Cov}(\varepsilon_{i_1},
-\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if}
-& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right.
-\end{align*}
-$$
-
-The randomness of \( \varepsilon_i \) implies that
-\( \mathbf{Y}_i \) is also a random variable. In particular,
-\( \mathbf{Y}_i \) is normally distributed, because \( \varepsilon_i \sim
-\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \beta \) is a
-non-random scalar. To specify the parameters of the distribution of
-\( \mathbf{Y}_i \) we need to calculate its first two moments.
-
-Its expectation equals:
-$$
-\begin{align*}
-\mathbb{E}(Y_i) & =
-\mathbb{E}(\mathbf{X}_{i, \ast} \, \beta) + \mathbb{E}(\varepsilon_i)
-\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta,
-\end{align*}
-$$
-
-while
-its variance is
-$$
-\begin{align*} \mbox{Var}(Y_i) & = \mathbb{E} \{ [Y_i
-- \mathbb{E}(Y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( Y_i^2 ) -
-[\mathbb{E}(Y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \,
-\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \beta)^2 \\ &
-= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 \varepsilon_i
-\mathbf{X}_{i, \ast} \, \beta + \varepsilon_i^2 ] - ( \mathbf{X}_{i,
-\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2
-\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \beta +
-\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \beta)^2
-\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \,
-\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2.
-\end{align*}
-$$
-
-Hence, \( Y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \beta, \sigma^2) \).
-
-
-
-A general
-\( m\times n \) matrix \( \hat{A} \) can be written in terms of a diagonal
-matrix \( \hat{D} \) of dimensionality \( n\times n \) and two orthognal
-matrices \( \hat{U} \) and \( \hat{V} \), where the first has dimensionality
-\( m \times m \) and the last dimensionality \( n\times n \).
-We have then
-$$
-\hat{A} = \hat{U}\hat{D}\hat{V}^T
-$$
+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. This may
+however not the be case in general and a standard matrix inversion
+algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit
+the coupling constant of the widely used Ising model.
+There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach.
+
+
+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.
+
+
+The one-dimensional Ising model with nearest neighbor interaction, no
+external field and a constant coupling constant \( J \) is given by
+
+$$
+\begin{align}
+ H = -J \sum_{k}^L s_k s_{k + 1},
+\label{_auto1}
+\end{align}
+$$
+
+
+where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins
+in the system is determined by \( L \). For the one-dimensional system
+there is no phase transition.
+
+
+We will look at a system of \( L = 40 \) spins with a coupling constant of
+\( J = 1 \). To get enough training data we will generate 10000 states
+with their respective energies.
+
+
+
+
+
+Here we use ordinary least squares
+regression to predict the energy for the nearest neighbor
+one-dimensional Ising model on a ring, i.e., the endpoints wrap
+around. We will use linear regression to fit a value for
+the coupling constant to achieve this.
+
+
+
+A more general form for the one-dimensional Ising model is
+
+$$
+\begin{align}
+ H = - \sum_j^L \sum_k^L s_j s_k J_{jk}.
+\label{_auto2}
+\end{align}
+$$
+
+
+Here we allow for interactions beyond the nearest neighbors and a state dependent
+coupling constant. This latter expression can be formulated as
+a matrix-product
+$$
+\begin{align}
+ \boldsymbol{H} = \boldsymbol{X} J,
+\label{_auto3}
+\end{align}
+$$
+
+
+where \( X_{jk} = s_j s_k \) and \( J \) is a matrix which consists of the
+elements \( -J_{jk} \). This form of writing the energy fits perfectly
+with the form utilized in linear regression, that is
+
+$$
+\begin{align}
+ \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon},
+\label{_auto4}
+\end{align}
+$$
+
+
+We split the data in training and test data as discussed in the previous example
+
+
+
+
+
+
+In the ordinary least squares method we choose the cost function
+
+$$
+\begin{align}
+ C(\boldsymbol{X}, \boldsymbol{\beta})= \frac{1}{n}\left\{(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})\right\}.
+\label{_auto5}
+\end{align}
+$$
+
+
+We then find the extremal point of \( C \) by taking the derivative with respect to \( \boldsymbol{\beta} \) as discussed above.
+This yields the expression for \( \boldsymbol{\beta} \) to be
+
+$$
+ \boldsymbol{\beta} = \frac{\boldsymbol{X}^T \boldsymbol{y}}{\boldsymbol{X}^T \boldsymbol{X}},
+$$
+
+
+which immediately imposes some requirements on \( \boldsymbol{X} \) as there must exist
+an inverse of \( \boldsymbol{X}^T \boldsymbol{X} \). If the expression we are modeling contains an
+intercept, i.e., a constant term, we must make sure that the
+first column of \( \boldsymbol{X} \) consists of \( 1 \). We do this here
+
+
+
+
+
+
+
+
+
+Doing the inversion directly turns out to be a bad idea since the matrix
+\( \boldsymbol{X}^T\boldsymbol{X} \) is singular. An alternative approach is to use the singular
+value decomposition. Using the definition of the Moore-Penrose
+pseudoinverse we can write the equation for \( \boldsymbol{\beta} \) as
+
+$$
+ \boldsymbol{\beta} = \boldsymbol{X}^{+}\boldsymbol{y},
+$$
+
+
+where the pseudoinverse of \( \boldsymbol{X} \) is given by
+
+$$
+ \boldsymbol{X}^{+} = \frac{\boldsymbol{X}^T}{\boldsymbol{X}^T\boldsymbol{X}}.
+$$
+
+
+Using singular value decomposition we can decompose the matrix \( \boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma} \boldsymbol{V}^T \),
+where \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal(unitary) matrices and \( \boldsymbol{\Sigma} \) contains the singular values (more details below).
+where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for
+\( \omega \) to
+$$
+\begin{align}
+ \boldsymbol{\beta} = \boldsymbol{V}\boldsymbol{\Sigma}^{+} \boldsymbol{U}^T \boldsymbol{y}.
+\label{_auto6}
+\end{align}
+$$
+
+
+Note that solving this equation by actually doing the pseudoinverse
+(which is what we will do) is not a good idea as this operation scales
+as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a
+general matrix. Instead, doing \( QR \)-factorization and solving the
+linear system as an equation would reduce this down to
+\( \mathcal{O}(n^2) \) operations.
+
+
+
+
+
+
+
+
+When extracting the \( J \)-matrix we need to make sure that we remove the intercept, as is done here
+
+
+
+
+
+A way of looking at the coefficients in \( J \) is to plot the matrices as images.
+
+
+
+
+
+It is interesting to note that OLS
+considers both \( J_{j, j + 1} = -0.5 \) and \( J_{j, j - 1} = -0.5 \) as
+valid matrix elements for \( J \).
+In our discussion below on hyperparameters and Ridge and Lasso regression we will see that
+this problem can be removed, partly and only with Lasso regression.
+
+
+In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD?
+
+
+
One of the typical problems we encounter with linear regression, in particular
-when the matrix \( \hat{X} \) (our so-called design matrix) is high-dimensional,
-are problems with near singular or singular matrices. The column vectors of \( \hat{X} \)
+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
@@ -1380,7 +1625,7 @@ $$
$$
-The columns of \( \hat{X} \) are linearly dependent. We se this easily since the
+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
@@ -1388,10 +1633,10 @@ 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 \( \hat{X}^T\hat{x} \) (the matrix we needto 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
+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*}
-\hat{X} & = \left[
+\boldsymbol{X} & = \left[
\begin{array}{rr}
1 & -1
\\
@@ -1400,425 +1645,421 @@ $$
\end{align*}
$$
-We see easily that \( \mbox{det}(\hat{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 \( \hat{X} \) has at least an eigenvalue which is zero.
+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 \( \hat{X} \) which enters the linear regression problem
+If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem
$$
\begin{align}
-\hat{\beta} & = (\hat{X}^{T} \hat{X})^{-1} \hat{X}^{T} \hat{y},
-\label{_auto1}
+\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y},
+\label{_auto7}
\end{align}
$$
has linearly dependent column vectors, we will not be able to compute the inverse
-of \( \hat{X}^T\hat{X} \) and we cannot find the parameters (estimators) \( \beta_i \).
-The estimators are only well-defined if \( (\hat{X}^{T}\hat{X})^{-1} \) exits.
-This is more likely to happen when the matrix \( \hat{X} \) is high-dimensional. In this case it is likely to encounter a situation where
+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.
-The ad hoc approach which was introduced in the 70s was simply to add a diagonal component to the matrix to invert, that is we change
+A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change
$$
-\hat{X}^{T} \hat{X} \rightarrow \hat{X}^{T} \hat{X}+\lambda \hat{I},
+\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I},
$$
-where \( \hat{I} \) is the identity matrix.
+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.
-We start by considering the case
-\( f(x)=2x \).
+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} \).
-Then the data is clearly generated by a model that is contained within
-all three model classes we are using to make predictions (linear
-models, third order polynomials, and tenth order polynomials).
+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.
-Run the code for the following cases:
+
+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 \( n\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!
+
+
+
+Consider the following matrix which can be SVD decomposed as
+
+$$
+\boldsymbol{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T.
+$$
+
+
+This is a \( 3\times 2 \) matrix which is decomposed in terms of a
+\( 3\times 3 \) matrix \( \boldsymbol{U} \), and a \( 2\times 2 \) matrix \( \boldsymbol{V} \). It is easy to see
+that \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal (how?).
+
+
+And the SVD
+decomposition (singular values) gives eigenvalues
+\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=2 \), 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\lg 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.
+
+
+
+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.
+
+
+
+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
+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.
+
+
+
+Before we proceed, we need to rethink what we have been doing. In our
+eager to fit the data, we have omitted several important elements in
+our regression analysis. In what follows we will
-Thus far, we have considered the case where the data is generated using a model contained in the model class. Now consider \( f(x)=2x-10x^5+15x^{10} \) . Notice that the for linear and third-order polynomial the true model \( f(x) \) is not contained in model class.
-
-
-
-
-
-
-
-
-
-
-
-
-
-In Ridge regression and the subsequent discussion of its properties
-the bias or penalty parameter is considered known or `given'. In
-practice, it is unknown and the user needs to make an informed
-decision on its value. How do we do that? Much of the same considerations apply to the Lasso method.
-
-
-
-
-
-
-
-
-
-
-
@@ -1838,9 +2079,11 @@ once using the original training sample.
+
Resampling approaches can be computationally expensive, because they
involve fitting the same statistical method multiple times using
@@ -1857,21 +2100,23 @@ of flexibility. The process of evaluating a model’s performance is
known as model assessment, whereas the process of selecting the proper
level of flexibility for a model is known as model selection. The
bootstrap is widely used.
+
+
@@ -1932,7 +2177,7 @@ selection of a large set of these numbers reproduces this PDF.
@@ -1955,7 +2200,7 @@ $$
@@ -1973,14 +2218,14 @@ $$
\begin{align}
\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle =
\int\! (x-\langle x\rangle)^2 p(x)\,dx
-\label{_auto2}\\
+\label{_auto8}\\
& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} +
\langle x\rangle^2\right)p(x)\,dx
-\label{_auto3}\\
+\label{_auto9}\\
& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2
-\label{_auto4}\\
+\label{_auto10}\\
& = \langle x^2\rangle - \langle x\rangle^2
-\label{_auto5}
+\label{_auto11}
\end{align}
$$
@@ -1993,7 +2238,7 @@ qualitatively as the spread of \( p \) around its mean.
@@ -2024,7 +2269,7 @@ $$
@@ -2037,17 +2282,17 @@ the expectation value. Consider the stochastic variables \( X_i \) and
$$
\begin{align}
\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle
-\label{_auto6}\\
+\label{_auto12}\\
&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle
-\label{_auto7}\\
+\label{_auto13}\\
&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle +
\langle \langle x_i\rangle\langle x_j\rangle\rangle
-\label{_auto8}\\
+\label{_auto14}\\
&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle +
\langle x_i\rangle\langle x_j\rangle
-\label{_auto9}\\
+\label{_auto15}\\
&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle
-\label{_auto10}
+\label{_auto16}
\end{align}
$$
@@ -2082,7 +2327,7 @@ $$
@@ -2114,7 +2359,7 @@ value of a set of measurements.
@@ -2142,7 +2387,7 @@ interested in finding the few lowest moments, like the mean
-
@@ -2168,7 +2413,7 @@ $$
@@ -2189,7 +2434,7 @@ and covariance \( \mathrm{cov}(X,Y) \).
@@ -2221,7 +2466,7 @@ true PDFs behind, which we usually do not have.
@@ -2243,7 +2488,7 @@ means.
@@ -2264,7 +2509,7 @@ And in particular we are interested in its variance \( \mathrm{var}(\overline X_
@@ -2289,7 +2534,7 @@ $$
@@ -2318,7 +2563,7 @@ estimate of the PDF of each of the \( X_i \), estimating all properties of
@@ -2345,7 +2590,7 @@ $$
@@ -2384,7 +2629,7 @@ measurements in the sample.
@@ -2419,7 +2664,7 @@ cannot overlook the always present correlations.
@@ -2448,7 +2693,7 @@ measurements. For uncorrelated measurements this second term is zero.
@@ -2470,7 +2715,7 @@ have to be stored throughout the experiment.
@@ -2503,7 +2748,7 @@ starting always at \( 1 \) for \( d=0 \).
@@ -2536,7 +2781,7 @@ $$
@@ -2559,42 +2804,187 @@ measurements is very large.
-
-A popular strategy is to choose a penalty parameter that yields a good
-but parsimonious model. Information criteria measure the balance
-between model fit and model complexity. One possibility is Aikaike's
-information criterion (AIC).
-The AIC measures model fit by the log-likelihood
-and model complexity is measured by the number of parameters used by
-the model. The number of model parameters in regular regression simply
-corresponds to the number of covariates in the model. Or, by the
-degrees of freedom consumed by the model, which is equivalent to the
-trace of the hat matrix. For ridge regression it thus seems natural to
-define model complexity analogously by the trace of the ridge hat
-matrix. This yields the AIC for the linear regression model with ridge
-estimates:
+Finally, we are going to discuss several statistical properties which can be obtained in terms of analytical expressions.
+The
+advantage of doing linear regression is that we actually end up with
+analytical expressions for several statistical quantities.
+Standard least squares and Ridge regression allow us to
+derive quantities like the variance and other expectation values in a
+rather straightforward way.
+
+It is assumed that \( \varepsilon_i
+\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are
+independent, i.e.:
$$
-\begin{align*}
-\mbox{AIC}(\lambda) & = 2 \, p - 2 \log(\hat{L})
-\\
-& = 2 \, \mbox{tr} [\mathbf{H}(\lambda)] - 2 \log\{L[\hat{\beta}(\lambda), \hat{\sigma}^2(\lambda)]\}
-\\
-& = 2 \, \sum_{j=1}^p \frac{d_{jj}^2}{d_{jj}^2 + \lambda}
-+ 2 n \, \log[\sqrt{2 \, \pi} \, \hat{\sigma}(\lambda)] + \frac{1}{\hat{\sigma}^2(\lambda)} \sum_{i=1}^n [y_i - \mathbf{X}_{i, \ast} \, \hat{\beta}(\lambda)]^2.
+\begin{align*}
+\mbox{Cov}(\varepsilon_{i_1},
+\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if}
+& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right.
+\end{align*}
+$$
+
+The randomness of \( \varepsilon_i \) implies that
+\( \mathbf{y}_i \) is also a random variable. In particular,
+\( \mathbf{y}_i \) is normally distributed, because \( \varepsilon_i \sim
+\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \boldsymbol{\beta} \) is a
+non-random scalar. To specify the parameters of the distribution of
+\( \mathbf{y}_i \) we need to calculate its first two moments.
+
+
+Recall that \( \boldsymbol{X} \) is a matrix of dimensionality \( n\times p \). The
+notation above \( \mathbf{X}_{i,\ast} \) means that we are looking at the
+row number \( i \) and perform a sum over all values \( p \).
+
+
+
+The assumption we have made here can be summarized as (and this is going to useful when we discuss the bias-variance trade off)
+that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \)
+which describes our data
+$$
+\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon}
+$$
+
+
+We approximate this function with our model from the solution of the linear regression equations, that is our
+function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we want to minimize \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), our MSE, with
+$$
+\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}.
+$$
+
+
+
+We can calculate the expectation value of \( \boldsymbol{y} \) for a given element \( i \)
+$$
+\begin{align*}
+\mathbb{E}(y_i) & =
+\mathbb{E}(\mathbf{X}_{i, \ast} \, \boldsymbol{\beta}) + \mathbb{E}(\varepsilon_i)
+\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta,
+\end{align*}
+$$
+
+while
+its variance is
+$$
+\begin{align*} \mbox{Var}(y_i) & = \mathbb{E} \{ [y_i
+- \mathbb{E}(y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( y_i^2 ) -
+[\mathbb{E}(y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \,
+\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 \\ &
+= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 \varepsilon_i
+\mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + \varepsilon_i^2 ] - ( \mathbf{X}_{i,
+\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2
+\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \boldsymbol{\beta} +
+\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2
+\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \,
+\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2.
\end{align*}
$$
-The value of \( \lambda \) which minimizes \( \mbox{AIC}(\lambda) \) corresponds to the `optimal' balance of model complexity and overfitting.
+Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with
+mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \) (not be confused with the singular values of the SVD).
+
+
+
+With the OLS expressions for the parameters \( \boldsymbol{\beta} \) we can evaluate the expectation value
+$$
+\mathbb{E}(\boldsymbol{\beta}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}.
+$$
+
+This means that the estimator of the regression parameters is unbiased.
+
+
+We can also calculate the variance
+
+
+The variance of \( \boldsymbol{\beta} \) is
+$$
+\begin{eqnarray*}
+\mbox{Var}(\boldsymbol{\beta}) & = & \mathbb{E} \{ [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})] [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})]^{T} \}
+\\
+& = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}]^{T} \}
+\\
+% & = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}]^{T} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+% \\
+% & = & \mathbb{E} \{ (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} \, \mathbf{Y}^{T} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+% \\
+& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \mathbb{E} \{ \mathbf{Y} \, \mathbf{Y}^{T} \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+\\
+& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+% \\
+% & = & (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1}
+% \\
+% & & + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \boldsymbol{\beta} \boldsymbol{\beta}^T
+\\
+& = & \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1},
+\end{eqnarray*}
+$$
+
+
+where we have used that \( \mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) =
+\mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} +
+\sigma^2 \, \mathbf{I}_{nn} \). From \( \mbox{Var}(\boldsymbol{\beta}) = \sigma^2
+\, (\mathbf{X}^{T} \mathbf{X})^{-1} \), one obtains an estimate of the
+variance of the estimate of the \( j \)-th regression coefficient:
+\( \hat{\sigma}^2 (\hat{\beta}_j ) = \hat{\sigma}^2 \sqrt{
+[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} } \). This may be used to
+construct a confidence interval for the estimates.
+
+
+In a similar way, we cna obtain analytical expressions for say the
+expectation values of the parameters \( \boldsymbol{\beta} \) and their variance
+when we employ Ridge regression, and thereby a confidence interval.
+
+
+It is rather straightforward to show that
+$$
+\mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\boldsymbol{\beta}^{\mathrm{OLS}}.
+$$
+
+We see clearly that
+\( \mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big] \not= \boldsymbol{\beta}^{\mathrm{OLS}} \) for any \( \lambda > 0 \). We say then that the ridge estimator is biased.
+
+
+We can also compute the variance as
+
+$$
+\mbox{Var}[\boldsymbol{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T},
+$$
+
+and it is easy to see that if the parameter \( \lambda \) goes to infinity then the variance of Ridge parameters \( \boldsymbol{\beta} \) goes to zero.
+
+
+With this, we can compute the difference
+
+$$
+\mbox{Var}[\boldsymbol{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\boldsymbol{\beta}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}.
+$$
+
+The difference is non-negative definite since each component of the
+matrix product is non-negative definite.
+This means the variance we obtain with the standard OLS will always for \( \lambda > 0 \) be larger than the variance of \( \boldsymbol{\beta} \) obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below.
-
Instead of choosing the penalty parameter to balance model fit with
@@ -2602,12 +2992,15 @@ model complexity, cross-validation requires it (i.e. the penalty
parameter) to yield a model with good prediction
performance. Commonly, this performance is evaluated on novel
data. Novel data need not be easy to come by and one has to make do
-with the data at hand. The setting of `original' and novel data is
+with the data at hand.
+
+
+The setting of original and novel data is
then mimicked by sample splitting: the data set is divided into two
-(groups of samples). One of these two data sets, called the training
-set, plays the role of `original' data on which the model is
+(groups of samples). One of these two data sets, called the
+training set, plays the role of original data on which the model is
built. The second of these data sets, called the test set, plays the
-role of the `novel' data and is used to evaluate the prediction
+role of the novel data and is used to evaluate the prediction
performance (often operationalized as the log-likelihood or the
prediction error or its square or the R2 score) of the model built on the training data set. This
procedure (model building and prediction evaluation on training and
@@ -2625,7 +3018,7 @@ some sense) is then selected.
The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks:
@@ -2637,7 +3030,7 @@ The validation set approach is conceptually simple and is easy to implement. But
-
When the repetitive splitting of the data set is done randomly,
@@ -2658,32 +3051,32 @@ cross-validation (LOOCV).
-
-Another approach in the LOOCV scheme is to the use the so-called Predicted Residual Error Sum of Squares (PRESS).
-
-
-We can define the optimal penalty parameter to minimize
-$$
-\begin{align*}
-\lambda_{\mbox{{\tiny opt}}} = \arg \min_{\lambda} \frac{1}{n} \sum_{i=1}^n [y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)]^2.
-\end{align*}
-$$
-
-
-The LOOCV prediction performance can be
-expressed analytically in terms of the known quantities derived from
-the design matrix and the parameters \( \beta \).
-
-
Two famous
@@ -2741,18 +3110,18 @@ need for bootstrapping.
The Jackknife works by making many replicas of the estimator \( \widehat{\theta} \).
-The jackknife is a resampling method, we explained that this happens by scrambling the data in some way. When using the jackknife, this is done by systematically leaving out one observation from the vector of observed values \( \hat{x} = (x_1,x_2,\cdots,X_n) \).
-Let \( \hat{x}_i \) denote the vector
+The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \( \boldsymbol{x} = (x_1,x_2,\cdots,X_n) \).
+Let \( \boldsymbol{x}_i \) denote the vector
$$
-\hat{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n),
+\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n),
$$
-which equals the vector \( \hat{x} \) with the exception that observation
+which equals the vector \( \boldsymbol{x} \) with the exception that observation
number \( i \) is left out. Using this notation, define
\( \widehat{\theta}_i \) to be the estimator
\( \widehat{\theta} \) computed using \( \vec{X}_i \).
@@ -2760,20 +3129,6 @@ number \( i \) is left out. Using this notation, define
-To get an estimate for the bias and
-standard error of \( \widehat{\theta} \), use the following
-estimators for each component of \( \widehat{\theta} \)
-
-$$
-\widehat{\mathrm{Bias}}(\widehat \theta,\theta) = (n-1)\left( - \widehat{\theta} + \frac{1}{n}\sum_{i=1}^{n} \widehat \theta_i \right) \qquad \text{and} \qquad \widehat{\sigma}^2_{\widehat{\theta} } = \frac{n-1}{n}\sum_{i=1}^{n}( \widehat{\theta}_i - \frac{1}{n}\sum_{j=1}^{n}\widehat \theta_j )^2.
-$$
-
-
-
@@ -2834,14 +3189,14 @@ advantages:
-Since \( \widehat{\theta} = \widehat{\theta}(\hat{X}) \) is a function of random variables,
+Since \( \widehat{\theta} = \widehat{\theta}(\boldsymbol{X}) \) is a function of random variables,
\( \widehat{\theta} \) itself must be a random variable. Thus it has
-a pdf, call this function \( p(\hat{t}) \). The aim of the bootstrap is to
-estimate \( p(\hat{t}) \) by the relative frequency of
+a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to
+estimate \( p(\boldsymbol{t}) \) by the relative frequency of
\( \widehat{\theta} \). You can think of this as using a histogram
-in the place of \( p(\hat{t}) \). If the relative frequency closely
+in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely
resembles \( p(\vec{t}) \), then using numerics, it is straight forward to
-estimate all the interesting parameters of \( p(\hat{t}) \) using point
+estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point
estimators.
@@ -2864,7 +3219,7 @@ been straight forward to do this by:
By repeated use of (1) and (2), many
estimates of \( \widehat{\theta} \) could have been obtained. The
idea is to use the relative frequency of \( \widehat{\theta}^* \)
-(think of a histogram) as an estimate of \( p(\hat{t}) \).
+(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \).
+The following code starts with a Gaussian distribution with mean value
+\( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data
+used in the bootstrap analysis. The bootstrap analysis returns a data
+set after a given number of bootstrap operations (as many as we have
+data points). This data set consists of estimated mean values for each
+bootstrap operation. The histogram generated by the bootstrap method
+shows that the distribution for these mean values is also a Gaussian,
+centered around the mean value \( \mu=100 \) but with standard deviation
+\( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in
+this case the same as the number of original data points). The value
+of the standard deviation is what we expect from the central limit
+theorem.
+
@@ -2922,30 +3299,29 @@ The following code starts with a Gaussian distribution with mean value \( \mu =1
def stat(data):
return mean(data)
-# Bootstrap algorithm
+# Bootstrap algorithm
def bootstrap(data, statistic, R):
t = zeros(R); n = len(data); inds = arange(n); t0 = time()
-
- # non-parametric bootstrap
+ # non-parametric bootstrap
for i in range(R):
t[i] = statistic(data[randint(0,n,n)])
- # analysis
+ # analysis
print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
print("original bias std. error")
- print("%8g %8g %14g %15g" % (statistic(data), std(data),\
- mean(t), \
- std(t)))
+ print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
return t
mu, sigma = 100, 15
datapoints = 10000
x = mu + sigma*random.randn(datapoints)
-# bootstrap returns the data sample t = bootstrap(x, stat, datapoints)
-# the histogram of the bootstrapped data n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
+# bootstrap returns the data sample
+t = bootstrap(x, stat, datapoints)
+# the histogram of the bootstrapped data
+n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
-# add a 'best fit' line
+# add a 'best fit' line
y = mlab.normpdf( binsboot, mean(t), std(t))
lt = plt.plot(binsboot, y, 'r--', linewidth=1)
plt.xlabel('Smarts')
@@ -2958,529 +3334,300 @@ plt.show()
-The blocking method was made popular by Flyvbjerg and Pedersen (1989)
-and has become one of the standard ways to estimate
-\( V(\widehat{\theta}) \) for exactly one \( \widehat{\theta} \), namely
-\( \widehat{\theta} = \overline{X} \).
-
-
-Assume \( n = 2^d \) for some integer \( d>1 \) and \( X_1,X_2,\cdots, X_n \) is a stationary time series to begin with.
-Moreover, assume that the time series is asymptotically uncorrelated. We switch to vector notation by arranging \( X_1,X_2,\cdots,X_n \) in an \( n \)-tuple. Define:
-$$
-\begin{align*}
-\hat{X} = (X_1,X_2,\cdots,X_n).
-\end{align*}
-$$
-
-
-The strength of the blocking method is when the number of
-observations, \( n \) is large. For large \( n \), the complexity of dependent
-bootstrapping scales poorly, but the blocking method does not,
-moreover, it becomes more accurate the larger \( n \) is.
-
-
-
-The quantity \( \vec{X}_k \) is
-subject to \( k \) blocking transformations. We now have \( d \) vectors
-\( \vec{X}_0, \vec{X}_1,\cdots,\vec X_{d-1} \) containing the subsequent
-averages of observations. It turns out that if the components of
-\( \vec{X} \) is a stationary time series, then the components of
-\( \vec{X}_i \) is a stationary time series for all \( 0 \leq i \leq d-1 \)
-
-
-We can then compute the autocovariance, the variance, sample mean, and
-number of observations for each \( i \).
-Let \( \gamma_i, \sigma_i^2,
-\overline{X}_i \) denote the autocovariance, variance and average of the
-elements of \( \vec{X}_i \) and let \( n_i \) be the number of elements of
-\( \vec{X}_i \). It follows by induction that \( n_i = n/2^i \).
-
-
-
-Using the
-definition of the blocking transformation and the distributive
-property of the covariance, it is clear that since \( h =|i-j| \)
-we can define
-$$
-\begin{align}
-\gamma_{k+1}(h) &= cov\left( ({X}_{k+1})_{i}, ({X}_{k+1})_{j} \right) \nonumber \\
-&= \frac{1}{4}cov\left( ({X}_{k})_{2i-1} + ({X}_{k})_{2i}, ({X}_{k})_{2j-1} + ({X}_{k})_{2j} \right) \nonumber \\
-&= \frac{1}{2}\gamma_{k}(2h) + \frac{1}{2}\gamma_k(2h+1) \hspace{0.1cm} \mathrm{h = 0}
-\label{_auto12}\\
-&=\frac{1}{4}\gamma_k(2h-1) + \frac{1}{2}\gamma_k(2h) + \frac{1}{4}\gamma_k(2h+1) \quad \mathrm{else}
-\label{_auto13}
-\end{align}
-$$
-
-
-The quantity \( \hat{X} \) is asymptotic uncorrelated by assumption, \( \hat{X}_k \) is also asymptotic uncorrelated. Let's turn our attention to the variance of the sample mean \( V(\overline{X}) \).
-
-
-
-
-We can then wrap up
-$$
-\begin{align}
-n_{j+1} \overline{X}_{j+1} &= \sum_{i=1}^{n_{j+1}} (\hat{X}_{j+1})_i = \frac{1}{2}\sum_{i=1}^{n_{j}/2} (\hat{X}_{j})_{2i-1} + (\hat{X}_{j})_{2i} \nonumber \\
-&= \frac{1}{2}\left[ (\hat{X}_j)_1 + (\hat{X}_j)_2 + \cdots + (\hat{X}_j)_{n_j} \right] = \underbrace{\frac{n_j}{2}}_{=n_{j+1}} \overline{X}_j = n_{j+1}\overline{X}_j.
-\label{_auto16}
-\end{align}
-$$
-
-By repeated use of this equation we get \( V(\overline{X}_i) = V(\overline{X}_0) = V(\overline{X}) \) for all \( 0 \leq i \leq d-1 \). This has the consequence that
-$$
-\begin{align}
-V(\overline{X}) = \frac{\sigma_k^2}{n_k} + e_k \qquad \text{for all} \qquad 0 \leq k \leq d-1. \label{eq:convergence}
-\end{align}
-$$
-
-
-Fyvbjerg and Petersen demonstrated that the sequence
-\( \{e_k\}_{k=0}^{d-1} \) is decreasing, and conjecture that the term
-\( e_k \) can be made as small as we would like by making \( k \) (and hence
-\( d \)) sufficiently large. The sequence is decreasing (Master of Science thesis by Marius Jonsson, UiO 2018).
-It means we can apply blocking transformations until
-\( e_k \) is sufficiently small, and then estimate \( V(\overline{X}) \) by
-\( \widehat{\sigma}^2_k/n_k \).
-
-
-
-
-We begin with an unknown function \( y=f(x) \) and fix a \emph{hypothesis set}
- \( \mathcal{H} \) consisting of all functions we are willing to consider,
- defined also on the domain of \( f \). This set may be uncountably
- infinite (e.g. if there are real-valued parameters to fit).
-The
- choice of which functions to include in \( \mathcal{H} \) usually depends
- on our intuition about the problem of interest. The function \( f(x) \)
- produces a set of pairs \( (x_i,y_i) \), \( i=1\dots N \), which serve as the
- observable data. Our goal is to select a function from the hypothesis
- set \( h\in\mathcal{H} \) which approximates \( f(x) \) as best as possible,
- namely, we would like to find \( h\in\mathcal{H} \) such that \( h\approx
- f \) in some strict mathematical sense which we specify below. If this
- is possible, we say that we \emph{learned} \( f(x) \). But if the
- function \( f(x) \) can, in principle, take any value on
- \emph{unobserved} inputs, how is it possible to learn in any
- meaningful sense?
+We will discuss the bias-variance tradeoff in the context of
+continuous predictions such as regression. However, many of the
+intuitions and ideas discussed here also carry over to classification
+tasks. Consider a dataset \( \mathcal{L} \) consisting of the data
+\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \).
+
+Let us assume that the true data is generated from a noisy model
+
+$$
+\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon}
+$$
+
+
+where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \).
+
+
+In our derivation of the ordinary least squares method we defined then
+an approximation to the function \( f \) in terms of the parameters
+\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model,
+that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \).
+
+
+Thereafter we found the parameters \( \boldsymbol{\beta} \) by optimizing the means squared error via the so-called cost function
+$$
+C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right].
+$$
+
+
+We can rewrite this as
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2.
+$$
+
+
+The three terms represent the square of the bias of the learning
+method, which can be thought of as the error caused by the simplifying
+assumptions built into the method. The second term represents the
+variance of the chosen model and finally the last terms is variance of
+the error \( \boldsymbol{\epsilon} \).
+
+
+To derive this equation, we need to recall that the variance of \( \boldsymbol{y} \) and \( \boldsymbol{\epsilon} \) are both equal to \( \sigma^2 \). The mean value of \( \boldsymbol{\epsilon} \) is by definition equal to zero. Furthermore, the function \( f \) is not a stochastics variable, idem for \( \boldsymbol{\tilde{y}} \).
+We use a more compact notation in terms of the expectation value
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right],
+$$
+
+and adding and subtracting \( \mathbb{E}\left[\boldsymbol{\tilde{y}}\right] \) we get
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right],
+$$
+
+which, using the abovementioned expectation values can be rewritten as
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2,
+$$
+
+that is the rewriting in terms of the so-called bias, the variance of the model \( \boldsymbol{\tilde{y}} \) and the variance of \( \boldsymbol{\epsilon} \).
+
+
+
+
+
+
+
+
+
+
-
-We will discuss the bias-variance tradeoff in the context of continuous predictions such as regression. However, many of the intuitions and ideas discussed here also carry over to classification tasks. Consider a dataset \( \mathcal{L} \) consisting of the data \( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=1\ldots N\} \). Let us assume that the true data is generated from a noisy model
-$$
-y=f(\boldsymbol{x}) + \epsilon
-$$
-
-where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma_\epsilon \).
-
-
-
-We have a statistical procedure (e.g. least-squares regression) for
-forming a predictor \( \hat{g}_{\mathcal{L}}(\boldsymbol{x}) \) that gives the
-prediction of our model for a new data point \( \boldsymbol{x} \). This estimator
-is chosen by minimizing a cost function which we take to be the
-squared error
-
-$$
- \mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) = \sum_i (y_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2.
-$$
-
-
-
-We are interested in the generalization error on all data drawn from
-the true model, not just the error on the particular training dataset
-\( \mathcal{L} \) that we have in hand. This is just the expectation of
-the cost function over many different data sets
-\( \{\mathcal{L}_j\} \). Denote this expectation value by
-\( E_{\mathcal{L}} \). In other words, we can view \( \hat{g}_{\mathcal{L}} \)
-as a stochastic functional that depends on the dataset \( \mathcal{L} \)
-and we can think of \( E_{\mathcal{L}} \) as the expected value of the
-functional if we drew an infinite number of datasets \( \{\mathcal{L}_1,
-\mathcal{L}_2, \ldots \} \).
-
-
-
-We would also like to average over different instances of the
-"noise" \( \epsilon \) and we denote the expectation value over the
-noise by \( E_\epsilon \). Thus, we can decompose the expected
-generalization error as
-
-$$
-\begin{align}
-E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ]&= E_\mathcal{L,\epsilon}\left[ \sum_i ({y}_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2 \right] \nonumber \\
- &= E_\mathcal{L, \epsilon}\left[ \sum_{i}({y}_i -f(\boldsymbol{x}_i) +f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2\right] \nonumber \\
- &= \sum_i E_\epsilon[ ({y}_i -f(\boldsymbol{x}_i))^2 ]+ E_\mathcal{L, \epsilon}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] + 2E_\epsilon[{y}_i -f(\boldsymbol{x}_i)]E_\mathcal{L}[f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i)] \nonumber \\
- &=\sum_i \sigma_\epsilon^2 + E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2],
-\label{_auto17}
-\end{align}
-$$
-
-
-where in the last line we used the fact that our noise has zero mean
-and variance \( \sigma_\epsilon^2 \) and the sum over \( i \) applies to all
-terms.
-
-
-
-It is also helpful to further decompose the second term as
-follows:
-
-$$
-\begin{align}
-E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] &=E_\mathcal{L}[(f(\mathbf{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]+ E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] \nonumber \\
-&=E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] + E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] \nonumber \\
-&+2E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])] \nonumber \\
-&=(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2+E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2].
-\label{_auto18}
-\end{align}
-$$
-
-
-
-The first term is called the bias
-$$
-Bias^2= \sum_i (f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2
-$$
-
-and measures the deviation of the expectation value of our estimator (i.e. the asymptotic value of our estimator in the infinite data limit) from the true value.
-
-
-
-and measures how much our estimator fluctuates due to finite-sample effects. Combining these expressions, we see that the expected out-of-sample error of our model can be decomposed as
-$$
-E_\mathrm{out}=E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ] = Bias^2 + Var + Noise.
-$$
+
The bias-variance tradeoff summarizes the fundamental tension in
machine learning, particularly supervised learning, between the
complexity of a model and the amount of training data needed to train
it. Since data is often limited, in practice it is often useful to
-use a less-complex model with higher bias – a model whose asymptotic
-performance is worse than another model – because it is easier to
+use a less-complex model with higher bias, that is a model whose asymptotic
+performance is worse than another model because it is easier to
train and less sensitive to sampling noise arising from having a
finite-sized training dataset (smaller variance).
-
-
-
-
The above equations tell us that in
order to minimize the expected test error, we need to select a
@@ -3503,15 +3650,99 @@ flexible statistical methods have higher variance.
+
+
+
+
-The one-dimensional Ising model with nearest neighbor interaction, no external field and a constant coupling constant \( J \) is given by
+Let us bring back the Ising model again, but now with an additional
+focus on Ridge and Lasso regression as well. We repeat some of the
+basic parts of the Ising model and the setup of the training and test
+data. The one-dimensional Ising model with nearest neighbor
+interaction, no external field and a constant coupling constant \( J \) is
+given by
$$
\begin{align}
H = -J \sum_{k}^L s_k s_{k + 1},
-\label{_auto19}
+\label{_auto17}
\end{align}
$$
@@ -3545,25 +3776,13 @@ energies = np.<
for i in range(n):
energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
-Here we use linear (ordinary least squares), ridge and LASSO
-regression to predict the energy in the nearest neighbor
-one-dimensional Ising model on a ring, i.e., the endpoints wrap
-around. We will use the linear regression models to fit a value for
-the coupling constant to achieve this.
-
-
-
A more general form for the one-dimensional Ising model is
$$
\begin{align}
H = - \sum_j^L \sum_k^L s_j s_k J_{jk}.
-\label{_auto20}
+\label{_auto18}
\end{align}
$$
@@ -3574,7 +3793,7 @@ a matrix-product on the form
$$
\begin{align}
H = X J,
-\label{_auto21}
+\label{_auto19}
\end{align}
$$
@@ -3584,11 +3803,12 @@ elements \( -J_{jk} \). This form of writing the energy fits perfectly
with the form utilized in linear regression, viz.
$$
\begin{align}
- y = X\omega + \epsilon,
-\label{_auto22}
+ \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}.
+\label{_auto20}
\end{align}
$$
+We organize the data as we did above
@@ -3609,149 +3829,7 @@ X_test_own = np
)
-
-The problem at hand is to try to fit the equation
-$$
-\begin{align}
- y = f(x) + \epsilon,
-\label{_auto23}
-\end{align}
-$$
-
-
-where \( f(x) \) is some unknown function of the data \( x \) and \( \epsilon \)
-is normally distributed with mean zero noise with standard deviation
-\( \sigma_{\epsilon} \). Our job is to try to find a predictor which
-estimates the function \( f(x) \). In linear regression we assume that we
-can formulate the problem as
-
-$$
-\begin{align}
- y = X\omega + \epsilon,
-\label{_auto24}
-\end{align}
-$$
-
-
-where \( X \) and \( \omega \) are now matrices. Our job at hand is now to
-find a cost function \( C \), which we wish to minimize in order to find
-the best estimate of \( \omega \).
-
-
-
-In the ordinary least squares method we choose the cost function
-$$
-\begin{align}
- C(X, \omega) = ||X\omega - y||^2
- = (X\omega - y)^T(X\omega - y)
-\label{_auto25}
-\end{align}
-$$
-
-We then find the extremal point of \( C \) by taking the derivative with respect to \( \omega \) and setting it to zero, i.e.,
-
-$$
-\begin{align}
- \dfrac{\mathrm{d}C}{\mathrm{d}\omega}
- = 0.
-\label{_auto26}
-\end{align}
-$$
-
-This yields the expression for \( \omega \) to be
-$$
-\begin{align}
- \omega = \frac{X^T y}{X^T X},
-\label{_auto27}
-\end{align}
-$$
-
-
-which immediately imposes some requirements on \( X \) as there must exist
-an inverse of \( X^T X \). If the expression we are modelling contains an
-intercept, i.e., a constant expression we must make sure that the
-first column of \( X \) consists of \( 1 \).
-
-
-
-
-
-
-Using singular value decomposition we have that \( X = U\Sigma V^T \),
-where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for
-\( \omega \) to
-$$
-\begin{align}
- \omega = V\Sigma^{+} U^T y.
-\label{_auto30}
-\end{align}
-$$
-
-
-Note that solving this equation by actually doing the pseudoinverse
-(which is what we will do) is not a good idea as this operation scales
-as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a
-general matrix. Instead, doing \( QR \)-factorization and solving the
-linear system as an equation would reduce this down to
-\( \mathcal{O}(n^2) \) operations.
-
-
-
-
-
-Before passing in the data to the function we append a column with ones to the training data.
-
-
-
-
-
-
-Next we fit a
@@ -3759,29 +3837,18 @@ Next we fit a
-Extracting the \( J \)-matrix from both our own method and the Scikit-learn model where we make sure to remove the intercept.
-
+When extracting the \( J \)-matrix we make sure to remove the intercept
-
-A way of looking at the coefficients in \( J \) is to plot the matrices as images.
-
+And then we plot the results
-We can see that our model for the least squares method performes close
-to the benchmark from Scikit-learn. It is interesting to note that OLS
-considers both \( J_{j, j + 1} = -0.5 \) and \( J_{j, j - 1} = -0.5 \) as
-valid matrix elements for \( J \).
+The results perfectly with our previous discussion where we used our own code.
Having explored the ordinary least squares we move on to ridge
regression. In ridge regression we include a regularizer. This
involves a new cost function which leads to a new estimate for the
-weights \( \omega \). This results in a penalized regression problem. The
+weights \( \boldsymbol{\beta} \). This results in a penalized regression problem. The
cost function is given by
$$
\begin{align}
- C(X, \omega; \lambda) = ||X\omega - y||^2 + \lambda ||\omega||^2
- = (X\omega - y)^T(X\omega - y) + \lambda \omega^T\omega.
-\label{_auto31}
+ C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \boldsymbol{\beta}^T\boldsymbol{\beta}.
+\label{_auto21}
\end{align}
$$
-Finding the extremum of this function yields the weights
-
-$$
-\begin{align}
- \omega(\lambda) = \frac{X^Ty}{X^TX + \lambda} \to \frac{\omega_{\text{LS}}}{1 + \lambda},
-\label{_auto32}
-\end{align}
-$$
-
-
-where \( \omega_{\text{LS}} \) is the weights from ordinary least
-squares. The last assumption assumes that \( X \) is orthogonal, which it
-is not. We will therefore resort to solving the equation as it stands
-on the left hand side.
-
-
In the Least Absolute Shrinkage and Selection Operator (LASSO)-method we get a third cost function.
+
$$
\begin{align}
- C(X, \omega; \lambda) =
- ||X\omega - y||^2 + \lambda ||\omega||
- = (X\omega - y)^T(X\omega - y) + \lambda \sqrt{\omega^T\omega}.
-\label{_auto33}
+ C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \sqrt{\boldsymbol{\beta}^T\boldsymbol{\beta}}.
+\label{_auto22}
\end{align}
$$
-Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-learn.
+
+Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-Learn.
@@ -3902,41 +3936,7 @@ constant as opposed to ridge and OLS. We get a sparse solution with
-In order to judge which model performs best at varying values of \( \lambda \) (for ridge and LASSO) we compute \( R^2 \) which is given by
-
-$$
-\begin{align}
- R^2 = 1 - \frac{(y - \hat{y})^2}{(y - \bar{y})^2},
-\label{_auto34}
-\end{align}
-$$
-
-where \( y \) is a vector with the true values of the energy, \( \hat{y} \) is the predicted values of \( y \) from the models and \( \bar{y} \) is the mean of \( \hat{y} \).
-
-
-
-
-
-This is the same metric used by Scikit-learn for their regression models when scoring.
-
-
-
-
-
We see how the different models perform for a different set of values for \( \lambda \).
@@ -3947,17 +3947,13 @@ We see how the different models perform for a different set of values for \( \la
-We can see that LASSO quite fast reaches a good solution for low
+We see that LASSO reaches a good solution for low
values of \( \lambda \), but will "wither" when we increase \( \lambda \) too
much. Ridge is more stable over a larger range of values for
\( \lambda \), but eventually also fades away.
@@ -4018,7 +3990,7 @@ much. Ridge is more stable over a larger range of values for
To determine which value of \( \lambda \) is best we plot the accuracy of
@@ -4034,8 +4006,6 @@ testing set that is close to the accuracy of the training set.
From the above figure we can see that LASSO with \( \lambda = 10^{-2} \)
-achieve a very good accuracy on the test set. This by far surpases the
+achieves a very good accuracy on the test set. This by far surpasses the
other models for all values of \( \lambda \).
+
+
+We will generate our own dataset for a function \( y(x) \) where \( x \in [0,1] \) and defined by random numbers computed with the uniform distribution. The function \( y \) is a quadratic polynomial in \( x \) with added stochastic noise according to the normal distribution \( \cal {N}(0,1) \).
+The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points).
+
+
+
+
+You can use the functionality included in scikit-learn. If you feel
+for it, you can use your own program and define functions which
+compute the above two functions. Discuss the meaning of these
+results. Try also to vary the coefficient in front of the added
+stochastic noise term and discuss the quality of the fits.
+
+
+Show that the variance of the parameters \( \beta \) in the linear regression method (chapter 3, equation (3.8) of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer) is given as
+
+$$
+\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2,
+$$
+
+with
+$$
+\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2,
+$$
+
+where we have assumed that we fit a function of degree \( p-1 \) (for example a polynomial in \( x \)).
+
+
+This exercise is a continuation of exercise 1. We will
+use the same function to generate our data set, still staying with a
+simple function \( y(x) \) which we want to fit using linear regression,
+but now extending the analysis to include the Ridge and the Lasso
+regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods.
+
+
+We will thus again generate our own dataset for a function \( y(x) \) where
+\( x \in [0,1] \) and defined by random numbers computed with the uniform
+distribution. The function \( y \) is a quadratic polynomial in \( x \) with
+added stochastic noise according to the normal distribution \( \cal{N}(0,1) \).
+
+
+The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points).
+
+
+
+
+We will study how
+to fit polynomials to a specific two-dimensional function called
+Franke's
+function. This
+is a function which has been widely used when testing various interpolation and fitting
+algorithms. Furthermore, after having established the model and the
+method, we will employ resamling techniques such as the cross-validation and/or
+the bootstrap methods, in order to perform a proper assessment of our models.
+
+
+The Franke function, which is a weighted sum of four exponentials reads as follows
+$$
+\begin{align*}
+f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\
+&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }.
+\end{align*}
+$$
+
+
+The function will be defined for \( x,y\in [0,1] \). Our first step will
+be to perform an OLS regression analysis of this function, trying out
+a polynomial fit with an \( x \) and \( y \) dependence of the form \( [x, y,
+x^2, y^2, xy, \dots] \). We will also include cross-validation and
+bootstrap as resampling techniques. As in homeworks 1 and 2, we
+can use a uniform distribution to set up the arrays of values for \( x \)
+and \( y \), or as in the example below just a fix values for \( x \) and \( y \) with a given step size.
+In this case we will have two predictors and need to fit a
+function (for example a polynomial) of \( x \) and \( y \). Thereafter we will
+repeat much of the same procedure using the the Ridge and
+Lasso regression methods, introducing thus a dependence on the bias
+(penalty) \( \lambda \).
+
+
+The Python fucntion for the Franke function is included here (it performs also a three-dimensional plot of it)
+
+
+
+
+We will thus again generate our own dataset for a function \( \mathrm{FrankeFunction}(x,y) \) where
+\( x,y \in [0,1] \) could be defined by random numbers computed with the uniform
+distribution. The function \( f(x,y) \) is the Franke function. You should explore also the addition
+an added stochastic noise to this function using the normal distribution \( \cal{N}(0,1) \).
+
+
+Write your own code (using either a matrix inversion or a singular value decomposition from e.g., numpy ) or use your code from exercises 1 and 3
+and perform a standard least square regression analysis using polynomials in \( x \) and \( y \) up to fifth order. Find the confidence intervals of the parameters \( \beta \) by computing their variances, evaluate the Mean Squared error (MSE)
+$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
+\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
+$$
+
+and the \( R^2 \) score function.
+If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as
+$$
+R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
+$$
+
+where we have defined the mean value of \( \hat{y} \) as
+$$
+\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
+$$
+
+
+Perform a resampling of the data where you split the data in training data and test data. Implement the \( k \)-fold cross-validation algorithm and/or the bootstrap algorithm
+and evaluate again the MSE and the \( R^2 \) functions resulting from the test data. Evaluate also the bias and variance of the final models.
+
+
+Write then your own code for the Ridge method, either using matrix
+inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the
+previous exercise (for the same polynomials and include resampling
+techniques) but now for different values of \( \lambda \). Compare and
+analyze your results with those obtained with standard OLS. Study the
+dependence on \( \lambda \) while also varying eventually the strength of
+the noise in your expression for \( \mathrm{FrankeFunction}(x,y) \).
+
+
+Then perform the same studies but now with Lasso regression. Use the functionalities of
+scikit-learn. Give a critical discussion of the three methods and a
+judgement of which model fits the data best.
+
"+text+" "+e+"Regression analysis, overarching aims
+
+
+Regression analysis, overarching aims II
+Regression analysis, overarching aims II
General linear models
+Examples
+$$
+BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1},
+$$
+
+
+we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms.
+This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a
+\( p\times n \) matrix \( \boldsymbol{X} \).
+
+General linear models
+
$$
-y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_i x_i^j+\epsilon_i,
+y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i,
$$
@@ -232,7 +288,7 @@ where \( \epsilon_i \) is the error in our approximation.
Rewriting the fitting procedure as a linear algebra problem
+Rewriting the fitting procedure as a linear algebra problem
@@ -253,35 +309,35 @@ $$
Rewriting the fitting procedure as a linear algebra problem, follows
+Rewriting the fitting procedure as a linear algebra problem, more details
$$
-\hat{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T,
+\boldsymbol{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T,
$$
and
$$
-\hat{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T,
+\boldsymbol{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T,
$$
and
$$
-\hat{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T,
+\boldsymbol{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T,
$$
-and the matrix
+and the design matrix
$$
-\hat{X}=
+\boldsymbol{X}=
\begin{bmatrix}
1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\
1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\
@@ -295,20 +351,26 @@ $$
we can rewrite our equations as
$$
-\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}.
+\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}.
$$
+
+The above design matrix is called a Vandermonde matrix.
Generalizing the fitting procedure as a linear algebra problem
+Generalizing the fitting procedure as a linear algebra problem
$$
\begin{align*}
@@ -318,23 +380,26 @@ y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilo
\dots & \dots \\
y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\
\dots & \dots \\
-y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\
+y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\
\end{align*}
$$
+
+Generalizing the fitting procedure as a linear algebra problem
+Generalizing the fitting procedure as a linear algebra problem
$$
-\hat{X}=
+\boldsymbol{X}=
\begin{bmatrix}
x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\
x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\
@@ -348,21 +413,21 @@ $$
and without loss of generality we rewrite again our equations as
$$
-\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}.
+\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}.
$$
-The left-hand side of this equation forms know. Our error vector \( \hat{\epsilon} \) and the parameter vector \( \hat{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values?
+The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values?
Optimizing our parameters
+Optimizing our parameters
$$
\begin{align*}
@@ -372,83 +437,214 @@ y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilo
\dots & \dots \\
y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\
\dots & \dots \\
-y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\
+y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\
\end{align*}
$$
+
+Optimizing our parameters, more details
+Our model for the nuclear binding energies
+
+# Common imports
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from IPython.display import display
+import os
+
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
+
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
+
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
+
+infile = open(data_path("MassEval2016.dat"),'r')
+
+
+# Read the experimental data with Pandas
+Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
+ names=('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)
+
+# 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.
+Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')
+Masses = Masses.dropna()
+# Convert from keV to MeV.
+Masses['Ebinding'] /= 1000
+
+# Group the DataFrame by nucleon number, A.
+Masses = Masses.groupby('A')
+# Find the rows of the grouped DataFrame with the maximum binding energy.
+Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
+A = Masses['A']
+Z = Masses['Z']
+N = Masses['N']
+Element = Masses['Element']
+Energies = Masses['Ebinding']
+
+# Now we set up the design matrix X
+X = np.zeros((len(A),5))
+X[:,0] = 1
+X[:,1] = A
+X[:,2] = A**(2.0/3.0)
+X[:,3] = A**(-1.0/3.0)
+X[:,4] = A**(-1.0)
+# Then nice printout using pandas
+DesignMatrix = pd.DataFrame(X)
+DesignMatrix.index = A
+DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
+display(DesignMatrix)
+
+$$
+\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta},
+$$
+
+
+throughout these lectures.
+Optimizing our parameters, more details
$$
-\hat{\tilde{y}}= \hat{X}\hat{\beta},
+\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta},
$$
-and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parametrized values \( \tilde{y}_i \), namely
+and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely
$$
-Q(\hat{\beta})=\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\left(\hat{y}-\hat{\tilde{y}}\right)^T\left(\hat{y}-\hat{\tilde{y}}\right),
+C(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\},
$$
-or using the matrix \( \hat{X} \) as
+or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as
$$
-Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right).
+C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)\right\}.
$$
+
+This function is one possible way to define the so-called cost function.
+
+
+$$
+C(\boldsymbol{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2,
+$$
+
+
+since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out.
Interpretations and optimizing our parameters
+Interpretations and optimizing our parameters
$$
-Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right),
+C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\},
$$
-can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value of for example a numerical experiment. When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value
+can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value.
+When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value (see exercises)
$$
y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i,
$$
-where \( \langle y_i \rangle \) is the mean value. Keep in mind also that till now we have treated \( y_i \) as the exact value. Normally, the response (dependent or outcome) variable \( y_i \) 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.
+
$$
-\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0,
+{\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\}.
+$$
+
+
+In practical terms it means we will require
+
+$$
+\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0,
$$
which results in
$$
-\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0,
+\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0,
$$
or in a matrix-vector form as
$$
-\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right).
+\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right).
$$
@@ -458,63 +654,194 @@ $$
Interpretations and optimizing our parameters
+Interpretations and optimizing our parameters
$$
-\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right),
+\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right),
$$
as
$$
-\hat{X}^T\hat{y} = \hat{X}^T\hat{X}\hat{\beta},
+\boldsymbol{X}^T\boldsymbol{y} = \boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta},
$$
-and if the matrix \( \hat{X}^T\hat{X} \) is invertible we have the solution
+and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution
$$
-\hat{\beta} =\left(\hat{X}^T\hat{X}\right)^{-1}\hat{X}^T\hat{y}.
+\boldsymbol{\beta} =\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
$$
+Interpretations and optimizing our parameters
+Interpretations and optimizing our parameters
$$
-\hat{\epsilon} = \hat{y}-\hat{\tilde{y}} = \hat{y}-\hat{X}\hat{\beta},
+\boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta},
$$
and with
$$
-\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0,
+\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0,
$$
we have
$$
-\hat{X}^T\hat{\epsilon}=\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0,
+\boldsymbol{X}^T\boldsymbol{\epsilon}=\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0,
$$
-meaning that the solution for \( \hat{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.
+meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.
+
+
+Own code for Ordinary Least Squares
+
+# 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
+
fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
+ytildenp = np.dot(fit,X.T)
+
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.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',
+ label='Fit')
+ax.legend()
+save_fig("Masses2016OLS")
+plt.show()
+
Adding error analysis and training set up
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
+
print(R2(Energies,ytilde))
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+print(MSE(Energies,ytilde))
+
def RelativeError(y_data,y_model):
+ return abs((y_data-y_model)/y_data)
+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
+The \( \chi^2 \) function
$$
-\chi^2(\hat{\beta})=\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\left(\hat{y}-\hat{\tilde{y}}\right)^T\frac{1}{\hat{\Sigma^2}}\left(\hat{y}-\hat{\tilde{y}}\right),
-$$
-
-
-where the matrix \( \hat{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements.
-
-
-The \( \chi^2 \) function
-
-$$
-\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \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,
+\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(\hat{\beta})}{\partial \beta_j} = -2\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,
+\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(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right).
+\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 \( \hat{A} =\hat{X}/\hat{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \hat{b} \) with elements \( b_i = y_i/\sigma_i \).
+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
+The \( \chi^2 \) function
$$
-\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right),
+\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right),
$$
as
$$
-\hat{A}^T\hat{b} = \hat{A}^T\hat{A}\hat{\beta},
+\boldsymbol{A}^T\boldsymbol{b} = \boldsymbol{A}^T\boldsymbol{A}\boldsymbol{\beta},
$$
-and if the matrix \( \hat{A}^T\hat{A} \) is invertible we have the solution
+and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution
$$
-\hat{\beta} =\left(\hat{A}^T\hat{A}\right)^{-1}\hat{A}^T\hat{b}.
+\boldsymbol{\beta} =\left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}\boldsymbol{A}^T\boldsymbol{b}.
$$
The \( \chi^2 \) function
+The \( \chi^2 \) function
$$
-\hat{H} = \left(\hat{A}^T\hat{A}\right)^{-1},
+\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 \( \hat{H} \) are \( h_{ij} \))
+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}
@@ -641,7 +945,7 @@ $$
The \( \chi^2 \) function
+The \( \chi^2 \) function
$$
-\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0,
+\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(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0.
+\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
+The \( \chi^2 \) function
$$
@@ -706,7 +1010,9 @@ $$
$$
+
$$
\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2},
@@ -720,574 +1026,528 @@ $$
Simple regression model
-We are now ready to write our first program which aims at solving the above linear regression equations. We start with data we have produced ourselves, in this case normally distributed random numbers along the \( x \)-axis. These numbers define then the value of a function \( y(x)=4+3x+N(0,1) \). Thereafter we order the \( x \) values and employ our linear regression algorithm to set up the best fit. Here we find it useful to use the numpy function \( c\_ \) arrays where arrays are stacked along their last axis after being upgraded to at least two dimensions with ones post-pended to the shape. The following examples help in understanding what happens
+Fitting an Equation of State for Dense Nuclear Matter
+
+The code
+
import numpy as np
-print(np.c_[np.array([1,2,3]), np.array([4,5,6])])
-print(np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])])
-
# Importing various packages
-from random import random, seed
+
# Common imports
+import os
import numpy as np
+import pandas as pd
import matplotlib.pyplot as plt
-
-x = 2*np.random.rand(100,1)
-y = 4+3*x+np.random.randn(100,1)
-
-xb = np.c_[np.ones((100,1)), x]
-beta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
-xnew = np.array([[0],[2]])
-xbnew = np.c_[np.ones((2,1)), xnew]
-ypredict = xbnew.dot(beta)
-
-plt.plot(xnew, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0,2.0,0, 15.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Linear Regression')
-plt.show()
-
Simple regression model, now using scikit-learn
-
-# Importing various packages
-from random import random, seed
-import numpy as np
import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression
+import sklearn.linear_model as skl
+from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
-x = 2*np.random.rand(100,1)
-y = 4+3*x+np.random.randn(100,1)
-linreg = LinearRegression()
-linreg.fit(x,y)
-xnew = np.array([[0],[2]])
-ypredict = linreg.predict(xnew)
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
-plt.plot(xnew, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0,2.0,0, 15.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Random numbers ')
-plt.show()
-
Simple linear regression model using scikit-learn
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
-
-$$
-y = 2x+N(0,1),
-$$
-
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
-# Importing various packages
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression
-
-x = np.random.rand(100,1)
-y = 2*x+np.random.randn(100,1)
-linreg = LinearRegression()
-linreg.fit(x,y)
-xnew = np.array([[0],[1]])
-ypredict = linreg.predict(xnew)
-
-plt.plot(xnew, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0,1.0,0, 5.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Simple Linear Regression')
-plt.show()
-
Simple linear regression model
-
-
-$$
-y = 10x+0.01 \times N(0,1),
-$$
-
-
-Less noise
-
-How to study our fits
-
-
-$$ \chi^2 = \frac{1}{n}
-\sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2},
-$$
-
-
-Minimizing the cost function
-
-Relative error
-
-
-$$
-\epsilon_{\mathrm{relative}}= \frac{\vert \hat{y} -\hat{\tilde{y}}\vert}{\vert \hat{y}\vert}.
-$$
-
-
-We can modify easily the above Python code and plot the relative error instead
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression
-
-x = np.random.rand(100,1)
-y = 5*x+0.01*np.random.randn(100,1)
-linreg = LinearRegression()
-linreg.fit(x,y)
-ypredict = linreg.predict(x)
-
-plt.plot(x, np.abs(ypredict-y)/abs(y), "ro")
-plt.axis([0,1.0,0.0, 0.5])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$\epsilon_{\mathrm{relative}}$')
-plt.title(r'Relative error')
-plt.show()
-
The richness of scikit-learn
-
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression
-from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error
-
-x = np.random.rand(100,1)
-y = 2.0+ 5*x+0.5*np.random.randn(100,1)
-linreg = LinearRegression()
-linreg.fit(x,y)
-ypredict = linreg.predict(x)
-print('The intercept alpha: \n', linreg.intercept_)
-print('Coefficient beta : \n', linreg.coef_)
+# We use now Scikit-Learn's linear regressor and ridge regressor
+# OLS part
+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(y, ypredict))
+print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde))
# Explained variance score: 1 is perfect prediction
-print('Variance score: %.2f' % r2_score(y, ypredict))
-# Mean squared log error
-print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) )
+print('Variance score: %.2f' % r2_score(Energies, ytilde))
# Mean absolute error
-print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict))
-plt.plot(x, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0.0,1.0,1.5, 7.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Linear Regression fit ')
+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
+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))
+# Explained variance score: 1 is perfect prediction
+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_)
+
+fig, ax = plt.subplots()
+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')
+ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',
+ label='OLS')
+ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g',
+ label='Ridge $\lambda = 0.1$')
+ax.legend()
+save_fig("EoSfitting")
plt.show()
Functions in scikit-learn
+Splitting our Data in Training and Test data
-$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
-\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
-$$
-
-
-Other functions in scikit-learn
-
-
-$$
-R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
-$$
-
-
-where we have defined the mean value of \( \hat{y} \) as
-
-$$
-\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
-$$
-
-The mean absolute error and other functions in scikit-learn
-
-
-$$
-\text{MAE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1} \left| y_i - \tilde{y}_i \right|.
-$$
-
-
-Finally we present the
-squared logarithmic (quadratic) error
-
-$$
-\text{MSLE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n - 1} (\log_e (1 + y_i) - \log_e (1 + \tilde{y}_i) )^2,
-$$
-
-
-Cubic polynomial in scikit-learn
-
-import matplotlib.pyplot as plt
-import numpy as np
-import random
-from sklearn.linear_model import Ridge
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.pipeline import make_pipeline
-from sklearn.linear_model import LinearRegression
-
-x=np.linspace(0.02,0.98,200)
-noise = np.asarray(random.sample((range(200)),200))
-y=x**3*noise
-yn=x**3*100
-poly3 = PolynomialFeatures(degree=3)
-X = poly3.fit_transform(x[:,np.newaxis])
-clf3 = LinearRegression()
-clf3.fit(X,y)
-
-Xplot=poly3.fit_transform(x[:,np.newaxis])
-poly3_plot=plt.plot(x, clf3.predict(Xplot), label='Cubic Fit')
-plt.plot(x,yn, color='red', label="True Cubic")
-plt.scatter(x, y, label='Data', color='orange', s=15)
-plt.legend()
-plt.show()
-
-def error(a):
- for i in y:
- err=(y-yn)/yn
- return abs(np.sum(err))/len(err)
-
-print (error(y))
-
Polynomial Regression
-# Importing various packages
-from math import exp, sqrt
-from random import random, seed
+
import os
import numpy as np
+import pandas as pd
import matplotlib.pyplot as plt
+from sklearn.model_selection import train_test_split
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
-m = 100
-x = 2*np.random.rand(m,1)+4.
-y = 4+3*x*x+ +x-np.random.randn(m,1)
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
-xb = np.c_[np.ones((m,1)), x]
-theta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
-xnew = np.array([[0],[2]])
-xbnew = np.c_[np.ones((2,1)), xnew]
-ypredict = xbnew.dot(theta)
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
-plt.plot(xnew, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0,2.0,0, 15.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Random numbers ')
-plt.show()
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+infile = open(data_path("EoS.csv"),'r')
+
+# Read the EoS data as csv file and organized into two arrays with density and energies
+EoS = pd.read_csv(infile, names=('Density', 'Energy'))
+EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
+EoS = EoS.dropna()
+Energies = EoS['Energy']
+Density = EoS['Density']
+# The design matrix now as function of various polytrops
+X = np.zeros((len(Density),5))
+X[:,0] = 1
+X[:,1] = Density**(2.0/3.0)
+X[:,2] = Density
+X[:,3] = Density**(4.0/3.0)
+X[:,4] = Density**(5.0/3.0)
+# We split the data in test and training data
+X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
+# 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))
Linking the regression analysis with a statistical interpretation
+The singular value decomposition
-$$
-\begin{align*}
-\mbox{Cov}(\varepsilon_{i_1},
-\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if}
-& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right.
-\end{align*}
-$$
-
-
-The randomness of \( \varepsilon_i \) implies that
-\( \mathbf{Y}_i \) is also a random variable. In particular,
-\( \mathbf{Y}_i \) is normally distributed, because \( \varepsilon_i \sim
-\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \beta \) is a
-non-random scalar. To specify the parameters of the distribution of
-\( \mathbf{Y}_i \) we need to calculate its first two moments.
-Expectation value and variance
-
-
-$$
-\begin{align*}
-\mathbb{E}(Y_i) & =
-\mathbb{E}(\mathbf{X}_{i, \ast} \, \beta) + \mathbb{E}(\varepsilon_i)
-\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta,
-\end{align*}
-$$
-
-
-while
-its variance is
-
-$$
-\begin{align*} \mbox{Var}(Y_i) & = \mathbb{E} \{ [Y_i
-- \mathbb{E}(Y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( Y_i^2 ) -
-[\mathbb{E}(Y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \,
-\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \beta)^2 \\ &
-= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 \varepsilon_i
-\mathbf{X}_{i, \ast} \, \beta + \varepsilon_i^2 ] - ( \mathbf{X}_{i,
-\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2
-\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \beta +
-\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \beta)^2
-\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \,
-\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2.
-\end{align*}
-$$
-
-
-Hence, \( Y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \beta, \sigma^2) \).
-The singular value decompostion
-$$
-\hat{A} = \hat{U}\hat{D}\hat{V}^T
-$$
-
+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. This may
+however not the be case in general and a standard matrix inversion
+algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit
+the coupling constant of the widely used Ising model.
+There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach.
+
+From standard regression to Ridge regressions
+The Ising model
+
+
+$$
+\begin{align}
+ H = -J \sum_{k}^L s_k s_{k + 1},
+\tag{1}
+\end{align}
+$$
+
+
+import numpy as np
+import matplotlib.pyplot as plt
+from mpl_toolkits.axes_grid1 import make_axes_locatable
+import seaborn as sns
+import scipy.linalg as scl
+from sklearn.model_selection import train_test_split
+import tqdm
+sns.set(color_codes=True)
+cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
+
+L = 40
+n = int(1e4)
+
+spins = np.random.choice([-1, 1], size=(n, L))
+J = 1.0
+
+energies = np.zeros(n)
+
+for i in range(n):
+ energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
+
Reformulating the problem to suit regression
+
+
+$$
+\begin{align}
+ H = - \sum_j^L \sum_k^L s_j s_k J_{jk}.
+\tag{2}
+\end{align}
+$$
+
+
+
+$$
+\begin{align}
+ \boldsymbol{H} = \boldsymbol{X} J,
+\tag{3}
+\end{align}
+$$
+
+
+
+$$
+\begin{align}
+ \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon},
+\tag{4}
+\end{align}
+$$
+
+
+X = np.zeros((n, L ** 2))
+for i in range(n):
+ X[i] = np.outer(spins[i], spins[i]).ravel()
+y = energies
+X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
+
Linear regression
+
+
+$$
+\begin{align}
+ C(\boldsymbol{X}, \boldsymbol{\beta})= \frac{1}{n}\left\{(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})\right\}.
+\tag{5}
+\end{align}
+$$
+
+
+
+$$
+ \boldsymbol{\beta} = \frac{\boldsymbol{X}^T \boldsymbol{y}}{\boldsymbol{X}^T \boldsymbol{X}},
+$$
+
+
+X_train_own = np.concatenate(
+ (np.ones(len(X_train))[:, np.newaxis], X_train),
+ axis=1
+)
+X_test_own = np.concatenate(
+ (np.ones(len(X_test))[:, np.newaxis], X_test),
+ axis=1
+)
+
def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray:
+ return scl.inv(x.T @ x) @ (x.T @ y)
+beta = ols_inv(X_train_own, y_train)
+
Singular Value decomposition
+
+
+$$
+ \boldsymbol{\beta} = \boldsymbol{X}^{+}\boldsymbol{y},
+$$
+
+
+
+$$
+ \boldsymbol{X}^{+} = \frac{\boldsymbol{X}^T}{\boldsymbol{X}^T\boldsymbol{X}}.
+$$
+
+
+
+$$
+\begin{align}
+ \boldsymbol{\beta} = \boldsymbol{V}\boldsymbol{\Sigma}^{+} \boldsymbol{U}^T \boldsymbol{y}.
+\tag{6}
+\end{align}
+$$
+
+
+def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray:
+ u, s, v = scl.svd(x)
+ return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
+
beta = ols_svd(X_train_own,y_train)
+
J = beta[1:].reshape(L, L)
+fig = plt.figure(figsize=(20, 14))
+im = plt.imshow(J, **cmap_args)
+plt.title("OLS", fontsize=18)
+plt.xticks(fontsize=18)
+plt.yticks(fontsize=18)
+cb = fig.colorbar(im)
+cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
+plt.show()
+
Linear Regression Problems
$$
\begin{align*}
-\hat{X} & = \left[
+\boldsymbol{X} & = \left[
\begin{array}{rr}
1 & -1
\\
@@ -1331,435 +1591,486 @@ $$
$$
-We see easily that \( \mbox{det}(\hat{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 \( \hat{X} \) has at least an eigenvalue which is zero.
+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
+Fixing the singularity
$$
\begin{align}
-\hat{\beta} & = (\hat{X}^{T} \hat{X})^{-1} \hat{X}^{T} \hat{y},
-\tag{1}
+\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y},
+\tag{7}
\end{align}
$$
has linearly dependent column vectors, we will not be able to compute the inverse
-of \( \hat{X}^T\hat{X} \) and we cannot find the parameters (estimators) \( \beta_i \).
-The estimators are only well-defined if \( (\hat{X}^{T}\hat{X})^{-1} \) exits.
-This is more likely to happen when the matrix \( \hat{X} \) is high-dimensional. In this case it is likely to encounter a situation where
+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.
$$
-\hat{X}^{T} \hat{X} \rightarrow \hat{X}^{T} \hat{X}+\lambda \hat{I},
+\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I},
$$
-where \( \hat{I} \) is the identity matrix.
+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.
Fitting vs. predicting when data is in the model class
+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,
+$$
+
+
+Another Example
+
+
+$$
+\boldsymbol{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T.
+$$
+
+
+Economy-size SVD
+
+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.
+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}},
+$$
+
+
+Where are we going?
+
+
-
Fitting versus predicting when data is not in the model class
-
-
-
-An example code without the model assessment part
-
-import numpy as np
-import sklearn as sk
-from sklearn import datasets, linear_model
-from sklearn.preprocessing import PolynomialFeatures
-
-import matplotlib as mpl
-from matplotlib import pyplot as plt
-
-%matplotlib notebook
-
-# The Training Data
-
-N_train=100
-
-sigma_train=1;
-
-# Train on integers
-x=np.linspace(0.05,0.95,N_train)
-# Draw random noise
-s = sigma_train*np.random.randn(N_train)
-
-#linear
-y=2*x+s
-
-#Tenth Order
-#y=2*x-10*x**5+15*x**10+s
-
-p1=plt.plot(x,y, "o",ms=15, label='Training')
-
-#Linear Regression
-# Create linear regression object
-clf = linear_model.LinearRegression()
-
-# Train the model using the training sets
-clf.fit(x[:, np.newaxis], y)
-# The coefficients
-
-xplot=np.linspace(0.02,0.98,200)
-linear_plot=plt.plot(xplot, clf.predict(xplot[:, np.newaxis]),label='Linear')
-
-#Polynomial Regression
-
-
-poly3 = PolynomialFeatures(degree=3)
-X = poly3.fit_transform(x[:,np.newaxis])
-clf3 = linear_model.LinearRegression()
-clf3.fit(X,y)
-
-
-Xplot=poly3.fit_transform(xplot[:,np.newaxis])
-poly3_plot=plt.plot(xplot, clf3.predict(Xplot), label='Poly 3')
-
-
-
-#poly5 = PolynomialFeatures(degree=5)
-#X = poly5.fit_transform(x[:,np.newaxis])
-#clf5 = linear_model.LinearRegression()
-#clf5.fit(X,y)
-
-#Xplot=poly5.fit_transform(xplot[:,np.newaxis])
-#plt.plot(xplot, clf5.predict(Xplot), 'r--',linewidth=1)
-
-poly10 = PolynomialFeatures(degree=10)
-X = poly10.fit_transform(x[:,np.newaxis])
-clf10 = linear_model.LinearRegression()
-clf10.fit(X,y)
-
-Xplot=poly10.fit_transform(xplot[:,np.newaxis])
-poly10_plot=plt.plot(xplot, clf10.predict(Xplot), label='Poly 10')
-
-axes = plt.gca()
-axes.set_ylim([-7,7])
-
-handles, labels=axes.get_legend_handles_labels()
-plt.legend(handles,labels, loc='lower center')
-plt.xlabel("$x$")
-plt.ylabel("$y$")
-Title="$N=$"+str(N_train)+", $\sigma=$"+str(sigma_train)
-plt.title(Title+" (train)")
-plt.tight_layout()
-plt.show()
-
Generating test data
-# Generate Test Data
-
-#Number of test data
-N_test=20
-
-sigma_test=sigma_train
-
-max_x=1.2
-x_test=max_x*np.random.random(N_test)
-# Draw random noise
-s_test = sigma_test*np.random.randn(N_test)
-
-#Linear
-y_test=2*x_test+s_test
-#Tenth order
-#y_test=2*x_test-10*x_test**5+15*x_test**10+s_test
-
-#Make design matrices for prediction
-x_plot=np.linspace(0,max_x, 200)
-X3 = poly3.fit_transform(x_plot[:,np.newaxis])
-X10 = poly10.fit_transform(x_plot[:,np.newaxis])
-
-%matplotlib notebook
-
-fig = plt.figure()
-p1=plt.plot(x_test,y_test.transpose(), 'o', ms=12, label='data')
-p2=plt.plot(x_plot,clf.predict(x_plot[:,np.newaxis]), label='linear')
-p3=plt.plot(x_plot,clf3.predict(X3), label='3rd order')
-p10=plt.plot(x_plot,clf10.predict(X10), label='10th order')
-
-
-plt.legend(loc=2)
-plt.xlabel('$x$')
-plt.ylabel('$y$')
-plt.legend(loc='best')
-plt.title(Title+" (pred.)")
-plt.tight_layout()
-plt.show()
-
How can we effectively evaluate the various models?
-
-Code examples for Ridge and Lasso Regression
-
-import matplotlib.pyplot as plt
-import numpy as np
-from sklearn import linear_model
-from sklearn.linear_model import LinearRegression
-from sklearn.metrics import mean_squared_error, r2_score
-
-#creating data with random noise
-x=np.arange(50)
-
-delta=np.random.uniform(-2.5,2.5, size=(50))
-np.random.shuffle(delta)
-y =0.5*x+5+delta
-
-#arranging data into 2x50 matrix
-a=np.array(x) #inputs
-b=np.array(y) #outputs
-
-#Split into training and test
-X_train=a[:37, np.newaxis]
-X_test=a[37:, np.newaxis]
-y_train=b[:37]
-y_test=b[37:]
-
-print ("X_train: ", X_train.shape)
-print ("y_train: ", y_train.shape)
-print ("X_test: ", X_test.shape)
-print ("y_test: ", y_test.shape)
-
-print ("------------------------------------")
-
-print ("Ordinary Least Squares")
-#Add Ordinary Least Squares fit
-reg=LinearRegression()
-reg.fit(X_train, y_train)
-pred=reg.predict(X_test)
-print ("Prediction Shape: ", pred.shape)
-
-print('Coefficients: \n', reg.coef_)
-# The mean squared error
-print("Mean squared error: %.2f"
- % mean_squared_error(y_test, pred))
-# Explained variance score: 1 is perfect prediction
-print('Variance score: %.2f' % r2_score(y_test, pred))
-
-#plot
-plt.scatter(X_test,y_test,color='green', label="Training Data")
-plt.plot(X_test, pred, color='black', label="Fit Line")
-plt.legend()
-plt.show()
-
-print ("------------------------------------")
-
-print ("Ridge Regression")
-
-ridge=linear_model.RidgeCV(alphas=[0.1,1.0,10.0])
-ridge.fit(X_train,y_train)
-print ("Ridge Coefficient: ",ridge.coef_)
-print ("Ridge Intercept: ", ridge.intercept_)
-#Look into graphing with Ridge fit
-
-print ("------------------------------------")
-
-print ("Lasso")
-lasso=linear_model.Lasso(alpha=0.1)
-lasso.fit(X_train,y_train)
-predl=lasso.predict(X_test)
-print("Lasso Coefficient: ", lasso.coef_)
-print("Lasso Intercept: ", lasso.intercept_)
-plt.scatter(X_test,y_test,color='green', label="Training Data")
-plt.plot(X_test, predl, color='blue', label="Lasso")
-plt.legend()
-plt.show()
-
A second-order polynomial with Ridge and Lasso
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.linear_model import Ridge
-from sklearn.metrics import r2_score
-
-np.random.seed(4155)
-
-n_samples = 100
-
-x = np.random.rand(n_samples,1)
-y = 5*x*x + 0.1*np.random.rand(n_samples,1)
-
-# Centering x and y.
-x_ = x - np.mean(x)
-y_ = y - np.mean(y) # beta_0 = mean(y)
-
-X = np.c_[np.ones((n_samples,1)), x, x**2]
-X_ = np.c_[x_, x_**2]
-
-
-### 1.
-lmb_values = [1e-4, 1e-3, 1e-2, 10, 1e2, 1e4]
-num_values = len(lmb_values)
-
-## Ridge-regression of centered and not centered data
-beta_ridge = np.zeros((3,num_values))
-beta_ridge_centered = np.zeros((3,num_values))
-
-I3 = np.eye(3)
-I2 = np.eye(2)
-
-for i,lmb in enumerate(lmb_values):
- beta_ridge[:,i] = (np.linalg.inv( X.T @ X + lmb*I3) @ X.T @ y).flatten()
- beta_ridge_centered[1:,i] = (np.linalg.inv( X_.T @ X_ + lmb*I2) @ X_.T @ y_).flatten()
-
-# sett beta_0 = np.mean(y)
-beta_ridge_centered[0,:] = np.mean(y)
-
-## OLS (ordinary least squares) solution
-beta_ls = np.linalg.inv( X.T @ X ) @ X.T @ y
-
-## Evaluate the models
-pred_ls = X @ beta_ls
-pred_ridge = X @ beta_ridge
-pred_ridge_centered = X_ @ beta_ridge_centered[1:] + beta_ridge_centered[0,:]
-
-## Plot the results
-
-# Sorting
-sort_ind = np.argsort(x[:,0])
-
-x_plot = x[sort_ind,0]
-x_centered_plot = x_[sort_ind,0]
-
-pred_ls_plot = pred_ls[sort_ind,0]
-pred_ridge_plot = pred_ridge[sort_ind,:]
-pred_ridge_centered_plot = pred_ridge_centered[sort_ind,:]
-
-# Plott not centered
-plt.plot(x_plot,pred_ls_plot,label='ls')
-
-for i in range(num_values):
- plt.plot(x_plot,pred_ridge_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])
-
-plt.plot(x,y,'ro')
-
-plt.title('linear regression on un-centered data')
-plt.legend()
-
-# Plott centered
-plt.figure()
-
-for i in range(num_values):
- plt.plot(x_centered_plot,pred_ridge_centered_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])
-
-plt.plot(x_,y,'ro')
-
-plt.title('linear regression on centered data')
-plt.legend()
-
-
-# 2.
-
-pred_ridge_scikit = np.zeros((n_samples,num_values))
-for i,lmb in enumerate(lmb_values):
- pred_ridge_scikit[:,i] = (Ridge(alpha=lmb,fit_intercept=False).fit(X,y).predict(X)).flatten() # fit_intercept=False fordi bias er allerede i X
-
-plt.figure()
-
-plt.plot(x_plot,pred_ls_plot,label='ls')
-
-for i in range(num_values):
- plt.plot(x_plot,pred_ridge_scikit[sort_ind,i],label='scikit-ridge, lmb=%g'%lmb_values[i])
-
-plt.plot(x,y,'ro')
-plt.legend()
-plt.title('linear regression using scikit')
-
-plt.show()
-
-### R2-score of the results
-for i in range(num_values):
- print('lambda = %g'%lmb_values[i])
- print('r2 for scikit: %g'%r2_score(y,pred_ridge_scikit[:,i]))
- print('r2 for own code, not centered: %g'%r2_score(y,pred_ridge[:,i]))
- print('r2 for own, centered: %g\n'%r2_score(y,pred_ridge_centered[:,i]))
-
Resampling methods
+Resampling methods
Resampling approaches can be computationally expensive
+Resampling approaches can be computationally expensive
Why resampling methods ?
+Why resampling methods ?
-
Statistical analysis
+Statistical analysis
-
@@ -1832,7 +2141,6 @@ bootstrap is widely used.
Statistics
+Statistics
Statistics, moments
+Statistics, moments
Statistics, central moments
+Statistics, central moments
@@ -1941,7 +2249,7 @@ qualitatively as the spread of \( p \) around its mean.
Statistics, covariance
+Statistics, covariance
@@ -1975,7 +2283,7 @@ $$
Statistics, more covariance
+Statistics, more covariance
@@ -2008,7 +2316,7 @@ $$
Statistics, independent variables
+Statistics, independent variables
Statistics, more variance
+Statistics, more variance
@@ -2074,7 +2382,7 @@ value of a set of measurements.
Statistics and stochastic processes
+Statistics and stochastic processes
Statistics and sample variables
+Statistics and sample variables
Statistics, sample variance and covariance
+Statistics, sample variance and covariance
Statistics, law of large numbers
+Statistics, law of large numbers
Statistics, more on sample error
+Statistics, more on sample error
Statistics
+Statistics
Statistics, central limit theorem
+Statistics, central limit theorem
@@ -2258,7 +2566,7 @@ $$
Statistics, more technicalities
+Statistics, more technicalities
@@ -2288,7 +2596,7 @@ estimate of the PDF of each of the \( X_i \), estimating all properties of
Statistics
+Statistics
Using \( \bar x \) in place of \( \mu_{X_i}^{\phantom X} \) we can give an
-estimate of the covariance in Eq. (14)
+estimate of the covariance in Eq. (20)
$$
\mathrm{cov}(X_i, X_j) = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle
@@ -2320,7 +2628,7 @@ $$
Statistics and sample variance
+Statistics and sample variance
@@ -2352,7 +2660,7 @@ $$
&=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) \nonumber \\
&\approx&\frac{1}{n^2}\sum_{ij}\frac{1}{n}\mathrm{cov}(x) =\frac{1}{n^2}n^2\frac{1}{n}\mathrm{cov}(x)\nonumber\\
&=\frac{1}{n}\mathrm{cov}(x)
-\tag{16}
+\tag{22}
\end{align}
$$
@@ -2364,7 +2672,7 @@ measurements in the sample.
Statistics, uncorrelated results
+Statistics, uncorrelated results
-where in the second step we have used Eq. (15).
+where in the second step we have used Eq. (21).
The error of the sample is then just its standard deviation divided by
the square root of the number of measurements the sample contains.
This is a very useful formula which is easy to compute. It acts as a
@@ -2400,12 +2708,12 @@ cannot overlook the always present correlations.
Statistics, computations
+Statistics, computations
$$
@@ -2418,13 +2726,13 @@ which equals
$$
\begin{equation}
\frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n)
-\tag{18}
+\tag{24}
\end{equation}
$$
The first term is the same as the error in the uncorrelated case,
-Eq. (17). This means that the second
+Eq. (23). This means that the second
term accounts for the error correction due to correlation between the
measurements. For uncorrelated measurements this second term is zero.
Statistics, more on computations of errors
+Statistics, more on computations of errors
Statistics, wrapping up 1
+Statistics, wrapping up 1
Statistics, final expression
+Statistics, final expression
$$
@@ -2507,7 +2815,7 @@ $$
\frac{f_d}{\mathrm{var}(x)}\nonumber\\ &=&
\left(1+2\sum_{d=1}^{n-1}\kappa_d\right)\frac{1}{n}\mathrm{var}(x)\nonumber\\
&=\frac{\tau}{n}\cdot\mathrm{var}(x)
-\tag{19}
+\tag{25}
\end{align}
$$
@@ -2520,7 +2828,7 @@ correction factor the autocorrelation time:
$$
\begin{equation}
\tau = 1+2\sum_{d=1}^{n-1}\kappa_d
-\tag{20}
+\tag{26}
\end{equation}
$$
@@ -2529,13 +2837,13 @@ $$
Statistics, effective number of correlations
+Statistics, effective number of correlations
@@ -2555,42 +2863,205 @@ measurements is very large.
Log-likelihood
+Linking the regression analysis with a statistical interpretation
$$
-\begin{align*}
-\mbox{AIC}(\lambda) & = 2 \, p - 2 \log(\hat{L})
-\\
-& = 2 \, \mbox{tr} [\mathbf{H}(\lambda)] - 2 \log\{L[\hat{\beta}(\lambda), \hat{\sigma}^2(\lambda)]\}
-\\
-& = 2 \, \sum_{j=1}^p \frac{d_{jj}^2}{d_{jj}^2 + \lambda}
-+ 2 n \, \log[\sqrt{2 \, \pi} \, \hat{\sigma}(\lambda)] + \frac{1}{\hat{\sigma}^2(\lambda)} \sum_{i=1}^n [y_i - \mathbf{X}_{i, \ast} \, \hat{\beta}(\lambda)]^2.
-\end{align*}
+\begin{align*}
+\mbox{Cov}(\varepsilon_{i_1},
+\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if}
+& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right.
+\end{align*}
$$
-The value of \( \lambda \) which minimizes \( \mbox{AIC}(\lambda) \) corresponds to the `optimal' balance of model complexity and overfitting.
+The randomness of \( \varepsilon_i \) implies that
+\( \mathbf{y}_i \) is also a random variable. In particular,
+\( \mathbf{y}_i \) is normally distributed, because \( \varepsilon_i \sim
+\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \boldsymbol{\beta} \) is a
+non-random scalar. To specify the parameters of the distribution of
+\( \mathbf{y}_i \) we need to calculate its first two moments.
+
+Cross-validation
+Assumptions made
+
+
+$$
+\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon}
+$$
+
+
+
+$$
+\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}.
+$$
+
+Expectation value and variance
+
+
+$$
+\begin{align*}
+\mathbb{E}(y_i) & =
+\mathbb{E}(\mathbf{X}_{i, \ast} \, \boldsymbol{\beta}) + \mathbb{E}(\varepsilon_i)
+\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta,
+\end{align*}
+$$
+
+
+while
+its variance is
+
+$$
+\begin{align*} \mbox{Var}(y_i) & = \mathbb{E} \{ [y_i
+- \mathbb{E}(y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( y_i^2 ) -
+[\mathbb{E}(y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \,
+\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 \\ &
+= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 \varepsilon_i
+\mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + \varepsilon_i^2 ] - ( \mathbf{X}_{i,
+\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2
+\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \boldsymbol{\beta} +
+\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2
+\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \,
+\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2.
+\end{align*}
+$$
+
+
+Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with
+mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \) (not be confused with the singular values of the SVD).
+Expectation value and variance for \( \boldsymbol{\beta} \)
+
+
+$$
+\mathbb{E}(\boldsymbol{\beta}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}.
+$$
+
+
+This means that the estimator of the regression parameters is unbiased.
+
+
+$$
+\begin{eqnarray*}
+\mbox{Var}(\boldsymbol{\beta}) & = & \mathbb{E} \{ [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})] [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})]^{T} \}
+\\
+& = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}]^{T} \}
+\\
+% & = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}]^{T} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+% \\
+% & = & \mathbb{E} \{ (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} \, \mathbf{Y}^{T} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+% \\
+& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \mathbb{E} \{ \mathbf{Y} \, \mathbf{Y}^{T} \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+\\
+& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+% \\
+% & = & (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1}
+% \\
+% & & + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \boldsymbol{\beta} \boldsymbol{\beta}^T
+\\
+& = & \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T}
+\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1},
+\end{eqnarray*}
+$$
+
+
+
+$$
+\mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\boldsymbol{\beta}^{\mathrm{OLS}}.
+$$
+
+
+We see clearly that
+\( \mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big] \not= \boldsymbol{\beta}^{\mathrm{OLS}} \) for any \( \lambda > 0 \). We say then that the ridge estimator is biased.
+
+
+$$
+\mbox{Var}[\boldsymbol{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T},
+$$
+
+
+and it is easy to see that if the parameter \( \lambda \) goes to infinity then the variance of Ridge parameters \( \boldsymbol{\beta} \) goes to zero.
+
+
+$$
+\mbox{Var}[\boldsymbol{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\boldsymbol{\beta}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}.
+$$
+
+
+The difference is non-negative definite since each component of the
+matrix product is non-negative definite.
+This means the variance we obtain with the standard OLS will always for \( \lambda > 0 \) be larger than the variance of \( \boldsymbol{\beta} \) obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below.
+Cross-validation
Computationally expensive
+Computationally expensive
Various steps in cross-validation
+Various steps in cross-validation
How to set up the cross-validation for Ridge and/or Lasso
+How to set up the cross-validation for Ridge and/or Lasso
$$
\begin{align*}
-\hat{\beta}_{-i}(\lambda) & = ( \hat{X}_{-i, \ast}^{\top}
-\hat{X}_{-i, \ast} + \lambda \hat{I}_{pp})^{-1}
-\hat{X}_{-i, \ast}^{\top} \hat{y}_{-i}
+\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T}
+\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1}
+\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i}
\end{align*}
$$
-
$$
\begin{align*}
-\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \hat{\beta}_{-i}(\lambda), \hat{\sigma}_{-i}^2(\lambda)]\}.
+\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}.
\end{align*}
$$
@@ -2694,32 +3168,7 @@ $$
Predicted Residual Error Sum of Squares
-
-$$
-\begin{align*}
-\lambda_{\mbox{{\tiny opt}}} = \arg \min_{\lambda} \frac{1}{n} \sum_{i=1}^n [y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)]^2.
-\end{align*}
-$$
-
-
-Resampling methods: Jackknife and Bootstrap
+Resampling methods: Jackknife and Bootstrap
Resampling methods: Jackknife
+Resampling methods: Jackknife
$$
-\hat{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n),
+\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n),
$$
Resampling methods: Jackknife estimator
-
-
-$$
-\widehat{\mathrm{Bias}}(\widehat \theta,\theta) = (n-1)\left( - \widehat{\theta} + \frac{1}{n}\sum_{i=1}^{n} \widehat \theta_i \right) \qquad \text{and} \qquad \widehat{\sigma}^2_{\widehat{\theta} } = \frac{n-1}{n}\sum_{i=1}^{n}( \widehat{\theta}_i - \frac{1}{n}\sum_{j=1}^{n}\widehat \theta_j )^2.
-$$
-
-Jackknife code example
Resampling methods: Bootstrap background
-
Code example for the Bootstrap method
-The following code starts with a Gaussian distribution with mean value \( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data used in the bootstrap analysis. The bootstrap analysis returns a data set after a given number of bootstrap operations (as many as we have data points). This data set consists of estimated mean values for each bootstrap operation. The histogram generated by the bootstrap method shows that the distribution for these mean values is also a Gaussian, centered around the mean value \( \mu=100 \) but with standard deviation \( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in this case the same as the number of original data points). The value of the standard deviation is what we expect from the central limit theorem.
+
+Resampling methods: Blocking
+Code Example for Cross-validation and \( k \)-fold Cross-validation
-$$
-\begin{align*}
-\hat{X} = (X_1,X_2,\cdots,X_n).
-\end{align*}
-$$
-
-
-Blocking Transformations
- We now define
-blocking transformations. The idea is to take the mean of subsequent
-pair of elements from \( \vec{X} \) and form a new vector
-\( \vec{X}_1 \). Continuing in the same way by taking the mean of
-subsequent pairs of elements of \( \vec{X}_1 \) we obtain \( \vec{X}_2 \), and
-so on.
-Define \( \vec{X}_i \) recursively by:
-
-
-$$
-\begin{align}
-(\vec{X}_0)_k &\equiv (\vec{X})_k \nonumber \\
-(\vec{X}_{i+1})_k &\equiv \frac{1}{2}\Big( (\vec{X}_i)_{2k-1} +
-(\vec{X}_i)_{2k} \Big) \qquad \text{for all} \qquad 1 \leq i \leq d-1
-\tag{21}
-\end{align}
-$$
-
-
-Blocking Transformations
-
-
-$$
-\begin{align}
-\gamma_{k+1}(h) &= cov\left( ({X}_{k+1})_{i}, ({X}_{k+1})_{j} \right) \nonumber \\
-&= \frac{1}{4}cov\left( ({X}_{k})_{2i-1} + ({X}_{k})_{2i}, ({X}_{k})_{2j-1} + ({X}_{k})_{2j} \right) \nonumber \\
-&= \frac{1}{2}\gamma_{k}(2h) + \frac{1}{2}\gamma_k(2h+1) \hspace{0.1cm} \mathrm{h = 0}
-\tag{22}\\
-&=\frac{1}{4}\gamma_k(2h-1) + \frac{1}{2}\gamma_k(2h) + \frac{1}{4}\gamma_k(2h+1) \quad \mathrm{else}
-\tag{23}
-\end{align}
-$$
-
-
-Blocking Transformations, getting there
-We have
-
-$$
-\begin{align}
-V(\overline{X}_k) = \frac{\sigma_k^2}{n_k} + \underbrace{\frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h)}_{\equiv e_k} = \frac{\sigma^2_k}{n_k} + e_k \quad \text{if} \quad \gamma_k(0) = \sigma_k^2.
-\tag{24}
-\end{align}
-$$
-
-
-The term \( e_k \) is called the truncation error:
-
-$$
-\begin{equation}
-e_k = \frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h).
-\tag{25}
-\end{equation}
-$$
-
-
-We can show that \( V(\overline{X}_i) = V(\overline{X}_j) \) for all \( 0 \leq i \leq d-1 \) and \( 0 \leq j \leq d-1 \).
-Blocking Transformations, final expressions
-
-
-$$
-\begin{align}
-n_{j+1} \overline{X}_{j+1} &= \sum_{i=1}^{n_{j+1}} (\hat{X}_{j+1})_i = \frac{1}{2}\sum_{i=1}^{n_{j}/2} (\hat{X}_{j})_{2i-1} + (\hat{X}_{j})_{2i} \nonumber \\
-&= \frac{1}{2}\left[ (\hat{X}_j)_1 + (\hat{X}_j)_2 + \cdots + (\hat{X}_j)_{n_j} \right] = \underbrace{\frac{n_j}{2}}_{=n_{j+1}} \overline{X}_j = n_{j+1}\overline{X}_j.
-\tag{26}
-\end{align}
-$$
-
-
-By repeated use of this equation we get \( V(\overline{X}_i) = V(\overline{X}_0) = V(\overline{X}) \) for all \( 0 \leq i \leq d-1 \). This has the consequence that
-
-$$
-\begin{align}
-V(\overline{X}) = \frac{\sigma_k^2}{n_k} + e_k \qquad \text{for all} \qquad 0 \leq k \leq d-1. \tag{27}
-\end{align}
-$$
-
-
-Code examples for Blocking, Jackknife and bootstrap
-
+The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial.
from sys import argv
-from os import mkdir, path
-import time
-import numpy as np
+
import numpy as np
import matplotlib.pyplot as plt
-from matplotlib.ticker import FormatStrFormatter
-from matplotlib.font_manager import FontProperties
+from sklearn.model_selection import KFold
+from sklearn.linear_model import Ridge
+from sklearn.model_selection import cross_val_score
+from sklearn.preprocessing import PolynomialFeatures
-# Timing Decorator
-def timeFunction(f):
- def wrap(*args):
- time1 = time.time()
- ret = f(*args)
- time2 = time.time()
- print '%s Function Took: \t %0.3f s' % (f.func_name.title(), (time2-time1))
- return ret
- return wrap
+# A seed just to ensure that the random numbers are the same for every run.
+# Useful for eventual debugging.
+np.random.seed(3155)
-class dataAnalysisClass:
- # General Init functions
- def __init__(self, fileName, size=0):
- self.inputFileName = fileName
- self.loadData(size)
- self.createOutputFolder()
- self.avg = np.average(self.data)
- self.var = np.var(self.data)
- self.std = np.std(self.data)
+# Generate the data.
+nsamples = 100
+x = np.random.randn(nsamples)
+y = 3*x**2 + np.random.randn(nsamples)
- def loadData(self, size=0):
- if size != 0:
- with open(self.inputFileName) as inputFile:
- self.data = np.zeros(size)
- for x in xrange(size):
- self.data[x] = float(next(inputFile))
- else:
- self.data = np.loadtxt(self.inputFileName)
+## Cross-validation on Ridge regression using KFold only
- # Statistical Analysis with Multiple Methods
- def runAllAnalyses(self):
- if len(self.data) <= 100000:
- print "Autocorrelation..."
- self.autocorrelation()
- print "Bootstrap..."
- self.bootstrap()
- print "Jackknife..."
- self.jackknife()
- print "Blocking..."
- self.blocking()
+# Decide degree on polynomial to fit
+poly = PolynomialFeatures(degree = 6)
- # Standard Autocorrelation
- @timeFunction
- def autocorrelation(self):
- self.acf = np.zeros(len(self.data)/2)
- for k in range(0, len(self.data)/2):
- self.acf[k] = np.corrcoef(np.array([self.data[0:len(self.data)-k], \
- self.data[k:len(self.data)]]))[0,1]
+# Decide which values of lambda to use
+nlambdas = 500
+lambdas = np.logspace(-3, 5, nlambdas)
- # Bootstrap
- @timeFunction
- def bootstrap(self, nBoots = 1000):
- bootVec = np.zeros(nBoots)
- for k in range(0,nBoots):
- bootVec[k] = np.average(np.random.choice(self.data, len(self.data)))
- self.bootAvg = np.average(bootVec)
- self.bootVar = np.var(bootVec)
- self.bootStd = np.std(bootVec)
+# Initialize a KFold instance
+k = 5
+kfold = KFold(n_splits = k)
- # Jackknife
- @timeFunction
- def jackknife(self):
- jackknVec = np.zeros(len(self.data))
- for k in range(0,len(self.data)):
- jackknVec[k] = np.average(np.delete(self.data, k))
- self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg)
- self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec)
- self.jackknStd = np.sqrt(self.jackknVar)
+# Perform the cross-validation to estimate MSE
+scores_KFold = np.zeros((nlambdas, k))
- # Blocking
- @timeFunction
- def blocking(self, blockSizeMax = 500):
- blockSizeMin = 1
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
+ j = 0
+ for train_inds, test_inds in kfold.split(x):
+ xtrain = x[train_inds]
+ ytrain = y[train_inds]
- self.blockSizes = []
- self.meanVec = []
- self.varVec = []
+ xtest = x[test_inds]
+ ytest = y[test_inds]
- for i in range(blockSizeMin, blockSizeMax):
- if(len(self.data) % i != 0):
- pass#continue
- blockSize = i
- meanTempVec = []
- varTempVec = []
- startPoint = 0
- endPoint = blockSize
+ Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
+ ridge.fit(Xtrain, ytrain[:, np.newaxis])
- while endPoint <= len(self.data):
- meanTempVec.append(np.average(self.data[startPoint:endPoint]))
- startPoint = endPoint
- endPoint += blockSize
- mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec)
- self.meanVec.append(mean)
- self.varVec.append(var)
- self.blockSizes.append(blockSize)
+ Xtest = poly.fit_transform(xtest[:, np.newaxis])
+ ypred = ridge.predict(Xtest)
- self.blockingAvg = np.average(self.meanVec[-200:])
- self.blockingVar = (np.average(self.varVec[-200:]))
- self.blockingStd = np.sqrt(self.blockingVar)
+ scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
+
+ j += 1
+ i += 1
+estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
- # Plot of Data, Autocorrelation Function and Histogram
- def plotAll(self):
- self.createOutputFolder()
- if len(self.data) <= 100000:
- self.plotAutocorrelation()
- self.plotData()
- self.plotHistogram()
- self.plotBlocking()
+## Cross-validation using cross_val_score from sklearn along with KFold
- # Create Output Plots Folder
- def createOutputFolder(self):
- self.outName = self.inputFileName[:-4]
- if not path.exists(self.outName):
- mkdir(self.outName)
+# kfold is an instance initialized above as:
+# kfold = KFold(n_splits = k)
- # Plot the Dataset, Mean and Std
- def plotData(self):
- # Far away plot
- font = {'fontname':'serif'}
- plt.plot(range(0, len(self.data)), self.data, 'r-', linewidth=1)
- plt.plot([0, len(self.data)], [self.avg, self.avg], 'b-', linewidth=1)
- plt.plot([0, len(self.data)], [self.avg + self.std, self.avg + self.std], 'g--', linewidth=1)
- plt.plot([0, len(self.data)], [self.avg - self.std, self.avg - self.std], 'g--', linewidth=1)
- plt.ylim(self.avg - 5*self.std, self.avg + 5*self.std)
- plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.4f'))
- plt.xlim(0, len(self.data))
- plt.ylabel(self.outName.title() + ' Monte Carlo Evolution', **font)
- plt.xlabel('MonteCarlo History', **font)
- plt.title(self.outName.title(), **font)
- plt.savefig(self.outName + "/data.eps")
- plt.savefig(self.outName + "/data.png")
- plt.clf()
+estimated_mse_sklearn = np.zeros(nlambdas)
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
- # Plot Histogram of Dataset and Gaussian around it
- def plotHistogram(self):
- binNumber = 50
- font = {'fontname':'serif'}
- count, bins, ignore = plt.hist(self.data, bins=np.linspace(self.avg - 5*self.std, self.avg + 5*self.std, binNumber))
- plt.plot([self.avg, self.avg], [0,np.max(count)+10], 'b-', linewidth=1)
- plt.ylim(0,np.max(count)+10)
- plt.ylabel(self.outName.title() + ' Histogram', **font)
- plt.xlabel(self.outName.title() , **font)
- plt.title('Counts', **font)
+ X = poly.fit_transform(x[:, np.newaxis])
+ estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
- #gaussian
- norm = 0
- for i in range(0,len(bins)-1):
- norm += (bins[i+1]-bins[i])*count[i]
- plt.plot(bins, norm/(self.std * np.sqrt(2 * np.pi)) * np.exp( - (bins - self.avg)**2 / (2 * self.std**2) ), linewidth=1, color='r')
- plt.savefig(self.outName + "/hist.eps")
- plt.savefig(self.outName + "/hist.png")
- plt.clf()
+ # cross_val_score return an array containing the estimated negative mse for every fold.
+ # we have to the the mean of every array in order to get an estimate of the mse of the model
+ estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
- # Plot the Autocorrelation Function
- def plotAutocorrelation(self):
- font = {'fontname':'serif'}
- plt.plot(range(1, len(self.data)/2), self.acf[1:], 'r-')
- plt.ylim(-1, 1)
- plt.xlim(0, len(self.data)/2)
- plt.ylabel('Autocorrelation Function', **font)
- plt.xlabel('Lag', **font)
- plt.title('Autocorrelation', **font)
- plt.savefig(self.outName + "/autocorrelation.eps")
- plt.savefig(self.outName + "/autocorrelation.png")
- plt.clf()
+ i += 1
- def plotBlocking(self):
- font = {'fontname':'serif'}
- plt.plot(self.blockSizes, self.varVec, 'r-')
- plt.ylabel('Variance', **font)
- plt.xlabel('Block Size', **font)
- plt.title('Blocking', **font)
- plt.savefig(self.outName + "/blocking.eps")
- plt.savefig(self.outName + "/blocking.png")
- plt.clf()
+## Plot and compare the slightly different ways to perform cross-validation
- # Print Stuff to the Terminal
- def printOutput(self):
- print "\nSample Size: \t", len(self.data)
- print "\n=========================================\n"
- print "Sample Average: \t", self.avg
- print "Sample Variance:\t", self.var
- print "Sample Std: \t", self.std
- print "\n=========================================\n"
- print "Bootstrap Average: \t", self.bootAvg
- print "Bootstrap Variance:\t", self.bootVar
- print "Bootstrap Error: \t", self.bootStd
- print "\n=========================================\n"
- print "Jackknife Average: \t", self.jackknAvg
- print "Jackknife Variance:\t", self.jackknVar
- print "Jackknife Error: \t", self.jackknStd
- print "\n=========================================\n"
- print "Blocking Average: \t", self.blockingAvg
- print "Blocking Variance:\t", self.blockingVar
- print "Blocking Error: \t", self.blockingStd, "\n"
+plt.figure()
-# Initialize the class
-if len(argv) > 2:
- dataAnalysis = dataAnalysisClass(argv[1], int(argv[2]))
-else:
- dataAnalysis = dataAnalysisClass(argv[1])
+plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
+plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
-# Run Analyses
-dataAnalysis.runAllAnalyses()
+plt.xlabel('log10(lambda)')
+plt.ylabel('mse')
-# Plot the data
-dataAnalysis.plotAll()
+plt.legend()
-# Print Some Output
-dataAnalysis.printOutput()
+plt.show()
The bias-variance tradeoff
+The bias-variance tradeoff
+$$
+\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon}
+$$
+
+
+
+$$
+C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right].
+$$
+
+
+
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2.
+$$
+
+
+
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right],
+$$
+
+
+and adding and subtracting \( \mathbb{E}\left[\boldsymbol{\tilde{y}}\right] \) we get
+
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right],
+$$
+
+
+which, using the abovementioned expectation values can be rewritten as
+
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2,
+$$
+
+
+that is the rewriting in terms of the so-called bias, the variance of the model \( \boldsymbol{\tilde{y}} \) and the variance of \( \boldsymbol{\epsilon} \).
Training and testing data
-
+Example code for Bias-Variance tradeoff
-$$
-y=f(\boldsymbol{x}) + \epsilon
-$$
-
-where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma_\epsilon \).
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+
+np.random.seed(2018)
+
+n = 500
+n_boostraps = 100
+degree = 18 # A quite high value, just to show.
+noise = 0.1
+
+# Make data set.
+x = np.linspace(-1, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)
+
+# Hold out some test data that is never used in training.
+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+# Combine x transformation and model into one operation.
+# Not neccesary, but convenient.
+model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
+
+# The following (m x n_bootstraps) matrix holds the column vectors y_pred
+# for each bootstrap iteration.
+y_pred = np.empty((y_test.shape[0], n_boostraps))
+for i in range(n_boostraps):
+ x_, y_ = resample(x_train, y_train)
+
+ # Evaluate the new model on the same test data each time.
+ y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
+
+# Note: Expectations and variances taken w.r.t. different training
+# data sets, hence the axis=1. Subsequent means are taken across the test data
+# set in order to obtain a total value, but before this we have error/bias/variance
+# calculated per data point in the test set.
+# Note 2: The use of keepdims=True is important in the calculation of bias as this
+# maintains the column vector form. Dropping this yields very unexpected results.
+error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+print('Error:', error)
+print('Bias^2:', bias)
+print('Var:', variance)
+print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))
+
+plt.plot(x[::5, :], y[::5, :], label='f(x)')
+plt.scatter(x_test, y_test, label='Data points')
+plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')
+plt.legend()
+plt.show()
+
Procedure to find a predictor
-
+Understanding what happens
-$$
- \mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) = \sum_i (y_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2.
-$$
-
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+
+np.random.seed(2018)
+
+n = 40
+n_boostraps = 100
+maxdegree = 14
+
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+for degree in range(maxdegree):
+ model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
+ y_pred = np.empty((y_test.shape[0], n_boostraps))
+ for i in range(n_boostraps):
+ x_, y_ = resample(x_train, y_train)
+ y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
+
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+ variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+ print('Polynomial degree:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.plot(polydegree, np.log10(error), label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+plt.show()
+
What we want
-
-The expected generalization error
-
-
-$$
-\begin{align}
-E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ]&= E_\mathcal{L,\epsilon}\left[ \sum_i ({y}_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2 \right] \nonumber \\
- &= E_\mathcal{L, \epsilon}\left[ \sum_{i}({y}_i -f(\boldsymbol{x}_i) +f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2\right] \nonumber \\
- &= \sum_i E_\epsilon[ ({y}_i -f(\boldsymbol{x}_i))^2 ]+ E_\mathcal{L, \epsilon}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] + 2E_\epsilon[{y}_i -f(\boldsymbol{x}_i)]E_\mathcal{L}[f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i)] \nonumber \\
- &=\sum_i \sigma_\epsilon^2 + E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2],
-\tag{28}
-\end{align}
-$$
-
-
-Elaborating a little bit more
-
-
-$$
-\begin{align}
-E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] &=E_\mathcal{L}[(f(\mathbf{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]+ E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] \nonumber \\
-&=E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] + E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] \nonumber \\
-&+2E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])] \nonumber \\
-&=(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2+E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2].
-\tag{29}
-\end{align}
-$$
-
-The bias
-
-
-$$
-Bias^2= \sum_i (f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2
-$$
-
-
-and measures the deviation of the expectation value of our estimator (i.e. the asymptotic value of our estimator in the infinite data limit) from the true value.
-The variance
-The second term is called the variance
-
-$$
-Var=\sum_i E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2],
-$$
-
-
-
-$$
-E_\mathrm{out}=E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ] = Bias^2 + Var + Noise.
-$$
-
+Summing up
Summing up
The one-dimensional Ising model, project 2
+Another Example rom Scikit-Learn's Repository
+"""
+============================
+Underfitting vs. Overfitting
+============================
+
+This example demonstrates the problems of underfitting and overfitting and
+how we can use linear regression with polynomial features to approximate
+nonlinear functions. The plot shows the function that we want to approximate,
+which is a part of the cosine function. In addition, the samples from the
+real function and the approximations of different models are displayed. The
+models have polynomial features of different degrees. We can see that a
+linear function (polynomial with degree 1) is not sufficient to fit the
+training samples. This is called **underfitting**. A polynomial of degree 4
+approximates the true function almost perfectly. However, for higher degrees
+the model will **overfit** the training data, i.e. it learns the noise of the
+training data.
+We evaluate quantitatively **overfitting** / **underfitting** by using
+cross-validation. We calculate the mean squared error (MSE) on the validation
+set, the higher, the less likely the model generalizes correctly from the
+training data.
+"""
+
+print(__doc__)
+
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.linear_model import LinearRegression
+from sklearn.model_selection import cross_val_score
+
+
+def true_fun(X):
+ return np.cos(1.5 * np.pi * X)
+
+np.random.seed(0)
+
+n_samples = 30
+degrees = [1, 4, 15]
+
+X = np.sort(np.random.rand(n_samples))
+y = true_fun(X) + np.random.randn(n_samples) * 0.1
+
+plt.figure(figsize=(14, 5))
+for i in range(len(degrees)):
+ ax = plt.subplot(1, len(degrees), i + 1)
+ plt.setp(ax, xticks=(), yticks=())
+
+ polynomial_features = PolynomialFeatures(degree=degrees[i],
+ include_bias=False)
+ linear_regression = LinearRegression()
+ pipeline = Pipeline([("polynomial_features", polynomial_features),
+ ("linear_regression", linear_regression)])
+ pipeline.fit(X[:, np.newaxis], y)
+
+ # Evaluate the models using crossvalidation
+ scores = cross_val_score(pipeline, X[:, np.newaxis], y,
+ scoring="neg_mean_squared_error", cv=10)
+
+ X_test = np.linspace(0, 1, 100)
+ plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
+ plt.plot(X_test, true_fun(X_test), label="True function")
+ plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
+ plt.xlabel("x")
+ plt.ylabel("y")
+ plt.xlim((0, 1))
+ plt.ylim((-2, 2))
+ plt.legend(loc="best")
+ plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
+ degrees[i], -scores.mean(), scores.std()))
+plt.show()
+
The one-dimensional Ising model
$$
\begin{align}
H = -J \sum_{k}^L s_k s_{k + 1},
-\tag{30}
+\tag{27}
\end{align}
$$
@@ -3586,18 +3882,6 @@ energies = np.zeros(n)
for i in range(n):
energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
Reformulating the problem to suit regression
-
@@ -3618,7 +3902,7 @@ a matrix-product on the form
$$
\begin{align}
H = X J,
-\tag{32}
+\tag{29}
\end{align}
$$
@@ -3630,12 +3914,13 @@ with the form utilized in linear regression, viz.
$$
\begin{align}
- y = X\omega + \epsilon,
-\tag{33}
+ \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}.
+\tag{30}
\end{align}
$$
+We organize the data as we did above
Linear regression
-
-$$
-\begin{align}
- y = f(x) + \epsilon,
-\tag{34}
-\end{align}
-$$
-
-
-
-$$
-\begin{align}
- y = X\omega + \epsilon,
-\tag{35}
-\end{align}
-$$
-
-
-Ordinary least squares
-
-
-$$
-\begin{align}
- C(X, \omega) = ||X\omega - y||^2
- = (X\omega - y)^T(X\omega - y)
-\tag{36}
-\end{align}
-$$
-
-
-We then find the extremal point of \( C \) by taking the derivative with respect to \( \omega \) and setting it to zero, i.e.,
-
-
-$$
-\begin{align}
- \dfrac{\mathrm{d}C}{\mathrm{d}\omega}
- = 0.
-\tag{37}
-\end{align}
-$$
-
-
-This yields the expression for \( \omega \) to be
-
-$$
-\begin{align}
- \omega = \frac{X^T y}{X^T X},
-\tag{38}
-\end{align}
-$$
-
-
-def get_ols_weights_naive(x: np.ndarray, y: np.ndarray) -> np.ndarray:
- return scl.inv(x.T @ x) @ (x.T @ y)
-omega = get_ols_weights_naive(X_train_own, y_train)
-
Singular Value decomposition
-Doing the inversion directly turns out to be a bad idea as the matrix
-\( X^TX \) is singular. An alternative approach is to use the singular
-value decomposition. Using the definition of the Moore-Penrose
-pseudoinverse we can write the equation for \( \omega \) as
-
-
-$$
-\begin{align}
- \omega = X^{+}y,
-\tag{39}
-\end{align}
-$$
-
-
-where the pseudoinverse of \( X \) is given by
-
-$$
-\begin{align}
- X^{+} = \frac{X^T}{X^T X}.
-\tag{40}
-\end{align}
-$$
-
-
-
-$$
-\begin{align}
- \omega = V\Sigma^{+} U^T y.
-\tag{41}
-\end{align}
-$$
-
-
-def get_ols_weights(x: np.ndarray, y: np.ndarray) -> np.ndarray:
- u, s, v = scl.svd(x)
- return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
-
omega = get_ols_weights(X_train_own,y_train)
-
Fitting with scikit-learn
-
-LinearRegression-model from Scikit-learn for comparison.
+We will do all fitting with Scikit-Learn,
LinearRegression-model from Scikit-learn for comparis
clf = skl.LinearRegression().fit(X_train, y_train)
J_own = omega[1:].reshape(L, L)
-J_sk = clf.coef_.reshape(L, L)
+
J_sk = clf.coef_.reshape(L, L)
fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_own, **cmap_args)
-plt.title("Home-made OLS", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-
-fig = plt.figure(figsize=(20, 14))
im = plt.imshow(J_sk, **cmap_args)
plt.title("LinearRegression from Scikit-learn", fontsize=18)
plt.xticks(fontsize=18)
@@ -3857,70 +3970,35 @@ cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=Ridge regression
+
Ridge regression
$$
\begin{align}
- C(X, \omega; \lambda) = ||X\omega - y||^2 + \lambda ||\omega||^2
- = (X\omega - y)^T(X\omega - y) + \lambda \omega^T\omega.
-\tag{42}
+ C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \boldsymbol{\beta}^T\boldsymbol{\beta}.
+\tag{31}
\end{align}
$$
-Finding the extremum of this function yields the weights
-
-
-$$
-\begin{align}
- \omega(\lambda) = \frac{X^Ty}{X^TX + \lambda} \to \frac{\omega_{\text{LS}}}{1 + \lambda},
-\tag{43}
-\end{align}
-$$
-
-
-def get_ridge_weights(x: np.ndarray, y: np.ndarray, _lambda: float) -> np.ndarray:
- return x.T @ y @ scl.inv(
- x.T @ x + np.eye(x.shape[1], x.shape[1]) * _lambda
- )
-_lambda = 0.1
-omega_ridge = get_ridge_weights(X_train_own, y_train, np.array([_lambda]))
+
_lambda = 0.1
clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)
-J_ridge_own = omega_ridge[1:].reshape(L, L)
J_ridge_sk = clf_ridge.coef_.reshape(L, L)
-fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_ridge_own, **cmap_args)
-plt.title("Home-made ridge regression", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-
fig = plt.figure(figsize=(20, 14))
im = plt.imshow(J_ridge_sk, **cmap_args)
plt.title("Ridge from Scikit-learn", fontsize=18)
@@ -3935,22 +4013,22 @@ plt.show()
LASSO regression
+LASSO regression
$$
\begin{align}
- C(X, \omega; \lambda) =
- ||X\omega - y||^2 + \lambda ||\omega||
- = (X\omega - y)^T(X\omega - y) + \lambda \sqrt{\omega^T\omega}.
-\tag{44}
+ C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \sqrt{\boldsymbol{\beta}^T\boldsymbol{\beta}}.
+\tag{32}
\end{align}
$$
-Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-learn.
+Performance of the different models
-
-
-$$
-\begin{align}
- R^2 = 1 - \frac{(y - \hat{y})^2}{(y - \bar{y})^2},
-\tag{45}
-\end{align}
-$$
-
-
-where \( y \) is a vector with the true values of the energy, \( \hat{y} \) is the predicted values of \( y \) from the models and \( \bar{y} \) is the mean of \( \hat{y} \).
-
-def r_squared(y, y_hat):
- return 1 - np.sum((y - y_hat) ** 2) / np.sum((y - np.mean(y_hat)) ** 2)
-
y_hat = clf.predict(X_test)
-r_test = r_squared(y_test, y_hat)
-sk_r_test = clf.score(X_test, y_test)
-
-assert abs(r_test - sk_r_test) < 1e-2
-
Performance as function of the regularization parameter
+Performance as function of the regularization parameter
lambdas = np.logspace(-4, 5, 10)
train_errors = {
- "ols_own": np.zeros(lambdas.size),
"ols_sk": np.zeros(lambdas.size),
- "ridge_own": np.zeros(lambdas.size),
"ridge_sk": np.zeros(lambdas.size),
"lasso_sk": np.zeros(lambdas.size)
}
test_errors = {
- "ols_own": np.zeros(lambdas.size),
"ols_sk": np.zeros(lambdas.size),
- "ridge_own": np.zeros(lambdas.size),
"ridge_sk": np.zeros(lambdas.size),
"lasso_sk": np.zeros(lambdas.size)
}
@@ -4043,30 +4080,6 @@ plot_counter = 1
fig = plt.figure(figsize=(32, 54))
for i, _lambda in enumerate(tqdm.tqdm(lambdas)):
- omega = get_ols_weights(X_train_own, y_train)
- y_hat_train = X_train_own @ omega
- y_hat_test = X_test_own @ omega
-
- train_errors["ols_own"][i] = r_squared(y_train, y_hat_train)
- test_errors["ols_own"][i] = r_squared(y_test, y_hat_test)
-
- plt.subplot(10, 5, plot_counter)
- plt.imshow(omega[1:].reshape(L, L), **cmap_args)
- plt.title("Home made OLS")
- plot_counter += 1
-
- omega = get_ridge_weights(X_train_own, y_train, _lambda)
- y_hat_train = X_train_own @ omega
- y_hat_test = X_test_own @ omega
-
- train_errors["ridge_own"][i] = r_squared(y_train, y_hat_train)
- test_errors["ridge_own"][i] = r_squared(y_test, y_hat_test)
-
- plt.subplot(10, 5, plot_counter)
- plt.imshow(omega[1:].reshape(L, L), **cmap_args)
- plt.title(r"Home made ridge, $\lambda = %.4f$" % _lambda)
- plot_counter += 1
-
for key, method in zip(
["ols_sk", "ridge_sk", "lasso_sk"],
[skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)]
@@ -4086,7 +4099,7 @@ fig = plt.figure(figsize=(32,
-
Finding the optimal value of \( \lambda \)
+Finding the optimal value of \( \lambda \)
fig = plt.figure(figsize=(20, 14))
colors = {
- "ols_own": "b",
- "ridge_own": "g",
"ols_sk": "r",
"ridge_sk": "y",
"lasso_sk": "c"
@@ -4134,9 +4145,6 @@ colors = {
label="Test {0}".format(key),
linewidth=4.0
)
-#plt.semilogx(lambdas, train_errors["ols_own"], label="Train (OLS own)")
-#plt.semilogx(lambdas, test_errors["ols_own"], label="Test (OLS own)")
-
plt.legend(loc="best", fontsize=18)
plt.xlabel(r"$\lambda$", fontsize=18)
plt.ylabel(r"$R^2$", fontsize=18)
@@ -4145,11 +4153,265 @@ plt.show()
Further Exercises
+
+Exercise 1
+
+x = np.random.rand(100,1)
+y = 5*x*x+0.1*np.random.randn(100,1)
+
+
+
+$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
+\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
+$$
+
+
+and the \( R^2 \) score function.
+If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as
+
+$$
+R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
+$$
+
+
+where we have defined the mean value of \( \hat{y} \) as
+
+$$
+\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
+$$
+
+
+Exercise 2, variance of the parameters \( \beta \) in linear regression
+
+
+$$
+\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2,
+$$
+
+
+with
+
+$$
+\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2,
+$$
+
+
+where we have assumed that we fit a function of degree \( p-1 \) (for example a polynomial in \( x \)).
+
+Exercise 3
+
+x = np.random.rand(100,1)
+y = 5*x*x+0.1*np.random.randn(100,1)
+
+
+
+$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
+\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
+$$
+
+
+and the \( R^2 \) score function.
+If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as
+
+$$
+R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
+$$
+
+
+where we have defined the mean value of \( \hat{y} \) as
+
+$$
+\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
+$$
+
+
+Discuss these quantities as functions of the variable \( \lambda \) in the Ridge and Lasso regression methods.
+
+Exercise 4
+
+
+$$
+\begin{align*}
+f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\
+&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }.
+\end{align*}
+$$
+
+
+from mpl_toolkits.mplot3d import Axes3D
+import matplotlib.pyplot as plt
+from matplotlib import cm
+from matplotlib.ticker import LinearLocator, FormatStrFormatter
+import numpy as np
+from random import random, seed
+
+fig = plt.figure()
+ax = fig.gca(projection='3d')
+
+# Make data.
+x = np.arange(0, 1, 0.05)
+y = np.arange(0, 1, 0.05)
+x, y = np.meshgrid(x,y)
+
+
+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
+
+
+z = FrankeFunction(x, y)
+
+# Plot the surface.
+surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
+ linewidth=0, antialiased=False)
+
+# Customize the z axis.
+ax.set_zlim(-0.10, 1.40)
+ax.zaxis.set_major_locator(LinearLocator(10))
+ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
+
+# Add a color bar which maps values to colors.
+fig.colorbar(surf, shrink=0.5, aspect=5)
+
+plt.show()
+
+$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
+\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
+$$
+
+
+and the \( R^2 \) score function.
+If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as
+
+$$
+R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
+$$
+
+
+where we have defined the mean value of \( \hat{y} \) as
+
+$$
+\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
+$$
+
+
+
Oct 18, 2018
Jun 10, 2019
-Regression analysis, overarching aims
+Why Linear Regression (aka Ordinary Least Squares and family)
+
+
+
+
+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.
+
+
+
+Regression analysis, overarching aims
- The goal of the regression analysis is to extract/exploit relationship between \( y_i \) and \( \hat{x}_i \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions .
+ The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{X} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.
-Regression analysis, overarching aims II
+Regression analysis, overarching aims II
-General linear models
+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, follows
+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
+Generalizing the fitting procedure as a linear algebra problem
-Optimizing our parameters
+Optimizing our parameters
-Optimizing our parameters, more details
+Our model for the nuclear binding energies
+
+# Common imports
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from IPython.display import display
+import os
+
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
+
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
+
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
+
+infile = open(data_path("MassEval2016.dat"),'r')
+
+
+# Read the experimental data with Pandas
+Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
+ names=('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)
+
+# 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.
+Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')
+Masses = Masses.dropna()
+# Convert from keV to MeV.
+Masses['Ebinding'] /= 1000
+
+# Group the DataFrame by nucleon number, A.
+Masses = Masses.groupby('A')
+# Find the rows of the grouped DataFrame with the maximum binding energy.
+Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
+A = Masses['A']
+Z = Masses['Z']
+N = Masses['N']
+Element = Masses['Element']
+Energies = Masses['Ebinding']
+
+# Now we set up the design matrix X
+X = np.zeros((len(A),5))
+X[:,0] = 1
+X[:,1] = A
+X[:,2] = A**(2.0/3.0)
+X[:,3] = A**(-1.0/3.0)
+X[:,4] = A**(-1.0)
+# Then nice printout using pandas
+DesignMatrix = pd.DataFrame(X)
+DesignMatrix.index = A
+DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
+display(DesignMatrix)
+
+
+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
-Interpretations and optimizing our parameters
+Interpretations and optimizing our parameters
+
+Own code for Ordinary Least Squares
+
+# 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
+
fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
+ytildenp = np.dot(fit,X.T)
+
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.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',
+ label='Fit')
+ax.legend()
+save_fig("Masses2016OLS")
+plt.show()
+
+
+Adding error analysis and training set up
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
+
print(R2(Energies,ytilde))
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+print(MSE(Energies,ytilde))
+
def RelativeError(y_data,y_model):
+ return abs((y_data-y_model)/y_data)
+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
-The \( \chi^2 \) function
+The \( \chi^2 \) function
-The \( \chi^2 \) function
+The \( \chi^2 \) function
-The \( \chi^2 \) function
+The \( \chi^2 \) function
-Simple regression model
-We are now ready to write our first program which aims at solving the above linear regression equations. We start with data we have produced ourselves, in this case normally distributed random numbers along the \( x \)-axis. These numbers define then the value of a function \( y(x)=4+3x+N(0,1) \). Thereafter we order the \( x \) values and employ our linear regression algorithm to set up the best fit. Here we find it useful to use the numpy function \( c\_ \) arrays where arrays are stacked along their last axis after being upgraded to at least two dimensions with ones post-pended to the shape. The following examples help in understanding what happens
+Fitting an Equation of State for Dense Nuclear Matter
+
+
+
+The code
+
import numpy as np
-print(np.c_[np.array([1,2,3]), np.array([4,5,6])])
-print(np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])])
-
# Importing various packages
-from random import random, seed
+
# Common imports
+import os
import numpy as np
+import pandas as pd
import matplotlib.pyplot as plt
-
-x = 2*np.random.rand(100,1)
-y = 4+3*x+np.random.randn(100,1)
-
-xb = np.c_[np.ones((100,1)), x]
-beta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
-xnew = np.array([[0],[2]])
-xbnew = np.c_[np.ones((2,1)), xnew]
-ypredict = xbnew.dot(beta)
-
-plt.plot(xnew, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0,2.0,0, 15.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Linear Regression')
-plt.show()
-
-
-Simple regression model, now using scikit-learn
-
-# Importing various packages
-from random import random, seed
-import numpy as np
import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression
+import sklearn.linear_model as skl
+from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
-x = 2*np.random.rand(100,1)
-y = 4+3*x+np.random.randn(100,1)
-linreg = LinearRegression()
-linreg.fit(x,y)
-xnew = np.array([[0],[2]])
-ypredict = linreg.predict(xnew)
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
-plt.plot(xnew, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0,2.0,0, 15.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Random numbers ')
-plt.show()
-
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
-Simple linear regression model using scikit-learn
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
-# Importing various packages
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression
-
-x = np.random.rand(100,1)
-y = 2*x+np.random.randn(100,1)
-linreg = LinearRegression()
-linreg.fit(x,y)
-xnew = np.array([[0],[1]])
-ypredict = linreg.predict(xnew)
-
-plt.plot(xnew, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0,1.0,0, 5.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Simple Linear Regression')
-plt.show()
-
-
-Simple linear regression model
-
-
-
-Less noise
-
-
-
-How to study our fits
-
-
-
-Minimizing the cost function
-
-
-
-Relative error
-
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression
-
-x = np.random.rand(100,1)
-y = 5*x+0.01*np.random.randn(100,1)
-linreg = LinearRegression()
-linreg.fit(x,y)
-ypredict = linreg.predict(x)
-
-plt.plot(x, np.abs(ypredict-y)/abs(y), "ro")
-plt.axis([0,1.0,0.0, 0.5])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$\epsilon_{\mathrm{relative}}$')
-plt.title(r'Relative error')
-plt.show()
-
-
-The richness of scikit-learn
-
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression
-from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error
-
-x = np.random.rand(100,1)
-y = 2.0+ 5*x+0.5*np.random.randn(100,1)
-linreg = LinearRegression()
-linreg.fit(x,y)
-ypredict = linreg.predict(x)
-print('The intercept alpha: \n', linreg.intercept_)
-print('Coefficient beta : \n', linreg.coef_)
+# We use now Scikit-Learn's linear regressor and ridge regressor
+# OLS part
+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(y, ypredict))
+print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde))
# Explained variance score: 1 is perfect prediction
-print('Variance score: %.2f' % r2_score(y, ypredict))
-# Mean squared log error
-print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) )
+print('Variance score: %.2f' % r2_score(Energies, ytilde))
# Mean absolute error
-print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict))
-plt.plot(x, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0.0,1.0,1.5, 7.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Linear Regression fit ')
+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
+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))
+# Explained variance score: 1 is perfect prediction
+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_)
+
+fig, ax = plt.subplots()
+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')
+ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',
+ label='OLS')
+ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g',
+ label='Ridge $\lambda = 0.1$')
+ax.legend()
+save_fig("EoSfitting")
plt.show()
-
-Functions in scikit-learn
+The above simple polynomial in density \( \rho \) gives an excellent fit
+to the data. Can you give an interpretation of the various powers of \( \rho \)?
-Other functions in scikit-learn
+Splitting our Data in Training and Test data
-
-The mean absolute error and other functions in scikit-learn
-
-
-
-Cubic polynomial in scikit-learn
-
-import matplotlib.pyplot as plt
-import numpy as np
-import random
-from sklearn.linear_model import Ridge
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.pipeline import make_pipeline
-from sklearn.linear_model import LinearRegression
-
-x=np.linspace(0.02,0.98,200)
-noise = np.asarray(random.sample((range(200)),200))
-y=x**3*noise
-yn=x**3*100
-poly3 = PolynomialFeatures(degree=3)
-X = poly3.fit_transform(x[:,np.newaxis])
-clf3 = LinearRegression()
-clf3.fit(X,y)
-
-Xplot=poly3.fit_transform(x[:,np.newaxis])
-poly3_plot=plt.plot(x, clf3.predict(Xplot), label='Cubic Fit')
-plt.plot(x,yn, color='red', label="True Cubic")
-plt.scatter(x, y, label='Data', color='orange', s=15)
-plt.legend()
-plt.show()
-
-def error(a):
- for i in y:
- err=(y-yn)/yn
- return abs(np.sum(err))/len(err)
-
-print (error(y))
-
-
-Polynomial Regression
-# Importing various packages
-from math import exp, sqrt
-from random import random, seed
+
import os
import numpy as np
+import pandas as pd
import matplotlib.pyplot as plt
+from sklearn.model_selection import train_test_split
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
-m = 100
-x = 2*np.random.rand(m,1)+4.
-y = 4+3*x*x+ +x-np.random.randn(m,1)
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
-xb = np.c_[np.ones((m,1)), x]
-theta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
-xnew = np.array([[0],[2]])
-xbnew = np.c_[np.ones((2,1)), xnew]
-ypredict = xbnew.dot(theta)
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
-plt.plot(xnew, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0,2.0,0, 15.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Random numbers ')
-plt.show()
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+infile = open(data_path("EoS.csv"),'r')
+
+# Read the EoS data as csv file and organized into two arrays with density and energies
+EoS = pd.read_csv(infile, names=('Density', 'Energy'))
+EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
+EoS = EoS.dropna()
+Energies = EoS['Energy']
+Density = EoS['Density']
+# The design matrix now as function of various polytrops
+X = np.zeros((len(Density),5))
+X[:,0] = 1
+X[:,1] = Density**(2.0/3.0)
+X[:,2] = Density
+X[:,3] = Density**(4.0/3.0)
+X[:,4] = Density**(5.0/3.0)
+# We split the data in test and training data
+X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
+# 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))
Linking the regression analysis with a statistical interpretation
-
-
-Expectation value and variance
+The singular value decomposition
-
-The singular value decompostion
-From standard regression to Ridge regressions
+The Ising model
+
+import numpy as np
+import matplotlib.pyplot as plt
+from mpl_toolkits.axes_grid1 import make_axes_locatable
+import seaborn as sns
+import scipy.linalg as scl
+from sklearn.model_selection import train_test_split
+import tqdm
+sns.set(color_codes=True)
+cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
+
+L = 40
+n = int(1e4)
+
+spins = np.random.choice([-1, 1], size=(n, L))
+J = 1.0
+
+energies = np.zeros(n)
+
+for i in range(n):
+ energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
+
+
+Reformulating the problem to suit regression
+
+X = np.zeros((n, L ** 2))
+for i in range(n):
+ X[i] = np.outer(spins[i], spins[i]).ravel()
+y = energies
+X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
+
+
+Linear regression
+
+X_train_own = np.concatenate(
+ (np.ones(len(X_train))[:, np.newaxis], X_train),
+ axis=1
+)
+X_test_own = np.concatenate(
+ (np.ones(len(X_test))[:, np.newaxis], X_test),
+ axis=1
+)
+
def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray:
+ return scl.inv(x.T @ x) @ (x.T @ y)
+beta = ols_inv(X_train_own, y_train)
+
+
+Singular Value decomposition
+
+def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray:
+ u, s, v = scl.svd(x)
+ return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
+
beta = ols_svd(X_train_own,y_train)
+
J = beta[1:].reshape(L, L)
+fig = plt.figure(figsize=(20, 14))
+im = plt.imshow(J, **cmap_args)
+plt.title("OLS", fontsize=18)
+plt.xticks(fontsize=18)
+plt.yticks(fontsize=18)
+cb = fig.colorbar(im)
+cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
+plt.show()
+
+
+Linear Regression Problems
-Fixing the singularity
+Fixing the singularity
-Fitting vs. predicting when data is in the model class
+Basic math of the SVD
+
+The SVD, a Fantastic Algorithm
+
+
+
+Another Example
+
+
+
+Economy-size SVD
+
+
+
+Mathematical Properties
+
+
+
+Ridge and LASSO Regression
+
+
+
+More on Ridge Regression
+
+
+
+Interpreting the Ridge results
+
+
+
+More interpretations
+
+
+
+Where are we going?
+
+
-
-Repeat the exercises above for \( f(x)=2x \) , \( Ntrain=100 \) , and \( \sigma=1 \) . What changes?
-Summarize what you have learned about the relationship between model complexity (number of parameters), goodness of fit on training data, and the ability to predict well.
+This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods.
-Fitting versus predicting when data is not in the model class
-
-
-
-
-Summarize what you think you learned about the relationship of knowing the true model class and predictive power.
-
-
-
-An example code without the model assessment part
-
-import numpy as np
-import sklearn as sk
-from sklearn import datasets, linear_model
-from sklearn.preprocessing import PolynomialFeatures
-
-import matplotlib as mpl
-from matplotlib import pyplot as plt
-
-%matplotlib notebook
-
-# The Training Data
-
-N_train=100
-
-sigma_train=1;
-
-# Train on integers
-x=np.linspace(0.05,0.95,N_train)
-# Draw random noise
-s = sigma_train*np.random.randn(N_train)
-
-#linear
-y=2*x+s
-
-#Tenth Order
-#y=2*x-10*x**5+15*x**10+s
-
-p1=plt.plot(x,y, "o",ms=15, label='Training')
-
-#Linear Regression
-# Create linear regression object
-clf = linear_model.LinearRegression()
-
-# Train the model using the training sets
-clf.fit(x[:, np.newaxis], y)
-# The coefficients
-
-xplot=np.linspace(0.02,0.98,200)
-linear_plot=plt.plot(xplot, clf.predict(xplot[:, np.newaxis]),label='Linear')
-
-#Polynomial Regression
-
-
-poly3 = PolynomialFeatures(degree=3)
-X = poly3.fit_transform(x[:,np.newaxis])
-clf3 = linear_model.LinearRegression()
-clf3.fit(X,y)
-
-
-Xplot=poly3.fit_transform(xplot[:,np.newaxis])
-poly3_plot=plt.plot(xplot, clf3.predict(Xplot), label='Poly 3')
-
-
-
-#poly5 = PolynomialFeatures(degree=5)
-#X = poly5.fit_transform(x[:,np.newaxis])
-#clf5 = linear_model.LinearRegression()
-#clf5.fit(X,y)
-
-#Xplot=poly5.fit_transform(xplot[:,np.newaxis])
-#plt.plot(xplot, clf5.predict(Xplot), 'r--',linewidth=1)
-
-poly10 = PolynomialFeatures(degree=10)
-X = poly10.fit_transform(x[:,np.newaxis])
-clf10 = linear_model.LinearRegression()
-clf10.fit(X,y)
-
-Xplot=poly10.fit_transform(xplot[:,np.newaxis])
-poly10_plot=plt.plot(xplot, clf10.predict(Xplot), label='Poly 10')
-
-axes = plt.gca()
-axes.set_ylim([-7,7])
-
-handles, labels=axes.get_legend_handles_labels()
-plt.legend(handles,labels, loc='lower center')
-plt.xlabel("$x$")
-plt.ylabel("$y$")
-Title="$N=$"+str(N_train)+", $\sigma=$"+str(sigma_train)
-plt.title(Title+" (train)")
-plt.tight_layout()
-plt.show()
-
Generating test data
-# Generate Test Data
-
-#Number of test data
-N_test=20
-
-sigma_test=sigma_train
-
-max_x=1.2
-x_test=max_x*np.random.random(N_test)
-# Draw random noise
-s_test = sigma_test*np.random.randn(N_test)
-
-#Linear
-y_test=2*x_test+s_test
-#Tenth order
-#y_test=2*x_test-10*x_test**5+15*x_test**10+s_test
-
-#Make design matrices for prediction
-x_plot=np.linspace(0,max_x, 200)
-X3 = poly3.fit_transform(x_plot[:,np.newaxis])
-X10 = poly10.fit_transform(x_plot[:,np.newaxis])
-
-%matplotlib notebook
-
-fig = plt.figure()
-p1=plt.plot(x_test,y_test.transpose(), 'o', ms=12, label='data')
-p2=plt.plot(x_plot,clf.predict(x_plot[:,np.newaxis]), label='linear')
-p3=plt.plot(x_plot,clf3.predict(X3), label='3rd order')
-p10=plt.plot(x_plot,clf10.predict(X10), label='10th order')
-
-
-plt.legend(loc=2)
-plt.xlabel('$x$')
-plt.ylabel('$y$')
-plt.legend(loc='best')
-plt.title(Title+" (pred.)")
-plt.tight_layout()
-plt.show()
-
-
-How can we effectively evaluate the various models?
-
-
-
-Code examples for Ridge and Lasso Regression
-
-import matplotlib.pyplot as plt
-import numpy as np
-from sklearn import linear_model
-from sklearn.linear_model import LinearRegression
-from sklearn.metrics import mean_squared_error, r2_score
-
-#creating data with random noise
-x=np.arange(50)
-
-delta=np.random.uniform(-2.5,2.5, size=(50))
-np.random.shuffle(delta)
-y =0.5*x+5+delta
-
-#arranging data into 2x50 matrix
-a=np.array(x) #inputs
-b=np.array(y) #outputs
-
-#Split into training and test
-X_train=a[:37, np.newaxis]
-X_test=a[37:, np.newaxis]
-y_train=b[:37]
-y_test=b[37:]
-
-print ("X_train: ", X_train.shape)
-print ("y_train: ", y_train.shape)
-print ("X_test: ", X_test.shape)
-print ("y_test: ", y_test.shape)
-
-print ("------------------------------------")
-
-print ("Ordinary Least Squares")
-#Add Ordinary Least Squares fit
-reg=LinearRegression()
-reg.fit(X_train, y_train)
-pred=reg.predict(X_test)
-print ("Prediction Shape: ", pred.shape)
-
-print('Coefficients: \n', reg.coef_)
-# The mean squared error
-print("Mean squared error: %.2f"
- % mean_squared_error(y_test, pred))
-# Explained variance score: 1 is perfect prediction
-print('Variance score: %.2f' % r2_score(y_test, pred))
-
-#plot
-plt.scatter(X_test,y_test,color='green', label="Training Data")
-plt.plot(X_test, pred, color='black', label="Fit Line")
-plt.legend()
-plt.show()
-
-print ("------------------------------------")
-
-print ("Ridge Regression")
-
-ridge=linear_model.RidgeCV(alphas=[0.1,1.0,10.0])
-ridge.fit(X_train,y_train)
-print ("Ridge Coefficient: ",ridge.coef_)
-print ("Ridge Intercept: ", ridge.intercept_)
-#Look into graphing with Ridge fit
-
-print ("------------------------------------")
-
-print ("Lasso")
-lasso=linear_model.Lasso(alpha=0.1)
-lasso.fit(X_train,y_train)
-predl=lasso.predict(X_test)
-print("Lasso Coefficient: ", lasso.coef_)
-print("Lasso Intercept: ", lasso.intercept_)
-plt.scatter(X_test,y_test,color='green', label="Training Data")
-plt.plot(X_test, predl, color='blue', label="Lasso")
-plt.legend()
-plt.show()
-
-
-A second-order polynomial with Ridge and Lasso
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.linear_model import Ridge
-from sklearn.metrics import r2_score
-
-np.random.seed(4155)
-
-n_samples = 100
-
-x = np.random.rand(n_samples,1)
-y = 5*x*x + 0.1*np.random.rand(n_samples,1)
-
-# Centering x and y.
-x_ = x - np.mean(x)
-y_ = y - np.mean(y) # beta_0 = mean(y)
-
-X = np.c_[np.ones((n_samples,1)), x, x**2]
-X_ = np.c_[x_, x_**2]
-
-
-### 1.
-lmb_values = [1e-4, 1e-3, 1e-2, 10, 1e2, 1e4]
-num_values = len(lmb_values)
-
-## Ridge-regression of centered and not centered data
-beta_ridge = np.zeros((3,num_values))
-beta_ridge_centered = np.zeros((3,num_values))
-
-I3 = np.eye(3)
-I2 = np.eye(2)
-
-for i,lmb in enumerate(lmb_values):
- beta_ridge[:,i] = (np.linalg.inv( X.T @ X + lmb*I3) @ X.T @ y).flatten()
- beta_ridge_centered[1:,i] = (np.linalg.inv( X_.T @ X_ + lmb*I2) @ X_.T @ y_).flatten()
-
-# sett beta_0 = np.mean(y)
-beta_ridge_centered[0,:] = np.mean(y)
-
-## OLS (ordinary least squares) solution
-beta_ls = np.linalg.inv( X.T @ X ) @ X.T @ y
-
-## Evaluate the models
-pred_ls = X @ beta_ls
-pred_ridge = X @ beta_ridge
-pred_ridge_centered = X_ @ beta_ridge_centered[1:] + beta_ridge_centered[0,:]
-
-## Plot the results
-
-# Sorting
-sort_ind = np.argsort(x[:,0])
-
-x_plot = x[sort_ind,0]
-x_centered_plot = x_[sort_ind,0]
-
-pred_ls_plot = pred_ls[sort_ind,0]
-pred_ridge_plot = pred_ridge[sort_ind,:]
-pred_ridge_centered_plot = pred_ridge_centered[sort_ind,:]
-
-# Plott not centered
-plt.plot(x_plot,pred_ls_plot,label='ls')
-
-for i in range(num_values):
- plt.plot(x_plot,pred_ridge_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])
-
-plt.plot(x,y,'ro')
-
-plt.title('linear regression on un-centered data')
-plt.legend()
-
-# Plott centered
-plt.figure()
-
-for i in range(num_values):
- plt.plot(x_centered_plot,pred_ridge_centered_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])
-
-plt.plot(x_,y,'ro')
-
-plt.title('linear regression on centered data')
-plt.legend()
-
-
-# 2.
-
-pred_ridge_scikit = np.zeros((n_samples,num_values))
-for i,lmb in enumerate(lmb_values):
- pred_ridge_scikit[:,i] = (Ridge(alpha=lmb,fit_intercept=False).fit(X,y).predict(X)).flatten() # fit_intercept=False fordi bias er allerede i X
-
-plt.figure()
-
-plt.plot(x_plot,pred_ls_plot,label='ls')
-
-for i in range(num_values):
- plt.plot(x_plot,pred_ridge_scikit[sort_ind,i],label='scikit-ridge, lmb=%g'%lmb_values[i])
-
-plt.plot(x,y,'ro')
-plt.legend()
-plt.title('linear regression using scikit')
-
-plt.show()
-
-### R2-score of the results
-for i in range(num_values):
- print('lambda = %g'%lmb_values[i])
- print('r2 for scikit: %g'%r2_score(y,pred_ridge_scikit[:,i]))
- print('r2 for own code, not centered: %g'%r2_score(y,pred_ridge[:,i]))
- print('r2 for own, centered: %g\n'%r2_score(y,pred_ridge_centered[:,i]))
-
-
-Resampling methods
+Resampling methods
-Resampling approaches can be computationally expensive
+Resampling approaches can be computationally expensive
-Why resampling methods ?
+Why resampling methods ?
-
-Statistical analysis
+Statistical analysis
-
-
-
-Statistics
+Statistics
-Statistics, moments
+Statistics, moments
-Statistics, central moments
+Statistics, central moments
-Statistics, covariance
+Statistics, covariance
-Statistics, more covariance
+Statistics, more covariance
-Statistics, independent variables
+Statistics, independent variables
-Statistics, more variance
+Statistics, more variance
-Statistics and stochastic processes
+Statistics and stochastic processes
Statistics and sample variables
+Statistics and sample variables
-Statistics, sample variance and covariance
+Statistics, sample variance and covariance
-Statistics, law of large numbers
+Statistics, law of large numbers
-Statistics, more on sample error
+Statistics, more on sample error
-Statistics
+Statistics
-Statistics, central limit theorem
+Statistics, central limit theorem
-Statistics, more technicalities
+Statistics, more technicalities
-Statistics
+Statistics
-Statistics and sample variance
+Statistics and sample variance
-Statistics, uncorrelated results
+Statistics, uncorrelated results
-Statistics, computations
+Statistics, computations
-Statistics, more on computations of errors
+Statistics, more on computations of errors
-Statistics, wrapping up 1
+Statistics, wrapping up 1
-Statistics, final expression
+Statistics, final expression
-Statistics, effective number of correlations
+Statistics, effective number of correlations
+
-Log-likelihood
+Linking the regression analysis with a statistical interpretation
+
+Assumptions made
+
+
+
+Expectation value and variance
+
+
+
+Expectation value and variance for \( \boldsymbol{\beta} \)
+
+Cross-validation
+Cross-validation
-Computationally expensive
+Computationally expensive
Various steps in cross-validation
+Various steps in cross-validation
How to set up the cross-validation for Ridge and/or Lasso
+How to set up the cross-validation for Ridge and/or Lasso
$$
\begin{align*}
-\hat{\beta}_{-i}(\lambda) & = ( \hat{X}_{-i, \ast}^{\top}
-\hat{X}_{-i, \ast} + \lambda \hat{I}_{pp})^{-1}
-\hat{X}_{-i, \ast}^{\top} \hat{y}_{-i}
+\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T}
+\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1}
+\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i}
\end{align*}
$$
-
$$
\begin{align*}
-\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \hat{\beta}_{-i}(\lambda), \hat{\sigma}_{-i}^2(\lambda)]\}.
+\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}.
\end{align*}
$$
@@ -2689,31 +3082,7 @@ $$
-Predicted Residual Error Sum of Squares
-
-
-Resampling methods: Jackknife and Bootstrap
+Resampling methods: Jackknife and Bootstrap
-Resampling methods: Jackknife
+Resampling methods: Jackknife
-Resampling methods: Jackknife estimator
-
-
-
Jackknife code example
Resampling methods: Bootstrap background
@@ -2880,7 +3235,7 @@ result in some asymptotic sense? The answer is yes.
Instead of generating the histogram for the relative
frequency of the observation \( X_i \), just draw the values
\( (X_1^*,X_2^*,\cdots,X_n^*) \) with replacement from the vector
-\( \hat{X} \).
+\( \boldsymbol{X} \).
@@ -2891,19 +3246,41 @@ frequency of the observation \( X_i \), just draw the values
The independent bootstrap works like this:
-
-When you are done, you can draw a histogram of the relative frequency of \( \widehat \theta^* \). This is your estimate of the probability distribution \( p(t) \). Using this probability distribution you can estimate any statistics thereof. In principle you never draw the histogram of the relative frequency of \( \widehat{\theta}^* \). Instead you use the estimators corresponding to the statistic of interest. For example, if you are interested in estimating the variance of \( \widehat \theta \), apply the etsimator \( \widehat \sigma^2 \) to the values \( \widehat \theta ^* \).
+When you are done, you can draw a histogram of the relative frequency
+of \( \widehat \theta^* \). This is your estimate of the probability
+distribution \( p(t) \). Using this probability distribution you can
+estimate any statistics thereof. In principle you never draw the
+histogram of the relative frequency of \( \widehat{\theta}^* \). Instead
+you use the estimators corresponding to the statistic of interest. For
+example, if you are interested in estimating the variance of \( \widehat
+\theta \), apply the etsimator \( \widehat \sigma^2 \) to the values
+\( \widehat \theta ^* \).
Code example for the Bootstrap method
-The following code starts with a Gaussian distribution with mean value \( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data used in the bootstrap analysis. The bootstrap analysis returns a data set after a given number of bootstrap operations (as many as we have data points). This data set consists of estimated mean values for each bootstrap operation. The histogram generated by the bootstrap method shows that the distribution for these mean values is also a Gaussian, centered around the mean value \( \mu=100 \) but with standard deviation \( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in this case the same as the number of original data points). The value of the standard deviation is what we expect from the central limit theorem.
+
+
-Resampling methods: Blocking
+Code Example for Cross-validation and \( k \)-fold Cross-validation
-
-Blocking Transformations
- We now define
-blocking transformations. The idea is to take the mean of subsequent
-pair of elements from \( \vec{X} \) and form a new vector
-\( \vec{X}_1 \). Continuing in the same way by taking the mean of
-subsequent pairs of elements of \( \vec{X}_1 \) we obtain \( \vec{X}_2 \), and
-so on.
-Define \( \vec{X}_i \) recursively by:
-
-$$
-\begin{align}
-(\vec{X}_0)_k &\equiv (\vec{X})_k \nonumber \\
-(\vec{X}_{i+1})_k &\equiv \frac{1}{2}\Big( (\vec{X}_i)_{2k-1} +
-(\vec{X}_i)_{2k} \Big) \qquad \text{for all} \qquad 1 \leq i \leq d-1
-\label{_auto11}
-\end{align}
-$$
-
-
-
-Blocking Transformations
-
-
-
-Blocking Transformations, getting there
-We have
-$$
-\begin{align}
-V(\overline{X}_k) = \frac{\sigma_k^2}{n_k} + \underbrace{\frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h)}_{\equiv e_k} = \frac{\sigma^2_k}{n_k} + e_k \quad \text{if} \quad \gamma_k(0) = \sigma_k^2.
-\label{_auto14}
-\end{align}
-$$
-
-The term \( e_k \) is called the truncation error:
-$$
-\begin{equation}
-e_k = \frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h).
-\label{_auto15}
-\end{equation}
-$$
-
-We can show that \( V(\overline{X}_i) = V(\overline{X}_j) \) for all \( 0 \leq i \leq d-1 \) and \( 0 \leq j \leq d-1 \).
-
-
-
-Blocking Transformations, final expressions
-
-
-
-Code examples for Blocking, Jackknife and bootstrap
-
+The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial.
from sys import argv
-from os import mkdir, path
-import time
-import numpy as np
+
import numpy as np
import matplotlib.pyplot as plt
-from matplotlib.ticker import FormatStrFormatter
-from matplotlib.font_manager import FontProperties
+from sklearn.model_selection import KFold
+from sklearn.linear_model import Ridge
+from sklearn.model_selection import cross_val_score
+from sklearn.preprocessing import PolynomialFeatures
-# Timing Decorator
-def timeFunction(f):
- def wrap(*args):
- time1 = time.time()
- ret = f(*args)
- time2 = time.time()
- print '%s Function Took: \t %0.3f s' % (f.func_name.title(), (time2-time1))
- return ret
- return wrap
+# A seed just to ensure that the random numbers are the same for every run.
+# Useful for eventual debugging.
+np.random.seed(3155)
-class dataAnalysisClass:
- # General Init functions
- def __init__(self, fileName, size=0):
- self.inputFileName = fileName
- self.loadData(size)
- self.createOutputFolder()
- self.avg = np.average(self.data)
- self.var = np.var(self.data)
- self.std = np.std(self.data)
+# Generate the data.
+nsamples = 100
+x = np.random.randn(nsamples)
+y = 3*x**2 + np.random.randn(nsamples)
- def loadData(self, size=0):
- if size != 0:
- with open(self.inputFileName) as inputFile:
- self.data = np.zeros(size)
- for x in xrange(size):
- self.data[x] = float(next(inputFile))
- else:
- self.data = np.loadtxt(self.inputFileName)
+## Cross-validation on Ridge regression using KFold only
- # Statistical Analysis with Multiple Methods
- def runAllAnalyses(self):
- if len(self.data) <= 100000:
- print "Autocorrelation..."
- self.autocorrelation()
- print "Bootstrap..."
- self.bootstrap()
- print "Jackknife..."
- self.jackknife()
- print "Blocking..."
- self.blocking()
+# Decide degree on polynomial to fit
+poly = PolynomialFeatures(degree = 6)
- # Standard Autocorrelation
- @timeFunction
- def autocorrelation(self):
- self.acf = np.zeros(len(self.data)/2)
- for k in range(0, len(self.data)/2):
- self.acf[k] = np.corrcoef(np.array([self.data[0:len(self.data)-k], \
- self.data[k:len(self.data)]]))[0,1]
+# Decide which values of lambda to use
+nlambdas = 500
+lambdas = np.logspace(-3, 5, nlambdas)
- # Bootstrap
- @timeFunction
- def bootstrap(self, nBoots = 1000):
- bootVec = np.zeros(nBoots)
- for k in range(0,nBoots):
- bootVec[k] = np.average(np.random.choice(self.data, len(self.data)))
- self.bootAvg = np.average(bootVec)
- self.bootVar = np.var(bootVec)
- self.bootStd = np.std(bootVec)
+# Initialize a KFold instance
+k = 5
+kfold = KFold(n_splits = k)
- # Jackknife
- @timeFunction
- def jackknife(self):
- jackknVec = np.zeros(len(self.data))
- for k in range(0,len(self.data)):
- jackknVec[k] = np.average(np.delete(self.data, k))
- self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg)
- self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec)
- self.jackknStd = np.sqrt(self.jackknVar)
+# Perform the cross-validation to estimate MSE
+scores_KFold = np.zeros((nlambdas, k))
- # Blocking
- @timeFunction
- def blocking(self, blockSizeMax = 500):
- blockSizeMin = 1
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
+ j = 0
+ for train_inds, test_inds in kfold.split(x):
+ xtrain = x[train_inds]
+ ytrain = y[train_inds]
- self.blockSizes = []
- self.meanVec = []
- self.varVec = []
+ xtest = x[test_inds]
+ ytest = y[test_inds]
- for i in range(blockSizeMin, blockSizeMax):
- if(len(self.data) % i != 0):
- pass#continue
- blockSize = i
- meanTempVec = []
- varTempVec = []
- startPoint = 0
- endPoint = blockSize
+ Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
+ ridge.fit(Xtrain, ytrain[:, np.newaxis])
- while endPoint <= len(self.data):
- meanTempVec.append(np.average(self.data[startPoint:endPoint]))
- startPoint = endPoint
- endPoint += blockSize
- mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec)
- self.meanVec.append(mean)
- self.varVec.append(var)
- self.blockSizes.append(blockSize)
+ Xtest = poly.fit_transform(xtest[:, np.newaxis])
+ ypred = ridge.predict(Xtest)
- self.blockingAvg = np.average(self.meanVec[-200:])
- self.blockingVar = (np.average(self.varVec[-200:]))
- self.blockingStd = np.sqrt(self.blockingVar)
+ scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
+
+ j += 1
+ i += 1
+estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
- # Plot of Data, Autocorrelation Function and Histogram
- def plotAll(self):
- self.createOutputFolder()
- if len(self.data) <= 100000:
- self.plotAutocorrelation()
- self.plotData()
- self.plotHistogram()
- self.plotBlocking()
+## Cross-validation using cross_val_score from sklearn along with KFold
- # Create Output Plots Folder
- def createOutputFolder(self):
- self.outName = self.inputFileName[:-4]
- if not path.exists(self.outName):
- mkdir(self.outName)
+# kfold is an instance initialized above as:
+# kfold = KFold(n_splits = k)
- # Plot the Dataset, Mean and Std
- def plotData(self):
- # Far away plot
- font = {'fontname':'serif'}
- plt.plot(range(0, len(self.data)), self.data, 'r-', linewidth=1)
- plt.plot([0, len(self.data)], [self.avg, self.avg], 'b-', linewidth=1)
- plt.plot([0, len(self.data)], [self.avg + self.std, self.avg + self.std], 'g--', linewidth=1)
- plt.plot([0, len(self.data)], [self.avg - self.std, self.avg - self.std], 'g--', linewidth=1)
- plt.ylim(self.avg - 5*self.std, self.avg + 5*self.std)
- plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.4f'))
- plt.xlim(0, len(self.data))
- plt.ylabel(self.outName.title() + ' Monte Carlo Evolution', **font)
- plt.xlabel('MonteCarlo History', **font)
- plt.title(self.outName.title(), **font)
- plt.savefig(self.outName + "/data.eps")
- plt.savefig(self.outName + "/data.png")
- plt.clf()
+estimated_mse_sklearn = np.zeros(nlambdas)
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
- # Plot Histogram of Dataset and Gaussian around it
- def plotHistogram(self):
- binNumber = 50
- font = {'fontname':'serif'}
- count, bins, ignore = plt.hist(self.data, bins=np.linspace(self.avg - 5*self.std, self.avg + 5*self.std, binNumber))
- plt.plot([self.avg, self.avg], [0,np.max(count)+10], 'b-', linewidth=1)
- plt.ylim(0,np.max(count)+10)
- plt.ylabel(self.outName.title() + ' Histogram', **font)
- plt.xlabel(self.outName.title() , **font)
- plt.title('Counts', **font)
+ X = poly.fit_transform(x[:, np.newaxis])
+ estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
- #gaussian
- norm = 0
- for i in range(0,len(bins)-1):
- norm += (bins[i+1]-bins[i])*count[i]
- plt.plot(bins, norm/(self.std * np.sqrt(2 * np.pi)) * np.exp( - (bins - self.avg)**2 / (2 * self.std**2) ), linewidth=1, color='r')
- plt.savefig(self.outName + "/hist.eps")
- plt.savefig(self.outName + "/hist.png")
- plt.clf()
+ # cross_val_score return an array containing the estimated negative mse for every fold.
+ # we have to the the mean of every array in order to get an estimate of the mse of the model
+ estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
- # Plot the Autocorrelation Function
- def plotAutocorrelation(self):
- font = {'fontname':'serif'}
- plt.plot(range(1, len(self.data)/2), self.acf[1:], 'r-')
- plt.ylim(-1, 1)
- plt.xlim(0, len(self.data)/2)
- plt.ylabel('Autocorrelation Function', **font)
- plt.xlabel('Lag', **font)
- plt.title('Autocorrelation', **font)
- plt.savefig(self.outName + "/autocorrelation.eps")
- plt.savefig(self.outName + "/autocorrelation.png")
- plt.clf()
+ i += 1
- def plotBlocking(self):
- font = {'fontname':'serif'}
- plt.plot(self.blockSizes, self.varVec, 'r-')
- plt.ylabel('Variance', **font)
- plt.xlabel('Block Size', **font)
- plt.title('Blocking', **font)
- plt.savefig(self.outName + "/blocking.eps")
- plt.savefig(self.outName + "/blocking.png")
- plt.clf()
+## Plot and compare the slightly different ways to perform cross-validation
- # Print Stuff to the Terminal
- def printOutput(self):
- print "\nSample Size: \t", len(self.data)
- print "\n=========================================\n"
- print "Sample Average: \t", self.avg
- print "Sample Variance:\t", self.var
- print "Sample Std: \t", self.std
- print "\n=========================================\n"
- print "Bootstrap Average: \t", self.bootAvg
- print "Bootstrap Variance:\t", self.bootVar
- print "Bootstrap Error: \t", self.bootStd
- print "\n=========================================\n"
- print "Jackknife Average: \t", self.jackknAvg
- print "Jackknife Variance:\t", self.jackknVar
- print "Jackknife Error: \t", self.jackknStd
- print "\n=========================================\n"
- print "Blocking Average: \t", self.blockingAvg
- print "Blocking Variance:\t", self.blockingVar
- print "Blocking Error: \t", self.blockingStd, "\n"
+plt.figure()
-# Initialize the class
-if len(argv) > 2:
- dataAnalysis = dataAnalysisClass(argv[1], int(argv[2]))
-else:
- dataAnalysis = dataAnalysisClass(argv[1])
+plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
+plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
-# Run Analyses
-dataAnalysis.runAllAnalyses()
+plt.xlabel('log10(lambda)')
+plt.ylabel('mse')
-# Plot the data
-dataAnalysis.plotAll()
+plt.legend()
-# Print Some Output
-dataAnalysis.printOutput()
+plt.show()
-The bias-variance tradeoff
+The bias-variance tradeoff
+
+Example code for Bias-Variance tradeoff
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+
+np.random.seed(2018)
+
+n = 500
+n_boostraps = 100
+degree = 18 # A quite high value, just to show.
+noise = 0.1
+
+# Make data set.
+x = np.linspace(-1, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)
+
+# Hold out some test data that is never used in training.
+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+# Combine x transformation and model into one operation.
+# Not neccesary, but convenient.
+model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
+
+# The following (m x n_bootstraps) matrix holds the column vectors y_pred
+# for each bootstrap iteration.
+y_pred = np.empty((y_test.shape[0], n_boostraps))
+for i in range(n_boostraps):
+ x_, y_ = resample(x_train, y_train)
+
+ # Evaluate the new model on the same test data each time.
+ y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
+
+# Note: Expectations and variances taken w.r.t. different training
+# data sets, hence the axis=1. Subsequent means are taken across the test data
+# set in order to obtain a total value, but before this we have error/bias/variance
+# calculated per data point in the test set.
+# Note 2: The use of keepdims=True is important in the calculation of bias as this
+# maintains the column vector form. Dropping this yields very unexpected results.
+error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+print('Error:', error)
+print('Bias^2:', bias)
+print('Var:', variance)
+print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))
+
+plt.plot(x[::5, :], y[::5, :], label='f(x)')
+plt.scatter(x_test, y_test, label='Data points')
+plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')
+plt.legend()
+plt.show()
+
+
+Understanding what happens
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+
+np.random.seed(2018)
+
+n = 40
+n_boostraps = 100
+maxdegree = 14
+
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+for degree in range(maxdegree):
+ model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
+ y_pred = np.empty((y_test.shape[0], n_boostraps))
+ for i in range(n_boostraps):
+ x_, y_ = resample(x_train, y_train)
+ y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
+
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+ variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+ print('Polynomial degree:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.plot(polydegree, np.log10(error), label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+plt.show()
+
Training and testing data
-
-
-
-Procedure to find a predictor
-
-
-
-What we want
-
-
-
-The expected generalization error
-
-
-
-Elaborating a little bit more
-
-
-
-The bias
-
-
-
-The variance
-The second term is called the variance
-$$
-Var=\sum_i E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2],
-$$
-
-Summing up
Summing up
-
-The one-dimensional Ising model, project 2
+Another Example rom Scikit-Learn's Repository
+"""
+============================
+Underfitting vs. Overfitting
+============================
+
+This example demonstrates the problems of underfitting and overfitting and
+how we can use linear regression with polynomial features to approximate
+nonlinear functions. The plot shows the function that we want to approximate,
+which is a part of the cosine function. In addition, the samples from the
+real function and the approximations of different models are displayed. The
+models have polynomial features of different degrees. We can see that a
+linear function (polynomial with degree 1) is not sufficient to fit the
+training samples. This is called **underfitting**. A polynomial of degree 4
+approximates the true function almost perfectly. However, for higher degrees
+the model will **overfit** the training data, i.e. it learns the noise of the
+training data.
+We evaluate quantitatively **overfitting** / **underfitting** by using
+cross-validation. We calculate the mean squared error (MSE) on the validation
+set, the higher, the less likely the model generalizes correctly from the
+training data.
+"""
+
+print(__doc__)
+
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.linear_model import LinearRegression
+from sklearn.model_selection import cross_val_score
+
+
+def true_fun(X):
+ return np.cos(1.5 * np.pi * X)
+
+np.random.seed(0)
+
+n_samples = 30
+degrees = [1, 4, 15]
+
+X = np.sort(np.random.rand(n_samples))
+y = true_fun(X) + np.random.randn(n_samples) * 0.1
+
+plt.figure(figsize=(14, 5))
+for i in range(len(degrees)):
+ ax = plt.subplot(1, len(degrees), i + 1)
+ plt.setp(ax, xticks=(), yticks=())
+
+ polynomial_features = PolynomialFeatures(degree=degrees[i],
+ include_bias=False)
+ linear_regression = LinearRegression()
+ pipeline = Pipeline([("polynomial_features", polynomial_features),
+ ("linear_regression", linear_regression)])
+ pipeline.fit(X[:, np.newaxis], y)
+
+ # Evaluate the models using crossvalidation
+ scores = cross_val_score(pipeline, X[:, np.newaxis], y,
+ scoring="neg_mean_squared_error", cv=10)
+
+ X_test = np.linspace(0, 1, 100)
+ plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
+ plt.plot(X_test, true_fun(X_test), label="True function")
+ plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
+ plt.xlabel("x")
+ plt.ylabel("y")
+ plt.xlim((0, 1))
+ plt.ylim((-2, 2))
+ plt.legend(loc="best")
+ plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
+ degrees[i], -scores.mean(), scores.std()))
+plt.show()
+
+
+The one-dimensional Ising model
-
-Reformulating the problem to suit regression
-
-
-Linear regression
-
-
-
-Ordinary least squares
-
-def get_ols_weights_naive(x: np.ndarray, y: np.ndarray) -> np.ndarray:
- return scl.inv(x.T @ x) @ (x.T @ y)
-omega = get_ols_weights_naive(X_train_own, y_train)
-
-
-Singular Value decomposition
-Doing the inversion directly turns out to be a bad idea as the matrix
-\( X^TX \) is singular. An alternative approach is to use the singular
-value decomposition. Using the definition of the Moore-Penrose
-pseudoinverse we can write the equation for \( \omega \) as
-
-$$
-\begin{align}
- \omega = X^{+}y,
-\label{_auto28}
-\end{align}
-$$
-
-where the pseudoinverse of \( X \) is given by
-$$
-\begin{align}
- X^{+} = \frac{X^T}{X^T X}.
-\label{_auto29}
-\end{align}
-$$
-
-def get_ols_weights(x: np.ndarray, y: np.ndarray) -> np.ndarray:
- u, s, v = scl.svd(x)
- return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
-
omega = get_ols_weights(X_train_own,y_train)
-
-
-Fitting with scikit-learn
-
-LinearRegression-model from Scikit-learn for comparison.
+We will do all fitting with Scikit-Learn,
LinearRegression-model from Scikit-learn for comparis
clf = skl.LinearRegression().fit(X_train, y_train)
J_own = omega[1:].reshape(L, L)
-J_sk = clf.coef_.reshape(L, L)
+
J_sk = clf.coef_.reshape(L, L)
fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_own, **cmap_args)
-plt.title("Home-made OLS", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-
-fig = plt.figure(figsize=(20, 14))
im = plt.imshow(J_sk, **cmap_args)
plt.title("LinearRegression from Scikit-learn", fontsize=18)
plt.xticks(fontsize=18)
@@ -3786,66 +3853,33 @@ cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=Ridge regression
+
Ridge regression
def get_ridge_weights(x: np.ndarray, y: np.ndarray, _lambda: float) -> np.ndarray:
- return x.T @ y @ scl.inv(
- x.T @ x + np.eye(x.shape[1], x.shape[1]) * _lambda
- )
-_lambda = 0.1
-omega_ridge = get_ridge_weights(X_train_own, y_train, np.array([_lambda]))
+
_lambda = 0.1
clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)
-J_ridge_own = omega_ridge[1:].reshape(L, L)
J_ridge_sk = clf_ridge.coef_.reshape(L, L)
-fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_ridge_own, **cmap_args)
-plt.title("Home-made ridge regression", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-
fig = plt.figure(figsize=(20, 14))
im = plt.imshow(J_ridge_sk, **cmap_args)
plt.title("Ridge from Scikit-learn", fontsize=18)
@@ -3859,20 +3893,20 @@ plt.show()
-LASSO regression
+LASSO regression
-Performance of the different models
-
-def r_squared(y, y_hat):
- return 1 - np.sum((y - y_hat) ** 2) / np.sum((y - np.mean(y_hat)) ** 2)
-
y_hat = clf.predict(X_test)
-r_test = r_squared(y_test, y_hat)
-sk_r_test = clf.score(X_test, y_test)
-
-assert abs(r_test - sk_r_test) < 1e-2
-
-
-Performance as function of the regularization parameter
+Performance as function of the regularization parameter
lambdas = np.logspace(-4, 5, 10)
train_errors = {
- "ols_own": np.zeros(lambdas.size),
"ols_sk": np.zeros(lambdas.size),
- "ridge_own": np.zeros(lambdas.size),
"ridge_sk": np.zeros(lambdas.size),
"lasso_sk": np.zeros(lambdas.size)
}
test_errors = {
- "ols_own": np.zeros(lambdas.size),
"ols_sk": np.zeros(lambdas.size),
- "ridge_own": np.zeros(lambdas.size),
"ridge_sk": np.zeros(lambdas.size),
"lasso_sk": np.zeros(lambdas.size)
}
@@ -3962,30 +3958,6 @@ plot_counter = 1
fig = plt.figure(figsize=(32, 54))
for i, _lambda in enumerate(tqdm.tqdm(lambdas)):
- omega = get_ols_weights(X_train_own, y_train)
- y_hat_train = X_train_own @ omega
- y_hat_test = X_test_own @ omega
-
- train_errors["ols_own"][i] = r_squared(y_train, y_hat_train)
- test_errors["ols_own"][i] = r_squared(y_test, y_hat_test)
-
- plt.subplot(10, 5, plot_counter)
- plt.imshow(omega[1:].reshape(L, L), **cmap_args)
- plt.title("Home made OLS")
- plot_counter += 1
-
- omega = get_ridge_weights(X_train_own, y_train, _lambda)
- y_hat_train = X_train_own @ omega
- y_hat_test = X_test_own @ omega
-
- train_errors["ridge_own"][i] = r_squared(y_train, y_hat_train)
- test_errors["ridge_own"][i] = r_squared(y_test, y_hat_test)
-
- plt.subplot(10, 5, plot_counter)
- plt.imshow(omega[1:].reshape(L, L), **cmap_args)
- plt.title(r"Home made ridge, $\lambda = %.4f$" % _lambda)
- plot_counter += 1
-
for key, method in zip(
["ols_sk", "ridge_sk", "lasso_sk"],
[skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)]
@@ -4005,7 +3977,7 @@ fig = plt.figure(figsize=(32,
-Finding the optimal value of \( \lambda \)
+Finding the optimal value of \( \lambda \)
fig = plt.figure(figsize=(20, 14))
colors = {
- "ols_own": "b",
- "ridge_own": "g",
"ols_sk": "r",
"ridge_sk": "y",
"lasso_sk": "c"
@@ -4053,9 +4023,6 @@ colors = {
label="Test {0}".format(key),
linewidth=4.0
)
-#plt.semilogx(lambdas, train_errors["ols_own"], label="Train (OLS own)")
-#plt.semilogx(lambdas, test_errors["ols_own"], label="Test (OLS own)")
-
plt.legend(loc="best", fontsize=18)
plt.xlabel(r"$\lambda$", fontsize=18)
plt.ylabel(r"$R^2$", fontsize=18)
@@ -4064,14 +4031,245 @@ plt.show()
+
+Further Exercises
+
+Exercise 1
+
+x = np.random.rand(100,1)
+y = 5*x*x+0.1*np.random.randn(100,1)
+
+
+
+$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
+\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
+$$
+
+and the \( R^2 \) score function.
+If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as
+$$
+R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
+$$
+
+where we have defined the mean value of \( \hat{y} \) as
+$$
+\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
+$$
+
+Exercise 2, variance of the parameters \( \beta \) in linear regression
+
+Exercise 3
+
+x = np.random.rand(100,1)
+y = 5*x*x+0.1*np.random.randn(100,1)
+
+
+
+$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
+\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
+$$
+
+and the \( R^2 \) score function.
+If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as
+$$
+R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
+$$
+
+where we have defined the mean value of \( \hat{y} \) as
+$$
+\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
+$$
+
+Discuss these quantities as functions of the variable \( \lambda \) in the Ridge and Lasso regression methods.
+
+Exercise 4
+
+from mpl_toolkits.mplot3d import Axes3D
+import matplotlib.pyplot as plt
+from matplotlib import cm
+from matplotlib.ticker import LinearLocator, FormatStrFormatter
+import numpy as np
+from random import random, seed
+
+fig = plt.figure()
+ax = fig.gca(projection='3d')
+
+# Make data.
+x = np.arange(0, 1, 0.05)
+y = np.arange(0, 1, 0.05)
+x, y = np.meshgrid(x,y)
+
+
+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
+
+
+z = FrankeFunction(x, y)
+
+# Plot the surface.
+surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
+ linewidth=0, antialiased=False)
+
+# Customize the z axis.
+ax.set_zlim(-0.10, 1.40)
+ax.zaxis.set_major_locator(LinearLocator(10))
+ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
+
+# Add a color bar which maps values to colors.
+fig.colorbar(surf, shrink=0.5, aspect=5)
+
+plt.show()
+
Oct 18, 2018
Jun 10, 2019
-Regression analysis, overarching aims
+Why Linear Regression (aka Ordinary Least Squares and family)
+
+
+
+
+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.
+
+
+
+Regression analysis, overarching aims
- The goal of the regression analysis is to extract/exploit relationship between \( y_i \) and \( \hat{x}_i \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions .
+ The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{X} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.
-Regression analysis, overarching aims II
+Regression analysis, overarching aims II
-General linear models
+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, follows
+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
+Generalizing the fitting procedure as a linear algebra problem
-Optimizing our parameters
+Optimizing our parameters
-Optimizing our parameters, more details
+Our model for the nuclear binding energies
+
+# Common imports
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from IPython.display import display
+import os
+
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
+
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
+
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
+
+infile = open(data_path("MassEval2016.dat"),'r')
+
+
+# Read the experimental data with Pandas
+Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
+ names=('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)
+
+# 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.
+Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')
+Masses = Masses.dropna()
+# Convert from keV to MeV.
+Masses['Ebinding'] /= 1000
+
+# Group the DataFrame by nucleon number, A.
+Masses = Masses.groupby('A')
+# Find the rows of the grouped DataFrame with the maximum binding energy.
+Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
+A = Masses['A']
+Z = Masses['Z']
+N = Masses['N']
+Element = Masses['Element']
+Energies = Masses['Ebinding']
+
+# Now we set up the design matrix X
+X = np.zeros((len(A),5))
+X[:,0] = 1
+X[:,1] = A
+X[:,2] = A**(2.0/3.0)
+X[:,3] = A**(-1.0/3.0)
+X[:,4] = A**(-1.0)
+# Then nice printout using pandas
+DesignMatrix = pd.DataFrame(X)
+DesignMatrix.index = A
+DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
+display(DesignMatrix)
+
+
+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
-Interpretations and optimizing our parameters
+Interpretations and optimizing our parameters
+
+Own code for Ordinary Least Squares
+
+# 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
+
fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
+ytildenp = np.dot(fit,X.T)
+
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.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',
+ label='Fit')
+ax.legend()
+save_fig("Masses2016OLS")
+plt.show()
+
+
+Adding error analysis and training set up
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
+
print(R2(Energies,ytilde))
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+print(MSE(Energies,ytilde))
+
def RelativeError(y_data,y_model):
+ return abs((y_data-y_model)/y_data)
+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
-The \( \chi^2 \) function
+The \( \chi^2 \) function
-The \( \chi^2 \) function
+The \( \chi^2 \) function
-The \( \chi^2 \) function
+The \( \chi^2 \) function
-Simple regression model
-We are now ready to write our first program which aims at solving the above linear regression equations. We start with data we have produced ourselves, in this case normally distributed random numbers along the \( x \)-axis. These numbers define then the value of a function \( y(x)=4+3x+N(0,1) \). Thereafter we order the \( x \) values and employ our linear regression algorithm to set up the best fit. Here we find it useful to use the numpy function \( c\_ \) arrays where arrays are stacked along their last axis after being upgraded to at least two dimensions with ones post-pended to the shape. The following examples help in understanding what happens
+Fitting an Equation of State for Dense Nuclear Matter
+
+
+
+The code
+
import numpy as np
-print(np.c_[np.array([1,2,3]), np.array([4,5,6])])
-print(np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])])
-
# Importing various packages
-from random import random, seed
+
# Common imports
+import os
import numpy as np
+import pandas as pd
import matplotlib.pyplot as plt
-
-x = 2*np.random.rand(100,1)
-y = 4+3*x+np.random.randn(100,1)
-
-xb = np.c_[np.ones((100,1)), x]
-beta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
-xnew = np.array([[0],[2]])
-xbnew = np.c_[np.ones((2,1)), xnew]
-ypredict = xbnew.dot(beta)
-
-plt.plot(xnew, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0,2.0,0, 15.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Linear Regression')
-plt.show()
-
-
-Simple regression model, now using scikit-learn
-
-# Importing various packages
-from random import random, seed
-import numpy as np
import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression
+import sklearn.linear_model as skl
+from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
-x = 2*np.random.rand(100,1)
-y = 4+3*x+np.random.randn(100,1)
-linreg = LinearRegression()
-linreg.fit(x,y)
-xnew = np.array([[0],[2]])
-ypredict = linreg.predict(xnew)
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
-plt.plot(xnew, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0,2.0,0, 15.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Random numbers ')
-plt.show()
-
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
-Simple linear regression model using scikit-learn
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
-# Importing various packages
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression
-
-x = np.random.rand(100,1)
-y = 2*x+np.random.randn(100,1)
-linreg = LinearRegression()
-linreg.fit(x,y)
-xnew = np.array([[0],[1]])
-ypredict = linreg.predict(xnew)
-
-plt.plot(xnew, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0,1.0,0, 5.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Simple Linear Regression')
-plt.show()
-
-
-Simple linear regression model
-
-
-
-Less noise
-
-
-
-How to study our fits
-
-
-
-Minimizing the cost function
-
-
-
-Relative error
-
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression
-
-x = np.random.rand(100,1)
-y = 5*x+0.01*np.random.randn(100,1)
-linreg = LinearRegression()
-linreg.fit(x,y)
-ypredict = linreg.predict(x)
-
-plt.plot(x, np.abs(ypredict-y)/abs(y), "ro")
-plt.axis([0,1.0,0.0, 0.5])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$\epsilon_{\mathrm{relative}}$')
-plt.title(r'Relative error')
-plt.show()
-
-
-The richness of scikit-learn
-
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.linear_model import LinearRegression
-from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error
-
-x = np.random.rand(100,1)
-y = 2.0+ 5*x+0.5*np.random.randn(100,1)
-linreg = LinearRegression()
-linreg.fit(x,y)
-ypredict = linreg.predict(x)
-print('The intercept alpha: \n', linreg.intercept_)
-print('Coefficient beta : \n', linreg.coef_)
+# We use now Scikit-Learn's linear regressor and ridge regressor
+# OLS part
+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(y, ypredict))
+print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde))
# Explained variance score: 1 is perfect prediction
-print('Variance score: %.2f' % r2_score(y, ypredict))
-# Mean squared log error
-print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) )
+print('Variance score: %.2f' % r2_score(Energies, ytilde))
# Mean absolute error
-print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict))
-plt.plot(x, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0.0,1.0,1.5, 7.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Linear Regression fit ')
+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
+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))
+# Explained variance score: 1 is perfect prediction
+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_)
+
+fig, ax = plt.subplots()
+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')
+ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',
+ label='OLS')
+ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g',
+ label='Ridge $\lambda = 0.1$')
+ax.legend()
+save_fig("EoSfitting")
plt.show()
-
-Functions in scikit-learn
+The above simple polynomial in density \( \rho \) gives an excellent fit
+to the data. Can you give an interpretation of the various powers of \( \rho \)?
-Other functions in scikit-learn
+Splitting our Data in Training and Test data
-
-The mean absolute error and other functions in scikit-learn
-
-
-
-Cubic polynomial in scikit-learn
-
-import matplotlib.pyplot as plt
-import numpy as np
-import random
-from sklearn.linear_model import Ridge
-from sklearn.preprocessing import PolynomialFeatures
-from sklearn.pipeline import make_pipeline
-from sklearn.linear_model import LinearRegression
-
-x=np.linspace(0.02,0.98,200)
-noise = np.asarray(random.sample((range(200)),200))
-y=x**3*noise
-yn=x**3*100
-poly3 = PolynomialFeatures(degree=3)
-X = poly3.fit_transform(x[:,np.newaxis])
-clf3 = LinearRegression()
-clf3.fit(X,y)
-
-Xplot=poly3.fit_transform(x[:,np.newaxis])
-poly3_plot=plt.plot(x, clf3.predict(Xplot), label='Cubic Fit')
-plt.plot(x,yn, color='red', label="True Cubic")
-plt.scatter(x, y, label='Data', color='orange', s=15)
-plt.legend()
-plt.show()
-
-def error(a):
- for i in y:
- err=(y-yn)/yn
- return abs(np.sum(err))/len(err)
-
-print (error(y))
-
-
-Polynomial Regression
-# Importing various packages
-from math import exp, sqrt
-from random import random, seed
+
import os
import numpy as np
+import pandas as pd
import matplotlib.pyplot as plt
+from sklearn.model_selection import train_test_split
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
-m = 100
-x = 2*np.random.rand(m,1)+4.
-y = 4+3*x*x+ +x-np.random.randn(m,1)
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
-xb = np.c_[np.ones((m,1)), x]
-theta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
-xnew = np.array([[0],[2]])
-xbnew = np.c_[np.ones((2,1)), xnew]
-ypredict = xbnew.dot(theta)
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
-plt.plot(xnew, ypredict, "r-")
-plt.plot(x, y ,'ro')
-plt.axis([0,2.0,0, 15.0])
-plt.xlabel(r'$x$')
-plt.ylabel(r'$y$')
-plt.title(r'Random numbers ')
-plt.show()
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+infile = open(data_path("EoS.csv"),'r')
+
+# Read the EoS data as csv file and organized into two arrays with density and energies
+EoS = pd.read_csv(infile, names=('Density', 'Energy'))
+EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
+EoS = EoS.dropna()
+Energies = EoS['Energy']
+Density = EoS['Density']
+# The design matrix now as function of various polytrops
+X = np.zeros((len(Density),5))
+X[:,0] = 1
+X[:,1] = Density**(2.0/3.0)
+X[:,2] = Density
+X[:,3] = Density**(4.0/3.0)
+X[:,4] = Density**(5.0/3.0)
+# We split the data in test and training data
+X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
+# 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))
Linking the regression analysis with a statistical interpretation
-
-
-Expectation value and variance
+The singular value decomposition
-
-The singular value decompostion
-From standard regression to Ridge regressions
+The Ising model
+
+import numpy as np
+import matplotlib.pyplot as plt
+from mpl_toolkits.axes_grid1 import make_axes_locatable
+import seaborn as sns
+import scipy.linalg as scl
+from sklearn.model_selection import train_test_split
+import tqdm
+sns.set(color_codes=True)
+cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
+
+L = 40
+n = int(1e4)
+
+spins = np.random.choice([-1, 1], size=(n, L))
+J = 1.0
+
+energies = np.zeros(n)
+
+for i in range(n):
+ energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
+
+
+Reformulating the problem to suit regression
+
+X = np.zeros((n, L ** 2))
+for i in range(n):
+ X[i] = np.outer(spins[i], spins[i]).ravel()
+y = energies
+X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
+
+
+Linear regression
+
+X_train_own = np.concatenate(
+ (np.ones(len(X_train))[:, np.newaxis], X_train),
+ axis=1
+)
+X_test_own = np.concatenate(
+ (np.ones(len(X_test))[:, np.newaxis], X_test),
+ axis=1
+)
+
def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray:
+ return scl.inv(x.T @ x) @ (x.T @ y)
+beta = ols_inv(X_train_own, y_train)
+
+
+Singular Value decomposition
+
+def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray:
+ u, s, v = scl.svd(x)
+ return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
+
beta = ols_svd(X_train_own,y_train)
+J = beta[1:].reshape(L, L)
+
fig = plt.figure(figsize=(20, 14))
+im = plt.imshow(J, **cmap_args)
+plt.title("OLS", fontsize=18)
+plt.xticks(fontsize=18)
+plt.yticks(fontsize=18)
+cb = fig.colorbar(im)
+cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
+plt.show()
+
+
+Linear Regression Problems
-Fixing the singularity
+Fixing the singularity
-Fitting vs. predicting when data is in the model class
+Basic math of the SVD
+
+The SVD, a Fantastic Algorithm
+
+
+
+Another Example
+
+
+
+Economy-size SVD
+
+
+
+Mathematical Properties
+
+
+
+Ridge and LASSO Regression
+
+
+
+More on Ridge Regression
+
+
+
+Interpreting the Ridge results
+
+
+
+More interpretations
+
+
+
+Where are we going?
+
+
-
-Repeat the exercises above for \( f(x)=2x \) , \( Ntrain=100 \) , and \( \sigma=1 \) . What changes?
-Summarize what you have learned about the relationship between model complexity (number of parameters), goodness of fit on training data, and the ability to predict well.
+This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods.
-Fitting versus predicting when data is not in the model class
-
-
-
-
-Summarize what you think you learned about the relationship of knowing the true model class and predictive power.
-
-
-
-An example code without the model assessment part
-
-import numpy as np
-import sklearn as sk
-from sklearn import datasets, linear_model
-from sklearn.preprocessing import PolynomialFeatures
-
-import matplotlib as mpl
-from matplotlib import pyplot as plt
-
-%matplotlib notebook
-
-# The Training Data
-
-N_train=100
-
-sigma_train=1;
-
-# Train on integers
-x=np.linspace(0.05,0.95,N_train)
-# Draw random noise
-s = sigma_train*np.random.randn(N_train)
-
-#linear
-y=2*x+s
-
-#Tenth Order
-#y=2*x-10*x**5+15*x**10+s
-
-p1=plt.plot(x,y, "o",ms=15, label='Training')
-
-#Linear Regression
-# Create linear regression object
-clf = linear_model.LinearRegression()
-
-# Train the model using the training sets
-clf.fit(x[:, np.newaxis], y)
-# The coefficients
-
-xplot=np.linspace(0.02,0.98,200)
-linear_plot=plt.plot(xplot, clf.predict(xplot[:, np.newaxis]),label='Linear')
-
-#Polynomial Regression
-
-
-poly3 = PolynomialFeatures(degree=3)
-X = poly3.fit_transform(x[:,np.newaxis])
-clf3 = linear_model.LinearRegression()
-clf3.fit(X,y)
-
-
-Xplot=poly3.fit_transform(xplot[:,np.newaxis])
-poly3_plot=plt.plot(xplot, clf3.predict(Xplot), label='Poly 3')
-
-
-
-#poly5 = PolynomialFeatures(degree=5)
-#X = poly5.fit_transform(x[:,np.newaxis])
-#clf5 = linear_model.LinearRegression()
-#clf5.fit(X,y)
-
-#Xplot=poly5.fit_transform(xplot[:,np.newaxis])
-#plt.plot(xplot, clf5.predict(Xplot), 'r--',linewidth=1)
-
-poly10 = PolynomialFeatures(degree=10)
-X = poly10.fit_transform(x[:,np.newaxis])
-clf10 = linear_model.LinearRegression()
-clf10.fit(X,y)
-
-Xplot=poly10.fit_transform(xplot[:,np.newaxis])
-poly10_plot=plt.plot(xplot, clf10.predict(Xplot), label='Poly 10')
-
-axes = plt.gca()
-axes.set_ylim([-7,7])
-
-handles, labels=axes.get_legend_handles_labels()
-plt.legend(handles,labels, loc='lower center')
-plt.xlabel("$x$")
-plt.ylabel("$y$")
-Title="$N=$"+str(N_train)+", $\sigma=$"+str(sigma_train)
-plt.title(Title+" (train)")
-plt.tight_layout()
-plt.show()
-
Generating test data
-# Generate Test Data
-
-#Number of test data
-N_test=20
-
-sigma_test=sigma_train
-
-max_x=1.2
-x_test=max_x*np.random.random(N_test)
-# Draw random noise
-s_test = sigma_test*np.random.randn(N_test)
-
-#Linear
-y_test=2*x_test+s_test
-#Tenth order
-#y_test=2*x_test-10*x_test**5+15*x_test**10+s_test
-
-#Make design matrices for prediction
-x_plot=np.linspace(0,max_x, 200)
-X3 = poly3.fit_transform(x_plot[:,np.newaxis])
-X10 = poly10.fit_transform(x_plot[:,np.newaxis])
-
-%matplotlib notebook
-
-fig = plt.figure()
-p1=plt.plot(x_test,y_test.transpose(), 'o', ms=12, label='data')
-p2=plt.plot(x_plot,clf.predict(x_plot[:,np.newaxis]), label='linear')
-p3=plt.plot(x_plot,clf3.predict(X3), label='3rd order')
-p10=plt.plot(x_plot,clf10.predict(X10), label='10th order')
-
-
-plt.legend(loc=2)
-plt.xlabel('$x$')
-plt.ylabel('$y$')
-plt.legend(loc='best')
-plt.title(Title+" (pred.)")
-plt.tight_layout()
-plt.show()
-
-
-How can we effectively evaluate the various models?
-
-
-
-Code examples for Ridge and Lasso Regression
-
-import matplotlib.pyplot as plt
-import numpy as np
-from sklearn import linear_model
-from sklearn.linear_model import LinearRegression
-from sklearn.metrics import mean_squared_error, r2_score
-
-#creating data with random noise
-x=np.arange(50)
-
-delta=np.random.uniform(-2.5,2.5, size=(50))
-np.random.shuffle(delta)
-y =0.5*x+5+delta
-
-#arranging data into 2x50 matrix
-a=np.array(x) #inputs
-b=np.array(y) #outputs
-
-#Split into training and test
-X_train=a[:37, np.newaxis]
-X_test=a[37:, np.newaxis]
-y_train=b[:37]
-y_test=b[37:]
-
-print ("X_train: ", X_train.shape)
-print ("y_train: ", y_train.shape)
-print ("X_test: ", X_test.shape)
-print ("y_test: ", y_test.shape)
-
-print ("------------------------------------")
-
-print ("Ordinary Least Squares")
-#Add Ordinary Least Squares fit
-reg=LinearRegression()
-reg.fit(X_train, y_train)
-pred=reg.predict(X_test)
-print ("Prediction Shape: ", pred.shape)
-
-print('Coefficients: \n', reg.coef_)
-# The mean squared error
-print("Mean squared error: %.2f"
- % mean_squared_error(y_test, pred))
-# Explained variance score: 1 is perfect prediction
-print('Variance score: %.2f' % r2_score(y_test, pred))
-
-#plot
-plt.scatter(X_test,y_test,color='green', label="Training Data")
-plt.plot(X_test, pred, color='black', label="Fit Line")
-plt.legend()
-plt.show()
-
-print ("------------------------------------")
-
-print ("Ridge Regression")
-
-ridge=linear_model.RidgeCV(alphas=[0.1,1.0,10.0])
-ridge.fit(X_train,y_train)
-print ("Ridge Coefficient: ",ridge.coef_)
-print ("Ridge Intercept: ", ridge.intercept_)
-#Look into graphing with Ridge fit
-
-print ("------------------------------------")
-
-print ("Lasso")
-lasso=linear_model.Lasso(alpha=0.1)
-lasso.fit(X_train,y_train)
-predl=lasso.predict(X_test)
-print("Lasso Coefficient: ", lasso.coef_)
-print("Lasso Intercept: ", lasso.intercept_)
-plt.scatter(X_test,y_test,color='green', label="Training Data")
-plt.plot(X_test, predl, color='blue', label="Lasso")
-plt.legend()
-plt.show()
-
-
-A second-order polynomial with Ridge and Lasso
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.linear_model import Ridge
-from sklearn.metrics import r2_score
-
-np.random.seed(4155)
-
-n_samples = 100
-
-x = np.random.rand(n_samples,1)
-y = 5*x*x + 0.1*np.random.rand(n_samples,1)
-
-# Centering x and y.
-x_ = x - np.mean(x)
-y_ = y - np.mean(y) # beta_0 = mean(y)
-
-X = np.c_[np.ones((n_samples,1)), x, x**2]
-X_ = np.c_[x_, x_**2]
-
-
-### 1.
-lmb_values = [1e-4, 1e-3, 1e-2, 10, 1e2, 1e4]
-num_values = len(lmb_values)
-
-## Ridge-regression of centered and not centered data
-beta_ridge = np.zeros((3,num_values))
-beta_ridge_centered = np.zeros((3,num_values))
-
-I3 = np.eye(3)
-I2 = np.eye(2)
-
-for i,lmb in enumerate(lmb_values):
- beta_ridge[:,i] = (np.linalg.inv( X.T @ X + lmb*I3) @ X.T @ y).flatten()
- beta_ridge_centered[1:,i] = (np.linalg.inv( X_.T @ X_ + lmb*I2) @ X_.T @ y_).flatten()
-
-# sett beta_0 = np.mean(y)
-beta_ridge_centered[0,:] = np.mean(y)
-
-## OLS (ordinary least squares) solution
-beta_ls = np.linalg.inv( X.T @ X ) @ X.T @ y
-
-## Evaluate the models
-pred_ls = X @ beta_ls
-pred_ridge = X @ beta_ridge
-pred_ridge_centered = X_ @ beta_ridge_centered[1:] + beta_ridge_centered[0,:]
-
-## Plot the results
-
-# Sorting
-sort_ind = np.argsort(x[:,0])
-
-x_plot = x[sort_ind,0]
-x_centered_plot = x_[sort_ind,0]
-
-pred_ls_plot = pred_ls[sort_ind,0]
-pred_ridge_plot = pred_ridge[sort_ind,:]
-pred_ridge_centered_plot = pred_ridge_centered[sort_ind,:]
-
-# Plott not centered
-plt.plot(x_plot,pred_ls_plot,label='ls')
-
-for i in range(num_values):
- plt.plot(x_plot,pred_ridge_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])
-
-plt.plot(x,y,'ro')
-
-plt.title('linear regression on un-centered data')
-plt.legend()
-
-# Plott centered
-plt.figure()
-
-for i in range(num_values):
- plt.plot(x_centered_plot,pred_ridge_centered_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])
-
-plt.plot(x_,y,'ro')
-
-plt.title('linear regression on centered data')
-plt.legend()
-
-
-# 2.
-
-pred_ridge_scikit = np.zeros((n_samples,num_values))
-for i,lmb in enumerate(lmb_values):
- pred_ridge_scikit[:,i] = (Ridge(alpha=lmb,fit_intercept=False).fit(X,y).predict(X)).flatten() # fit_intercept=False fordi bias er allerede i X
-
-plt.figure()
-
-plt.plot(x_plot,pred_ls_plot,label='ls')
-
-for i in range(num_values):
- plt.plot(x_plot,pred_ridge_scikit[sort_ind,i],label='scikit-ridge, lmb=%g'%lmb_values[i])
-
-plt.plot(x,y,'ro')
-plt.legend()
-plt.title('linear regression using scikit')
-
-plt.show()
-
-### R2-score of the results
-for i in range(num_values):
- print('lambda = %g'%lmb_values[i])
- print('r2 for scikit: %g'%r2_score(y,pred_ridge_scikit[:,i]))
- print('r2 for own code, not centered: %g'%r2_score(y,pred_ridge[:,i]))
- print('r2 for own, centered: %g\n'%r2_score(y,pred_ridge_centered[:,i]))
-
-
-Resampling methods
+Resampling methods
-Resampling approaches can be computationally expensive
+Resampling approaches can be computationally expensive
-Why resampling methods ?
+Why resampling methods ?
-
-Statistical analysis
+Statistical analysis
-
-
-
-Statistics
+Statistics
-Statistics, moments
+Statistics, moments
-Statistics, central moments
+Statistics, central moments
-Statistics, covariance
+Statistics, covariance
-Statistics, more covariance
+Statistics, more covariance
-Statistics, independent variables
+Statistics, independent variables
-Statistics, more variance
+Statistics, more variance
-Statistics and stochastic processes
+Statistics and stochastic processes
Statistics and sample variables
+Statistics and sample variables
-Statistics, sample variance and covariance
+Statistics, sample variance and covariance
-Statistics, law of large numbers
+Statistics, law of large numbers
-Statistics, more on sample error
+Statistics, more on sample error
-Statistics
+Statistics
-Statistics, central limit theorem
+Statistics, central limit theorem
-Statistics, more technicalities
+Statistics, more technicalities
-Statistics
+Statistics
-Statistics and sample variance
+Statistics and sample variance
-Statistics, uncorrelated results
+Statistics, uncorrelated results
-Statistics, computations
+Statistics, computations
-Statistics, more on computations of errors
+Statistics, more on computations of errors
-Statistics, wrapping up 1
+Statistics, wrapping up 1
-Statistics, final expression
+Statistics, final expression
-Statistics, effective number of correlations
+Statistics, effective number of correlations
+
-Log-likelihood
+Linking the regression analysis with a statistical interpretation
+
+Assumptions made
+
+
+
+Expectation value and variance
+
+
+
+Expectation value and variance for \( \boldsymbol{\beta} \)
+
+Cross-validation
+Cross-validation
-Computationally expensive
+Computationally expensive
Various steps in cross-validation
+Various steps in cross-validation
How to set up the cross-validation for Ridge and/or Lasso
+How to set up the cross-validation for Ridge and/or Lasso
$$
\begin{align*}
-\hat{\beta}_{-i}(\lambda) & = ( \hat{X}_{-i, \ast}^{\top}
-\hat{X}_{-i, \ast} + \lambda \hat{I}_{pp})^{-1}
-\hat{X}_{-i, \ast}^{\top} \hat{y}_{-i}
+\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T}
+\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1}
+\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i}
\end{align*}
$$
-
$$
\begin{align*}
-\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \hat{\beta}_{-i}(\lambda), \hat{\sigma}_{-i}^2(\lambda)]\}.
+\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}.
\end{align*}
$$
@@ -2694,31 +3087,7 @@ $$
-Predicted Residual Error Sum of Squares
-
-
-Resampling methods: Jackknife and Bootstrap
+Resampling methods: Jackknife and Bootstrap
-Resampling methods: Jackknife
+Resampling methods: Jackknife
-Resampling methods: Jackknife estimator
-
-
-
Jackknife code example
Resampling methods: Bootstrap background
@@ -2885,7 +3240,7 @@ result in some asymptotic sense? The answer is yes.
Instead of generating the histogram for the relative
frequency of the observation \( X_i \), just draw the values
\( (X_1^*,X_2^*,\cdots,X_n^*) \) with replacement from the vector
-\( \hat{X} \).
+\( \boldsymbol{X} \).
@@ -2896,19 +3251,41 @@ frequency of the observation \( X_i \), just draw the values
The independent bootstrap works like this:
-
-When you are done, you can draw a histogram of the relative frequency of \( \widehat \theta^* \). This is your estimate of the probability distribution \( p(t) \). Using this probability distribution you can estimate any statistics thereof. In principle you never draw the histogram of the relative frequency of \( \widehat{\theta}^* \). Instead you use the estimators corresponding to the statistic of interest. For example, if you are interested in estimating the variance of \( \widehat \theta \), apply the etsimator \( \widehat \sigma^2 \) to the values \( \widehat \theta ^* \).
+When you are done, you can draw a histogram of the relative frequency
+of \( \widehat \theta^* \). This is your estimate of the probability
+distribution \( p(t) \). Using this probability distribution you can
+estimate any statistics thereof. In principle you never draw the
+histogram of the relative frequency of \( \widehat{\theta}^* \). Instead
+you use the estimators corresponding to the statistic of interest. For
+example, if you are interested in estimating the variance of \( \widehat
+\theta \), apply the etsimator \( \widehat \sigma^2 \) to the values
+\( \widehat \theta ^* \).
Code example for the Bootstrap method
-The following code starts with a Gaussian distribution with mean value \( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data used in the bootstrap analysis. The bootstrap analysis returns a data set after a given number of bootstrap operations (as many as we have data points). This data set consists of estimated mean values for each bootstrap operation. The histogram generated by the bootstrap method shows that the distribution for these mean values is also a Gaussian, centered around the mean value \( \mu=100 \) but with standard deviation \( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in this case the same as the number of original data points). The value of the standard deviation is what we expect from the central limit theorem.
+
+
-Resampling methods: Blocking
+Code Example for Cross-validation and \( k \)-fold Cross-validation
-
-Blocking Transformations
- We now define
-blocking transformations. The idea is to take the mean of subsequent
-pair of elements from \( \vec{X} \) and form a new vector
-\( \vec{X}_1 \). Continuing in the same way by taking the mean of
-subsequent pairs of elements of \( \vec{X}_1 \) we obtain \( \vec{X}_2 \), and
-so on.
-Define \( \vec{X}_i \) recursively by:
-
-$$
-\begin{align}
-(\vec{X}_0)_k &\equiv (\vec{X})_k \nonumber \\
-(\vec{X}_{i+1})_k &\equiv \frac{1}{2}\Big( (\vec{X}_i)_{2k-1} +
-(\vec{X}_i)_{2k} \Big) \qquad \text{for all} \qquad 1 \leq i \leq d-1
-\label{_auto11}
-\end{align}
-$$
-
-
-
-Blocking Transformations
-
-
-
-Blocking Transformations, getting there
-We have
-$$
-\begin{align}
-V(\overline{X}_k) = \frac{\sigma_k^2}{n_k} + \underbrace{\frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h)}_{\equiv e_k} = \frac{\sigma^2_k}{n_k} + e_k \quad \text{if} \quad \gamma_k(0) = \sigma_k^2.
-\label{_auto14}
-\end{align}
-$$
-
-The term \( e_k \) is called the truncation error:
-$$
-\begin{equation}
-e_k = \frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h).
-\label{_auto15}
-\end{equation}
-$$
-
-We can show that \( V(\overline{X}_i) = V(\overline{X}_j) \) for all \( 0 \leq i \leq d-1 \) and \( 0 \leq j \leq d-1 \).
-
-
-
-Blocking Transformations, final expressions
-
-
-
-Code examples for Blocking, Jackknife and bootstrap
-
+The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial.
from sys import argv
-from os import mkdir, path
-import time
-import numpy as np
+
import numpy as np
import matplotlib.pyplot as plt
-from matplotlib.ticker import FormatStrFormatter
-from matplotlib.font_manager import FontProperties
+from sklearn.model_selection import KFold
+from sklearn.linear_model import Ridge
+from sklearn.model_selection import cross_val_score
+from sklearn.preprocessing import PolynomialFeatures
-# Timing Decorator
-def timeFunction(f):
- def wrap(*args):
- time1 = time.time()
- ret = f(*args)
- time2 = time.time()
- print '%s Function Took: \t %0.3f s' % (f.func_name.title(), (time2-time1))
- return ret
- return wrap
+# A seed just to ensure that the random numbers are the same for every run.
+# Useful for eventual debugging.
+np.random.seed(3155)
-class dataAnalysisClass:
- # General Init functions
- def __init__(self, fileName, size=0):
- self.inputFileName = fileName
- self.loadData(size)
- self.createOutputFolder()
- self.avg = np.average(self.data)
- self.var = np.var(self.data)
- self.std = np.std(self.data)
+# Generate the data.
+nsamples = 100
+x = np.random.randn(nsamples)
+y = 3*x**2 + np.random.randn(nsamples)
- def loadData(self, size=0):
- if size != 0:
- with open(self.inputFileName) as inputFile:
- self.data = np.zeros(size)
- for x in xrange(size):
- self.data[x] = float(next(inputFile))
- else:
- self.data = np.loadtxt(self.inputFileName)
+## Cross-validation on Ridge regression using KFold only
- # Statistical Analysis with Multiple Methods
- def runAllAnalyses(self):
- if len(self.data) <= 100000:
- print "Autocorrelation..."
- self.autocorrelation()
- print "Bootstrap..."
- self.bootstrap()
- print "Jackknife..."
- self.jackknife()
- print "Blocking..."
- self.blocking()
+# Decide degree on polynomial to fit
+poly = PolynomialFeatures(degree = 6)
- # Standard Autocorrelation
- @timeFunction
- def autocorrelation(self):
- self.acf = np.zeros(len(self.data)/2)
- for k in range(0, len(self.data)/2):
- self.acf[k] = np.corrcoef(np.array([self.data[0:len(self.data)-k], \
- self.data[k:len(self.data)]]))[0,1]
+# Decide which values of lambda to use
+nlambdas = 500
+lambdas = np.logspace(-3, 5, nlambdas)
- # Bootstrap
- @timeFunction
- def bootstrap(self, nBoots = 1000):
- bootVec = np.zeros(nBoots)
- for k in range(0,nBoots):
- bootVec[k] = np.average(np.random.choice(self.data, len(self.data)))
- self.bootAvg = np.average(bootVec)
- self.bootVar = np.var(bootVec)
- self.bootStd = np.std(bootVec)
+# Initialize a KFold instance
+k = 5
+kfold = KFold(n_splits = k)
- # Jackknife
- @timeFunction
- def jackknife(self):
- jackknVec = np.zeros(len(self.data))
- for k in range(0,len(self.data)):
- jackknVec[k] = np.average(np.delete(self.data, k))
- self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg)
- self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec)
- self.jackknStd = np.sqrt(self.jackknVar)
+# Perform the cross-validation to estimate MSE
+scores_KFold = np.zeros((nlambdas, k))
- # Blocking
- @timeFunction
- def blocking(self, blockSizeMax = 500):
- blockSizeMin = 1
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
+ j = 0
+ for train_inds, test_inds in kfold.split(x):
+ xtrain = x[train_inds]
+ ytrain = y[train_inds]
- self.blockSizes = []
- self.meanVec = []
- self.varVec = []
+ xtest = x[test_inds]
+ ytest = y[test_inds]
- for i in range(blockSizeMin, blockSizeMax):
- if(len(self.data) % i != 0):
- pass#continue
- blockSize = i
- meanTempVec = []
- varTempVec = []
- startPoint = 0
- endPoint = blockSize
+ Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
+ ridge.fit(Xtrain, ytrain[:, np.newaxis])
- while endPoint <= len(self.data):
- meanTempVec.append(np.average(self.data[startPoint:endPoint]))
- startPoint = endPoint
- endPoint += blockSize
- mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec)
- self.meanVec.append(mean)
- self.varVec.append(var)
- self.blockSizes.append(blockSize)
+ Xtest = poly.fit_transform(xtest[:, np.newaxis])
+ ypred = ridge.predict(Xtest)
- self.blockingAvg = np.average(self.meanVec[-200:])
- self.blockingVar = (np.average(self.varVec[-200:]))
- self.blockingStd = np.sqrt(self.blockingVar)
+ scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
+
+ j += 1
+ i += 1
+estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
- # Plot of Data, Autocorrelation Function and Histogram
- def plotAll(self):
- self.createOutputFolder()
- if len(self.data) <= 100000:
- self.plotAutocorrelation()
- self.plotData()
- self.plotHistogram()
- self.plotBlocking()
+## Cross-validation using cross_val_score from sklearn along with KFold
- # Create Output Plots Folder
- def createOutputFolder(self):
- self.outName = self.inputFileName[:-4]
- if not path.exists(self.outName):
- mkdir(self.outName)
+# kfold is an instance initialized above as:
+# kfold = KFold(n_splits = k)
- # Plot the Dataset, Mean and Std
- def plotData(self):
- # Far away plot
- font = {'fontname':'serif'}
- plt.plot(range(0, len(self.data)), self.data, 'r-', linewidth=1)
- plt.plot([0, len(self.data)], [self.avg, self.avg], 'b-', linewidth=1)
- plt.plot([0, len(self.data)], [self.avg + self.std, self.avg + self.std], 'g--', linewidth=1)
- plt.plot([0, len(self.data)], [self.avg - self.std, self.avg - self.std], 'g--', linewidth=1)
- plt.ylim(self.avg - 5*self.std, self.avg + 5*self.std)
- plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.4f'))
- plt.xlim(0, len(self.data))
- plt.ylabel(self.outName.title() + ' Monte Carlo Evolution', **font)
- plt.xlabel('MonteCarlo History', **font)
- plt.title(self.outName.title(), **font)
- plt.savefig(self.outName + "/data.eps")
- plt.savefig(self.outName + "/data.png")
- plt.clf()
+estimated_mse_sklearn = np.zeros(nlambdas)
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
- # Plot Histogram of Dataset and Gaussian around it
- def plotHistogram(self):
- binNumber = 50
- font = {'fontname':'serif'}
- count, bins, ignore = plt.hist(self.data, bins=np.linspace(self.avg - 5*self.std, self.avg + 5*self.std, binNumber))
- plt.plot([self.avg, self.avg], [0,np.max(count)+10], 'b-', linewidth=1)
- plt.ylim(0,np.max(count)+10)
- plt.ylabel(self.outName.title() + ' Histogram', **font)
- plt.xlabel(self.outName.title() , **font)
- plt.title('Counts', **font)
+ X = poly.fit_transform(x[:, np.newaxis])
+ estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
- #gaussian
- norm = 0
- for i in range(0,len(bins)-1):
- norm += (bins[i+1]-bins[i])*count[i]
- plt.plot(bins, norm/(self.std * np.sqrt(2 * np.pi)) * np.exp( - (bins - self.avg)**2 / (2 * self.std**2) ), linewidth=1, color='r')
- plt.savefig(self.outName + "/hist.eps")
- plt.savefig(self.outName + "/hist.png")
- plt.clf()
+ # cross_val_score return an array containing the estimated negative mse for every fold.
+ # we have to the the mean of every array in order to get an estimate of the mse of the model
+ estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
- # Plot the Autocorrelation Function
- def plotAutocorrelation(self):
- font = {'fontname':'serif'}
- plt.plot(range(1, len(self.data)/2), self.acf[1:], 'r-')
- plt.ylim(-1, 1)
- plt.xlim(0, len(self.data)/2)
- plt.ylabel('Autocorrelation Function', **font)
- plt.xlabel('Lag', **font)
- plt.title('Autocorrelation', **font)
- plt.savefig(self.outName + "/autocorrelation.eps")
- plt.savefig(self.outName + "/autocorrelation.png")
- plt.clf()
+ i += 1
- def plotBlocking(self):
- font = {'fontname':'serif'}
- plt.plot(self.blockSizes, self.varVec, 'r-')
- plt.ylabel('Variance', **font)
- plt.xlabel('Block Size', **font)
- plt.title('Blocking', **font)
- plt.savefig(self.outName + "/blocking.eps")
- plt.savefig(self.outName + "/blocking.png")
- plt.clf()
+## Plot and compare the slightly different ways to perform cross-validation
- # Print Stuff to the Terminal
- def printOutput(self):
- print "\nSample Size: \t", len(self.data)
- print "\n=========================================\n"
- print "Sample Average: \t", self.avg
- print "Sample Variance:\t", self.var
- print "Sample Std: \t", self.std
- print "\n=========================================\n"
- print "Bootstrap Average: \t", self.bootAvg
- print "Bootstrap Variance:\t", self.bootVar
- print "Bootstrap Error: \t", self.bootStd
- print "\n=========================================\n"
- print "Jackknife Average: \t", self.jackknAvg
- print "Jackknife Variance:\t", self.jackknVar
- print "Jackknife Error: \t", self.jackknStd
- print "\n=========================================\n"
- print "Blocking Average: \t", self.blockingAvg
- print "Blocking Variance:\t", self.blockingVar
- print "Blocking Error: \t", self.blockingStd, "\n"
+plt.figure()
-# Initialize the class
-if len(argv) > 2:
- dataAnalysis = dataAnalysisClass(argv[1], int(argv[2]))
-else:
- dataAnalysis = dataAnalysisClass(argv[1])
+plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
+plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
-# Run Analyses
-dataAnalysis.runAllAnalyses()
+plt.xlabel('log10(lambda)')
+plt.ylabel('mse')
-# Plot the data
-dataAnalysis.plotAll()
+plt.legend()
-# Print Some Output
-dataAnalysis.printOutput()
+plt.show()
-The bias-variance tradeoff
+The bias-variance tradeoff
+
+Example code for Bias-Variance tradeoff
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+
+np.random.seed(2018)
+
+n = 500
+n_boostraps = 100
+degree = 18 # A quite high value, just to show.
+noise = 0.1
+
+# Make data set.
+x = np.linspace(-1, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)
+
+# Hold out some test data that is never used in training.
+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+# Combine x transformation and model into one operation.
+# Not neccesary, but convenient.
+model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
+
+# The following (m x n_bootstraps) matrix holds the column vectors y_pred
+# for each bootstrap iteration.
+y_pred = np.empty((y_test.shape[0], n_boostraps))
+for i in range(n_boostraps):
+ x_, y_ = resample(x_train, y_train)
+
+ # Evaluate the new model on the same test data each time.
+ y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
+
+# Note: Expectations and variances taken w.r.t. different training
+# data sets, hence the axis=1. Subsequent means are taken across the test data
+# set in order to obtain a total value, but before this we have error/bias/variance
+# calculated per data point in the test set.
+# Note 2: The use of keepdims=True is important in the calculation of bias as this
+# maintains the column vector form. Dropping this yields very unexpected results.
+error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+print('Error:', error)
+print('Bias^2:', bias)
+print('Var:', variance)
+print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))
+
+plt.plot(x[::5, :], y[::5, :], label='f(x)')
+plt.scatter(x_test, y_test, label='Data points')
+plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')
+plt.legend()
+plt.show()
+
+
+Understanding what happens
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+
+np.random.seed(2018)
+
+n = 40
+n_boostraps = 100
+maxdegree = 14
+
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+for degree in range(maxdegree):
+ model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
+ y_pred = np.empty((y_test.shape[0], n_boostraps))
+ for i in range(n_boostraps):
+ x_, y_ = resample(x_train, y_train)
+ y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
+
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+ variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+ print('Polynomial degree:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.plot(polydegree, np.log10(error), label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+plt.show()
+
Training and testing data
-
-
-
-Procedure to find a predictor
-
-
-
-What we want
-
-
-
-The expected generalization error
-
-
-
-Elaborating a little bit more
-
-
-
-The bias
-
-
-
-The variance
-The second term is called the variance
-$$
-Var=\sum_i E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2],
-$$
-
-Summing up
Summing up
-
-The one-dimensional Ising model, project 2
+Another Example rom Scikit-Learn's Repository
+"""
+============================
+Underfitting vs. Overfitting
+============================
+
+This example demonstrates the problems of underfitting and overfitting and
+how we can use linear regression with polynomial features to approximate
+nonlinear functions. The plot shows the function that we want to approximate,
+which is a part of the cosine function. In addition, the samples from the
+real function and the approximations of different models are displayed. The
+models have polynomial features of different degrees. We can see that a
+linear function (polynomial with degree 1) is not sufficient to fit the
+training samples. This is called **underfitting**. A polynomial of degree 4
+approximates the true function almost perfectly. However, for higher degrees
+the model will **overfit** the training data, i.e. it learns the noise of the
+training data.
+We evaluate quantitatively **overfitting** / **underfitting** by using
+cross-validation. We calculate the mean squared error (MSE) on the validation
+set, the higher, the less likely the model generalizes correctly from the
+training data.
+"""
+
+print(__doc__)
+
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.linear_model import LinearRegression
+from sklearn.model_selection import cross_val_score
+
+
+def true_fun(X):
+ return np.cos(1.5 * np.pi * X)
+
+np.random.seed(0)
+
+n_samples = 30
+degrees = [1, 4, 15]
+
+X = np.sort(np.random.rand(n_samples))
+y = true_fun(X) + np.random.randn(n_samples) * 0.1
+
+plt.figure(figsize=(14, 5))
+for i in range(len(degrees)):
+ ax = plt.subplot(1, len(degrees), i + 1)
+ plt.setp(ax, xticks=(), yticks=())
+
+ polynomial_features = PolynomialFeatures(degree=degrees[i],
+ include_bias=False)
+ linear_regression = LinearRegression()
+ pipeline = Pipeline([("polynomial_features", polynomial_features),
+ ("linear_regression", linear_regression)])
+ pipeline.fit(X[:, np.newaxis], y)
+
+ # Evaluate the models using crossvalidation
+ scores = cross_val_score(pipeline, X[:, np.newaxis], y,
+ scoring="neg_mean_squared_error", cv=10)
+
+ X_test = np.linspace(0, 1, 100)
+ plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
+ plt.plot(X_test, true_fun(X_test), label="True function")
+ plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
+ plt.xlabel("x")
+ plt.ylabel("y")
+ plt.xlim((0, 1))
+ plt.ylim((-2, 2))
+ plt.legend(loc="best")
+ plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
+ degrees[i], -scores.mean(), scores.std()))
+plt.show()
+
+
+The one-dimensional Ising model
-
-Reformulating the problem to suit regression
-
-
-Linear regression
-
-
-
-Ordinary least squares
-
-def get_ols_weights_naive(x: np.ndarray, y: np.ndarray) -> np.ndarray:
- return scl.inv(x.T @ x) @ (x.T @ y)
-omega = get_ols_weights_naive(X_train_own, y_train)
-
-
-Singular Value decomposition
-Doing the inversion directly turns out to be a bad idea as the matrix
-\( X^TX \) is singular. An alternative approach is to use the singular
-value decomposition. Using the definition of the Moore-Penrose
-pseudoinverse we can write the equation for \( \omega \) as
-
-$$
-\begin{align}
- \omega = X^{+}y,
-\label{_auto28}
-\end{align}
-$$
-
-where the pseudoinverse of \( X \) is given by
-$$
-\begin{align}
- X^{+} = \frac{X^T}{X^T X}.
-\label{_auto29}
-\end{align}
-$$
-
-def get_ols_weights(x: np.ndarray, y: np.ndarray) -> np.ndarray:
- u, s, v = scl.svd(x)
- return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
-
omega = get_ols_weights(X_train_own,y_train)
-
-
-Fitting with scikit-learn
-
-LinearRegression-model from Scikit-learn for comparison.
+We will do all fitting with Scikit-Learn,
LinearRegression-model from Scikit-learn for comparis
clf = skl.LinearRegression().fit(X_train, y_train)
J_own = omega[1:].reshape(L, L)
-J_sk = clf.coef_.reshape(L, L)
+
J_sk = clf.coef_.reshape(L, L)
fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_own, **cmap_args)
-plt.title("Home-made OLS", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-
-fig = plt.figure(figsize=(20, 14))
im = plt.imshow(J_sk, **cmap_args)
plt.title("LinearRegression from Scikit-learn", fontsize=18)
plt.xticks(fontsize=18)
@@ -3791,66 +3858,33 @@ cb.ax.se
plt.show()
-Ridge regression
+Ridge regression
def get_ridge_weights(x: np.ndarray, y: np.ndarray, _lambda: float) -> np.ndarray:
- return x.T @ y @ scl.inv(
- x.T @ x + np.eye(x.shape[1], x.shape[1]) * _lambda
- )
-_lambda = 0.1
-omega_ridge = get_ridge_weights(X_train_own, y_train, np.array([_lambda]))
+
_lambda = 0.1
clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)
-J_ridge_own = omega_ridge[1:].reshape(L, L)
J_ridge_sk = clf_ridge.coef_.reshape(L, L)
-fig = plt.figure(figsize=(20, 14))
-im = plt.imshow(J_ridge_own, **cmap_args)
-plt.title("Home-made ridge regression", fontsize=18)
-plt.xticks(fontsize=18)
-plt.yticks(fontsize=18)
-cb = fig.colorbar(im)
-cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
-
fig = plt.figure(figsize=(20, 14))
im = plt.imshow(J_ridge_sk, **cmap_args)
plt.title("Ridge from Scikit-learn", fontsize=18)
@@ -3864,20 +3898,20 @@ plt.show()
-LASSO regression
+LASSO regression
-Performance of the different models
-
-def r_squared(y, y_hat):
- return 1 - np.sum((y - y_hat) ** 2) / np.sum((y - np.mean(y_hat)) ** 2)
-
y_hat = clf.predict(X_test)
-r_test = r_squared(y_test, y_hat)
-sk_r_test = clf.score(X_test, y_test)
-
-assert abs(r_test - sk_r_test) < 1e-2
-
-
-Performance as function of the regularization parameter
+Performance as function of the regularization parameter
lambdas = np.logspace(-4, 5, 10)
train_errors = {
- "ols_own": np.zeros(lambdas.size),
"ols_sk": np.zeros(lambdas.size),
- "ridge_own": np.zeros(lambdas.size),
"ridge_sk": np.zeros(lambdas.size),
"lasso_sk": np.zeros(lambdas.size)
}
test_errors = {
- "ols_own": np.zeros(lambdas.size),
"ols_sk": np.zeros(lambdas.size),
- "ridge_own": np.zeros(lambdas.size),
"ridge_sk": np.zeros(lambdas.size),
"lasso_sk": np.zeros(lambdas.size)
}
@@ -3967,30 +3963,6 @@ plot_counter =
fig = plt.figure(figsize=(32, 54))
for i, _lambda in enumerate(tqdm.tqdm(lambdas)):
- omega = get_ols_weights(X_train_own, y_train)
- y_hat_train = X_train_own @ omega
- y_hat_test = X_test_own @ omega
-
- train_errors["ols_own"][i] = r_squared(y_train, y_hat_train)
- test_errors["ols_own"][i] = r_squared(y_test, y_hat_test)
-
- plt.subplot(10, 5, plot_counter)
- plt.imshow(omega[1:].reshape(L, L), **cmap_args)
- plt.title("Home made OLS")
- plot_counter += 1
-
- omega = get_ridge_weights(X_train_own, y_train, _lambda)
- y_hat_train = X_train_own @ omega
- y_hat_test = X_test_own @ omega
-
- train_errors["ridge_own"][i] = r_squared(y_train, y_hat_train)
- test_errors["ridge_own"][i] = r_squared(y_test, y_hat_test)
-
- plt.subplot(10, 5, plot_counter)
- plt.imshow(omega[1:].reshape(L, L), **cmap_args)
- plt.title(r"Home made ridge, $\lambda = %.4f$" % _lambda)
- plot_counter += 1
-
for key, method in zip(
["ols_sk", "ridge_sk", "lasso_sk"],
[skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)]
@@ -4010,7 +3982,7 @@ fig = plt..show()
-Finding the optimal value of \( \lambda \)
+Finding the optimal value of \( \lambda \)
fig = plt.figure(figsize=(20, 14))
colors = {
- "ols_own": "b",
- "ridge_own": "g",
"ols_sk": "r",
"ridge_sk": "y",
"lasso_sk": "c"
@@ -4058,9 +4028,6 @@ colors = {
label="Test {0}".format(key),
linewidth=4.0
)
-#plt.semilogx(lambdas, train_errors["ols_own"], label="Train (OLS own)")
-#plt.semilogx(lambdas, test_errors["ols_own"], label="Test (OLS own)")
-
plt.legend(loc="best", fontsize=18)
plt.xlabel(r"$\lambda$", fontsize=18)
plt.ylabel(r"$R^2$", fontsize=18)
@@ -4069,14 +4036,245 @@ plt.show()
+
+Further Exercises
+
+Exercise 1
+
+x = np.random.rand(100,1)
+y = 5*x*x+0.1*np.random.randn(100,1)
+
+
+
+$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
+\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
+$$
+
+and the \( R^2 \) score function.
+If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as
+$$
+R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
+$$
+
+where we have defined the mean value of \( \hat{y} \) as
+$$
+\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
+$$
+
+Exercise 2, variance of the parameters \( \beta \) in linear regression
+
+Exercise 3
+
+x = np.random.rand(100,1)
+y = 5*x*x+0.1*np.random.randn(100,1)
+
+
+
+$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
+\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
+$$
+
+and the \( R^2 \) score function.
+If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as
+$$
+R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
+$$
+
+where we have defined the mean value of \( \hat{y} \) as
+$$
+\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
+$$
+
+Discuss these quantities as functions of the variable \( \lambda \) in the Ridge and Lasso regression methods.
+
+Exercise 4
+
+from mpl_toolkits.mplot3d import Axes3D
+import matplotlib.pyplot as plt
+from matplotlib import cm
+from matplotlib.ticker import LinearLocator, FormatStrFormatter
+import numpy as np
+from random import random, seed
+
+fig = plt.figure()
+ax = fig.gca(projection='3d')
+
+# Make data.
+x = np.arange(0, 1, 0.05)
+y = np.arange(0, 1, 0.05)
+x, y = np.meshgrid(x,y)
+
+
+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
+
+
+z = FrankeFunction(x, y)
+
+# Plot the surface.
+surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
+ linewidth=0, antialiased=False)
+
+# Customize the z axis.
+ax.set_zlim(-0.10, 1.40)
+ax.zaxis.set_major_locator(LinearLocator(10))
+ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
+
+# Add a color bar which maps values to colors.
+fig.colorbar(surf, shrink=0.5, aspect=5)
+
+plt.show()
+
+# reveal.js [](https://travis-ci.org/hakimel/reveal.js)
-A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://revealjs.com/).
+A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/).
-reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). There's also a fully featured visual editor and platform for sharing reveal.js presentations at [slides.com](https://slides.com?ref=github).
+reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a modern browser but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere.
-## Table of contents
-- [Online Editor](#online-editor)
-- [Instructions](#instructions)
- - [Markup](#markup)
- - [Markdown](#markdown)
- - [Element Attributes](#element-attributes)
- - [Slide Attributes](#slide-attributes)
-- [Configuration](#configuration)
-- [Presentation Size](#presentation-size)
-- [Dependencies](#dependencies)
-- [Ready Event](#ready-event)
-- [Auto-sliding](#auto-sliding)
-- [Keyboard Bindings](#keyboard-bindings)
-- [Touch Navigation](#touch-navigation)
-- [Lazy Loading](#lazy-loading)
-- [API](#api)
- - [Slide Changed Event](#slide-changed-event)
- - [Presentation State](#presentation-state)
- - [Slide States](#slide-states)
- - [Slide Backgrounds](#slide-backgrounds)
- - [Parallax Background](#parallax-background)
- - [Slide Transitions](#slide-transitions)
- - [Internal links](#internal-links)
- - [Fragments](#fragments)
- - [Fragment events](#fragment-events)
- - [Code syntax highlighting](#code-syntax-highlighting)
- - [Slide number](#slide-number)
- - [Overview mode](#overview-mode)
- - [Fullscreen mode](#fullscreen-mode)
- - [Embedded media](#embedded-media)
- - [Stretching elements](#stretching-elements)
- - [postMessage API](#postmessage-api)
-- [PDF Export](#pdf-export)
-- [Theming](#theming)
-- [Speaker Notes](#speaker-notes)
- - [Share and Print Speaker Notes](#share-and-print-speaker-notes)
- - [Server Side Speaker Notes](#server-side-speaker-notes)
-- [Multiplexing](#multiplexing)
- - [Master presentation](#master-presentation)
- - [Client presentation](#client-presentation)
- - [Socket.io server](#socketio-server)
-- [MathJax](#mathjax)
-- [Installation](#installation)
- - [Basic setup](#basic-setup)
- - [Full setup](#full-setup)
- - [Folder Structure](#folder-structure)
-- [License](#license)
-#### More reading
+#### More reading:
+- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer.
- [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history.
- [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own!
- [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks.
@@ -60,36 +14,14 @@ reveal.js comes with a broad range of features including [nested slides](https:/
## Online Editor
-Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [https://slides.com](https://slides.com?ref=github).
+Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slides.com](http://slides.com).
## Instructions
### Markup
-Here's a barebones example of a fully working reveal.js presentation:
-```html
-
-
-
-
-
-
-
"}return'"+(escaped?code:escape(code,true))+"\n
\n"};Renderer.prototype.blockquote=function(quote){return"'+(escaped?code:escape(code,true))+"\n\n"+quote+"
\n"};Renderer.prototype.html=function(html){return html};Renderer.prototype.heading=function(text,level,raw){return"
\n":"
\n"};Renderer.prototype.list=function(body,ordered){var type=ordered?"ol":"ul";return"<"+type+">\n"+body+""+type+">\n"};Renderer.prototype.listitem=function(text){return"\n"+"\n"+header+"\n"+"\n"+body+"\n"+"
\n"};Renderer.prototype.tablerow=function(content){return"\n"+content+" \n"};Renderer.prototype.tablecell=function(content,flags){var type=flags.header?"th":"td";var tag=flags.align?"<"+type+' style="text-align:'+flags.align+'">':"<"+type+">";return tag+content+""+type+">\n"};Renderer.prototype.strong=function(text){return""+text+""};Renderer.prototype.em=function(text){return""+text+""};Renderer.prototype.codespan=function(text){return""+text+""};Renderer.prototype.br=function(){return this.options.xhtml?"
":"
"};Renderer.prototype.del=function(text){return""+text+""};Renderer.prototype.link=function(href,title,text){if(this.options.sanitize){try{var prot=decodeURIComponent(unescape(href)).replace(/[^\w:]/g,"").toLowerCase()}catch(e){return""}if(prot.indexOf("javascript:")===0||prot.indexOf("vbscript:")===0){return""}}var out='"+text+"";return out};Renderer.prototype.image=function(href,title,text){var out='":">";return out};Renderer.prototype.text=function(text){return text};function Parser(options){this.tokens=[];this.token=null;this.options=options||marked.defaults;this.options.renderer=this.options.renderer||new Renderer;this.renderer=this.options.renderer;this.renderer.options=this.options}Parser.parse=function(src,options,renderer){var parser=new Parser(options,renderer);return parser.parse(src)};Parser.prototype.parse=function(src){this.inline=new InlineLexer(src.links,this.options,this.renderer);this.tokens=src.reverse();var out="";while(this.next()){out+=this.tok()}return out};Parser.prototype.next=function(){return this.token=this.tokens.pop()};Parser.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0};Parser.prototype.parseText=function(){var body=this.token.text;while(this.peek().type==="text"){body+="\n"+this.next().text}return this.inline.output(body)};Parser.prototype.tok=function(){switch(this.token.type){case"space":{return""}case"hr":{return this.renderer.hr()}case"heading":{return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,this.token.text)}case"code":{return this.renderer.code(this.token.text,this.token.lang,this.token.escaped)}case"table":{var header="",body="",i,row,cell,flags,j;cell="";for(i=0;i
"+escape(e.message+"",true)+"
"}throw e}}marked.options=marked.setOptions=function(opt){merge(marked.defaults,opt);return marked};marked.defaults={gfm:true,tables:true,breaks:false,pedantic:false,sanitize:false,sanitizer:null,mangle:true,smartLists:false,silent:false,highlight:null,langPrefix:"lang-",smartypants:false,headerPrefix:"",renderer:new Renderer,xhtml:false};marked.Parser=Parser;marked.parser=Parser.parse;marked.Renderer=Renderer;marked.Lexer=Lexer;marked.lexer=Lexer.lex;marked.InlineLexer=InlineLexer;marked.inlineLexer=InlineLexer.output;marked.parse=marked;if(typeof module!=="undefined"&&typeof exports==="object"){module.exports=marked}else if(typeof define==="function"&&define.amd){define(function(){return marked})}else{this.marked=marked}}).call(function(){return this||(typeof window!=="undefined"?window:global)}());
\ No newline at end of file
+(function(){function e(e){this.tokens=[],this.tokens.links={},this.options=e||a.defaults,this.rules=p.normal,this.options.gfm&&(this.rules=this.options.tables?p.tables:p.gfm)}function t(e,t){if(this.options=t||a.defaults,this.links=e,this.rules=u.normal,this.renderer=this.options.renderer||new n,this.renderer.options=this.options,!this.links)throw new Error("Tokens array requires a `links` property.");this.options.gfm?this.rules=this.options.breaks?u.breaks:u.gfm:this.options.pedantic&&(this.rules=u.pedantic)}function n(e){this.options=e||{}}function r(e){this.tokens=[],this.token=null,this.options=e||a.defaults,this.options.renderer=this.options.renderer||new n,this.renderer=this.options.renderer,this.renderer.options=this.options}function s(e,t){return e.replace(t?/&/g:/&(?!#?\w+;)/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function i(e){return e.replace(/&([#\w]+);/g,function(e,t){return t=t.toLowerCase(),"colon"===t?":":"#"===t.charAt(0)?String.fromCharCode("x"===t.charAt(1)?parseInt(t.substring(2),16):+t.substring(1)):""})}function l(e,t){return e=e.source,t=t||"",function n(r,s){return r?(s=s.source||s,s=s.replace(/(^|[^\[])\^/g,"$1"),e=e.replace(r,s),n):new RegExp(e,t)}}function o(){}function h(e){for(var t,n,r=1;r"+s(c.message+"",!0)+"
";throw c}}var p={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:o,hr:/^( *[-*_]){3,} *(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,nptable:o,lheading:/^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,blockquote:/^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,list:/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,html:/^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,def:/^ *\[([^\]]+)\]: *([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,table:o,paragraph:/^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,text:/^[^\n]+/};p.bullet=/(?:[*+-]|\d+\.)/,p.item=/^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/,p.item=l(p.item,"gm")(/bull/g,p.bullet)(),p.list=l(p.list)(/bull/g,p.bullet)("hr","\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))")("def","\\n+(?="+p.def.source+")")(),p.blockquote=l(p.blockquote)("def",p.def)(),p._tag="(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b",p.html=l(p.html)("comment",//)("closed",/<(tag)[\s\S]+?<\/\1>/)("closing",/
\n":"'+(n?e:s(e,!0))+"\n
"},n.prototype.blockquote=function(e){return""+(n?e:s(e,!0))+"\n\n"+e+"
\n"},n.prototype.html=function(e){return e},n.prototype.heading=function(e,t,n){return"
\n":"
\n"},n.prototype.list=function(e,t){var n=t?"ol":"ul";return"<"+n+">\n"+e+""+n+">\n"},n.prototype.listitem=function(e){return"\n\n"+e+"\n\n"+t+"\n
\n"},n.prototype.tablerow=function(e){return"\n"+e+" \n"},n.prototype.tablecell=function(e,t){var n=t.header?"th":"td",r=t.align?"<"+n+' style="text-align:'+t.align+'">':"<"+n+">";return r+e+""+n+">\n"},n.prototype.strong=function(e){return""+e+""},n.prototype.em=function(e){return""+e+""},n.prototype.codespan=function(e){return""+e+""},n.prototype.br=function(){return this.options.xhtml?"
":"
"},n.prototype.del=function(e){return""+e+""},n.prototype.link=function(e,t,n){if(this.options.sanitize){try{var r=decodeURIComponent(i(e)).replace(/[^\w:]/g,"").toLowerCase()}catch(s){return""}if(0===r.indexOf("javascript:")||0===r.indexOf("vbscript:"))return""}var l='"+n+""},n.prototype.image=function(e,t,n){var r='":">"},r.parse=function(e,t,n){var s=new r(t,n);return s.parse(e)},r.prototype.parse=function(e){this.inline=new t(e.links,this.options,this.renderer),this.tokens=e.reverse();for(var n="";this.next();)n+=this.tok();return n},r.prototype.next=function(){return this.token=this.tokens.pop()},r.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0},r.prototype.parseText=function(){for(var e=this.token.text;"text"===this.peek().type;)e+="\n"+this.next().text;return this.inline.output(e)},r.prototype.tok=function(){switch(this.token.type){case"space":return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code":return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table":var e,t,n,r,s,i="",l="";for(n="",e=0;e
reveal.js multiplex server.
Generate token');
- res.end();
- });
- stream.on('readable', function() {
- stream.pipe(res);
- });
+ fs.createReadStream(opts.baseDir + '/index.html').pipe(res);
});
app.get("/token", function(req,res) {
@@ -55,7 +47,7 @@ var createHash = function(secret) {
};
// Actually listen
-server.listen( opts.port || null );
+app.listen(opts.port || null);
var brown = '\033[33m',
green = '\033[32m',
diff --git a/doc/pub/Regression/html/reveal.js/plugin/multiplex/master.js b/doc/pub/Regression/html/reveal.js/plugin/multiplex/master.js
index 7f4bf4511..b6a7eb7dc 100644
--- a/doc/pub/Regression/html/reveal.js/plugin/multiplex/master.js
+++ b/doc/pub/Regression/html/reveal.js/plugin/multiplex/master.js
@@ -1,34 +1,51 @@
(function() {
-
// Don't emit events from inside of notes windows
if ( window.location.search.match( /receiver/gi ) ) { return; }
var multiplex = Reveal.getConfig().multiplex;
- var socket = io.connect( multiplex.url );
+ var socket = io.connect(multiplex.url);
- function post() {
+ var notify = function( slideElement, indexh, indexv, origin ) {
+ if( typeof origin === 'undefined' && origin !== 'remote' ) {
+ var nextindexh;
+ var nextindexv;
- var messageData = {
- state: Reveal.getState(),
- secret: multiplex.secret,
- socketId: multiplex.id
- };
+ var fragmentindex = Reveal.getIndices().f;
+ if (typeof fragmentindex == 'undefined') {
+ fragmentindex = 0;
+ }
- socket.emit( 'multiplex-statechanged', messageData );
+ if (slideElement.nextElementSibling && slideElement.parentNode.nodeName == 'SECTION') {
+ nextindexh = indexh;
+ nextindexv = indexv + 1;
+ } else {
+ nextindexh = indexh + 1;
+ nextindexv = 0;
+ }
+ var slideData = {
+ indexh : indexh,
+ indexv : indexv,
+ indexf : fragmentindex,
+ nextindexh : nextindexh,
+ nextindexv : nextindexv,
+ secret: multiplex.secret,
+ socketId : multiplex.id
+ };
+
+ socket.emit('slidechanged', slideData);
+ }
+ }
+
+ Reveal.addEventListener( 'slidechanged', function( event ) {
+ notify( event.currentSlide, event.indexh, event.indexv, event.origin );
+ } );
+
+ var fragmentNotify = function( event ) {
+ notify( Reveal.getCurrentSlide(), Reveal.getIndices().h, Reveal.getIndices().v, event.origin );
};
- // post once the page is loaded, so the client follows also on "open URL".
- window.addEventListener( 'load', post );
-
- // Monitor events that trigger a change in state
- Reveal.addEventListener( 'slidechanged', post );
- Reveal.addEventListener( 'fragmentshown', post );
- Reveal.addEventListener( 'fragmenthidden', post );
- Reveal.addEventListener( 'overviewhidden', post );
- Reveal.addEventListener( 'overviewshown', post );
- Reveal.addEventListener( 'paused', post );
- Reveal.addEventListener( 'resumed', post );
-
-}());
+ Reveal.addEventListener( 'fragmentshown', fragmentNotify );
+ Reveal.addEventListener( 'fragmenthidden', fragmentNotify );
+}());
\ No newline at end of file
diff --git a/doc/pub/Regression/html/reveal.js/plugin/notes-server/client.js b/doc/pub/Regression/html/reveal.js/plugin/notes-server/client.js
index 00b277baf..628586ffb 100644
--- a/doc/pub/Regression/html/reveal.js/plugin/notes-server/client.js
+++ b/doc/pub/Regression/html/reveal.js/plugin/notes-server/client.js
@@ -41,15 +41,10 @@
}
// When a new notes window connects, post our current state
- socket.on( 'new-subscriber', function( data ) {
+ socket.on( 'connect', function( data ) {
post();
} );
- // When the state changes from inside of the speaker view
- socket.on( 'statechanged-speaker', function( data ) {
- Reveal.setState( data.state );
- } );
-
// Monitor events that trigger a change in state
Reveal.addEventListener( 'slidechanged', post );
Reveal.addEventListener( 'fragmentshown', post );
diff --git a/doc/pub/Regression/html/reveal.js/plugin/notes-server/index.js b/doc/pub/Regression/html/reveal.js/plugin/notes-server/index.js
index b95f07188..df917f112 100644
--- a/doc/pub/Regression/html/reveal.js/plugin/notes-server/index.js
+++ b/doc/pub/Regression/html/reveal.js/plugin/notes-server/index.js
@@ -1,40 +1,37 @@
-var http = require('http');
var express = require('express');
var fs = require('fs');
var io = require('socket.io');
+var _ = require('underscore');
var Mustache = require('mustache');
-var app = express();
+var app = express.createServer();
var staticDir = express.static;
-var server = http.createServer(app);
-io = io(server);
+io = io.listen(app);
var opts = {
port : 1947,
baseDir : __dirname + '/../../'
};
-io.on( 'connection', function( socket ) {
+io.sockets.on( 'connection', function( socket ) {
- socket.on( 'new-subscriber', function( data ) {
- socket.broadcast.emit( 'new-subscriber', data );
+ socket.on( 'connect', function( data ) {
+ socket.broadcast.emit( 'connect', data );
});
socket.on( 'statechanged', function( data ) {
- delete data.state.overview;
socket.broadcast.emit( 'statechanged', data );
});
- socket.on( 'statechanged-speaker', function( data ) {
- delete data.state.overview;
- socket.broadcast.emit( 'statechanged-speaker', data );
- });
-
});
-[ 'css', 'js', 'images', 'plugin', 'lib' ].forEach( function( dir ) {
- app.use( '/' + dir, staticDir( opts.baseDir + dir ) );
+app.configure( function() {
+
+ [ 'css', 'js', 'images', 'plugin', 'lib' ].forEach( function( dir ) {
+ app.use( '/' + dir, staticDir( opts.baseDir + dir ) );
+ });
+
});
app.get('/', function( req, res ) {
@@ -55,7 +52,7 @@ app.get( '/notes/:socketId', function( req, res ) {
});
// Actually listen
-server.listen( opts.port || null );
+app.listen( opts.port || null );
var brown = '\033[33m',
green = '\033[32m',
@@ -65,5 +62,5 @@ var slidesLocation = 'http://localhost' + ( opts.port ? ( ':' + opts.port ) : ''
console.log( brown + 'reveal.js - Speaker Notes' + reset );
console.log( '1. Open the slides at ' + green + slidesLocation + reset );
-console.log( '2. Click on the link in your JS console to go to the notes page' );
+console.log( '2. Click on the link your JS console to go to the notes page' );
console.log( '3. Advance through your slides and your notes will advance automatically' );
diff --git a/doc/pub/Regression/html/reveal.js/plugin/notes-server/notes.html b/doc/pub/Regression/html/reveal.js/plugin/notes-server/notes.html
index ab8c5b17a..72d0317f1 100644
--- a/doc/pub/Regression/html/reveal.js/plugin/notes-server/notes.html
+++ b/doc/pub/Regression/html/reveal.js/plugin/notes-server/notes.html
@@ -8,7 +8,6 @@
@@ -247,7 +152,7 @@
- Time
@@ -265,10 +170,6 @@