diff --git a/doc/pub/week37/html/week37-bs.html b/doc/pub/week37/html/week37-bs.html index a7405d633..907a5adda 100644 --- a/doc/pub/week37/html/week37-bs.html +++ b/doc/pub/week37/html/week37-bs.html @@ -1,15 +1,15 @@
- + - + -@@ -183,7 +270,7 @@ MathJax.Hub.Config({
-
@@ -207,7 +294,7 @@ MathJax.Hub.Config({
@@ -148,71 +148,471 @@ MathJax.Hub.Config({
-
-Video of Lecture and handwritten notes - -
-More material will be added here, see handwritten notes also. +
-See Handwritten notes +Our basic assumption when we derived the OLS equations was to assume +that our output is determined by a given continuous function +\( f(\boldsymbol{x}) \) and a random noise \( \boldsymbol{\epsilon} \) given by the normal +distribution with zero mean value and an undetermined variance +\( \sigma^2 \). + +
+We found above that the outputs \( \boldsymbol{y} \) have a mean value given by +\( \boldsymbol{X}\hat{\boldsymbol{\beta}} \) and variance \( \sigma^2 \). Since the entries to +the design matrix are not stochastic variables, we can assume that the +probability distribution of our targets is also a normal distribution +but now with mean value \( \boldsymbol{X}\hat{\boldsymbol{\beta}} \). This means that a +single output \( y_i \) is given by the Gaussian distribution + +
+$$
+y_i\sim \mathcal{N}(\boldsymbol{X}_{i,*}\boldsymbol{\beta}, \sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
+$$
+
+We assume now that the various \( y_i \) values are stochastically distributed according to the above Gaussian distribution. +We define this distribution as +
+$$
+p(y_i, \boldsymbol{X}\vert\boldsymbol{\beta})=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]},
+$$
+
+
+which reads as finding the likelihood of an event \( y_i \) with the input variables \( \boldsymbol{X} \) given the parameters (to be determined) \( \boldsymbol{\beta} \).
+
+
+Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event \( \boldsymbol{y} \) as the product of the single events, that is we have + +
+$$
+p(\boldsymbol{y},\boldsymbol{X}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta}).
+$$
+
+
+
+We will write this in a more compact form reserving \( \boldsymbol{D} \) for the domain of events, including the ouputs (targets) and the inputs. That is +in case we have a simple one-dimensional input and output case +
+$$
+\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})].
+$$
+
+
+In the more general case the various inputs should be replaced by the possible features represented by the input data set \( \boldsymbol{X} \).
+We can now rewrite the above probability as
+
+$$
+p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
+$$
+
+
+
+It is a conditional probability (see below) and reads as the likelihood of a domain of events \( \boldsymbol{D} \) given a set of parameters \( \boldsymbol{\beta} \). +
+In statistics, maximum likelihood estimation (MLE) is a method of +estimating the parameters of an assumed probability distribution, +given some observed data. This is achieved by maximizing a likelihood +function so that, under the assumed statistical model, the observed +data is the most probable. + +
+We will assume here that our events are given by the above Gaussian +distribution and we will determine the optimal parameters \( \beta \) by +maximizing the above PDF. However, computing the derivatives of a +product function is cumbersome and can easily lead to overflow and/or +underflowproblems, with potentials for loss of numerical precision. + +
+In practice, it is more convenient to maximize the logarithm of the +PDF because it is a monotonically increasing function of the argument. +Alternatively, and this will be our option, we will minimize the +negative of the logarithm since this is a monotonically decreasing +function. + +
+Note also that maximization/minimization of the logarithm of the PDF +is equivalent to the maximization/minimization of the function itself. +
+We could now define a new cost function to minimize, namely the negative logarithm of the above PDF + +
+$$
+C(\boldsymbol{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})},
+$$
+
+
+which becomes
+
+$$
+C(\boldsymbol{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}.
+$$
+
+
+
+Taking the derivative of the new cost function with respect to the parameters \( \beta \) we recognize our familiar OLS equation, namely + +
+$$
+\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right) =0,
+$$
+
+
+which leads to the well-known OLS equation for the optimal paramters \( \beta \)
+
+$$
+\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}!
+$$
+
+
+If we combine the conditional probability with the marginal probability and the standard product rule, we have +
+$$
+p(X\vert Y)= \frac{p(X,Y)}{p(Y)},
+$$
+
+
+which we can rewrite as
+
+
+$$
+p(X\vert Y)= \frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}=\frac{p(Y\vert X)p(X)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)},
+$$
+
+
+which is Bayes' theorem. It allows us to evaluate the uncertainty in in \( X \) after we have observed \( Y \). We can easily interchange \( X \) with \( Y \).
+
+The quantity \( p(Y\vert X) \) on the right-hand side of the theorem is +evaluated for the observed data \( Y \) and can be viewed as a function of +the parameter space represented by \( X \). This function is not +necesseraly normalized and is normally called the likelihood function. + +
+The function \( p(X) \) on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution. +
+We will play around with a study of the values for the optimal +parameters \( \boldsymbol{\beta} \) using OLS, Ridge and Lasso regression. For +OLS, you will notice as function of the noise and polynomial degree, +that the parameters \( \beta \) will fluctuate from order to order in the +polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS. + +
+For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one. + +
+ + +
import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.model_selection import train_test_split
+from sklearn import linear_model
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+# Make data set.
+n = 10000
+x = np.random.rand(n)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
+
+Maxpolydegree = 5
+X = np.zeros((len(x),Maxpolydegree))
+X[:,0] = 1.0
+
+for polydegree in range(1, Maxpolydegree):
+ for degree in range(polydegree):
+ X[:,degree] = x**(degree)
+
+
+# We split the data in test and training data
+X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
+
+# matrix inversion to find beta
+OLSbeta = np.linalg.pinv(X_train.T @ X_train) @ X_train.T @ y_train
+print(OLSbeta)
+ypredictOLS = X_test @ OLSbeta
+print("Test MSE OLS")
+print(MSE(y_test,ypredictOLS))
+# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn
+# Decide which values of lambda to use
+nlambdas = 4
+MSERidgePredict = np.zeros(nlambdas)
+MSELassoPredict = np.zeros(nlambdas)
+lambdas = np.logspace(-3, 1, nlambdas)
+for i in range(nlambdas):
+ lmb = lambdas[i]
+ # Make the fit using Ridge and Lasso
+ RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
+ RegRidge.fit(X_train,y_train)
+ RegLasso = linear_model.Lasso(lmb,fit_intercept=False)
+ RegLasso.fit(X_train,y_train)
+ # and then make the prediction
+ ypredictRidge = RegRidge.predict(X_test)
+ ypredictLasso = RegLasso.predict(X_test)
+ # Compute the MSE and print it
+ MSERidgePredict[i] = MSE(y_test,ypredictRidge)
+ MSELassoPredict[i] = MSE(y_test,ypredictLasso)
+ print(lmb,RegRidge.coef_)
+ print(lmb,RegLasso.coef_)
+# Now plot the results
+plt.figure()
+plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')
+plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
++How can we understand this? +
+Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression. + +
+For ordinary least squares we postulated that the maximum likelihood for the doamin of events \( \boldsymbol{D} \) (one-dimensional case) +
+$$
+\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})],
+$$
+
+
+is given by
+
+$$
+p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
+$$
+
+
+
+In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set \( \boldsymbol{\beta} \) given a domain of events \( \boldsymbol{D} \)? That is, how can we define the posterior probability + +
+$$
+p(\boldsymbol{\beta}\vert\boldsymbol{D}).
+$$
+
+
+
+Bayes' theorem comes to our rescue here since (omitting the normalization constant) +
+$$
+p(\boldsymbol{\beta}\vert\boldsymbol{D})\propto p(\boldsymbol{D}\vert\boldsymbol{\beta})p(\boldsymbol{\beta}).
+$$
+
+
+
+We have a model for \( p(\boldsymbol{D}\vert\boldsymbol{\beta}) \) but need one for the prior \( p(\boldsymbol{\beta} \)! +
+With the posterior probability defined by a likelihood which we have +already modeled and an unknown prior, we are now ready to make +additional models for the prior. + +
+We can, based on our discussions of the variance of \( \boldsymbol{\beta} \) and the mean value, assume that the prior for the values \( \boldsymbol{\beta} \) is given by a Gaussian with mean value zero and variance \( \tau^2 \), that is + +
+$$
+p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}.
+$$
+
+
+
+Our posterior probability becomes then (omitting the normalization factor which is just a constant) +
+$$
+p(\boldsymbol{\beta\vert\boldsymbol{D})}=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}.
+$$
+
+
+
+We can now optimize this quantity with respect to \( \boldsymbol{\beta} \). As we +did for OLS, this is most conveniently done by taking the negative +logarithm of the posterior probability. Doing so and leaving out the +constants terms that do not depend on \( \beta \), we have + +
+$$
+C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{2\tau^2}\vert\vert\boldsymbol{\beta}\vert\vert_2^2,
+$$
+
+
+and replacing \( 1/2\tau^2 \) with \( \lambda \) we have
+
+
+$$
+C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_2^2,
+$$
+
+
+which is our Ridge cost function! Nice, isn't it?
+
+To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution (Laplace in this case) with zero mean value, that is + +
+$$
+p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}.
+$$
+
+
+
+Our posterior probability becomes then (omitting the normalization factor which is just a constant) +
+$$
+p(\boldsymbol{\beta}\vert\boldsymbol{D})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}.
+$$
+
+
+
+Taking the negative +logarithm of the posterior probability and leaving out the +constants terms that do not depend on \( \beta \), we have + +
+$$
+C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{\tau}\vert\vert\boldsymbol{\beta}\vert\vert_1,
+$$
+
+
+and replacing \( 1/\tau \) with \( \lambda \) we have
+
+
+$$
+C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1,
+$$
+
+
+which is our Lasso cost function!
+
+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 + +
+ +This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods. +
-The examples we have looked at so far are cases where we normally can -invert the matrix \( \boldsymbol{X}^T\boldsymbol{X} \). Using a polynomial expansion as we -did both for the masses and the fitting of the equation of state, -leads to row vectors of the design matrix which are essentially -orthogonal due to the polynomial character of our model. Obtaining the inverse of the design matrix is then often done via a so-called LU, QR or Cholesky decomposition. +Resampling 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.
-This may -however not the be case in general and a standard matrix inversion -algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below. +Two resampling methods are often used in Machine Learning analyses, +
-There is however a way to partially circumvent this problem and also gain some insights about the ordinary least squares approach, and later shrinkage methods like Ridge and Lasso regressions. -
-This is given by the Singular Value Decomposition algorithm, perhaps -the most powerful linear algebra algorithm. Let us look at a -different example where we may have problems with the standard matrix -inversion algorithm. Thereafter we dive into the math of the SVD. +In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular +cross-validation and the bootstrap method.
+Resampling approaches can be computationally expensive, because they +involve fitting the same statistical method multiple times using +different subsets of the training data. However, due to recent +advances in computing power, the computational requirements of +resampling methods generally are not prohibitive. In this chapter, we +discuss two of the most commonly used resampling methods, +cross-validation and the bootstrap. Both methods are important tools +in the practical application of many statistical learning +procedures. For example, cross-validation can be used to estimate the +test error associated with a given statistical learning method in +order to evaluate its performance, or to select the appropriate level +of flexibility. The process of evaluating a model’s performance is +known as model assessment, whereas the process of selecting the proper +level of flexibility for a model is known as model selection. The +bootstrap is widely used. + + +
-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 +With all these analytical equations for both the OLS and Ridge +regression, we will now outline how to assess a given model. This will +lead us to a discussion of the so-called bias-variance tradeoff (see +below) and so-called resampling methods. + +
+One of the quantities we have discussed as a way to measure errors is +the mean-squared error (MSE), mainly used for fitting of continuous +functions. Another choice is the absolute error. + +
+In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data, +we discuss the + +
+ +As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error. +For a certain level of complexity the test error will reach minimum, before starting to increase again. The +training error reaches a saturation. +
+Two famous +resampling methods are the independent bootstrap and the jackknife. + +
+The jackknife is a special case of the independent bootstrap. Still, the jackknife was made +popular prior to the independent bootstrap. And as the popularity of +the independent bootstrap soared, new variants, such as the dependent bootstrap. + +
+The Jackknife and independent bootstrap work for +independent, identically distributed random variables. +If these conditions are not +satisfied, the methods will fail. Yet, it should be said that if the data are +independent, identically distributed, and we only want to estimate the +variance of \( \overline{X} \) (which often is the case), then there is no +need for bootstrapping. +
+The Jackknife works by making many replicas of the estimator \( \widehat{\theta} \). +The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \( \boldsymbol{x} = (x_1,x_2,\cdots,X_n) \). +Let \( \boldsymbol{x}_i \) denote the vector +
+$$
+\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n),
+$$
+
+
+
+which equals the vector \( \boldsymbol{x} \) with the exception that observation +number \( i \) is left out. Using this notation, define +\( \widehat{\theta}_i \) to be the estimator +\( \widehat{\theta} \) computed using \( \vec{X}_i \). +
+ + +
from numpy import *
+from numpy.random import randint, randn
+from time import time
+
+def jackknife(data, stat):
+ n = len(data);t = zeros(n); inds = arange(n); t0 = time()
+ ## 'jackknifing' by leaving out an observation for each i
+ for i in range(n):
+ t[i] = stat(delete(data,i) )
+
+ # analysis
+ print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :")
+ print("original bias std. error")
+ print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))
+
+ return t
+
+
+# Returns mean of data samples
+def stat(data):
+ return mean(data)
+
+
+mu, sigma = 100, 15
+datapoints = 10000
+x = mu + sigma*random.randn(datapoints)
+# jackknife returns the data sample
+t = jackknife(x, stat)
++Bootstrapping is a nonparametric approach to statistical inference +that substitutes computation for more traditional distributional +assumptions and asymptotic results. Bootstrapping offers a number of +advantages: + +
+Since \( \widehat{\theta} = \widehat{\theta}(\boldsymbol{X}) \) is a function of random variables, +\( \widehat{\theta} \) itself must be a random variable. Thus it has +a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to +estimate \( p(\boldsymbol{t}) \) by the relative frequency of +\( \widehat{\theta} \). You can think of this as using a histogram +in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely +resembles \( p(\vec{t}) \), then using numerics, it is straight forward to +estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point +estimators. +
+In the case that \( \widehat{\theta} \) has +more than one component, and the components are independent, we use the +same estimator on each component separately. If the probability +density function of \( X_i \), \( p(x) \), had been known, then it would have +been straight forward to do this by: + +
+ +By repeated use of (1) and (2), many +estimates of \( \widehat{\theta} \) could have been obtained. The +idea is to use the relative frequency of \( \widehat{\theta}^* \) +(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \). +
+But +unless there is enough information available about the process that +generated \( X_1,X_2,\cdots,X_n \), \( p(x) \) is in general +unknown. Therefore, Efron in 1979 asked the +question: What if we replace \( p(x) \) by the relative frequency +of the observation \( X_i \); if we draw observations in accordance with +the relative frequency of the observations, will we obtain the same +result in some asymptotic sense? The answer is yes. + +
+Instead of generating the histogram for the relative +frequency of the observation \( X_i \), just draw the values +\( (X_1^*,X_2^*,\cdots,X_n^*) \) with replacement from the vector +\( \boldsymbol{X} \). +
+The independent bootstrap works like this: + +
+ +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. + +
+ + +
from numpy import *
+from numpy.random import randint, randn
+from time import time
+import matplotlib.mlab as mlab
+import matplotlib.pyplot as plt
+
+# Returns mean of bootstrap samples
+def stat(data):
+ return mean(data)
+
+# Bootstrap algorithm
+def bootstrap(data, statistic, R):
+ t = zeros(R); n = len(data); inds = arange(n); t0 = time()
+ # non-parametric bootstrap
+ for i in range(R):
+ t[i] = statistic(data[randint(0,n,n)])
+
+ # analysis
+ print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
+ print("original bias std. error")
+ print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
+ return t
+
+
+mu, sigma = 100, 15
+datapoints = 10000
+x = mu + sigma*random.randn(datapoints)
+# bootstrap returns the data sample
+t = bootstrap(x, stat, datapoints)
+# the histogram of the bootstrapped data
+n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
+
+# add a 'best fit' line
+y = mlab.normpdf( binsboot, mean(t), std(t))
+lt = plt.plot(binsboot, y, 'r--', linewidth=1)
+plt.xlabel('Smarts')
+plt.ylabel('Probability')
+plt.axis([99.5, 100.6, 0, 3.0])
+plt.grid(True)
+
+plt.show()
++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). +
$$
\begin{align*}
-\mathbf{X} & = \left[
-\begin{array}{rrr}
-1 & -1 & 2
-\\
-1 & 0 & 1
-\\
-1 & 2 & -1
-\\
-1 & 1 & 0
-\end{array} \right]
+\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 columns of \( \boldsymbol{X} \) are linearly dependent. We see this easily since the -the first column is the row-wise sum of the other two columns. The rank (more correct, -the column rank) of a matrix is the dimension of the space spanned by the -column vectors. Hence, the rank of \( \mathbf{X} \) is equal to the number -of linearly independent columns. In this particular case the matrix has rank 2. -
-Super-collinearity of an \( (n \times p) \)-dimensional design matrix \( \mathbf{X} \) implies -that the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this +
$$
\begin{align*}
-\boldsymbol{X} & = \left[
-\begin{array}{rr}
-1 & -1
-\\
-1 & -1
-\end{array} \right].
+\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*}
$$
-
-We see easily that \( \mbox{det}(\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined.
-This is equivalent to saying that the matrix \( \boldsymbol{X} \) has at least an eigenvalue which is zero.
-If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem -
-$$
-\begin{align}
-\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y},
-\tag{1}
-\end{align}
-$$
-
+For the various values of \( k \)
-has linearly dependent column vectors, we will not be able to compute the inverse
-of \( \boldsymbol{X}^T\boldsymbol{X} \) and we cannot find the parameters (estimators) \( \beta_i \).
-The estimators are only well-defined if \( (\boldsymbol{X}^{T}\boldsymbol{X})^{-1} \) exits.
-This is more likely to happen when the matrix \( \boldsymbol{X} \) is high-dimensional. In this case it is likely to encounter a situation where
-the regression parameters \( \beta_i \) cannot be estimated.
+
-A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change -
-$$
-\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I},
-$$
-
-
-where \( \boldsymbol{I} \) is the identity matrix. When we discuss Ridge regression this is actually what we end up evaluating. The parameter \( \lambda \) is called a hyperparameter. More about this later.
+
-From standard linear algebra we know that a square matrix \( \boldsymbol{X} \) can be diagonalized if and only it is -a so-called normal matrix, that is if \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \) -we have \( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) or if \( \boldsymbol{X}\in {\mathbb{C}}^{n\times n} \) we have \( \boldsymbol{X}\boldsymbol{X}^{\dagger}=\boldsymbol{X}^{\dagger}\boldsymbol{X} \). -The matrix has then a set of eigenpairs - -
-$$
-(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n),
-$$
-
-
-and the eigenvalues are given by the diagonal matrix
-
-$$
-\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n).
-$$
-
-
-The matrix \( \boldsymbol{X} \) can be written in terms of an orthogonal/unitary transformation \( \boldsymbol{U} \)
-
-$$
-\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,
-$$
-
-
-with \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I} \) or \( \boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I} \).
-
-
-Not all square matrices are diagonalizable. A matrix like the one discussed above -
-$$
-\boldsymbol{X} = \begin{bmatrix}
-1& -1 \\
-1& -1\\
-\end{bmatrix}
-$$
-
-
-is not diagonalizable, it is a so-called defective matrix. It is easy to see that the condition
-\( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) is not fulfilled.
-
-However, and this is the strength of the SVD algorithm, any general -matrix \( \boldsymbol{X} \) can be decomposed in terms of a diagonal matrix and -two orthogonal/unitary matrices. The Singular Value Decompostion -(SVD) theorem -states that a general \( m\times n \) matrix \( \boldsymbol{X} \) can be written in -terms of a diagonal matrix \( \boldsymbol{\Sigma} \) of dimensionality \( m\times n \) -and two orthognal matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \), where the first has -dimensionality \( m \times m \) and the last dimensionality \( n\times n \). -We have then - -
-$$
-\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T
-$$
-
-
-
-As an example, the above defective matrix can be decomposed as - -
-$$
-\boldsymbol{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,
-$$
-
-
-
-with eigenvalues \( \sigma_1=2 \) and \( \sigma_2=0 \). -The SVD exits always! - -
-The SVD -decomposition (singular values) gives eigenvalues -\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=p \), the -eigenvalues (singular values) are zero. - -
-In the general case, where our design matrix \( \boldsymbol{X} \) has dimension -\( n\times p \), the matrix is thus decomposed into an \( n\times n \) -orthogonal matrix \( \boldsymbol{U} \), a \( p\times p \) orthogonal matrix \( \boldsymbol{V} \) -and a diagonal matrix \( \boldsymbol{\Sigma} \) with \( r=\mathrm{min}(n,p) \) -singular values \( \sigma_i\geq 0 \) on the main diagonal and zeros filling -the rest of the matrix. There are at most \( p \) singular values -assuming that \( n > p \). In our regression examples for the nuclear -masses and the equation of state this is indeed the case, while for -the Ising model we have \( p > n \). These are often cases that lead to -near singular or singular matrices. - -
-The columns of \( \boldsymbol{U} \) are called the left singular vectors while the columns of \( \boldsymbol{V} \) are the right singular vectors. -
-If we assume that \( n > p \), then our matrix \( \boldsymbol{U} \) has dimension \( n -\times n \). The last \( n-p \) columns of \( \boldsymbol{U} \) become however -irrelevant in our calculations since they are multiplied with the -zeros in \( \boldsymbol{\Sigma} \). - -
-The economy-size decomposition removes extra rows or columns of zeros -from the diagonal matrix of singular values, \( \boldsymbol{\Sigma} \), along with the columns -in either \( \boldsymbol{U} \) or \( \boldsymbol{V} \) that multiply those zeros in the expression. -Removing these zeros and columns can improve execution time -and reduce storage requirements without compromising the accuracy of -the decomposition. - -
-If \( n > p \), we keep only the first \( p \) columns of \( \boldsymbol{U} \) and \( \boldsymbol{\Sigma} \) has dimension \( p\times p \). -If \( p > n \), then only the first \( n \) columns of \( \boldsymbol{V} \) are computed and \( \boldsymbol{\Sigma} \) has dimension \( n\times n \). -The \( n=p \) case is obvious, we retain the full SVD. -In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy. -
-
import numpy as np
-# SVD inversion
-def SVDinv(A):
- ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).
- SVD is numerically more stable than the inversion algorithms provided by
- numpy and scipy.linalg at the cost of being slower.
- '''
- U, s, VT = np.linalg.svd(A)
-# print('test U')
-# print( (np.transpose(U) @ U - U @np.transpose(U)))
-# print('test VT')
-# print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))
- print(U)
- print(s)
- print(VT)
+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
- D = np.zeros((len(U),len(VT)))
- for i in range(0,len(VT)):
- D[i,i]=s[i]
- UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)
- return np.matmul(V,np.matmul(invD,UT))
+# 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
-X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])
-print(X)
-A = np.transpose(X) @ X
-print(A)
-# Brute force inversion of super-collinear matrix
-#B = np.linalg.inv(A)
-#print(B)
-C = SVDinv(A)
-print(C)
+estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
+
+## Cross-validation using cross_val_score from sklearn along with KFold
+
+# kfold is an instance initialized above as:
+# kfold = KFold(n_splits = k)
+
+estimated_mse_sklearn = np.zeros(nlambdas)
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
+
+ X = poly.fit_transform(x[:, np.newaxis])
+ estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
+
+ # cross_val_score return an array containing the estimated negative mse for every fold.
+ # we have to the the mean of every array in order to get an estimate of the mse of the model
+ estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
+
+ i += 1
+
+## Plot and compare the slightly different ways to perform cross-validation
+
+plt.figure()
+
+plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
+plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
+
+plt.xlabel('log10(lambda)')
+plt.ylabel('mse')
+
+plt.legend()
+
+plt.show()
-
-The matrix \( \boldsymbol{X} \) has columns that are linearly dependent. The first
-column is the row-wise sum of the other two columns. The rank of a
-matrix (the column rank) is the dimension of space spanned by the
-column vectors. The rank of the matrix is the number of linearly
-independent columns, in this case just \( 2 \). We see this from the
-singular values when running the above code. Running the standard
-inversion algorithm for matrix inversion with \( \boldsymbol{X}^T\boldsymbol{X} \) results
-in the program terminating due to a singular matrix.
-Mathematical Properties
+The bias-variance tradeoff
-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 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\} \).
-We have from OLS that the parameters of the linear approximation are given by
+Let us assume that the true data is generated from a noisy model
+
$$
-\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
+\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon}
$$
-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.
+where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \).
-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.
+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} \).
-Going back to our OLS equation we have
+Thereafter we found the parameters \( \boldsymbol{\beta} \) by optimizing the means squared error via the so-called cost function
$$
-\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}.
+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 will come back to this expression when we discuss Ridge regression.
-
+
+We can rewrite this as
-$$ \tilde{y}^{OLS}={\bf X}\hat{\beta}^{OLS}=\sum_{j=1}^p {\bf u}_j{\bf u}_j^T{\bf y}$$
-
and for Ridge we have
-
+$$
+\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.
+$$
-$$ \tilde{y}^{Ridge}={\bf X}\hat{\beta}^{Ridge}=\sum_{j=1}^p {\bf u}_j\frac{\sigma_j^2}{\sigma_j^2+\lambda}{\bf u}_j^T{\bf y}$$
-
.
-It is indeed the economy-sized SVD, note the summation runs up tp
-$$p$$
-
only and not
-$$n$$
-
.
+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} \).
-Here we have that
-$${\bf X} = {\bf U}{\bf \Sigma}{\bf V}^T$$
-
, with
-$$\Sigma$$
-
being an
-$$ n\times p$$
-
matrix and
-$${\bf V}$$
-
being a
-$$ p\times p$$
-
matrix. We also have assumed here that
-$$ n > p$$
-
.
+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} \).
-Friday September 12
-
-
-Video of Lecture and handwritten notes
-
-
-More material will be added here, see handwritten notes also.
-
-
-
-
-Ridge and LASSO Regression
-
-
-Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is
-our optimization problem is
-
-$$
-{\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}.
-$$
-
-
-or we can state it as
-
-$$
-{\displaystyle \min_{\boldsymbol{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2,
-$$
-
-
-where we have used the definition of a norm-2 vector, that is
-
-$$
-\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.
-$$
-
-
-
-By minimizing the above equation with respect to the parameters
-\( \boldsymbol{\beta} \) we could then obtain an analytical expression for the
-parameters \( \boldsymbol{\beta} \). We can add a regularization parameter \( \lambda \) by
-defining a new cost function to be optimized, that is
-
-
-$$
-{\displaystyle \min_{\boldsymbol{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2
-$$
-
-
-
-which leads to the Ridge regression minimization problem where we
-require that \( \vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t \), where \( t \) is
-a finite number larger than zero. By defining
-
-
-$$
-C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1,
-$$
-
-
-
-we have a new optimization equation
-
-$$
-{\displaystyle \min_{\boldsymbol{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1
-$$
-
-
-which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.
-
-
-Here we have defined the norm-1 as
-
-$$
-\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert.
-$$
-
-
-
-
-
-More on Ridge Regression
-
-
-Using the matrix-vector expression for Ridge regression,
-
-
-$$
-C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta},
-$$
-
-
-
-by taking the derivatives with respect to \( \boldsymbol{\beta} \) we obtain then
-a slightly modified matrix inversion problem which for finite values
-of \( \lambda \) does not suffer from singularity problems. We obtain
-
-
-$$
-\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
-$$
-
-
-
-with \( \boldsymbol{I} \) being a \( p\times p \) identity matrix with the constraint that
-
-
-$$
-\sum_{i=0}^{p-1} \beta_i^2 \leq t,
-$$
-
-
-
-with \( t \) a finite positive number.
-
-
-We see that Ridge regression is nothing but the standard
-OLS with a modified diagonal term added to \( \boldsymbol{X}^T\boldsymbol{X} \). The
-consequences, in particular for our discussion of the bias-variance tradeoff
-are rather interesting.
-
-
-Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had
-
-$$
-(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}.
-$$
-
-
-
-We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as
-
-$$
-\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}
-$$
-
-
-
-For Ridge regression this becomes
-
-
-$$
-\boldsymbol{X}\boldsymbol{\beta}^{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T+\lambda\boldsymbol{I} \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\sum_{j=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{y},
-$$
-
-
-
-with the vectors \( \boldsymbol{u}_j \) being the columns of \( \boldsymbol{U} \).
-
-
-
-
-Interpreting the Ridge results
-
-
-Since \( \lambda \geq 0 \), it means that compared to OLS, we have
-
-
-$$
-\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1.
-$$
-
-
-
-Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the
-orthonormal basis \( \boldsymbol{U} \), it then shrinks the coordinates by
-\( \frac{\sigma_j^2}{\sigma_j^2+\lambda} \). Recall that the SVD has
-eigenvalues ordered in a descending way, that is \( \sigma_i \geq
-\sigma_{i+1} \).
-
-
-For small eigenvalues \( \sigma_i \) it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom.
-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.
-
-
-
-
-More interpretations
-
-
-For the sake of simplicity, let us assume that the design matrix is orthonormal, that is
-
-
-$$
-\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}.
-$$
-
-
-
-In this case the standard OLS results in
-
-$$
-\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{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.
-
-
-
-
-A better understanding of regularization
-
-
-The parameter \( \lambda \) that we have introduced in the Ridge (and
-Lasso as well) regression is often called a regularization parameter
-or shrinkage parameter. It is common to call it a hyperparameter. What does it mean mathemtically?
-
-
-Here we will first look at how to analyze the difference between the
-standard OLS equations and the Ridge expressions in terms of a linear
-algebra analysis using the SVD algorithm. Thereafter, we will link
-(see the material on the bias-variance tradeoff below) these
-observation to the statisical analysis of the results. In particular
-we consider how the variance of the parameters \( \boldsymbol{\beta} \) is
-affected by changing the parameter \( \lambda \).
-
-
-
-
-Decomposing the OLS and Ridge expressions
-
-
-We have our design matrix
- \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). With the SVD we decompose it as
-
-
-$$
-\boldsymbol{X} = \boldsymbol{U\Sigma V^T},
-$$
-
-
-
-with \( \boldsymbol{U}\in {\mathbb{R}}^{n\times n} \), \( \boldsymbol{\Sigma}\in {\mathbb{R}}^{n\times p} \)
-and \( \boldsymbol{V}\in {\mathbb{R}}^{p\times p} \).
-
-
-The matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are unitary/orthonormal matrices, that is in case the matrices are real we have \( \boldsymbol{U}^T\boldsymbol{U}=\boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I} \) and \( \boldsymbol{V}^T\boldsymbol{V}=\boldsymbol{V}\boldsymbol{V}^T=\boldsymbol{I} \).
-
-
-
-
-Introducing the Covariance and Correlation functions
-
-
-Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about
-the definition of the covariance and the correlation function. These are quantities
-
-
-Suppose we have defined two vectors
-\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as
-
-$$
-\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\
- \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\
- \end{bmatrix},
-$$
-
-
-where for example
-
-$$
-\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}).
-$$
-
-
-With this definition and recalling that the variance is defined as
-
-$$
-\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2,
-$$
-
-
-we can rewrite the covariance matrix as
-
-$$
-\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\
- \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\
- \end{bmatrix}.
-$$
-
-
-
-The covariance takes values between zero and infinity and may thus
-lead to problems with loss of numerical precision for particularly
-large values. It is common to scale the covariance matrix by
-introducing instead the correlation matrix defined via the so-called
-correlation function
-
-
-$$
-\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}.
-$$
-
-
-
-The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]
-\in [-1,1] \). This avoids eventual problems with too large values. We
-can then define the correlation matrix for the two vectors \( \boldsymbol{x} \)
-and \( \boldsymbol{y} \) as
-
-
-$$
-\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\
- \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\
- \end{bmatrix},
-$$
-
-
-
-In the above example this is the function we constructed using pandas.
-
-
-
-
-Correlation Function and Design/Feature Matrix
-
-
-In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression
-we defined the design/feature matrix \( \boldsymbol{X} \) as
-
-
-$$
-\boldsymbol{X}=\begin{bmatrix}
-x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\
-x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\
-x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\
-\dots & \dots & \dots & \dots \dots & \dots \\
-x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\
-x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\
-\end{bmatrix},
-$$
-
-
-with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the
-entries \( n \) being the row elements.
-We can rewrite the design/feature matrix in terms of its column vectors as
-
-$$
-\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix},
-$$
-
-
-with a given vector
-
-$$
-\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}.
-$$
-
-
-
-With these definitions, we can now rewrite our \( 2\times 2 \)
-correaltion/covariance matrix in terms of a moe general design/feature
-matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \)
-covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \)
-
-
-$$
-\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix}
-\mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\
-\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\
-\mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_1] & \mathrm{var}[\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & \mathrm{var}[\boldsymbol{x}_{p-1}]\\
-\end{bmatrix},
-$$
-
-
-and the correlation matrix
-
-$$
-\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix}
-1 & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\
-\mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_0] & 1 & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\
-\mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & 1\\
-\end{bmatrix},
-$$
-
-
-
-
-
-Covariance Matrix Examples
-
-
-The Numpy function np.cov calculates the covariance elements using
-the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have
-the exact mean values. The following simple function uses the
-np.vstack function which takes each vector of dimension \( 1\times n \)
-and produces a \( 2\times n \) matrix \( \boldsymbol{W} \)
-
-
-$$
-\boldsymbol{W} = \begin{bmatrix} x_0 & y_0 \\
- x_1 & y_1 \\
- x_2 & y_2\\
- \dots & \dots \\
- x_{n-2} & y_{n-2}\\
- x_{n-1} & y_{n-1} &
- \end{bmatrix},
-$$
-
-
-
-which in turn is converted into into the \( 2\times 2 \) covariance matrix
-\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate
-the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy
-function np.mean(x). We can also extract the eigenvalues of the
-covariance matrix through the np.linalg.eig() function.
-
+
Example code for Bias-Variance tradeoff
-
# Importing various packages
+import matplotlib.pyplot as plt
import numpy as np
-n = 100
-x = np.random.normal(size=n)
-print(np.mean(x))
-y = 4+3*x+np.random.normal(size=n)
-print(np.mean(y))
-W = np.vstack((x, y))
-C = np.cov(W)
-print(C)
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+
+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()
-Correlation Matrix
-
-
-The previous example can be converted into the correlation matrix by
-simply scaling the matrix elements with the variances. We should also
-subtract the mean values for each column. This leads to the following
-code which sets up the correlations matrix for the previous example in
-a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors).
-
+
Understanding what happens
-
import numpy as np
-n = 100
-# define two vectors
-x = np.random.random(size=n)
-y = 4+3*x+np.random.normal(size=n)
-#scaling the x and y vectors
-x = x - np.mean(x)
-y = y - np.mean(y)
-variance_x = np.sum(x@x)/n
-variance_y = np.sum(y@y)/n
-print(variance_x)
-print(variance_y)
-cov_xy = np.sum(x@y)/n
-cov_xx = np.sum(x@x)/n
-cov_yy = np.sum(y@y)/n
-C = np.zeros((2,2))
-C[0,0]= cov_xx/variance_x
-C[1,1]= cov_yy/variance_y
-C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
-C[1,0]= C[0,1]
-print(C)
-
-
-We see that the matrix elements along the diagonal are one as they
-should be and that the matrix is symmetric. Furthermore, diagonalizing
-this matrix we easily see that it is a positive definite matrix.
+
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
-
-The above procedure with numpy can be made more compact if we use pandas.
+np.random.seed(2018)
+
+n = 40
+n_boostraps = 100
+maxdegree = 14
+
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+for degree in range(maxdegree):
+ model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
+ y_pred = np.empty((y_test.shape[0], n_boostraps))
+ for i in range(n_boostraps):
+ x_, y_ = resample(x_train, y_train)
+ y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
+
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+ variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+ print('Polynomial degree:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+plt.show()
+
-Correlation Matrix with Pandas
+Summing up
-We whow here how we can set up the correlation matrix using pandas, as done in this simple code
-
+The bias-variance tradeoff summarizes the fundamental tension in
+machine learning, particularly supervised learning, between the
+complexity of a model and the amount of training data needed to train
+it. Since data is often limited, in practice it is often useful to
+use a less-complex model with higher bias, that is a model whose asymptotic
+performance is worse than another model because it is easier to
+train and less sensitive to sampling noise arising from having a
+finite-sized training dataset (smaller variance).
-
-
import numpy as np
-import pandas as pd
-n = 10
-x = np.random.normal(size=n)
-x = x - np.mean(x)
-y = 4+3*x+np.random.normal(size=n)
-y = y - np.mean(y)
-X = (np.vstack((x, y))).T
-print(X)
-Xpd = pd.DataFrame(X)
-print(Xpd)
-correlation_matrix = Xpd.corr()
-print(correlation_matrix)
-
-We expand this model to the Franke function discussed above.
+The above equations tell us that in
+order to minimize the expected test error, we need to select a
+statistical learning method that simultaneously achieves low variance
+and low bias. Note that variance is inherently a nonnegative quantity,
+and squared bias is also nonnegative. Hence, we see that the expected
+test MSE can never lie below \( Var(\epsilon) \), the irreducible error.
+
+
+What do we mean by the variance and bias of a statistical learning
+method? The variance refers to the amount by which our model would change if we
+estimated it using a different training data set. Since the training
+data are used to fit the statistical learning method, different
+training data sets will result in a different estimate. But ideally the
+estimate for our model should not vary too much between training
+sets. However, if a method has high variance then small changes in
+the training data can result in large changes in the model. In general, more
+flexible statistical methods have higher variance.
+
+
+You may also find this recent article of interest.
-Correlation Matrix with Pandas and the Franke function
+Another Example from 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()
+
+
+
+
+
+More examples on bootstrap and cross-validation and errors
-
# Common imports
+# Common imports
+import os
import numpy as np
import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.model_selection import train_test_split
+from sklearn.utils import resample
+from sklearn.metrics import mean_squared_error
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
-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
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
-def create_X(x, y, n ):
- if len(x.shape) > 1:
- x = np.ravel(x)
- y = np.ravel(y)
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
- N = len(x)
- l = int((n+1)*(n+2)/2) # Number of elements in beta
- X = np.ones((N,l))
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
- for i in range(1,n+1):
- q = int((i)*(i+1)/2)
- for k in range(i+1):
- X[:,q+k] = (x**(i-k))*(y**k)
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
- return X
+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
-# Making meshgrid of datapoints and compute Franke's function
-n = 4
-N = 100
-x = np.sort(np.random.uniform(0, 1, N))
-y = np.sort(np.random.uniform(0, 1, N))
-z = FrankeFunction(x, y)
-X = create_X(x, y, n=n)
+Maxpolydegree = 30
+X = np.zeros((len(Density),Maxpolydegree))
+X[:,0] = 1.0
+testerror = np.zeros(Maxpolydegree)
+trainingerror = np.zeros(Maxpolydegree)
+polynomial = np.zeros(Maxpolydegree)
-Xpd = pd.DataFrame(X)
-# subtract the mean values and set up the covariance matrix
-Xpd = Xpd - Xpd.mean()
-covariance_matrix = Xpd.cov()
-print(covariance_matrix)
+trials = 100
+for polydegree in range(1, Maxpolydegree):
+ polynomial[polydegree] = polydegree
+ for degree in range(polydegree):
+ X[:,degree] = Density**(degree/3.0)
+
+# loop over trials in order to estimate the expectation value of the MSE
+ testerror[polydegree] = 0.0
+ trainingerror[polydegree] = 0.0
+ for samples in range(trials):
+ x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
+ model = LinearRegression(fit_intercept=True).fit(x_train, y_train)
+ ypred = model.predict(x_train)
+ ytilde = model.predict(x_test)
+ testerror[polydegree] += mean_squared_error(y_test, ytilde)
+ trainingerror[polydegree] += mean_squared_error(y_train, ypred)
+
+ testerror[polydegree] /= trials
+ trainingerror[polydegree] /= trials
+ print("Degree of polynomial: %3d"% polynomial[polydegree])
+ print("Mean squared error on training data: %.8f" % trainingerror[polydegree])
+ print("Mean squared error on test data: %.8f" % testerror[polydegree])
+
+plt.plot(polynomial, np.log10(trainingerror), label='Training Error')
+plt.plot(polynomial, np.log10(testerror), label='Test Error')
+plt.xlabel('Polynomial degree')
+plt.ylabel('log10[MSE]')
+plt.legend()
+plt.show()
-
-We note here that the covariance is zero for the first rows and
-columns since all matrix elements in the design matrix were set to one
-(we are fitting the function in terms of a polynomial of degree \( n \)).
-
-
-This means that the variance for these elements will be zero and will
-cause problems when we set up the correlation matrix. We can simply
-drop these elements and construct a correlation
-matrix without these elements.
-Rewriting the Covariance and/or Correlation Matrix
+The same example but now with cross-validation
-We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as
-
-$$
-\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}].
-$$
-
-
-To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \)
-
-$$
-\boldsymbol{X}=\begin{bmatrix}
-x_{00} & x_{01}\\
-x_{10} & x_{11}\\
-\end{bmatrix}=\begin{bmatrix}
-\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\
-\end{bmatrix}.
-$$
-
+
+
# Common imports
+import os
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.metrics import mean_squared_error
+from sklearn.model_selection import KFold
+from sklearn.model_selection import cross_val_score
-
-If we then compute the expectation value
-
-$$
-\mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}=\begin{bmatrix}
-x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\
-x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\
-\end{bmatrix},
-$$
-
-which is just
-
-$$
-\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]=\begin{bmatrix} \mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] \\
- \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\
- \end{bmatrix},
-$$
-
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
-where we wrote
-$$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$
-
to indicate that this the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \).
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
-
-It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \).
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
+
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
+
+infile = open(data_path("EoS.csv"),'r')
+
+# Read the EoS data as csv file and organize the data into two arrays with density and energies
+EoS = pd.read_csv(infile, names=('Density', 'Energy'))
+EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
+EoS = EoS.dropna()
+Energies = EoS['Energy']
+Density = EoS['Density']
+# The design matrix now as function of various polytrops
+
+Maxpolydegree = 30
+X = np.zeros((len(Density),Maxpolydegree))
+X[:,0] = 1.0
+estimated_mse_sklearn = np.zeros(Maxpolydegree)
+polynomial = np.zeros(Maxpolydegree)
+k =5
+kfold = KFold(n_splits = k)
+
+for polydegree in range(1, Maxpolydegree):
+ polynomial[polydegree] = polydegree
+ for degree in range(polydegree):
+ X[:,degree] = Density**(degree/3.0)
+ OLS = LinearRegression()
+# loop over trials in order to estimate the expectation value of the MSE
+ estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)
+#[:, np.newaxis]
+ estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)
+
+plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')
+plt.xlabel('Polynomial degree')
+plt.ylabel('log10[MSE]')
+plt.legend()
+plt.show()
+
-Linking with SVD
+Cross-validation with Ridge
+
+
+
+
import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.model_selection import KFold
+from sklearn.linear_model import Ridge
+from sklearn.model_selection import cross_val_score
+from sklearn.preprocessing import PolynomialFeatures
+
+# A seed just to ensure that the random numbers are the same for every run.
+np.random.seed(3155)
+# Generate the data.
+n = 100
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+# Decide degree on polynomial to fit
+poly = PolynomialFeatures(degree = 10)
+
+# Decide which values of lambda to use
+nlambdas = 500
+lambdas = np.logspace(-3, 5, nlambdas)
+# Initialize a KFold instance
+k = 5
+kfold = KFold(n_splits = k)
+estimated_mse_sklearn = np.zeros(nlambdas)
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
+ estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)
+ estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
+ i += 1
+plt.figure()
+plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
+
diff --git a/doc/pub/week37/html/week37-solarized.html b/doc/pub/week37/html/week37-solarized.html
index d13e7f564..da1fa2df3 100644
--- a/doc/pub/week37/html/week37-solarized.html
+++ b/doc/pub/week37/html/week37-solarized.html
@@ -1,19 +1,19 @@
-
+
-
+
-Week 37: Ridge and Lasso Regression
+Week 37: Summary of Ridge and Lasso Regression and Resampling Methods
-
-
+
+
@@ -48,10 +48,10 @@ pre {
.alert-block > p, .alert-block > ul {margin-bottom:1em}
.alert li {margin-top: 1em}
.alert-block p+p {margin-top:5px}
-.alert-notice { background-image: url(https://cdn.rawgit.com/hplgit/doconce/master/bundled/html_images/small_yellow_notice.png); }
-.alert-summary { background-image:url(https://cdn.rawgit.com/hplgit/doconce/master/bundled/html_images/small_yellow_summary.png); }
-.alert-warning { background-image: url(https://cdn.rawgit.com/hplgit/doconce/master/bundled/html_images/small_yellow_warning.png); }
-.alert-question {background-image:url(https://cdn.rawgit.com/hplgit/doconce/master/bundled/html_images/small_yellow_question.png); }
+.alert-notice { background-image: url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_yellow_notice.png); }
+.alert-summary { background-image:url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_yellow_summary.png); }
+.alert-warning { background-image: url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_yellow_warning.png); }
+.alert-question {background-image:url(https://cdn.rawgit.com/doconce/doconce/master/bundled/html_images/small_yellow_question.png); }
div { text-align: justify; text-justify: inter-word; }
@@ -61,51 +61,125 @@ div { text-align: justify; text-justify: inter-word; }
@@ -131,7 +205,7 @@ MathJax.Hub.Config({
-Week 37: Ridge and Lasso Regression
+Week 37: Summary of Ridge and Lasso Regression and Resampling Methods
@@ -147,64 +221,416 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
Sep 16, 2020
+Sep 12, 2021
-
Plans for week 37
+Plans for week 37
-- Thursday September 10: Motivation for shrinkage methods and the Singular Value Decompostion theorem
-- Friday September 11: Ridge and Lasso regression
+- Thursday September 16: Summary of Ridge and Lasso with examples and start resampling techniques
+- Friday September 17: Resampling methods, Cross-validation, Bootstrapping and jackknife
-Thursday September 10
-
-
-Video of Lecture and handwritten notes
-
-
-More material will be added here, see handwritten notes also.
-
-
-
A Bayesian approach to develop intuition about skrinkage methods
-
-
-See Handwritten notes
+
Thursday September 16, Summary of Ridge and Lasso Regression and start Resampling methods
-
The singular value decomposition
+Deriving OLS from a probability distribution
+Our basic assumption when we derived the OLS equations was to assume
+that our output is determined by a given continuous function
+\( f(\boldsymbol{x}) \) and a random noise \( \boldsymbol{\epsilon} \) given by the normal
+distribution with zero mean value and an undetermined variance
+\( \sigma^2 \).
+
+
+We found above that the outputs \( \boldsymbol{y} \) have a mean value given by
+\( \boldsymbol{X}\hat{\boldsymbol{\beta}} \) and variance \( \sigma^2 \). Since the entries to
+the design matrix are not stochastic variables, we can assume that the
+probability distribution of our targets is also a normal distribution
+but now with mean value \( \boldsymbol{X}\hat{\boldsymbol{\beta}} \). This means that a
+single output \( y_i \) is given by the Gaussian distribution
+
+$$
+y_i\sim \mathcal{N}(\boldsymbol{X}_{i,*}\boldsymbol{\beta}, \sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
+$$
+
+
+
+
+
Independent and Identically Distrubuted (iid)
+
+
+We assume now that the various \( y_i \) values are stochastically distributed according to the above Gaussian distribution.
+We define this distribution as
+$$
+p(y_i, \boldsymbol{X}\vert\boldsymbol{\beta})=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]},
+$$
+
+which reads as finding the likelihood of an event \( y_i \) with the input variables \( \boldsymbol{X} \) given the parameters (to be determined) \( \boldsymbol{\beta} \).
+
+
+Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event \( \boldsymbol{y} \) as the product of the single events, that is we have
+
+$$
+p(\boldsymbol{y},\boldsymbol{X}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta}).
+$$
+
+
+We will write this in a more compact form reserving \( \boldsymbol{D} \) for the domain of events, including the ouputs (targets) and the inputs. That is
+in case we have a simple one-dimensional input and output case
+$$
+\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})].
+$$
+
+In the more general case the various inputs should be replaced by the possible features represented by the input data set \( \boldsymbol{X} \).
+We can now rewrite the above probability as
+$$
+p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
+$$
+
+
+It is a conditional probability (see below) and reads as the likelihood of a domain of events \( \boldsymbol{D} \) given a set of parameters \( \boldsymbol{\beta} \).
+
+
+
+
+
Maximum Likelihood Estimation (MLE)
+
+
+In statistics, maximum likelihood estimation (MLE) is a method of
+estimating the parameters of an assumed probability distribution,
+given some observed data. This is achieved by maximizing a likelihood
+function so that, under the assumed statistical model, the observed
+data is the most probable.
+
+
+We will assume here that our events are given by the above Gaussian
+distribution and we will determine the optimal parameters \( \beta \) by
+maximizing the above PDF. However, computing the derivatives of a
+product function is cumbersome and can easily lead to overflow and/or
+underflowproblems, with potentials for loss of numerical precision.
+
+
+In practice, it is more convenient to maximize the logarithm of the
+PDF because it is a monotonically increasing function of the argument.
+Alternatively, and this will be our option, we will minimize the
+negative of the logarithm since this is a monotonically decreasing
+function.
+
+
+Note also that maximization/minimization of the logarithm of the PDF
+is equivalent to the maximization/minimization of the function itself.
+
+
+
+
+
A new Cost Function
+
+
+We could now define a new cost function to minimize, namely the negative logarithm of the above PDF
+
+$$
+C(\boldsymbol{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})},
+$$
+
+which becomes
+$$
+C(\boldsymbol{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}.
+$$
+
+
+Taking the derivative of the new cost function with respect to the parameters \( \beta \) we recognize our familiar OLS equation, namely
+
+$$
+\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right) =0,
+$$
+
+which leads to the well-known OLS equation for the optimal paramters \( \beta \)
+$$
+\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}!
+$$
+
+
+
+
+
Bayes' Theorem
+
+
+If we combine the conditional probability with the marginal probability and the standard product rule, we have
+$$
+p(X\vert Y)= \frac{p(X,Y)}{p(Y)},
+$$
+
+which we can rewrite as
+
+$$
+p(X\vert Y)= \frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}=\frac{p(Y\vert X)p(X)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)},
+$$
+
+which is Bayes' theorem. It allows us to evaluate the uncertainty in in \( X \) after we have observed \( Y \). We can easily interchange \( X \) with \( Y \).
+
+
+
+
+
Interpretations of Bayes' Theorem
+
+
+The quantity \( p(Y\vert X) \) on the right-hand side of the theorem is
+evaluated for the observed data \( Y \) and can be viewed as a function of
+the parameter space represented by \( X \). This function is not
+necesseraly normalized and is normally called the likelihood function.
+
+
+The function \( p(X) \) on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution.
+
+
+
+
+
Test Function for what happens with OLS, Ridge and Lasso
+
+
+We will play around with a study of the values for the optimal
+parameters \( \boldsymbol{\beta} \) using OLS, Ridge and Lasso regression. For
+OLS, you will notice as function of the noise and polynomial degree,
+that the parameters \( \beta \) will fluctuate from order to order in the
+polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS.
+
+
+For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one.
+
+
+
+
+
import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.model_selection import train_test_split
+from sklearn import linear_model
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+# Make data set.
+n = 10000
+x = np.random.rand(n)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
+
+Maxpolydegree = 5
+X = np.zeros((len(x),Maxpolydegree))
+X[:,0] = 1.0
+
+for polydegree in range(1, Maxpolydegree):
+ for degree in range(polydegree):
+ X[:,degree] = x**(degree)
+
+
+# We split the data in test and training data
+X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
+
+# matrix inversion to find beta
+OLSbeta = np.linalg.pinv(X_train.T @ X_train) @ X_train.T @ y_train
+print(OLSbeta)
+ypredictOLS = X_test @ OLSbeta
+print("Test MSE OLS")
+print(MSE(y_test,ypredictOLS))
+# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn
+# Decide which values of lambda to use
+nlambdas = 4
+MSERidgePredict = np.zeros(nlambdas)
+MSELassoPredict = np.zeros(nlambdas)
+lambdas = np.logspace(-3, 1, nlambdas)
+for i in range(nlambdas):
+ lmb = lambdas[i]
+ # Make the fit using Ridge and Lasso
+ RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
+ RegRidge.fit(X_train,y_train)
+ RegLasso = linear_model.Lasso(lmb,fit_intercept=False)
+ RegLasso.fit(X_train,y_train)
+ # and then make the prediction
+ ypredictRidge = RegRidge.predict(X_test)
+ ypredictLasso = RegLasso.predict(X_test)
+ # Compute the MSE and print it
+ MSERidgePredict[i] = MSE(y_test,ypredictRidge)
+ MSELassoPredict[i] = MSE(y_test,ypredictLasso)
+ print(lmb,RegRidge.coef_)
+ print(lmb,RegLasso.coef_)
+# Now plot the results
+plt.figure()
+plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')
+plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
+
+
+How can we understand this?
+
+
+
+
+
Invoking Bayes' theorem
+
+
+Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression.
+
+
+For ordinary least squares we postulated that the maximum likelihood for the doamin of events \( \boldsymbol{D} \) (one-dimensional case)
+$$
+\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})],
+$$
+
+is given by
+$$
+p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
+$$
+
+
+In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set \( \boldsymbol{\beta} \) given a domain of events \( \boldsymbol{D} \)? That is, how can we define the posterior probability
+
+$$
+p(\boldsymbol{\beta}\vert\boldsymbol{D}).
+$$
+
+
+Bayes' theorem comes to our rescue here since (omitting the normalization constant)
+$$
+p(\boldsymbol{\beta}\vert\boldsymbol{D})\propto p(\boldsymbol{D}\vert\boldsymbol{\beta})p(\boldsymbol{\beta}).
+$$
+
+
+We have a model for \( p(\boldsymbol{D}\vert\boldsymbol{\beta}) \) but need one for the prior \( p(\boldsymbol{\beta} \)!
+
+
+
+
+
Ridge and Bayes
+
+
+With the posterior probability defined by a likelihood which we have
+already modeled and an unknown prior, we are now ready to make
+additional models for the prior.
+
+
+We can, based on our discussions of the variance of \( \boldsymbol{\beta} \) and the mean value, assume that the prior for the values \( \boldsymbol{\beta} \) is given by a Gaussian with mean value zero and variance \( \tau^2 \), that is
+
+$$
+p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}.
+$$
+
+
+Our posterior probability becomes then (omitting the normalization factor which is just a constant)
+$$
+p(\boldsymbol{\beta\vert\boldsymbol{D})}=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}.
+$$
+
+
+We can now optimize this quantity with respect to \( \boldsymbol{\beta} \). As we
+did for OLS, this is most conveniently done by taking the negative
+logarithm of the posterior probability. Doing so and leaving out the
+constants terms that do not depend on \( \beta \), we have
+
+$$
+C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{2\tau^2}\vert\vert\boldsymbol{\beta}\vert\vert_2^2,
+$$
+
+and replacing \( 1/2\tau^2 \) with \( \lambda \) we have
+
+$$
+C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_2^2,
+$$
+
+which is our Ridge cost function! Nice, isn't it?
+
+
+
+
+
Lasso and Bayes
+
+
+To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution (Laplace in this case) with zero mean value, that is
+
+$$
+p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}.
+$$
+
+
+Our posterior probability becomes then (omitting the normalization factor which is just a constant)
+$$
+p(\boldsymbol{\beta}\vert\boldsymbol{D})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}.
+$$
+
+
+Taking the negative
+logarithm of the posterior probability and leaving out the
+constants terms that do not depend on \( \beta \), we have
+
+$$
+C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{\tau}\vert\vert\boldsymbol{\beta}\vert\vert_1,
+$$
+
+and replacing \( 1/\tau \) with \( \lambda \) we have
+
+$$
+C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1,
+$$
+
+which is our Lasso cost function!
+
+
+
+
+
Why resampling methods
+
+
+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
+
+
+- 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
+
+
+This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods.
+
+
+
+
+
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.
-The examples we have looked at so far are cases where we normally can
-invert the matrix \( \boldsymbol{X}^T\boldsymbol{X} \). Using a polynomial expansion as we
-did both for the masses and the fitting of the equation of state,
-leads to row vectors of the design matrix which are essentially
-orthogonal due to the polynomial character of our model. Obtaining the inverse of the design matrix is then often done via a so-called LU, QR or Cholesky decomposition.
+Two resampling methods are often used in Machine Learning analyses,
-
-This may
-however not the be case in general and a standard matrix inversion
-algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.
+
+- The bootstrap method
+- and Cross-Validation
+
-
-There is however a way to partially circumvent this problem and also gain some insights about the ordinary least squares approach, and later shrinkage methods like Ridge and Lasso regressions.
-
-
-This is given by the Singular Value Decomposition algorithm, perhaps
-the most powerful linear algebra algorithm. Let us look at a
-different example where we may have problems with the standard matrix
-inversion algorithm. Thereafter we dive into the math of the SVD.
+In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular
+cross-validation and the bootstrap method.
@@ -213,892 +639,1032 @@ inversion algorithm. Thereafter we dive into the math of the SVD.
-
Linear Regression Problems
+Resampling approaches can be computationally expensive
+
+
+
-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*}
-$$
+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 columns of \( \boldsymbol{X} \) are linearly dependent. We see this easily since the
-the first column is the row-wise sum of the other two columns. The rank (more correct,
-the column rank) of a matrix is the dimension of the space spanned by the
-column vectors. Hence, the rank of \( \mathbf{X} \) is equal to the number
-of linearly independent columns. In this particular case the matrix has rank 2.
-
-Super-collinearity of an \( (n \times p) \)-dimensional design matrix \( \mathbf{X} \) implies
-that the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this
-$$
-\begin{align*}
-\boldsymbol{X} & = \left[
-\begin{array}{rr}
-1 & -1
-\\
-1 & -1
-\end{array} \right].
-\end{align*}
-$$
+
-We see easily that \( \mbox{det}(\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined.
-This is equivalent to saying that the matrix \( \boldsymbol{X} \) has at least an eigenvalue which is zero.
-
Fixing the singularity
-
+Why resampling methods ?
+
+Statistical analysis
-If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem
-$$
-\begin{align}
-\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y},
-\label{_auto1}
-\end{align}
-$$
-has linearly dependent column vectors, we will not be able to compute the inverse
-of \( \boldsymbol{X}^T\boldsymbol{X} \) and we cannot find the parameters (estimators) \( \beta_i \).
-The estimators are only well-defined if \( (\boldsymbol{X}^{T}\boldsymbol{X})^{-1} \) exits.
-This is more likely to happen when the matrix \( \boldsymbol{X} \) is high-dimensional. In this case it is likely to encounter a situation where
-the regression parameters \( \beta_i \) cannot be estimated.
+
+- Our simulations can be treated as computer experiments. This is particularly the case for Monte Carlo methods
+- The results can be analysed with the same statistical tools as we would use analysing experimental data.
+- As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
+
+
-
-A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change
-$$
-\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I},
-$$
-
-where \( \boldsymbol{I} \) is the identity matrix. When we discuss Ridge regression this is actually what we end up evaluating. The parameter \( \lambda \) is called a hyperparameter. More about this later.
-
Basic math of the SVD
-
+Statistical analysis
+
+
-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),
-$$
+
+- As in other experiments, many numerical experiments have two classes of errors:
-and the eigenvalues are given by the diagonal matrix
-$$
-\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n).
-$$
+
+ - Statistical errors
+ - Systematical errors
+
-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,
-$$
+- Statistical errors can be estimated using standard tools from statistics
+- Systematical errors are method specific and must be treated differently from case to case.
+
+
-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.
-
The SVD, a Fantastic Algorithm
+Resampling methods
-However, and this is the strength of the SVD algorithm, any general
-matrix \( \boldsymbol{X} \) can be decomposed in terms of a diagonal matrix and
-two orthogonal/unitary matrices. The Singular Value Decompostion
-(SVD) theorem
-states that a general \( m\times n \) matrix \( \boldsymbol{X} \) can be written in
-terms of a diagonal matrix \( \boldsymbol{\Sigma} \) of dimensionality \( m\times n \)
-and two orthognal matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \), where the first has
-dimensionality \( m \times m \) and the last dimensionality \( n\times n \).
-We have then
-
-$$
-\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T
-$$
+With all these analytical equations for both the OLS and Ridge
+regression, we will now outline how to assess a given model. This will
+lead us to a discussion of the so-called bias-variance tradeoff (see
+below) and so-called resampling methods.
-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,
-$$
+One of the quantities we have discussed as a way to measure errors is
+the mean-squared error (MSE), mainly used for fitting of continuous
+functions. Another choice is the absolute error.
-with eigenvalues \( \sigma_1=2 \) and \( \sigma_2=0 \).
-The SVD exits always!
+In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,
+we discuss the
-
-The SVD
-decomposition (singular values) gives eigenvalues
-\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=p \), the
-eigenvalues (singular values) are zero.
+
+- prediction error or simply the test error \( \mathrm{Err_{Test}} \), where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the
+- training error \( \mathrm{Err_{Train}} \), which is the average loss over the training data.
+
-
-In the general case, where our design matrix \( \boldsymbol{X} \) has dimension
-\( n\times p \), the matrix is thus decomposed into an \( n\times n \)
-orthogonal matrix \( \boldsymbol{U} \), a \( p\times p \) orthogonal matrix \( \boldsymbol{V} \)
-and a diagonal matrix \( \boldsymbol{\Sigma} \) with \( r=\mathrm{min}(n,p) \)
-singular values \( \sigma_i\geq 0 \) on the main diagonal and zeros filling
-the rest of the matrix. There are at most \( p \) singular values
-assuming that \( n > p \). In our regression examples for the nuclear
-masses and the equation of state this is indeed the case, while for
-the Ising model we have \( p > n \). These are often cases that lead to
-near singular or singular matrices.
-
-
-The columns of \( \boldsymbol{U} \) are called the left singular vectors while the columns of \( \boldsymbol{V} \) are the right singular vectors.
+As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.
+For a certain level of complexity the test error will reach minimum, before starting to increase again. The
+training error reaches a saturation.
-
Economy-size SVD
+Resampling methods: Jackknife and Bootstrap
-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} \).
+Two famous
+resampling methods are the independent bootstrap and the jackknife.
-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.
+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.
-If \( n > p \), we keep only the first \( p \) columns of \( \boldsymbol{U} \) and \( \boldsymbol{\Sigma} \) has dimension \( p\times p \).
-If \( p > n \), then only the first \( n \) columns of \( \boldsymbol{V} \) are computed and \( \boldsymbol{\Sigma} \) has dimension \( n\times n \).
-The \( n=p \) case is obvious, we retain the full SVD.
-In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.
+The 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.
-
Codes for the SVD
+Resampling methods: Jackknife
+
+
+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),
+$$
+
+
+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 \).
+
+
+
+
+
Jackknife code example
+
+
+
+
from numpy import *
+from numpy.random import randint, randn
+from time import time
+
+def jackknife(data, stat):
+ n = len(data);t = zeros(n); inds = arange(n); t0 = time()
+ ## 'jackknifing' by leaving out an observation for each i
+ for i in range(n):
+ t[i] = stat(delete(data,i) )
+
+ # analysis
+ print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :")
+ print("original bias std. error")
+ print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))
+
+ return t
+
+
+# Returns mean of data samples
+def stat(data):
+ return mean(data)
+
+
+mu, sigma = 100, 15
+datapoints = 10000
+x = mu + sigma*random.randn(datapoints)
+# jackknife returns the data sample
+t = jackknife(x, stat)
+
+
+
+
+
Resampling methods: Bootstrap
+
+
+
+Bootstrapping is a nonparametric approach to statistical inference
+that substitutes computation for more traditional distributional
+assumptions and asymptotic results. Bootstrapping offers a number of
+advantages:
+
+
+- The bootstrap is quite general, although there are some cases in which it fails.
+- Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small.
+- It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically.
+- It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).
+
+
+
+
+
+
+
+
Resampling methods: Bootstrap background
+
+
+Since \( \widehat{\theta} = \widehat{\theta}(\boldsymbol{X}) \) is a function of random variables,
+\( \widehat{\theta} \) itself must be a random variable. Thus it has
+a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to
+estimate \( p(\boldsymbol{t}) \) by the relative frequency of
+\( \widehat{\theta} \). You can think of this as using a histogram
+in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely
+resembles \( p(\vec{t}) \), then using numerics, it is straight forward to
+estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point
+estimators.
+
+
+
+
+
Resampling methods: More Bootstrap background
+
+
+In the case that \( \widehat{\theta} \) has
+more than one component, and the components are independent, we use the
+same estimator on each component separately. If the probability
+density function of \( X_i \), \( p(x) \), had been known, then it would have
+been straight forward to do this by:
+
+
+- Drawing lots of numbers from \( p(x) \), suppose we call one such set of numbers \( (X_1^*, X_2^*, \cdots, X_n^*) \).
+- Then using these numbers, we could compute a replica of \( \widehat{\theta} \) called \( \widehat{\theta}^* \).
+
+
+By repeated use of (1) and (2), many
+estimates of \( \widehat{\theta} \) could have been obtained. The
+idea is to use the relative frequency of \( \widehat{\theta}^* \)
+(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \).
+
+
+
+
+
Resampling methods: Bootstrap approach
+
+
+But
+unless there is enough information available about the process that
+generated \( X_1,X_2,\cdots,X_n \), \( p(x) \) is in general
+unknown. Therefore, Efron in 1979 asked the
+question: What if we replace \( p(x) \) by the relative frequency
+of the observation \( X_i \); if we draw observations in accordance with
+the relative frequency of the observations, will we obtain the same
+result in some asymptotic sense? The answer is yes.
+
+
+Instead of generating the histogram for the relative
+frequency of the observation \( X_i \), just draw the values
+\( (X_1^*,X_2^*,\cdots,X_n^*) \) with replacement from the vector
+\( \boldsymbol{X} \).
+
+
+
+
+
Resampling methods: Bootstrap steps
+
+
+The independent bootstrap works like this:
+
+
+- Draw with replacement \( n \) numbers for the observed variables \( \boldsymbol{x} = (x_1,x_2,\cdots,x_n) \).
+- Define a vector \( \boldsymbol{x}^* \) containing the values which were drawn from \( \boldsymbol{x} \).
+- Using the vector \( \boldsymbol{x}^* \) compute \( \widehat{\theta}^* \) by evaluating \( \widehat \theta \) under the observations \( \boldsymbol{x}^* \).
+- Repeat this process \( k \) times.
+
+
+When you are done, you can draw a histogram of the relative frequency
+of \( \widehat \theta^* \). This is your estimate of the probability
+distribution \( p(t) \). Using this probability distribution you can
+estimate any statistics thereof. In principle you never draw the
+histogram of the relative frequency of \( \widehat{\theta}^* \). Instead
+you use the estimators corresponding to the statistic of interest. For
+example, if you are interested in estimating the variance of \( \widehat
+\theta \), apply the etsimator \( \widehat \sigma^2 \) to the values
+\( \widehat \theta ^* \).
+
+
+
+
+
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.
-
import numpy as np
-# SVD inversion
-def SVDinv(A):
- ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).
- SVD is numerically more stable than the inversion algorithms provided by
- numpy and scipy.linalg at the cost of being slower.
- '''
- U, s, VT = np.linalg.svd(A)
-# print('test U')
-# print( (np.transpose(U) @ U - U @np.transpose(U)))
-# print('test VT')
-# print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))
- print(U)
- print(s)
- print(VT)
+from numpy import *
+from numpy.random import randint, randn
+from time import time
+import matplotlib.mlab as mlab
+import matplotlib.pyplot as plt
- D = np.zeros((len(U),len(VT)))
- for i in range(0,len(VT)):
- D[i,i]=s[i]
- UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)
- return np.matmul(V,np.matmul(invD,UT))
+# Returns mean of bootstrap samples
+def stat(data):
+ return mean(data)
+
+# Bootstrap algorithm
+def bootstrap(data, statistic, R):
+ t = zeros(R); n = len(data); inds = arange(n); t0 = time()
+ # non-parametric bootstrap
+ for i in range(R):
+ t[i] = statistic(data[randint(0,n,n)])
+
+ # analysis
+ print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
+ print("original bias std. error")
+ print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
+ return t
-X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])
-print(X)
-A = np.transpose(X) @ X
-print(A)
-# Brute force inversion of super-collinear matrix
-#B = np.linalg.inv(A)
-#print(B)
-C = SVDinv(A)
-print(C)
+mu, sigma = 100, 15
+datapoints = 10000
+x = mu + sigma*random.randn(datapoints)
+# bootstrap returns the data sample
+t = bootstrap(x, stat, datapoints)
+# the histogram of the bootstrapped data
+n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
+
+# add a 'best fit' line
+y = mlab.normpdf( binsboot, mean(t), std(t))
+lt = plt.plot(binsboot, y, 'r--', linewidth=1)
+plt.xlabel('Smarts')
+plt.ylabel('Probability')
+plt.axis([99.5, 100.6, 0, 3.0])
+plt.grid(True)
+
+plt.show()
-The matrix \( \boldsymbol{X} \) has columns that are linearly dependent. The first
-column is the row-wise sum of the other two columns. The rank of a
-matrix (the column rank) is the dimension of space spanned by the
-column vectors. The rank of the matrix is the number of linearly
-independent columns, in this case just \( 2 \). We see this from the
-singular values when running the above code. Running the standard
-inversion algorithm for matrix inversion with \( \boldsymbol{X}^T\boldsymbol{X} \) results
-in the program terminating due to a singular matrix.
+
+
+
Various steps in cross-validation
-
-
-
Mathematical Properties
-
-
-There are several interesting mathematical properties which will be
-relevant when we are going to discuss the differences between say
-ordinary least squares (OLS) and Ridge regression.
-
-
-We have from OLS that the parameters of the linear approximation are given by
-$$
-\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
-$$
-
-
-The matrix to invert can be rewritten in terms of our SVD decomposition as
-
-$$
-\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T.
-$$
-
-Using the orthogonality properties of \( \boldsymbol{U} \) we have
-
-$$
-\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T = \boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T,
-$$
-
-with \( \boldsymbol{D} \) being a diagonal matrix with values along the diagonal given by the singular values squared.
-
-
-This means that
-$$
-(\boldsymbol{X}^T\boldsymbol{X})\boldsymbol{V} = \boldsymbol{V}\boldsymbol{D},
-$$
-
-that is the eigenvectors of \( (\boldsymbol{X}^T\boldsymbol{X}) \) are given by the columns of the right singular matrix of \( \boldsymbol{X} \) and the eigenvalues are the squared singular values. It is easy to show (show this) that
-$$
-(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D},
-$$
-
-that is, the eigenvectors of \( (\boldsymbol{X}\boldsymbol{X})^T \) are the columns of the left singular matrix and the eigenvalues are the same.
-
-
-Going back to our OLS equation we have
-$$
-\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}.
-$$
-
-We will come back to this expression when we discuss Ridge regression.
-
-$$ \tilde{y}^{OLS}={\bf X}\hat{\beta}^{OLS}=\sum_{j=1}^p {\bf u}_j{\bf u}_j^T{\bf y}$$ and for Ridge we have
-
-$$ \tilde{y}^{Ridge}={\bf X}\hat{\beta}^{Ridge}=\sum_{j=1}^p {\bf u}_j\frac{\sigma_j^2}{\sigma_j^2+\lambda}{\bf u}_j^T{\bf y}$$ .
-
-
-It is indeed the economy-sized SVD, note the summation runs up tp $$p$$ only and not $$n$$.
-
-
-Here we have that $${\bf X} = {\bf U}{\bf \Sigma}{\bf V}^T$$, with $$\Sigma$$ being an $$ n\times p$$ matrix and $${\bf V}$$ being a $$ p\times p$$ matrix. We also have assumed here that $$ n > p$$.
-
-
-
-
-
Friday September 12
-
-
-Video of Lecture and handwritten notes
-
-
-More material will be added here, see handwritten notes also.
-
-
-
-
-
Ridge and LASSO Regression
-
-
-Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is
-our optimization problem is
-$$
-{\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}.
-$$
-
-or we can state it as
-$$
-{\displaystyle \min_{\boldsymbol{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2,
-$$
-
-where we have used the definition of a norm-2 vector, that is
-$$
-\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.
-$$
-
-
-By minimizing the above equation with respect to the parameters
-\( \boldsymbol{\beta} \) we could then obtain an analytical expression for the
-parameters \( \boldsymbol{\beta} \). We can add a regularization parameter \( \lambda \) by
-defining a new cost function to be optimized, that is
-
-$$
-{\displaystyle \min_{\boldsymbol{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2
-$$
-
-
-which leads to the Ridge regression minimization problem where we
-require that \( \vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t \), where \( t \) is
-a finite number larger than zero. By defining
-
-$$
-C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1,
-$$
-
-
-we have a new optimization equation
-$$
-{\displaystyle \min_{\boldsymbol{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1
-$$
-
-which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.
-
-
-Here we have defined the norm-1 as
-$$
-\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert.
-$$
-
-
-
-
-
More on Ridge Regression
-
-
-Using the matrix-vector expression for Ridge regression,
-
-$$
-C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta},
-$$
-
-
-by taking the derivatives with respect to \( \boldsymbol{\beta} \) we obtain then
-a slightly modified matrix inversion problem which for finite values
-of \( \lambda \) does not suffer from singularity problems. We obtain
-
-$$
-\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
-$$
-
-
-with \( \boldsymbol{I} \) being a \( p\times p \) identity matrix with the constraint that
-
-$$
-\sum_{i=0}^{p-1} \beta_i^2 \leq t,
-$$
-
-
-with \( t \) a finite positive number.
-
-
-We see that Ridge regression is nothing but the standard
-OLS with a modified diagonal term added to \( \boldsymbol{X}^T\boldsymbol{X} \). The
-consequences, in particular for our discussion of the bias-variance tradeoff
-are rather interesting.
-
-
-Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had
-$$
-(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}.
-$$
-
-
-We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as
-$$
-\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}
-$$
-
-
-For Ridge regression this becomes
-
-$$
-\boldsymbol{X}\boldsymbol{\beta}^{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T+\lambda\boldsymbol{I} \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\sum_{j=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{y},
-$$
-
-
-with the vectors \( \boldsymbol{u}_j \) being the columns of \( \boldsymbol{U} \).
-
-
-
-
-
Interpreting the Ridge results
-
-
-Since \( \lambda \geq 0 \), it means that compared to OLS, we have
-
-$$
-\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1.
-$$
-
-
-Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the
-orthonormal basis \( \boldsymbol{U} \), it then shrinks the coordinates by
-\( \frac{\sigma_j^2}{\sigma_j^2+\lambda} \). Recall that the SVD has
-eigenvalues ordered in a descending way, that is \( \sigma_i \geq
-\sigma_{i+1} \).
-
-
-For small eigenvalues \( \sigma_i \) it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom.
-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.
-
-
-
-
-
More interpretations
-
-
-For the sake of simplicity, let us assume that the design matrix is orthonormal, that is
-
-$$
-\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}.
-$$
-
-
-In this case the standard OLS results in
-$$
-\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{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.
+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).
-
A better understanding of regularization
+How to set up the cross-validation for Ridge and/or Lasso
-
-The parameter \( \lambda \) that we have introduced in the Ridge (and
-Lasso as well) regression is often called a regularization parameter
-or shrinkage parameter. It is common to call it a hyperparameter. What does it mean mathemtically?
-
-
-Here we will first look at how to analyze the difference between the
-standard OLS equations and the Ridge expressions in terms of a linear
-algebra analysis using the SVD algorithm. Thereafter, we will link
-(see the material on the bias-variance tradeoff below) these
-observation to the statisical analysis of the results. In particular
-we consider how the variance of the parameters \( \boldsymbol{\beta} \) is
-affected by changing the parameter \( \lambda \).
-
-
-
-
-
Decomposing the OLS and Ridge expressions
-
-
-We have our design matrix
- \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). With the SVD we decompose it as
+
+- Define a range of interest for the penalty parameter.
+- Divide the data set into training and test set comprising samples \( \{1, \ldots, n\} \setminus i \) and \( \{ i \} \), respectively.
+- Fit the linear regression model by means of ridge estimation for each \( \lambda \) in the grid using the training set, and the corresponding estimate of the error variance \( \boldsymbol{\sigma}_{-i}^2(\lambda) \), as
+
$$
-\boldsymbol{X} = \boldsymbol{U\Sigma V^T},
+\begin{align*}
+\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T}
+\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1}
+\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i}
+\end{align*}
$$
-
-with \( \boldsymbol{U}\in {\mathbb{R}}^{n\times n} \), \( \boldsymbol{\Sigma}\in {\mathbb{R}}^{n\times p} \)
-and \( \boldsymbol{V}\in {\mathbb{R}}^{p\times p} \).
-
-The matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are unitary/orthonormal matrices, that is in case the matrices are real we have \( \boldsymbol{U}^T\boldsymbol{U}=\boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I} \) and \( \boldsymbol{V}^T\boldsymbol{V}=\boldsymbol{V}\boldsymbol{V}^T=\boldsymbol{I} \).
-
-
-
-
-
Introducing the Covariance and Correlation functions
-
-
-Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about
-the definition of the covariance and the correlation function. These are quantities
-
-
-Suppose we have defined two vectors
-\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as
-$$
-\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\
- \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\
- \end{bmatrix},
-$$
-
-where for example
-$$
-\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}).
-$$
-
-With this definition and recalling that the variance is defined as
-$$
-\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2,
-$$
-
-we can rewrite the covariance matrix as
-$$
-\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\
- \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\
- \end{bmatrix}.
-$$
-
-
-The covariance takes values between zero and infinity and may thus
-lead to problems with loss of numerical precision for particularly
-large values. It is common to scale the covariance matrix by
-introducing instead the correlation matrix defined via the so-called
-correlation function
+
+- Evaluate the prediction performance of these models on the test set by \( \log\{L[y_i, \boldsymbol{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\} \). Or, by the prediction error \( |y_i - \boldsymbol{X}_{i, \ast} \boldsymbol{\beta}_{-i}(\lambda)| \), the relative error, the error squared or the R2 score function.
+- Repeat the first three steps such that each sample plays the role of the test set once.
+- Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as
+
$$
-\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}.
-$$
-
-
-The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]
-\in [-1,1] \). This avoids eventual problems with too large values. We
-can then define the correlation matrix for the two vectors \( \boldsymbol{x} \)
-and \( \boldsymbol{y} \) as
-
-$$
-\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\
- \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\
- \end{bmatrix},
-$$
-
-
-In the above example this is the function we constructed using pandas.
-
-
-
-
-
Correlation Function and Design/Feature Matrix
-
-
-In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression
-we defined the design/feature matrix \( \boldsymbol{X} \) as
-
-$$
-\boldsymbol{X}=\begin{bmatrix}
-x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\
-x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\
-x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\
-\dots & \dots & \dots & \dots \dots & \dots \\
-x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\
-x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\
-\end{bmatrix},
-$$
-
-with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the
-entries \( n \) being the row elements.
-We can rewrite the design/feature matrix in terms of its column vectors as
-$$
-\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix},
-$$
-
-with a given vector
-$$
-\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}.
-$$
-
-
-With these definitions, we can now rewrite our \( 2\times 2 \)
-correaltion/covariance matrix in terms of a moe general design/feature
-matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \)
-covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \)
-
-$$
-\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix}
-\mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\
-\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\
-\mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_1] & \mathrm{var}[\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & \mathrm{var}[\boldsymbol{x}_{p-1}]\\
-\end{bmatrix},
-$$
-
-and the correlation matrix
-$$
-\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix}
-1 & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\
-\mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_0] & 1 & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\
-\mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & 1\\
-\end{bmatrix},
+\begin{align*}
+\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}.
+\end{align*}
$$
-
Covariance Matrix Examples
+Cross-validation in brief
-The Numpy function np.cov calculates the covariance elements using
-the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have
-the exact mean values. The following simple function uses the
-np.vstack function which takes each vector of dimension \( 1\times n \)
-and produces a \( 2\times n \) matrix \( \boldsymbol{W} \)
+For the various values of \( k \)
-$$
-\boldsymbol{W} = \begin{bmatrix} x_0 & y_0 \\
- x_1 & y_1 \\
- x_2 & y_2\\
- \dots & \dots \\
- x_{n-2} & y_{n-2}\\
- x_{n-1} & y_{n-1} &
- \end{bmatrix},
-$$
+
+- shuffle the dataset randomly.
+- Split the dataset into \( k \) groups.
+- For each unique group:
+
+
+- Decide which group to use as set for test data
+- Take the remaining groups as a training data set
+- Fit a model on the training set and evaluate it on the test set
+- Retain the evaluation score and discard the model
+
+
+ Summarize the model using the sample of model evaluation scores
+
+
+
+
+Code Example for Cross-validation and \( k \)-fold Cross-validation
-which in turn is converted into into the \( 2\times 2 \) covariance matrix
-\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate
-the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy
-function np.mean(x). We can also extract the eigenvalues of the
-covariance matrix through the np.linalg.eig() function.
-
+The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial.
-
# Importing various packages
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.model_selection import KFold
+from sklearn.linear_model import Ridge
+from sklearn.model_selection import cross_val_score
+from sklearn.preprocessing import PolynomialFeatures
+
+# A seed just to ensure that the random numbers are the same for every run.
+# Useful for eventual debugging.
+np.random.seed(3155)
+
+# Generate the data.
+nsamples = 100
+x = np.random.randn(nsamples)
+y = 3*x**2 + np.random.randn(nsamples)
+
+## Cross-validation on Ridge regression using KFold only
+
+# Decide degree on polynomial to fit
+poly = PolynomialFeatures(degree = 6)
+
+# Decide which values of lambda to use
+nlambdas = 500
+lambdas = np.logspace(-3, 5, nlambdas)
+
+# Initialize a KFold instance
+k = 5
+kfold = KFold(n_splits = k)
+
+# Perform the cross-validation to estimate MSE
+scores_KFold = np.zeros((nlambdas, k))
+
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
+ j = 0
+ for train_inds, test_inds in kfold.split(x):
+ xtrain = x[train_inds]
+ ytrain = y[train_inds]
+
+ xtest = x[test_inds]
+ ytest = y[test_inds]
+
+ Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
+ ridge.fit(Xtrain, ytrain[:, np.newaxis])
+
+ Xtest = poly.fit_transform(xtest[:, np.newaxis])
+ ypred = ridge.predict(Xtest)
+
+ scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
+
+ j += 1
+ i += 1
+
+
+estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
+
+## Cross-validation using cross_val_score from sklearn along with KFold
+
+# kfold is an instance initialized above as:
+# kfold = KFold(n_splits = k)
+
+estimated_mse_sklearn = np.zeros(nlambdas)
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
+
+ X = poly.fit_transform(x[:, np.newaxis])
+ estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
+
+ # cross_val_score return an array containing the estimated negative mse for every fold.
+ # we have to the the mean of every array in order to get an estimate of the mse of the model
+ estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
+
+ i += 1
+
+## Plot and compare the slightly different ways to perform cross-validation
+
+plt.figure()
+
+plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
+plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
+
+plt.xlabel('log10(lambda)')
+plt.ylabel('mse')
+
+plt.legend()
+
+plt.show()
+
+
+
+
+
The bias-variance tradeoff
+
+
+We will discuss the bias-variance tradeoff in the context of
+continuous predictions such as regression. However, many of the
+intuitions and ideas discussed here also carry over to classification
+tasks. Consider a dataset \( \mathcal{L} \) consisting of the data
+\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \).
+
+
+Let us assume that the true data is generated from a noisy model
+
+$$
+\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon}
+$$
+
+
+where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \).
+
+
+In our derivation of the ordinary least squares method we defined then
+an approximation to the function \( f \) in terms of the parameters
+\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model,
+that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \).
+
+
+Thereafter we found the parameters \( \boldsymbol{\beta} \) by optimizing the means squared error via the so-called cost function
+$$
+C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right].
+$$
+
+
+We can rewrite this as
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2.
+$$
+
+
+The three terms represent the square of the bias of the learning
+method, which can be thought of as the error caused by the simplifying
+assumptions built into the method. The second term represents the
+variance of the chosen model and finally the last terms is variance of
+the error \( \boldsymbol{\epsilon} \).
+
+
+To derive this equation, we need to recall that the variance of \( \boldsymbol{y} \) and \( \boldsymbol{\epsilon} \) are both equal to \( \sigma^2 \). The mean value of \( \boldsymbol{\epsilon} \) is by definition equal to zero. Furthermore, the function \( f \) is not a stochastics variable, idem for \( \boldsymbol{\tilde{y}} \).
+We use a more compact notation in terms of the expectation value
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right],
+$$
+
+and adding and subtracting \( \mathbb{E}\left[\boldsymbol{\tilde{y}}\right] \) we get
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right],
+$$
+
+which, using the abovementioned expectation values can be rewritten as
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2,
+$$
+
+that is the rewriting in terms of the so-called bias, the variance of the model \( \boldsymbol{\tilde{y}} \) and the variance of \( \boldsymbol{\epsilon} \).
+
+
+
+
+
Example code for Bias-Variance tradeoff
+
+
+
+
import matplotlib.pyplot as plt
import numpy as np
-n = 100
-x = np.random.normal(size=n)
-print(np.mean(x))
-y = 4+3*x+np.random.normal(size=n)
-print(np.mean(y))
-W = np.vstack((x, y))
-C = np.cov(W)
-print(C)
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+
+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()
-
Correlation Matrix
-
-
-The previous example can be converted into the correlation matrix by
-simply scaling the matrix elements with the variances. We should also
-subtract the mean values for each column. This leads to the following
-code which sets up the correlations matrix for the previous example in
-a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors).
-
+
Understanding what happens
-
import numpy as np
-n = 100
-# define two vectors
-x = np.random.random(size=n)
-y = 4+3*x+np.random.normal(size=n)
-#scaling the x and y vectors
-x = x - np.mean(x)
-y = y - np.mean(y)
-variance_x = np.sum(x@x)/n
-variance_y = np.sum(y@y)/n
-print(variance_x)
-print(variance_y)
-cov_xy = np.sum(x@y)/n
-cov_xx = np.sum(x@x)/n
-cov_yy = np.sum(y@y)/n
-C = np.zeros((2,2))
-C[0,0]= cov_xx/variance_x
-C[1,1]= cov_yy/variance_y
-C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
-C[1,0]= C[0,1]
-print(C)
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+
+np.random.seed(2018)
+
+n = 40
+n_boostraps = 100
+maxdegree = 14
+
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+for degree in range(maxdegree):
+ model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
+ y_pred = np.empty((y_test.shape[0], n_boostraps))
+ for i in range(n_boostraps):
+ x_, y_ = resample(x_train, y_train)
+ y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
+
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+ variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+ print('Polynomial degree:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+plt.show()
-We see that the matrix elements along the diagonal are one as they
-should be and that the matrix is symmetric. Furthermore, diagonalizing
-this matrix we easily see that it is a positive definite matrix.
+
+
+
Summing up
-The above procedure with numpy can be made more compact if we use pandas.
+The bias-variance tradeoff summarizes the fundamental tension in
+machine learning, particularly supervised learning, between the
+complexity of a model and the amount of training data needed to train
+it. Since data is often limited, in practice it is often useful to
+use a less-complex model with higher bias, that is a model whose asymptotic
+performance is worse than another model because it is easier to
+train and less sensitive to sampling noise arising from having a
+finite-sized training dataset (smaller variance).
+
+
+The above equations tell us that in
+order to minimize the expected test error, we need to select a
+statistical learning method that simultaneously achieves low variance
+and low bias. Note that variance is inherently a nonnegative quantity,
+and squared bias is also nonnegative. Hence, we see that the expected
+test MSE can never lie below \( Var(\epsilon) \), the irreducible error.
+
+
+What do we mean by the variance and bias of a statistical learning
+method? The variance refers to the amount by which our model would change if we
+estimated it using a different training data set. Since the training
+data are used to fit the statistical learning method, different
+training data sets will result in a different estimate. But ideally the
+estimate for our model should not vary too much between training
+sets. However, if a method has high variance then small changes in
+the training data can result in large changes in the model. In general, more
+flexible statistical methods have higher variance.
+
+
+You may also find this recent article of interest.
-
Correlation Matrix with Pandas
-
-
-We whow here how we can set up the correlation matrix using pandas, as done in this simple code
+
Another Example from Scikit-Learn's Repository
-
import numpy as np
-import pandas as pd
-n = 10
-x = np.random.normal(size=n)
-x = x - np.mean(x)
-y = 4+3*x+np.random.normal(size=n)
-y = y - np.mean(y)
-X = (np.vstack((x, y))).T
-print(X)
-Xpd = pd.DataFrame(X)
-print(Xpd)
-correlation_matrix = Xpd.corr()
-print(correlation_matrix)
-
-
-We expand this model to the Franke function discussed above.
+
"""
+============================
+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()
+
-
Correlation Matrix with Pandas and the Franke function
+More examples on bootstrap and cross-validation and errors
-
# Common imports
+# Common imports
+import os
import numpy as np
import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.model_selection import train_test_split
+from sklearn.utils import resample
+from sklearn.metrics import mean_squared_error
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
-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
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
-def create_X(x, y, n ):
- if len(x.shape) > 1:
- x = np.ravel(x)
- y = np.ravel(y)
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
- N = len(x)
- l = int((n+1)*(n+2)/2) # Number of elements in beta
- X = np.ones((N,l))
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
- for i in range(1,n+1):
- q = int((i)*(i+1)/2)
- for k in range(i+1):
- X[:,q+k] = (x**(i-k))*(y**k)
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
- return X
+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
-# Making meshgrid of datapoints and compute Franke's function
-n = 4
-N = 100
-x = np.sort(np.random.uniform(0, 1, N))
-y = np.sort(np.random.uniform(0, 1, N))
-z = FrankeFunction(x, y)
-X = create_X(x, y, n=n)
+Maxpolydegree = 30
+X = np.zeros((len(Density),Maxpolydegree))
+X[:,0] = 1.0
+testerror = np.zeros(Maxpolydegree)
+trainingerror = np.zeros(Maxpolydegree)
+polynomial = np.zeros(Maxpolydegree)
-Xpd = pd.DataFrame(X)
-# subtract the mean values and set up the covariance matrix
-Xpd = Xpd - Xpd.mean()
-covariance_matrix = Xpd.cov()
-print(covariance_matrix)
+trials = 100
+for polydegree in range(1, Maxpolydegree):
+ polynomial[polydegree] = polydegree
+ for degree in range(polydegree):
+ X[:,degree] = Density**(degree/3.0)
+
+# loop over trials in order to estimate the expectation value of the MSE
+ testerror[polydegree] = 0.0
+ trainingerror[polydegree] = 0.0
+ for samples in range(trials):
+ x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
+ model = LinearRegression(fit_intercept=True).fit(x_train, y_train)
+ ypred = model.predict(x_train)
+ ytilde = model.predict(x_test)
+ testerror[polydegree] += mean_squared_error(y_test, ytilde)
+ trainingerror[polydegree] += mean_squared_error(y_train, ypred)
+
+ testerror[polydegree] /= trials
+ trainingerror[polydegree] /= trials
+ print("Degree of polynomial: %3d"% polynomial[polydegree])
+ print("Mean squared error on training data: %.8f" % trainingerror[polydegree])
+ print("Mean squared error on test data: %.8f" % testerror[polydegree])
+
+plt.plot(polynomial, np.log10(trainingerror), label='Training Error')
+plt.plot(polynomial, np.log10(testerror), label='Test Error')
+plt.xlabel('Polynomial degree')
+plt.ylabel('log10[MSE]')
+plt.legend()
+plt.show()
-We note here that the covariance is zero for the first rows and
-columns since all matrix elements in the design matrix were set to one
-(we are fitting the function in terms of a polynomial of degree \( n \)).
+
+
+
The same example but now with cross-validation
-This means that the variance for these elements will be zero and will
-cause problems when we set up the correlation matrix. We can simply
-drop these elements and construct a correlation
-matrix without these elements.
+
+
# Common imports
+import os
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.metrics import mean_squared_error
+from sklearn.model_selection import KFold
+from sklearn.model_selection import cross_val_score
+
+
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
+
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
+
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
+
+infile = open(data_path("EoS.csv"),'r')
+
+# Read the EoS data as csv file and organize the data into two arrays with density and energies
+EoS = pd.read_csv(infile, names=('Density', 'Energy'))
+EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
+EoS = EoS.dropna()
+Energies = EoS['Energy']
+Density = EoS['Density']
+# The design matrix now as function of various polytrops
+
+Maxpolydegree = 30
+X = np.zeros((len(Density),Maxpolydegree))
+X[:,0] = 1.0
+estimated_mse_sklearn = np.zeros(Maxpolydegree)
+polynomial = np.zeros(Maxpolydegree)
+k =5
+kfold = KFold(n_splits = k)
+
+for polydegree in range(1, Maxpolydegree):
+ polynomial[polydegree] = polydegree
+ for degree in range(polydegree):
+ X[:,degree] = Density**(degree/3.0)
+ OLS = LinearRegression()
+# loop over trials in order to estimate the expectation value of the MSE
+ estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)
+#[:, np.newaxis]
+ estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)
+
+plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')
+plt.xlabel('Polynomial degree')
+plt.ylabel('log10[MSE]')
+plt.legend()
+plt.show()
+
-
Rewriting the Covariance and/or Correlation Matrix
-
+Cross-validation with Ridge
-We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as
-$$
-\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}].
-$$
+
+
import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.model_selection import KFold
+from sklearn.linear_model import Ridge
+from sklearn.model_selection import cross_val_score
+from sklearn.preprocessing import PolynomialFeatures
+
+# A seed just to ensure that the random numbers are the same for every run.
+np.random.seed(3155)
+# Generate the data.
+n = 100
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+# Decide degree on polynomial to fit
+poly = PolynomialFeatures(degree = 10)
+
+# Decide which values of lambda to use
+nlambdas = 500
+lambdas = np.logspace(-3, 5, nlambdas)
+# Initialize a KFold instance
+k = 5
+kfold = KFold(n_splits = k)
+estimated_mse_sklearn = np.zeros(nlambdas)
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
+ estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)
+ estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
+ i += 1
+plt.figure()
+plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
+
-To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \)
-$$
-\boldsymbol{X}=\begin{bmatrix}
-x_{00} & x_{01}\\
-x_{10} & x_{11}\\
-\end{bmatrix}=\begin{bmatrix}
-\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\
-\end{bmatrix}.
-$$
-
-
-If we then compute the expectation value
-$$
-\mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}=\begin{bmatrix}
-x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\
-x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\
-\end{bmatrix},
-$$
-
-which is just
-$$
-\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]=\begin{bmatrix} \mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] \\
- \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\
- \end{bmatrix},
-$$
-
-where we wrote $$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ to indicate that this the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \).
-
-
-It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \).
-
-
-
-
-
Linking with SVD
- © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
+ © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
diff --git a/doc/pub/week37/html/week37.html b/doc/pub/week37/html/week37.html
index 9244cce1b..5bfb00bd4 100644
--- a/doc/pub/week37/html/week37.html
+++ b/doc/pub/week37/html/week37.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 37: Ridge and Lasso Regression
+Week 37: Summary of Ridge and Lasso Regression and Resampling Methods
@@ -66,51 +66,125 @@ div { text-align: justify; text-justify: inter-word; }
@@ -136,7 +210,7 @@ MathJax.Hub.Config({
-Week 37: Ridge and Lasso Regression
+Week 37: Summary of Ridge and Lasso Regression and Resampling Methods
@@ -152,64 +226,416 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
Sep 16, 2020
+Sep 12, 2021
-
Plans for week 37
+Plans for week 37
-- Thursday September 10: Motivation for shrinkage methods and the Singular Value Decompostion theorem
-- Friday September 11: Ridge and Lasso regression
+- Thursday September 16: Summary of Ridge and Lasso with examples and start resampling techniques
+- Friday September 17: Resampling methods, Cross-validation, Bootstrapping and jackknife
-Thursday September 10
-
-
-Video of Lecture and handwritten notes
-
-
-More material will be added here, see handwritten notes also.
-
-
-
A Bayesian approach to develop intuition about skrinkage methods
-
-
-See Handwritten notes
+
Thursday September 16, Summary of Ridge and Lasso Regression and start Resampling methods
-
The singular value decomposition
+Deriving OLS from a probability distribution
+Our basic assumption when we derived the OLS equations was to assume
+that our output is determined by a given continuous function
+\( f(\boldsymbol{x}) \) and a random noise \( \boldsymbol{\epsilon} \) given by the normal
+distribution with zero mean value and an undetermined variance
+\( \sigma^2 \).
+
+
+We found above that the outputs \( \boldsymbol{y} \) have a mean value given by
+\( \boldsymbol{X}\hat{\boldsymbol{\beta}} \) and variance \( \sigma^2 \). Since the entries to
+the design matrix are not stochastic variables, we can assume that the
+probability distribution of our targets is also a normal distribution
+but now with mean value \( \boldsymbol{X}\hat{\boldsymbol{\beta}} \). This means that a
+single output \( y_i \) is given by the Gaussian distribution
+
+$$
+y_i\sim \mathcal{N}(\boldsymbol{X}_{i,*}\boldsymbol{\beta}, \sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
+$$
+
+
+
+
+
Independent and Identically Distrubuted (iid)
+
+
+We assume now that the various \( y_i \) values are stochastically distributed according to the above Gaussian distribution.
+We define this distribution as
+$$
+p(y_i, \boldsymbol{X}\vert\boldsymbol{\beta})=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]},
+$$
+
+which reads as finding the likelihood of an event \( y_i \) with the input variables \( \boldsymbol{X} \) given the parameters (to be determined) \( \boldsymbol{\beta} \).
+
+
+Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event \( \boldsymbol{y} \) as the product of the single events, that is we have
+
+$$
+p(\boldsymbol{y},\boldsymbol{X}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta}).
+$$
+
+
+We will write this in a more compact form reserving \( \boldsymbol{D} \) for the domain of events, including the ouputs (targets) and the inputs. That is
+in case we have a simple one-dimensional input and output case
+$$
+\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})].
+$$
+
+In the more general case the various inputs should be replaced by the possible features represented by the input data set \( \boldsymbol{X} \).
+We can now rewrite the above probability as
+$$
+p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
+$$
+
+
+It is a conditional probability (see below) and reads as the likelihood of a domain of events \( \boldsymbol{D} \) given a set of parameters \( \boldsymbol{\beta} \).
+
+
+
+
+
Maximum Likelihood Estimation (MLE)
+
+
+In statistics, maximum likelihood estimation (MLE) is a method of
+estimating the parameters of an assumed probability distribution,
+given some observed data. This is achieved by maximizing a likelihood
+function so that, under the assumed statistical model, the observed
+data is the most probable.
+
+
+We will assume here that our events are given by the above Gaussian
+distribution and we will determine the optimal parameters \( \beta \) by
+maximizing the above PDF. However, computing the derivatives of a
+product function is cumbersome and can easily lead to overflow and/or
+underflowproblems, with potentials for loss of numerical precision.
+
+
+In practice, it is more convenient to maximize the logarithm of the
+PDF because it is a monotonically increasing function of the argument.
+Alternatively, and this will be our option, we will minimize the
+negative of the logarithm since this is a monotonically decreasing
+function.
+
+
+Note also that maximization/minimization of the logarithm of the PDF
+is equivalent to the maximization/minimization of the function itself.
+
+
+
+
+
A new Cost Function
+
+
+We could now define a new cost function to minimize, namely the negative logarithm of the above PDF
+
+$$
+C(\boldsymbol{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})},
+$$
+
+which becomes
+$$
+C(\boldsymbol{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}.
+$$
+
+
+Taking the derivative of the new cost function with respect to the parameters \( \beta \) we recognize our familiar OLS equation, namely
+
+$$
+\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right) =0,
+$$
+
+which leads to the well-known OLS equation for the optimal paramters \( \beta \)
+$$
+\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}!
+$$
+
+
+
+
+
Bayes' Theorem
+
+
+If we combine the conditional probability with the marginal probability and the standard product rule, we have
+$$
+p(X\vert Y)= \frac{p(X,Y)}{p(Y)},
+$$
+
+which we can rewrite as
+
+$$
+p(X\vert Y)= \frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}=\frac{p(Y\vert X)p(X)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)},
+$$
+
+which is Bayes' theorem. It allows us to evaluate the uncertainty in in \( X \) after we have observed \( Y \). We can easily interchange \( X \) with \( Y \).
+
+
+
+
+
Interpretations of Bayes' Theorem
+
+
+The quantity \( p(Y\vert X) \) on the right-hand side of the theorem is
+evaluated for the observed data \( Y \) and can be viewed as a function of
+the parameter space represented by \( X \). This function is not
+necesseraly normalized and is normally called the likelihood function.
+
+
+The function \( p(X) \) on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution.
+
+
+
+
+
Test Function for what happens with OLS, Ridge and Lasso
+
+
+We will play around with a study of the values for the optimal
+parameters \( \boldsymbol{\beta} \) using OLS, Ridge and Lasso regression. For
+OLS, you will notice as function of the noise and polynomial degree,
+that the parameters \( \beta \) will fluctuate from order to order in the
+polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS.
+
+
+For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one.
+
+
+
+
+
import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.model_selection import train_test_split
+from sklearn import linear_model
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+# Make data set.
+n = 10000
+x = np.random.rand(n)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
+
+Maxpolydegree = 5
+X = np.zeros((len(x),Maxpolydegree))
+X[:,0] = 1.0
+
+for polydegree in range(1, Maxpolydegree):
+ for degree in range(polydegree):
+ X[:,degree] = x**(degree)
+
+
+# We split the data in test and training data
+X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
+
+# matrix inversion to find beta
+OLSbeta = np.linalg.pinv(X_train.T @ X_train) @ X_train.T @ y_train
+print(OLSbeta)
+ypredictOLS = X_test @ OLSbeta
+print("Test MSE OLS")
+print(MSE(y_test,ypredictOLS))
+# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn
+# Decide which values of lambda to use
+nlambdas = 4
+MSERidgePredict = np.zeros(nlambdas)
+MSELassoPredict = np.zeros(nlambdas)
+lambdas = np.logspace(-3, 1, nlambdas)
+for i in range(nlambdas):
+ lmb = lambdas[i]
+ # Make the fit using Ridge and Lasso
+ RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
+ RegRidge.fit(X_train,y_train)
+ RegLasso = linear_model.Lasso(lmb,fit_intercept=False)
+ RegLasso.fit(X_train,y_train)
+ # and then make the prediction
+ ypredictRidge = RegRidge.predict(X_test)
+ ypredictLasso = RegLasso.predict(X_test)
+ # Compute the MSE and print it
+ MSERidgePredict[i] = MSE(y_test,ypredictRidge)
+ MSELassoPredict[i] = MSE(y_test,ypredictLasso)
+ print(lmb,RegRidge.coef_)
+ print(lmb,RegLasso.coef_)
+# Now plot the results
+plt.figure()
+plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')
+plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
+
+
+How can we understand this?
+
+
+
+
+
Invoking Bayes' theorem
+
+
+Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression.
+
+
+For ordinary least squares we postulated that the maximum likelihood for the doamin of events \( \boldsymbol{D} \) (one-dimensional case)
+$$
+\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})],
+$$
+
+is given by
+$$
+p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}.
+$$
+
+
+In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set \( \boldsymbol{\beta} \) given a domain of events \( \boldsymbol{D} \)? That is, how can we define the posterior probability
+
+$$
+p(\boldsymbol{\beta}\vert\boldsymbol{D}).
+$$
+
+
+Bayes' theorem comes to our rescue here since (omitting the normalization constant)
+$$
+p(\boldsymbol{\beta}\vert\boldsymbol{D})\propto p(\boldsymbol{D}\vert\boldsymbol{\beta})p(\boldsymbol{\beta}).
+$$
+
+
+We have a model for \( p(\boldsymbol{D}\vert\boldsymbol{\beta}) \) but need one for the prior \( p(\boldsymbol{\beta} \)!
+
+
+
+
+
Ridge and Bayes
+
+
+With the posterior probability defined by a likelihood which we have
+already modeled and an unknown prior, we are now ready to make
+additional models for the prior.
+
+
+We can, based on our discussions of the variance of \( \boldsymbol{\beta} \) and the mean value, assume that the prior for the values \( \boldsymbol{\beta} \) is given by a Gaussian with mean value zero and variance \( \tau^2 \), that is
+
+$$
+p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}.
+$$
+
+
+Our posterior probability becomes then (omitting the normalization factor which is just a constant)
+$$
+p(\boldsymbol{\beta\vert\boldsymbol{D})}=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}.
+$$
+
+
+We can now optimize this quantity with respect to \( \boldsymbol{\beta} \). As we
+did for OLS, this is most conveniently done by taking the negative
+logarithm of the posterior probability. Doing so and leaving out the
+constants terms that do not depend on \( \beta \), we have
+
+$$
+C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{2\tau^2}\vert\vert\boldsymbol{\beta}\vert\vert_2^2,
+$$
+
+and replacing \( 1/2\tau^2 \) with \( \lambda \) we have
+
+$$
+C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_2^2,
+$$
+
+which is our Ridge cost function! Nice, isn't it?
+
+
+
+
+
Lasso and Bayes
+
+
+To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution (Laplace in this case) with zero mean value, that is
+
+$$
+p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}.
+$$
+
+
+Our posterior probability becomes then (omitting the normalization factor which is just a constant)
+$$
+p(\boldsymbol{\beta}\vert\boldsymbol{D})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}.
+$$
+
+
+Taking the negative
+logarithm of the posterior probability and leaving out the
+constants terms that do not depend on \( \beta \), we have
+
+$$
+C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{\tau}\vert\vert\boldsymbol{\beta}\vert\vert_1,
+$$
+
+and replacing \( 1/\tau \) with \( \lambda \) we have
+
+$$
+C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1,
+$$
+
+which is our Lasso cost function!
+
+
+
+
+
Why resampling methods
+
+
+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
+
+
+- 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
+
+
+This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods.
+
+
+
+
+
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.
-The examples we have looked at so far are cases where we normally can
-invert the matrix \( \boldsymbol{X}^T\boldsymbol{X} \). Using a polynomial expansion as we
-did both for the masses and the fitting of the equation of state,
-leads to row vectors of the design matrix which are essentially
-orthogonal due to the polynomial character of our model. Obtaining the inverse of the design matrix is then often done via a so-called LU, QR or Cholesky decomposition.
+Two resampling methods are often used in Machine Learning analyses,
-
-This may
-however not the be case in general and a standard matrix inversion
-algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.
+
+- The bootstrap method
+- and Cross-Validation
+
-
-There is however a way to partially circumvent this problem and also gain some insights about the ordinary least squares approach, and later shrinkage methods like Ridge and Lasso regressions.
-
-
-This is given by the Singular Value Decomposition algorithm, perhaps
-the most powerful linear algebra algorithm. Let us look at a
-different example where we may have problems with the standard matrix
-inversion algorithm. Thereafter we dive into the math of the SVD.
+In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular
+cross-validation and the bootstrap method.
@@ -218,892 +644,1032 @@ inversion algorithm. Thereafter we dive into the math of the SVD.
-
Linear Regression Problems
+Resampling approaches can be computationally expensive
+
+
+
-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*}
-$$
+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 columns of \( \boldsymbol{X} \) are linearly dependent. We see this easily since the
-the first column is the row-wise sum of the other two columns. The rank (more correct,
-the column rank) of a matrix is the dimension of the space spanned by the
-column vectors. Hence, the rank of \( \mathbf{X} \) is equal to the number
-of linearly independent columns. In this particular case the matrix has rank 2.
-
-Super-collinearity of an \( (n \times p) \)-dimensional design matrix \( \mathbf{X} \) implies
-that the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this
-$$
-\begin{align*}
-\boldsymbol{X} & = \left[
-\begin{array}{rr}
-1 & -1
-\\
-1 & -1
-\end{array} \right].
-\end{align*}
-$$
+
-We see easily that \( \mbox{det}(\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined.
-This is equivalent to saying that the matrix \( \boldsymbol{X} \) has at least an eigenvalue which is zero.
-
Fixing the singularity
-
+Why resampling methods ?
+
+Statistical analysis
-If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem
-$$
-\begin{align}
-\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y},
-\label{_auto1}
-\end{align}
-$$
-has linearly dependent column vectors, we will not be able to compute the inverse
-of \( \boldsymbol{X}^T\boldsymbol{X} \) and we cannot find the parameters (estimators) \( \beta_i \).
-The estimators are only well-defined if \( (\boldsymbol{X}^{T}\boldsymbol{X})^{-1} \) exits.
-This is more likely to happen when the matrix \( \boldsymbol{X} \) is high-dimensional. In this case it is likely to encounter a situation where
-the regression parameters \( \beta_i \) cannot be estimated.
+
+- Our simulations can be treated as computer experiments. This is particularly the case for Monte Carlo methods
+- The results can be analysed with the same statistical tools as we would use analysing experimental data.
+- As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
+
+
-
-A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change
-$$
-\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I},
-$$
-
-where \( \boldsymbol{I} \) is the identity matrix. When we discuss Ridge regression this is actually what we end up evaluating. The parameter \( \lambda \) is called a hyperparameter. More about this later.
-
Basic math of the SVD
-
+Statistical analysis
+
+
-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),
-$$
+
+- As in other experiments, many numerical experiments have two classes of errors:
-and the eigenvalues are given by the diagonal matrix
-$$
-\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n).
-$$
+
+ - Statistical errors
+ - Systematical errors
+
-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,
-$$
+- Statistical errors can be estimated using standard tools from statistics
+- Systematical errors are method specific and must be treated differently from case to case.
+
+
-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.
-
The SVD, a Fantastic Algorithm
+Resampling methods
-However, and this is the strength of the SVD algorithm, any general
-matrix \( \boldsymbol{X} \) can be decomposed in terms of a diagonal matrix and
-two orthogonal/unitary matrices. The Singular Value Decompostion
-(SVD) theorem
-states that a general \( m\times n \) matrix \( \boldsymbol{X} \) can be written in
-terms of a diagonal matrix \( \boldsymbol{\Sigma} \) of dimensionality \( m\times n \)
-and two orthognal matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \), where the first has
-dimensionality \( m \times m \) and the last dimensionality \( n\times n \).
-We have then
-
-$$
-\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T
-$$
+With all these analytical equations for both the OLS and Ridge
+regression, we will now outline how to assess a given model. This will
+lead us to a discussion of the so-called bias-variance tradeoff (see
+below) and so-called resampling methods.
-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,
-$$
+One of the quantities we have discussed as a way to measure errors is
+the mean-squared error (MSE), mainly used for fitting of continuous
+functions. Another choice is the absolute error.
-with eigenvalues \( \sigma_1=2 \) and \( \sigma_2=0 \).
-The SVD exits always!
+In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,
+we discuss the
-
-The SVD
-decomposition (singular values) gives eigenvalues
-\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=p \), the
-eigenvalues (singular values) are zero.
+
+- prediction error or simply the test error \( \mathrm{Err_{Test}} \), where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the
+- training error \( \mathrm{Err_{Train}} \), which is the average loss over the training data.
+
-
-In the general case, where our design matrix \( \boldsymbol{X} \) has dimension
-\( n\times p \), the matrix is thus decomposed into an \( n\times n \)
-orthogonal matrix \( \boldsymbol{U} \), a \( p\times p \) orthogonal matrix \( \boldsymbol{V} \)
-and a diagonal matrix \( \boldsymbol{\Sigma} \) with \( r=\mathrm{min}(n,p) \)
-singular values \( \sigma_i\geq 0 \) on the main diagonal and zeros filling
-the rest of the matrix. There are at most \( p \) singular values
-assuming that \( n > p \). In our regression examples for the nuclear
-masses and the equation of state this is indeed the case, while for
-the Ising model we have \( p > n \). These are often cases that lead to
-near singular or singular matrices.
-
-
-The columns of \( \boldsymbol{U} \) are called the left singular vectors while the columns of \( \boldsymbol{V} \) are the right singular vectors.
+As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.
+For a certain level of complexity the test error will reach minimum, before starting to increase again. The
+training error reaches a saturation.
-
Economy-size SVD
+Resampling methods: Jackknife and Bootstrap
-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} \).
+Two famous
+resampling methods are the independent bootstrap and the jackknife.
-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.
+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.
-If \( n > p \), we keep only the first \( p \) columns of \( \boldsymbol{U} \) and \( \boldsymbol{\Sigma} \) has dimension \( p\times p \).
-If \( p > n \), then only the first \( n \) columns of \( \boldsymbol{V} \) are computed and \( \boldsymbol{\Sigma} \) has dimension \( n\times n \).
-The \( n=p \) case is obvious, we retain the full SVD.
-In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.
+The 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.
-
Codes for the SVD
+Resampling methods: Jackknife
+
+
+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),
+$$
+
+
+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 \).
+
+
+
+
+
Jackknife code example
+
+
+
+
from numpy import *
+from numpy.random import randint, randn
+from time import time
+
+def jackknife(data, stat):
+ n = len(data);t = zeros(n); inds = arange(n); t0 = time()
+ ## 'jackknifing' by leaving out an observation for each i
+ for i in range(n):
+ t[i] = stat(delete(data,i) )
+
+ # analysis
+ print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :")
+ print("original bias std. error")
+ print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))
+
+ return t
+
+
+# Returns mean of data samples
+def stat(data):
+ return mean(data)
+
+
+mu, sigma = 100, 15
+datapoints = 10000
+x = mu + sigma*random.randn(datapoints)
+# jackknife returns the data sample
+t = jackknife(x, stat)
+
+
+
+
+
Resampling methods: Bootstrap
+
+
+
+Bootstrapping is a nonparametric approach to statistical inference
+that substitutes computation for more traditional distributional
+assumptions and asymptotic results. Bootstrapping offers a number of
+advantages:
+
+
+- The bootstrap is quite general, although there are some cases in which it fails.
+- Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small.
+- It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically.
+- It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).
+
+
+
+
+
+
+
+
Resampling methods: Bootstrap background
+
+
+Since \( \widehat{\theta} = \widehat{\theta}(\boldsymbol{X}) \) is a function of random variables,
+\( \widehat{\theta} \) itself must be a random variable. Thus it has
+a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to
+estimate \( p(\boldsymbol{t}) \) by the relative frequency of
+\( \widehat{\theta} \). You can think of this as using a histogram
+in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely
+resembles \( p(\vec{t}) \), then using numerics, it is straight forward to
+estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point
+estimators.
+
+
+
+
+
Resampling methods: More Bootstrap background
+
+
+In the case that \( \widehat{\theta} \) has
+more than one component, and the components are independent, we use the
+same estimator on each component separately. If the probability
+density function of \( X_i \), \( p(x) \), had been known, then it would have
+been straight forward to do this by:
+
+
+- Drawing lots of numbers from \( p(x) \), suppose we call one such set of numbers \( (X_1^*, X_2^*, \cdots, X_n^*) \).
+- Then using these numbers, we could compute a replica of \( \widehat{\theta} \) called \( \widehat{\theta}^* \).
+
+
+By repeated use of (1) and (2), many
+estimates of \( \widehat{\theta} \) could have been obtained. The
+idea is to use the relative frequency of \( \widehat{\theta}^* \)
+(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \).
+
+
+
+
+
Resampling methods: Bootstrap approach
+
+
+But
+unless there is enough information available about the process that
+generated \( X_1,X_2,\cdots,X_n \), \( p(x) \) is in general
+unknown. Therefore, Efron in 1979 asked the
+question: What if we replace \( p(x) \) by the relative frequency
+of the observation \( X_i \); if we draw observations in accordance with
+the relative frequency of the observations, will we obtain the same
+result in some asymptotic sense? The answer is yes.
+
+
+Instead of generating the histogram for the relative
+frequency of the observation \( X_i \), just draw the values
+\( (X_1^*,X_2^*,\cdots,X_n^*) \) with replacement from the vector
+\( \boldsymbol{X} \).
+
+
+
+
+
Resampling methods: Bootstrap steps
+
+
+The independent bootstrap works like this:
+
+
+- Draw with replacement \( n \) numbers for the observed variables \( \boldsymbol{x} = (x_1,x_2,\cdots,x_n) \).
+- Define a vector \( \boldsymbol{x}^* \) containing the values which were drawn from \( \boldsymbol{x} \).
+- Using the vector \( \boldsymbol{x}^* \) compute \( \widehat{\theta}^* \) by evaluating \( \widehat \theta \) under the observations \( \boldsymbol{x}^* \).
+- Repeat this process \( k \) times.
+
+
+When you are done, you can draw a histogram of the relative frequency
+of \( \widehat \theta^* \). This is your estimate of the probability
+distribution \( p(t) \). Using this probability distribution you can
+estimate any statistics thereof. In principle you never draw the
+histogram of the relative frequency of \( \widehat{\theta}^* \). Instead
+you use the estimators corresponding to the statistic of interest. For
+example, if you are interested in estimating the variance of \( \widehat
+\theta \), apply the etsimator \( \widehat \sigma^2 \) to the values
+\( \widehat \theta ^* \).
+
+
+
+
+
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.
-
import numpy as np
-# SVD inversion
-def SVDinv(A):
- ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).
- SVD is numerically more stable than the inversion algorithms provided by
- numpy and scipy.linalg at the cost of being slower.
- '''
- U, s, VT = np.linalg.svd(A)
-# print('test U')
-# print( (np.transpose(U) @ U - U @np.transpose(U)))
-# print('test VT')
-# print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))
- print(U)
- print(s)
- print(VT)
+from numpy import *
+from numpy.random import randint, randn
+from time import time
+import matplotlib.mlab as mlab
+import matplotlib.pyplot as plt
- D = np.zeros((len(U),len(VT)))
- for i in range(0,len(VT)):
- D[i,i]=s[i]
- UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)
- return np.matmul(V,np.matmul(invD,UT))
+# Returns mean of bootstrap samples
+def stat(data):
+ return mean(data)
+
+# Bootstrap algorithm
+def bootstrap(data, statistic, R):
+ t = zeros(R); n = len(data); inds = arange(n); t0 = time()
+ # non-parametric bootstrap
+ for i in range(R):
+ t[i] = statistic(data[randint(0,n,n)])
+
+ # analysis
+ print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
+ print("original bias std. error")
+ print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
+ return t
-X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])
-print(X)
-A = np.transpose(X) @ X
-print(A)
-# Brute force inversion of super-collinear matrix
-#B = np.linalg.inv(A)
-#print(B)
-C = SVDinv(A)
-print(C)
+mu, sigma = 100, 15
+datapoints = 10000
+x = mu + sigma*random.randn(datapoints)
+# bootstrap returns the data sample
+t = bootstrap(x, stat, datapoints)
+# the histogram of the bootstrapped data
+n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
+
+# add a 'best fit' line
+y = mlab.normpdf( binsboot, mean(t), std(t))
+lt = plt.plot(binsboot, y, 'r--', linewidth=1)
+plt.xlabel('Smarts')
+plt.ylabel('Probability')
+plt.axis([99.5, 100.6, 0, 3.0])
+plt.grid(True)
+
+plt.show()
-The matrix \( \boldsymbol{X} \) has columns that are linearly dependent. The first
-column is the row-wise sum of the other two columns. The rank of a
-matrix (the column rank) is the dimension of space spanned by the
-column vectors. The rank of the matrix is the number of linearly
-independent columns, in this case just \( 2 \). We see this from the
-singular values when running the above code. Running the standard
-inversion algorithm for matrix inversion with \( \boldsymbol{X}^T\boldsymbol{X} \) results
-in the program terminating due to a singular matrix.
+
+
+
Various steps in cross-validation
-
-
-
Mathematical Properties
-
-
-There are several interesting mathematical properties which will be
-relevant when we are going to discuss the differences between say
-ordinary least squares (OLS) and Ridge regression.
-
-
-We have from OLS that the parameters of the linear approximation are given by
-$$
-\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
-$$
-
-
-The matrix to invert can be rewritten in terms of our SVD decomposition as
-
-$$
-\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T.
-$$
-
-Using the orthogonality properties of \( \boldsymbol{U} \) we have
-
-$$
-\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T = \boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T,
-$$
-
-with \( \boldsymbol{D} \) being a diagonal matrix with values along the diagonal given by the singular values squared.
-
-
-This means that
-$$
-(\boldsymbol{X}^T\boldsymbol{X})\boldsymbol{V} = \boldsymbol{V}\boldsymbol{D},
-$$
-
-that is the eigenvectors of \( (\boldsymbol{X}^T\boldsymbol{X}) \) are given by the columns of the right singular matrix of \( \boldsymbol{X} \) and the eigenvalues are the squared singular values. It is easy to show (show this) that
-$$
-(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D},
-$$
-
-that is, the eigenvectors of \( (\boldsymbol{X}\boldsymbol{X})^T \) are the columns of the left singular matrix and the eigenvalues are the same.
-
-
-Going back to our OLS equation we have
-$$
-\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}.
-$$
-
-We will come back to this expression when we discuss Ridge regression.
-
-$$ \tilde{y}^{OLS}={\bf X}\hat{\beta}^{OLS}=\sum_{j=1}^p {\bf u}_j{\bf u}_j^T{\bf y}$$ and for Ridge we have
-
-$$ \tilde{y}^{Ridge}={\bf X}\hat{\beta}^{Ridge}=\sum_{j=1}^p {\bf u}_j\frac{\sigma_j^2}{\sigma_j^2+\lambda}{\bf u}_j^T{\bf y}$$ .
-
-
-It is indeed the economy-sized SVD, note the summation runs up tp $$p$$ only and not $$n$$.
-
-
-Here we have that $${\bf X} = {\bf U}{\bf \Sigma}{\bf V}^T$$, with $$\Sigma$$ being an $$ n\times p$$ matrix and $${\bf V}$$ being a $$ p\times p$$ matrix. We also have assumed here that $$ n > p$$.
-
-
-
-
-
Friday September 12
-
-
-Video of Lecture and handwritten notes
-
-
-More material will be added here, see handwritten notes also.
-
-
-
-
-
Ridge and LASSO Regression
-
-
-Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is
-our optimization problem is
-$$
-{\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}.
-$$
-
-or we can state it as
-$$
-{\displaystyle \min_{\boldsymbol{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2,
-$$
-
-where we have used the definition of a norm-2 vector, that is
-$$
-\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.
-$$
-
-
-By minimizing the above equation with respect to the parameters
-\( \boldsymbol{\beta} \) we could then obtain an analytical expression for the
-parameters \( \boldsymbol{\beta} \). We can add a regularization parameter \( \lambda \) by
-defining a new cost function to be optimized, that is
-
-$$
-{\displaystyle \min_{\boldsymbol{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2
-$$
-
-
-which leads to the Ridge regression minimization problem where we
-require that \( \vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t \), where \( t \) is
-a finite number larger than zero. By defining
-
-$$
-C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1,
-$$
-
-
-we have a new optimization equation
-$$
-{\displaystyle \min_{\boldsymbol{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1
-$$
-
-which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.
-
-
-Here we have defined the norm-1 as
-$$
-\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert.
-$$
-
-
-
-
-
More on Ridge Regression
-
-
-Using the matrix-vector expression for Ridge regression,
-
-$$
-C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta},
-$$
-
-
-by taking the derivatives with respect to \( \boldsymbol{\beta} \) we obtain then
-a slightly modified matrix inversion problem which for finite values
-of \( \lambda \) does not suffer from singularity problems. We obtain
-
-$$
-\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
-$$
-
-
-with \( \boldsymbol{I} \) being a \( p\times p \) identity matrix with the constraint that
-
-$$
-\sum_{i=0}^{p-1} \beta_i^2 \leq t,
-$$
-
-
-with \( t \) a finite positive number.
-
-
-We see that Ridge regression is nothing but the standard
-OLS with a modified diagonal term added to \( \boldsymbol{X}^T\boldsymbol{X} \). The
-consequences, in particular for our discussion of the bias-variance tradeoff
-are rather interesting.
-
-
-Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had
-$$
-(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}.
-$$
-
-
-We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as
-$$
-\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}
-$$
-
-
-For Ridge regression this becomes
-
-$$
-\boldsymbol{X}\boldsymbol{\beta}^{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T+\lambda\boldsymbol{I} \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\sum_{j=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{y},
-$$
-
-
-with the vectors \( \boldsymbol{u}_j \) being the columns of \( \boldsymbol{U} \).
-
-
-
-
-
Interpreting the Ridge results
-
-
-Since \( \lambda \geq 0 \), it means that compared to OLS, we have
-
-$$
-\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1.
-$$
-
-
-Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the
-orthonormal basis \( \boldsymbol{U} \), it then shrinks the coordinates by
-\( \frac{\sigma_j^2}{\sigma_j^2+\lambda} \). Recall that the SVD has
-eigenvalues ordered in a descending way, that is \( \sigma_i \geq
-\sigma_{i+1} \).
-
-
-For small eigenvalues \( \sigma_i \) it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom.
-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.
-
-
-
-
-
More interpretations
-
-
-For the sake of simplicity, let us assume that the design matrix is orthonormal, that is
-
-$$
-\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}.
-$$
-
-
-In this case the standard OLS results in
-$$
-\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{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.
+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).
-
A better understanding of regularization
+How to set up the cross-validation for Ridge and/or Lasso
-
-The parameter \( \lambda \) that we have introduced in the Ridge (and
-Lasso as well) regression is often called a regularization parameter
-or shrinkage parameter. It is common to call it a hyperparameter. What does it mean mathemtically?
-
-
-Here we will first look at how to analyze the difference between the
-standard OLS equations and the Ridge expressions in terms of a linear
-algebra analysis using the SVD algorithm. Thereafter, we will link
-(see the material on the bias-variance tradeoff below) these
-observation to the statisical analysis of the results. In particular
-we consider how the variance of the parameters \( \boldsymbol{\beta} \) is
-affected by changing the parameter \( \lambda \).
-
-
-
-
-
Decomposing the OLS and Ridge expressions
-
-
-We have our design matrix
- \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). With the SVD we decompose it as
+
+- Define a range of interest for the penalty parameter.
+- Divide the data set into training and test set comprising samples \( \{1, \ldots, n\} \setminus i \) and \( \{ i \} \), respectively.
+- Fit the linear regression model by means of ridge estimation for each \( \lambda \) in the grid using the training set, and the corresponding estimate of the error variance \( \boldsymbol{\sigma}_{-i}^2(\lambda) \), as
+
$$
-\boldsymbol{X} = \boldsymbol{U\Sigma V^T},
+\begin{align*}
+\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T}
+\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1}
+\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i}
+\end{align*}
$$
-
-with \( \boldsymbol{U}\in {\mathbb{R}}^{n\times n} \), \( \boldsymbol{\Sigma}\in {\mathbb{R}}^{n\times p} \)
-and \( \boldsymbol{V}\in {\mathbb{R}}^{p\times p} \).
-
-The matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are unitary/orthonormal matrices, that is in case the matrices are real we have \( \boldsymbol{U}^T\boldsymbol{U}=\boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I} \) and \( \boldsymbol{V}^T\boldsymbol{V}=\boldsymbol{V}\boldsymbol{V}^T=\boldsymbol{I} \).
-
-
-
-
-
Introducing the Covariance and Correlation functions
-
-
-Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about
-the definition of the covariance and the correlation function. These are quantities
-
-
-Suppose we have defined two vectors
-\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as
-$$
-\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\
- \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\
- \end{bmatrix},
-$$
-
-where for example
-$$
-\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}).
-$$
-
-With this definition and recalling that the variance is defined as
-$$
-\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2,
-$$
-
-we can rewrite the covariance matrix as
-$$
-\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\
- \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\
- \end{bmatrix}.
-$$
-
-
-The covariance takes values between zero and infinity and may thus
-lead to problems with loss of numerical precision for particularly
-large values. It is common to scale the covariance matrix by
-introducing instead the correlation matrix defined via the so-called
-correlation function
+
+- Evaluate the prediction performance of these models on the test set by \( \log\{L[y_i, \boldsymbol{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\} \). Or, by the prediction error \( |y_i - \boldsymbol{X}_{i, \ast} \boldsymbol{\beta}_{-i}(\lambda)| \), the relative error, the error squared or the R2 score function.
+- Repeat the first three steps such that each sample plays the role of the test set once.
+- Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as
+
$$
-\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}.
-$$
-
-
-The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]
-\in [-1,1] \). This avoids eventual problems with too large values. We
-can then define the correlation matrix for the two vectors \( \boldsymbol{x} \)
-and \( \boldsymbol{y} \) as
-
-$$
-\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\
- \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\
- \end{bmatrix},
-$$
-
-
-In the above example this is the function we constructed using pandas.
-
-
-
-
-
Correlation Function and Design/Feature Matrix
-
-
-In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression
-we defined the design/feature matrix \( \boldsymbol{X} \) as
-
-$$
-\boldsymbol{X}=\begin{bmatrix}
-x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\
-x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\
-x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\
-\dots & \dots & \dots & \dots \dots & \dots \\
-x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\
-x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\
-\end{bmatrix},
-$$
-
-with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the
-entries \( n \) being the row elements.
-We can rewrite the design/feature matrix in terms of its column vectors as
-$$
-\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix},
-$$
-
-with a given vector
-$$
-\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}.
-$$
-
-
-With these definitions, we can now rewrite our \( 2\times 2 \)
-correaltion/covariance matrix in terms of a moe general design/feature
-matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \)
-covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \)
-
-$$
-\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix}
-\mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\
-\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\
-\mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_1] & \mathrm{var}[\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & \mathrm{var}[\boldsymbol{x}_{p-1}]\\
-\end{bmatrix},
-$$
-
-and the correlation matrix
-$$
-\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix}
-1 & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\
-\mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_0] & 1 & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\
-\mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & 1\\
-\end{bmatrix},
+\begin{align*}
+\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}.
+\end{align*}
$$
-
Covariance Matrix Examples
+Cross-validation in brief
-The Numpy function np.cov calculates the covariance elements using
-the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have
-the exact mean values. The following simple function uses the
-np.vstack function which takes each vector of dimension \( 1\times n \)
-and produces a \( 2\times n \) matrix \( \boldsymbol{W} \)
+For the various values of \( k \)
-$$
-\boldsymbol{W} = \begin{bmatrix} x_0 & y_0 \\
- x_1 & y_1 \\
- x_2 & y_2\\
- \dots & \dots \\
- x_{n-2} & y_{n-2}\\
- x_{n-1} & y_{n-1} &
- \end{bmatrix},
-$$
+
+- shuffle the dataset randomly.
+- Split the dataset into \( k \) groups.
+- For each unique group:
+
+
+- Decide which group to use as set for test data
+- Take the remaining groups as a training data set
+- Fit a model on the training set and evaluate it on the test set
+- Retain the evaluation score and discard the model
+
+
+ Summarize the model using the sample of model evaluation scores
+
+
+
+
+Code Example for Cross-validation and \( k \)-fold Cross-validation
-which in turn is converted into into the \( 2\times 2 \) covariance matrix
-\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate
-the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy
-function np.mean(x). We can also extract the eigenvalues of the
-covariance matrix through the np.linalg.eig() function.
-
+The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial.
-
# Importing various packages
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.model_selection import KFold
+from sklearn.linear_model import Ridge
+from sklearn.model_selection import cross_val_score
+from sklearn.preprocessing import PolynomialFeatures
+
+# A seed just to ensure that the random numbers are the same for every run.
+# Useful for eventual debugging.
+np.random.seed(3155)
+
+# Generate the data.
+nsamples = 100
+x = np.random.randn(nsamples)
+y = 3*x**2 + np.random.randn(nsamples)
+
+## Cross-validation on Ridge regression using KFold only
+
+# Decide degree on polynomial to fit
+poly = PolynomialFeatures(degree = 6)
+
+# Decide which values of lambda to use
+nlambdas = 500
+lambdas = np.logspace(-3, 5, nlambdas)
+
+# Initialize a KFold instance
+k = 5
+kfold = KFold(n_splits = k)
+
+# Perform the cross-validation to estimate MSE
+scores_KFold = np.zeros((nlambdas, k))
+
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
+ j = 0
+ for train_inds, test_inds in kfold.split(x):
+ xtrain = x[train_inds]
+ ytrain = y[train_inds]
+
+ xtest = x[test_inds]
+ ytest = y[test_inds]
+
+ Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
+ ridge.fit(Xtrain, ytrain[:, np.newaxis])
+
+ Xtest = poly.fit_transform(xtest[:, np.newaxis])
+ ypred = ridge.predict(Xtest)
+
+ scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
+
+ j += 1
+ i += 1
+
+
+estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
+
+## Cross-validation using cross_val_score from sklearn along with KFold
+
+# kfold is an instance initialized above as:
+# kfold = KFold(n_splits = k)
+
+estimated_mse_sklearn = np.zeros(nlambdas)
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
+
+ X = poly.fit_transform(x[:, np.newaxis])
+ estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
+
+ # cross_val_score return an array containing the estimated negative mse for every fold.
+ # we have to the the mean of every array in order to get an estimate of the mse of the model
+ estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
+
+ i += 1
+
+## Plot and compare the slightly different ways to perform cross-validation
+
+plt.figure()
+
+plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
+plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
+
+plt.xlabel('log10(lambda)')
+plt.ylabel('mse')
+
+plt.legend()
+
+plt.show()
+
+
+
+
+
The bias-variance tradeoff
+
+
+We will discuss the bias-variance tradeoff in the context of
+continuous predictions such as regression. However, many of the
+intuitions and ideas discussed here also carry over to classification
+tasks. Consider a dataset \( \mathcal{L} \) consisting of the data
+\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \).
+
+
+Let us assume that the true data is generated from a noisy model
+
+$$
+\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon}
+$$
+
+
+where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \).
+
+
+In our derivation of the ordinary least squares method we defined then
+an approximation to the function \( f \) in terms of the parameters
+\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model,
+that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \).
+
+
+Thereafter we found the parameters \( \boldsymbol{\beta} \) by optimizing the means squared error via the so-called cost function
+$$
+C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right].
+$$
+
+
+We can rewrite this as
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2.
+$$
+
+
+The three terms represent the square of the bias of the learning
+method, which can be thought of as the error caused by the simplifying
+assumptions built into the method. The second term represents the
+variance of the chosen model and finally the last terms is variance of
+the error \( \boldsymbol{\epsilon} \).
+
+
+To derive this equation, we need to recall that the variance of \( \boldsymbol{y} \) and \( \boldsymbol{\epsilon} \) are both equal to \( \sigma^2 \). The mean value of \( \boldsymbol{\epsilon} \) is by definition equal to zero. Furthermore, the function \( f \) is not a stochastics variable, idem for \( \boldsymbol{\tilde{y}} \).
+We use a more compact notation in terms of the expectation value
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right],
+$$
+
+and adding and subtracting \( \mathbb{E}\left[\boldsymbol{\tilde{y}}\right] \) we get
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right],
+$$
+
+which, using the abovementioned expectation values can be rewritten as
+$$
+\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2,
+$$
+
+that is the rewriting in terms of the so-called bias, the variance of the model \( \boldsymbol{\tilde{y}} \) and the variance of \( \boldsymbol{\epsilon} \).
+
+
+
+
+
Example code for Bias-Variance tradeoff
+
+
+
+
import matplotlib.pyplot as plt
import numpy as np
-n = 100
-x = np.random.normal(size=n)
-print(np.mean(x))
-y = 4+3*x+np.random.normal(size=n)
-print(np.mean(y))
-W = np.vstack((x, y))
-C = np.cov(W)
-print(C)
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+
+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()
-
Correlation Matrix
-
-
-The previous example can be converted into the correlation matrix by
-simply scaling the matrix elements with the variances. We should also
-subtract the mean values for each column. This leads to the following
-code which sets up the correlations matrix for the previous example in
-a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors).
-
+
Understanding what happens
-
import numpy as np
-n = 100
-# define two vectors
-x = np.random.random(size=n)
-y = 4+3*x+np.random.normal(size=n)
-#scaling the x and y vectors
-x = x - np.mean(x)
-y = y - np.mean(y)
-variance_x = np.sum(x@x)/n
-variance_y = np.sum(y@y)/n
-print(variance_x)
-print(variance_y)
-cov_xy = np.sum(x@y)/n
-cov_xx = np.sum(x@x)/n
-cov_yy = np.sum(y@y)/n
-C = np.zeros((2,2))
-C[0,0]= cov_xx/variance_x
-C[1,1]= cov_yy/variance_y
-C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
-C[1,0]= C[0,1]
-print(C)
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+
+np.random.seed(2018)
+
+n = 40
+n_boostraps = 100
+maxdegree = 14
+
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+for degree in range(maxdegree):
+ model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
+ y_pred = np.empty((y_test.shape[0], n_boostraps))
+ for i in range(n_boostraps):
+ x_, y_ = resample(x_train, y_train)
+ y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
+
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+ variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+ print('Polynomial degree:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+plt.show()
-We see that the matrix elements along the diagonal are one as they
-should be and that the matrix is symmetric. Furthermore, diagonalizing
-this matrix we easily see that it is a positive definite matrix.
+
+
+
Summing up
-The above procedure with numpy can be made more compact if we use pandas.
+The bias-variance tradeoff summarizes the fundamental tension in
+machine learning, particularly supervised learning, between the
+complexity of a model and the amount of training data needed to train
+it. Since data is often limited, in practice it is often useful to
+use a less-complex model with higher bias, that is a model whose asymptotic
+performance is worse than another model because it is easier to
+train and less sensitive to sampling noise arising from having a
+finite-sized training dataset (smaller variance).
+
+
+The above equations tell us that in
+order to minimize the expected test error, we need to select a
+statistical learning method that simultaneously achieves low variance
+and low bias. Note that variance is inherently a nonnegative quantity,
+and squared bias is also nonnegative. Hence, we see that the expected
+test MSE can never lie below \( Var(\epsilon) \), the irreducible error.
+
+
+What do we mean by the variance and bias of a statistical learning
+method? The variance refers to the amount by which our model would change if we
+estimated it using a different training data set. Since the training
+data are used to fit the statistical learning method, different
+training data sets will result in a different estimate. But ideally the
+estimate for our model should not vary too much between training
+sets. However, if a method has high variance then small changes in
+the training data can result in large changes in the model. In general, more
+flexible statistical methods have higher variance.
+
+
+You may also find this recent article of interest.
-
Correlation Matrix with Pandas
-
-
-We whow here how we can set up the correlation matrix using pandas, as done in this simple code
+
Another Example from Scikit-Learn's Repository
-
import numpy as np
-import pandas as pd
-n = 10
-x = np.random.normal(size=n)
-x = x - np.mean(x)
-y = 4+3*x+np.random.normal(size=n)
-y = y - np.mean(y)
-X = (np.vstack((x, y))).T
-print(X)
-Xpd = pd.DataFrame(X)
-print(Xpd)
-correlation_matrix = Xpd.corr()
-print(correlation_matrix)
-
-
-We expand this model to the Franke function discussed above.
+
"""
+============================
+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()
+
-
Correlation Matrix with Pandas and the Franke function
+More examples on bootstrap and cross-validation and errors
-
# Common imports
+# Common imports
+import os
import numpy as np
import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.model_selection import train_test_split
+from sklearn.utils import resample
+from sklearn.metrics import mean_squared_error
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
-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
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
-def create_X(x, y, n ):
- if len(x.shape) > 1:
- x = np.ravel(x)
- y = np.ravel(y)
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
- N = len(x)
- l = int((n+1)*(n+2)/2) # Number of elements in beta
- X = np.ones((N,l))
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
- for i in range(1,n+1):
- q = int((i)*(i+1)/2)
- for k in range(i+1):
- X[:,q+k] = (x**(i-k))*(y**k)
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
- return X
+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
-# Making meshgrid of datapoints and compute Franke's function
-n = 4
-N = 100
-x = np.sort(np.random.uniform(0, 1, N))
-y = np.sort(np.random.uniform(0, 1, N))
-z = FrankeFunction(x, y)
-X = create_X(x, y, n=n)
+Maxpolydegree = 30
+X = np.zeros((len(Density),Maxpolydegree))
+X[:,0] = 1.0
+testerror = np.zeros(Maxpolydegree)
+trainingerror = np.zeros(Maxpolydegree)
+polynomial = np.zeros(Maxpolydegree)
-Xpd = pd.DataFrame(X)
-# subtract the mean values and set up the covariance matrix
-Xpd = Xpd - Xpd.mean()
-covariance_matrix = Xpd.cov()
-print(covariance_matrix)
+trials = 100
+for polydegree in range(1, Maxpolydegree):
+ polynomial[polydegree] = polydegree
+ for degree in range(polydegree):
+ X[:,degree] = Density**(degree/3.0)
+
+# loop over trials in order to estimate the expectation value of the MSE
+ testerror[polydegree] = 0.0
+ trainingerror[polydegree] = 0.0
+ for samples in range(trials):
+ x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
+ model = LinearRegression(fit_intercept=True).fit(x_train, y_train)
+ ypred = model.predict(x_train)
+ ytilde = model.predict(x_test)
+ testerror[polydegree] += mean_squared_error(y_test, ytilde)
+ trainingerror[polydegree] += mean_squared_error(y_train, ypred)
+
+ testerror[polydegree] /= trials
+ trainingerror[polydegree] /= trials
+ print("Degree of polynomial: %3d"% polynomial[polydegree])
+ print("Mean squared error on training data: %.8f" % trainingerror[polydegree])
+ print("Mean squared error on test data: %.8f" % testerror[polydegree])
+
+plt.plot(polynomial, np.log10(trainingerror), label='Training Error')
+plt.plot(polynomial, np.log10(testerror), label='Test Error')
+plt.xlabel('Polynomial degree')
+plt.ylabel('log10[MSE]')
+plt.legend()
+plt.show()
-We note here that the covariance is zero for the first rows and
-columns since all matrix elements in the design matrix were set to one
-(we are fitting the function in terms of a polynomial of degree \( n \)).
+
+
+
The same example but now with cross-validation
-This means that the variance for these elements will be zero and will
-cause problems when we set up the correlation matrix. We can simply
-drop these elements and construct a correlation
-matrix without these elements.
+
+
# Common imports
+import os
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.metrics import mean_squared_error
+from sklearn.model_selection import KFold
+from sklearn.model_selection import cross_val_score
+
+
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
+
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
+
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
+
+infile = open(data_path("EoS.csv"),'r')
+
+# Read the EoS data as csv file and organize the data into two arrays with density and energies
+EoS = pd.read_csv(infile, names=('Density', 'Energy'))
+EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
+EoS = EoS.dropna()
+Energies = EoS['Energy']
+Density = EoS['Density']
+# The design matrix now as function of various polytrops
+
+Maxpolydegree = 30
+X = np.zeros((len(Density),Maxpolydegree))
+X[:,0] = 1.0
+estimated_mse_sklearn = np.zeros(Maxpolydegree)
+polynomial = np.zeros(Maxpolydegree)
+k =5
+kfold = KFold(n_splits = k)
+
+for polydegree in range(1, Maxpolydegree):
+ polynomial[polydegree] = polydegree
+ for degree in range(polydegree):
+ X[:,degree] = Density**(degree/3.0)
+ OLS = LinearRegression()
+# loop over trials in order to estimate the expectation value of the MSE
+ estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)
+#[:, np.newaxis]
+ estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)
+
+plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')
+plt.xlabel('Polynomial degree')
+plt.ylabel('log10[MSE]')
+plt.legend()
+plt.show()
+
-
Rewriting the Covariance and/or Correlation Matrix
-
+Cross-validation with Ridge
-We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as
-$$
-\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}].
-$$
+
+
import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.model_selection import KFold
+from sklearn.linear_model import Ridge
+from sklearn.model_selection import cross_val_score
+from sklearn.preprocessing import PolynomialFeatures
+
+# A seed just to ensure that the random numbers are the same for every run.
+np.random.seed(3155)
+# Generate the data.
+n = 100
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+# Decide degree on polynomial to fit
+poly = PolynomialFeatures(degree = 10)
+
+# Decide which values of lambda to use
+nlambdas = 500
+lambdas = np.logspace(-3, 5, nlambdas)
+# Initialize a KFold instance
+k = 5
+kfold = KFold(n_splits = k)
+estimated_mse_sklearn = np.zeros(nlambdas)
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
+ estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)
+ estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
+ i += 1
+plt.figure()
+plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
+
-To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \)
-$$
-\boldsymbol{X}=\begin{bmatrix}
-x_{00} & x_{01}\\
-x_{10} & x_{11}\\
-\end{bmatrix}=\begin{bmatrix}
-\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\
-\end{bmatrix}.
-$$
-
-
-If we then compute the expectation value
-$$
-\mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}=\begin{bmatrix}
-x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\
-x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\
-\end{bmatrix},
-$$
-
-which is just
-$$
-\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]=\begin{bmatrix} \mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] \\
- \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\
- \end{bmatrix},
-$$
-
-where we wrote $$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ to indicate that this the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \).
-
-
-It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \).
-
-
-
-
-
Linking with SVD
- © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
+ © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
diff --git a/doc/pub/week37/ipynb/ipynb-week37-src.tar.gz b/doc/pub/week37/ipynb/ipynb-week37-src.tar.gz
index dd7a1e438..4d7b11611 100644
Binary files a/doc/pub/week37/ipynb/ipynb-week37-src.tar.gz and b/doc/pub/week37/ipynb/ipynb-week37-src.tar.gz differ
diff --git a/doc/pub/week37/ipynb/week37.ipynb b/doc/pub/week37/ipynb/week37.ipynb
index 3351b28f7..b8e187a88 100644
--- a/doc/pub/week37/ipynb/week37.ipynb
+++ b/doc/pub/week37/ipynb/week37.ipynb
@@ -4,67 +4,41 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "\n",
- "# Week 37: Ridge and Lasso Regression\n",
+ "\n",
+ "# Week 37: Summary of Ridge and Lasso Regression and Resampling Methods\n",
"\n",
" \n",
"**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n",
"\n",
- "Date: **Sep 16, 2020**\n",
+ "Date: **Sep 12, 2021**\n",
"\n",
- "Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
+ "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
"\n",
"\n",
"\n",
"## Plans for week 37\n",
"\n",
- "* Thursday September 10: Motivation for shrinkage methods and the Singular Value Decompostion theorem\n",
+ "* Thursday September 16: Summary of Ridge and Lasso with examples and start resampling techniques\n",
"\n",
- "* Friday September 11: Ridge and Lasso regression\n",
+ "* Friday September 17: Resampling methods, Cross-validation, Bootstrapping and jackknife\n",
"\n",
- "## Thursday September 10\n",
- "\n",
- "[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember10.mp4?vrtx=view-as-webpage) and [handwritten notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/NotesSeptember10.pdf)\n",
- "\n",
- "More material will be added here, see handwritten notes also.\n",
- "## A Bayesian approach to develop intuition about skrinkage methods\n",
- "\n",
- "See Handwritten notes\n",
- "\n",
- "## The singular value decomposition\n",
+ "## Thursday September 16, Summary of Ridge and Lasso Regression and start Resampling methods\n",
"\n",
"\n",
- "The examples we have looked at so far are cases where we normally can\n",
- "invert the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$. Using a polynomial expansion as we\n",
- "did both for the masses and the fitting of the equation of state,\n",
- "leads to row vectors of the design matrix which are essentially\n",
- "orthogonal due to the polynomial character of our model. Obtaining the inverse of the design matrix is then often done via a so-called LU, QR or Cholesky decomposition. \n",
+ "## Deriving OLS from a probability distribution\n",
"\n",
+ "Our basic assumption when we derived the OLS equations was to assume\n",
+ "that our output is determined by a given continuous function\n",
+ "$f(\\boldsymbol{x})$ and a random noise $\\boldsymbol{\\epsilon}$ given by the normal\n",
+ "distribution with zero mean value and an undetermined variance\n",
+ "$\\sigma^2$.\n",
"\n",
- "\n",
- "This may\n",
- "however not the be case in general and a standard matrix inversion\n",
- "algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.\n",
- "\n",
- "There is however a way to partially circumvent this problem and also gain some insights about the ordinary least squares approach, and later shrinkage methods like Ridge and Lasso regressions. \n",
- "\n",
- "This is given by the **Singular Value Decomposition** algorithm, perhaps\n",
- "the most powerful linear algebra algorithm. Let us look at a\n",
- "different example where we may have problems with the standard matrix\n",
- "inversion algorithm. Thereafter we dive into the math of the SVD.\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "## Linear Regression Problems\n",
- "\n",
- "One of the typical problems we encounter with linear regression, in particular \n",
- "when the matrix $\\boldsymbol{X}$ (our so-called design matrix) is high-dimensional, \n",
- "are problems with near singular or singular matrices. The column vectors of $\\boldsymbol{X}$ \n",
- "may be linearly dependent, normally referred to as super-collinearity. \n",
- "This means that the matrix may be rank deficient and it is basically impossible to \n",
- "to model the data using linear regression. As an example, consider the matrix"
+ "We found above that the outputs $\\boldsymbol{y}$ have a mean value given by\n",
+ "$\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$ and variance $\\sigma^2$. Since the entries to\n",
+ "the design matrix are not stochastic variables, we can assume that the\n",
+ "probability distribution of our targets is also a normal distribution\n",
+ "but now with mean value $\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$. This means that a\n",
+ "single output $y_i$ is given by the Gaussian distribution"
]
},
{
@@ -72,18 +46,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\begin{align*}\n",
- "\\mathbf{X} & = \\left[\n",
- "\\begin{array}{rrr}\n",
- "1 & -1 & 2\n",
- "\\\\\n",
- "1 & 0 & 1\n",
- "\\\\\n",
- "1 & 2 & -1\n",
- "\\\\\n",
- "1 & 1 & 0\n",
- "\\end{array} \\right]\n",
- "\\end{align*}\n",
+ "y_i\\sim \\mathcal{N}(\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta}, \\sigma^2)=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
"$$"
]
},
@@ -91,14 +54,10 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The columns of $\\boldsymbol{X}$ are linearly dependent. We see this easily since the \n",
- "the first column is the row-wise sum of the other two columns. The rank (more correct,\n",
- "the column rank) of a matrix is the dimension of the space spanned by the\n",
- "column vectors. Hence, the rank of $\\mathbf{X}$ is equal to the number\n",
- "of linearly independent columns. In this particular case the matrix has rank 2.\n",
+ "## Independent and Identically Distrubuted (iid)\n",
"\n",
- "Super-collinearity of an $(n \\times p)$-dimensional design matrix $\\mathbf{X}$ implies\n",
- "that the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this"
+ "We assume now that the various $y_i$ values are stochastically distributed according to the above Gaussian distribution. \n",
+ "We define this distribution as"
]
},
{
@@ -106,14 +65,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\begin{align*}\n",
- "\\boldsymbol{X} & = \\left[\n",
- "\\begin{array}{rr}\n",
- "1 & -1\n",
- "\\\\\n",
- "1 & -1\n",
- "\\end{array} \\right].\n",
- "\\end{align*}\n",
+ "p(y_i, \\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]},\n",
"$$"
]
},
@@ -121,41 +73,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "We see easily that $\\mbox{det}(\\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \\times (-1) - 1 \\times (-1) = 0$. Hence, $\\mathbf{X}$ is singular and its inverse is undefined.\n",
- "This is equivalent to saying that the matrix $\\boldsymbol{X}$ has at least an eigenvalue which is zero.\n",
+ "which reads as finding the likelihood of an event $y_i$ with the input variables $\\boldsymbol{X}$ given the parameters (to be determined) $\\boldsymbol{\\beta}$.\n",
"\n",
- "\n",
- "## Fixing the singularity\n",
- "\n",
- "If our design matrix $\\boldsymbol{X}$ which enters the linear regression problem"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "\n",
- "\n",
- "$$\n",
- "\\begin{equation}\n",
- "\\boldsymbol{\\beta} = (\\boldsymbol{X}^{T} \\boldsymbol{X})^{-1} \\boldsymbol{X}^{T} \\boldsymbol{y},\n",
- "\\label{_auto1} \\tag{1}\n",
- "\\end{equation}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "has linearly dependent column vectors, we will not be able to compute the inverse\n",
- "of $\\boldsymbol{X}^T\\boldsymbol{X}$ and we cannot find the parameters (estimators) $\\beta_i$. \n",
- "The estimators are only well-defined if $(\\boldsymbol{X}^{T}\\boldsymbol{X})^{-1}$ exits. \n",
- "This is more likely to happen when the matrix $\\boldsymbol{X}$ is high-dimensional. In this case it is likely to encounter a situation where \n",
- "the regression parameters $\\beta_i$ cannot be estimated.\n",
- "\n",
- "A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change"
+ "Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event $\\boldsymbol{y}$ as the product of the single events, that is we have"
]
},
{
@@ -163,7 +83,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X}^{T} \\boldsymbol{X} \\rightarrow \\boldsymbol{X}^{T} \\boldsymbol{X}+\\lambda \\boldsymbol{I},\n",
+ "p(\\boldsymbol{y},\\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}=\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta}).\n",
"$$"
]
},
@@ -171,17 +91,8 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "where $\\boldsymbol{I}$ is the identity matrix. When we discuss **Ridge** regression this is actually what we end up evaluating. The parameter $\\lambda$ is called a hyperparameter. More about this later. \n",
- "\n",
- "\n",
- "\n",
- "## Basic math of the SVD\n",
- "\n",
- "\n",
- "From standard linear algebra we know that a square matrix $\\boldsymbol{X}$ can be diagonalized if and only it is \n",
- "a so-called [normal matrix](https://en.wikipedia.org/wiki/Normal_matrix), that is if $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$\n",
- "we have $\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ or if $\\boldsymbol{X}\\in {\\mathbb{C}}^{n\\times n}$ we have $\\boldsymbol{X}\\boldsymbol{X}^{\\dagger}=\\boldsymbol{X}^{\\dagger}\\boldsymbol{X}$.\n",
- "The matrix has then a set of eigenpairs"
+ "We will write this in a more compact form reserving $\\boldsymbol{D}$ for the domain of events, including the ouputs (targets) and the inputs. That is\n",
+ "in case we have a simple one-dimensional input and output case"
]
},
{
@@ -189,7 +100,7 @@
"metadata": {},
"source": [
"$$\n",
- "(\\lambda_1,\\boldsymbol{u}_1),\\dots, (\\lambda_n,\\boldsymbol{u}_n),\n",
+ "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})].\n",
"$$"
]
},
@@ -197,7 +108,8 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "and the eigenvalues are given by the diagonal matrix"
+ "In the more general case the various inputs should be replaced by the possible features represented by the input data set $\\boldsymbol{X}$. \n",
+ "We can now rewrite the above probability as"
]
},
{
@@ -205,7 +117,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{\\Sigma}=\\mathrm{Diag}(\\lambda_1, \\dots,\\lambda_n).\n",
+ "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
"$$"
]
},
@@ -213,7 +125,38 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The matrix $\\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\\boldsymbol{U}$"
+ "It is a conditional probability (see below) and reads as the likelihood of a domain of events $\\boldsymbol{D}$ given a set of parameters $\\boldsymbol{\\beta}$.\n",
+ "\n",
+ "## Maximum Likelihood Estimation (MLE)\n",
+ "\n",
+ "In statistics, maximum likelihood estimation (MLE) is a method of\n",
+ "estimating the parameters of an assumed probability distribution,\n",
+ "given some observed data. This is achieved by maximizing a likelihood\n",
+ "function so that, under the assumed statistical model, the observed\n",
+ "data is the most probable. \n",
+ "\n",
+ "\n",
+ "We will assume here that our events are given by the above Gaussian\n",
+ "distribution and we will determine the optimal parameters $\\beta$ by\n",
+ "maximizing the above PDF. However, computing the derivatives of a\n",
+ "product function is cumbersome and can easily lead to overflow and/or\n",
+ "underflowproblems, with potentials for loss of numerical precision.\n",
+ "\n",
+ "\n",
+ "In practice, it is more convenient to maximize the logarithm of the\n",
+ "PDF because it is a monotonically increasing function of the argument.\n",
+ "Alternatively, and this will be our option, we will minimize the\n",
+ "negative of the logarithm since this is a monotonically decreasing\n",
+ "function.\n",
+ "\n",
+ "Note also that maximization/minimization of the logarithm of the PDF\n",
+ "is equivalent to the maximization/minimization of the function itself.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## A new Cost Function\n",
+ "\n",
+ "We could now define a new cost function to minimize, namely the negative logarithm of the above PDF"
]
},
{
@@ -221,7 +164,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "C(\\boldsymbol{\\beta}=-\\log{\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})}=-\\sum_{i=0}^{n-1}\\log{p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})},\n",
"$$"
]
},
@@ -229,9 +172,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "with $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ or $\\boldsymbol{U}\\boldsymbol{U}^{\\dagger}=\\boldsymbol{I}$.\n",
- "\n",
- "Not all square matrices are diagonalizable. A matrix like the one discussed above"
+ "which becomes"
]
},
{
@@ -239,10 +180,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X} = \\begin{bmatrix} \n",
- "1& -1 \\\\\n",
- "1& -1\\\\\n",
- "\\end{bmatrix}\n",
+ "C(\\boldsymbol{\\beta}=\\frac{n}{2}\\log{2\\pi\\sigma^2}+\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}.\n",
"$$"
]
},
@@ -250,22 +188,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "is not diagonalizable, it is a so-called [defective matrix](https://en.wikipedia.org/wiki/Defective_matrix). It is easy to see that the condition\n",
- "$\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ is not fulfilled. \n",
- "\n",
- "\n",
- "## The SVD, a Fantastic Algorithm\n",
- "\n",
- "\n",
- "However, and this is the strength of the SVD algorithm, any general\n",
- "matrix $\\boldsymbol{X}$ can be decomposed in terms of a diagonal matrix and\n",
- "two orthogonal/unitary matrices. The [Singular Value Decompostion\n",
- "(SVD) theorem](https://en.wikipedia.org/wiki/Singular_value_decomposition)\n",
- "states that a general $m\\times n$ matrix $\\boldsymbol{X}$ can be written in\n",
- "terms of a diagonal matrix $\\boldsymbol{\\Sigma}$ of dimensionality $m\\times n$\n",
- "and two orthognal matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$, where the first has\n",
- "dimensionality $m \\times m$ and the last dimensionality $n\\times n$.\n",
- "We have then"
+ "Taking the derivative of the *new* cost function with respect to the parameters $\\beta$ we recognize our familiar OLS equation, namely"
]
},
{
@@ -273,7 +196,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\n",
+ "\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right) =0,\n",
"$$"
]
},
@@ -281,7 +204,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "As an example, the above defective matrix can be decomposed as"
+ "which leads to the well-known OLS equation for the optimal paramters $\\beta$"
]
},
{
@@ -289,7 +212,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X} = \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& 1 \\\\ 1& -1\\\\ \\end{bmatrix} \\begin{bmatrix} 2& 0 \\\\ 0& 0\\\\ \\end{bmatrix} \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& -1 \\\\ 1& 1\\\\ \\end{bmatrix}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n",
+ "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}!\n",
"$$"
]
},
@@ -297,113 +220,150 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "with eigenvalues $\\sigma_1=2$ and $\\sigma_2=0$. \n",
- "The SVD exits always! \n",
+ "## Bayes' Theorem\n",
"\n",
- "The SVD\n",
- "decomposition (singular values) gives eigenvalues \n",
- "$\\sigma_i\\geq\\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=p$, the\n",
- "eigenvalues (singular values) are zero.\n",
+ "If we combine the conditional probability with the marginal probability and the standard product rule, we have"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which we can rewrite as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "p(X\\vert Y)= \\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}=\\frac{p(Y\\vert X)p(X)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which is Bayes' theorem. It allows us to evaluate the uncertainty in in $X$ after we have observed $Y$. We can easily interchange $X$ with $Y$. \n",
"\n",
- "In the general case, where our design matrix $\\boldsymbol{X}$ has dimension\n",
- "$n\\times p$, the matrix is thus decomposed into an $n\\times n$\n",
- "orthogonal matrix $\\boldsymbol{U}$, a $p\\times p$ orthogonal matrix $\\boldsymbol{V}$\n",
- "and a diagonal matrix $\\boldsymbol{\\Sigma}$ with $r=\\mathrm{min}(n,p)$\n",
- "singular values $\\sigma_i\\geq 0$ on the main diagonal and zeros filling\n",
- "the rest of the matrix. There are at most $p$ singular values\n",
- "assuming that $n > p$. In our regression examples for the nuclear\n",
- "masses and the equation of state this is indeed the case, while for\n",
- "the Ising model we have $p > n$. These are often cases that lead to\n",
- "near singular or singular matrices.\n",
+ "## Interpretations of Bayes' Theorem\n",
"\n",
- "The columns of $\\boldsymbol{U}$ are called the left singular vectors while the columns of $\\boldsymbol{V}$ are the right singular vectors.\n",
+ "The quantity $p(Y\\vert X)$ on the right-hand side of the theorem is\n",
+ "evaluated for the observed data $Y$ and can be viewed as a function of\n",
+ "the parameter space represented by $X$. This function is not\n",
+ "necesseraly normalized and is normally called the likelihood function.\n",
"\n",
- "## Economy-size SVD\n",
+ "The function $p(X)$ on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution.\n",
"\n",
- "If we assume that $n > p$, then our matrix $\\boldsymbol{U}$ has dimension $n\n",
- "\\times n$. The last $n-p$ columns of $\\boldsymbol{U}$ become however\n",
- "irrelevant in our calculations since they are multiplied with the\n",
- "zeros in $\\boldsymbol{\\Sigma}$.\n",
+ "## Test Function for what happens with OLS, Ridge and Lasso\n",
"\n",
- "The economy-size decomposition removes extra rows or columns of zeros\n",
- "from the diagonal matrix of singular values, $\\boldsymbol{\\Sigma}$, along with the columns\n",
- "in either $\\boldsymbol{U}$ or $\\boldsymbol{V}$ that multiply those zeros in the expression. \n",
- "Removing these zeros and columns can improve execution time\n",
- "and reduce storage requirements without compromising the accuracy of\n",
- "the decomposition.\n",
+ "We will play around with a study of the values for the optimal\n",
+ "parameters $\\boldsymbol{\\beta}$ using OLS, Ridge and Lasso regression. For\n",
+ "OLS, you will notice as function of the noise and polynomial degree,\n",
+ "that the parameters $\\beta$ will fluctuate from order to order in the\n",
+ "polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS.\n",
"\n",
- "If $n > p$, we keep only the first $p$ columns of $\\boldsymbol{U}$ and $\\boldsymbol{\\Sigma}$ has dimension $p\\times p$. \n",
- "If $p > n$, then only the first $n$ columns of $\\boldsymbol{V}$ are computed and $\\boldsymbol{\\Sigma}$ has dimension $n\\times n$.\n",
- "The $n=p$ case is obvious, we retain the full SVD. \n",
- "In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.\n",
- "\n",
- "## Codes for the SVD"
+ "For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one."
]
},
{
"cell_type": "code",
- "execution_count": 1,
+ "execution_count": null,
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
+ "%matplotlib inline\n",
+ "\n",
"import numpy as np\n",
- "# SVD inversion\n",
- "def SVDinv(A):\n",
- " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n",
- " SVD is numerically more stable than the inversion algorithms provided by\n",
- " numpy and scipy.linalg at the cost of being slower.\n",
- " '''\n",
- " U, s, VT = np.linalg.svd(A)\n",
- "# print('test U')\n",
- "# print( (np.transpose(U) @ U - U @np.transpose(U)))\n",
- "# print('test VT')\n",
- "# print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n",
- " print(U)\n",
- " print(s)\n",
- " print(VT)\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn import linear_model\n",
"\n",
- " D = np.zeros((len(U),len(VT)))\n",
- " for i in range(0,len(VT)):\n",
- " D[i,i]=s[i]\n",
- " UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)\n",
- " return np.matmul(V,np.matmul(invD,UT))\n",
+ "def R2(y_data, y_model):\n",
+ " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
+ "def MSE(y_data,y_model):\n",
+ " n = np.size(y_model)\n",
+ " return np.sum((y_data-y_model)**2)/n\n",
+ "\n",
+ "# Make data set.\n",
+ "n = 10000\n",
+ "x = np.random.rand(n)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n",
+ "\n",
+ "Maxpolydegree = 5\n",
+ "X = np.zeros((len(x),Maxpolydegree))\n",
+ "X[:,0] = 1.0\n",
+ "\n",
+ "for polydegree in range(1, Maxpolydegree):\n",
+ " for degree in range(polydegree):\n",
+ " X[:,degree] = x**(degree)\n",
"\n",
"\n",
- "X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])\n",
- "print(X)\n",
- "A = np.transpose(X) @ X\n",
- "print(A)\n",
- "# Brute force inversion of super-collinear matrix\n",
- "#B = np.linalg.inv(A)\n",
- "#print(B)\n",
- "C = SVDinv(A)\n",
- "print(C)"
+ "# We split the data in test and training data\n",
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
+ "\n",
+ "# matrix inversion to find beta\n",
+ "OLSbeta = np.linalg.pinv(X_train.T @ X_train) @ X_train.T @ y_train\n",
+ "print(OLSbeta)\n",
+ "ypredictOLS = X_test @ OLSbeta\n",
+ "print(\"Test MSE OLS\")\n",
+ "print(MSE(y_test,ypredictOLS))\n",
+ "# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 4\n",
+ "MSERidgePredict = np.zeros(nlambdas)\n",
+ "MSELassoPredict = np.zeros(nlambdas)\n",
+ "lambdas = np.logspace(-3, 1, nlambdas)\n",
+ "for i in range(nlambdas):\n",
+ " lmb = lambdas[i]\n",
+ " # Make the fit using Ridge and Lasso\n",
+ " RegRidge = linear_model.Ridge(lmb,fit_intercept=False)\n",
+ " RegRidge.fit(X_train,y_train)\n",
+ " RegLasso = linear_model.Lasso(lmb,fit_intercept=False)\n",
+ " RegLasso.fit(X_train,y_train)\n",
+ " # and then make the prediction\n",
+ " ypredictRidge = RegRidge.predict(X_test)\n",
+ " ypredictLasso = RegLasso.predict(X_test)\n",
+ " # Compute the MSE and print it\n",
+ " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n",
+ " MSELassoPredict[i] = MSE(y_test,ypredictLasso)\n",
+ " print(lmb,RegRidge.coef_)\n",
+ " print(lmb,RegLasso.coef_)\n",
+ "# Now plot the results\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')\n",
+ "plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "The matrix $\\boldsymbol{X}$ has columns that are linearly dependent. The first\n",
- "column is the row-wise sum of the other two columns. The rank of a\n",
- "matrix (the column rank) is the dimension of space spanned by the\n",
- "column vectors. The rank of the matrix is the number of linearly\n",
- "independent columns, in this case just $2$. We see this from the\n",
- "singular values when running the above code. Running the standard\n",
- "inversion algorithm for matrix inversion with $\\boldsymbol{X}^T\\boldsymbol{X}$ results\n",
- "in the program terminating due to a singular matrix.\n",
+ "How can we understand this? \n",
"\n",
"\n",
+ "## Invoking Bayes' theorem\n",
"\n",
- "## Mathematical Properties\n",
+ "Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression. \n",
"\n",
- "There are several interesting mathematical properties which will be\n",
- "relevant when we are going to discuss the differences between say\n",
- "ordinary least squares (OLS) and **Ridge** regression.\n",
- "\n",
- "We have from OLS that the parameters of the linear approximation are given by"
+ "For ordinary least squares we postulated that the maximum likelihood for the doamin of events $\\boldsymbol{D}$ (one-dimensional case)"
]
},
{
@@ -411,7 +371,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
+ "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})],\n",
"$$"
]
},
@@ -419,7 +379,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The matrix to invert can be rewritten in terms of our SVD decomposition as"
+ "is given by"
]
},
{
@@ -427,7 +387,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X}^T\\boldsymbol{X} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n",
+ "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
"$$"
]
},
@@ -435,7 +395,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Using the orthogonality properties of $\\boldsymbol{U}$ we have"
+ "In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set $\\boldsymbol{\\beta}$ given a domain of events $\\boldsymbol{D}$? That is, how can we define the posterior probability"
]
},
{
@@ -443,7 +403,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X}^T\\boldsymbol{X} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T = \\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T,\n",
+ "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D}).\n",
"$$"
]
},
@@ -451,9 +411,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "with $\\boldsymbol{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared. \n",
- "\n",
- "This means that"
+ "Bayes' theorem comes to our rescue here since (omitting the normalization constant)"
]
},
{
@@ -461,7 +419,7 @@
"metadata": {},
"source": [
"$$\n",
- "(\\boldsymbol{X}^T\\boldsymbol{X})\\boldsymbol{V} = \\boldsymbol{V}\\boldsymbol{D},\n",
+ "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})\\propto p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})p(\\boldsymbol{\\beta}).\n",
"$$"
]
},
@@ -469,7 +427,16 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "that is the eigenvectors of $(\\boldsymbol{X}^T\\boldsymbol{X})$ are given by the columns of the right singular matrix of $\\boldsymbol{X}$ and the eigenvalues are the squared singular values. It is easy to show (show this) that"
+ "We have a model for $p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})$ but need one for the **prior** $p(\\boldsymbol{\\beta}$! \n",
+ "\n",
+ "\n",
+ "## Ridge and Bayes\n",
+ "\n",
+ "With the posterior probability defined by a likelihood which we have\n",
+ "already modeled and an unknown prior, we are now ready to make\n",
+ "additional models for the prior.\n",
+ "\n",
+ "We can, based on our discussions of the variance of $\\boldsymbol{\\beta}$ and the mean value, assume that the prior for the values $\\boldsymbol{\\beta}$ is given by a Gaussian with mean value zero and variance $\\tau^2$, that is"
]
},
{
@@ -477,7 +444,7 @@
"metadata": {},
"source": [
"$$\n",
- "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U} = \\boldsymbol{U}\\boldsymbol{D},\n",
+ "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n",
"$$"
]
},
@@ -485,9 +452,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "that is, the eigenvectors of $(\\boldsymbol{X}\\boldsymbol{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same. \n",
- "\n",
- "Going back to our OLS equation we have"
+ "Our posterior probability becomes then (omitting the normalization factor which is just a constant)"
]
},
{
@@ -495,7 +460,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n",
+ "p(\\boldsymbol{\\beta\\vert\\boldsymbol{D})}=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n",
"$$"
]
},
@@ -503,30 +468,10 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "We will come back to this expression when we discuss Ridge regression. \n",
- "\n",
- "\n",
- "$$ \\tilde{y}^{OLS}={\\bf X}\\hat{\\beta}^{OLS}=\\sum_{j=1}^p {\\bf u}_j{\\bf u}_j^T{\\bf y}$$ and for Ridge we have \n",
- "\n",
- "$$ \\tilde{y}^{Ridge}={\\bf X}\\hat{\\beta}^{Ridge}=\\sum_{j=1}^p {\\bf u}_j\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}{\\bf u}_j^T{\\bf y}$$ . \n",
- "\n",
- "It is indeed the economy-sized SVD, note the summation runs up tp $$p$$ only and not $$n$$. \n",
- "\n",
- "Here we have that $${\\bf X} = {\\bf U}{\\bf \\Sigma}{\\bf V}^T$$, with $$\\Sigma$$ being an $$ n\\times p$$ matrix and $${\\bf V}$$ being a $$ p\\times p$$ matrix. We also have assumed here that $$ n > p$$. \n",
- "\n",
- "\n",
- "\n",
- "## Friday September 12\n",
- "\n",
- "[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember11.mp4?vrtx=view-as-webpage) and [handwritten notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/NotesSeptember11.pdf)\n",
- "\n",
- "More material will be added here, see handwritten notes also.\n",
- "\n",
- "\n",
- "## Ridge and LASSO Regression\n",
- "\n",
- "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n",
- "our optimization problem is"
+ "We can now optimize this quantity with respect to $\\boldsymbol{\\beta}$. As we\n",
+ "did for OLS, this is most conveniently done by taking the negative\n",
+ "logarithm of the posterior probability. Doing so and leaving out the\n",
+ "constants terms that do not depend on $\\beta$, we have"
]
},
{
@@ -534,7 +479,7 @@
"metadata": {},
"source": [
"$$\n",
- "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n",
+ "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{2\\tau^2}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
"$$"
]
},
@@ -542,7 +487,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "or we can state it as"
+ "and replacing $1/2\\tau^2$ with $\\lambda$ we have"
]
},
{
@@ -550,8 +495,7 @@
"metadata": {},
"source": [
"$$\n",
- "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
- "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
+ "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
"$$"
]
},
@@ -559,98 +503,11 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "where we have used the definition of a norm-2 vector, that is"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "By minimizing the above equation with respect to the parameters\n",
- "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n",
- "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n",
- "defining a new cost function to be optimized, that is"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
- "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which leads to the Ridge regression minimization problem where we\n",
- "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n",
- "a finite number larger than zero. By defining"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "we have a new optimization equation"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
- "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n",
+ "which is our Ridge cost function! Nice, isn't it?\n",
"\n",
- "Here we have defined the norm-1 as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## More on Ridge Regression\n",
+ "## Lasso and Bayes\n",
"\n",
- "Using the matrix-vector expression for Ridge regression,"
+ "To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution ([Laplace in this case](https://en.wikipedia.org/wiki/Laplace_distribution)) with zero mean value, that is"
]
},
{
@@ -658,7 +515,7 @@
"metadata": {},
"source": [
"$$\n",
- "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n",
+ "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n",
"$$"
]
},
@@ -666,9 +523,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "by taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n",
- "a slightly modified matrix inversion problem which for finite values\n",
- "of $\\lambda$ does not suffer from singularity problems. We obtain"
+ "Our posterior probability becomes then (omitting the normalization factor which is just a constant)"
]
},
{
@@ -676,7 +531,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n",
+ "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n",
"$$"
]
},
@@ -684,7 +539,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that"
+ "Taking the negative\n",
+ "logarithm of the posterior probability and leaving out the\n",
+ "constants terms that do not depend on $\\beta$, we have"
]
},
{
@@ -692,7 +549,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n",
+ "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{\\tau}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
"$$"
]
},
@@ -700,14 +557,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "with $t$ a finite positive number. \n",
- "\n",
- "We see that Ridge regression is nothing but the standard\n",
- "OLS with a modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The\n",
- "consequences, in particular for our discussion of the bias-variance tradeoff \n",
- "are rather interesting.\n",
- "\n",
- "Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had"
+ "and replacing $1/\\tau$ with $\\lambda$ we have"
]
},
{
@@ -715,7 +565,7 @@
"metadata": {},
"source": [
"$$\n",
- "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U} = \\boldsymbol{U}\\boldsymbol{D}.\n",
+ "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
"$$"
]
},
@@ -723,72 +573,145 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "For Ridge regression this becomes"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$. \n",
- "\n",
- "## Interpreting the Ridge results\n",
- "\n",
- "Since $\\lambda \\geq 0$, it means that compared to OLS, we have"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n",
- "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n",
- "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n",
- "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n",
- "\\sigma_{i+1}$.\n",
- "\n",
- "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom.\n",
- "Actually, calculating the variance of $\\boldsymbol{X}\\boldsymbol{v}_j$ shows that this quantity is equal to $\\sigma_j^2/n$.\n",
- "With a parameter $\\lambda$ we can thus shrink the role of specific parameters. \n",
+ "which is our Lasso cost function! \n",
"\n",
"\n",
- "## More interpretations\n",
"\n",
- "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is"
+ "## Why resampling methods\n",
+ "\n",
+ "Before we proceed, we need to rethink what we have been doing. In our\n",
+ "eager to fit the data, we have omitted several important elements in\n",
+ "our regression analysis. In what follows we will\n",
+ "1. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff\n",
+ "\n",
+ "2. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more\n",
+ "\n",
+ "This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods. \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Resampling methods\n",
+ "Resampling methods are an indispensable tool in modern\n",
+ "statistics. They involve repeatedly drawing samples from a training\n",
+ "set and refitting a model of interest on each sample in order to\n",
+ "obtain additional information about the fitted model. For example, in\n",
+ "order to estimate the variability of a linear regression fit, we can\n",
+ "repeatedly draw different samples from the training data, fit a linear\n",
+ "regression to each new sample, and then examine the extent to which\n",
+ "the resulting fits differ. Such an approach may allow us to obtain\n",
+ "information that would not be available from fitting the model only\n",
+ "once using the original training sample.\n",
+ "\n",
+ "Two resampling methods are often used in Machine Learning analyses,\n",
+ "1. The **bootstrap method**\n",
+ "\n",
+ "2. and **Cross-Validation**\n",
+ "\n",
+ "In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular\n",
+ "cross-validation and the bootstrap method.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Resampling approaches can be computationally expensive\n",
+ "\n",
+ "Resampling approaches can be computationally expensive, because they\n",
+ "involve fitting the same statistical method multiple times using\n",
+ "different subsets of the training data. However, due to recent\n",
+ "advances in computing power, the computational requirements of\n",
+ "resampling methods generally are not prohibitive. In this chapter, we\n",
+ "discuss two of the most commonly used resampling methods,\n",
+ "cross-validation and the bootstrap. Both methods are important tools\n",
+ "in the practical application of many statistical learning\n",
+ "procedures. For example, cross-validation can be used to estimate the\n",
+ "test error associated with a given statistical learning method in\n",
+ "order to evaluate its performance, or to select the appropriate level\n",
+ "of flexibility. The process of evaluating a model’s performance is\n",
+ "known as model assessment, whereas the process of selecting the proper\n",
+ "level of flexibility for a model is known as model selection. The\n",
+ "bootstrap is widely used.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Why resampling methods ?\n",
+ "**Statistical analysis.**\n",
+ "\n",
+ "\n",
+ "* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods\n",
+ "\n",
+ "* The results can be analysed with the same statistical tools as we would use analysing experimental data.\n",
+ "\n",
+ "* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n",
+ "\n",
+ " \n",
+ "\n",
+ "## Statistical analysis\n",
+ "\n",
+ "* As in other experiments, many numerical experiments have two classes of errors:\n",
+ "\n",
+ " * Statistical errors\n",
+ "\n",
+ " * Systematical errors\n",
+ "\n",
+ "\n",
+ "* Statistical errors can be estimated using standard tools from statistics\n",
+ "\n",
+ "* Systematical errors are method specific and must be treated differently from case to case.\n",
+ "\n",
+ " \n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Resampling methods\n",
+ "\n",
+ "With all these analytical equations for both the OLS and Ridge\n",
+ "regression, we will now outline how to assess a given model. This will\n",
+ "lead us to a discussion of the so-called bias-variance tradeoff (see\n",
+ "below) and so-called resampling methods.\n",
+ "\n",
+ "One of the quantities we have discussed as a way to measure errors is\n",
+ "the mean-squared error (MSE), mainly used for fitting of continuous\n",
+ "functions. Another choice is the absolute error.\n",
+ "\n",
+ "In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,\n",
+ "we discuss the\n",
+ "1. prediction error or simply the **test error** $\\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the \n",
+ "\n",
+ "2. training error $\\mathrm{Err_{Train}}$, which is the average loss over the training data.\n",
+ "\n",
+ "As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.\n",
+ "For a certain level of complexity the test error will reach minimum, before starting to increase again. The\n",
+ "training error reaches a saturation.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Resampling methods: Jackknife and Bootstrap\n",
+ "\n",
+ "Two famous\n",
+ "resampling methods are the **independent bootstrap** and **the jackknife**. \n",
+ "\n",
+ "The jackknife is a special case of the independent bootstrap. Still, the jackknife was made\n",
+ "popular prior to the independent bootstrap. And as the popularity of\n",
+ "the independent bootstrap soared, new variants, such as **the dependent bootstrap**.\n",
+ "\n",
+ "The Jackknife and independent bootstrap work for\n",
+ "independent, identically distributed random variables.\n",
+ "If these conditions are not\n",
+ "satisfied, the methods will fail. Yet, it should be said that if the data are\n",
+ "independent, identically distributed, and we only want to estimate the\n",
+ "variance of $\\overline{X}$ (which often is the case), then there is no\n",
+ "need for bootstrapping. \n",
+ "\n",
+ "## Resampling methods: Jackknife\n",
+ "\n",
+ "The Jackknife works by making many replicas of the estimator $\\widehat{\\theta}$. \n",
+ "The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\\boldsymbol{x} = (x_1,x_2,\\cdots,X_n)$. \n",
+ "Let $\\boldsymbol{x}_i$ denote the vector"
]
},
{
@@ -796,7 +719,7 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n",
+ "\\boldsymbol{x}_i = (x_1,x_2,\\cdots,x_{i-1},x_{i+1},\\cdots,x_n),\n",
"$$"
]
},
@@ -804,67 +727,241 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "In this case the standard OLS results in"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "and"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n",
- "the Ridge estimator converges to zero when the hyperparameter goes to\n",
- "infinity.\n",
+ "which equals the vector $\\boldsymbol{x}$ with the exception that observation\n",
+ "number $i$ is left out. Using this notation, define\n",
+ "$\\widehat{\\theta}_i$ to be the estimator\n",
+ "$\\widehat{\\theta}$ computed using $\\vec{X}_i$. \n",
"\n",
- "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n",
"\n",
- "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n",
- "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\n",
+ "## Jackknife code example"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from numpy import *\n",
+ "from numpy.random import randint, randn\n",
+ "from time import time\n",
"\n",
+ "def jackknife(data, stat):\n",
+ " n = len(data);t = zeros(n); inds = arange(n); t0 = time()\n",
+ " ## 'jackknifing' by leaving out an observation for each i \n",
+ " for i in range(n):\n",
+ " t[i] = stat(delete(data,i) )\n",
+ "\n",
+ " # analysis \n",
+ " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Jackknife Statistics :\")\n",
+ " print(\"original bias std. error\")\n",
+ " print(\"%8g %14g %15g\" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))\n",
+ "\n",
+ " return t\n",
+ "\n",
+ "\n",
+ "# Returns mean of data samples \n",
+ "def stat(data):\n",
+ " return mean(data)\n",
+ "\n",
+ "\n",
+ "mu, sigma = 100, 15\n",
+ "datapoints = 10000\n",
+ "x = mu + sigma*random.randn(datapoints)\n",
+ "# jackknife returns the data sample \n",
+ "t = jackknife(x, stat)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Resampling methods: Bootstrap\n",
+ "Bootstrapping is a nonparametric approach to statistical inference\n",
+ "that substitutes computation for more traditional distributional\n",
+ "assumptions and asymptotic results. Bootstrapping offers a number of\n",
+ "advantages: \n",
+ "1. The bootstrap is quite general, although there are some cases in which it fails. \n",
+ "\n",
+ "2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. \n",
+ "\n",
+ "3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. \n",
+ "\n",
+ "4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Resampling methods: Bootstrap background\n",
+ "\n",
+ "Since $\\widehat{\\theta} = \\widehat{\\theta}(\\boldsymbol{X})$ is a function of random variables,\n",
+ "$\\widehat{\\theta}$ itself must be a random variable. Thus it has\n",
+ "a pdf, call this function $p(\\boldsymbol{t})$. The aim of the bootstrap is to\n",
+ "estimate $p(\\boldsymbol{t})$ by the relative frequency of\n",
+ "$\\widehat{\\theta}$. You can think of this as using a histogram\n",
+ "in the place of $p(\\boldsymbol{t})$. If the relative frequency closely\n",
+ "resembles $p(\\vec{t})$, then using numerics, it is straight forward to\n",
+ "estimate all the interesting parameters of $p(\\boldsymbol{t})$ using point\n",
+ "estimators. \n",
+ "\n",
+ "\n",
+ "## Resampling methods: More Bootstrap background\n",
+ "\n",
+ "In the case that $\\widehat{\\theta}$ has\n",
+ "more than one component, and the components are independent, we use the\n",
+ "same estimator on each component separately. If the probability\n",
+ "density function of $X_i$, $p(x)$, had been known, then it would have\n",
+ "been straight forward to do this by: \n",
+ "1. Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \\cdots, X_n^*)$. \n",
+ "\n",
+ "2. Then using these numbers, we could compute a replica of $\\widehat{\\theta}$ called $\\widehat{\\theta}^*$. \n",
+ "\n",
+ "By repeated use of (1) and (2), many\n",
+ "estimates of $\\widehat{\\theta}$ could have been obtained. The\n",
+ "idea is to use the relative frequency of $\\widehat{\\theta}^*$\n",
+ "(think of a histogram) as an estimate of $p(\\boldsymbol{t})$.\n",
+ "\n",
+ "## Resampling methods: Bootstrap approach\n",
+ "\n",
+ "But\n",
+ "unless there is enough information available about the process that\n",
+ "generated $X_1,X_2,\\cdots,X_n$, $p(x)$ is in general\n",
+ "unknown. Therefore, [Efron in 1979](https://projecteuclid.org/euclid.aos/1176344552) asked the\n",
+ "question: What if we replace $p(x)$ by the relative frequency\n",
+ "of the observation $X_i$; if we draw observations in accordance with\n",
+ "the relative frequency of the observations, will we obtain the same\n",
+ "result in some asymptotic sense? The answer is yes.\n",
+ "\n",
+ "\n",
+ "Instead of generating the histogram for the relative\n",
+ "frequency of the observation $X_i$, just draw the values\n",
+ "$(X_1^*,X_2^*,\\cdots,X_n^*)$ with replacement from the vector\n",
+ "$\\boldsymbol{X}$. \n",
+ "\n",
+ "## Resampling methods: Bootstrap steps\n",
+ "\n",
+ "The independent bootstrap works like this: \n",
+ "\n",
+ "1. Draw with replacement $n$ numbers for the observed variables $\\boldsymbol{x} = (x_1,x_2,\\cdots,x_n)$. \n",
+ "\n",
+ "2. Define a vector $\\boldsymbol{x}^*$ containing the values which were drawn from $\\boldsymbol{x}$. \n",
+ "\n",
+ "3. Using the vector $\\boldsymbol{x}^*$ compute $\\widehat{\\theta}^*$ by evaluating $\\widehat \\theta$ under the observations $\\boldsymbol{x}^*$. \n",
+ "\n",
+ "4. Repeat this process $k$ times. \n",
+ "\n",
+ "When you are done, you can draw a histogram of the relative frequency\n",
+ "of $\\widehat \\theta^*$. This is your estimate of the probability\n",
+ "distribution $p(t)$. Using this probability distribution you can\n",
+ "estimate any statistics thereof. In principle you never draw the\n",
+ "histogram of the relative frequency of $\\widehat{\\theta}^*$. Instead\n",
+ "you use the estimators corresponding to the statistic of interest. For\n",
+ "example, if you are interested in estimating the variance of $\\widehat\n",
+ "\\theta$, apply the etsimator $\\widehat \\sigma^2$ to the values\n",
+ "$\\widehat \\theta ^*$.\n",
+ "\n",
+ "\n",
+ "## Code example for the Bootstrap method\n",
+ "\n",
+ "The following code starts with a Gaussian distribution with mean value\n",
+ "$\\mu =100$ and variance $\\sigma=15$. We use this to generate the data\n",
+ "used in the bootstrap analysis. The bootstrap analysis returns a data\n",
+ "set after a given number of bootstrap operations (as many as we have\n",
+ "data points). This data set consists of estimated mean values for each\n",
+ "bootstrap operation. The histogram generated by the bootstrap method\n",
+ "shows that the distribution for these mean values is also a Gaussian,\n",
+ "centered around the mean value $\\mu=100$ but with standard deviation\n",
+ "$\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in\n",
+ "this case the same as the number of original data points). The value\n",
+ "of the standard deviation is what we expect from the central limit\n",
+ "theorem."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "from numpy import *\n",
+ "from numpy.random import randint, randn\n",
+ "from time import time\n",
+ "import matplotlib.mlab as mlab\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "# Returns mean of bootstrap samples \n",
+ "def stat(data):\n",
+ " return mean(data)\n",
+ "\n",
+ "# Bootstrap algorithm\n",
+ "def bootstrap(data, statistic, R):\n",
+ " t = zeros(R); n = len(data); inds = arange(n); t0 = time()\n",
+ " # non-parametric bootstrap \n",
+ " for i in range(R):\n",
+ " t[i] = statistic(data[randint(0,n,n)])\n",
+ "\n",
+ " # analysis \n",
+ " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Bootstrap Statistics :\")\n",
+ " print(\"original bias std. error\")\n",
+ " print(\"%8g %8g %14g %15g\" % (statistic(data), std(data),mean(t),std(t)))\n",
+ " return t\n",
+ "\n",
+ "\n",
+ "mu, sigma = 100, 15\n",
+ "datapoints = 10000\n",
+ "x = mu + sigma*random.randn(datapoints)\n",
+ "# bootstrap returns the data sample \n",
+ "t = bootstrap(x, stat, datapoints)\n",
+ "# the histogram of the bootstrapped data \n",
+ "n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)\n",
+ "\n",
+ "# add a 'best fit' line \n",
+ "y = mlab.normpdf( binsboot, mean(t), std(t))\n",
+ "lt = plt.plot(binsboot, y, 'r--', linewidth=1)\n",
+ "plt.xlabel('Smarts')\n",
+ "plt.ylabel('Probability')\n",
+ "plt.axis([99.5, 100.6, 0, 3.0])\n",
+ "plt.grid(True)\n",
+ "\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "## Various steps in cross-validation\n",
+ "\n",
+ "When the repetitive splitting of the data set is done randomly,\n",
+ "samples may accidently end up in a fast majority of the splits in\n",
+ "either training or test set. Such samples may have an unbalanced\n",
+ "influence on either model building or prediction evaluation. To avoid\n",
+ "this $k$-fold cross-validation structures the data splitting. The\n",
+ "samples are divided into $k$ more or less equally sized exhaustive and\n",
+ "mutually exclusive subsets. In turn (at each split) one of these\n",
+ "subsets plays the role of the test set while the union of the\n",
+ "remaining subsets constitutes the training set. Such a splitting\n",
+ "warrants a balanced representation of each sample in both training and\n",
+ "test set over the splits. Still the division into the $k$ subsets\n",
+ "involves a degree of randomness. This may be fully excluded when\n",
+ "choosing $k=n$. This particular case is referred to as leave-one-out\n",
+ "cross-validation (LOOCV). \n",
"\n",
"\n",
- "## A better understanding of regularization\n",
+ "## How to set up the cross-validation for Ridge and/or Lasso\n",
"\n",
- "The parameter $\\lambda$ that we have introduced in the Ridge (and\n",
- "Lasso as well) regression is often called a regularization parameter\n",
- "or shrinkage parameter. It is common to call it a hyperparameter. What does it mean mathemtically?\n",
+ "* Define a range of interest for the penalty parameter.\n",
"\n",
- "Here we will first look at how to analyze the difference between the\n",
- "standard OLS equations and the Ridge expressions in terms of a linear\n",
- "algebra analysis using the SVD algorithm. Thereafter, we will link\n",
- "(see the material on the bias-variance tradeoff below) these\n",
- "observation to the statisical analysis of the results. In particular\n",
- "we consider how the variance of the parameters $\\boldsymbol{\\beta}$ is\n",
- "affected by changing the parameter $\\lambda$.\n",
+ "* Divide the data set into training and test set comprising samples $\\{1, \\ldots, n\\} \\setminus i$ and $\\{ i \\}$, respectively.\n",
"\n",
- "## Decomposing the OLS and Ridge expressions\n",
- "\n",
- "We have our design matrix\n",
- " $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. With the SVD we decompose it as"
+ "* Fit the linear regression model by means of ridge estimation for each $\\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\\boldsymbol{\\sigma}_{-i}^2(\\lambda)$, as"
]
},
{
@@ -872,7 +969,11 @@
"metadata": {},
"source": [
"$$\n",
- "\\boldsymbol{X} = \\boldsymbol{U\\Sigma V^T},\n",
+ "\\begin{align*}\n",
+ "\\boldsymbol{\\beta}_{-i}(\\lambda) & = ( \\boldsymbol{X}_{-i, \\ast}^{T}\n",
+ "\\boldsymbol{X}_{-i, \\ast} + \\lambda \\boldsymbol{I}_{pp})^{-1}\n",
+ "\\boldsymbol{X}_{-i, \\ast}^{T} \\boldsymbol{y}_{-i}\n",
+ "\\end{align*}\n",
"$$"
]
},
@@ -880,539 +981,779 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "with $\\boldsymbol{U}\\in {\\mathbb{R}}^{n\\times n}$, $\\boldsymbol{\\Sigma}\\in {\\mathbb{R}}^{n\\times p}$\n",
- "and $\\boldsymbol{V}\\in {\\mathbb{R}}^{p\\times p}$.\n",
+ "* Evaluate the prediction performance of these models on the test set by $\\log\\{L[y_i, \\boldsymbol{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}$. Or, by the prediction error $|y_i - \\boldsymbol{X}_{i, \\ast} \\boldsymbol{\\beta}_{-i}(\\lambda)|$, the relative error, the error squared or the R2 score function.\n",
"\n",
- "The matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$ are unitary/orthonormal matrices, that is in case the matrices are real we have $\\boldsymbol{U}^T\\boldsymbol{U}=\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ and $\\boldsymbol{V}^T\\boldsymbol{V}=\\boldsymbol{V}\\boldsymbol{V}^T=\\boldsymbol{I}$.\n",
+ "* Repeat the first three steps such that each sample plays the role of the test set once.\n",
+ "\n",
+ "* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\begin{align*}\n",
+ "\\frac{1}{n} \\sum_{i = 1}^n \\log\\{L[y_i, \\mathbf{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}.\n",
+ "\\end{align*}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Cross-validation in brief\n",
+ "\n",
+ "For the various values of $k$\n",
+ "\n",
+ "1. shuffle the dataset randomly.\n",
+ "\n",
+ "2. Split the dataset into $k$ groups.\n",
+ "\n",
+ "3. For each unique group:\n",
+ "\n",
+ "a. Decide which group to use as set for test data\n",
+ "\n",
+ "b. Take the remaining groups as a training data set\n",
+ "\n",
+ "c. Fit a model on the training set and evaluate it on the test set\n",
+ "\n",
+ "d. Retain the evaluation score and discard the model\n",
"\n",
"\n",
+ "5. Summarize the model using the sample of model evaluation scores\n",
"\n",
- "## Introducing the Covariance and Correlation functions\n",
+ "## Code Example for Cross-validation and $k$-fold Cross-validation\n",
"\n",
- "Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about\n",
- "the definition of the covariance and the correlation function. These are quantities \n",
- "\n",
- "Suppose we have defined two vectors\n",
- "$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
- " \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "where for example"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "With this definition and recalling that the variance is defined as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "we can rewrite the covariance matrix as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
- " \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n",
- " \\end{bmatrix}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The covariance takes values between zero and infinity and may thus\n",
- "lead to problems with loss of numerical precision for particularly\n",
- "large values. It is common to scale the covariance matrix by\n",
- "introducing instead the correlation matrix defined via the so-called\n",
- "correlation function"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]=\\frac{\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}]}{\\sqrt{\\mathrm{var}[\\boldsymbol{x}] \\mathrm{var}[\\boldsymbol{y}]}}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The correlation function is then given by values $\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]\n",
- "\\in [-1,1]$. This avoids eventual problems with too large values. We\n",
- "can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n",
- "and $\\boldsymbol{y}$ as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
- " \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In the above example this is the function we constructed using **pandas**.\n",
- "\n",
- "## Correlation Function and Design/Feature Matrix\n",
- "\n",
- "In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**\n",
- "we defined the design/feature matrix $\\boldsymbol{X}$ as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}=\\begin{bmatrix}\n",
- "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
- "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
- "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
- "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
- "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
- "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ refering to the column numbers and the\n",
- "entries $n$ being the row elements.\n",
- "We can rewrite the design/feature matrix in terms of its column vectors as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "with a given vector"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{x}_i^T = \\begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \\dots & \\dots x_{n-1,i}\\end{bmatrix}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "With these definitions, we can now rewrite our $2\\times 2$\n",
- "correaltion/covariance matrix in terms of a moe general design/feature\n",
- "matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$\n",
- "covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i=0,1,\\dots,p-1$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
- "\\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n",
- "\\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n",
- "\\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & \\mathrm{var}[\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & \\mathrm{var}[\\boldsymbol{x}_{p-1}]\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "and the correlation matrix"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
- "1 & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n",
- "\\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & 1 & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n",
- "\\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & 1 & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & 1\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Covariance Matrix Examples\n",
- "\n",
- "\n",
- "The Numpy function **np.cov** calculates the covariance elements using\n",
- "the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n",
- "the exact mean values. The following simple function uses the\n",
- "**np.vstack** function which takes each vector of dimension $1\\times n$\n",
- "and produces a $2\\times n$ matrix $\\boldsymbol{W}$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{W} = \\begin{bmatrix} x_0 & y_0 \\\\\n",
- " x_1 & y_1 \\\\\n",
- " x_2 & y_2\\\\\n",
- " \\dots & \\dots \\\\\n",
- " x_{n-2} & y_{n-2}\\\\\n",
- " x_{n-1} & y_{n-1} & \n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which in turn is converted into into the $2\\times 2$ covariance matrix\n",
- "$\\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate\n",
- "the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n",
- "function **np.mean(x)**. We can also extract the eigenvalues of the\n",
- "covariance matrix through the **np.linalg.eig()** function."
+ "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial."
]
},
{
"cell_type": "code",
- "execution_count": 2,
+ "execution_count": null,
"metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "# Importing various packages\n",
- "import numpy as np\n",
- "n = 100\n",
- "x = np.random.normal(size=n)\n",
- "print(np.mean(x))\n",
- "y = 4+3*x+np.random.normal(size=n)\n",
- "print(np.mean(y))\n",
- "W = np.vstack((x, y))\n",
- "C = np.cov(W)\n",
- "print(C)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Correlation Matrix\n",
- "\n",
- "The previous example can be converted into the correlation matrix by\n",
- "simply scaling the matrix elements with the variances. We should also\n",
- "subtract the mean values for each column. This leads to the following\n",
- "code which sets up the correlations matrix for the previous example in\n",
- "a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\\times 2$ correlation matrix (since we have only two vectors)."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
"import numpy as np\n",
- "n = 100\n",
- "# define two vectors \n",
- "x = np.random.random(size=n)\n",
- "y = 4+3*x+np.random.normal(size=n)\n",
- "#scaling the x and y vectors \n",
- "x = x - np.mean(x)\n",
- "y = y - np.mean(y)\n",
- "variance_x = np.sum(x@x)/n\n",
- "variance_y = np.sum(y@y)/n\n",
- "print(variance_x)\n",
- "print(variance_y)\n",
- "cov_xy = np.sum(x@y)/n\n",
- "cov_xx = np.sum(x@x)/n\n",
- "cov_yy = np.sum(y@y)/n\n",
- "C = np.zeros((2,2))\n",
- "C[0,0]= cov_xx/variance_x\n",
- "C[1,1]= cov_yy/variance_y\n",
- "C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n",
- "C[1,0]= C[0,1]\n",
- "print(C)"
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import KFold\n",
+ "from sklearn.linear_model import Ridge\n",
+ "from sklearn.model_selection import cross_val_score\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "# Useful for eventual debugging.\n",
+ "np.random.seed(3155)\n",
+ "\n",
+ "# Generate the data.\n",
+ "nsamples = 100\n",
+ "x = np.random.randn(nsamples)\n",
+ "y = 3*x**2 + np.random.randn(nsamples)\n",
+ "\n",
+ "## Cross-validation on Ridge regression using KFold only\n",
+ "\n",
+ "# Decide degree on polynomial to fit\n",
+ "poly = PolynomialFeatures(degree = 6)\n",
+ "\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 500\n",
+ "lambdas = np.logspace(-3, 5, nlambdas)\n",
+ "\n",
+ "# Initialize a KFold instance\n",
+ "k = 5\n",
+ "kfold = KFold(n_splits = k)\n",
+ "\n",
+ "# Perform the cross-validation to estimate MSE\n",
+ "scores_KFold = np.zeros((nlambdas, k))\n",
+ "\n",
+ "i = 0\n",
+ "for lmb in lambdas:\n",
+ " ridge = Ridge(alpha = lmb)\n",
+ " j = 0\n",
+ " for train_inds, test_inds in kfold.split(x):\n",
+ " xtrain = x[train_inds]\n",
+ " ytrain = y[train_inds]\n",
+ "\n",
+ " xtest = x[test_inds]\n",
+ " ytest = y[test_inds]\n",
+ "\n",
+ " Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n",
+ " ridge.fit(Xtrain, ytrain[:, np.newaxis])\n",
+ "\n",
+ " Xtest = poly.fit_transform(xtest[:, np.newaxis])\n",
+ " ypred = ridge.predict(Xtest)\n",
+ "\n",
+ " scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n",
+ "\n",
+ " j += 1\n",
+ " i += 1\n",
+ "\n",
+ "\n",
+ "estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n",
+ "\n",
+ "## Cross-validation using cross_val_score from sklearn along with KFold\n",
+ "\n",
+ "# kfold is an instance initialized above as:\n",
+ "# kfold = KFold(n_splits = k)\n",
+ "\n",
+ "estimated_mse_sklearn = np.zeros(nlambdas)\n",
+ "i = 0\n",
+ "for lmb in lambdas:\n",
+ " ridge = Ridge(alpha = lmb)\n",
+ "\n",
+ " X = poly.fit_transform(x[:, np.newaxis])\n",
+ " estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n",
+ "\n",
+ " # cross_val_score return an array containing the estimated negative mse for every fold.\n",
+ " # we have to the the mean of every array in order to get an estimate of the mse of the model\n",
+ " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n",
+ "\n",
+ " i += 1\n",
+ "\n",
+ "## Plot and compare the slightly different ways to perform cross-validation\n",
+ "\n",
+ "plt.figure()\n",
+ "\n",
+ "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n",
+ "plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n",
+ "\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('mse')\n",
+ "\n",
+ "plt.legend()\n",
+ "\n",
+ "plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "We see that the matrix elements along the diagonal are one as they\n",
- "should be and that the matrix is symmetric. Furthermore, diagonalizing\n",
- "this matrix we easily see that it is a positive definite matrix.\n",
+ "## The bias-variance tradeoff\n",
"\n",
- "The above procedure with **numpy** can be made more compact if we use **pandas**.\n",
"\n",
- "## Correlation Matrix with Pandas\n",
+ "We will discuss the bias-variance tradeoff in the context of\n",
+ "continuous predictions such as regression. However, many of the\n",
+ "intuitions and ideas discussed here also carry over to classification\n",
+ "tasks. Consider a dataset $\\mathcal{L}$ consisting of the data\n",
+ "$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$. \n",
"\n",
- "We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code"
+ "Let us assume that the true data is generated from a noisy model"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "where $\\epsilon$ is normally distributed with mean zero and standard deviation $\\sigma^2$.\n",
+ "\n",
+ "In our derivation of the ordinary least squares method we defined then\n",
+ "an approximation to the function $f$ in terms of the parameters\n",
+ "$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n",
+ "that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$. \n",
+ "\n",
+ "Thereafter we found the parameters $\\boldsymbol{\\beta}$ by optimizing the means squared error via the so-called cost function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can rewrite this as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\frac{1}{n}\\sum_i(f_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\sigma^2.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The three terms represent the square of the bias of the learning\n",
+ "method, which can be thought of as the error caused by the simplifying\n",
+ "assumptions built into the method. The second term represents the\n",
+ "variance of the chosen model and finally the last terms is variance of\n",
+ "the error $\\boldsymbol{\\epsilon}$.\n",
+ "\n",
+ "To derive this equation, we need to recall that the variance of $\\boldsymbol{y}$ and $\\boldsymbol{\\epsilon}$ are both equal to $\\sigma^2$. The mean value of $\\boldsymbol{\\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\\boldsymbol{\\tilde{y}}$.\n",
+ "We use a more compact notation in terms of the expectation value"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}})^2\\right],\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and adding and subtracting $\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]$ we get"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}}+\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right],\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which, using the abovementioned expectation values can be rewritten as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "$$\n",
+ "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right]+\\mathrm{Var}\\left[\\boldsymbol{\\tilde{y}}\\right]+\\sigma^2,\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "that is the rewriting in terms of the so-called bias, the variance of the model $\\boldsymbol{\\tilde{y}}$ and the variance of $\\boldsymbol{\\epsilon}$.\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Example code for Bias-Variance tradeoff"
]
},
{
"cell_type": "code",
- "execution_count": 4,
+ "execution_count": null,
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
+ "import matplotlib.pyplot as plt\n",
"import numpy as np\n",
- "import pandas as pd\n",
- "n = 10\n",
- "x = np.random.normal(size=n)\n",
- "x = x - np.mean(x)\n",
- "y = 4+3*x+np.random.normal(size=n)\n",
- "y = y - np.mean(y)\n",
- "X = (np.vstack((x, y))).T\n",
- "print(X)\n",
- "Xpd = pd.DataFrame(X)\n",
- "print(Xpd)\n",
- "correlation_matrix = Xpd.corr()\n",
- "print(correlation_matrix)"
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.pipeline import make_pipeline\n",
+ "from sklearn.utils import resample\n",
+ "\n",
+ "np.random.seed(2018)\n",
+ "\n",
+ "n = 500\n",
+ "n_boostraps = 100\n",
+ "degree = 18 # A quite high value, just to show.\n",
+ "noise = 0.1\n",
+ "\n",
+ "# Make data set.\n",
+ "x = np.linspace(-1, 3, n).reshape(-1, 1)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)\n",
+ "\n",
+ "# Hold out some test data that is never used in training.\n",
+ "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
+ "\n",
+ "# Combine x transformation and model into one operation.\n",
+ "# Not neccesary, but convenient.\n",
+ "model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
+ "\n",
+ "# The following (m x n_bootstraps) matrix holds the column vectors y_pred\n",
+ "# for each bootstrap iteration.\n",
+ "y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
+ "for i in range(n_boostraps):\n",
+ " x_, y_ = resample(x_train, y_train)\n",
+ "\n",
+ " # Evaluate the new model on the same test data each time.\n",
+ " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
+ "\n",
+ "# Note: Expectations and variances taken w.r.t. different training\n",
+ "# data sets, hence the axis=1. Subsequent means are taken across the test data\n",
+ "# set in order to obtain a total value, but before this we have error/bias/variance\n",
+ "# calculated per data point in the test set.\n",
+ "# Note 2: The use of keepdims=True is important in the calculation of bias as this \n",
+ "# maintains the column vector form. Dropping this yields very unexpected results.\n",
+ "error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
+ "bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
+ "variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
+ "print('Error:', error)\n",
+ "print('Bias^2:', bias)\n",
+ "print('Var:', variance)\n",
+ "print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))\n",
+ "\n",
+ "plt.plot(x[::5, :], y[::5, :], label='f(x)')\n",
+ "plt.scatter(x_test, y_test, label='Data points')\n",
+ "plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')\n",
+ "plt.legend()\n",
+ "plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "We expand this model to the Franke function discussed above.\n",
- "\n",
- "## Correlation Matrix with Pandas and the Franke function"
+ "## Understanding what happens"
]
},
{
"cell_type": "code",
- "execution_count": 5,
+ "execution_count": null,
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.pipeline import make_pipeline\n",
+ "from sklearn.utils import resample\n",
+ "\n",
+ "np.random.seed(2018)\n",
+ "\n",
+ "n = 40\n",
+ "n_boostraps = 100\n",
+ "maxdegree = 14\n",
+ "\n",
+ "\n",
+ "# Make data set.\n",
+ "x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
+ "error = np.zeros(maxdegree)\n",
+ "bias = np.zeros(maxdegree)\n",
+ "variance = np.zeros(maxdegree)\n",
+ "polydegree = np.zeros(maxdegree)\n",
+ "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
+ "\n",
+ "for degree in range(maxdegree):\n",
+ " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
+ " y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
+ " for i in range(n_boostraps):\n",
+ " x_, y_ = resample(x_train, y_train)\n",
+ " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
+ "\n",
+ " polydegree[degree] = degree\n",
+ " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
+ " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
+ " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
+ " print('Polynomial degree:', degree)\n",
+ " print('Error:', error[degree])\n",
+ " print('Bias^2:', bias[degree])\n",
+ " print('Var:', variance[degree])\n",
+ " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n",
+ "\n",
+ "plt.plot(polydegree, error, label='Error')\n",
+ "plt.plot(polydegree, bias, label='bias')\n",
+ "plt.plot(polydegree, variance, label='Variance')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "## Summing up\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "The bias-variance tradeoff summarizes the fundamental tension in\n",
+ "machine learning, particularly supervised learning, between the\n",
+ "complexity of a model and the amount of training data needed to train\n",
+ "it. Since data is often limited, in practice it is often useful to\n",
+ "use a less-complex model with higher bias, that is a model whose asymptotic\n",
+ "performance is worse than another model because it is easier to\n",
+ "train and less sensitive to sampling noise arising from having a\n",
+ "finite-sized training dataset (smaller variance). \n",
+ "\n",
+ "\n",
+ "\n",
+ "The above equations tell us that in\n",
+ "order to minimize the expected test error, we need to select a\n",
+ "statistical learning method that simultaneously achieves low variance\n",
+ "and low bias. Note that variance is inherently a nonnegative quantity,\n",
+ "and squared bias is also nonnegative. Hence, we see that the expected\n",
+ "test MSE can never lie below $Var(\\epsilon)$, the irreducible error.\n",
+ "\n",
+ "\n",
+ "What do we mean by the variance and bias of a statistical learning\n",
+ "method? The variance refers to the amount by which our model would change if we\n",
+ "estimated it using a different training data set. Since the training\n",
+ "data are used to fit the statistical learning method, different\n",
+ "training data sets will result in a different estimate. But ideally the\n",
+ "estimate for our model should not vary too much between training\n",
+ "sets. However, if a method has high variance then small changes in\n",
+ "the training data can result in large changes in the model. In general, more\n",
+ "flexible statistical methods have higher variance.\n",
+ "\n",
+ "\n",
+ "You may also find this recent [article](https://www.pnas.org/content/116/32/15849) of interest.\n",
+ "\n",
+ "## Another Example from Scikit-Learn's Repository"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "\"\"\"\n",
+ "============================\n",
+ "Underfitting vs. Overfitting\n",
+ "============================\n",
+ "\n",
+ "This example demonstrates the problems of underfitting and overfitting and\n",
+ "how we can use linear regression with polynomial features to approximate\n",
+ "nonlinear functions. The plot shows the function that we want to approximate,\n",
+ "which is a part of the cosine function. In addition, the samples from the\n",
+ "real function and the approximations of different models are displayed. The\n",
+ "models have polynomial features of different degrees. We can see that a\n",
+ "linear function (polynomial with degree 1) is not sufficient to fit the\n",
+ "training samples. This is called **underfitting**. A polynomial of degree 4\n",
+ "approximates the true function almost perfectly. However, for higher degrees\n",
+ "the model will **overfit** the training data, i.e. it learns the noise of the\n",
+ "training data.\n",
+ "We evaluate quantitatively **overfitting** / **underfitting** by using\n",
+ "cross-validation. We calculate the mean squared error (MSE) on the validation\n",
+ "set, the higher, the less likely the model generalizes correctly from the\n",
+ "training data.\n",
+ "\"\"\"\n",
+ "\n",
+ "print(__doc__)\n",
+ "\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.pipeline import Pipeline\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "from sklearn.linear_model import LinearRegression\n",
+ "from sklearn.model_selection import cross_val_score\n",
+ "\n",
+ "\n",
+ "def true_fun(X):\n",
+ " return np.cos(1.5 * np.pi * X)\n",
+ "\n",
+ "np.random.seed(0)\n",
+ "\n",
+ "n_samples = 30\n",
+ "degrees = [1, 4, 15]\n",
+ "\n",
+ "X = np.sort(np.random.rand(n_samples))\n",
+ "y = true_fun(X) + np.random.randn(n_samples) * 0.1\n",
+ "\n",
+ "plt.figure(figsize=(14, 5))\n",
+ "for i in range(len(degrees)):\n",
+ " ax = plt.subplot(1, len(degrees), i + 1)\n",
+ " plt.setp(ax, xticks=(), yticks=())\n",
+ "\n",
+ " polynomial_features = PolynomialFeatures(degree=degrees[i],\n",
+ " include_bias=False)\n",
+ " linear_regression = LinearRegression()\n",
+ " pipeline = Pipeline([(\"polynomial_features\", polynomial_features),\n",
+ " (\"linear_regression\", linear_regression)])\n",
+ " pipeline.fit(X[:, np.newaxis], y)\n",
+ "\n",
+ " # Evaluate the models using crossvalidation\n",
+ " scores = cross_val_score(pipeline, X[:, np.newaxis], y,\n",
+ " scoring=\"neg_mean_squared_error\", cv=10)\n",
+ "\n",
+ " X_test = np.linspace(0, 1, 100)\n",
+ " plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label=\"Model\")\n",
+ " plt.plot(X_test, true_fun(X_test), label=\"True function\")\n",
+ " plt.scatter(X, y, edgecolor='b', s=20, label=\"Samples\")\n",
+ " plt.xlabel(\"x\")\n",
+ " plt.ylabel(\"y\")\n",
+ " plt.xlim((0, 1))\n",
+ " plt.ylim((-2, 2))\n",
+ " plt.legend(loc=\"best\")\n",
+ " plt.title(\"Degree {}\\nMSE = {:.2e}(+/- {:.2e})\".format(\n",
+ " degrees[i], -scores.mean(), scores.std()))\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## More examples on bootstrap and cross-validation and errors"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
},
"outputs": [],
"source": [
"# Common imports\n",
+ "import os\n",
"import numpy as np\n",
"import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.model_selection import train_test_split\n",
+ "from sklearn.utils import resample\n",
+ "from sklearn.metrics import mean_squared_error\n",
+ "# Where to save the figures and data files\n",
+ "PROJECT_ROOT_DIR = \"Results\"\n",
+ "FIGURE_ID = \"Results/FigureFiles\"\n",
+ "DATA_ID = \"DataFiles/\"\n",
"\n",
+ "if not os.path.exists(PROJECT_ROOT_DIR):\n",
+ " os.mkdir(PROJECT_ROOT_DIR)\n",
"\n",
- "def FrankeFunction(x,y):\n",
- "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
- "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
- "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
- "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
- "\treturn term1 + term2 + term3 + term4\n",
+ "if not os.path.exists(FIGURE_ID):\n",
+ " os.makedirs(FIGURE_ID)\n",
"\n",
+ "if not os.path.exists(DATA_ID):\n",
+ " os.makedirs(DATA_ID)\n",
"\n",
- "def create_X(x, y, n ):\n",
- "\tif len(x.shape) > 1:\n",
- "\t\tx = np.ravel(x)\n",
- "\t\ty = np.ravel(y)\n",
+ "def image_path(fig_id):\n",
+ " return os.path.join(FIGURE_ID, fig_id)\n",
"\n",
- "\tN = len(x)\n",
- "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n",
- "\tX = np.ones((N,l))\n",
+ "def data_path(dat_id):\n",
+ " return os.path.join(DATA_ID, dat_id)\n",
"\n",
- "\tfor i in range(1,n+1):\n",
- "\t\tq = int((i)*(i+1)/2)\n",
- "\t\tfor k in range(i+1):\n",
- "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n",
+ "def save_fig(fig_id):\n",
+ " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
"\n",
- "\treturn X\n",
+ "infile = open(data_path(\"EoS.csv\"),'r')\n",
"\n",
+ "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
+ "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
+ "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
+ "EoS = EoS.dropna()\n",
+ "Energies = EoS['Energy']\n",
+ "Density = EoS['Density']\n",
+ "# The design matrix now as function of various polytrops\n",
"\n",
- "# Making meshgrid of datapoints and compute Franke's function\n",
- "n = 4\n",
- "N = 100\n",
- "x = np.sort(np.random.uniform(0, 1, N))\n",
- "y = np.sort(np.random.uniform(0, 1, N))\n",
- "z = FrankeFunction(x, y)\n",
- "X = create_X(x, y, n=n) \n",
+ "Maxpolydegree = 30\n",
+ "X = np.zeros((len(Density),Maxpolydegree))\n",
+ "X[:,0] = 1.0\n",
+ "testerror = np.zeros(Maxpolydegree)\n",
+ "trainingerror = np.zeros(Maxpolydegree)\n",
+ "polynomial = np.zeros(Maxpolydegree)\n",
"\n",
- "Xpd = pd.DataFrame(X)\n",
- "# subtract the mean values and set up the covariance matrix\n",
- "Xpd = Xpd - Xpd.mean()\n",
- "covariance_matrix = Xpd.cov()\n",
- "print(covariance_matrix)"
+ "trials = 100\n",
+ "for polydegree in range(1, Maxpolydegree):\n",
+ " polynomial[polydegree] = polydegree\n",
+ " for degree in range(polydegree):\n",
+ " X[:,degree] = Density**(degree/3.0)\n",
+ "\n",
+ "# loop over trials in order to estimate the expectation value of the MSE\n",
+ " testerror[polydegree] = 0.0\n",
+ " trainingerror[polydegree] = 0.0\n",
+ " for samples in range(trials):\n",
+ " x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n",
+ " model = LinearRegression(fit_intercept=True).fit(x_train, y_train)\n",
+ " ypred = model.predict(x_train)\n",
+ " ytilde = model.predict(x_test)\n",
+ " testerror[polydegree] += mean_squared_error(y_test, ytilde)\n",
+ " trainingerror[polydegree] += mean_squared_error(y_train, ypred) \n",
+ "\n",
+ " testerror[polydegree] /= trials\n",
+ " trainingerror[polydegree] /= trials\n",
+ " print(\"Degree of polynomial: %3d\"% polynomial[polydegree])\n",
+ " print(\"Mean squared error on training data: %.8f\" % trainingerror[polydegree])\n",
+ " print(\"Mean squared error on test data: %.8f\" % testerror[polydegree])\n",
+ "\n",
+ "plt.plot(polynomial, np.log10(trainingerror), label='Training Error')\n",
+ "plt.plot(polynomial, np.log10(testerror), label='Test Error')\n",
+ "plt.xlabel('Polynomial degree')\n",
+ "plt.ylabel('log10[MSE]')\n",
+ "plt.legend()\n",
+ "plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "We note here that the covariance is zero for the first rows and\n",
- "columns since all matrix elements in the design matrix were set to one\n",
- "(we are fitting the function in terms of a polynomial of degree $n$).\n",
- "\n",
- "This means that the variance for these elements will be zero and will\n",
- "cause problems when we set up the correlation matrix. We can simply\n",
- "drop these elements and construct a correlation\n",
- "matrix without these elements. \n",
+ "\n",
+ "## The same example but now with cross-validation"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "# Common imports\n",
+ "import os\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
+ "from sklearn.metrics import mean_squared_error\n",
+ "from sklearn.model_selection import KFold\n",
+ "from sklearn.model_selection import cross_val_score\n",
"\n",
"\n",
- "## Rewriting the Covariance and/or Correlation Matrix\n",
+ "# Where to save the figures and data files\n",
+ "PROJECT_ROOT_DIR = \"Results\"\n",
+ "FIGURE_ID = \"Results/FigureFiles\"\n",
+ "DATA_ID = \"DataFiles/\"\n",
"\n",
- "We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\\boldsymbol{X}$ as"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{X}=\\begin{bmatrix}\n",
- "x_{00} & x_{01}\\\\\n",
- "x_{10} & x_{11}\\\\\n",
- "\\end{bmatrix}=\\begin{bmatrix}\n",
- "\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n",
- "\\end{bmatrix}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "If we then compute the expectation value"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}=\\begin{bmatrix}\n",
- "x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\\\\n",
- "x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "which is just"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]=\\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] \\\\\n",
- " \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "where we wrote $$\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]$$ to indicate that this the covariance of the vectors $\\boldsymbol{x}$ of the design/feature matrix $\\boldsymbol{X}$.\n",
+ "if not os.path.exists(PROJECT_ROOT_DIR):\n",
+ " os.mkdir(PROJECT_ROOT_DIR)\n",
"\n",
- "It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$.\n",
+ "if not os.path.exists(FIGURE_ID):\n",
+ " os.makedirs(FIGURE_ID)\n",
"\n",
+ "if not os.path.exists(DATA_ID):\n",
+ " os.makedirs(DATA_ID)\n",
"\n",
- "## Linking with SVD"
+ "def image_path(fig_id):\n",
+ " return os.path.join(FIGURE_ID, fig_id)\n",
+ "\n",
+ "def data_path(dat_id):\n",
+ " return os.path.join(DATA_ID, dat_id)\n",
+ "\n",
+ "def save_fig(fig_id):\n",
+ " plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
+ "\n",
+ "infile = open(data_path(\"EoS.csv\"),'r')\n",
+ "\n",
+ "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
+ "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
+ "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
+ "EoS = EoS.dropna()\n",
+ "Energies = EoS['Energy']\n",
+ "Density = EoS['Density']\n",
+ "# The design matrix now as function of various polytrops\n",
+ "\n",
+ "Maxpolydegree = 30\n",
+ "X = np.zeros((len(Density),Maxpolydegree))\n",
+ "X[:,0] = 1.0\n",
+ "estimated_mse_sklearn = np.zeros(Maxpolydegree)\n",
+ "polynomial = np.zeros(Maxpolydegree)\n",
+ "k =5\n",
+ "kfold = KFold(n_splits = k)\n",
+ "\n",
+ "for polydegree in range(1, Maxpolydegree):\n",
+ " polynomial[polydegree] = polydegree\n",
+ " for degree in range(polydegree):\n",
+ " X[:,degree] = Density**(degree/3.0)\n",
+ " OLS = LinearRegression()\n",
+ "# loop over trials in order to estimate the expectation value of the MSE\n",
+ " estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)\n",
+ "#[:, np.newaxis]\n",
+ " estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)\n",
+ "\n",
+ "plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')\n",
+ "plt.xlabel('Polynomial degree')\n",
+ "plt.ylabel('log10[MSE]')\n",
+ "plt.legend()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Cross-validation with Ridge"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "editable": true
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.model_selection import KFold\n",
+ "from sklearn.linear_model import Ridge\n",
+ "from sklearn.model_selection import cross_val_score\n",
+ "from sklearn.preprocessing import PolynomialFeatures\n",
+ "\n",
+ "# A seed just to ensure that the random numbers are the same for every run.\n",
+ "np.random.seed(3155)\n",
+ "# Generate the data.\n",
+ "n = 100\n",
+ "x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
+ "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
+ "# Decide degree on polynomial to fit\n",
+ "poly = PolynomialFeatures(degree = 10)\n",
+ "\n",
+ "# Decide which values of lambda to use\n",
+ "nlambdas = 500\n",
+ "lambdas = np.logspace(-3, 5, nlambdas)\n",
+ "# Initialize a KFold instance\n",
+ "k = 5\n",
+ "kfold = KFold(n_splits = k)\n",
+ "estimated_mse_sklearn = np.zeros(nlambdas)\n",
+ "i = 0\n",
+ "for lmb in lambdas:\n",
+ " ridge = Ridge(alpha = lmb)\n",
+ " estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)\n",
+ " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n",
+ " i += 1\n",
+ "plt.figure()\n",
+ "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n",
+ "plt.xlabel('log10(lambda)')\n",
+ "plt.ylabel('MSE')\n",
+ "plt.legend()\n",
+ "plt.show()"
]
}
],
"metadata": {},
"nbformat": 4,
- "nbformat_minor": 2
+ "nbformat_minor": 4
}
diff --git a/doc/src/week37/week37.do.txt b/doc/src/week37/week37.do.txt
index ef0b58b91..2d818b100 100644
--- a/doc/src/week37/week37.do.txt
+++ b/doc/src/week37/week37.do.txt
@@ -1,905 +1,1360 @@
-TITLE: Week 37: Ridge and Lasso Regression
+TITLE: Week 37: Summary of Ridge and Lasso Regression and Resampling Methods
AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
DATE: today
!split
===== Plans for week 37 =====
-* Thursday September 10: Motivation for shrinkage methods and the Singular Value Decompostion theorem
-* Friday September 11: Ridge and Lasso regression
+* Thursday September 16: Summary of Ridge and Lasso with examples and start resampling techniques
+* Friday September 17: Resampling methods, Cross-validation, Bootstrapping and jackknife
!split
-===== Thursday September 10 =====
+===== Thursday September 16, Summary of Ridge and Lasso Regression and start Resampling methods =====
-"Video of Lecture":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember10.mp4?vrtx=view-as-webpage" and "handwritten notes":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/NotesSeptember10.pdf"
-
-More material will be added here, see handwritten notes also.
-!split
-===== A Bayesian approach to develop intuition about skrinkage methods =====
-
-See Handwritten notes
!split
-===== The singular value decomposition =====
+===== Deriving OLS from a probability distribution =====
+Our basic assumption when we derived the OLS equations was to assume
+that our output is determined by a given continuous function
+$f(\bm{x})$ and a random noise $\bm{\epsilon}$ given by the normal
+distribution with zero mean value and an undetermined variance
+$\sigma^2$.
+
+We found above that the outputs $\bm{y}$ have a mean value given by
+$\bm{X}\hat{\bm{\beta}}$ and variance $\sigma^2$. Since the entries to
+the design matrix are not stochastic variables, we can assume that the
+probability distribution of our targets is also a normal distribution
+but now with mean value $\bm{X}\hat{\bm{\beta}}$. This means that a
+single output $y_i$ is given by the Gaussian distribution
+
+!bt
+\[
+y_i\sim \mathcal{N}(\bm{X}_{i,*}\bm{\beta}, \sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}.
+\]
+!et
+
+!split
+===== Independent and Identically Distrubuted (iid) =====
+
+We assume now that the various $y_i$ values are stochastically distributed according to the above Gaussian distribution.
+We define this distribution as
+!bt
+\[
+p(y_i, \bm{X}\vert\bm{\beta})=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]},
+\]
+!et
+which reads as finding the likelihood of an event $y_i$ with the input variables $\bm{X}$ given the parameters (to be determined) $\bm{\beta}$.
+
+Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event $\bm{y}$ as the product of the single events, that is we have
+
+!bt
+\[
+p(\bm{y},\bm{X}\vert\bm{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\bm{X}\vert\bm{\beta}).
+\]
+!et
+
+We will write this in a more compact form reserving $\bm{D}$ for the domain of events, including the ouputs (targets) and the inputs. That is
+in case we have a simple one-dimensional input and output case
+!bt
+\[
+\bm{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})].
+\]
+!et
+In the more general case the various inputs should be replaced by the possible features represented by the input data set $\bm{X}$.
+We can now rewrite the above probability as
+!bt
+\[
+p(\bm{D}\vert\bm{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}.
+\]
+!et
+
+It is a conditional probability (see below) and reads as the likelihood of a domain of events $\bm{D}$ given a set of parameters $\bm{\beta}$.
+
+!split
+===== Maximum Likelihood Estimation (MLE) =====
+
+In statistics, maximum likelihood estimation (MLE) is a method of
+estimating the parameters of an assumed probability distribution,
+given some observed data. This is achieved by maximizing a likelihood
+function so that, under the assumed statistical model, the observed
+data is the most probable.
+
+
+We will assume here that our events are given by the above Gaussian
+distribution and we will determine the optimal parameters $\beta$ by
+maximizing the above PDF. However, computing the derivatives of a
+product function is cumbersome and can easily lead to overflow and/or
+underflowproblems, with potentials for loss of numerical precision.
+
+
+In practice, it is more convenient to maximize the logarithm of the
+PDF because it is a monotonically increasing function of the argument.
+Alternatively, and this will be our option, we will minimize the
+negative of the logarithm since this is a monotonically decreasing
+function.
+
+Note also that maximization/minimization of the logarithm of the PDF
+is equivalent to the maximization/minimization of the function itself.
+
+
+
+!split
+===== A new Cost Function =====
+
+We could now define a new cost function to minimize, namely the negative logarithm of the above PDF
+
+!bt
+\[
+C(\bm{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\bm{X}\vert\bm{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\bm{X}\vert\bm{\beta})},
+\]
+!et
+which becomes
+!bt
+\[
+C(\bm{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}.
+\]
+!et
+
+Taking the derivative of the *new* cost function with respect to the parameters $\beta$ we recognize our familiar OLS equation, namely
+
+!bt
+\[
+\bm{X}^T\left(\bm{y}-\bm{X}\bm{\beta}\right) =0,
+\]
+!et
+which leads to the well-known OLS equation for the optimal paramters $\beta$
+!bt
+\[
+\hat{\bm{\beta}}^{\mathrm{OLS}}=\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}!
+\]
+!et
+
+
+
+!split
+===== Bayes' Theorem =====
+
+If we combine the conditional probability with the marginal probability and the standard product rule, we have
+!bt
+\[
+p(X\vert Y)= \frac{p(X,Y)}{p(Y)},
+\]
+!et
+which we can rewrite as
+
+!bt
+\[
+p(X\vert Y)= \frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}=\frac{p(Y\vert X)p(X)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)},
+\]
+!et
+which is Bayes' theorem. It allows us to evaluate the uncertainty in in $X$ after we have observed $Y$. We can easily interchange $X$ with $Y$.
+
+!split
+===== Interpretations of Bayes' Theorem =====
+
+The quantity $p(Y\vert X)$ on the right-hand side of the theorem is
+evaluated for the observed data $Y$ and can be viewed as a function of
+the parameter space represented by $X$. This function is not
+necesseraly normalized and is normally called the likelihood function.
+
+The function $p(X)$ on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution.
+
+!split
+===== Test Function for what happens with OLS, Ridge and Lasso =====
+
+We will play around with a study of the values for the optimal
+parameters $\bm{\beta}$ using OLS, Ridge and Lasso regression. For
+OLS, you will notice as function of the noise and polynomial degree,
+that the parameters $\beta$ will fluctuate from order to order in the
+polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS.
+
+For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one.
+
+!bc pycod
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.model_selection import train_test_split
+from sklearn import linear_model
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+# Make data set.
+n = 10000
+x = np.random.rand(n)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
+
+Maxpolydegree = 5
+X = np.zeros((len(x),Maxpolydegree))
+X[:,0] = 1.0
+
+for polydegree in range(1, Maxpolydegree):
+ for degree in range(polydegree):
+ X[:,degree] = x**(degree)
+
+
+# We split the data in test and training data
+X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
+
+# matrix inversion to find beta
+OLSbeta = np.linalg.pinv(X_train.T @ X_train) @ X_train.T @ y_train
+print(OLSbeta)
+ypredictOLS = X_test @ OLSbeta
+print("Test MSE OLS")
+print(MSE(y_test,ypredictOLS))
+# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn
+# Decide which values of lambda to use
+nlambdas = 4
+MSERidgePredict = np.zeros(nlambdas)
+MSELassoPredict = np.zeros(nlambdas)
+lambdas = np.logspace(-3, 1, nlambdas)
+for i in range(nlambdas):
+ lmb = lambdas[i]
+ # Make the fit using Ridge and Lasso
+ RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
+ RegRidge.fit(X_train,y_train)
+ RegLasso = linear_model.Lasso(lmb,fit_intercept=False)
+ RegLasso.fit(X_train,y_train)
+ # and then make the prediction
+ ypredictRidge = RegRidge.predict(X_test)
+ ypredictLasso = RegLasso.predict(X_test)
+ # Compute the MSE and print it
+ MSERidgePredict[i] = MSE(y_test,ypredictRidge)
+ MSELassoPredict[i] = MSE(y_test,ypredictLasso)
+ print(lmb,RegRidge.coef_)
+ print(lmb,RegLasso.coef_)
+# Now plot the results
+plt.figure()
+plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')
+plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
+
+
+!ec
+
+How can we understand this?
+
+
+!split
+===== Invoking Bayes' theorem =====
+
+Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression.
+
+For ordinary least squares we postulated that the maximum likelihood for the doamin of events $\bm{D}$ (one-dimensional case)
+!bt
+\[
+\bm{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})],
+\]
+!et
+is given by
+!bt
+\[
+p(\bm{D}\vert\bm{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}.
+\]
+!et
+
+In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set $\bm{\beta}$ given a domain of events $\bm{D}$? That is, how can we define the posterior probability
+
+!bt
+\[
+p(\bm{\beta}\vert\bm{D}).
+\]
+!et
+
+Bayes' theorem comes to our rescue here since (omitting the normalization constant)
+!bt
+\[
+p(\bm{\beta}\vert\bm{D})\propto p(\bm{D}\vert\bm{\beta})p(\bm{\beta}).
+\]
+!et
+
+We have a model for $p(\bm{D}\vert\bm{\beta})$ but need one for the _prior_ $p(\bm{\beta}$!
+
+
+!split
+===== Ridge and Bayes =====
+
+With the posterior probability defined by a likelihood which we have
+already modeled and an unknown prior, we are now ready to make
+additional models for the prior.
+
+We can, based on our discussions of the variance of $\bm{\beta}$ and the mean value, assume that the prior for the values $\bm{\beta}$ is given by a Gaussian with mean value zero and variance $\tau^2$, that is
+
+!bt
+\[
+p(\bm{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}.
+\]
+!et
+
+Our posterior probability becomes then (omitting the normalization factor which is just a constant)
+!bt
+\[
+p(\bm{\beta\vert\bm{D})}=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}.
+\]
+!et
+
+
+We can now optimize this quantity with respect to $\bm{\beta}$. As we
+did for OLS, this is most conveniently done by taking the negative
+logarithm of the posterior probability. Doing so and leaving out the
+constants terms that do not depend on $\beta$, we have
+
+
+!bt
+\[
+C(\bm{\beta})=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{2\tau^2}\vert\vert\bm{\beta}\vert\vert_2^2,
+\]
+!et
+and replacing $1/2\tau^2$ with $\lambda$ we have
+
+!bt
+\[
+C(\bm{\beta})=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\bm{\beta}\vert\vert_2^2,
+\]
+!et
+which is our Ridge cost function! Nice, isn't it?
+
+!split
+===== Lasso and Bayes =====
+
+To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution ("Laplace in this case":"https://en.wikipedia.org/wiki/Laplace_distribution") with zero mean value, that is
+
+!bt
+\[
+p(\bm{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}.
+\]
+!et
+
+Our posterior probability becomes then (omitting the normalization factor which is just a constant)
+!bt
+\[
+p(\bm{\beta}\vert\bm{D})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}.
+\]
+!et
+
+
+Taking the negative
+logarithm of the posterior probability and leaving out the
+constants terms that do not depend on $\beta$, we have
+
+
+!bt
+\[
+C(\bm{\beta}=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{\tau}\vert\vert\bm{\beta}\vert\vert_1,
+\]
+!et
+and replacing $1/\tau$ with $\lambda$ we have
+
+!bt
+\[
+C(\bm{\beta}=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\bm{\beta}\vert\vert_1,
+\]
+!et
+which is our Lasso cost function!
+
+
+
+!split
+===== Why resampling methods =====
+
+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
+o look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff
+o introduce resampling techniques like cross-validation, bootstrapping and jackknife and more
+
+This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods.
+
+
+
+
+
+!split
+===== Resampling methods =====
!bblock
+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.
-The examples we have looked at so far are cases where we normally can
-invert the matrix $\bm{X}^T\bm{X}$. Using a polynomial expansion as we
-did both for the masses and the fitting of the equation of state,
-leads to row vectors of the design matrix which are essentially
-orthogonal due to the polynomial character of our model. Obtaining the inverse of the design matrix is then often done via a so-called LU, QR or Cholesky decomposition.
+Two resampling methods are often used in Machine Learning analyses,
+o The _bootstrap method_
+o and _Cross-Validation_
+In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular
+cross-validation and the bootstrap method.
-This may
-however not the be case in general and a standard matrix inversion
-algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.
-
-There is however a way to partially circumvent this problem and also gain some insights about the ordinary least squares approach, and later shrinkage methods like Ridge and Lasso regressions.
-
-This is given by the _Singular Value Decomposition_ algorithm, perhaps
-the most powerful linear algebra algorithm. Let us look at a
-different example where we may have problems with the standard matrix
-inversion algorithm. Thereafter we dive into the math of the SVD.
-
!eblock
+!split
+===== Resampling approaches can be computationally expensive =====
+!bblock
+
+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.
+
+!eblock
!split
-===== Linear Regression Problems =====
+===== Why resampling methods ? =====
+!bblock Statistical analysis
+
+* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods
+* The results can be analysed with the same statistical tools as we would use analysing experimental data.
+* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
-One of the typical problems we encounter with linear regression, in particular
-when the matrix $\bm{X}$ (our so-called design matrix) is high-dimensional,
-are problems with near singular or singular matrices. The column vectors of $\bm{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
-!bt
-\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*}
-!et
-
-The columns of $\bm{X}$ are linearly dependent. We see this easily since the
-the first column is the row-wise sum of the other two columns. The rank (more correct,
-the column rank) of a matrix is the dimension of the space spanned by the
-column vectors. Hence, the rank of $\mathbf{X}$ is equal to the number
-of linearly independent columns. In this particular case the matrix has rank 2.
-
-Super-collinearity of an $(n \times p)$-dimensional design matrix $\mathbf{X}$ implies
-that the inverse of the matrix $\bm{X}^T\bm{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
-!bt
-\begin{align*}
-\bm{X} & = \left[
-\begin{array}{rr}
-1 & -1
-\\
-1 & -1
-\end{array} \right].
-\end{align*}
-!et
-We see easily that $\mbox{det}(\bm{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 $\bm{X}$ has at least an eigenvalue which is zero.
+!eblock
!split
-===== Fixing the singularity =====
+===== Statistical analysis =====
+!bblock
+
+* As in other experiments, many numerical experiments have two classes of errors:
+ * Statistical errors
+ * Systematical errors
+* Statistical errors can be estimated using standard tools from statistics
+* Systematical errors are method specific and must be treated differently from case to case.
+!eblock
-If our design matrix $\bm{X}$ which enters the linear regression problem
-!bt
-\begin{align}
-\bm{\beta} & = (\bm{X}^{T} \bm{X})^{-1} \bm{X}^{T} \bm{y},
-\end{align}
-!et
-has linearly dependent column vectors, we will not be able to compute the inverse
-of $\bm{X}^T\bm{X}$ and we cannot find the parameters (estimators) $\beta_i$.
-The estimators are only well-defined if $(\bm{X}^{T}\bm{X})^{-1}$ exits.
-This is more likely to happen when the matrix $\bm{X}$ is high-dimensional. In this case it is likely to encounter a situation where
-the regression parameters $\beta_i$ cannot be estimated.
-A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change
-!bt
-\[
-\bm{X}^{T} \bm{X} \rightarrow \bm{X}^{T} \bm{X}+\lambda \bm{I},
-\]
-!et
-where $\bm{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.
!split
-===== Basic math of the SVD =====
+===== Resampling methods =====
+
+With all these analytical equations for both the OLS and Ridge
+regression, we will now outline how to assess a given model. This will
+lead us to a discussion of the so-called bias-variance tradeoff (see
+below) and so-called resampling methods.
+
+One of the quantities we have discussed as a way to measure errors is
+the mean-squared error (MSE), mainly used for fitting of continuous
+functions. Another choice is the absolute error.
+
+In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,
+we discuss the
+o prediction error or simply the _test error_ $\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the
+o training error $\mathrm{Err_{Train}}$, which is the average loss over the training data.
+
+As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.
+For a certain level of complexity the test error will reach minimum, before starting to increase again. The
+training error reaches a saturation.
-From standard linear algebra we know that a square matrix $\bm{X}$ can be diagonalized if and only it is
-a so-called "normal matrix":"https://en.wikipedia.org/wiki/Normal_matrix", that is if $\bm{X}\in {\mathbb{R}}^{n\times n}$
-we have $\bm{X}\bm{X}^T=\bm{X}^T\bm{X}$ or if $\bm{X}\in {\mathbb{C}}^{n\times n}$ we have $\bm{X}\bm{X}^{\dagger}=\bm{X}^{\dagger}\bm{X}$.
-The matrix has then a set of eigenpairs
-
-!bt
-\[
-(\lambda_1,\bm{u}_1),\dots, (\lambda_n,\bm{u}_n),
-!et
-and the eigenvalues are given by the diagonal matrix
-!bt
-\[
-\bm{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n).
-\]
-!et
-The matrix $\bm{X}$ can be written in terms of an orthogonal/unitary transformation $\bm{U}$
-!bt
-\[
-\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T,
-\]
-!et
-with $\bm{U}\bm{U}^T=\bm{I}$ or $\bm{U}\bm{U}^{\dagger}=\bm{I}$.
-
-Not all square matrices are diagonalizable. A matrix like the one discussed above
-!bt
-\[
-\bm{X} = \begin{bmatrix}
-1& -1 \\
-1& -1\\
-\end{bmatrix}
-\]
-!et
-is not diagonalizable, it is a so-called "defective matrix":"https://en.wikipedia.org/wiki/Defective_matrix". It is easy to see that the condition
-$\bm{X}\bm{X}^T=\bm{X}^T\bm{X}$ is not fulfilled.
!split
-===== The SVD, a Fantastic Algorithm =====
+===== Resampling methods: Jackknife and Bootstrap =====
+Two famous
+resampling methods are the _independent bootstrap_ and _the jackknife_.
-However, and this is the strength of the SVD algorithm, any general
-matrix $\bm{X}$ can be decomposed in terms of a diagonal matrix and
-two orthogonal/unitary matrices. The "Singular Value Decompostion
-(SVD) theorem":"https://en.wikipedia.org/wiki/Singular_value_decomposition"
-states that a general $m\times n$ matrix $\bm{X}$ can be written in
-terms of a diagonal matrix $\bm{\Sigma}$ of dimensionality $m\times n$
-and two orthognal matrices $\bm{U}$ and $\bm{V}$, where the first has
-dimensionality $m \times m$ and the last dimensionality $n\times n$.
-We have then
+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_.
-!bt
-\[
-\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T
-\]
-!et
+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.
-As an example, the above defective matrix can be decomposed as
+!split
+===== Resampling methods: Jackknife =====
+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 $\bm{x} = (x_1,x_2,\cdots,X_n)$.
+Let $\bm{x}_i$ denote the vector
!bt
\[
-\bm{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}=\bm{U}\bm{\Sigma}\bm{V}^T,
+\bm{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n),
\]
!et
-with eigenvalues $\sigma_1=2$ and $\sigma_2=0$.
-The SVD exits always!
+which equals the vector $\bm{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 SVD
-decomposition (singular values) gives eigenvalues
-$\sigma_i\geq\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=p$, the
-eigenvalues (singular values) are zero.
-
-In the general case, where our design matrix $\bm{X}$ has dimension
-$n\times p$, the matrix is thus decomposed into an $n\times n$
-orthogonal matrix $\bm{U}$, a $p\times p$ orthogonal matrix $\bm{V}$
-and a diagonal matrix $\bm{\Sigma}$ with $r=\mathrm{min}(n,p)$
-singular values $\sigma_i\geq 0$ on the main diagonal and zeros filling
-the rest of the matrix. There are at most $p$ singular values
-assuming that $n > p$. In our regression examples for the nuclear
-masses and the equation of state this is indeed the case, while for
-the Ising model we have $p > n$. These are often cases that lead to
-near singular or singular matrices.
-
-The columns of $\bm{U}$ are called the left singular vectors while the columns of $\bm{V}$ are the right singular vectors.
!split
-===== Economy-size SVD =====
-
-If we assume that $n > p$, then our matrix $\bm{U}$ has dimension $n
-\times n$. The last $n-p$ columns of $\bm{U}$ become however
-irrelevant in our calculations since they are multiplied with the
-zeros in $\bm{\Sigma}$.
-
-The economy-size decomposition removes extra rows or columns of zeros
-from the diagonal matrix of singular values, $\bm{\Sigma}$, along with the columns
-in either $\bm{U}$ or $\bm{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 $\bm{U}$ and $\bm{\Sigma}$ has dimension $p\times p$.
-If $p > n$, then only the first $n$ columns of $\bm{V}$ are computed and $\bm{\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.
-
-!split
-===== Codes for the SVD =====
-
+===== Jackknife code example =====
!bc pycod
-import numpy as np
-# SVD inversion
-def SVDinv(A):
- ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).
- SVD is numerically more stable than the inversion algorithms provided by
- numpy and scipy.linalg at the cost of being slower.
- '''
- U, s, VT = np.linalg.svd(A)
-# print('test U')
-# print( (np.transpose(U) @ U - U @np.transpose(U)))
-# print('test VT')
-# print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))
- print(U)
- print(s)
- print(VT)
+from numpy import *
+from numpy.random import randint, randn
+from time import time
- D = np.zeros((len(U),len(VT)))
- for i in range(0,len(VT)):
- D[i,i]=s[i]
- UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)
- return np.matmul(V,np.matmul(invD,UT))
+def jackknife(data, stat):
+ n = len(data);t = zeros(n); inds = arange(n); t0 = time()
+ ## 'jackknifing' by leaving out an observation for each i
+ for i in range(n):
+ t[i] = stat(delete(data,i) )
+
+ # analysis
+ print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :")
+ print("original bias std. error")
+ print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))
+
+ return t
-X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])
-print(X)
-A = np.transpose(X) @ X
-print(A)
-# Brute force inversion of super-collinear matrix
-#B = np.linalg.inv(A)
-#print(B)
-C = SVDinv(A)
-print(C)
+# Returns mean of data samples
+def stat(data):
+ return mean(data)
+
+
+mu, sigma = 100, 15
+datapoints = 10000
+x = mu + sigma*random.randn(datapoints)
+# jackknife returns the data sample
+t = jackknife(x, stat)
!ec
-The matrix $\bm{X}$ has columns that are linearly dependent. The first
-column is the row-wise sum of the other two columns. The rank of a
-matrix (the column rank) is the dimension of space spanned by the
-column vectors. The rank of the matrix is the number of linearly
-independent columns, in this case just $2$. We see this from the
-singular values when running the above code. Running the standard
-inversion algorithm for matrix inversion with $\bm{X}^T\bm{X}$ results
-in the program terminating due to a singular matrix.
+!split
+===== Resampling methods: Bootstrap =====
+!bblock
+Bootstrapping is a nonparametric approach to statistical inference
+that substitutes computation for more traditional distributional
+assumptions and asymptotic results. Bootstrapping offers a number of
+advantages:
+o The bootstrap is quite general, although there are some cases in which it fails.
+o Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small.
+o It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically.
+o It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).
+!eblock
!split
-===== Mathematical Properties =====
+===== Resampling methods: Bootstrap background =====
-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
-!bt
-\[
-\bm{\tilde{y}} = \bm{X}\bm{\beta} = \bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}.
-\]
-!et
-
-The matrix to invert can be rewritten in terms of our SVD decomposition as
-
-!bt
-\[
-\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T.
-\]
-!et
-Using the orthogonality properties of $\bm{U}$ we have
-
-!bt
-\[
-\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T = \bm{V}\bm{D}\bm{V}^T,
-\]
-!et
-with $\bm{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared.
-
-This means that
-!bt
-\[
-(\bm{X}^T\bm{X})\bm{V} = \bm{V}\bm{D},
-\]
-!et
-that is the eigenvectors of $(\bm{X}^T\bm{X})$ are given by the columns of the right singular matrix of $\bm{X}$ and the eigenvalues are the squared singular values. It is easy to show (show this) that
-!bt
-\[
-(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D},
-\]
-!et
-that is, the eigenvectors of $(\bm{X}\bm{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same.
-
-Going back to our OLS equation we have
-!bt
-\[
-\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y}.
-\]
-!et
-We will come back to this expression when we discuss Ridge regression.
-
-
-$$ \tilde{y}^{OLS}={\bf X}\hat{\beta}^{OLS}=\sum_{j=1}^p {\bf u}_j{\bf u}_j^T{\bf y}$$ and for Ridge we have
-
-$$ \tilde{y}^{Ridge}={\bf X}\hat{\beta}^{Ridge}=\sum_{j=1}^p {\bf u}_j\frac{\sigma_j^2}{\sigma_j^2+\lambda}{\bf u}_j^T{\bf y}$$ .
-
-It is indeed the economy-sized SVD, note the summation runs up tp $$p$$ only and not $$n$$.
-
-Here we have that $${\bf X} = {\bf U}{\bf \Sigma}{\bf V}^T$$, with $$\Sigma$$ being an $$ n\times p$$ matrix and $${\bf V}$$ being a $$ p\times p$$ matrix. We also have assumed here that $$ n > p$$.
-
-
-
-!split
-===== Friday September 12 =====
-
-"Video of Lecture":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember11.mp4?vrtx=view-as-webpage" and "handwritten notes":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/NotesSeptember11.pdf"
-
-More material will be added here, see handwritten notes also.
+Since $\widehat{\theta} = \widehat{\theta}(\bm{X})$ is a function of random variables,
+$\widehat{\theta}$ itself must be a random variable. Thus it has
+a pdf, call this function $p(\bm{t})$. The aim of the bootstrap is to
+estimate $p(\bm{t})$ by the relative frequency of
+$\widehat{\theta}$. You can think of this as using a histogram
+in the place of $p(\bm{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(\bm{t})$ using point
+estimators.
!split
-===== Ridge and LASSO Regression =====
+===== Resampling methods: More Bootstrap background =====
-Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is
-our optimization problem is
-!bt
-\[
-{\displaystyle \min_{\bm{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}.
-\]
-!et
-or we can state it as
-!bt
-\[
-{\displaystyle \min_{\bm{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2,
-\]
-!et
-where we have used the definition of a norm-2 vector, that is
-!bt
-\[
-\vert\vert \bm{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.
-\]
-!et
+In the case that $\widehat{\theta}$ has
+more than one component, and the components are independent, we use the
+same estimator on each component separately. If the probability
+density function of $X_i$, $p(x)$, had been known, then it would have
+been straight forward to do this by:
+o Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \cdots, X_n^*)$.
+o Then using these numbers, we could compute a replica of $\widehat{\theta}$ called $\widehat{\theta}^*$.
-By minimizing the above equation with respect to the parameters
-$\bm{\beta}$ we could then obtain an analytical expression for the
-parameters $\bm{\beta}$. We can add a regularization parameter $\lambda$ by
-defining a new cost function to be optimized, that is
+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(\bm{t})$.
-!bt
-\[
-{\displaystyle \min_{\bm{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_2^2
-\]
-!et
+!split
+===== Resampling methods: Bootstrap approach =====
-which leads to the Ridge regression minimization problem where we
-require that $\vert\vert \bm{\beta}\vert\vert_2^2\le t$, where $t$ is
-a finite number larger than zero. By defining
+But
+unless there is enough information available about the process that
+generated $X_1,X_2,\cdots,X_n$, $p(x)$ is in general
+unknown. Therefore, "Efron in 1979":"https://projecteuclid.org/euclid.aos/1176344552" asked the
+question: What if we replace $p(x)$ by the relative frequency
+of the observation $X_i$; if we draw observations in accordance with
+the relative frequency of the observations, will we obtain the same
+result in some asymptotic sense? The answer is yes.
-!bt
-\[
-C(\bm{X},\bm{\beta})=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1,
-\]
-!et
-we have a new optimization equation
-!bt
-\[
-{\displaystyle \min_{\bm{\beta}\in
-{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1
-\]
-!et
-which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.
+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
+$\bm{X}$.
-Here we have defined the norm-1 as
-!bt
-\[
-\vert\vert \bm{x}\vert\vert_1 = \sum_i \vert x_i\vert.
-\]
-!et
+!split
+===== Resampling methods: Bootstrap steps =====
+
+The independent bootstrap works like this:
+
+o Draw with replacement $n$ numbers for the observed variables $\bm{x} = (x_1,x_2,\cdots,x_n)$.
+o Define a vector $\bm{x}^*$ containing the values which were drawn from $\bm{x}$.
+o Using the vector $\bm{x}^*$ compute $\widehat{\theta}^*$ by evaluating $\widehat \theta$ under the observations $\bm{x}^*$.
+o Repeat this process $k$ times.
+
+When you are done, you can draw a histogram of the relative frequency
+of $\widehat \theta^*$. This is your estimate of the probability
+distribution $p(t)$. Using this probability distribution you can
+estimate any statistics thereof. In principle you never draw the
+histogram of the relative frequency of $\widehat{\theta}^*$. Instead
+you use the estimators corresponding to the statistic of interest. For
+example, if you are interested in estimating the variance of $\widehat
+\theta$, apply the etsimator $\widehat \sigma^2$ to the values
+$\widehat \theta ^*$.
!split
-===== More on Ridge Regression =====
+===== Code example for the Bootstrap method =====
-Using the matrix-vector expression for Ridge regression,
-
-!bt
-\[
-C(\bm{X},\bm{\beta})=\frac{1}{n}\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\bm{\beta}^T\bm{\beta},
-\]
-!et
-
-by taking the derivatives with respect to $\bm{\beta}$ we obtain then
-a slightly modified matrix inversion problem which for finite values
-of $\lambda$ does not suffer from singularity problems. We obtain
-
-!bt
-\[
-\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y},
-\]
-!et
-
-with $\bm{I}$ being a $p\times p$ identity matrix with the constraint that
-
-!bt
-\[
-\sum_{i=0}^{p-1} \beta_i^2 \leq t,
-\]
-!et
-
-with $t$ a finite positive number.
-
-We see that Ridge regression is nothing but the standard
-OLS with a modified diagonal term added to $\bm{X}^T\bm{X}$. The
-consequences, in particular for our discussion of the bias-variance tradeoff
-are rather interesting.
-
-Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had
-!bt
-\[
-(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D}.
-\]
-!et
-
-We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\bm{U}$ as
-!bt
-\[
-\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y}
-\]
-!et
+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.
-For Ridge regression this becomes
+!bc pycod
+from numpy import *
+from numpy.random import randint, randn
+from time import time
+import matplotlib.mlab as mlab
+import matplotlib.pyplot as plt
-!bt
-\[
-\bm{X}\bm{\beta}^{\mathrm{Ridge}} = \bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T+\lambda\bm{I} \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\sum_{j=0}^{p-1}\bm{u}_j\bm{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\bm{y},
-\]
-!et
+# Returns mean of bootstrap samples
+def stat(data):
+ return mean(data)
-with the vectors $\bm{u}_j$ being the columns of $\bm{U}$.
+# Bootstrap algorithm
+def bootstrap(data, statistic, R):
+ t = zeros(R); n = len(data); inds = arange(n); t0 = time()
+ # non-parametric bootstrap
+ for i in range(R):
+ t[i] = statistic(data[randint(0,n,n)])
-!split
-===== Interpreting the Ridge results =====
-
-Since $\lambda \geq 0$, it means that compared to OLS, we have
-
-!bt
-\[
-\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1.
-\]
-!et
-
-Ridge regression finds the coordinates of $\bm{y}$ with respect to the
-orthonormal basis $\bm{U}$, it then shrinks the coordinates by
-$\frac{\sigma_j^2}{\sigma_j^2+\lambda}$. Recall that the SVD has
-eigenvalues ordered in a descending way, that is $\sigma_i \geq
-\sigma_{i+1}$.
-
-For small eigenvalues $\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom.
-Actually, calculating the variance of $\bm{X}\bm{v}_j$ shows that this quantity is equal to $\sigma_j^2/n$.
-With a parameter $\lambda$ we can thus shrink the role of specific parameters.
+ # analysis
+ print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
+ print("original bias std. error")
+ print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
+ return t
-!split
-===== More interpretations =====
+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)
-For the sake of simplicity, let us assume that the design matrix is orthonormal, that is
+# add a 'best fit' line
+y = mlab.normpdf( binsboot, mean(t), std(t))
+lt = plt.plot(binsboot, y, 'r--', linewidth=1)
+plt.xlabel('Smarts')
+plt.ylabel('Probability')
+plt.axis([99.5, 100.6, 0, 3.0])
+plt.grid(True)
-!bt
-\[
-\bm{X}^T\bm{X}=(\bm{X}^T\bm{X})^{-1} =\bm{I}.
-\]
-!et
+plt.show()
-In this case the standard OLS results in
-!bt
-\[
-\bm{\beta}^{\mathrm{OLS}} = \bm{X}^T\bm{y}=\sum_{i=0}^{p-1}\bm{u}_j\bm{u}_j^T\bm{y},
-\]
-!et
-
-and
-
-!bt
-\[
-\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{I}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}=\left(1+\lambda\right)^{-1}\bm{\beta}^{\mathrm{OLS}},
-\]
-!et
-
-that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\lambda$, and
-the Ridge estimator converges to zero when the hyperparameter goes to
-infinity.
-
-We will come back to more interpreations after we have gone through some of the statistical analysis part.
-
-For more discussions of Ridge and Lasso regression, "Wessel van Wieringen's":"https://arxiv.org/abs/1509.09169" article is highly recommended.
-Similarly, "Mehta et al's article":"https://arxiv.org/abs/1803.08823" is also recommended.
+!ec
!split
-===== A better understanding of regularization =====
+===== Various steps in cross-validation =====
-The parameter $\lambda$ that we have introduced in the Ridge (and
-Lasso as well) regression is often called a regularization parameter
-or shrinkage parameter. It is common to call it a hyperparameter. What does it mean mathemtically?
+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).
-Here we will first look at how to analyze the difference between the
-standard OLS equations and the Ridge expressions in terms of a linear
-algebra analysis using the SVD algorithm. Thereafter, we will link
-(see the material on the bias-variance tradeoff below) these
-observation to the statisical analysis of the results. In particular
-we consider how the variance of the parameters $\bm{\beta}$ is
-affected by changing the parameter $\lambda$.
+!split
+===== How to set up the cross-validation for Ridge and/or Lasso =====
-!split
-===== Decomposing the OLS and Ridge expressions =====
+* Define a range of interest for the penalty parameter.
-We have our design matrix
- $\bm{X}\in {\mathbb{R}}^{n\times p}$. With the SVD we decompose it as
+* Divide the data set into training and test set comprising samples $\{1, \ldots, n\} \setminus i$ and $\{ i \}$, respectively.
-!bt
-\[
-\bm{X} = \bm{U\Sigma V^T},
-\]
+* Fit the linear regression model by means of ridge estimation for each $\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\bm{\sigma}_{-i}^2(\lambda)$, as
+!bt
+\begin{align*}
+\bm{\beta}_{-i}(\lambda) & = ( \bm{X}_{-i, \ast}^{T}
+\bm{X}_{-i, \ast} + \lambda \bm{I}_{pp})^{-1}
+\bm{X}_{-i, \ast}^{T} \bm{y}_{-i}
+\end{align*}
+!et
+
+* Evaluate the prediction performance of these models on the test set by $\log\{L[y_i, \bm{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}$. Or, by the prediction error $|y_i - \bm{X}_{i, \ast} \bm{\beta}_{-i}(\lambda)|$, the relative error, the error squared or the R2 score function.
+
+* Repeat the first three steps such that each sample plays the role of the test set once.
+
+* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as
+!bt
+\begin{align*}
+\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}.
+\end{align*}
!et
-with $\bm{U}\in {\mathbb{R}}^{n\times n}$, $\bm{\Sigma}\in {\mathbb{R}}^{n\times p}$
-and $\bm{V}\in {\mathbb{R}}^{p\times p}$.
+!split
+===== Cross-validation in brief =====
-The matrices $\bm{U}$ and $\bm{V}$ are unitary/orthonormal matrices, that is in case the matrices are real we have $\bm{U}^T\bm{U}=\bm{U}\bm{U}^T=\bm{I}$ and $\bm{V}^T\bm{V}=\bm{V}\bm{V}^T=\bm{I}$.
+For the various values of $k$
+
+o shuffle the dataset randomly.
+o Split the dataset into $k$ groups.
+o For each unique group:
+ o Decide which group to use as set for test data
+ o Take the remaining groups as a training data set
+ o Fit a model on the training set and evaluate it on the test set
+ o Retain the evaluation score and discard the model
+o Summarize the model using the sample of model evaluation scores
!split
-===== Introducing the Covariance and Correlation functions =====
-
-Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about
-the definition of the covariance and the correlation function. These are quantities
-
-Suppose we have defined two vectors
-$\hat{x}$ and $\hat{y}$ with $n$ elements each. The covariance matrix $\bm{C}$ is defined as
-!bt
-\[
-\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{cov}[\bm{x},\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\
- \mathrm{cov}[\bm{y},\bm{x}] & \mathrm{cov}[\bm{y},\bm{y}] \\
- \end{bmatrix},
-\]
-!et
-where for example
-!bt
-\[
-\mathrm{cov}[\bm{x},\bm{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}).
-\]
-!et
-With this definition and recalling that the variance is defined as
-!bt
-\[
-\mathrm{var}[\bm{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2,
-\]
-!et
-we can rewrite the covariance matrix as
-!bt
-\[
-\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{var}[\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\
- \mathrm{cov}[\bm{x},\bm{y}] & \mathrm{var}[\bm{y}] \\
- \end{bmatrix}.
-\]
-!et
-
-The covariance takes values between zero and infinity and may thus
-lead to problems with loss of numerical precision for particularly
-large values. It is common to scale the covariance matrix by
-introducing instead the correlation matrix defined via the so-called
-correlation function
-
-!bt
-\[
-\mathrm{corr}[\bm{x},\bm{y}]=\frac{\mathrm{cov}[\bm{x},\bm{y}]}{\sqrt{\mathrm{var}[\bm{x}] \mathrm{var}[\bm{y}]}}.
-\]
-!et
-
-The correlation function is then given by values $\mathrm{corr}[\bm{x},\bm{y}]
-\in [-1,1]$. This avoids eventual problems with too large values. We
-can then define the correlation matrix for the two vectors $\bm{x}$
-and $\bm{y}$ as
-
-!bt
-\[
-\bm{K}[\bm{x},\bm{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\bm{x},\bm{y}] \\
- \mathrm{corr}[\bm{y},\bm{x}] & 1 \\
- \end{bmatrix},
-\]
-!et
-
-In the above example this is the function we constructed using _pandas_.
-
-!split
-===== Correlation Function and Design/Feature Matrix =====
-
-In our derivation of the various regression algorithms like _Ordinary Least Squares_ or _Ridge regression_
-we defined the design/feature matrix $\bm{X}$ as
-
-!bt
-\[
-\bm{X}=\begin{bmatrix}
-x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\
-x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\
-x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\
-\dots & \dots & \dots & \dots \dots & \dots \\
-x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\
-x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\
-\end{bmatrix},
-\]
-!et
-with $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors/features $p$ refering to the column numbers and the
-entries $n$ being the row elements.
-We can rewrite the design/feature matrix in terms of its column vectors as
-!bt
-\[
-\bm{X}=\begin{bmatrix} \bm{x}_0 & \bm{x}_1 & \bm{x}_2 & \dots & \dots & \bm{x}_{p-1}\end{bmatrix},
-\]
-!et
-with a given vector
-!bt
-\[
-\bm{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}.
-\]
-!et
-
-With these definitions, we can now rewrite our $2\times 2$
-correaltion/covariance matrix in terms of a moe general design/feature
-matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$. This leads to a $p\times p$
-covariance matrix for the vectors $\bm{x}_i$ with $i=0,1,\dots,p-1$
-
-!bt
-\[
-\bm{C}[\bm{x}] = \begin{bmatrix}
-\mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] & \mathrm{cov}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_0,\bm{x}_{p-1}]\\
-\mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] & \mathrm{cov}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_1,\bm{x}_{p-1}]\\
-\mathrm{cov}[\bm{x}_2,\bm{x}_0] & \mathrm{cov}[\bm{x}_2,\bm{x}_1] & \mathrm{var}[\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_2,\bm{x}_{p-1}]\\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\mathrm{cov}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & \mathrm{var}[\bm{x}_{p-1}]\\
-\end{bmatrix},
-\]
-!et
-and the correlation matrix
-!bt
-\[
-\bm{K}[\bm{x}] = \begin{bmatrix}
-1 & \mathrm{corr}[\bm{x}_0,\bm{x}_1] & \mathrm{corr}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_0,\bm{x}_{p-1}]\\
-\mathrm{corr}[\bm{x}_1,\bm{x}_0] & 1 & \mathrm{corr}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_1,\bm{x}_{p-1}]\\
-\mathrm{corr}[\bm{x}_2,\bm{x}_0] & \mathrm{corr}[\bm{x}_2,\bm{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\bm{x}_2,\bm{x}_{p-1}]\\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\dots & \dots & \dots & \dots & \dots & \dots \\
-\mathrm{corr}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & 1\\
-\end{bmatrix},
-\]
-!et
-
-
-!split
-===== Covariance Matrix Examples =====
-
-
-The Numpy function _np.cov_ calculates the covariance elements using
-the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have
-the exact mean values. The following simple function uses the
-_np.vstack_ function which takes each vector of dimension $1\times n$
-and produces a $2\times n$ matrix $\bm{W}$
-
-
-!bt
-\[
-\bm{W} = \begin{bmatrix} x_0 & y_0 \\
- x_1 & y_1 \\
- x_2 & y_2\\
- \dots & \dots \\
- x_{n-2} & y_{n-2}\\
- x_{n-1} & y_{n-1} &
- \end{bmatrix},
-\]
-!et
-
-which in turn is converted into into the $2\times 2$ covariance matrix
-$\bm{C}$ via the Numpy function _np.cov()_. We note that we can also calculate
-the mean value of each set of samples $\bm{x}$ etc using the Numpy
-function _np.mean(x)_. We can also extract the eigenvalues of the
-covariance matrix through the _np.linalg.eig()_ function.
-
-!bc pycod
-# Importing various packages
-import numpy as np
-n = 100
-x = np.random.normal(size=n)
-print(np.mean(x))
-y = 4+3*x+np.random.normal(size=n)
-print(np.mean(y))
-W = np.vstack((x, y))
-C = np.cov(W)
-print(C)
-!ec
-
-!split
-===== Correlation Matrix =====
-
-The previous example can be converted into the correlation matrix by
-simply scaling the matrix elements with the variances. We should also
-subtract the mean values for each column. This leads to the following
-code which sets up the correlations matrix for the previous example in
-a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\times 2$ correlation matrix (since we have only two vectors).
+===== Code Example for Cross-validation and $k$-fold Cross-validation =====
+The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial.
!bc pycod
import numpy as np
-n = 100
-# define two vectors
-x = np.random.random(size=n)
-y = 4+3*x+np.random.normal(size=n)
-#scaling the x and y vectors
-x = x - np.mean(x)
-y = y - np.mean(y)
-variance_x = np.sum(x@x)/n
-variance_y = np.sum(y@y)/n
-print(variance_x)
-print(variance_y)
-cov_xy = np.sum(x@y)/n
-cov_xx = np.sum(x@x)/n
-cov_yy = np.sum(y@y)/n
-C = np.zeros((2,2))
-C[0,0]= cov_xx/variance_x
-C[1,1]= cov_yy/variance_y
-C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
-C[1,0]= C[0,1]
-print(C)
-!ec
+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
-We see that the matrix elements along the diagonal are one as they
-should be and that the matrix is symmetric. Furthermore, diagonalizing
-this matrix we easily see that it is a positive definite matrix.
+# A seed just to ensure that the random numbers are the same for every run.
+# Useful for eventual debugging.
+np.random.seed(3155)
-The above procedure with _numpy_ can be made more compact if we use _pandas_.
+# Generate the data.
+nsamples = 100
+x = np.random.randn(nsamples)
+y = 3*x**2 + np.random.randn(nsamples)
-!split
-===== Correlation Matrix with Pandas =====
+## 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()
-We whow here how we can set up the correlation matrix using _pandas_, as done in this simple code
-!bc pycod
-import numpy as np
-import pandas as pd
-n = 10
-x = np.random.normal(size=n)
-x = x - np.mean(x)
-y = 4+3*x+np.random.normal(size=n)
-y = y - np.mean(y)
-X = (np.vstack((x, y))).T
-print(X)
-Xpd = pd.DataFrame(X)
-print(Xpd)
-correlation_matrix = Xpd.corr()
-print(correlation_matrix)
!ec
-We expand this model to the Franke function discussed above.
+!split
+===== The bias-variance tradeoff =====
+
+
+We will discuss the bias-variance tradeoff in the context of
+continuous predictions such as regression. However, many of the
+intuitions and ideas discussed here also carry over to classification
+tasks. Consider a dataset $\mathcal{L}$ consisting of the data
+$\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}$.
+
+Let us assume that the true data is generated from a noisy model
+
+!bt
+\[
+\bm{y}=f(\boldsymbol{x}) + \bm{\epsilon}
+\]
+!et
+
+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
+$\bm{\beta}$ and the design matrix $\bm{X}$ which embody our model,
+that is $\bm{\tilde{y}}=\bm{X}\bm{\beta}$.
+
+Thereafter we found the parameters $\bm{\beta}$ by optimizing the means squared error via the so-called cost function
+!bt
+\[
+C(\bm{X},\bm{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right].
+\]
+!et
+
+We can rewrite this as
+!bt
+\[
+\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\sigma^2.
+\]
+!et
+
+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 $\bm{\epsilon}$.
+
+To derive this equation, we need to recall that the variance of $\bm{y}$ and $\bm{\epsilon}$ are both equal to $\sigma^2$. The mean value of $\bm{\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\bm{\tilde{y}}$.
+We use a more compact notation in terms of the expectation value
+!bt
+\[
+\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}})^2\right],
+\]
+!et
+and adding and subtracting $\mathbb{E}\left[\bm{\tilde{y}}\right]$ we get
+!bt
+\[
+\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}}+\mathbb{E}\left[\bm{\tilde{y}}\right]-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right],
+\]
+!et
+which, using the abovementioned expectation values can be rewritten as
+!bt
+\[
+\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{y}-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\bm{\tilde{y}}\right]+\sigma^2,
+\]
+!et
+that is the rewriting in terms of the so-called bias, the variance of the model $\bm{\tilde{y}}$ and the variance of $\bm{\epsilon}$.
+
+
+
+
!split
-===== Correlation Matrix with Pandas and the Franke function =====
+===== Example code for Bias-Variance tradeoff =====
+!bc pycod
+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()
+
+!ec
+
+
+!split
+===== Understanding what happens =====
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+
+np.random.seed(2018)
+
+n = 40
+n_boostraps = 100
+maxdegree = 14
+
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+for degree in range(maxdegree):
+ model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
+ y_pred = np.empty((y_test.shape[0], n_boostraps))
+ for i in range(n_boostraps):
+ x_, y_ = resample(x_train, y_train)
+ y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
+
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+ variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+ print('Polynomial degree:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+plt.show()
+
+
+
+
+!ec
+
+!split
+===== Summing up =====
+
+
+
+
+The bias-variance tradeoff summarizes the fundamental tension in
+machine learning, particularly supervised learning, between the
+complexity of a model and the amount of training data needed to train
+it. Since data is often limited, in practice it is often useful to
+use a less-complex model with higher bias, that is a model whose asymptotic
+performance is worse than another model because it is easier to
+train and less sensitive to sampling noise arising from having a
+finite-sized training dataset (smaller variance).
+
+
+
+The above equations tell us that in
+order to minimize the expected test error, we need to select a
+statistical learning method that simultaneously achieves low variance
+and low bias. Note that variance is inherently a nonnegative quantity,
+and squared bias is also nonnegative. Hence, we see that the expected
+test MSE can never lie below $Var(\epsilon)$, the irreducible error.
+
+
+What do we mean by the variance and bias of a statistical learning
+method? The variance refers to the amount by which our model would change if we
+estimated it using a different training data set. Since the training
+data are used to fit the statistical learning method, different
+training data sets will result in a different estimate. But ideally the
+estimate for our model should not vary too much between training
+sets. However, if a method has high variance then small changes in
+the training data can result in large changes in the model. In general, more
+flexible statistical methods have higher variance.
+
+
+You may also find this recent "article":"https://www.pnas.org/content/116/32/15849" of interest.
+
+!split
+===== Another Example from Scikit-Learn's Repository =====
+!bc pycod
+"""
+============================
+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()
+!ec
+
+
+!split
+===== More examples on bootstrap and cross-validation and errors =====
!bc pycod
# Common imports
+import os
import numpy as np
import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.model_selection import train_test_split
+from sklearn.utils import resample
+from sklearn.metrics import mean_squared_error
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
-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
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
-def create_X(x, y, n ):
- if len(x.shape) > 1:
- x = np.ravel(x)
- y = np.ravel(y)
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
- N = len(x)
- l = int((n+1)*(n+2)/2) # Number of elements in beta
- X = np.ones((N,l))
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
- for i in range(1,n+1):
- q = int((i)*(i+1)/2)
- for k in range(i+1):
- X[:,q+k] = (x**(i-k))*(y**k)
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
- return X
+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
-# Making meshgrid of datapoints and compute Franke's function
-n = 4
-N = 100
-x = np.sort(np.random.uniform(0, 1, N))
-y = np.sort(np.random.uniform(0, 1, N))
-z = FrankeFunction(x, y)
-X = create_X(x, y, n=n)
+Maxpolydegree = 30
+X = np.zeros((len(Density),Maxpolydegree))
+X[:,0] = 1.0
+testerror = np.zeros(Maxpolydegree)
+trainingerror = np.zeros(Maxpolydegree)
+polynomial = np.zeros(Maxpolydegree)
+
+trials = 100
+for polydegree in range(1, Maxpolydegree):
+ polynomial[polydegree] = polydegree
+ for degree in range(polydegree):
+ X[:,degree] = Density**(degree/3.0)
+
+# loop over trials in order to estimate the expectation value of the MSE
+ testerror[polydegree] = 0.0
+ trainingerror[polydegree] = 0.0
+ for samples in range(trials):
+ x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
+ model = LinearRegression(fit_intercept=True).fit(x_train, y_train)
+ ypred = model.predict(x_train)
+ ytilde = model.predict(x_test)
+ testerror[polydegree] += mean_squared_error(y_test, ytilde)
+ trainingerror[polydegree] += mean_squared_error(y_train, ypred)
+
+ testerror[polydegree] /= trials
+ trainingerror[polydegree] /= trials
+ print("Degree of polynomial: %3d"% polynomial[polydegree])
+ print("Mean squared error on training data: %.8f" % trainingerror[polydegree])
+ print("Mean squared error on test data: %.8f" % testerror[polydegree])
+
+plt.plot(polynomial, np.log10(trainingerror), label='Training Error')
+plt.plot(polynomial, np.log10(testerror), label='Test Error')
+plt.xlabel('Polynomial degree')
+plt.ylabel('log10[MSE]')
+plt.legend()
+plt.show()
-Xpd = pd.DataFrame(X)
-# subtract the mean values and set up the covariance matrix
-Xpd = Xpd - Xpd.mean()
-covariance_matrix = Xpd.cov()
-print(covariance_matrix)
!ec
-We note here that the covariance is zero for the first rows and
-columns since all matrix elements in the design matrix were set to one
-(we are fitting the function in terms of a polynomial of degree $n$).
-This means that the variance for these elements will be zero and will
-cause problems when we set up the correlation matrix. We can simply
-drop these elements and construct a correlation
-matrix without these elements.
+!split
+===== The same example but now with cross-validation =====
+!bc pycod
+# Common imports
+import os
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.metrics import mean_squared_error
+from sklearn.model_selection import KFold
+from sklearn.model_selection import cross_val_score
+
+
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
+
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
+
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
+
+infile = open(data_path("EoS.csv"),'r')
+
+# Read the EoS data as csv file and organize the data into two arrays with density and energies
+EoS = pd.read_csv(infile, names=('Density', 'Energy'))
+EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
+EoS = EoS.dropna()
+Energies = EoS['Energy']
+Density = EoS['Density']
+# The design matrix now as function of various polytrops
+
+Maxpolydegree = 30
+X = np.zeros((len(Density),Maxpolydegree))
+X[:,0] = 1.0
+estimated_mse_sklearn = np.zeros(Maxpolydegree)
+polynomial = np.zeros(Maxpolydegree)
+k =5
+kfold = KFold(n_splits = k)
+
+for polydegree in range(1, Maxpolydegree):
+ polynomial[polydegree] = polydegree
+ for degree in range(polydegree):
+ X[:,degree] = Density**(degree/3.0)
+ OLS = LinearRegression()
+# loop over trials in order to estimate the expectation value of the MSE
+ estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)
+#[:, np.newaxis]
+ estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)
+
+plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')
+plt.xlabel('Polynomial degree')
+plt.ylabel('log10[MSE]')
+plt.legend()
+plt.show()
+
+!ec
!split
-===== Rewriting the Covariance and/or Correlation Matrix =====
+===== Cross-validation with Ridge =====
+!bc pycod
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.model_selection import KFold
+from sklearn.linear_model import Ridge
+from sklearn.model_selection import cross_val_score
+from sklearn.preprocessing import PolynomialFeatures
+
+# A seed just to ensure that the random numbers are the same for every run.
+np.random.seed(3155)
+# Generate the data.
+n = 100
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+# Decide degree on polynomial to fit
+poly = PolynomialFeatures(degree = 10)
+
+# Decide which values of lambda to use
+nlambdas = 500
+lambdas = np.logspace(-3, 5, nlambdas)
+# Initialize a KFold instance
+k = 5
+kfold = KFold(n_splits = k)
+estimated_mse_sklearn = np.zeros(nlambdas)
+i = 0
+for lmb in lambdas:
+ ridge = Ridge(alpha = lmb)
+ estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)
+ estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
+ i += 1
+plt.figure()
+plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
+
+
+!ec
+
-We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\bm{X}$ as
-!bt
-\[
-\bm{C}[\bm{x}] = \frac{1}{n}\bm{X}^T\bm{X}= \mathbb{E}[\bm{X}^T\bm{X}].
-\]
-!et
-To see this let us simply look at a design matrix $\bm{X}\in {\mathbb{R}}^{2\times 2}$
-!bt
-\[
-\bm{X}=\begin{bmatrix}
-x_{00} & x_{01}\\
-x_{10} & x_{11}\\
-\end{bmatrix}=\begin{bmatrix}
-\bm{x}_{0} & \bm{x}_{1}\\
-\end{bmatrix}.
-\]
-!et
-
-If we then compute the expectation value
-!bt
-\[
-\mathbb{E}[\bm{X}^T\bm{X}] = \frac{1}{n}\bm{X}^T\bm{X}=\begin{bmatrix}
-x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\
-x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\
-\end{bmatrix},
-\]
-!et
-which is just
-!bt
-\[
-\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]=\begin{bmatrix} \mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] \\
- \mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] \\
- \end{bmatrix},
-\]
-!et
-where we wrote $$\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]$$ to indicate that this the covariance of the vectors $\bm{x}$ of the design/feature matrix $\bm{X}$.
-
-It is easy to generalize this to a matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$.
-!split
-===== Linking with SVD =====