From c30998b68a2424425dd6a9e97901f227e72f0257 Mon Sep 17 00:00:00 2001 From: Morten Hjorth-Jensen Date: Mon, 13 Sep 2021 11:52:44 +0200 Subject: [PATCH] updating --- doc/BookChapters/chapter1.dlog | 45 - doc/BookChapters/chapter1.do.txt | 326 +- doc/BookChapters/chapter10.dlog | 19 - doc/BookChapters/chapter11.dlog | 29 - doc/BookChapters/chapter12.dlog | 10 - doc/BookChapters/chapter2.do.txt | 3326 +++++++++++---- doc/BookChapters/chapter3.do.txt | 3515 ++++------------ doc/BookChapters/chapter5.dlog | 30 - doc/BookChapters/chapter6.dlog | 5 - doc/BookChapters/chapter7.dlog | 12 - doc/BookChapters/chapter8.dlog | 33 - doc/BookChapters/chapter9.dlog | 4 - doc/BookChapters/linalg.dlog | 22 - doc/BookChapters/statistics.dlog | 4 - doc/LectureNotes/DataFiles/chddata.csv | 100 + doc/LectureNotes/chapter1.ipynb | 356 +- doc/LectureNotes/chapter2.ipynb | 992 +++-- doc/LectureNotes/chapter3.ipynb | 5178 +++++------------------- 18 files changed, 5355 insertions(+), 8651 deletions(-) delete mode 100644 doc/BookChapters/chapter10.dlog delete mode 100644 doc/BookChapters/chapter11.dlog delete mode 100644 doc/BookChapters/chapter12.dlog delete mode 100644 doc/BookChapters/chapter5.dlog delete mode 100644 doc/BookChapters/chapter6.dlog delete mode 100644 doc/BookChapters/chapter7.dlog delete mode 100644 doc/BookChapters/chapter8.dlog delete mode 100644 doc/BookChapters/chapter9.dlog delete mode 100644 doc/BookChapters/linalg.dlog delete mode 100644 doc/BookChapters/statistics.dlog create mode 100644 doc/LectureNotes/DataFiles/chddata.csv diff --git a/doc/BookChapters/chapter1.dlog b/doc/BookChapters/chapter1.dlog index 4f6d8fde4..aaeebdc52 100644 --- a/doc/BookChapters/chapter1.dlog +++ b/doc/BookChapters/chapter1.dlog @@ -7,48 +7,3 @@ Translating doconce text in chapter1.do.txt to ipynb Failed to remove ans_at_end environment Failed to remove sol_at_end environment output in chapter1.ipynb -Translating doconce text in chapter1.do.txt to ipynb -*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. -Failed to remove ans_at_end environment -Failed to remove sol_at_end environment -output in chapter1.ipynb -Translating doconce text in chapter1.do.txt to ipynb -*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. -Failed to remove ans_at_end environment -Failed to remove sol_at_end environment -output in chapter1.ipynb -Translating doconce text in chapter1.do.txt to ipynb -*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. -Failed to remove ans_at_end environment -Failed to remove sol_at_end environment -output in chapter1.ipynb -Translating doconce text in chapter1.do.txt to ipynb -*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. -Failed to remove ans_at_end environment -Failed to remove sol_at_end environment -output in chapter1.ipynb -Translating doconce text in chapter1.do.txt to ipynb -*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. -Failed to remove ans_at_end environment -Failed to remove sol_at_end environment -output in chapter1.ipynb diff --git a/doc/BookChapters/chapter1.do.txt b/doc/BookChapters/chapter1.do.txt index 029b8a4a0..43367c5de 100644 --- a/doc/BookChapters/chapter1.do.txt +++ b/doc/BookChapters/chapter1.do.txt @@ -230,7 +230,9 @@ How to evaluate which model fits best the data is something we will come back to ===== Simple linear regression model using _scikit-learn_ ===== -We start with perhaps our simplest possible example, using _Scikit-Learn_ to perform linear regression analysis on a data set produced by us. +We start with perhaps our simplest possible example, using +_Scikit-Learn_ to perform linear regression analysis on a data set +produced by us. What follows is a simple Python code where we have defined a function $y$ in terms of the variable $x$. Both are defined as vectors with $100$ entries. @@ -373,7 +375,8 @@ We can modify easily the above Python code and plot the relative error instead import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression - +# Number of data points +n = 100 x = np.random.rand(100,1) y = 5*x+0.01*np.random.randn(100,1) linreg = LinearRegression() @@ -391,7 +394,8 @@ plt.show() Depending on the parameter in front of the normal distribution, we may have a small or larger relative error. Try to play around with different training data sets and study (graphically) the value of the -relative error. +relative error. Note also that _Scikit-Learn_ requires a matrix as input for the input values $x$ and $y$. In the above code we have +solved this by declaring $x$ and $y$ as arrays of dimension $n\times 1$. As mentioned above, _Scikit-Learn_ has an impressive functionality. We can for example extract the values of $\alpha$ and $\beta$ and @@ -493,13 +497,14 @@ ways of dealing with outliers. The Huber cost function is defined as !bt \[ -H_{\delta}(\bm{a})=\left\{\begin{array}{cc}\frac{1}{2} \bm{a}^{2}& \text{for }|\bm{a}|\leq \delta\\ \delta (|\b\ -m{a}|-\frac{1}{2}\delta ),&\text{otherwise}.\end{array}\right. +H_{\delta}(\bm{a})=\left\{\begin{array}{cc}\frac{1}{2} \bm{a}^{2}& \text{for }|\bm{a}|\leq \delta\\ \delta (|\bm{a}|-\frac{1}{2}\delta ),&\text{otherwise}.\end{array}\right. \] !et Here $\bm{a}=\bm{y} - \bm{\tilde{y}}$. + + We will discuss in more detail these and other functions in the various lectures. We conclude this part with another example. Instead of a linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn. @@ -761,6 +766,9 @@ X[:,2] = A**(2.0/3.0) X[:,3] = A**(-1.0/3.0) X[:,4] = A**(-1.0) !ec + +Note well that we have made life simple here. We perform a fit in terms of the number of nucleons only. A more sophisticated fit can be done by including an explicit dependence on the number of protons and neutrons in the asymmetry and Coulomb terms. + With _scikitlearn_ we are now ready to use linear regression and fit our data. !bc pycod clf = skl.LinearRegression().fit(X, Energies) @@ -775,7 +783,6 @@ print("Mean squared error: %.2f" % mean_squared_error(Energies, fity)) print('Variance score: %.2f' % r2_score(Energies, fity)) # Mean absolute error print('Mean absolute error: %.2f' % mean_absolute_error(Energies, fity)) -print(clf.coef_, clf.intercept_) Masses['Eapprox'] = fity # Generate a plot comparing the experimental with the fitted values values. @@ -1874,6 +1881,93 @@ plt.show() !ec +===== Splitting our Data in Training and Test data ===== + + +It is normal in essentially all Machine Learning studies to split the +data in a training set and a test set (sometimes also an additional +validation set). _Scikit-Learn_ has an own function for this. There +is no explicit recipe for how much data should be included as training +data and say test data. An accepted rule of thumb is to use +approximately $2/3$ to $4/5$ of the data as training data. We will +postpone a discussion of this splitting to the end of these notes and +our discussion of the so-called _bias-variance_ tradeoff. Here we +limit ourselves to repeat the above equation of state fitting example +but now splitting the data into a training set and a test set. + +Let us study some examples. The first code here takes a simple +one-dimensional second-order polynomial and we fit it to a +second-order polynomial. Depending on the strength of the added noise, +the various measures like the $R2$ score or the mean-squared error, +the fit becomes better or worse. + +!bc pycod +import os +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +from sklearn.model_selection import train_test_split + + +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 + +x = np.random.rand(100) +y = 2.0+5*x*x+0.1*np.random.randn(100) + + +# The design matrix now as function of a given polynomial +X = np.zeros((len(x),3)) +X[:,0] = 1.0 +X[:,1] = x +X[:,2] = x**2 +# 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 +beta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train +print(beta) +# and then make the prediction +ytilde = X_train @ beta +print("Training R2") +print(R2(y_train,ytilde)) +print("Training MSE") +print(MSE(y_train,ytilde)) +ypredict = X_test @ beta +print("Test R2") +print(R2(y_test,ypredict)) +print("Test MSE") +print(MSE(y_test,ypredict)) +!ec + +Alternatively, you could write your own test-train splitting function as shown here. + +!bc pycod +# equivalently in numpy +def train_test_split_numpy(inputs, labels, train_size, test_size): + n_inputs = len(inputs) + inputs_shuffled = inputs.copy() + labels_shuffled = labels.copy() + + np.random.shuffle(inputs_shuffled) + np.random.shuffle(labels_shuffled) + + train_end = int(n_inputs*train_size) + X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:] + Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:] + + return X_train, X_test, Y_train, Y_test +!ec + +But since _scikit-learn_ has its own function for doing this and since +it interfaces easily with _tensorflow_ and other libraries, we +normally recommend using the latter functionality. + + + + ===== Reducing the number of degrees of freedom, overarching view ===== Many Machine Learning problems involve thousands or even millions of @@ -1897,6 +1991,7 @@ is one of the most used tools in data modeling, compression and visualization. + Before we proceed however, we will discuss how to preprocess our data. Till now and in connection with our previous examples we have not met so many cases where we are too sensitive to the scaling of our @@ -1904,6 +1999,15 @@ data. Normally the data may need a rescaling and/or may be sensitive to extreme values. Scaling the data renders our inputs much more suitable for the algorithms we want to employ. +For data sets gathered for real world applications, it is rather normal that +different features have very different units and +numerical scales. For example, a data set detailing health habits may include +features such as _age_ in the range $0-80$, and _caloric intake_ of order $2000$. +Many machine learning methods sensitive to the scales of the features and may perform poorly if they +are very different scales. Therefore, it is typical to scale +the features in a way to avoid such outlier values. + + _Scikit-Learn_ has several functions which allow us to rescale the data, normally resulting in much better results in terms of various accuracy scores. The _StandardScaler_ function in _Scikit-Learn_ @@ -1933,107 +2037,134 @@ outliers, and might often lead to trouble for other scaling techniques. -=== Simple preprocessing examples, Franke function and regression === +Many features are often scaled using standardization to improve +performance. In _Scikit-Learn_ this is given by the _StandardScaler_ +function as discussed above. It is easy however to write your own. +Mathematically, this involves subtracting the mean and divide by the +standard deviation over the data set, for each feature: + +!bt +\[ + x_j^{(i)} \rightarrow \frac{x_j^{(i)} - \overline{x}_j}{\sigma(x_j)}, +\] +!et + +where $\overline{x}_j$ and $\sigma(x_j)$ are the mean and standard +deviation, respectively, of the feature $x_j$. This ensures that each +feature has zero mean and unit standard deviation. For data sets +where we do not have the standard deviation or don't wish to calculate +it, it is then common to simply set it to one. + + + +Let us consider the following vanilla example where we use both +_Scikit-Learn_ and write our own function as well. We produce a +simple test design matrix with random numbers. Each column could then +represent a specific feature whose mean value is subracted. + !bc pycod -# Common imports -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt import sklearn.linear_model as skl from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer - -# 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') - - -def FrankeFunction(x,y): - term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) - term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) - term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) - term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) - return term1 + term2 + term3 + term4 - - -def create_X(x, y, n ): - if len(x.shape) > 1: - x = np.ravel(x) - y = np.ravel(y) - - N = len(x) - l = int((n+1)*(n+2)/2) # Number of elements in beta - X = np.ones((N,l)) - - for i in range(1,n+1): - q = int((i)*(i+1)/2) - for k in range(i+1): - X[:,q+k] = (x**(i-k))*(y**k) - - return X - - -# Making meshgrid of datapoints and compute Franke's function -n = 5 -N = 1000 -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) -# split in training and test data -X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=0.2) - - -clf = skl.LinearRegression().fit(X_train, y_train) - -# The mean squared error and R2 score -print("MSE before scaling: {:.2f}".format(mean_squared_error(clf.predict(X_test), y_test))) -print("R2 score before scaling {:.2f}".format(clf.score(X_test,y_test))) - -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) - -print("Feature min values before scaling:\n {}".format(X_train.min(axis=0))) -print("Feature max values before scaling:\n {}".format(X_train.max(axis=0))) - -print("Feature min values after scaling:\n {}".format(X_train_scaled.min(axis=0))) -print("Feature max values after scaling:\n {}".format(X_train_scaled.max(axis=0))) - -clf = skl.LinearRegression().fit(X_train_scaled, y_train) - - -print("MSE after scaling: {:.2f}".format(mean_squared_error(clf.predict(X_test_scaled), y_test))) -print("R2 score for scaled data: {:.2f}".format(clf.score(X_test_scaled,y_test))) - +import numpy as np +import pandas as pd +from IPython.display import display +np.random.seed(100) +# setting up a 10 x 5 matrix +rows = 10 +cols = 5 +X = np.random.randn(rows,cols) +XPandas = pd.DataFrame(X) +display(XPandas) +print(XPandas.mean()) +print(XPandas.std()) +XPandas = (XPandas -XPandas.mean()) +display(XPandas) +# This option does not include the standard deviation +scaler = StandardScaler(with_std=False) +scaler.fit(X) +Xscaled = scaler.transform(X) +display(XPandas-Xscaled) !ec +Small exercise: perform the standard scaling by including the standard deviation and compare with what Scikit-Learn gives. +Another commonly used scaling method is min-max scaling. This is very +useful for when we want the features to lie in a certain interval. To +scale the feature $x_j$ to the interval $[a, b]$, we can apply the +transformation + +!bt +\[ +x_j^{(i)} \rightarrow (b-a)\frac{x_j^{(i)} - \min(x_j)}{\max(x_j) - \min(x_j)} - a +\] +!et +where $\min(x_j)$ and $\max(x_j)$ return the minimum and maximum value of $x_j$ over the data set, respectively. + + + + +===== Testing the Means Squared Error as function of Complexity ===== + + +Before we proceed with a more detailed analysis of the so-called +Bias-Variance tradeoff, we present here an example of the relation +between model complexity and the mean squared error for the triaining +data and the test data. + +The results here tell us clearly that for the data not included in the +training, there is an optimal model as function of the complexity of +ourmodel (here in terms of the polynomial degree of the model). + +The results here will vary as function of model complexity and the amount od data used for training. + + +Our data is defined by $x\in [-3,3]$ with a total of for example $100$ data points. + +!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 + + +np.random.seed(2018) +n = 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) +TestError = np.zeros(maxdegree) +TrainError = np.zeros(maxdegree) +polydegree = np.zeros(maxdegree) +x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) +scaler = StandardScaler() +scaler.fit(x_train) +x_train_scaled = scaler.transform(x_train) +x_test_scaled = scaler.transform(x_test) + +for degree in range(maxdegree): + model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) + clf = model.fit(x_train_scaled,y_train) + y_fit = clf.predict(x_train_scaled) + y_pred = clf.predict(x_test_scaled) + polydegree[degree] = degree + TestError[degree] = np.mean( np.mean((y_test - y_pred)**2) ) + TrainError[degree] = np.mean( np.mean((y_train - y_fit)**2) ) + +plt.plot(polydegree, TestError, label='Test Error') +plt.plot(polydegree, TrainError, label='Train Error') +plt.legend() +plt.show() +!ec + + @@ -2235,3 +2366,6 @@ your results. For which polynomial degree do you find an optimal MSE + + + diff --git a/doc/BookChapters/chapter10.dlog b/doc/BookChapters/chapter10.dlog deleted file mode 100644 index f0cd1b812..000000000 --- a/doc/BookChapters/chapter10.dlog +++ /dev/null @@ -1,19 +0,0 @@ -*** error: file has a mako construction ${0:.1f}' - but seemingly no definition in <%...%>' - (it is not a command-line given mako variable either). - However, if this is a variable in a Makefile or Bash script - run with --no_mako - and you cannot use mako and Makefile or Bash variables - in the same document! - -*** error: file has a mako construction ${0:.1f}' - but seemingly no definition in <%...%>' - (it is not a command-line given mako variable either). - However, if this is a variable in a Makefile or Bash script - run with --no_mako - and you cannot use mako and Makefile or Bash variables - in the same document! - -avoided abortion because of --no-abort -Translating doconce text in chapter10.do.txt to ipynb -Failed to remove ans_at_end environment -Failed to remove sol_at_end environment -output in chapter10.ipynb diff --git a/doc/BookChapters/chapter11.dlog b/doc/BookChapters/chapter11.dlog deleted file mode 100644 index 05b99d6dc..000000000 --- a/doc/BookChapters/chapter11.dlog +++ /dev/null @@ -1,29 +0,0 @@ -Translating doconce text in chapter11.do.txt to ipynb -*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) - -*** warning: latex envir \begin{aligned} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{aligned} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{aligned} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{pmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{aligned} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{aligned} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{aligned} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{aligned} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{aligned} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{aligned} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{aligned} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{aligned} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. -Failed to remove ans_at_end environment -Failed to remove sol_at_end environment -output in chapter11.ipynb diff --git a/doc/BookChapters/chapter12.dlog b/doc/BookChapters/chapter12.dlog deleted file mode 100644 index d0a5de96d..000000000 --- a/doc/BookChapters/chapter12.dlog +++ /dev/null @@ -1,10 +0,0 @@ -Translating doconce text in chapter12.do.txt to ipynb -*** error: figure file "figslides/nn.jpeg" does not exist! -Translating doconce text in chapter12.do.txt to ipynb -Failed to remove ans_at_end environment -Failed to remove sol_at_end environment -output in chapter12.ipynb -Translating doconce text in chapter12.do.txt to ipynb -Failed to remove ans_at_end environment -Failed to remove sol_at_end environment -output in chapter12.ipynb diff --git a/doc/BookChapters/chapter2.do.txt b/doc/BookChapters/chapter2.do.txt index 16031ac61..dcb02629f 100644 --- a/doc/BookChapters/chapter2.do.txt +++ b/doc/BookChapters/chapter2.do.txt @@ -1,55 +1,2074 @@ -======= Resampling Methods ======= - -===== Introduction ===== - -Resampling methods are an indispensable tool in modern -statistics. They involve repeatedly drawing samples from a training -set and refitting a model of interest on each sample in order to -obtain additional information about the fitted model. For example, in -order to estimate the variability of a linear regression fit, we can -repeatedly draw different samples from the training data, fit a linear -regression to each new sample, and then examine the extent to which -the resulting fits differ. Such an approach may allow us to obtain -information that would not be available from fitting the model only -once using the original training sample. - -Two resampling methods are often used in Machine Learning analyses, -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. +======= Ridge and Lasso Regression ======= -Resampling approaches can be computationally expensive, because they -involve fitting the same statistical method multiple times using -different subsets of the training data. However, due to recent -advances in computing power, the computational requirements of -resampling methods generally are not prohibitive. In this chapter, we -discuss two of the most commonly used resampling methods, -cross-validation and the bootstrap. Both methods are important tools -in the practical application of many statistical learning -procedures. For example, cross-validation can be used to estimate the -test error associated with a given statistical learning method in -order to evaluate its performance, or to select the appropriate level -of flexibility. The process of evaluating a model’s performance is -known as model assessment, whereas the process of selecting the proper -level of flexibility for a model is known as model selection. The -bootstrap is widely used. +===== Mathematical Interpretation of Ordinary Least Squares ===== + +What is presented here is a mathematical analysis of various regression algorithms (ordinary least squares, Ridge and Lasso Regression). The analysis is based on an important algorithm in linear algebra, the so-called Singular Value Decomposition (SVD). + + +We have shown that in ordinary least squares the optimal parameters $\beta$ are given by + +!bt +\[ +\hat{\bm{\beta}} = \left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. +\] +!et + +The _hat_ over $\bm{\beta}$ means we have the optimal parameters after minimization of the cost function. + +This means that our best model is defined as + +!bt +\[ +\tilde{\bm{y}}=\bm{X}\hat{\bm{\beta}} = \bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. +\] +!et + +We now define a matrix +!bt +\[ +\bm{A}=\bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T. +\] +!et + +We can rewrite +!bt +\[ +\tilde{\bm{y}}=\bm{X}\hat{\bm{\beta}} = \bm{A}\bm{y}. +\] +!et + +The matrix $\bm{A}$ has the important property that $\bm{A}^2=\bm{A}$. This is the definition of a projection matrix. +We can then interpret our optimal model $\tilde{\bm{y}}$ as being represented by an orthogonal projection of $\bm{y}$ onto a space defined by the column vectors of $\bm{X}$. In our case here the matrix $\bm{A}$ is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix. + + + + +We have defined the residual error as +!bt +\[ +\bm{\epsilon}=\bm{y}-\tilde{\bm{y}}=\left[\bm{I}-\bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\right]\bm{y}. +\] +!et + +The residual errors are then the projections of $\bm{y}$ onto the orthogonal component of the space defined by the column vectors of $\bm{X}$. + + +If the matrix $\bm{X}$ is an orthogonal (or unitary in case of complex values) matrix, we have + +!bt +\[ +\bm{X}^T\bm{X}=\bm{X}\bm{X}^T = \bm{I}. +\] +!et + +In this case the matrix $\bm{A}$ becomes +!bt +\[ +\bm{A}=\bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T)=\bm{I}, +\] +!et +and we have the obvious case +!bt +\[ +\bm{\epsilon}=\bm{y}-\tilde{\bm{y}}=0. +\] +!et + +This serves also as a useful test of our codes. + + + + +===== The singular value decomposition ===== + + +The examples we have looked at so far are cases where we normally can +invert the matrix $\bm{X}^T\bm{X}$. Using a polynomial expansion where we fit of various functions leads to +row vectors of the design matrix which are essentially orthogonal due +to the polynomial character of our model. Obtaining the inverse of the +design matrix is then often done via a so-called LU, QR or Cholesky +decomposition. + + +As we will also see in the first project, +this may +however not the be case in general and a standard matrix inversion +algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below. + +There is however a way to circumvent this problem and also +gain some insights about the ordinary least squares approach, and +later shrinkage methods like Ridge and Lasso regressions. + +This is given by the _Singular Value Decomposition_ (SVD) algorithm, +perhaps the most powerful linear algebra algorithm. The SVD provides +a numerically stable matrix decomposition that is used in a large +swath oc applications and the decomposition is always stable +numerically. + +In machine learning it plays a central role in dealing with for +example design matrices that may be near singular or singular. +Furthermore, as we will see here, the singular values can be related +to the covariance matrix (and thereby the correlation matrix) and in +turn the variance of a given quantity. It plays also an important role +in the principal component analysis where high-dimensional data can be +reduced to the statistically relevant features. + + + + +One of the typical problems we encounter with linear regression, in particular +when the matrix $\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. + + + +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. + + + + +===== Basic math of the SVD ===== + + +From standard linear algebra we know that a square matrix $\bm{X}$ can be diagonalized if and only it is +a so-called "normal matrix":"https://en.wikipedia.org/wiki/Normal_matrix", that is if $\bm{X}\in {\mathbb{R}}^{n\times n}$ +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. + + + + + +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 + +!bt +\[ +\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T +\] +!et + +As an example, the above defective matrix can be decomposed as + +!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, +\] +!et + +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 $\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. + + +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 ===== + +!bc pycod +import numpy as np +# SVD inversion +def SVD(A): + ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD). + SVD is numerically more stable than the inversion algorithms provided by + numpy and scipy.linalg at the cost of being slower. + ''' + U, S, VT = np.linalg.svd(A,full_matrices=True) + print('test U') + print( (np.transpose(U) @ U - U @np.transpose(U))) + print('test VT') + print( (np.transpose(VT) @ VT - VT @np.transpose(VT))) + print(U) + print(S) + print(VT) + + D = np.zeros((len(U),len(VT))) + for i in range(0,len(VT)): + D[i,i]=S[i] + return U @ D @ VT + + +X = np.array([ [1.0,-1.0], [1.0,-1.0]]) +#X = np.array([[1, 2], [3, 4], [5, 6]]) + +print(X) +C = SVD(X) +# Print the difference between the original matrix and the SVD one +print(C-X) +!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. + + + +The $U$, $S$, and $V$ matrices returned from the _svd()_ function +cannot be multiplied directly. + +As you can see from the code, the $S$ vector must be converted into a +diagonal matrix. This may cause a problem as the size of the matrices +do not fit the rules of matrix multiplication, where the number of +columns in a matrix must match the number of rows in the subsequent +matrix. + +If you wish to include the zero singular values, you will need to +resize the matrices and set up a diagonal matrix as done in the above +example + + +===== Code for SVD and Inversion of Matrices ===== + +How do we use the SVD to invert a matrix $\bm{X}^\bm{X}$ which is singular or near singular? +The simple answer is to use the linear algebra function for the pseudoinverse, that is +!bc pycod +#Ainv = np.linlag.pinv(A) +!ec + +Let us first look at a matrix which does not causes problems and write our own function where we just use the SVD. + +!bc pycod +import numpy as np +# SVD inversion +def SVDinv(A): + ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD). + SVD is numerically more stable than the inversion algorithms provided by + numpy and scipy.linalg at the cost of being slower. + ''' + U, s, VT = np.linalg.svd(A) + print('test U') + print( (np.transpose(U) @ U - U @np.transpose(U))) + print('test VT') + print( (np.transpose(VT) @ VT - VT @np.transpose(VT))) + + + D = np.zeros((len(U),len(VT))) + D = np.diag(s) + UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D) + return np.matmul(V,np.matmul(invD,UT)) + + +#X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ]) +# Non-singular square matrix +X = np.array( [ [1,2,3],[2,4,5],[3,5,6]]) +print(X) +A = np.transpose(X) @ X +# Brute force inversion +B = np.linalg.pinv(A) # here we could use np.linalg.inv(A), try it! +C = SVDinv(A) +print(np.abs(B-C)) + +!ec + + +Although our matrix to invert $\bm{X}^T\bm{X}$ is a square matrix, our matrix may be singular. + +The pseudoinverse is the generalization of the matrix inverse for square matrices to +rectangular matrices where the number of rows and columns are not equal. + +It is also called the the Moore-Penrose Inverse after two independent discoverers of the method or the Generalized Inverse. +It is used for the calculation of the inverse for singular or near singular matrices and for rectangular matrices. + +Using the SVD we can obtain the pseudoinverse of a matrix $\bm{A}$ (labeled here as $\bm{A}_{\mathrm{PI}}$ +!bt +\[ +\bm{A}_{\mathrm{PI}}= \bm{V}\bm{D}_{\mathrm{PI}}\bm{U}^T, +\] +!et +where $\bm{D}_{\mathrm{PI}}$ can be calculated by creating a diagonal matrix from $\bm{Sigma}$ where we only keep the singular values (the non-zero values). The following code computes the pseudoinvers of the matrix based on the SVD. + + +!bc pycod +import numpy as np +# SVD inversion +def SVDinv(A): + U, s, VT = np.linalg.svd(A) + # reciprocals of singular values of s + d = 1.0 / s + # create m x n D matrix + D = np.zeros(A.shape) + # populate D with n x n diagonal matrix + D[:A.shape[1], :A.shape[1]] = np.diag(d) + UT = np.transpose(U) + V = np.transpose(VT) + return np.matmul(V,np.matmul(D.T,UT)) + + +A = np.array([ [0.3, 0.4], [0.5, 0.6], [0.7, 0.8],[0.9, 1.0]]) +print(A) +# Brute force inversion of super-collinear matrix +B = np.linalg.pinv(A) +print(B) +# Compare our own algorithm with pinv +C = SVDinv(A) +print(np.abs(C-B)) + +!ec +As you can see from these examples, our own decomposition based on the SVD agrees the pseudoinverse algorithm provided by _Numpy_. + + + + + +===== Mathematics of the SVD and implications ===== + +Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies. + +Our starting point is our design matrix $\bm{X}$ of dimension $n\times p$ +!bt +\[ +\bm{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 + +We can SVD decompose our matrix as +!bt +\[ +\bm{X}=\bm{U}\bm{\Sigma}\bm{V}^T, +\] +!et +where $\bm{U}$ is an orthogonal matrix of dimension $n\times n$, meaning that $\bm{U}\bm{U}^T=\bm{U}^T\bm{U}=\bm{I}_n$. Here $\bm{I}_n$ is the unit matrix of dimension $n \times n$. + +Similarly, $\bm{V}$ is an orthogonal matrix of dimension $p\times p$, meaning that $\bm{V}\bm{V}^T=\bm{V}^T\bm{V}=\bm{I}_p$. Here $\bm{I}_n$ is the unit matrix of dimension $p \times p$. + +Finally $\bm{\Sigma}$ contains the singular values $\sigma_i$. This matrix has dimension $n\times p$ and the singular values $\sigma_i$ are all positive. The non-zero values are ordered in descending order, that is + +!bt +\[ +\sigma_0 > \sigma_1 > \sigma_2 > \dots > \sigma_{p-1} > 0. +\] +!et + +All values beyond $p-1$ are all zero. + + +As an example, consider the following $3\times 2$ example for the matrix $\bm{\Sigma}$ + +!bt +\[ +\bm{\Sigma}= +\begin{bmatrix} +2& 0 \\ +0 & 1 \\ +0 & 0 \\ +\end{bmatrix} +\] +!et + +The singular values are $\sigma_0=2$ and $\sigma_1=1$. It is common to rewrite the matrix $\bm{\Sigma}$ as + +!bt +\[ +\bm{\Sigma}= +\begin{bmatrix} +\bm{\tilde{\Sigma}}\\ +\bm{0}\\ +\end{bmatrix}, +\] +!et + +where +!bt +\[ +\bm{\tilde{\Sigma}}= +\begin{bmatrix} +2& 0 \\ +0 & 1 \\ +\end{bmatrix}, +\] +!et +contains only the singular values. Note also (and we will use this below) that + +!bt +\[ +\bm{\Sigma}^T\bm{\Sigma}= +\begin{bmatrix} +4& 0 \\ +0 & 1 \\ +\end{bmatrix}, +\] +!et +which is a $2\times 2 $ matrix while +!bt +\[ +\bm{\Sigma}\bm{\Sigma}^T= +\begin{bmatrix} +4& 0 & 0\\ +0 & 1 & 0\\ +0 & 0 & 0\\ +\end{bmatrix}, +\] +!et + +is a $3\times 3 $ matrix. The last row and column of this last matrix +contain only zeros. This will have important consequences for our SVD +decomposition of the design matrix. + + + +The matrix that may cause problems for us is $\bm{X}^T\bm{X}$. Using the SVD we can rewrite this matrix as + +!bt +\[ +\bm{X}^T\bm{X}=\bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T, +\] +!et +and using the orthogonality of the matrix $\bm{U}$ we have + +!bt +\[ +\bm{X}^T\bm{X}=\bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T. +\] +!et +We define $\bm{\Sigma}^T\bm{\Sigma}=\tilde{\bm{\Sigma}}^2$ which is a diagonal matrix containing only the singular values squared. It has dimensionality $p \times p$. + +This means, using the orthogonality of $\bm{V}$, that we get + +!bt +\[ +\bm{X}^T\bm{X}=\tilde{\bm{\Sigma}}^2. +\] +!et + +We can now insert the result for the matrix $\bm{X}^T\bm{X}$ into our equation for ordinary least squares where + +!bt +\[ +\tilde{y}_{\mathrm{OLS}}=\bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}, +\] +!et +and using our SVD decomposition of $\bm{X}$ we have + +!bt +\[ +\tilde{y}_{\mathrm{OLS}}=\bm{U}\bm{\Sigma}\bm{V}^T\tilde{\bm{\Sigma}}^{-2}\bm{V}\bm{\Sigma}^T\bm{U}^T\bm{y}, +\] +!et +which gives us, using the orthogonality of the matrices $\bm{U}$ and $\bm{V}$, + +!bt +\[ +\tilde{y}_{\mathrm{OLS}}=\bm{U}\bm{U}^T\bm{y}=\sum_{i=0}^{p-1}\bm{u}_i\bm{u}^T_j\bm{y}, +\] +!et + +Note here that when we perform the multiplication of the various matrices, the orthogonal vectors of the matrix $\bm{U}$ +!bt +\[ +\bm{U}=[\bm{u}_0,\bm{u}_1,\dots,\bm{u}_{n-1}], +\] +!et +that belong to $i>p-1$, result in only zeros when we perform the multiplications. This means that the sum above has non-zero elements only up to $i=p-1$. This corresponds also to the number of singular values (these are all non-zero). + +It means that the ordinary least square model (with the optimal parameters) $\bm{\tilde{y}}$, corresponds to an orthogonal transformation of the output (or target) vector $\bm{y}$ by the vectors of the matrix $\bm{U}$. + + +===== Further properties (important for our analyses later) ===== + +Let us study again $\bm{X}^T\bm{X}$ in terms of our SVD, +!bt +\[ +\bm{X}^T\bm{X}=\bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T=\bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T. +\] +!et + +If we now multiply from the right with $\bm{V}$ (using the orthogonality of $\bm{V}$) we get +!bt +\[ +\left(\bm{X}^T\bm{X}\right)\bm{V}=\bm{V}\bm{\Sigma}^T\bm{\Sigma}. +\] +!et +This means the vectors $\bm{v}_i$ of the orthogonal matrix $\bm{V}$ are the eigenvectors of the matrix $\bm{X}^T\bm{X}$ +with eigenvalues given by the singular values squared, that is +!bt +\[ +\left(\bm{X}^T\bm{X}\right)\bm{v}_i=\bm{v}_i\sigma_i^2. +\] +!et + +Similarly, if we use the SVD decomposition for the matrix $\bm{X}\bm{X}^T$, we have +!bt +\[ +\bm{X}\bm{X}^T=\bm{U}\bm{\Sigma}\bm{V}^T\bm{V}\bm{\Sigma}^T\bm{U}^T=\bm{U}\bm{\Sigma}\bm{\Sigma}^T\bm{U}^T. +\] +!et + +If we now multiply from the right with $\bm{U}$ (using the orthogonality of $\bm{U}$) we get +!bt +\[ +\left(\bm{X}\bm{X}^T\right)\bm{U}=\bm{U}\bm{\Sigma}\bm{\Sigma}^T. +\] +!et +This means the vectors $\bm{u}_i$ of the orthogonal matrix $\bm{U}$ are the eigenvectors of the matrix $\bm{X}\bm{X}^T$ +with eigenvalues given by the singular values squared, that is +!bt +\[ +\left(\bm{X}\bm{X}^T\right)\bm{u}_i=\bm{u}_i\sigma_i^2. +\] +!et + +_Important note_: we have defined our design matrix $\bm{X}$ to be an +$n\times p$ matrix. In most supervised learning cases we have that $n +\ge p$, and quite often we have $n >> p$. For linear algebra based methods like ordinary least squares or Ridge regression, this leads to a matrix $\bm{X}^T\bm{X}$ which is small and thereby easier to handle from a computational point of view (in terms of number of floating point operations). + +In our lectures, the number of columns will +always refer to the number of features in our data set, while the +number of rows represents the number of data inputs. Note that in +other texts you may find the opposite notation. This has consequences +for the definition of for example the covariance matrix and its relation to the SVD. + + +===== Meet the Covariance Matrix ===== + + +Before we move on to a discussion of Ridge and Lasso regression, we want to show an important example of the above. + +We have already noted that the matrix $\bm{X}^T\bm{X}$ in ordinary +least squares is proportional to the second derivative of the cost +function, that is we have + +!bt +\[ +\frac{\partial^2 C(\bm{\beta})}{\partial \bm{\beta}^T\partial \bm{\beta}} =\frac{2}{n}\bm{X}^T\bm{X}. +\] +!et +This quantity defines was what is called the Hessian matrix (the second derivative of a function we want to optimize). + +The Hessian matrix plays an important role and is defined in this course as + +!bt +\[ +\bm{H}=\bm{X}^T\bm{X}. +\] +!et + + +The Hessian matrix for ordinary least squares is also proportional to +the covariance matrix. This means also that we can use the SVD to find +the eigenvalues of the covariance matrix and the Hessian matrix in +terms of the singular values. Let us develop these arguments, as they will play an important role in our machine learning studies. + + + +Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about +the definition of the covariance and the correlation function. These are quantities that play a central role in machine learning methods. + +Suppose we have defined two vectors +$\hat{x}$ and $\hat{y}$ with $n$ elements each. The covariance matrix $\bm{C}$ is defined as +!bt +\[ +\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{cov}[\bm{x},\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\ + \mathrm{cov}[\bm{y},\bm{x}] & \mathrm{cov}[\bm{y},\bm{y}] \\ + \end{bmatrix}, +\] +!et +where for example +!bt +\[ +\mathrm{cov}[\bm{x},\bm{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). +\] +!et +With this definition and recalling that the variance is defined as +!bt +\[ +\mathrm{var}[\bm{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, +\] +!et +we can rewrite the covariance matrix as +!bt +\[ +\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{var}[\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\ + \mathrm{cov}[\bm{x},\bm{y}] & \mathrm{var}[\bm{y}] \\ + \end{bmatrix}. +\] +!et + +_Note:_ we have used $1/n$ in the above definitions of the *sample* variance and covariance. We assume then that we can calculate the exact mean value. +What you will find in essentially all statistics texts are equations +with a factor $1/(n-1)$. This is called "Bessel's correction":"https://mathworld.wolfram.com/BesselsCorrection.html". This +method corrects the bias in the estimation of the population variance +and covariance. It also partially corrects the bias in the estimation +of the population standard deviation. If you use a library like +_Scikit-Learn_ or _nunmpy's_ function calculate the covariance, this +quantity will be computed with a factor $1/(n-1)$. + + +The covariance takes values between zero and infinity and may thus +lead to problems with loss of numerical precision for particularly +large values. It is common to scale the covariance matrix by +introducing instead the correlation matrix defined via the so-called +correlation function + +!bt +\[ +\mathrm{corr}[\bm{x},\bm{y}]=\frac{\mathrm{cov}[\bm{x},\bm{y}]}{\sqrt{\mathrm{var}[\bm{x}] \mathrm{var}[\bm{y}]}}. +\] +!et + +The correlation function is then given by values $\mathrm{corr}[\bm{x},\bm{y}] +\in [-1,1]$. This avoids eventual problems with too large values. We +can then define the correlation matrix for the two vectors $\bm{x}$ +and $\bm{y}$ as + +!bt +\[ +\bm{K}[\bm{x},\bm{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\bm{x},\bm{y}] \\ + \mathrm{corr}[\bm{y},\bm{x}] & 1 \\ + \end{bmatrix}, +\] +!et + +In the above example this is the function we constructed using _pandas_. + + + +In our derivation of the various regression algorithms like _Ordinary Least Squares_ or _Ridge regression_ +we defined the design/feature matrix $\bm{X}$ as + +!bt +\[ +\bm{X}=\begin{bmatrix} +x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ +x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ +x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ +\dots & \dots & \dots & \dots \dots & \dots \\ +x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ +x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ +\end{bmatrix}, +\] +!et +with $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors/features $p$ refering to the column numbers and the +entries $n$ being the row elements. +We can rewrite the design/feature matrix in terms of its column vectors as +!bt +\[ +\bm{X}=\begin{bmatrix} \bm{x}_0 & \bm{x}_1 & \bm{x}_2 & \dots & \dots & \bm{x}_{p-1}\end{bmatrix}, +\] +!et +with a given vector +!bt +\[ +\bm{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. +\] +!et + +With these definitions, we can now rewrite our $2\times 2$ +correlation/covariance matrix in terms of a moe general design/feature +matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$. This leads to a $p\times p$ +covariance matrix for the vectors $\bm{x}_i$ with $i=0,1,\dots,p-1$ + +!bt +\[ +\bm{C}[\bm{x}] = \begin{bmatrix} +\mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] & \mathrm{cov}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_0,\bm{x}_{p-1}]\\ +\mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] & \mathrm{cov}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_1,\bm{x}_{p-1}]\\ +\mathrm{cov}[\bm{x}_2,\bm{x}_0] & \mathrm{cov}[\bm{x}_2,\bm{x}_1] & \mathrm{var}[\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_2,\bm{x}_{p-1}]\\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\mathrm{cov}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & \mathrm{var}[\bm{x}_{p-1}]\\ +\end{bmatrix}, +\] +!et +and the correlation matrix +!bt +\[ +\bm{K}[\bm{x}] = \begin{bmatrix} +1 & \mathrm{corr}[\bm{x}_0,\bm{x}_1] & \mathrm{corr}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_0,\bm{x}_{p-1}]\\ +\mathrm{corr}[\bm{x}_1,\bm{x}_0] & 1 & \mathrm{corr}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_1,\bm{x}_{p-1}]\\ +\mathrm{corr}[\bm{x}_2,\bm{x}_0] & \mathrm{corr}[\bm{x}_2,\bm{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\bm{x}_2,\bm{x}_{p-1}]\\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\mathrm{corr}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & 1\\ +\end{bmatrix}, +\] +!et + + + +The Numpy function _np.cov_ calculates the covariance elements using +the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have +the exact mean values. The following simple function uses the +_np.vstack_ function which takes each vector of dimension $1\times n$ +and produces a $2\times n$ matrix $\bm{W}$ + +Note that this assumes you have the features as the rows, and the inputs as columns, that is +!bt +\[ +\bm{W} = \begin{bmatrix} x_0 & x_1 & x_2 & \dots & x_{n-2} & x_{n-1} \\ + y_0 & y_1 & y_2 & \dots & y_{n-2} & y_{n-1} \\ + \end{bmatrix}, +\] +!et + +which in turn is converted into into the $2\times 2$ covariance matrix +$\bm{C}$ via the Numpy function _np.cov()_. We note that we can also calculate +the mean value of each set of samples $\bm{x}$ etc using the Numpy +function _np.mean(x)_. We can also extract the eigenvalues of the +covariance matrix through the _np.linalg.eig()_ function. + +!bc pycod +# Importing various packages +import numpy as np +n = 100 +x = np.random.normal(size=n) +print(np.mean(x)) +y = 4+3*x+np.random.normal(size=n) +print(np.mean(y)) +W = np.vstack((x, y)) +C = np.cov(W) +print(C) +!ec + + + +The previous example can be converted into the correlation matrix by +simply scaling the matrix elements with the variances. We should also +subtract the mean values for each column. This leads to the following +code which sets up the correlations matrix for the previous example in +a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\times 2$ correlation matrix (since we have only two vectors). + +!bc pycod +import numpy as np +n = 100 +# define two vectors +x = np.random.random(size=n) +y = 4+3*x+np.random.normal(size=n) +#scaling the x and y vectors +x = x - np.mean(x) +y = y - np.mean(y) +variance_x = np.sum(x@x)/n +variance_y = np.sum(y@y)/n +print(variance_x) +print(variance_y) +cov_xy = np.sum(x@y)/n +cov_xx = np.sum(x@x)/n +cov_yy = np.sum(y@y)/n +C = np.zeros((2,2)) +C[0,0]= cov_xx/variance_x +C[1,1]= cov_yy/variance_y +C[0,1]= cov_xy/np.sqrt(variance_y*variance_x) +C[1,0]= C[0,1] +print(C) +!ec + +We see that the matrix elements along the diagonal are one as they +should be and that the matrix is symmetric. Furthermore, diagonalizing +this matrix we easily see that it is a positive definite matrix. + +The above procedure with _numpy_ can be made more compact if we use _pandas_. + + + +We whow here how we can set up the correlation matrix using _pandas_, as done in this simple code +!bc pycod +import numpy as np +import pandas as pd +n = 10 +x = np.random.normal(size=n) +x = x - np.mean(x) +y = 4+3*x+np.random.normal(size=n) +y = y - np.mean(y) +# Note that we transpose the matrix in order to stay with our ordering n x p +X = (np.vstack((x, y))).T +print(X) +Xpd = pd.DataFrame(X) +print(Xpd) +correlation_matrix = Xpd.corr() +print(correlation_matrix) +!ec + + +We expand this model to the Franke function discussed earlier. + + +!bc pycod +# Common imports +import numpy as np +import pandas as pd + + +def FrankeFunction(x,y): + term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) + term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) + term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) + term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) + return term1 + term2 + term3 + term4 + + +def create_X(x, y, n ): + if len(x.shape) > 1: + x = np.ravel(x) + y = np.ravel(y) + + N = len(x) + l = int((n+1)*(n+2)/2) # Number of elements in beta + X = np.ones((N,l)) + + for i in range(1,n+1): + q = int((i)*(i+1)/2) + for k in range(i+1): + X[:,q+k] = (x**(i-k))*(y**k) + + return X + + +# Making meshgrid of datapoints and compute Franke's function +n = 4 +N = 100 +x = np.sort(np.random.uniform(0, 1, N)) +y = np.sort(np.random.uniform(0, 1, N)) +z = FrankeFunction(x, y) +X = create_X(x, y, n=n) + +Xpd = pd.DataFrame(X) +# subtract the mean values and set up the covariance matrix +Xpd = Xpd - Xpd.mean() +covariance_matrix = Xpd.cov() +print(covariance_matrix) +!ec + +We note here that the covariance is zero for the first rows and +columns since all matrix elements in the design matrix were set to one +(we are fitting the function in terms of a polynomial of degree $n$). + +This means that the variance for these elements will be zero and will +cause problems when we set up the correlation matrix. We can simply +drop these elements and construct a correlation +matrix without these elements. + + + +We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\bm{X}$ as +!bt +\[ +\bm{C}[\bm{x}] = \frac{1}{n}\bm{X}^T\bm{X}= \mathbb{E}[\bm{X}^T\bm{X}]. +\] +!et + +To see this let us simply look at a design matrix $\bm{X}\in {\mathbb{R}}^{2\times 2}$ +!bt +\[ +\bm{X}=\begin{bmatrix} +x_{00} & x_{01}\\ +x_{10} & x_{11}\\ +\end{bmatrix}=\begin{bmatrix} +\bm{x}_{0} & \bm{x}_{1}\\ +\end{bmatrix}. +\] +!et + +If we then compute the expectation value (note the $1/n$ factor instead of $1/(n-1)$) +!bt +\[ +\mathbb{E}[\bm{X}^T\bm{X}] = \frac{1}{n}\bm{X}^T\bm{X}=\frac{1}{n}\begin{bmatrix} +x_{00}^2+x_{10}^2 & x_{00}x_{01}+x_{10}x_{11}\\ +x_{01}x_{00}+x_{11}x_{10} & x_{01}^2+x_{11}^2\\ +\end{bmatrix}, +\] +!et +which is just +!bt +\[ +\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]=\begin{bmatrix} \mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] \\ + \mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] \\ + \end{bmatrix}, +\] +!et +where we wrote $$\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]$$ to indicate that this is the covariance of the vectors $\bm{x}$ of the design/feature matrix $\bm{X}$. + +It is easy to generalize this to a matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$. + + + +===== Linking with the SVD ===== + +We saw earlier that +!bt +\[ +\bm{X}^T\bm{X}=\bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T=\bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T. +\] +!et +Since the matrices here have dimension $p\times p$, with $p$ corresponding to the singular values, we defined earlier the matrix +!bt +\[ +\bm{\Sigma}^T\bm{\Sigma} = \begin{bmatrix} \tilde{\bm{\Sigma}} & \bm{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\bm{\Sigma}} \\ \bm{0}\\ \end{bmatrix}, +\] +!et +where the tilde-matrix $\tilde{\bm{\Sigma}}$ is a matrix of dimension $p\times p$ containing only the singular values $\sigma_i$, that is + +!bt +\[ +\tilde{\bm{\Sigma}}=\begin{bmatrix} \sigma_0 & 0 & 0 & \dots & 0 & 0 \\ + 0 & \sigma_1 & 0 & \dots & 0 & 0 \\ + 0 & 0 & \sigma_2 & \dots & 0 & 0 \\ + 0 & 0 & 0 & \dots & \sigma_{p-2} & 0 \\ + 0 & 0 & 0 & \dots & 0 & \sigma_{p-1} \\ +\end{bmatrix}, +\] +!et +meaning we can write +!bt +\[ +\bm{X}^T\bm{X}=\bm{V}\tilde{\bm{\Sigma}}^2\bm{V}^T. +\] +!et +Multiplying from the right with $\bm{V}$ (using the orthogonality of $\bm{V}$) we get +!bt +\[ +\left(\bm{X}^T\bm{X}\right)\bm{V}=\bm{V}\tilde{\bm{\Sigma}}^2. +\] +!et + + +This means the vectors $\bm{v}_i$ of the orthogonal matrix $\bm{V}$ +are the eigenvectors of the matrix $\bm{X}^T\bm{X}$ with eigenvalues +given by the singular values squared, that is + +!bt +\[ +\left(\bm{X}^T\bm{X}\right)\bm{v}_i=\bm{v}_i\sigma_i^2. +\] +!et + +In other words, each non-zero singular value of $\bm{X}$ is a positive +square root of an eigenvalue of $\bm{X}^T\bm{X}$. It means also that +the columns of $\bm{V}$ are the eigenvectors of +$\bm{X}^T\bm{X}$. Since we have ordered the singular values of +$\bm{X}$ in a descending order, it means that the column vectors +$\bm{v}_i$ are hierarchically ordered by how much correlation they +encode from the columns of $\bm{X}$. + + +Note that these are also the eigenvectors and eigenvalues of the +Hessian matrix. + +If we now recall the definition of the covariance matrix (not using +Bessel's correction) we have + + +!bt +\[ +\bm{C}[\bm{X}]=\frac{1}{n}\bm{X}^T\bm{X}, +\] +!et + +meaning that every squared non-singular value of $\bm{X}$ divided by $n$ ( +the number of samples) are the eigenvalues of the covariance +matrix. Every singular value of $\bm{X}$ is thus a positive square +root of an eigenvalue of $\bm{X}^T\bm{X}$. If the matrix $\bm{X}$ is +self-adjoint, the singular values of $\bm{X}$ are equal to the +absolute value of the eigenvalues of $\bm{X}$. + + +For $\bm{X}\bm{X}^T$ we found + +!bt +\[ +\bm{X}\bm{X}^T=\bm{U}\bm{\Sigma}\bm{V}^T\bm{V}\bm{\Sigma}^T\bm{U}^T=\bm{U}\bm{\Sigma}^T\bm{\Sigma}\bm{U}^T. +\] +!et +Since the matrices here have dimension $n\times n$, we have +!bt +\[ +\bm{\Sigma}\bm{\Sigma}^T = \begin{bmatrix} \tilde{\bm{\Sigma}} \\ \bm{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\bm{\Sigma}} \bm{0}\\ \end{bmatrix}=\begin{bmatrix} \tilde{\bm{\Sigma}} & \bm{0} \\ \bm{0} & \bm{0}\\ \end{bmatrix}, +\] +!et +leading to +!bt +\[ +\bm{X}\bm{X}^T=\bm{U}\begin{bmatrix} \tilde{\bm{\Sigma}} & \bm{0} \\ \bm{0} & \bm{0}\\ \end{bmatrix}\bm{U}^T. +\] +!et + +Multiplying with $\bm{U}$ from the right gives us the eigenvalue problem +!bt +\[ +(\bm{X}\bm{X}^T)\bm{U}=\bm{U}\begin{bmatrix} \tilde{\bm{\Sigma}} & \bm{0} \\ \bm{0} & \bm{0}\\ \end{bmatrix}. +\] +!et + +It means that the eigenvalues of $\bm{X}\bm{X}^T$ are again given by +the non-zero singular values plus now a series of zeros. The column +vectors of $\bm{U}$ are the eigenvectors of $\bm{X}\bm{X}^T$ and +measure how much correlations are contained in the rows of $\bm{X}$. + +Since we will mainly be interested in the correlations among the features +of our data (the columns of $\bm{X}$, the quantity of interest for us are the non-zero singular +values and the column vectors of $\bm{V}$. + + + + +===== Ridge and Lasso Regression ===== + +Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is +our optimization problem is +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}. +\] +!et +or we can state it as +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2, +\] +!et +where we have used the definition of a norm-2 vector, that is +!bt +\[ +\vert\vert \bm{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. +\] +!et + + + +By minimizing the above equation with respect to the parameters +$\bm{\beta}$ we could then obtain an analytical expression for the +parameters $\bm{\beta}$. We can add a regularization parameter $\lambda$ by +defining a new cost function to be optimized, that is + +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_2^2 +\] +!et + +which leads to the Ridge regression minimization problem where we +require that $\vert\vert \bm{\beta}\vert\vert_2^2\le t$, where $t$ is +a finite number larger than zero. By defining + +!bt +\[ +C(\bm{X},\bm{\beta})=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1, +\] +!et + +we have a new optimization equation +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1 +\] +!et +which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. + +Here we have defined the norm-1 as +!bt +\[ +\vert\vert \bm{x}\vert\vert_1 = \sum_i \vert x_i\vert. +\] +!et + + + + + +Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have + +!bt +\[ +C(\bm{X},\bm{\beta})=\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\bm{\beta}^T\bm{\beta}, +\] +!et +and +taking the derivatives with respect to $\bm{\beta}$ we obtain then +a slightly modified matrix inversion problem which for finite values +of $\lambda$ does not suffer from singularity problems. We obtain +the optimal parameters +!bt +\[ +\hat{\bm{\beta}}_{\mathrm{Ridge}} = \left(\bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}, +\] +!et + +with $\bm{I}$ being a $p\times p$ identity matrix with the constraint that + +!bt +\[ +\sum_{i=0}^{p-1} \beta_i^2 \leq t, +\] +!et + +with $t$ a finite positive number. + +When we compare this with the ordinary least squares result we have +!bt +\[ +\hat{\bm{\beta}}_{\mathrm{OLS}} = \left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}, +\] +!et +which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\bm{X}^T\bm{X}$. + + +We see that Ridge regression is nothing but the standard OLS with a +modified diagonal term added to $\bm{X}^T\bm{X}$. The consequences, in +particular for our discussion of the bias-variance tradeoff are rather +interesting. We will see that for specific values of $\lambda$, we may +even reduce the variance of the optimal parameters $\bm{\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here. + + + +Using our insights about the SVD of the design matrix $\bm{X}$ +We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\bm{U}$ as +!bt +\[ +\tilde{\bm{y}}_{\mathrm{OLS}}=\bm{X}\bm{\beta} =\bm{U}\bm{U}^T\bm{y}. +\] +!et + + +For Ridge regression this becomes + +!bt +\[ +\tilde{\bm{y}}_{\mathrm{Ridge}}=\bm{X}\bm{\beta}_{\mathrm{Ridge}} = \bm{U\Sigma V^T}\left(\bm{V}\bm{\Sigma}^2\bm{V}^T+\lambda\bm{I} \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\sum_{j=0}^{p-1}\bm{u}_j\bm{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\bm{y}, +\] +!et + +with the vectors $\bm{u}_j$ being the columns of $\bm{U}$ from the SVD of the matrix $\bm{X}$. + + + +Since $\lambda \geq 0$, it means that compared to OLS, we have + +!bt +\[ +\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1. +\] +!et + +Ridge regression finds the coordinates of $\bm{y}$ with respect to the +orthonormal basis $\bm{U}$, it then shrinks the coordinates by +$\frac{\sigma_j^2}{\sigma_j^2+\lambda}$. Recall that the SVD has +eigenvalues ordered in a descending way, that is $\sigma_i \geq +\sigma_{i+1}$. + +For small eigenvalues $\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods. + + + +For the sake of simplicity, let us assume that the design matrix is orthonormal, that is + +!bt +\[ +\bm{X}^T\bm{X}=(\bm{X}^T\bm{X})^{-1} =\bm{I}. +\] +!et + +In this case the standard OLS results in +!bt +\[ +\bm{\beta}^{\mathrm{OLS}} = \bm{X}^T\bm{y}=\sum_{i=0}^{p-1}\bm{u}_j\bm{u}_j^T\bm{y}, +\] +!et + +and + +!bt +\[ +\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{I}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}=\left(1+\lambda\right)^{-1}\bm{\beta}^{\mathrm{OLS}}, +\] +!et + +that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\lambda$, and +the Ridge estimator converges to zero when the hyperparameter goes to +infinity. + +We will come back to more interpreations after we have gone through some of the statistical analysis part. + + + +Using the matrix-vector expression for Lasso regression and dropping the parameter $1/n$ in front of the standard mean squared error equation, we have the following _cost_ function + +!bt +\[ +C(\bm{X},\bm{\beta})=\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\vert\vert\bm{\beta}\vert\vert_1, +\] +!et + +Taking the derivative with respect to $\bm{\beta}$ and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty) +!bt +\[ +\frac{d \vert \beta\vert}{d \bm{\beta}}=\mathrm{sgn}(\bm{\beta})=\left\{\begin{array}{cc} 1 & \beta > 0 \\ 0 & \beta =0\\-1 & \beta < 0, \end{array}\right. +\] +!et +we have that the derivative of the cost function is + +!bt +\[ +\frac{\partial C(\bm{X},\bm{\beta})}{\partial \bm{\beta}}=-2\bm{X}^T(\bm{y}-\bm{X}\bm{\beta})+\lambda sgn(\bm{\beta})=0, +\] +!et +and reordering we have +!bt +\[ +\bm{X}^T\bm{X}\bm{\beta}+\lambda sgn(\bm{\beta})=2\bm{X}^T\bm{y}. +\] +!et +This equation does not lead to a nice analytical equation as in Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms using for example the Python package "CVXOPT":"https://cvxopt.org/". We will discuss this later. + + + + + +Let us assume that our design matrix is given by unit (identity) matrix, that is a square diagonal matrix with ones only along the +diagonal. In this case we have an equal number of rows and columns $n=p$. + +Our model approximation is just $\tilde{\bm{y}}=\bm{\beta}$ and the mean squared error and thereby the cost function for ordinary least sqquares (OLS) is then (we drop the term $1/n$) +!bt +\[ +C(\bm{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2, +\] +!et +and minimizing we have that +!bt +\[ +\hat{\beta}_i^{\mathrm{OLS}} = y_i. +\] +!et + + +For Ridge regression our cost function is +!bt +\[ +C(\bm{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\beta_i^2, +\] +!et +and minimizing we have that +!bt +\[ +\hat{\beta}_i^{\mathrm{Ridge}} = \frac{y_i}{1+\lambda}. +\] +!et + + +For Lasso regression our cost function is +!bt +\[ +C(\bm{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\vert\beta_i\vert=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\sqrt{\beta_i^2}, +\] +!et +and minimizing we have that +!bt +\[ +-2\sum_{i=0}^{p-1}(y_i-\beta_i)+\lambda \sum_{i=0}^{p-1}\frac{(\beta_i)}{\vert\beta_i\vert}=0, +\] +!et +which leads to +!bt +\[ +\hat{\bm{\beta}}_i^{\mathrm{Lasso}} = \left\{\begin{array}{ccc}y_i-\frac{\lambda}{2} &\mathrm{if} & y_i> \frac{\lambda}{2}\\ + y_i+\frac{\lambda}{2} &\mathrm{if} & y_i< -\frac{\lambda}{2}\\ + 0 &\mathrm{if} & \vert y_i\vert\le \frac{\lambda}{2}\end{array}\right.\\. +\] +!et + +Plotting these results ("figure in handwritten notes for week 36":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2021/NotesSeptember9.pdf") shows clearly that Lasso regression suppresses (sets to zero) values of $\beta_i$ for specific values of $\lambda$. Ridge regression reduces on the other hand the values of $\beta_i$ as function of $\lambda$. + + +As another examples, +let us assume we have a data set with outputs/targets given by the vector + +!bt +\[ +\bm{y}=\begin{bmatrix}4 \\ 2 \\3\end{bmatrix}, +\] +!et +and our inputs as a $3\times 2$ design matrix +!bt +\[ +\bm{X}=\begin{bmatrix}2 & 0\\ 0 & 1 \\ 0 & 0\end{bmatrix}, +\] +!et +meaning that we have two features and two unknown parameters $\beta_0$ and $\beta_1$ to be determined either by ordinary least squares, Ridge or Lasso regression. + + +For ordinary least squares (OLS) we know that the optimal solution is + +!bt +\[ +\hat{\bm{\beta}}^{\mathrm{OLS}}=\left( \bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. +\] +!et +Inserting the above values we obtain that + +!bt +\[ +\hat{\bm{\beta}}^{\mathrm{OLS}}=\begin{bmatrix}2 \\ 2\end{bmatrix}, +\] +!et + +The code which implements this simpler case is presented after the discussion of Ridge and Lasso. + + +For Ridge regression we have + +!bt +\[ +\hat{\bm{\beta}}^{\mathrm{Ridge}}=\left( \bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}. +\] +!et +Inserting the above values we obtain that + +!bt +\[ +\hat{\bm{\beta}}^{\mathrm{Ridge}}=\begin{bmatrix}\frac{8}{4+\lambda} \\ \frac{2}{1+\lambda}\end{bmatrix}, +\] +!et + +There is normally a constraint on the value of $\vert\vert \bm{\beta}\vert\vert_2$ via the parameter $\lambda$. +Let us for simplicity assume that $\beta_0^2+\beta_1^2=1$ as constraint. This will allow us to find an expression for the optimal values of $\beta$ and $\lambda$. + +To see this, let us write the cost function for Ridge regression. + + + +We define the MSE without the $1/n$ factor and have then, using that +!bt +\[ +\bm{X}\bm{\beta}=\begin{bmatrix} 2\beta_0 \\ \beta_1 \\0 \end{bmatrix}, +\] +!et + +!bt +\[ +C(\bm{\beta})=(4-2\beta_0)^2+(2-\beta_1)^2+\lambda(\beta_0^2+\beta_1^2), +\] +!et +and taking the derivative with respect to $\beta_0$ we get +!bt +\[ +\beta_0=\frac{8}{4+\lambda}, +\] +!et +and for $\beta_1$ we obtain +!bt +\[ +\beta_1=\frac{2}{1+\lambda}, +\] +!et + +Using the constraint for $\beta_0^2+\beta_1^2=1$ we can constrain $\lambda$ by solving +!bt +\[ +\left(\frac{8}{4+\lambda}\right)^2+\left(\frac{2}{1+\lambda}\right)^2=1, +\] +!et +which gives $\lambda=4.571$ and $\beta_0=0.933$ and $\beta_1=0.359$. + + +For Lasso we need now, keeping a constraint on $\vert\beta_0\vert+\vert\beta_1\vert=1$, to take the derivative of the absolute values of $\beta_0$ +and $\beta_1$. This gives us the following derivatives of the cost function +!bt +\[ +C(\bm{\beta})=(4-2\beta_0)^2+(2-\beta_1)^2+\lambda(\vert\beta_0\vert+\vert\beta_1\vert), +\] +!et + +!bt +\[ +\frac{\partial C(\bm{\beta})}{\partial \beta_0}=-4(4-2\beta_0)+\lambda\mathrm{sgn}(\beta_0)=0, +\] +!et +and +!bt +\[ +\frac{\partial C(\bm{\beta})}{\partial \beta_1}=-2(2-\beta_1)+\lambda\mathrm{sgn}(\beta_1)=0. +\] +!et +We have now four cases to solve besides the trivial cases $\beta_0$ and/or $\beta_1$ are zero, namely +o $\beta_0 > 0$ and $\beta_1 > 0$, +o $\beta_0 > 0$ and $\beta_1 < 0$, +o $\beta_0 < 0$ and $\beta_1 > 0$, +o $\beta_0 < 0$ and $\beta_1 < 0$. + + +If we consider the first case, we have then +!bt +\[ +-4(4-2\beta_0)+\lambda=0, +\] +!et +and +!bt +\[ +-2(2-\beta_1)+\lambda=0. +\] +!et +which yields + +!bt +\[ +\beta_0=\frac{16+\lambda}{8}, +\] +!et +and +!bt +\[ +\beta_1=\frac{4+\lambda}{2}. +\] +!et + +Using the constraint on $\beta_0$ and $\beta_1$ we can then find the optimal value of $\lambda$ for the different cases. We leave this as an exercise to you. + + +Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of $\lambda$, meaning that we need to perform a search in order to find the optimal values. + +First we study and compare the OLS and Ridge results. The next code compares all three methods. +We select values of the hyperparameter $\lambda\in [10^{-4},10^4]$ and compute the predicted values for ordinary least squares and Ridge regression. + +!bc pycod +import os +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt + +def R2(y_data, y_model): + return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2) +def MSE(y_data,y_model): + n = np.size(y_model) + return np.sum((y_data-y_model)**2)/n + + +# A seed just to ensure that the random numbers are the same for every run. +# Useful for eventual debugging. + +X = np.array( [ [ 2, 0], [0, 1], [0,0]]) +y = np.array( [4, 2, 3]) + + +# matrix inversion to find beta +OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y +print(OLSbeta) +# and then make the prediction +ytildeOLS = X @ OLSbeta +print("Training MSE for OLS") +print(MSE(y,ytildeOLS)) +ypredictOLS = X @ OLSbeta + +# Repeat now for Ridge regression and various values of the regularization parameter +I = np.eye(2,2) +# Decide which values of lambda to use +nlambdas = 100 +MSEPredict = np.zeros(nlambdas) +lambdas = np.logspace(-4, 4, nlambdas) +for i in range(nlambdas): + lmb = lambdas[i] + Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y +# print(Ridgebeta) + # and then make the prediction + ypredictRidge = X @ Ridgebeta + MSEPredict[i] = MSE(y,ypredictRidge) +# print(MSEPredict[i]) + # Now plot the results +plt.figure() +plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Train') +plt.xlabel('log10(lambda)') +plt.ylabel('MSE') +plt.legend() +plt.show() + +!ec + +We see here that we reach a plateau for the Ridge results. Writing out the coefficients $\bm{\beta}$, we that they are getting smaller and smaller and our error stabilizes since the predicted values of $\tilde{\bm{y}}$ approach zero. + +This happens also for Lasso regression, as seen from the next code +output. The difference is that Lasso shrinks the values of $\beta$ to +zero at a much earlier stage and the results flatten out. We see that +Lasso gives also an excellent fit for small values of $\lambda$ and +shows rthe best performance of the three regression methods. + +!bc pycod +import os +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +from sklearn import linear_model + +def R2(y_data, y_model): + return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2) +def MSE(y_data,y_model): + n = np.size(y_model) + return np.sum((y_data-y_model)**2)/n + + +# A seed just to ensure that the random numbers are the same for every run. +# Useful for eventual debugging. + +X = np.array( [ [ 2, 0], [0, 1], [0,0]]) +y = np.array( [4, 2, 3]) + + +# matrix inversion to find beta +OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y +print(OLSbeta) +# and then make the prediction +ytildeOLS = X @ OLSbeta +print("Training MSE for OLS") +print(MSE(y,ytildeOLS)) +ypredictOLS = X @ OLSbeta + +# Repeat now for Ridge regression and various values of the regularization parameter +I = np.eye(2,2) +# Decide which values of lambda to use +nlambdas = 100 +MSERidgePredict = np.zeros(nlambdas) +MSELassoPredict = np.zeros(nlambdas) +lambdas = np.logspace(-4, 4, nlambdas) +for i in range(nlambdas): + lmb = lambdas[i] + Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y + print(Ridgebeta) + # and then make the prediction + ypredictRidge = X @ Ridgebeta + MSERidgePredict[i] = MSE(y,ypredictRidge) + RegLasso = linear_model.Lasso(lmb) + RegLasso.fit(X,y) + ypredictLasso = RegLasso.predict(X) + print(RegLasso.coef_) + MSELassoPredict[i] = MSE(y,ypredictLasso) +# Now plot the results +plt.figure() +plt.plot(np.log10(lambdas), MSERidgePredict, 'r--', label = 'MSE Ridge Train') +plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Train') +plt.xlabel('log10(lambda)') +plt.ylabel('MSE') +plt.legend() +plt.show() + +!ec + + +We bring then back our exponential function example and study all +three regression methods. Depending on the level of noise, we note +that for small values of the hyperparameter $\lambda$ all three +methods produce the same mean squared error. Again, Lasso shrinks the +parameter values to zero much earlier than Ridge regression and the +Lasso results flatten out much earlier since all $\beta_j=0$ (check +this by printing the values). This case is an example of where OLS +performs best. Lasso and Ridge reproduce the OLS results for a limited +set of $\lambda$ values. + +!bc pycod +import os +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +from sklearn.model_selection import train_test_split +from sklearn import linear_model + +def R2(y_data, y_model): + return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2) +def MSE(y_data,y_model): + n = np.size(y_model) + return np.sum((y_data-y_model)**2)/n + + +# A seed just to ensure that the random numbers are the same for every run. +# Useful for eventual debugging. +np.random.seed(3155) + +x = np.random.rand(100) +y = 2.0+5*x*x+0.1*np.random.randn(100) + +# number of features p (here degree of polynomial +p = 3 +# The design matrix now as function of a given polynomial +X = np.zeros((len(x),p)) +X[:,0] = 1.0 +X[:,1] = x +X[:,2] = x*x +# We split the data in test and training data +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) + +# matrix inversion to find beta +OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train +print(OLSbeta) +# and then make the prediction +ytildeOLS = X_train @ OLSbeta +print("Training MSE for OLS") +print(MSE(y_train,ytildeOLS)) +ypredictOLS = X_test @ OLSbeta +print("Test MSE OLS") +print(MSE(y_test,ypredictOLS)) + +# Repeat now for Lasso and Ridge regression and various values of the regularization parameter +I = np.eye(p,p) +# Decide which values of lambda to use +nlambdas = 100 +MSEPredict = np.zeros(nlambdas) +MSETrain = np.zeros(nlambdas) +MSELassoPredict = np.zeros(nlambdas) +MSELassoTrain = np.zeros(nlambdas) +lambdas = np.logspace(-4, 4, nlambdas) +for i in range(nlambdas): + lmb = lambdas[i] + Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train + # include lasso using Scikit-Learn + RegLasso = linear_model.Lasso(lmb) + RegLasso.fit(X_train,y_train) + # and then make the prediction + ytildeRidge = X_train @ Ridgebeta + ypredictRidge = X_test @ Ridgebeta + ytildeLasso = RegLasso.predict(X_train) + ypredictLasso = RegLasso.predict(X_test) + MSEPredict[i] = MSE(y_test,ypredictRidge) + MSETrain[i] = MSE(y_train,ytildeRidge) + MSELassoPredict[i] = MSE(y_test,ypredictLasso) + MSELassoTrain[i] = MSE(y_train,ytildeLasso) + +# Now plot the results +plt.figure() +plt.plot(np.log10(lambdas), MSETrain, label = 'MSE Ridge train') +plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Test') +plt.plot(np.log10(lambdas), MSELassoTrain, label = 'MSE Lasso train') +plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Test') + +plt.xlabel('log10(lambda)') +plt.ylabel('MSE') +plt.legend() +plt.show() + +!ec + + +Both these example send a clear message. The addition of a +shrinkage/regularization term implies that we need to perform a search +for the optimal values of $\lambda$. We will see this throughout these +series of lectures. + + +As a small addendum, we note that you can also solve this problem using the convex optimization package "CVXOPT":"https://cvxopt.org/examples/mlbook/l1regls.html". This requires, in addition to having installed _CVXOPT_, you need to download the file *l1regl.py*. +The following code example solves the simpler problem we discussed above, where we have added the latter python file. + +!bc pycod +from cvxopt import matrix, spdiag, mul, div, sqrt, normal, setseed +from cvxopt import blas, lapack, solvers, sparse, spmatrix +import math + +try: + import mosek + import sys + __MOSEK = True +except: __MOSEK = False + +if __MOSEK: + + def l1regls_mosek(A, b): + """ + + Returns the solution of l1-norm regularized least-squares problem + + minimize || A*x - b ||_2^2 + e'*u + + subject to -u <= x <= u + + """ + + m, n = A.size + + env = mosek.Env() + task = env.Task(0,0) + task.set_Stream(mosek.streamtype.log, lambda x: sys.stdout.write(x)) + + task.appendvars( 2*n) # number of variables + task.appendcons( 2*n) # number of constraints + + # input quadratic objective + Q = matrix(0.0, (n,n)) + blas.syrk(A, Q, alpha = 2.0, trans='T') + + I = [] + for i in range(n): + I.extend(range(i,n)) + + J = [] + for i in range(n): + J.extend((n-i)*[i]) + + task.putqobj(I, J, list(Q[matrix(I) + matrix(J)*n])) + task.putclist(range(2*n), list(-2*A.T*b) + n*[1.0]) # setup linear objective + + # input constraint matrix row by row + for i in range(n): + task.putarow( i, [i, n+i], [1.0, -1.0]) + task.putarow( n+i, [i, n+i], [1.0, 1.0]) + + # setup bounds on constraints + task.putboundslice(mosek.accmode.con, + 0, n, n*[mosek.boundkey.up], n*[0.0], n*[0.0]) + task.putboundslice(mosek.accmode.con, + n, 2*n, n*[mosek.boundkey.lo], n*[0.0], n*[0.0]) + + # setup variable bounds + task.putboundslice(mosek.accmode.var, + 0, 2*n, 2*n*[mosek.boundkey.fr], 2*n*[0.0], 2*n*[0.0]) + + # optimize the task + task.putobjsense(mosek.objsense.minimize) + task.optimize() + task.solutionsummary(mosek.streamtype.log) + x = n*[0.0] + task.getsolutionslice(mosek.soltype.itr, mosek.solitem.xx, 0, n, x) + + return matrix(x) + + def l1regls_mosek2(A, b): + """ + + Returns the solution of l1-norm regularized least-squares problem + + minimize w'*w + e'*u + + subject to -u <= x <= u + + A*x - w = b + + """ + + m, n = A.size + + env = mosek.Env() + task = env.Task(0,0) + task.set_Stream(mosek.streamtype.log, lambda x: sys.stdout.write(x)) + + task.appendvars(2*n + m) # number of variables + task.appendcons(2*n + m) # number of constraints + + # input quadratic objective + task.putqobj(range(2*n,2*n+m), range(2*n,2*n+m), m*[2.0]) + + task.putclist(range(2*n+m), n*[0.0] + n*[1.0] + m*[0.0]) # setup linear objective + + # input constraint matrix row by row + for i in range(n): + task.putarow( i, [i, n+i], [1.0, -1.0]) + task.putarow( n+i, [i, n+i], [1.0, 1.0]) + + for i in range(m): + task.putarow( 2*n+i, range(n) + [2*n+i], list(A[i,:]) + [-1.0]) + + # setup bounds on constraints + task.putboundslice(mosek.accmode.con, + 0, n, n*[mosek.boundkey.up], n*[0.0], n*[0.0]) + task.putboundslice(mosek.accmode.con, + n, 2*n, n*[mosek.boundkey.lo], n*[0.0], n*[0.0]) + task.putboundslice(mosek.accmode.con, + 2*n, 2*n+m, m*[mosek.boundkey.fx], list(b), list(b)) + + # setup variable bounds + task.putboundslice(mosek.accmode.var, 0, 2*n+m, (2*n+m)*[mosek.boundkey.fr], + (2*n+m)*[0.0], (2*n+m)*[0.0]) + + # optimize the task + task.putobjsense(mosek.objsense.minimize) + task.optimize() + task.solutionsummary(mosek.streamtype.log) + x = n*[0.0] + task.getsolutionslice(mosek.soltype.itr, mosek.solitem.xx, 0, n, x) + + return matrix(x) + +def l1regls(A, b): + """ -* 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. + Returns the solution of l1-norm regularized least-squares problem + + minimize || A*x - b ||_2^2 + || x ||_1. -===== Reminder on Statistics ===== + """ + + m, n = A.size + q = matrix(1.0, (2*n,1)) + q[:n] = -2.0 * A.T * b + + def P(u, v, alpha = 1.0, beta = 0.0 ): + """ + v := alpha * 2.0 * [ A'*A, 0; 0, 0 ] * u + beta * v + """ + v *= beta + v[:n] += alpha * 2.0 * A.T * (A * u[:n]) -* 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. + def G(u, v, alpha=1.0, beta=0.0, trans='N'): + """ + v := alpha*[I, -I; -I, -I] * u + beta * v (trans = 'N' or 'T') + """ + + v *= beta + v[:n] += alpha*(u[:n] - u[n:]) + v[n:] += alpha*(-u[:n] - u[n:]) + + h = matrix(0.0, (2*n,1)) + + + # Customized solver for the KKT system + # + # [ 2.0*A'*A 0 I -I ] [x[:n] ] [bx[:n] ] + # [ 0 0 -I -I ] [x[n:] ] = [bx[n:] ]. + # [ I -I -D1^-1 0 ] [zl[:n]] [bzl[:n]] + # [ -I -I 0 -D2^-1 ] [zl[n:]] [bzl[n:]] + # + # where D1 = W['di'][:n]**2, D2 = W['di'][:n]**2. + # + # We first eliminate zl and x[n:]: + # + # ( 2*A'*A + 4*D1*D2*(D1+D2)^-1 ) * x[:n] = + # bx[:n] - (D2-D1)*(D1+D2)^-1 * bx[n:] + + # D1 * ( I + (D2-D1)*(D1+D2)^-1 ) * bzl[:n] - + # D2 * ( I - (D2-D1)*(D1+D2)^-1 ) * bzl[n:] + # + # x[n:] = (D1+D2)^-1 * ( bx[n:] - D1*bzl[:n] - D2*bzl[n:] ) + # - (D2-D1)*(D1+D2)^-1 * x[:n] + # + # zl[:n] = D1 * ( x[:n] - x[n:] - bzl[:n] ) + # zl[n:] = D2 * (-x[:n] - x[n:] - bzl[n:] ). + # + # The first equation has the form + # + # (A'*A + D)*x[:n] = rhs + # + # and is equivalent to + # + # [ D A' ] [ x:n] ] = [ rhs ] + # [ A -I ] [ v ] [ 0 ]. + # + # It can be solved as + # + # ( A*D^-1*A' + I ) * v = A * D^-1 * rhs + # x[:n] = D^-1 * ( rhs - A'*v ). + + S = matrix(0.0, (m,m)) + Asc = matrix(0.0, (m,n)) + v = matrix(0.0, (m,1)) + + def Fkkt(W): + + # Factor + # + # S = A*D^-1*A' + I + # + # where D = 2*D1*D2*(D1+D2)^-1, D1 = d[:n]**-2, D2 = d[n:]**-2. + + d1, d2 = W['di'][:n]**2, W['di'][n:]**2 + + # ds is square root of diagonal of D + ds = math.sqrt(2.0) * div( mul( W['di'][:n], W['di'][n:]), + sqrt(d1+d2) ) + d3 = div(d2 - d1, d1 + d2) + + # Asc = A*diag(d)^-1/2 + Asc = A * spdiag(ds**-1) + + # S = I + A * D^-1 * A' + blas.syrk(Asc, S) + S[::m+1] += 1.0 + lapack.potrf(S) + + def g(x, y, z): + + x[:n] = 0.5 * ( x[:n] - mul(d3, x[n:]) + + mul(d1, z[:n] + mul(d3, z[:n])) - mul(d2, z[n:] - + mul(d3, z[n:])) ) + x[:n] = div( x[:n], ds) + + # Solve + # + # S * v = 0.5 * A * D^-1 * ( bx[:n] - + # (D2-D1)*(D1+D2)^-1 * bx[n:] + + # D1 * ( I + (D2-D1)*(D1+D2)^-1 ) * bzl[:n] - + # D2 * ( I - (D2-D1)*(D1+D2)^-1 ) * bzl[n:] ) + + blas.gemv(Asc, x, v) + lapack.potrs(S, v) + + # x[:n] = D^-1 * ( rhs - A'*v ). + blas.gemv(Asc, v, x, alpha=-1.0, beta=1.0, trans='T') + x[:n] = div(x[:n], ds) + + # x[n:] = (D1+D2)^-1 * ( bx[n:] - D1*bzl[:n] - D2*bzl[n:] ) + # - (D2-D1)*(D1+D2)^-1 * x[:n] + x[n:] = div( x[n:] - mul(d1, z[:n]) - mul(d2, z[n:]), d1+d2 )\ + - mul( d3, x[:n] ) + + # zl[:n] = D1^1/2 * ( x[:n] - x[n:] - bzl[:n] ) + # zl[n:] = D2^1/2 * ( -x[:n] - x[n:] - bzl[n:] ). + z[:n] = mul( W['di'][:n], x[:n] - x[n:] - z[:n] ) + z[n:] = mul( W['di'][n:], -x[:n] - x[n:] - z[n:] ) + + return g + + return solvers.coneqp(P, q, G, h, kktsolver = Fkkt)['x'][:n] + + +!ec + + +Then we call the above functions and solve the problem, as done here + +!bc pycod +from cvxopt import matrix, normal + +X = matrix( [ [ 2, 0, 1], [0, 1, 3]]) +y = matrix( [4, 2, 3]) +x = l1regls(X,y) +!ec + + + +===== Linking the regression analysis with a statistical interpretation ===== + +We will now couple the discussions of ordinary least squares, Ridge +and Lasso regression with a statistical interpretation, that is we +move from a linear algebra analysis to a statistical analysis. In +particular, we will focus on what the regularization terms can result +in. We will amongst other things show that the regularization +parameter can reduce considerably the variance of the parameters +$\beta$. + The advantage of doing linear regression is that we actually end up with @@ -81,6 +2100,7 @@ notation above $\mathbf{X}_{i,\ast}$ means that we are looking at the row number $i$ and perform a sum over all values $p$. + The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off) that there exists a function $f(\bm{x})$ and a normal distributed error $\bm{\varepsilon}\sim \mathcal{N}(0, \sigma^2)$ which describe our data @@ -166,8 +2186,7 @@ where we have used that $\mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) = \sigma^2 \, \mathbf{I}_{nn}$. From $\mbox{Var}(\bm{\beta}) = \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}$, one obtains an estimate of the variance of the estimate of the $j$-th regression coefficient: -$\bm{\sigma}^2 (\bm{\beta}_j ) = \bm{\sigma}^2 \sqrt{ -[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} }$. This may be used to +$\bm{\sigma}^2 (\bm{\beta}_j ) = \bm{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} $. This may be used to construct a confidence interval for the estimates. @@ -206,861 +2225,325 @@ This means the variance we obtain with the standard OLS will always for $\lambda -===== Resampling methods ===== +===== Deriving OLS from a probability distribution ===== -With all these analytical equations for both the OLS and Ridge -regression, we will now outline how to assess a given model. This will -lead us to a discussion of the so-called bias-variance tradeoff (see -below) and so-called resampling methods. +Our basic assumption when we derived the OLS equations was to assume +that our output is determined by a given continuous function +$f(\bm{x})$ and a random noise $\bm{\epsilon}$ given by the normal +distribution with zero mean value and an undetermined variance +$\sigma^2$. -One of the quantities we have discussed as a way to measure errors is -the mean-squared error (MSE), mainly used for fitting of continuous -functions. Another choice is the absolute error. +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 -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. - - - -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 $\bm{x} = (x_1,x_2,\cdots,X_n)$. -Let $\bm{x}_i$ denote the vector !bt \[ -\bm{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), +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 -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$. - - -!bc pycod -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) - -!ec - - -=== 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: -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). - - - -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. - - - -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 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})$. - - -But -unless there is enough information available about the process that -generated $X_1,X_2,\cdots,X_n$, $p(x)$ is in general -unknown. Therefore, "Efron in 1979":"https://projecteuclid.org/euclid.aos/1176344552" asked the -question: What if we replace $p(x)$ by the relative frequency -of the observation $X_i$; if we draw observations in accordance with -the relative frequency of the observations, will we obtain the same -result in some asymptotic sense? The answer is yes. - - -Instead of generating the histogram for the relative -frequency of the observation $X_i$, just draw the values -$(X_1^*,X_2^*,\cdots,X_n^*)$ with replacement from the vector -$\bm{X}$. - - -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 ^*$. - - - -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. - - -!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 - -# 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() - -!ec - - - -===== Various steps in cross-validation ===== - -When the repetitive splitting of the data set is done randomly, -samples may accidently end up in a fast majority of the splits in -either training or test set. Such samples may have an unbalanced -influence on either model building or prediction evaluation. To avoid -this $k$-fold cross-validation structures the data splitting. The -samples are divided into $k$ more or less equally sized exhaustive and -mutually exclusive subsets. In turn (at each split) one of these -subsets plays the role of the test set while the union of the -remaining subsets constitutes the training set. Such a splitting -warrants a balanced representation of each sample in both training and -test set over the splits. Still the division into the $k$ subsets -involves a degree of randomness. This may be fully excluded when -choosing $k=n$. This particular case is referred to as leave-one-out -cross-validation (LOOCV). - - -* Define a range of interest for the penalty parameter. - -* Divide the data set into training and test set comprising samples $\{1, \ldots, n\} \setminus i$ and $\{ i \}$, respectively. - -* Fit the linear regression model by means of ridge estimation for each $\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\bm{\sigma}_{-i}^2(\lambda)$, as +We assume now that the various $y_i$ values are stochastically distributed according to the above Gaussian distribution. +We define this distribution as !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 +\[ +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}$. -* 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. +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 -* 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*} +\[ +p(\bm{y},\bm{X}\vert\bm{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\bm{X}\vert\bm{\beta}). +\] +!et + +We will write this in a more compact form reserving $\bm{D}$ for the domain of events, including the ouputs (targets) and the inputs. That is +in case we have a simple one-dimensional input and output case +!bt +\[ +\bm{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})]. +\] +!et +In the more general case the various inputs should be replaced by the possible features represented by the input data set $\bm{X}$. +We can now rewrite the above probability as +!bt +\[ +p(\bm{D}\vert\bm{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}. +\] +!et + +It is a conditional probability (see below) and reads as the likelihood of a domain of events $\bm{D}$ given a set of parameters $\bm{\beta}$. + + +In statistics, maximum likelihood estimation (MLE) is a method of +estimating the parameters of an assumed probability distribution, +given some observed data. This is achieved by maximizing a likelihood +function so that, under the assumed statistical model, the observed +data is the most probable. + + +We will assume here that our events are given by the above Gaussian +distribution and we will determine the optimal parameters $\beta$ by +maximizing the above PDF. However, computing the derivatives of a +product function is cumbersome and can easily lead to overflow and/or +underflowproblems, with potentials for loss of numerical precision. + + +In practice, it is more convenient to maximize the logarithm of the +PDF because it is a monotonically increasing function of the argument. +Alternatively, and this will be our option, we will minimize the +negative of the logarithm since this is a monotonically decreasing +function. + +Note also that maximization/minimization of the logarithm of the PDF +is equivalent to the maximization/minimization of the function itself. + + + + +We could now define a new cost function to minimize, namely the negative logarithm of the above PDF + +!bt +\[ +C(\bm{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\bm{X}\vert\bm{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\bm{X}\vert\bm{\beta})}, +\] +!et +which becomes +!bt +\[ +C(\bm{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}. +\] +!et + +Taking the derivative of the *new* cost function with respect to the parameters $\beta$ we recognize our familiar OLS equation, namely + +!bt +\[ +\bm{X}^T\left(\bm{y}-\bm{X}\bm{\beta}\right) =0, +\] +!et +which leads to the well-known OLS equation for the optimal paramters $\beta$ +!bt +\[ +\hat{\bm{\beta}}^{\mathrm{OLS}}=\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}! +\] !et -For the various values of $k$ +Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics. -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 + +A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry. +Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics. + +Assume we have two domains of events $X=[x_0,x_1,\dots,x_{n-1}]$ and $Y=[y_0,y_1,\dots,y_{n-1}]$. + +We define also the likelihood for $X$ and $Y$ as $p(X)$ and $p(Y)$ respectively. +The likelihood of a specific event $x_i$ (or $y_i$) is then written as $p(X=x_i)$ or just $p(x_i)=p_i$. + +!bblock Union of events is given by +!bt +\[ +p(X \cup Y)= p(X)+p(Y)-p(X \cap Y). +\] +!et +!eblock + + +!bblock The product rule (aka joint probability) is given by +!bt +\[ +p(X \cup Y)= p(X,Y)= p(X\vert Y)p(Y)=p(Y\vert X)p(X), +\] +!et +where we read $p(X\vert Y)$ as the likelihood of obtaining $X$ given $Y$. +!eblock + +If we have independent events then $p(X,Y)=p(X)p(Y)$. +The marginal probability is defined in terms of only one of the set of variables $X,Y$. For a discrete probability we have +!bblock +!bt +\[ +p(X)=\sum_{i=0}^{n-1}p(X,Y=y_i)=\sum_{i=0}^{n-1}p(X\vert Y=y_i)p(Y=y_i)=\sum_{i=0}^{n-1}p(X\vert y_i)p(y_i). +\] +!et +!eblock + + + +The conditional probability, if $p(Y) > 0$, is +!bblock +!bt +\[ +p(X\vert Y)= \frac{p(X,Y)}{p(Y)}=\frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}. +\] +!et +!eblock + + + +If we combine the conditional probability with the marginal probability and the standard product rule, we have +!bt +\[ +p(X\vert Y)= \frac{p(X,Y)}{p(Y)}, +\] +!et +which we can rewrite as + +!bt +\[ +p(X\vert Y)= \frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}=\frac{p(Y\vert X)p(X)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}, +\] +!et +which is Bayes' theorem. It allows us to evaluate the uncertainty in in $X$ after we have observed $Y$. We can easily interchange $X$ with $Y$. + + +The quantity $p(Y\vert X)$ on the right-hand side of the theorem is +evaluated for the observed data $Y$ and can be viewed as a function of +the parameter space represented by $X$. This function is not +necesseraly normalized and is normally called the likelihood function. + +The function $p(X)$ on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution. + +Let us try to illustrate Bayes' theorem through an example. + + +Let us suppose that you are undergoing a series of mammography scans in +order to rule out possible breast cancer cases. We define the +sensitivity for a positive event by the variable $X$. It takes binary +values with $X=1$ representing a positive event and $X=0$ being a +negative event. We reserve $Y$ as a classification parameter for +either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing). + +We let $Y=1$ represent the the case of having breast cancer and $Y=0$ as not. + +Let us assume that if you have breast cancer, the test will be positive with a probability of $0.8$, that is we have + +!bt +\[ +p(X=1\vert Y=1) =0.8. +\] +!et + +This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of $80\%$ for having cancer. +It is however not correct, as the following Bayesian analysis shows. + + +If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number. +Let us assume that the prior probability in the population as a whole is + +!bt +\[ +p(Y=1) =0.004. +\] +!et + +We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have +!bt +\[ +p(X=1\vert Y=0) =0.1. +\] +!et + +Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute + +!bt +\[ +p(Y=1\vert X=1)=\frac{p(X=1\vert Y=1)p(Y=1)}{p(X=1\vert Y=1)p(Y=1)+p(X=1\vert Y=0)p(Y=0)}=\frac{0.8\times 0.004}{0.8\times 0.004+0.1\times 0.996}=0.031. +\] +!et +That is, in case of a positive test, there is only a $3\%$ chance of having breast cancer! + + + +===== Bayes' Theorem and Ridge and Lasso Regression ===== + +Hitherto we have discussed Ridge and Lasso regression in terms of a +linear analysis. This may to many of you feel rather technical and +perhaps not that intuitive. The question is whether we can develop a +more intuitive way of understanding what Ridge and Lasso express. + +Before we proceed let us perform a Ridge, Lasso and OLS analysis of a polynomial fit. + + +We will play around with a study of the values for the optimal +parameters $\bm{\beta}$ using OLS, Ridge and Lasso regression. For +OLS, you will notice as function of the noise and polynomial degree, +that the parameters $\beta$ will fluctuate from order to order in the +polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS. + +For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one. -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 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() - -!ec - - - -===== 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}$. - - - - -!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 +from sklearn import linear_model -np.random.seed(2018) - -n = 500 -n_boostraps = 100 -degree = 18 # A quite high value, just to show. -noise = 0.1 +def R2(y_data, y_model): + return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2) +def MSE(y_data,y_model): + n = np.size(y_model) + return np.sum((y_data-y_model)**2)/n # Make data set. -x = np.linspace(-1, 3, n).reshape(-1, 1) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape) +n = 10000 +x = np.random.rand(n) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n) -# Hold out some test data that is never used in training. -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) - -# Combine x transformation and model into one operation. -# Not neccesary, but convenient. -model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) - -# The following (m x n_bootstraps) matrix holds the column vectors y_pred -# for each bootstrap iteration. -y_pred = np.empty((y_test.shape[0], n_boostraps)) -for i in range(n_boostraps): - x_, y_ = resample(x_train, y_train) - - # Evaluate the new model on the same test data each time. - y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() - -# Note: Expectations and variances taken w.r.t. different training -# data sets, hence the axis=1. Subsequent means are taken across the test data -# set in order to obtain a total value, but before this we have error/bias/variance -# calculated per data point in the test set. -# Note 2: The use of keepdims=True is important in the calculation of bias as this -# maintains the column vector form. Dropping this yields very unexpected results. -error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) -bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) -variance = np.mean( np.var(y_pred, axis=1, keepdims=True) ) -print('Error:', error) -print('Bias^2:', bias) -print('Var:', variance) -print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance)) - -plt.plot(x[::5, :], y[::5, :], label='f(x)') -plt.scatter(x_test, y_test, label='Data points') -plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred') -plt.legend() -plt.show() - -!ec - - - -!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 - - - -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. - - -!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 - - - -!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) - -if not os.path.exists(FIGURE_ID): - os.makedirs(FIGURE_ID) - -if not os.path.exists(DATA_ID): - os.makedirs(DATA_ID) - -def image_path(fig_id): - return os.path.join(FIGURE_ID, fig_id) - -def data_path(dat_id): - return os.path.join(DATA_ID, dat_id) - -def save_fig(fig_id): - plt.savefig(image_path(fig_id) + ".png", format='png') - -infile = open(data_path("EoS.csv"),'r') - -# Read the EoS data as csv file and organize the data into two arrays with density and energies -EoS = pd.read_csv(infile, names=('Density', 'Energy')) -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') -EoS = EoS.dropna() -Energies = EoS['Energy'] -Density = EoS['Density'] -# The design matrix now as function of various polytrops - -Maxpolydegree = 30 -X = np.zeros((len(Density),Maxpolydegree)) +Maxpolydegree = 5 +X = np.zeros((len(x),Maxpolydegree)) X[:,0] = 1.0 -testerror = np.zeros(Maxpolydegree) -trainingerror = np.zeros(Maxpolydegree) -polynomial = np.zeros(Maxpolydegree) - -trials = 100 -for polydegree in range(1, Maxpolydegree): - polynomial[polydegree] = polydegree - for degree in range(polydegree): - X[:,degree] = Density**(degree/3.0) - -# loop over trials in order to estimate the expectation value of the MSE - testerror[polydegree] = 0.0 - trainingerror[polydegree] = 0.0 - for samples in range(trials): - x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2) - model = LinearRegression(fit_intercept=True).fit(x_train, y_train) - ypred = model.predict(x_train) - ytilde = model.predict(x_test) - testerror[polydegree] += mean_squared_error(y_test, ytilde) - trainingerror[polydegree] += mean_squared_error(y_train, ypred) - - testerror[polydegree] /= trials - trainingerror[polydegree] /= trials - print("Degree of polynomial: %3d"% polynomial[polydegree]) - print("Mean squared error on training data: %.8f" % trainingerror[polydegree]) - print("Mean squared error on test data: %.8f" % testerror[polydegree]) - -plt.plot(polynomial, np.log10(trainingerror), label='Training Error') -plt.plot(polynomial, np.log10(testerror), label='Test Error') -plt.xlabel('Polynomial degree') -plt.ylabel('log10[MSE]') -plt.legend() -plt.show() - -!ec - - - -!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 + X[:,degree] = x**(degree) -!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) +# We split the data in test and training data +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) +# matrix inversion to find beta +OLSbeta = np.linalg.pinv(X_train.T @ X_train) @ X_train.T @ y_train +print(OLSbeta) +ypredictOLS = X_test @ OLSbeta +print("Test MSE OLS") +print(MSE(y_test,ypredictOLS)) +# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn # Decide which values of lambda to use -nlambdas = 500 -lambdas = np.logspace(-3, 5, nlambdas) -# Initialize a KFold instance -k = 5 -kfold = KFold(n_splits = k) -estimated_mse_sklearn = np.zeros(nlambdas) -i = 0 -for lmb in lambdas: - ridge = Ridge(alpha = lmb) - estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold) - estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds) - i += 1 +nlambdas = 4 +MSERidgePredict = np.zeros(nlambdas) +MSELassoPredict = np.zeros(nlambdas) +lambdas = np.logspace(-3, 1, nlambdas) +for i in range(nlambdas): + lmb = lambdas[i] + # Make the fit using Ridge and Lasso + RegRidge = linear_model.Ridge(lmb,fit_intercept=False) + RegRidge.fit(X_train,y_train) + RegLasso = linear_model.Lasso(lmb,fit_intercept=False) + RegLasso.fit(X_train,y_train) + # and then make the prediction + ypredictRidge = RegRidge.predict(X_test) + ypredictLasso = RegLasso.predict(X_test) + # Compute the MSE and print it + MSERidgePredict[i] = MSE(y_test,ypredictRidge) + MSELassoPredict[i] = MSE(y_test,ypredictLasso) + print(lmb,RegRidge.coef_) + print(lmb,RegLasso.coef_) +# Now plot the results plt.figure() -plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score') +plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test') +plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test') plt.xlabel('log10(lambda)') plt.ylabel('MSE') plt.legend() @@ -1069,4 +2552,119 @@ plt.show() !ec +How can we understand this? + + + +Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression. + +For ordinary least squares we postulated that the maximum likelihood for the doamin of events $\bm{D}$ (one-dimensional case) +!bt +\[ +\bm{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})], +\] +!et +is given by +!bt +\[ +p(\bm{D}\vert\bm{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}. +\] +!et + +In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set $\bm{\beta}$ given a domain of events $\bm{D}$? That is, how can we define the posterior probability + +!bt +\[ +p(\bm{\beta}\vert\bm{D}). +\] +!et + +Bayes' theorem comes to our rescue here since (omitting the normalization constant) +!bt +\[ +p(\bm{\beta}\vert\bm{D})\propto p(\bm{D}\vert\bm{\beta})p(\bm{\beta}). +\] +!et + +We have a model for $p(\bm{D}\vert\bm{\beta})$ but need one for the _prior_ $p(\bm{\beta}$! + + + +With the posterior probability defined by a likelihood which we have +already modeled and an unknown prior, we are now ready to make +additional models for the prior. + +We can, based on our discussions of the variance of $\bm{\beta}$ and the mean value, assume that the prior for the values $\bm{\beta}$ is given by a Gaussian with mean value zero and variance $\tau^2$, that is + +!bt +\[ +p(\bm{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}. +\] +!et + +Our posterior probability becomes then (omitting the normalization factor which is just a constant) +!bt +\[ +p(\bm{\beta\vert\bm{D})}=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}. +\] +!et + + +We can now optimize this quantity with respect to $\bm{\beta}$. As we +did for OLS, this is most conveniently done by taking the negative +logarithm of the posterior probability. Doing so and leaving out the +constants terms that do not depend on $\beta$, we have + + +!bt +\[ +C(\bm{\beta})=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{2\tau^2}\vert\vert\bm{\beta}\vert\vert_2^2, +\] +!et +and replacing $1/2\tau^2$ with $\lambda$ we have + +!bt +\[ +C(\bm{\beta})=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\bm{\beta}\vert\vert_2^2, +\] +!et +which is our Ridge cost function! Nice, isn't it? + + +To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution ("Laplace in this case":"https://en.wikipedia.org/wiki/Laplace_distribution") with zero mean value, that is + +!bt +\[ +p(\bm{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}. +\] +!et + +Our posterior probability becomes then (omitting the normalization factor which is just a constant) +!bt +\[ +p(\bm{\beta}\vert\bm{D})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}. +\] +!et + + +Taking the negative +logarithm of the posterior probability and leaving out the +constants terms that do not depend on $\beta$, we have + + +!bt +\[ +C(\bm{\beta}=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{\tau}\vert\vert\bm{\beta}\vert\vert_1, +\] +!et +and replacing $1/\tau$ with $\lambda$ we have + +!bt +\[ +C(\bm{\beta}=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\bm{\beta}\vert\vert_1, +\] +!et +which is our Lasso cost function! + + diff --git a/doc/BookChapters/chapter3.do.txt b/doc/BookChapters/chapter3.do.txt index 744b0feda..16031ac61 100644 --- a/doc/BookChapters/chapter3.do.txt +++ b/doc/BookChapters/chapter3.do.txt @@ -1,2257 +1,55 @@ -======= Ridge and Lasso Regression ======= +======= Resampling Methods ======= + +===== Introduction ===== + +Resampling methods are an indispensable tool in modern +statistics. They involve repeatedly drawing samples from a training +set and refitting a model of interest on each sample in order to +obtain additional information about the fitted model. For example, in +order to estimate the variability of a linear regression fit, we can +repeatedly draw different samples from the training data, fit a linear +regression to each new sample, and then examine the extent to which +the resulting fits differ. Such an approach may allow us to obtain +information that would not be available from fitting the model only +once using the original training sample. + +Two resampling methods are often used in Machine Learning analyses, +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. + + +Resampling approaches can be computationally expensive, because they +involve fitting the same statistical method multiple times using +different subsets of the training data. However, due to recent +advances in computing power, the computational requirements of +resampling methods generally are not prohibitive. In this chapter, we +discuss two of the most commonly used resampling methods, +cross-validation and the bootstrap. Both methods are important tools +in the practical application of many statistical learning +procedures. For example, cross-validation can be used to estimate the +test error associated with a given statistical learning method in +order to evaluate its performance, or to select the appropriate level +of flexibility. The process of evaluating a model’s performance is +known as model assessment, whereas the process of selecting the proper +level of flexibility for a model is known as model selection. The +bootstrap is widely used. - - -===== Mathematical Interpretation of Ordinary Least Squares ===== - -What is presented here is a mathematical analysis of various regression algorithms (ordinary least squares, Ridge and Lasso Regression). The analysis is based on an important algorithm in linear algebra, the so-called Singular Value Decomposition (SVD). - - -We have shown that in ordinary least squares the optimal parameters $\beta$ are given by - -!bt -\[ -\hat{\bm{\beta}} = \left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. -\] -!et - -The _hat_ over $\bm{\beta}$ means we have the optimal parameters after minimization of the cost function. - -This means that our best model is defined as - -!bt -\[ -\tilde{\bm{y}}=\bm{X}\hat{\bm{\beta}} = \bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. -\] -!et - -We now define a matrix -!bt -\[ -\bm{A}=\bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T. -\] -!et - -We can rewrite -!bt -\[ -\tilde{\bm{y}}=\bm{X}\hat{\bm{\beta}} = \bm{A}\bm{y}. -\] -!et - -The matrix $\bm{A}$ has the important property that $\bm{A}^2=\bm{A}$. This is the definition of a projection matrix. -We can then interpret our optimal model $\tilde{\bm{y}}$ as being represented by an orthogonal projection of $\bm{y}$ onto a space defined by the column vectors of $\bm{X}$. In our case here the matrix $\bm{A}$ is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix. - - - - -We have defined the residual error as -!bt -\[ -\bm{\epsilon}=\bm{y}-\tilde{\bm{y}}=\left[\bm{I}-\bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\right]\bm{y}. -\] -!et - -The residual errors are then the projections of $\bm{y}$ onto the orthogonal component of the space defined by the column vectors of $\bm{X}$. - - -If the matrix $\bm{X}$ is an orthogonal (or unitary in case of complex values) matrix, we have - -!bt -\[ -\bm{X}^T\bm{X}=\bm{X}\bm{X}^T = \bm{I}. -\] -!et - -In this case the matrix $\bm{A}$ becomes -!bt -\[ -\bm{A}=\bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T)=\bm{I}, -\] -!et -and we have the obvious case -!bt -\[ -\bm{\epsilon}=\bm{y}-\tilde{\bm{y}}=0. -\] -!et - -This serves also as a useful test of our codes. - - - - -===== The singular value decomposition ===== - - -The examples we have looked at so far are cases where we normally can -invert the matrix $\bm{X}^T\bm{X}$. Using a polynomial expansion where we fit of various functions leads to -row vectors of the design matrix which are essentially orthogonal due -to the polynomial character of our model. Obtaining the inverse of the -design matrix is then often done via a so-called LU, QR or Cholesky -decomposition. - - -As we will also see in the first project, -this may -however not the be case in general and a standard matrix inversion -algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below. - -There is however a way to circumvent this problem and also -gain some insights about the ordinary least squares approach, and -later shrinkage methods like Ridge and Lasso regressions. - -This is given by the _Singular Value Decomposition_ (SVD) algorithm, -perhaps the most powerful linear algebra algorithm. The SVD provides -a numerically stable matrix decomposition that is used in a large -swath oc applications and the decomposition is always stable -numerically. - -In machine learning it plays a central role in dealing with for -example design matrices that may be near singular or singular. -Furthermore, as we will see here, the singular values can be related -to the covariance matrix (and thereby the correlation matrix) and in -turn the variance of a given quantity. It plays also an important role -in the principal component analysis where high-dimensional data can be -reduced to the statistically relevant features. - - - - -One of the typical problems we encounter with linear regression, in particular -when the matrix $\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. - - - -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. - - - - -===== Basic math of the SVD ===== - - -From standard linear algebra we know that a square matrix $\bm{X}$ can be diagonalized if and only it is -a so-called "normal matrix":"https://en.wikipedia.org/wiki/Normal_matrix", that is if $\bm{X}\in {\mathbb{R}}^{n\times n}$ -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. - - - - - -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 - -!bt -\[ -\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T -\] -!et - -As an example, the above defective matrix can be decomposed as - -!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, -\] -!et - -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 $\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. - - -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 ===== - -!bc pycod -import numpy as np -# SVD inversion -def SVD(A): - ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD). - SVD is numerically more stable than the inversion algorithms provided by - numpy and scipy.linalg at the cost of being slower. - ''' - U, S, VT = np.linalg.svd(A,full_matrices=True) - print('test U') - print( (np.transpose(U) @ U - U @np.transpose(U))) - print('test VT') - print( (np.transpose(VT) @ VT - VT @np.transpose(VT))) - print(U) - print(S) - print(VT) - - D = np.zeros((len(U),len(VT))) - for i in range(0,len(VT)): - D[i,i]=S[i] - return U @ D @ VT - - -X = np.array([ [1.0,-1.0], [1.0,-1.0]]) -#X = np.array([[1, 2], [3, 4], [5, 6]]) - -print(X) -C = SVD(X) -# Print the difference between the original matrix and the SVD one -print(C-X) -!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. - - - -The $U$, $S$, and $V$ matrices returned from the _svd()_ function -cannot be multiplied directly. - -As you can see from the code, the $S$ vector must be converted into a -diagonal matrix. This may cause a problem as the size of the matrices -do not fit the rules of matrix multiplication, where the number of -columns in a matrix must match the number of rows in the subsequent -matrix. - -If you wish to include the zero singular values, you will need to -resize the matrices and set up a diagonal matrix as done in the above -example - - - - - -===== Mathematics of the SVD and implications ===== - -Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies. - -Our starting point is our design matrix $\bm{X}$ of dimension $n\times p$ -!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 - -We can SVD decompose our matrix as -!bt -\[ -\bm{X}=\bm{U}\bm{\Sigma}\bm{V}^T, -\] -!et -where $\bm{U}$ is an orthogonal matrix of dimension $n\times n$, meaning that $\bm{U}\bm{U}^T=\bm{U}^T\bm{U}=\bm{I}_n$. Here $\bm{I}_n$ is the unit matrix of dimension $n \times n$. - -Similarly, $\bm{V}$ is an orthogonal matrix of dimension $p\times p$, meaning that $\bm{V}\bm{V}^T=\bm{V}^T\bm{V}=\bm{I}_p$. Here $\bm{I}_n$ is the unit matrix of dimension $p \times p$. - -Finally $\bm{\Sigma}$ contains the singular values $\sigma_i$. This matrix has dimension $n\times p$ and the singular values $\sigma_i$ are all positive. The non-zero values are ordered in descending order, that is - -!bt -\[ -\sigma_0 > \sigma_1 > \sigma_2 > \dots > \sigma_{p-1} > 0. -\] -!et - -All values beyond $p-1$ are all zero. - - -As an example, consider the following $3\times 2$ example for the matrix $\bm{\Sigma}$ - -!bt -\[ -\bm{\Sigma}= -\begin{bmatrix} -2& 0 \\ -0 & 1 \\ -0 & 0 \\ -\end{bmatrix} -\] -!et - -The singular values are $\sigma_0=2$ and $\sigma_1=1$. It is common to rewrite the matrix $\bm{\Sigma}$ as - -!bt -\[ -\bm{\Sigma}= -\begin{bmatrix} -\bm{\tilde{\Sigma}}\\ -\bm{0}\\ -\end{bmatrix}, -\] -!et - -where -!bt -\[ -\bm{\tilde{\Sigma}}= -\begin{bmatrix} -2& 0 \\ -0 & 1 \\ -\end{bmatrix}, -\] -!et -contains only the singular values. Note also (and we will use this below) that - -!bt -\[ -\bm{\Sigma}^T\bm{\Sigma}= -\begin{bmatrix} -4& 0 \\ -0 & 1 \\ -\end{bmatrix}, -\] -!et -which is a $2\times 2 $ matrix while -!bt -\[ -\bm{\Sigma}\bm{\Sigma}^T= -\begin{bmatrix} -4& 0 & 0\\ -0 & 1 & 0\\ -0 & 0 & 0\\ -\end{bmatrix}, -\] -!et - -is a $3\times 3 $ matrix. The last row and column of this last matrix -contain only zeros. This will have important consequences for our SVD -decomposition of the design matrix. - - - -The matrix that may cause problems for us is $\bm{X}^T\bm{X}$. Using the SVD we can rewrite this matrix as - -!bt -\[ -\bm{X}^T\bm{X}=\bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T, -\] -!et -and using the orthogonality of the matrix $\bm{U}$ we have - -!bt -\[ -\bm{X}^T\bm{X}=\bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T. -\] -!et -We define $\bm{\Sigma}^T\bm{\Sigma}=\tilde{\bm{\Sigma}}^2$ which is a diagonal matrix containing only the singular values squared. It has dimensionality $p \times p$. - -This means, using the orthogonality of $\bm{V}$, that we get - -!bt -\[ -\bm{X}^T\bm{X}=\tilde{\bm{\Sigma}}^2. -\] -!et - -We can now insert the result for the matrix $\bm{X}^T\bm{X}$ into our equation for ordinary least squares where - -!bt -\[ -\tilde{y}_{\mathrm{OLS}}=\bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}, -\] -!et -and using our SVD decomposition of $\bm{X}$ we have - -!bt -\[ -\tilde{y}_{\mathrm{OLS}}=\bm{U}\bm{\Sigma}\bm{V}^T\tilde{\bm{\Sigma}}^{-2}\bm{V}\bm{\Sigma}^T\bm{U}^T\bm{y}, -\] -!et -which gives us, using the orthogonality of the matrices $\bm{U}$ and $\bm{V}$, - -!bt -\[ -\tilde{y}_{\mathrm{OLS}}=\bm{U}\bm{U}^T\bm{y}=\sum_{i=0}^{p-1}\bm{u}_i\bm{u}^T_j\bm{y}, -\] -!et - -Note here that when we perform the multiplication of the various matrices, the orthogonal vectors of the matrix $\bm{U}$ -!bt -\[ -\bm{U}=[\bm{u}_0,\bm{u}_1,\dots,\bm{u}_{n-1}], -\] -!et -that belong to $i>p-1$, result in only zeros when we perform the multiplications. This means that the sum above has non-zero elements only up to $i=p-1$. This corresponds also to the number of singular values (these are all non-zero). - -It means that the ordinary least square model (with the optimal parameters) $\bm{\tilde{y}}$, corresponds to an orthogonal transformation of the output (or target) vector $\bm{y}$ by the vectors of the matrix $\bm{U}$. - - -===== Further properties (important for our analyses later) ===== - -Let us study again $\bm{X}^T\bm{X}$ in terms of our SVD, -!bt -\[ -\bm{X}^T\bm{X}=\bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T=\bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T. -\] -!et - -If we now multiply from the right with $\bm{V}$ (using the orthogonality of $\bm{V}$) we get -!bt -\[ -\left(\bm{X}^T\bm{X}\right)\bm{V}=\bm{V}\bm{\Sigma}^T\bm{\Sigma}. -\] -!et -This means the vectors $\bm{v}_i$ of the orthogonal matrix $\bm{V}$ are the eigenvectors of the matrix $\bm{X}^T\bm{X}$ -with eigenvalues given by the singular values squared, that is -!bt -\[ -\left(\bm{X}^T\bm{X}\right)\bm{v}_i=\bm{v}_i\sigma_i^2. -\] -!et - -Similarly, if we use the SVD decomposition for the matrix $\bm{X}\bm{X}^T$, we have -!bt -\[ -\bm{X}\bm{X}^T=\bm{U}\bm{\Sigma}\bm{V}^T\bm{V}\bm{\Sigma}^T\bm{U}^T=\bm{U}\bm{\Sigma}\bm{\Sigma}^T\bm{U}^T. -\] -!et - -If we now multiply from the right with $\bm{U}$ (using the orthogonality of $\bm{U}$) we get -!bt -\[ -\left(\bm{X}\bm{X}^T\right)\bm{U}=\bm{U}\bm{\Sigma}\bm{\Sigma}^T. -\] -!et -This means the vectors $\bm{u}_i$ of the orthogonal matrix $\bm{U}$ are the eigenvectors of the matrix $\bm{X}\bm{X}^T$ -with eigenvalues given by the singular values squared, that is -!bt -\[ -\left(\bm{X}\bm{X}^T\right)\bm{u}_i=\bm{u}_i\sigma_i^2. -\] -!et - -_Important note_: we have defined our design matrix $\bm{X}$ to be an -$n\times p$ matrix. In most supervised learning cases we have that $n -\ge p$, and quite often we have $n >> p$. For linear algebra based methods like ordinary least squares or Ridge regression, this leads to a matrix $\bm{X}^T\bm{X}$ which is small and thereby easier to handle from a computational point of view (in terms of number of floating point operations). - -In our lectures, the number of columns will -always refer to the number of features in our data set, while the -number of rows represents the number of data inputs. Note that in -other texts you may find the opposite notation. This has consequences -for the definition of for example the covariance matrix and its relation to the SVD. - - -===== Meet the Covariance Matrix ===== - - -Before we move on to a discussion of Ridge and Lasso regression, we want to show an important example of the above. - -We have already noted that the matrix $\bm{X}^T\bm{X}$ in ordinary -least squares is proportional to the second derivative of the cost -function, that is we have - -!bt -\[ -\frac{\partial^2 C(\bm{\beta})}{\partial \bm{\beta}^T\partial \bm{\beta}} =\frac{2}{n}\bm{X}^T\bm{X}. -\] -!et -This quantity defines was what is called the Hessian matrix (the second derivative of a function we want to optimize). - -The Hessian matrix plays an important role and is defined in this course as - -!bt -\[ -\bm{H}=\bm{X}^T\bm{X}. -\] -!et - - -The Hessian matrix for ordinary least squares is also proportional to -the covariance matrix. This means also that we can use the SVD to find -the eigenvalues of the covariance matrix and the Hessian matrix in -terms of the singular values. Let us develop these arguments, as they will play an important role in our machine learning studies. - - - -Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about -the definition of the covariance and the correlation function. These are quantities that play a central role in machine learning methods. - -Suppose we have defined two vectors -$\hat{x}$ and $\hat{y}$ with $n$ elements each. The covariance matrix $\bm{C}$ is defined as -!bt -\[ -\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{cov}[\bm{x},\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\ - \mathrm{cov}[\bm{y},\bm{x}] & \mathrm{cov}[\bm{y},\bm{y}] \\ - \end{bmatrix}, -\] -!et -where for example -!bt -\[ -\mathrm{cov}[\bm{x},\bm{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). -\] -!et -With this definition and recalling that the variance is defined as -!bt -\[ -\mathrm{var}[\bm{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, -\] -!et -we can rewrite the covariance matrix as -!bt -\[ -\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{var}[\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\ - \mathrm{cov}[\bm{x},\bm{y}] & \mathrm{var}[\bm{y}] \\ - \end{bmatrix}. -\] -!et - -_Note:_ we have used $1/n$ in the above definitions of the *sample* variance and covariance. We assume then that we can calculate the exact mean value. -What you will find in essentially all statistics texts are equations -with a factor $1/(n-1)$. This is called "Bessel's correction":"https://mathworld.wolfram.com/BesselsCorrection.html". This -method corrects the bias in the estimation of the population variance -and covariance. It also partially corrects the bias in the estimation -of the population standard deviation. If you use a library like -_Scikit-Learn_ or _nunmpy's_ function calculate the covariance, this -quantity will be computed with a factor $1/(n-1)$. - - -The covariance takes values between zero and infinity and may thus -lead to problems with loss of numerical precision for particularly -large values. It is common to scale the covariance matrix by -introducing instead the correlation matrix defined via the so-called -correlation function - -!bt -\[ -\mathrm{corr}[\bm{x},\bm{y}]=\frac{\mathrm{cov}[\bm{x},\bm{y}]}{\sqrt{\mathrm{var}[\bm{x}] \mathrm{var}[\bm{y}]}}. -\] -!et - -The correlation function is then given by values $\mathrm{corr}[\bm{x},\bm{y}] -\in [-1,1]$. This avoids eventual problems with too large values. We -can then define the correlation matrix for the two vectors $\bm{x}$ -and $\bm{y}$ as - -!bt -\[ -\bm{K}[\bm{x},\bm{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\bm{x},\bm{y}] \\ - \mathrm{corr}[\bm{y},\bm{x}] & 1 \\ - \end{bmatrix}, -\] -!et - -In the above example this is the function we constructed using _pandas_. - - - -In our derivation of the various regression algorithms like _Ordinary Least Squares_ or _Ridge regression_ -we defined the design/feature matrix $\bm{X}$ as - -!bt -\[ -\bm{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}, -\] -!et -with $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors/features $p$ refering to the column numbers and the -entries $n$ being the row elements. -We can rewrite the design/feature matrix in terms of its column vectors as -!bt -\[ -\bm{X}=\begin{bmatrix} \bm{x}_0 & \bm{x}_1 & \bm{x}_2 & \dots & \dots & \bm{x}_{p-1}\end{bmatrix}, -\] -!et -with a given vector -!bt -\[ -\bm{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. -\] -!et - -With these definitions, we can now rewrite our $2\times 2$ -correlation/covariance matrix in terms of a moe general design/feature -matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$. This leads to a $p\times p$ -covariance matrix for the vectors $\bm{x}_i$ with $i=0,1,\dots,p-1$ - -!bt -\[ -\bm{C}[\bm{x}] = \begin{bmatrix} -\mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] & \mathrm{cov}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_0,\bm{x}_{p-1}]\\ -\mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] & \mathrm{cov}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_1,\bm{x}_{p-1}]\\ -\mathrm{cov}[\bm{x}_2,\bm{x}_0] & \mathrm{cov}[\bm{x}_2,\bm{x}_1] & \mathrm{var}[\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_2,\bm{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{cov}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & \mathrm{var}[\bm{x}_{p-1}]\\ -\end{bmatrix}, -\] -!et -and the correlation matrix -!bt -\[ -\bm{K}[\bm{x}] = \begin{bmatrix} -1 & \mathrm{corr}[\bm{x}_0,\bm{x}_1] & \mathrm{corr}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_0,\bm{x}_{p-1}]\\ -\mathrm{corr}[\bm{x}_1,\bm{x}_0] & 1 & \mathrm{corr}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_1,\bm{x}_{p-1}]\\ -\mathrm{corr}[\bm{x}_2,\bm{x}_0] & \mathrm{corr}[\bm{x}_2,\bm{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\bm{x}_2,\bm{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{corr}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & 1\\ -\end{bmatrix}, -\] -!et - - - -The Numpy function _np.cov_ calculates the covariance elements using -the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have -the exact mean values. The following simple function uses the -_np.vstack_ function which takes each vector of dimension $1\times n$ -and produces a $2\times n$ matrix $\bm{W}$ - -Note that this assumes you have the features as the rows, and the inputs as columns, that is -!bt -\[ -\bm{W} = \begin{bmatrix} x_0 & x_1 & x_2 & \dots & x_{n-2} & x_{n-1} \\ - y_0 & y_1 & y_2 & \dots & y_{n-2} & y_{n-1} \\ - \end{bmatrix}, -\] -!et - -which in turn is converted into into the $2\times 2$ covariance matrix -$\bm{C}$ via the Numpy function _np.cov()_. We note that we can also calculate -the mean value of each set of samples $\bm{x}$ etc using the Numpy -function _np.mean(x)_. We can also extract the eigenvalues of the -covariance matrix through the _np.linalg.eig()_ function. - -!bc pycod -# Importing various packages -import numpy as np -n = 100 -x = np.random.normal(size=n) -print(np.mean(x)) -y = 4+3*x+np.random.normal(size=n) -print(np.mean(y)) -W = np.vstack((x, y)) -C = np.cov(W) -print(C) -!ec - - - -The previous example can be converted into the correlation matrix by -simply scaling the matrix elements with the variances. We should also -subtract the mean values for each column. This leads to the following -code which sets up the correlations matrix for the previous example in -a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\times 2$ correlation matrix (since we have only two vectors). - -!bc pycod -import numpy as np -n = 100 -# define two vectors -x = np.random.random(size=n) -y = 4+3*x+np.random.normal(size=n) -#scaling the x and y vectors -x = x - np.mean(x) -y = y - np.mean(y) -variance_x = np.sum(x@x)/n -variance_y = np.sum(y@y)/n -print(variance_x) -print(variance_y) -cov_xy = np.sum(x@y)/n -cov_xx = np.sum(x@x)/n -cov_yy = np.sum(y@y)/n -C = np.zeros((2,2)) -C[0,0]= cov_xx/variance_x -C[1,1]= cov_yy/variance_y -C[0,1]= cov_xy/np.sqrt(variance_y*variance_x) -C[1,0]= C[0,1] -print(C) -!ec - -We see that the matrix elements along the diagonal are one as they -should be and that the matrix is symmetric. Furthermore, diagonalizing -this matrix we easily see that it is a positive definite matrix. - -The above procedure with _numpy_ can be made more compact if we use _pandas_. - - - -We whow here how we can set up the correlation matrix using _pandas_, as done in this simple code -!bc pycod -import numpy as np -import pandas as pd -n = 10 -x = np.random.normal(size=n) -x = x - np.mean(x) -y = 4+3*x+np.random.normal(size=n) -y = y - np.mean(y) -# Note that we transpose the matrix in order to stay with our ordering n x p -X = (np.vstack((x, y))).T -print(X) -Xpd = pd.DataFrame(X) -print(Xpd) -correlation_matrix = Xpd.corr() -print(correlation_matrix) -!ec - - -We expand this model to the Franke function discussed earlier. - - -!bc pycod -# Common imports -import numpy as np -import pandas as pd - - -def FrankeFunction(x,y): - term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) - term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) - term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) - term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) - return term1 + term2 + term3 + term4 - - -def create_X(x, y, n ): - if len(x.shape) > 1: - x = np.ravel(x) - y = np.ravel(y) - - N = len(x) - l = int((n+1)*(n+2)/2) # Number of elements in beta - X = np.ones((N,l)) - - for i in range(1,n+1): - q = int((i)*(i+1)/2) - for k in range(i+1): - X[:,q+k] = (x**(i-k))*(y**k) - - return X - - -# Making meshgrid of datapoints and compute Franke's function -n = 4 -N = 100 -x = np.sort(np.random.uniform(0, 1, N)) -y = np.sort(np.random.uniform(0, 1, N)) -z = FrankeFunction(x, y) -X = create_X(x, y, n=n) - -Xpd = pd.DataFrame(X) -# subtract the mean values and set up the covariance matrix -Xpd = Xpd - Xpd.mean() -covariance_matrix = Xpd.cov() -print(covariance_matrix) -!ec - -We note here that the covariance is zero for the first rows and -columns since all matrix elements in the design matrix were set to one -(we are fitting the function in terms of a polynomial of degree $n$). - -This means that the variance for these elements will be zero and will -cause problems when we set up the correlation matrix. We can simply -drop these elements and construct a correlation -matrix without these elements. - - - -We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\bm{X}$ as -!bt -\[ -\bm{C}[\bm{x}] = \frac{1}{n}\bm{X}^T\bm{X}= \mathbb{E}[\bm{X}^T\bm{X}]. -\] -!et - -To see this let us simply look at a design matrix $\bm{X}\in {\mathbb{R}}^{2\times 2}$ -!bt -\[ -\bm{X}=\begin{bmatrix} -x_{00} & x_{01}\\ -x_{10} & x_{11}\\ -\end{bmatrix}=\begin{bmatrix} -\bm{x}_{0} & \bm{x}_{1}\\ -\end{bmatrix}. -\] -!et - -If we then compute the expectation value (note the $1/n$ factor instead of $1/(n-1)$) -!bt -\[ -\mathbb{E}[\bm{X}^T\bm{X}] = \frac{1}{n}\bm{X}^T\bm{X}=\frac{1}{n}\begin{bmatrix} -x_{00}^2+x_{10}^2 & x_{00}x_{01}+x_{10}x_{11}\\ -x_{01}x_{00}+x_{11}x_{10} & x_{01}^2+x_{11}^2\\ -\end{bmatrix}, -\] -!et -which is just -!bt -\[ -\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]=\begin{bmatrix} \mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] \\ - \mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] \\ - \end{bmatrix}, -\] -!et -where we wrote $$\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]$$ to indicate that this is the covariance of the vectors $\bm{x}$ of the design/feature matrix $\bm{X}$. - -It is easy to generalize this to a matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$. - - - -===== Linking with the SVD ===== - -We saw earlier that -!bt -\[ -\bm{X}^T\bm{X}=\bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T=\bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T. -\] -!et -Since the matrices here have dimension $p\times p$, with $p$ corresponding to the singular values, we defined earlier the matrix -!bt -\[ -\bm{\Sigma}^T\bm{\Sigma} = \begin{bmatrix} \tilde{\bm{\Sigma}} & \bm{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\bm{\Sigma}} \\ \bm{0}\\ \end{bmatrix}, -\] -!et -where the tilde-matrix $\tilde{\bm{\Sigma}}$ is a matrix of dimension $p\times p$ containing only the singular values $\sigma_i$, that is - -!bt -\[ -\tilde{\bm{\Sigma}}=\begin{bmatrix} \sigma_0 & 0 & 0 & \dots & 0 & 0 \\ - 0 & \sigma_1 & 0 & \dots & 0 & 0 \\ - 0 & 0 & \sigma_2 & \dots & 0 & 0 \\ - 0 & 0 & 0 & \dots & \sigma_{p-2} & 0 \\ - 0 & 0 & 0 & \dots & 0 & \sigma_{p-1} \\ -\end{bmatrix}, -\] -!et -meaning we can write -!bt -\[ -\bm{X}^T\bm{X}=\bm{V}\tilde{\bm{\Sigma}}^2\bm{V}^T. -\] -!et -Multiplying from the right with $\bm{V}$ (using the orthogonality of $\bm{V}$) we get -!bt -\[ -\left(\bm{X}^T\bm{X}\right)\bm{V}=\bm{V}\tilde{\bm{\Sigma}}^2. -\] -!et - - -This means the vectors $\bm{v}_i$ of the orthogonal matrix $\bm{V}$ -are the eigenvectors of the matrix $\bm{X}^T\bm{X}$ with eigenvalues -given by the singular values squared, that is - -!bt -\[ -\left(\bm{X}^T\bm{X}\right)\bm{v}_i=\bm{v}_i\sigma_i^2. -\] -!et - -In other words, each non-zero singular value of $\bm{X}$ is a positive -square root of an eigenvalue of $\bm{X}^T\bm{X}$. It means also that -the columns of $\bm{V}$ are the eigenvectors of -$\bm{X}^T\bm{X}$. Since we have ordered the singular values of -$\bm{X}$ in a descending order, it means that the column vectors -$\bm{v}_i$ are hierarchically ordered by how much correlation they -encode from the columns of $\bm{X}$. - - -Note that these are also the eigenvectors and eigenvalues of the -Hessian matrix. - -If we now recall the definition of the covariance matrix (not using -Bessel's correction) we have - - -!bt -\[ -\bm{C}[\bm{X}]=\frac{1}{n}\bm{X}^T\bm{X}, -\] -!et - -meaning that every squared non-singular value of $\bm{X}$ divided by $n$ ( -the number of samples) are the eigenvalues of the covariance -matrix. Every singular value of $\bm{X}$ is thus a positive square -root of an eigenvalue of $\bm{X}^T\bm{X}$. If the matrix $\bm{X}$ is -self-adjoint, the singular values of $\bm{X}$ are equal to the -absolute value of the eigenvalues of $\bm{X}$. - - -For $\bm{X}\bm{X}^T$ we found - -!bt -\[ -\bm{X}\bm{X}^T=\bm{U}\bm{\Sigma}\bm{V}^T\bm{V}\bm{\Sigma}^T\bm{U}^T=\bm{U}\bm{\Sigma}^T\bm{\Sigma}\bm{U}^T. -\] -!et -Since the matrices here have dimension $n\times n$, we have -!bt -\[ -\bm{\Sigma}\bm{\Sigma}^T = \begin{bmatrix} \tilde{\bm{\Sigma}} \\ \bm{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\bm{\Sigma}} \bm{0}\\ \end{bmatrix}=\begin{bmatrix} \tilde{\bm{\Sigma}} & \bm{0} \\ \bm{0} & \bm{0}\\ \end{bmatrix}, -\] -!et -leading to -!bt -\[ -\bm{X}\bm{X}^T=\bm{U}\begin{bmatrix} \tilde{\bm{\Sigma}} & \bm{0} \\ \bm{0} & \bm{0}\\ \end{bmatrix}\bm{U}^T. -\] -!et - -Multiplying with $\bm{U}$ from the right gives us the eigenvalue problem -!bt -\[ -(\bm{X}\bm{X}^T)\bm{U}=\bm{U}\begin{bmatrix} \tilde{\bm{\Sigma}} & \bm{0} \\ \bm{0} & \bm{0}\\ \end{bmatrix}. -\] -!et - -It means that the eigenvalues of $\bm{X}\bm{X}^T$ are again given by -the non-zero singular values plus now a series of zeros. The column -vectors of $\bm{U}$ are the eigenvectors of $\bm{X}\bm{X}^T$ and -measure how much correlations are contained in the rows of $\bm{X}$. - -Since we will mainly be interested in the correlations among the features -of our data (the columns of $\bm{X}$, the quantity of interest for us are the non-zero singular -values and the column vectors of $\bm{V}$. - - - -===== Ridge and LASSO Regression ===== - -Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is -our optimization problem is -!bt -\[ -{\displaystyle \min_{\bm{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}. -\] -!et -or we can state it as -!bt -\[ -{\displaystyle \min_{\bm{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2, -\] -!et -where we have used the definition of a norm-2 vector, that is -!bt -\[ -\vert\vert \bm{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. -\] -!et - -By minimizing the above equation with respect to the parameters -$\bm{\beta}$ we could then obtain an analytical expression for the -parameters $\bm{\beta}$. We can add a regularization parameter $\lambda$ by -defining a new cost function to be optimized, that is - -!bt -\[ -{\displaystyle \min_{\bm{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_2^2 -\] -!et - -which leads to the Ridge regression minimization problem where we -require that $\vert\vert \bm{\beta}\vert\vert_2^2\le t$, where $t$ is -a finite number larger than zero. By defining - -!bt -\[ -C(\bm{X},\bm{\beta})=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1, -\] -!et - -we have a new optimization equation -!bt -\[ -{\displaystyle \min_{\bm{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1 -\] -!et -which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. - -Here we have defined the norm-1 as -!bt -\[ -\vert\vert \bm{x}\vert\vert_1 = \sum_i \vert x_i\vert. -\] -!et - - - -Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have - -!bt -\[ -C(\bm{X},\bm{\beta})=\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\bm{\beta}^T\bm{\beta}, -\] -!et -and -taking the derivatives with respect to $\bm{\beta}$ we obtain then -a slightly modified matrix inversion problem which for finite values -of $\lambda$ does not suffer from singularity problems. We obtain -the optimal parameters -!bt -\[ -\hat{\bm{\beta}}_{\mathrm{Ridge}} = \left(\bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}, -\] -!et - -with $\bm{I}$ being a $p\times p$ identity matrix with the constraint that - -!bt -\[ -\sum_{i=0}^{p-1} \beta_i^2 \leq t, -\] -!et - -with $t$ a finite positive number. - -When we compare this with the ordinary least squares result we have -!bt -\[ -\hat{\bm{\beta}}_{\mathrm{OLS}} = \left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}, -\] -!et -which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\bm{X}^T\bm{X}$. - - -We see that Ridge regression is nothing but the standard OLS with a -modified diagonal term added to $\bm{X}^T\bm{X}$. The consequences, in -particular for our discussion of the bias-variance tradeoff are rather -interesting. We will see that for specific values of $\lambda$, we may -even reduce the variance of the optimal parameters $\bm{\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here. - -Using our insights about the SVD of the design matrix $\bm{X}$ -We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\bm{U}$ as -!bt -\[ -\tilde{\bm{y}}_{\mathrm{OLS}}=\bm{X}\bm{\beta} =\bm{U}\bm{U}^T\bm{y}. -\] -!et - - -For Ridge regression this becomes - -!bt -\[ -\tilde{\bm{y}}_{\mathrm{Ridge}}=\bm{X}\bm{\beta}_{\mathrm{Ridge}} = \bm{U\Sigma V^T}\left(\bm{V}\bm{\Sigma}^2\bm{V}^T+\lambda\bm{I} \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\sum_{j=0}^{p-1}\bm{u}_j\bm{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\bm{y}, -\] -!et - -with the vectors $\bm{u}_j$ being the columns of $\bm{U}$ from the SVD of the matrix $\bm{X}$. - - -Since $\lambda \geq 0$, it means that compared to OLS, we have - -!bt -\[ -\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1. -\] -!et - -Ridge regression finds the coordinates of $\bm{y}$ with respect to the -orthonormal basis $\bm{U}$, it then shrinks the coordinates by -$\frac{\sigma_j^2}{\sigma_j^2+\lambda}$. Recall that the SVD has -eigenvalues ordered in a descending way, that is $\sigma_i \geq -\sigma_{i+1}$. - -For small eigenvalues $\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods. - - - -For the sake of simplicity, let us assume that the design matrix is orthonormal, that is - -!bt -\[ -\bm{X}^T\bm{X}=(\bm{X}^T\bm{X})^{-1} =\bm{I}. -\] -!et - -In this case the standard OLS results in -!bt -\[ -\bm{\beta}^{\mathrm{OLS}} = \bm{X}^T\bm{y}=\sum_{i=0}^{p-1}\bm{u}_j\bm{u}_j^T\bm{y}, -\] -!et - -and - -!bt -\[ -\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{I}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}=\left(1+\lambda\right)^{-1}\bm{\beta}^{\mathrm{OLS}}, -\] -!et - -that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\lambda$, and -the Ridge estimator converges to zero when the hyperparameter goes to -infinity. - -We will come back to more interpreations after we have gone through some of the statistical analysis part. - -For more discussions of Ridge and Lasso regression, "Wessel van Wieringen's":"https://arxiv.org/abs/1509.09169" article is highly recommended. -Similarly, "Mehta et al's article":"https://arxiv.org/abs/1803.08823" is also recommended. - - -Using the matrix-vector expression for Lasso regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have the following _cost_ function - -!bt -\[ -C(\bm{X},\bm{\beta})=\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\vert\vert\bm{\beta}\vert\vert_1, -\] -!et - -Taking the derivative with respect to $\bm{\beta}$ and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty) -!bt -\[ -\frac{d \vert \beta\vert}{d \bm{\beta}}=\mathrm{sgn}(\bm{\beta})=\left\{\begin{array}{cc} 1 & \beta > 0 \\ 0 & \beta =0\\-1 & \beta < 0, \end{array}\right. -\] -!et -we have that the derivative of the cost function is - -!bt -\[ -\frac{\partial C(\bm{X},\bm{\beta})}{\partial \bm{\beta}}=-2\bm{X}^T(\bm{y}-\bm{X}\bm{\beta})+\lambda sgn(\bm{\beta})=0, -\] -!et -and reordering we have -!bt -\[ -\bm{X}^T\bm{X}\bm{\beta})+\lambda sgn(\bm{\beta})=2\bm{X}^T(\bm{y}. -\] -!et -This equation does not lead to a nice analytical equation as in either Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms using for example the Python package "CVXOPT":"https://cvxopt.org/". We will discuss this below. - -===== Code for SVD and Inversion of Matrices ===== - -How do we use the SVD to invert a matrix $\bm{X}^\bm{X}$ which is singular or near singular? -The simple answer is to use the linear algebra function for the pseudoinverse, that is -!bc pycod -#Ainv = np.linlag.pinv(A) -!ec - -Let us first look at a matrix which does not causes problems and write our own function where we just use the SVD. - -!bc pycod -import numpy as np -# SVD inversion -def SVDinv(A): - ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD). - SVD is numerically more stable than the inversion algorithms provided by - numpy and scipy.linalg at the cost of being slower. - ''' - U, s, VT = np.linalg.svd(A) - print('test U') - print( (np.transpose(U) @ U - U @np.transpose(U))) - print('test VT') - print( (np.transpose(VT) @ VT - VT @np.transpose(VT))) - - - D = np.zeros((len(U),len(VT))) - D = np.diag(s) - UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D) - return np.matmul(V,np.matmul(invD,UT)) - - -#X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ]) -# Non-singular square matrix -X = np.array( [ [1,2,3],[2,4,5],[3,5,6]]) -print(X) -A = np.transpose(X) @ X -# Brute force inversion -B = np.linalg.inv(A) # here we could use np.linalg.pinv(A) -C = SVDinv(A) -print(np.abs(B-C)) - -!ec - - -Although our matrix to invert $\bm{X}^T\bm{X}$ is a square matrix, our matrix may be singular. - -The pseudoinverse is the generalization of the matrix inverse for square matrices to -rectangular matrices where the number of rows and columns are not equal. - -It is also called the the Moore-Penrose Inverse after two independent discoverers of the method or the Generalized Inverse. -It is used for the calculation of the inverse for singular or near singular matrices and for rectangular matrices. - -Using the SVD we can obtain the pseudoinverse of a matrix $\bm{A}$ (labeled here as $\bm{A}_{\mathrm{PI}}$ -!bt -\[ -\bm{A}_{\mathrm{PI}}= \bm{V}\bm{D}_{\mathrm{PI}}\bm{U}^T, -\] -!et -where $\bm{D}_{\mathrm{PI}}$ can be calculated by creating a diagonal matrix from $\bm{Sigma}$ where we only keep the singular values (the non-zero values). The following code computes the pseudoinvers of the matrix based on the SVD. - - -!bc pycod -import numpy as np -# SVD inversion -def SVDinv(A): - U, s, VT = np.linalg.svd(A) - # reciprocals of singular values of s - d = 1.0 / s - # create m x n D matrix - D = np.zeros(A.shape) - # populate D with n x n diagonal matrix - D[:A.shape[1], :A.shape[1]] = np.diag(d) - UT = np.transpose(U) - V = np.transpose(VT) - return np.matmul(V,np.matmul(D.T,UT)) - - -A = np.array([ [0.3, 0.4], [0.5, 0.6], [0.7, 0.8],[0.9, 1.0]]) -print(A) -# Brute force inversion of super-collinear matrix -B = np.linalg.pinv(A) -print(B) -# Compare our own algorithm with pinv -C = SVDinv(A) -print(np.abs(C-B)) - -!ec -As you can see from this example, our own decomposition based on the SVD agrees the pseudoinverse algorithm provided by _Numpy_. - - - -===== Deriving the Ridge Regression Equations ===== - -Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is -our optimization problem is -!bt -\[ -{\displaystyle \min_{\bm{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}. -\] -!et -or we can state it as -!bt -\[ -{\displaystyle \min_{\bm{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2, -\] -!et -where we have used the definition of a norm-2 vector, that is -!bt -\[ -\vert\vert \bm{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. -\] -!et - - - -By minimizing the above equation with respect to the parameters -$\bm{\beta}$ we could then obtain an analytical expression for the -parameters $\bm{\beta}$. We can add a regularization parameter $\lambda$ by -defining a new cost function to be optimized, that is - -!bt -\[ -{\displaystyle \min_{\bm{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_2^2 -\] -!et - -which leads to the Ridge regression minimization problem where we -require that $\vert\vert \bm{\beta}\vert\vert_2^2\le t$, where $t$ is -a finite number larger than zero. By defining - -!bt -\[ -C(\bm{X},\bm{\beta})=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1, -\] -!et - -we have a new optimization equation -!bt -\[ -{\displaystyle \min_{\bm{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1 -\] -!et -which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. - -Here we have defined the norm-1 as -!bt -\[ -\vert\vert \bm{x}\vert\vert_1 = \sum_i \vert x_i\vert. -\] -!et - - - - - -Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have - -!bt -\[ -C(\bm{X},\bm{\beta})=\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\bm{\beta}^T\bm{\beta}, -\] -!et -and -taking the derivatives with respect to $\bm{\beta}$ we obtain then -a slightly modified matrix inversion problem which for finite values -of $\lambda$ does not suffer from singularity problems. We obtain -the optimal parameters -!bt -\[ -\hat{\bm{\beta}}_{\mathrm{Ridge}} = \left(\bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}, -\] -!et - -with $\bm{I}$ being a $p\times p$ identity matrix with the constraint that - -!bt -\[ -\sum_{i=0}^{p-1} \beta_i^2 \leq t, -\] -!et - -with $t$ a finite positive number. - -When we compare this with the ordinary least squares result we have -!bt -\[ -\hat{\bm{\beta}}_{\mathrm{OLS}} = \left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}, -\] -!et -which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\bm{X}^T\bm{X}$. - - -We see that Ridge regression is nothing but the standard OLS with a -modified diagonal term added to $\bm{X}^T\bm{X}$. The consequences, in -particular for our discussion of the bias-variance tradeoff are rather -interesting. We will see that for specific values of $\lambda$, we may -even reduce the variance of the optimal parameters $\bm{\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here. - - - -Using our insights about the SVD of the design matrix $\bm{X}$ -We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\bm{U}$ as -!bt -\[ -\tilde{\bm{y}}_{\mathrm{OLS}}=\bm{X}\bm{\beta} =\bm{U}\bm{U}^T\bm{y}. -\] -!et - - -For Ridge regression this becomes - -!bt -\[ -\tilde{\bm{y}}_{\mathrm{Ridge}}=\bm{X}\bm{\beta}_{\mathrm{Ridge}} = \bm{U\Sigma V^T}\left(\bm{V}\bm{\Sigma}^2\bm{V}^T+\lambda\bm{I} \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\sum_{j=0}^{p-1}\bm{u}_j\bm{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\bm{y}, -\] -!et - -with the vectors $\bm{u}_j$ being the columns of $\bm{U}$ from the SVD of the matrix $\bm{X}$. - - - -Since $\lambda \geq 0$, it means that compared to OLS, we have - -!bt -\[ -\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1. -\] -!et - -Ridge regression finds the coordinates of $\bm{y}$ with respect to the -orthonormal basis $\bm{U}$, it then shrinks the coordinates by -$\frac{\sigma_j^2}{\sigma_j^2+\lambda}$. Recall that the SVD has -eigenvalues ordered in a descending way, that is $\sigma_i \geq -\sigma_{i+1}$. - -For small eigenvalues $\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods. - - - -For the sake of simplicity, let us assume that the design matrix is orthonormal, that is - -!bt -\[ -\bm{X}^T\bm{X}=(\bm{X}^T\bm{X})^{-1} =\bm{I}. -\] -!et - -In this case the standard OLS results in -!bt -\[ -\bm{\beta}^{\mathrm{OLS}} = \bm{X}^T\bm{y}=\sum_{i=0}^{p-1}\bm{u}_j\bm{u}_j^T\bm{y}, -\] -!et - -and - -!bt -\[ -\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{I}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}=\left(1+\lambda\right)^{-1}\bm{\beta}^{\mathrm{OLS}}, -\] -!et - -that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\lambda$, and -the Ridge estimator converges to zero when the hyperparameter goes to -infinity. - -We will come back to more interpreations after we have gone through some of the statistical analysis part. - - - -Using the matrix-vector expression for Lasso regression and dropping the parameter $1/n$ in front of the standard mean squared error equation, we have the following _cost_ function - -!bt -\[ -C(\bm{X},\bm{\beta})=\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\vert\vert\bm{\beta}\vert\vert_1, -\] -!et - -Taking the derivative with respect to $\bm{\beta}$ and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty) -!bt -\[ -\frac{d \vert \beta\vert}{d \bm{\beta}}=\mathrm{sgn}(\bm{\beta})=\left\{\begin{array}{cc} 1 & \beta > 0 \\ 0 & \beta =0\\-1 & \beta < 0, \end{array}\right. -\] -!et -we have that the derivative of the cost function is - -!bt -\[ -\frac{\partial C(\bm{X},\bm{\beta})}{\partial \bm{\beta}}=-2\bm{X}^T(\bm{y}-\bm{X}\bm{\beta})+\lambda sgn(\bm{\beta})=0, -\] -!et -and reordering we have -!bt -\[ -\bm{X}^T\bm{X}\bm{\beta}+\lambda sgn(\bm{\beta})=2\bm{X}^T\bm{y}. -\] -!et -This equation does not lead to a nice analytical equation as in Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms using for example the Python package "CVXOPT":"https://cvxopt.org/". We will discuss this later. - - - - - -Let us assume that our design matrix is given by unit (identity) matrix, that is a square diagonal matrix with ones only along the -diagonal. In this case we have an equal number of rows and columns $n=p$. - -Our model approximation is just $\tilde{\bm{y}}=\bm{\beta}$ and the mean squared error and thereby the cost function for ordinary least sqquares (OLS) is then (we drop the term $1/n$) -!bt -\[ -C(\bm{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2, -\] -!et -and minimizing we have that -!bt -\[ -\hat{\beta}_i^{\mathrm{OLS}} = y_i. -\] -!et - - -For Ridge regression our cost function is -!bt -\[ -C(\bm{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\beta_i^2, -\] -!et -and minimizing we have that -!bt -\[ -\hat{\beta}_i^{\mathrm{Ridge}} = \frac{y_i}{1+\lambda}. -\] -!et - - -For Lasso regression our cost function is -!bt -\[ -C(\bm{\beta})=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\vert\beta_i\vert=\sum_{i=0}^{p-1}(y_i-\beta_i)^2+\lambda\sum_{i=0}^{p-1}\sqrt{\beta_i^2}, -\] -!et -and minimizing we have that -!bt -\[ --2\sum_{i=0}^{p-1}(y_i-\beta_i)+\lambda \sum_{i=0}^{p-1}\frac{(\beta_i)}{\vert\beta_i\vert}=0, -\] -!et -which leads to -!bt -\[ -\hat{\bm{\beta}}_i^{\mathrm{Lasso}} = \left\{\begin{array}{ccc}y_i-\frac{\lambda}{2} &\mathrm{if} & y_i> \frac{\lambda}{2}\\ - y_i+\frac{\lambda}{2} &\mathrm{if} & y_i< -\frac{\lambda}{2}\\ - 0 &\mathrm{if} & \vert y_i\vert\le \frac{\lambda}{2}\end{array}\right.\\. -\] -!et - -Plotting these results ("figure in handwritten notes for week 36":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2021/NotesSeptember9.pdf") shows clearly that Lasso regression suppresses (sets to zero) values of $\beta_i$ for specific values of $\lambda$. Ridge regression reduces on the other hand the values of $\beta_i$ as function of $\lambda$. - - -As another examples, -let us assume we have a data set with outputs/targets given by the vector - -!bt -\[ -\bm{y}=\begin{bmatrix}4 \\ 2 \\3\end{bmatrix}, -\] -!et -and our inputs as a $3\times 2$ design matrix -!bt -\[ -\bm{X}=\begin{bmatrix}2 & 0\\ 0 & 1 \\ 0 & 0\end{bmatrix}, -\] -!et -meaning that we have two features and two unknown parameters $\beta_0$ and $\beta_1$ to be determined either by ordinary least squares, Ridge or Lasso regression. - - -For ordinary least squares (OLS) we know that the optimal solution is - -!bt -\[ -\hat{\bm{\beta}}^{\mathrm{OLS}}=\left( \bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. -\] -!et -Inserting the above values we obtain that - -!bt -\[ -\hat{\bm{\beta}}^{\mathrm{OLS}}=\begin{bmatrix}2 \\ 2\end{bmatrix}, -\] -!et - -The code which implements this simpler case is presented after the discussion of Ridge and Lasso. - - -For Ridge regression we have - -!bt -\[ -\hat{\bm{\beta}}^{\mathrm{Ridge}}=\left( \bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}. -\] -!et -Inserting the above values we obtain that - -!bt -\[ -\hat{\bm{\beta}}^{\mathrm{Ridge}}=\begin{bmatrix}\frac{8}{4+\lambda} \\ \frac{2}{1+\lambda}\end{bmatrix}, -\] -!et - -There is normally a constraint on the value of $\vert\vert \bm{\beta}\vert\vert_2$ via the parameter $\lambda$. -Let us for simplicity assume that $\beta_0^2+\beta_1^2=1$ as constraint. This will allow us to find an expression for the optimal values of $\beta$ and $\lambda$. - -To see this, let us write the cost function for Ridge regression. - - - -We define the MSE without the $1/n$ factor and have then, using that -!bt -\[ -\bm{X}\bm{\beta}=\begin{bmatrix} 2\beta_0 \\ \beta_1 \\0 \end{bmatrix}, -\] -!et - -!bt -\[ -C(\bm{\beta})=(4-2\beta_0)^2+(2-\beta_1)^2+\lambda(\beta_0^2+\beta_1^2), -\] -!et -and taking the derivative with respect to $\beta_0$ we get -!bt -\[ -\beta_0=\frac{8}{4+\lambda}, -\] -!et -and for $\beta_1$ we obtain -!bt -\[ -\beta_1=\frac{2}{1+\lambda}, -\] -!et - -Using the constraint for $\beta_0^2+\beta_1^2=1$ we can constrain $\lambda$ by solving -!bt -\[ -\left(\frac{8}{4+\lambda}\right)^2+\left(\frac{2}{1+\lambda}\right)^2=1, -\] -!et -which gives $\lambda=4.571$ and $\beta_0=0.933$ and $\beta_1=0.359$. - - -For Lasso we need now, keeping a constraint on $\vert\beta_0\vert+\vert\beta_1\vert=1$, to take the derivative of the absolute values of $\beta_0$ -and $\beta_1$. This gives us the following derivatives of the cost function -!bt -\[ -C(\bm{\beta})=(4-2\beta_0)^2+(2-\beta_1)^2+\lambda(\vert\beta_0\vert+\vert\beta_1\vert), -\] -!et - -!bt -\[ -\frac{\partial C(\bm{\beta})}{\partial \beta_0}=-4(4-2\beta_0)+\lambda\mathrm{sgn}(\beta_0)=0, -\] -!et -and -!bt -\[ -\frac{\partial C(\bm{\beta})}{\partial \beta_1}=-2(2-\beta_1)+\lambda\mathrm{sgn}(\beta_1)=0. -\] -!et -We have now four cases to solve besides the trivial cases $\beta_0$ and/or $\beta_1$ are zero, namely -o $\beta_0 > 0$ and $\beta_1 > 0$, -o $\beta_0 > 0$ and $\beta_1 < 0$, -o $\beta_0 < 0$ and $\beta_1 > 0$, -o $\beta_0 < 0$ and $\beta_1 < 0$. - - -If we consider the first case, we have then -!bt -\[ --4(4-2\beta_0)+\lambda=0, -\] -!et -and -!bt -\[ --2(2-\beta_1)+\lambda=0. -\] -!et -which yields - -!bt -\[ -\beta_0=\frac{16+\lambda}{8}, -\] -!et -and -!bt -\[ -\beta_1=\frac{4+\lambda}{2}. -\] -!et - -Using the constraint on $\beta_0$ and $\beta_1$ we can then find the optimal value of $\lambda$ for the different cases. We leave this as an exercise to you. - - -Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of $\lambda$, meaning that we need to perform a search in order to find the optimal values. - -First we study and compare the OLS and Ridge results. The next code compares all three methods. - - -!bc pycod -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt - -def R2(y_data, y_model): - return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2) -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n - - -# A seed just to ensure that the random numbers are the same for every run. -# Useful for eventual debugging. - -X = np.array( [ [ 2, 0], [0, 1], [0,0]]) -y = np.array( [4, 2, 3]) - - -# matrix inversion to find beta -OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y -print(OLSbeta) -# and then make the prediction -ytildeOLS = X @ OLSbeta -print("Training MSE for OLS") -print(MSE(y,ytildeOLS)) -ypredictOLS = X @ OLSbeta - -# Repeat now for Ridge regression and various values of the regularization parameter -I = np.eye(2,2) -# Decide which values of lambda to use -nlambdas = 100 -MSEPredict = np.zeros(nlambdas) -lambdas = np.logspace(-4, 4, nlambdas) -for i in range(nlambdas): - lmb = lambdas[i] - Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y -# print(Ridgebeta) - # and then make the prediction - ypredictRidge = X @ Ridgebeta - MSEPredict[i] = MSE(y,ypredictRidge) -# print(MSEPredict[i]) - # Now plot the results -plt.figure() -plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Train') -plt.xlabel('log10(lambda)') -plt.ylabel('MSE') -plt.legend() -plt.show() - -!ec - -We see here that we reach a plateau. What is actually happening? - - - -!bc pycod -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from sklearn import linear_model - -def R2(y_data, y_model): - return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2) -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n - - -# A seed just to ensure that the random numbers are the same for every run. -# Useful for eventual debugging. - -X = np.array( [ [ 2, 0], [0, 1], [0,0]]) -y = np.array( [4, 2, 3]) - - -# matrix inversion to find beta -OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y -print(OLSbeta) -# and then make the prediction -ytildeOLS = X @ OLSbeta -print("Training MSE for OLS") -print(MSE(y,ytildeOLS)) -ypredictOLS = X @ OLSbeta - -# Repeat now for Ridge regression and various values of the regularization parameter -I = np.eye(2,2) -# Decide which values of lambda to use -nlambdas = 100 -MSERidgePredict = np.zeros(nlambdas) -MSELassoPredict = np.zeros(nlambdas) -lambdas = np.logspace(-4, 4, nlambdas) -for i in range(nlambdas): - lmb = lambdas[i] - Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y - print(Ridgebeta) - # and then make the prediction - ypredictRidge = X @ Ridgebeta - MSERidgePredict[i] = MSE(y,ypredictRidge) - RegLasso = linear_model.Lasso(lmb) - RegLasso.fit(X,y) - ypredictLasso = RegLasso.predict(X) - print(RegLasso.coef_) - MSELassoPredict[i] = MSE(y,ypredictLasso) -# Now plot the results -plt.figure() -plt.plot(np.log10(lambdas), MSERidgePredict, 'r--', label = 'MSE Ridge Train') -plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Train') -plt.xlabel('log10(lambda)') -plt.ylabel('MSE') -plt.legend() -plt.show() - -!ec - - -Another Example, now with a polynomial fit. - -!bc pycod -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from sklearn.model_selection import train_test_split -from sklearn import linear_model - -def R2(y_data, y_model): - return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2) -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n - - -# A seed just to ensure that the random numbers are the same for every run. -# Useful for eventual debugging. -np.random.seed(3155) - -x = np.random.rand(100) -y = 2.0+5*x*x+0.1*np.random.randn(100) - -# number of features p (here degree of polynomial -p = 3 -# The design matrix now as function of a given polynomial -X = np.zeros((len(x),p)) -X[:,0] = 1.0 -X[:,1] = x -X[:,2] = x*x -# We split the data in test and training data -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) - -# matrix inversion to find beta -OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train -print(OLSbeta) -# and then make the prediction -ytildeOLS = X_train @ OLSbeta -print("Training MSE for OLS") -print(MSE(y_train,ytildeOLS)) -ypredictOLS = X_test @ OLSbeta -print("Test MSE OLS") -print(MSE(y_test,ypredictOLS)) - -# Repeat now for Lasso and Ridge regression and various values of the regularization parameter -I = np.eye(p,p) -# Decide which values of lambda to use -nlambdas = 100 -MSEPredict = np.zeros(nlambdas) -MSETrain = np.zeros(nlambdas) -MSELassoPredict = np.zeros(nlambdas) -MSELassoTrain = np.zeros(nlambdas) -lambdas = np.logspace(-4, 4, nlambdas) -for i in range(nlambdas): - lmb = lambdas[i] - Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train - # include lasso using Scikit-Learn - RegLasso = linear_model.Lasso(lmb) - RegLasso.fit(X_train,y_train) - # and then make the prediction - ytildeRidge = X_train @ Ridgebeta - ypredictRidge = X_test @ Ridgebeta - ytildeLasso = RegLasso.predict(X_train) - ypredictLasso = RegLasso.predict(X_test) - MSEPredict[i] = MSE(y_test,ypredictRidge) - MSETrain[i] = MSE(y_train,ytildeRidge) - MSELassoPredict[i] = MSE(y_test,ypredictLasso) - MSELassoTrain[i] = MSE(y_train,ytildeLasso) - -# Now plot the results -plt.figure() -plt.plot(np.log10(lambdas), MSETrain, label = 'MSE Ridge train') -plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Test') -plt.plot(np.log10(lambdas), MSELassoTrain, label = 'MSE Lasso train') -plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Test') - -plt.xlabel('log10(lambda)') -plt.ylabel('MSE') -plt.legend() -plt.show() - -!ec - -As a small addendum, we note that you can also solve this problem using the convex optimization package "CVXOPT":"https://cvxopt.org/examples/mlbook/l1regls.html". This requires, in addition to having installed _CVXOPT_, you need to download the file *l1regl.py*. -The following code example solves the simpler problem we discussed above, where we have added the latter python file. - -!bc pycod -from l1regls import l1regls -from cvxopt import matrix, normal -import numpy as np - -X = matrix( [ [ 2, 0, 1], [0, 1, 3]]) -y = matrix( [4, 2, 3]) -x = l1regls(X,y) - -from cvxopt import matrix, spdiag, mul, div, sqrt, normal, setseed -from cvxopt import blas, lapack, solvers, sparse, spmatrix -import math - -try: - import mosek - import sys - __MOSEK = True -except: __MOSEK = False - -if __MOSEK: - - def l1regls_mosek(A, b): - """ - - Returns the solution of l1-norm regularized least-squares problem - - minimize || A*x - b ||_2^2 + e'*u - - subject to -u <= x <= u - - """ - - m, n = A.size - - env = mosek.Env() - task = env.Task(0,0) - task.set_Stream(mosek.streamtype.log, lambda x: sys.stdout.write(x)) - - task.appendvars( 2*n) # number of variables - task.appendcons( 2*n) # number of constraints - - # input quadratic objective - Q = matrix(0.0, (n,n)) - blas.syrk(A, Q, alpha = 2.0, trans='T') - - I = [] - for i in range(n): - I.extend(range(i,n)) - - J = [] - for i in range(n): - J.extend((n-i)*[i]) - - task.putqobj(I, J, list(Q[matrix(I) + matrix(J)*n])) - task.putclist(range(2*n), list(-2*A.T*b) + n*[1.0]) # setup linear objective - - # input constraint matrix row by row - for i in range(n): - task.putarow( i, [i, n+i], [1.0, -1.0]) - task.putarow( n+i, [i, n+i], [1.0, 1.0]) - - # setup bounds on constraints - task.putboundslice(mosek.accmode.con, - 0, n, n*[mosek.boundkey.up], n*[0.0], n*[0.0]) - task.putboundslice(mosek.accmode.con, - n, 2*n, n*[mosek.boundkey.lo], n*[0.0], n*[0.0]) - - # setup variable bounds - task.putboundslice(mosek.accmode.var, - 0, 2*n, 2*n*[mosek.boundkey.fr], 2*n*[0.0], 2*n*[0.0]) - - # optimize the task - task.putobjsense(mosek.objsense.minimize) - task.optimize() - task.solutionsummary(mosek.streamtype.log) - x = n*[0.0] - task.getsolutionslice(mosek.soltype.itr, mosek.solitem.xx, 0, n, x) - - return matrix(x) - - def l1regls_mosek2(A, b): - """ - - Returns the solution of l1-norm regularized least-squares problem - - minimize w'*w + e'*u - - subject to -u <= x <= u - - A*x - w = b - - """ - - m, n = A.size - - env = mosek.Env() - task = env.Task(0,0) - task.set_Stream(mosek.streamtype.log, lambda x: sys.stdout.write(x)) - - task.appendvars(2*n + m) # number of variables - task.appendcons(2*n + m) # number of constraints - - # input quadratic objective - task.putqobj(range(2*n,2*n+m), range(2*n,2*n+m), m*[2.0]) - - task.putclist(range(2*n+m), n*[0.0] + n*[1.0] + m*[0.0]) # setup linear objective - - # input constraint matrix row by row - for i in range(n): - task.putarow( i, [i, n+i], [1.0, -1.0]) - task.putarow( n+i, [i, n+i], [1.0, 1.0]) - - for i in range(m): - task.putarow( 2*n+i, range(n) + [2*n+i], list(A[i,:]) + [-1.0]) - - # setup bounds on constraints - task.putboundslice(mosek.accmode.con, - 0, n, n*[mosek.boundkey.up], n*[0.0], n*[0.0]) - task.putboundslice(mosek.accmode.con, - n, 2*n, n*[mosek.boundkey.lo], n*[0.0], n*[0.0]) - task.putboundslice(mosek.accmode.con, - 2*n, 2*n+m, m*[mosek.boundkey.fx], list(b), list(b)) - - # setup variable bounds - task.putboundslice(mosek.accmode.var, 0, 2*n+m, (2*n+m)*[mosek.boundkey.fr], - (2*n+m)*[0.0], (2*n+m)*[0.0]) - - # optimize the task - task.putobjsense(mosek.objsense.minimize) - task.optimize() - task.solutionsummary(mosek.streamtype.log) - x = n*[0.0] - task.getsolutionslice(mosek.soltype.itr, mosek.solitem.xx, 0, n, x) - - return matrix(x) - -def l1regls(A, b): - """ - Returns the solution of l1-norm regularized least-squares problem - - minimize || A*x - b ||_2^2 + || x ||_1. +* 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. - """ - - m, n = A.size - q = matrix(1.0, (2*n,1)) - q[:n] = -2.0 * A.T * b - - def P(u, v, alpha = 1.0, beta = 0.0 ): - """ - v := alpha * 2.0 * [ A'*A, 0; 0, 0 ] * u + beta * v - """ - v *= beta - v[:n] += alpha * 2.0 * A.T * (A * u[:n]) +===== Reminder on Statistics ===== - def G(u, v, alpha=1.0, beta=0.0, trans='N'): - """ - v := alpha*[I, -I; -I, -I] * u + beta * v (trans = 'N' or 'T') - """ - - v *= beta - v[:n] += alpha*(u[:n] - u[n:]) - v[n:] += alpha*(-u[:n] - u[n:]) - - h = matrix(0.0, (2*n,1)) - - - # Customized solver for the KKT system - # - # [ 2.0*A'*A 0 I -I ] [x[:n] ] [bx[:n] ] - # [ 0 0 -I -I ] [x[n:] ] = [bx[n:] ]. - # [ I -I -D1^-1 0 ] [zl[:n]] [bzl[:n]] - # [ -I -I 0 -D2^-1 ] [zl[n:]] [bzl[n:]] - # - # where D1 = W['di'][:n]**2, D2 = W['di'][:n]**2. - # - # We first eliminate zl and x[n:]: - # - # ( 2*A'*A + 4*D1*D2*(D1+D2)^-1 ) * x[:n] = - # bx[:n] - (D2-D1)*(D1+D2)^-1 * bx[n:] + - # D1 * ( I + (D2-D1)*(D1+D2)^-1 ) * bzl[:n] - - # D2 * ( I - (D2-D1)*(D1+D2)^-1 ) * bzl[n:] - # - # x[n:] = (D1+D2)^-1 * ( bx[n:] - D1*bzl[:n] - D2*bzl[n:] ) - # - (D2-D1)*(D1+D2)^-1 * x[:n] - # - # zl[:n] = D1 * ( x[:n] - x[n:] - bzl[:n] ) - # zl[n:] = D2 * (-x[:n] - x[n:] - bzl[n:] ). - # - # The first equation has the form - # - # (A'*A + D)*x[:n] = rhs - # - # and is equivalent to - # - # [ D A' ] [ x:n] ] = [ rhs ] - # [ A -I ] [ v ] [ 0 ]. - # - # It can be solved as - # - # ( A*D^-1*A' + I ) * v = A * D^-1 * rhs - # x[:n] = D^-1 * ( rhs - A'*v ). - - S = matrix(0.0, (m,m)) - Asc = matrix(0.0, (m,n)) - v = matrix(0.0, (m,1)) - - def Fkkt(W): - - # Factor - # - # S = A*D^-1*A' + I - # - # where D = 2*D1*D2*(D1+D2)^-1, D1 = d[:n]**-2, D2 = d[n:]**-2. - - d1, d2 = W['di'][:n]**2, W['di'][n:]**2 - - # ds is square root of diagonal of D - ds = math.sqrt(2.0) * div( mul( W['di'][:n], W['di'][n:]), - sqrt(d1+d2) ) - d3 = div(d2 - d1, d1 + d2) - - # Asc = A*diag(d)^-1/2 - Asc = A * spdiag(ds**-1) - - # S = I + A * D^-1 * A' - blas.syrk(Asc, S) - S[::m+1] += 1.0 - lapack.potrf(S) - - def g(x, y, z): - - x[:n] = 0.5 * ( x[:n] - mul(d3, x[n:]) + - mul(d1, z[:n] + mul(d3, z[:n])) - mul(d2, z[n:] - - mul(d3, z[n:])) ) - x[:n] = div( x[:n], ds) - - # Solve - # - # S * v = 0.5 * A * D^-1 * ( bx[:n] - - # (D2-D1)*(D1+D2)^-1 * bx[n:] + - # D1 * ( I + (D2-D1)*(D1+D2)^-1 ) * bzl[:n] - - # D2 * ( I - (D2-D1)*(D1+D2)^-1 ) * bzl[n:] ) - - blas.gemv(Asc, x, v) - lapack.potrs(S, v) - - # x[:n] = D^-1 * ( rhs - A'*v ). - blas.gemv(Asc, v, x, alpha=-1.0, beta=1.0, trans='T') - x[:n] = div(x[:n], ds) - - # x[n:] = (D1+D2)^-1 * ( bx[n:] - D1*bzl[:n] - D2*bzl[n:] ) - # - (D2-D1)*(D1+D2)^-1 * x[:n] - x[n:] = div( x[n:] - mul(d1, z[:n]) - mul(d2, z[n:]), d1+d2 )\ - - mul( d3, x[:n] ) - - # zl[:n] = D1^1/2 * ( x[:n] - x[n:] - bzl[:n] ) - # zl[n:] = D2^1/2 * ( -x[:n] - x[n:] - bzl[n:] ). - z[:n] = mul( W['di'][:n], x[:n] - x[n:] - z[:n] ) - z[n:] = mul( W['di'][n:], -x[:n] - x[n:] - z[n:] ) - - return g - - return solvers.coneqp(P, q, G, h, kktsolver = Fkkt)['x'][:n] - - -!ec - - -===== Linking the regression analysis with a statistical interpretation ===== - -We will now couple the discussions of ordinary least squares, Ridge -and Lasso regression with a statistical interpretation, that is we -move from a linear algebra analysis to a statistical analysis. In -particular, we will focus on what the regularization terms can result -in. We will amongst other things show that the regularization -parameter can reduce considerably the variance of the parameters -$\beta$. - +* As in other experiments, many numerical experiments have two classes of errors: + * Statistical errors + * Systematical errors +* Statistical errors can be estimated using standard tools from statistics +* Systematical errors are method specific and must be treated differently from case to case. The advantage of doing linear regression is that we actually end up with @@ -2283,7 +81,6 @@ notation above $\mathbf{X}_{i,\ast}$ means that we are looking at the row number $i$ and perform a sum over all values $p$. - The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off) that there exists a function $f(\bm{x})$ and a normal distributed error $\bm{\varepsilon}\sim \mathcal{N}(0, \sigma^2)$ which describe our data @@ -2369,7 +166,8 @@ where we have used that $\mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) = \sigma^2 \, \mathbf{I}_{nn}$. From $\mbox{Var}(\bm{\beta}) = \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}$, one obtains an estimate of the variance of the estimate of the $j$-th regression coefficient: -$\bm{\sigma}^2 (\bm{\beta}_j ) = \bm{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} $. This may be used to +$\bm{\sigma}^2 (\bm{\beta}_j ) = \bm{\sigma}^2 \sqrt{ +[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} }$. This may be used to construct a confidence interval for the estimates. @@ -2408,325 +206,861 @@ This means the variance we obtain with the standard OLS will always for $\lambda -===== Deriving OLS from a probability distribution ===== +===== Resampling methods ===== -Our basic assumption when we derived the OLS equations was to assume -that our output is determined by a given continuous function -$f(\bm{x})$ and a random noise $\bm{\epsilon}$ given by the normal -distribution with zero mean value and an undetermined variance -$\sigma^2$. +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. -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 +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. + + + +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 $\bm{x} = (x_1,x_2,\cdots,X_n)$. +Let $\bm{x}_i$ denote the vector !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]}. +\bm{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), \] !et +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$. -We assume now that the various $y_i$ values are stochastically distributed according to the above Gaussian distribution. -We define this distribution as + + +!bc pycod +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) + +!ec + + +=== 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: +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). + + + +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. + + + +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 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})$. + + +But +unless there is enough information available about the process that +generated $X_1,X_2,\cdots,X_n$, $p(x)$ is in general +unknown. Therefore, "Efron in 1979":"https://projecteuclid.org/euclid.aos/1176344552" asked the +question: What if we replace $p(x)$ by the relative frequency +of the observation $X_i$; if we draw observations in accordance with +the relative frequency of the observations, will we obtain the same +result in some asymptotic sense? The answer is yes. + + +Instead of generating the histogram for the relative +frequency of the observation $X_i$, just draw the values +$(X_1^*,X_2^*,\cdots,X_n^*)$ with replacement from the vector +$\bm{X}$. + + +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 ^*$. + + + +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. + + +!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 + +# 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() + +!ec + + + +===== Various steps in cross-validation ===== + +When the repetitive splitting of the data set is done randomly, +samples may accidently end up in a fast majority of the splits in +either training or test set. Such samples may have an unbalanced +influence on either model building or prediction evaluation. To avoid +this $k$-fold cross-validation structures the data splitting. The +samples are divided into $k$ more or less equally sized exhaustive and +mutually exclusive subsets. In turn (at each split) one of these +subsets plays the role of the test set while the union of the +remaining subsets constitutes the training set. Such a splitting +warrants a balanced representation of each sample in both training and +test set over the splits. Still the division into the $k$ subsets +involves a degree of randomness. This may be fully excluded when +choosing $k=n$. This particular case is referred to as leave-one-out +cross-validation (LOOCV). + + +* Define a range of interest for the penalty parameter. + +* Divide the data set into training and test set comprising samples $\{1, \ldots, n\} \setminus i$ and $\{ i \}$, respectively. + +* Fit the linear regression model by means of ridge estimation for each $\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\bm{\sigma}_{-i}^2(\lambda)$, 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}$. +\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 -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 +* 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 -\[ -p(\bm{y},\bm{X}\vert\bm{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\bm{X}\vert\bm{\beta}). -\] -!et - -We will write this in a more compact form reserving $\bm{D}$ for the domain of events, including the ouputs (targets) and the inputs. That is -in case we have a simple one-dimensional input and output case -!bt -\[ -\bm{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})]. -\] -!et -In the more general case the various inputs should be replaced by the possible features represented by the input data set $\bm{X}$. -We can now rewrite the above probability as -!bt -\[ -p(\bm{D}\vert\bm{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}. -\] -!et - -It is a conditional probability (see below) and reads as the likelihood of a domain of events $\bm{D}$ given a set of parameters $\bm{\beta}$. - - -In statistics, maximum likelihood estimation (MLE) is a method of -estimating the parameters of an assumed probability distribution, -given some observed data. This is achieved by maximizing a likelihood -function so that, under the assumed statistical model, the observed -data is the most probable. - - -We will assume here that our events are given by the above Gaussian -distribution and we will determine the optimal parameters $\beta$ by -maximizing the above PDF. However, computing the derivatives of a -product function is cumbersome and can easily lead to overflow and/or -underflowproblems, with potentials for loss of numerical precision. - - -In practice, it is more convenient to maximize the logarithm of the -PDF because it is a monotonically increasing function of the argument. -Alternatively, and this will be our option, we will minimize the -negative of the logarithm since this is a monotonically decreasing -function. - -Note also that maximization/minimization of the logarithm of the PDF -is equivalent to the maximization/minimization of the function itself. - - - - -We could now define a new cost function to minimize, namely the negative logarithm of the above PDF - -!bt -\[ -C(\bm{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\bm{X}\vert\bm{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\bm{X}\vert\bm{\beta})}, -\] -!et -which becomes -!bt -\[ -C(\bm{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}. -\] -!et - -Taking the derivative of the *new* cost function with respect to the parameters $\beta$ we recognize our familiar OLS equation, namely - -!bt -\[ -\bm{X}^T\left(\bm{y}-\bm{X}\bm{\beta}\right) =0, -\] -!et -which leads to the well-known OLS equation for the optimal paramters $\beta$ -!bt -\[ -\hat{\bm{\beta}}^{\mathrm{OLS}}=\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}! -\] +\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 -Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics. +For the various values of $k$ - -A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry. -Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics. - -Assume we have two domains of events $X=[x_0,x_1,\dots,x_{n-1}]$ and $Y=[y_0,y_1,\dots,y_{n-1}]$. - -We define also the likelihood for $X$ and $Y$ as $p(X)$ and $p(Y)$ respectively. -The likelihood of a specific event $x_i$ (or $y_i$) is then written as $p(X=x_i)$ or just $p(x_i)=p_i$. - -!bblock Union of events is given by -!bt -\[ -p(X \cup Y)= p(X)+p(Y)-p(X \cap Y). -\] -!et -!eblock - - -!bblock The product rule (aka joint probability) is given by -!bt -\[ -p(X \cup Y)= p(X,Y)= p(X\vert Y)p(Y)=p(Y\vert X)p(X), -\] -!et -where we read $p(X\vert Y)$ as the likelihood of obtaining $X$ given $Y$. -!eblock - -If we have independent events then $p(X,Y)=p(X)p(Y)$. +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 -The marginal probability is defined in terms of only one of the set of variables $X,Y$. For a discrete probability we have -!bblock -!bt -\[ -p(X)=\sum_{i=0}^{n-1}p(X,Y=y_i)=\sum_{i=0}^{n-1}p(X\vert Y=y_i)p(Y=y_i)=\sum_{i=0}^{n-1}p(X\vert y_i)p(y_i). -\] -!et -!eblock - - - -The conditional probability, if $p(Y) > 0$, is -!bblock -!bt -\[ -p(X\vert Y)= \frac{p(X,Y)}{p(Y)}=\frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}. -\] -!et -!eblock - - - -If we combine the conditional probability with the marginal probability and the standard product rule, we have -!bt -\[ -p(X\vert Y)= \frac{p(X,Y)}{p(Y)}, -\] -!et -which we can rewrite as - -!bt -\[ -p(X\vert Y)= \frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}=\frac{p(Y\vert X)p(X)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}, -\] -!et -which is Bayes' theorem. It allows us to evaluate the uncertainty in in $X$ after we have observed $Y$. We can easily interchange $X$ with $Y$. - - -The quantity $p(Y\vert X)$ on the right-hand side of the theorem is -evaluated for the observed data $Y$ and can be viewed as a function of -the parameter space represented by $X$. This function is not -necesseraly normalized and is normally called the likelihood function. - -The function $p(X)$ on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution. - -Let us try to illustrate Bayes' theorem through an example. - - -Let us suppose that you are undergoing a series of mammography scans in -order to rule out possible breast cancer cases. We define the -sensitivity for a positive event by the variable $X$. It takes binary -values with $X=1$ representing a positive event and $X=0$ being a -negative event. We reserve $Y$ as a classification parameter for -either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing). - -We let $Y=1$ represent the the case of having breast cancer and $Y=0$ as not. - -Let us assume that if you have breast cancer, the test will be positive with a probability of $0.8$, that is we have - -!bt -\[ -p(X=1\vert Y=1) =0.8. -\] -!et - -This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of $80\%$ for having cancer. -It is however not correct, as the following Bayesian analysis shows. - - -If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number. -Let us assume that the prior probability in the population as a whole is - -!bt -\[ -p(Y=1) =0.004. -\] -!et - -We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have -!bt -\[ -p(X=1\vert Y=0) =0.1. -\] -!et - -Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute - -!bt -\[ -p(Y=1\vert X=1)=\frac{p(X=1\vert Y=1)p(Y=1)}{p(X=1\vert Y=1)p(Y=1)+p(X=1\vert Y=0)p(Y=0)}=\frac{0.8\times 0.004}{0.8\times 0.004+0.1\times 0.996}=0.031. -\] -!et -That is, in case of a positive test, there is only a $3\%$ chance of having breast cancer! - - - -===== Bayes' Theorem and Ridge and Lasso Regression ===== - -Hitherto we have discussed Ridge and Lasso regression in terms of a -linear analysis. This may to many of you feel rather technical and -perhaps not that intuitive. The question is whether we can develop a -more intuitive way of understanding what Ridge and Lasso express. - -Before we proceed let us perform a Ridge, Lasso and OLS analysis of a polynomial fit. - - -We will play around with a study of the values for the optimal -parameters $\bm{\beta}$ using OLS, Ridge and Lasso regression. For -OLS, you will notice as function of the noise and polynomial degree, -that the parameters $\beta$ will fluctuate from order to order in the -polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS. - -For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one. +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 import matplotlib.pyplot as plt -from sklearn.model_selection import train_test_split -from sklearn import linear_model +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 -def R2(y_data, y_model): - return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2) -def MSE(y_data,y_model): - n = np.size(y_model) - return np.sum((y_data-y_model)**2)/n +# A seed just to ensure that the random numbers are the same for every run. +# Useful for eventual debugging. +np.random.seed(3155) + +# 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() + +!ec + + + +===== 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}$. + + + + +!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. -n = 10000 -x = np.random.rand(n) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n) +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) -Maxpolydegree = 5 -X = np.zeros((len(x),Maxpolydegree)) +# 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 + + + +!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 + + + +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. + + +!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 + + + +!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) + +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) + +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) + +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) + +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) + +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') + +infile = open(data_path("EoS.csv"),'r') + +# Read the EoS data as csv file and organize the data into two arrays with density and energies +EoS = pd.read_csv(infile, names=('Density', 'Energy')) +EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') +EoS = EoS.dropna() +Energies = EoS['Energy'] +Density = EoS['Density'] +# The design matrix now as function of various polytrops + +Maxpolydegree = 30 +X = np.zeros((len(Density),Maxpolydegree)) X[:,0] = 1.0 +testerror = np.zeros(Maxpolydegree) +trainingerror = np.zeros(Maxpolydegree) +polynomial = np.zeros(Maxpolydegree) + +trials = 100 +for polydegree in range(1, Maxpolydegree): + polynomial[polydegree] = polydegree + for degree in range(polydegree): + X[:,degree] = Density**(degree/3.0) + +# loop over trials in order to estimate the expectation value of the MSE + testerror[polydegree] = 0.0 + trainingerror[polydegree] = 0.0 + for samples in range(trials): + x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2) + model = LinearRegression(fit_intercept=True).fit(x_train, y_train) + ypred = model.predict(x_train) + ytilde = model.predict(x_test) + testerror[polydegree] += mean_squared_error(y_test, ytilde) + trainingerror[polydegree] += mean_squared_error(y_train, ypred) + + testerror[polydegree] /= trials + trainingerror[polydegree] /= trials + print("Degree of polynomial: %3d"% polynomial[polydegree]) + print("Mean squared error on training data: %.8f" % trainingerror[polydegree]) + print("Mean squared error on test data: %.8f" % testerror[polydegree]) + +plt.plot(polynomial, np.log10(trainingerror), label='Training Error') +plt.plot(polynomial, np.log10(testerror), label='Test Error') +plt.xlabel('Polynomial degree') +plt.ylabel('log10[MSE]') +plt.legend() +plt.show() + +!ec + + + +!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] = x**(degree) + 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 -# 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) +!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) -# 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 +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), MSERidgePredict, 'b', label = 'MSE Ridge Test') -plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test') +plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score') plt.xlabel('log10(lambda)') plt.ylabel('MSE') plt.legend() @@ -2735,119 +1069,4 @@ plt.show() !ec -How can we understand this? - - - -Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression. - -For ordinary least squares we postulated that the maximum likelihood for the doamin of events $\bm{D}$ (one-dimensional case) -!bt -\[ -\bm{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})], -\] -!et -is given by -!bt -\[ -p(\bm{D}\vert\bm{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}. -\] -!et - -In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set $\bm{\beta}$ given a domain of events $\bm{D}$? That is, how can we define the posterior probability - -!bt -\[ -p(\bm{\beta}\vert\bm{D}). -\] -!et - -Bayes' theorem comes to our rescue here since (omitting the normalization constant) -!bt -\[ -p(\bm{\beta}\vert\bm{D})\propto p(\bm{D}\vert\bm{\beta})p(\bm{\beta}). -\] -!et - -We have a model for $p(\bm{D}\vert\bm{\beta})$ but need one for the _prior_ $p(\bm{\beta}$! - - - -With the posterior probability defined by a likelihood which we have -already modeled and an unknown prior, we are now ready to make -additional models for the prior. - -We can, based on our discussions of the variance of $\bm{\beta}$ and the mean value, assume that the prior for the values $\bm{\beta}$ is given by a Gaussian with mean value zero and variance $\tau^2$, that is - -!bt -\[ -p(\bm{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}. -\] -!et - -Our posterior probability becomes then (omitting the normalization factor which is just a constant) -!bt -\[ -p(\bm{\beta\vert\bm{D})}=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}. -\] -!et - - -We can now optimize this quantity with respect to $\bm{\beta}$. As we -did for OLS, this is most conveniently done by taking the negative -logarithm of the posterior probability. Doing so and leaving out the -constants terms that do not depend on $\beta$, we have - - -!bt -\[ -C(\bm{\beta})=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{2\tau^2}\vert\vert\bm{\beta}\vert\vert_2^2, -\] -!et -and replacing $1/2\tau^2$ with $\lambda$ we have - -!bt -\[ -C(\bm{\beta})=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\bm{\beta}\vert\vert_2^2, -\] -!et -which is our Ridge cost function! Nice, isn't it? - - -To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution ("Laplace in this case":"https://en.wikipedia.org/wiki/Laplace_distribution") with zero mean value, that is - -!bt -\[ -p(\bm{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}. -\] -!et - -Our posterior probability becomes then (omitting the normalization factor which is just a constant) -!bt -\[ -p(\bm{\beta}\vert\bm{D})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\bm{X}_{i,*}\bm{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}. -\] -!et - - -Taking the negative -logarithm of the posterior probability and leaving out the -constants terms that do not depend on $\beta$, we have - - -!bt -\[ -C(\bm{\beta}=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{\tau}\vert\vert\bm{\beta}\vert\vert_1, -\] -!et -and replacing $1/\tau$ with $\lambda$ we have - -!bt -\[ -C(\bm{\beta}=\frac{\vert\vert (\bm{y}-\bm{X}\bm{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\bm{\beta}\vert\vert_1, -\] -!et -which is our Lasso cost function! - - diff --git a/doc/BookChapters/chapter5.dlog b/doc/BookChapters/chapter5.dlog deleted file mode 100644 index 521ee8c4a..000000000 --- a/doc/BookChapters/chapter5.dlog +++ /dev/null @@ -1,30 +0,0 @@ -*** error: file has a mako construction ${\cal L}' - but seemingly no definition in <%...%>' - (it is not a command-line given mako variable either). - However, if this is a variable in a Makefile or Bash script - run with --no_mako - and you cannot use mako and Makefile or Bash variables - in the same document! - -Translating doconce text in chapter5.do.txt to ipynb -*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. -Failed to remove ans_at_end environment -Failed to remove sol_at_end environment -output in chapter5.ipynb diff --git a/doc/BookChapters/chapter6.dlog b/doc/BookChapters/chapter6.dlog deleted file mode 100644 index 454f04e74..000000000 --- a/doc/BookChapters/chapter6.dlog +++ /dev/null @@ -1,5 +0,0 @@ -Translating doconce text in chapter6.do.txt to ipynb -ERROR: 0 !bblock do not match 1 !eblock directives -Failed to remove ans_at_end environment -Failed to remove sol_at_end environment -output in chapter6.ipynb diff --git a/doc/BookChapters/chapter7.dlog b/doc/BookChapters/chapter7.dlog deleted file mode 100644 index b6e00dcff..000000000 --- a/doc/BookChapters/chapter7.dlog +++ /dev/null @@ -1,12 +0,0 @@ -*** error: file has a mako construction ${\cal C}' - but seemingly no definition in <%...%>' - (it is not a command-line given mako variable either). - However, if this is a variable in a Makefile or Bash script - run with --no_mako - and you cannot use mako and Makefile or Bash variables - in the same document! - -Translating doconce text in chapter7.do.txt to ipynb -*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) -Failed to remove ans_at_end environment -Failed to remove sol_at_end environment -output in chapter7.ipynb diff --git a/doc/BookChapters/chapter8.dlog b/doc/BookChapters/chapter8.dlog deleted file mode 100644 index 56f30f7ea..000000000 --- a/doc/BookChapters/chapter8.dlog +++ /dev/null @@ -1,33 +0,0 @@ -Translating doconce text in chapter8.do.txt to ipynb -*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. -Failed to remove ans_at_end environment -Failed to remove sol_at_end environment -output in chapter8.ipynb diff --git a/doc/BookChapters/chapter9.dlog b/doc/BookChapters/chapter9.dlog deleted file mode 100644 index 0965bb1ac..000000000 --- a/doc/BookChapters/chapter9.dlog +++ /dev/null @@ -1,4 +0,0 @@ -Translating doconce text in chapter9.do.txt to ipynb -Failed to remove ans_at_end environment -Failed to remove sol_at_end environment -output in chapter9.ipynb diff --git a/doc/BookChapters/linalg.dlog b/doc/BookChapters/linalg.dlog deleted file mode 100644 index 1ca3c89c3..000000000 --- a/doc/BookChapters/linalg.dlog +++ /dev/null @@ -1,22 +0,0 @@ -Translating doconce text in linalg.do.txt to ipynb - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. - -*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments. -Failed to remove ans_at_end environment -Failed to remove sol_at_end environment -output in linalg.ipynb diff --git a/doc/BookChapters/statistics.dlog b/doc/BookChapters/statistics.dlog deleted file mode 100644 index 2800d3164..000000000 --- a/doc/BookChapters/statistics.dlog +++ /dev/null @@ -1,4 +0,0 @@ -Translating doconce text in statistics.do.txt to ipynb -Failed to remove ans_at_end environment -Failed to remove sol_at_end environment -output in statistics.ipynb diff --git a/doc/LectureNotes/DataFiles/chddata.csv b/doc/LectureNotes/DataFiles/chddata.csv new file mode 100644 index 000000000..7f44183c7 --- /dev/null +++ b/doc/LectureNotes/DataFiles/chddata.csv @@ -0,0 +1,100 @@ +1, 21, 1, 0 +2, 23, 1, 0 +3, 25, 1, 1 +4, 29, 1, 0 +5, 21, 1, 0 +6, 24, 1, 0 +7, 27, 1, 0 +8, 29, 1, 0 +9, 28, 1, 0 +10, 26, 1, 0 +11, 30, 2, 0 +12, 31, 2, 0 +13, 31, 2, 0 +14, 31, 2, 1 +15, 32, 2, 0 +16, 34, 2, 0 +17, 34, 2, 0 +18, 31, 2, 0 +19, 32, 2, 0 +20, 32, 2, 0 +21, 33, 2, 0 +22, 34, 2, 0 +23, 31, 2, 1 +24, 30, 2, 0 +25, 33, 2, 0 +26, 36, 3, 1 +27, 35, 3, 0 +28, 35, 3, 0 +29, 38, 3, 0 +30, 37, 3, 1 +31, 36, 3, 0 +32, 35, 3, 0 +33, 39, 3, 0 +34, 39, 3, 0 +35, 38, 3, 1 +36, 37, 3, 0 +37, 37, 3, 0 +38, 40, 4, 0 +39, 41, 4, 1 +40, 44, 4, 0 +41, 44, 4, 0 +42, 43, 4, 1 +43, 42, 4, 0 +44, 41, 4, 0 +45, 40, 4, 1 +46, 42, 4, 0 +47, 42, 4, 0 +48, 43, 4, 0 +49, 44, 4, 1 +50, 44, 4, 0 +51, 42, 4, 0 +52, 41, 4, 1 +53, 45, 5, 0 +54, 45, 5, 1 +55, 49, 5, 0 +56, 48, 5, 1 +57, 47, 5, 0 +58, 49, 5, 1 +59, 46, 5, 1 +60, 45, 5, 0 +61, 49, 5, 1 +62, 48, 5, 0 +63, 47, 5, 1 +64, 46, 5, 0 +65, 47, 5, 0 +66, 50, 6, 1 +67, 51, 6, 1 +68, 51, 6, 0 +69, 54, 6, 1 +70, 53, 6, 1 +71, 51, 6, 0 +72, 52, 6, 1 +73, 54, 6, 0 +74, 55, 7, 1 +75, 56, 7, 1 +76, 58, 7, 0 +77, 59, 7, 1 +78, 59, 7, 1 +79, 58, 7, 0 +80, 55, 7, 1 +81, 56, 7, 1 +82, 57, 7, 1 +83, 58, 7, 1 +84, 59, 7, 0 +85, 55, 7, 1 +86, 56, 7, 1 +87, 57, 7, 1 +88, 58, 7, 0 +89, 59, 7, 1 +90, 56, 7, 1 +91, 60, 8, 1 +92, 65, 8, 1 +93, 67, 8, 1 +94, 66, 8, 0 +95, 63, 8, 1 +96, 61, 8, 1 +97, 69, 8, 1 +98, 65, 8, 1 +99, 64, 8, 1 +100, 63, 8, 0 \ No newline at end of file diff --git a/doc/LectureNotes/chapter1.ipynb b/doc/LectureNotes/chapter1.ipynb index 756ce7708..c930e0a6b 100644 --- a/doc/LectureNotes/chapter1.ipynb +++ b/doc/LectureNotes/chapter1.ipynb @@ -6,8 +6,6 @@ "source": [ "# Linear Regression\n", "\n", - "[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h20/forelesningsvideoer/LectureAug21.mp4?vrtx=view-as-webpage)\n", - "\n", "\n", "## Introduction\n", "\n", @@ -15,7 +13,7 @@ "\n", "\n", "\n", - "Our emphasis throughout this series of lectures (small change) \n", + "Our emphasis throughout this series of lectures \n", "is on understanding the mathematical aspects of\n", "different algorithms used in the fields of data analysis and machine learning. \n", "\n", @@ -235,7 +233,9 @@ "\n", "## Simple linear regression model using **scikit-learn**\n", "\n", - "We start with perhaps our simplest possible example, using **Scikit-Learn** to perform linear regression analysis on a data set produced by us. \n", + "We start with perhaps our simplest possible example, using\n", + "**Scikit-Learn** to perform linear regression analysis on a data set\n", + "produced by us.\n", "\n", "What follows is a simple Python code where we have defined a function\n", "$y$ in terms of the variable $x$. Both are defined as vectors with $100$ entries. \n", @@ -437,7 +437,8 @@ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from sklearn.linear_model import LinearRegression\n", - "\n", + "# Number of data points\n", + "n = 100\n", "x = np.random.rand(100,1)\n", "y = 5*x+0.01*np.random.randn(100,1)\n", "linreg = LinearRegression()\n", @@ -459,7 +460,8 @@ "Depending on the parameter in front of the normal distribution, we may\n", "have a small or larger relative error. Try to play around with\n", "different training data sets and study (graphically) the value of the\n", - "relative error.\n", + "relative error. Note also that **Scikit-Learn** requires a matrix as input for the input values $x$ and $y$. In the above code we have\n", + "solved this by declaring $x$ and $y$ as arrays of dimension $n\\times 1$.\n", "\n", "As mentioned above, **Scikit-Learn** has an impressive functionality.\n", "We can for example extract the values of $\\alpha$ and $\\beta$ and\n", @@ -629,8 +631,7 @@ "metadata": {}, "source": [ "$$\n", - "H_{\\delta}(\\boldsymbol{a})=\\left\\{\\begin{array}{cc}\\frac{1}{2} \\boldsymbol{a}^{2}& \\text{for }|\\boldsymbol{a}|\\leq \\delta\\\\ \\delta (|\\b\\\n", - "m{a}|-\\frac{1}{2}\\delta ),&\\text{otherwise}.\\end{array}\\right.\n", + "H_{\\delta}(\\boldsymbol{a})=\\left\\{\\begin{array}{cc}\\frac{1}{2} \\boldsymbol{a}^{2}& \\text{for }|\\boldsymbol{a}|\\leq \\delta\\\\ \\delta (|\\boldsymbol{a}|-\\frac{1}{2}\\delta ),&\\text{otherwise}.\\end{array}\\right.\n", "$$" ] }, @@ -641,6 +642,8 @@ "Here $\\boldsymbol{a}=\\boldsymbol{y} - \\boldsymbol{\\tilde{y}}$.\n", "\n", "\n", + "\n", + "\n", "We will discuss in more\n", "detail these and other functions in the various lectures. We conclude this part with another example. Instead of \n", "a linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn." @@ -1061,6 +1064,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "Note well that we have made life simple here. We perform a fit in terms of the number of nucleons only. A more sophisticated fit can be done by including an explicit dependence on the number of protons and neutrons in the asymmetry and Coulomb terms.\n", + "\n", "With **scikitlearn** we are now ready to use linear regression and fit our data." ] }, @@ -1100,7 +1105,6 @@ "print('Variance score: %.2f' % r2_score(Energies, fity))\n", "# Mean absolute error \n", "print('Mean absolute error: %.2f' % mean_absolute_error(Energies, fity))\n", - "print(clf.coef_, clf.intercept_)\n", "\n", "Masses['Eapprox'] = fity\n", "# Generate a plot comparing the experimental with the fitted values values.\n", @@ -3046,6 +3050,119 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "## Splitting our Data in Training and Test data\n", + "\n", + "\n", + "It is normal in essentially all Machine Learning studies to split the\n", + "data in a training set and a test set (sometimes also an additional\n", + "validation set). **Scikit-Learn** has an own function for this. There\n", + "is no explicit recipe for how much data should be included as training\n", + "data and say test data. An accepted rule of thumb is to use\n", + "approximately $2/3$ to $4/5$ of the data as training data. We will\n", + "postpone a discussion of this splitting to the end of these notes and\n", + "our discussion of the so-called **bias-variance** tradeoff. Here we\n", + "limit ourselves to repeat the above equation of state fitting example\n", + "but now splitting the data into a training set and a test set.\n", + "\n", + "Let us study some examples. The first code here takes a simple\n", + "one-dimensional second-order polynomial and we fit it to a\n", + "second-order polynomial. Depending on the strength of the added noise,\n", + "the various measures like the $R2$ score or the mean-squared error,\n", + "the fit becomes better or worse." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import os\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "\n", + "def R2(y_data, y_model):\n", + " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", + "def MSE(y_data,y_model):\n", + " n = np.size(y_model)\n", + " return np.sum((y_data-y_model)**2)/n\n", + "\n", + "x = np.random.rand(100)\n", + "y = 2.0+5*x*x+0.1*np.random.randn(100)\n", + "\n", + "\n", + "# The design matrix now as function of a given polynomial\n", + "X = np.zeros((len(x),3))\n", + "X[:,0] = 1.0\n", + "X[:,1] = x\n", + "X[:,2] = x**2\n", + "# We split the data in test and training data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", + "# matrix inversion to find beta\n", + "beta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n", + "print(beta)\n", + "# and then make the prediction\n", + "ytilde = X_train @ beta\n", + "print(\"Training R2\")\n", + "print(R2(y_train,ytilde))\n", + "print(\"Training MSE\")\n", + "print(MSE(y_train,ytilde))\n", + "ypredict = X_test @ beta\n", + "print(\"Test R2\")\n", + "print(R2(y_test,ypredict))\n", + "print(\"Test MSE\")\n", + "print(MSE(y_test,ypredict))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Alternatively, you could write your own test-train splitting function as shown here." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# equivalently in numpy\n", + "def train_test_split_numpy(inputs, labels, train_size, test_size):\n", + " n_inputs = len(inputs)\n", + " inputs_shuffled = inputs.copy()\n", + " labels_shuffled = labels.copy()\n", + "\n", + " np.random.shuffle(inputs_shuffled)\n", + " np.random.shuffle(labels_shuffled)\n", + "\n", + " train_end = int(n_inputs*train_size)\n", + " X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]\n", + " Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]\n", + "\n", + " return X_train, X_test, Y_train, Y_test" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "But since **scikit-learn** has its own function for doing this and since\n", + "it interfaces easily with **tensorflow** and other libraries, we\n", + "normally recommend using the latter functionality.\n", + "\n", + "\n", + "\n", + "\n", "## Reducing the number of degrees of freedom, overarching view\n", "\n", "Many Machine Learning problems involve thousands or even millions of\n", @@ -3069,6 +3186,7 @@ "visualization.\n", "\n", "\n", + "\n", "Before we proceed however, we will discuss how to preprocess our\n", "data. Till now and in connection with our previous examples we have\n", "not met so many cases where we are too sensitive to the scaling of our\n", @@ -3076,6 +3194,15 @@ "to extreme values. Scaling the data renders our inputs much more\n", "suitable for the algorithms we want to employ.\n", "\n", + "For data sets gathered for real world applications, it is rather normal that\n", + "different features have very different units and\n", + "numerical scales. For example, a data set detailing health habits may include\n", + "features such as **age** in the range $0-80$, and **caloric intake** of order $2000$.\n", + "Many machine learning methods sensitive to the scales of the features and may perform poorly if they\n", + "are very different scales. Therefore, it is typical to scale\n", + "the features in a way to avoid such outlier values.\n", + "\n", + "\n", "**Scikit-Learn** has several functions which allow us to rescale the\n", "data, normally resulting in much better results in terms of various\n", "accuracy scores. The **StandardScaler** function in **Scikit-Learn**\n", @@ -3105,7 +3232,38 @@ "techniques.\n", "\n", "\n", - "### Simple preprocessing examples, Franke function and regression" + "Many features are often scaled using standardization to improve\n", + "performance. In **Scikit-Learn** this is given by the **StandardScaler**\n", + "function as discussed above. It is easy however to write your own.\n", + "Mathematically, this involves subtracting the mean and divide by the\n", + "standard deviation over the data set, for each feature:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "x_j^{(i)} \\rightarrow \\frac{x_j^{(i)} - \\overline{x}_j}{\\sigma(x_j)},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $\\overline{x}_j$ and $\\sigma(x_j)$ are the mean and standard\n", + "deviation, respectively, of the feature $x_j$. This ensures that each\n", + "feature has zero mean and unit standard deviation. For data sets\n", + "where we do not have the standard deviation or don't wish to calculate\n", + "it, it is then common to simply set it to one.\n", + "\n", + "\n", + "\n", + "Let us consider the following vanilla example where we use both\n", + "**Scikit-Learn** and write our own function as well. We produce a\n", + "simple test design matrix with random numbers. Each column could then\n", + "represent a specific feature whose mean value is subracted." ] }, { @@ -3117,98 +3275,126 @@ }, "outputs": [], "source": [ - "# Common imports\n", - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", "import sklearn.linear_model as skl\n", "from sklearn.metrics import mean_squared_error\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", + "import numpy as np\n", + "import pandas as pd\n", + "from IPython.display import display\n", + "np.random.seed(100)\n", + "# setting up a 10 x 5 matrix\n", + "rows = 10\n", + "cols = 5\n", + "X = np.random.randn(rows,cols)\n", + "XPandas = pd.DataFrame(X)\n", + "display(XPandas)\n", + "print(XPandas.mean())\n", + "print(XPandas.std())\n", + "XPandas = (XPandas -XPandas.mean())\n", + "display(XPandas)\n", + "# This option does not include the standard deviation\n", + "scaler = StandardScaler(with_std=False)\n", + "scaler.fit(X)\n", + "Xscaled = scaler.transform(X)\n", + "display(XPandas-Xscaled)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Small exercise: perform the standard scaling by including the standard deviation and compare with what Scikit-Learn gives.\n", "\n", "\n", - "def FrankeFunction(x,y):\n", - "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n", - "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n", - "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n", - "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n", - "\treturn term1 + term2 + term3 + term4\n", + "\n", + "Another commonly used scaling method is min-max scaling. This is very\n", + "useful for when we want the features to lie in a certain interval. To\n", + "scale the feature $x_j$ to the interval $[a, b]$, we can apply the\n", + "transformation" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "x_j^{(i)} \\rightarrow (b-a)\\frac{x_j^{(i)} - \\min(x_j)}{\\max(x_j) - \\min(x_j)} - a\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $\\min(x_j)$ and $\\max(x_j)$ return the minimum and maximum value of $x_j$ over the data set, respectively.\n", "\n", "\n", - "def create_X(x, y, n ):\n", - "\tif len(x.shape) > 1:\n", - "\t\tx = np.ravel(x)\n", - "\t\ty = np.ravel(y)\n", - "\n", - "\tN = len(x)\n", - "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n", - "\tX = np.ones((N,l))\n", - "\n", - "\tfor i in range(1,n+1):\n", - "\t\tq = int((i)*(i+1)/2)\n", - "\t\tfor k in range(i+1):\n", - "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n", - "\n", - "\treturn X\n", "\n", "\n", - "# Making meshgrid of datapoints and compute Franke's function\n", - "n = 5\n", - "N = 1000\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", - "# split in training and test data\n", - "X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=0.2)\n", + "## Testing the Means Squared Error as function of Complexity\n", "\n", "\n", - "clf = skl.LinearRegression().fit(X_train, y_train)\n", + "Before we proceed with a more detailed analysis of the so-called\n", + "Bias-Variance tradeoff, we present here an example of the relation\n", + "between model complexity and the mean squared error for the triaining\n", + "data and the test data.\n", "\n", - "# The mean squared error and R2 score\n", - "print(\"MSE before scaling: {:.2f}\".format(mean_squared_error(clf.predict(X_test), y_test)))\n", - "print(\"R2 score before scaling {:.2f}\".format(clf.score(X_test,y_test)))\n", + "The results here tell us clearly that for the data not included in the\n", + "training, there is an optimal model as function of the complexity of\n", + "ourmodel (here in terms of the polynomial degree of the model).\n", "\n", + "The results here will vary as function of model complexity and the amount od data used for training. \n", + "\n", + "\n", + "Our data is defined by $x\\in [-3,3]$ with a total of for example $100$ data points." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", + "from sklearn.preprocessing import PolynomialFeatures\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.pipeline import make_pipeline\n", + "\n", + "\n", + "np.random.seed(2018)\n", + "n = 100\n", + "maxdegree = 14\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", + "TestError = np.zeros(maxdegree)\n", + "TrainError = 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", "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", + "scaler.fit(x_train)\n", + "x_train_scaled = scaler.transform(x_train)\n", + "x_test_scaled = scaler.transform(x_test)\n", "\n", - "print(\"Feature min values before scaling:\\n {}\".format(X_train.min(axis=0)))\n", - "print(\"Feature max values before scaling:\\n {}\".format(X_train.max(axis=0)))\n", + "for degree in range(maxdegree):\n", + " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n", + " clf = model.fit(x_train_scaled,y_train)\n", + " y_fit = clf.predict(x_train_scaled)\n", + " y_pred = clf.predict(x_test_scaled) \n", + " polydegree[degree] = degree\n", + " TestError[degree] = np.mean( np.mean((y_test - y_pred)**2) )\n", + " TrainError[degree] = np.mean( np.mean((y_train - y_fit)**2) )\n", "\n", - "print(\"Feature min values after scaling:\\n {}\".format(X_train_scaled.min(axis=0)))\n", - "print(\"Feature max values after scaling:\\n {}\".format(X_train_scaled.max(axis=0)))\n", - "\n", - "clf = skl.LinearRegression().fit(X_train_scaled, y_train)\n", - "\n", - "\n", - "print(\"MSE after scaling: {:.2f}\".format(mean_squared_error(clf.predict(X_test_scaled), y_test)))\n", - "print(\"R2 score for scaled data: {:.2f}\".format(clf.score(X_test_scaled,y_test)))" + "plt.plot(polydegree, TestError, label='Test Error')\n", + "plt.plot(polydegree, TrainError, label='Train Error')\n", + "plt.legend()\n", + "plt.show()" ] }, { diff --git a/doc/LectureNotes/chapter2.ipynb b/doc/LectureNotes/chapter2.ipynb index 99ead382c..651eadf4a 100644 --- a/doc/LectureNotes/chapter2.ipynb +++ b/doc/LectureNotes/chapter2.ipynb @@ -543,6 +543,143 @@ "example\n", "\n", "\n", + "## Code for SVD and Inversion of Matrices\n", + "\n", + "How do we use the SVD to invert a matrix $\\boldsymbol{X}^\\boldsymbol{X}$ which is singular or near singular?\n", + "The simple answer is to use the linear algebra function for the pseudoinverse, that is" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "#Ainv = np.linlag.pinv(A)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let us first look at a matrix which does not causes problems and write our own function where we just use the SVD." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "# SVD inversion\n", + "def SVDinv(A):\n", + " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n", + " SVD is numerically more stable than the inversion algorithms provided by\n", + " numpy and scipy.linalg at the cost of being slower.\n", + " '''\n", + " U, s, VT = np.linalg.svd(A)\n", + " print('test U')\n", + " print( (np.transpose(U) @ U - U @np.transpose(U)))\n", + " print('test VT')\n", + " print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n", + "\n", + "\n", + " D = np.zeros((len(U),len(VT)))\n", + " D = np.diag(s)\n", + " UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)\n", + " return np.matmul(V,np.matmul(invD,UT))\n", + "\n", + "\n", + "#X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])\n", + "# Non-singular square matrix\n", + "X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])\n", + "print(X)\n", + "A = np.transpose(X) @ X\n", + "# Brute force inversion\n", + "B = np.linalg.pinv(A) # here we could use np.linalg.inv(A), try it!\n", + "C = SVDinv(A)\n", + "print(np.abs(B-C))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Although our matrix to invert $\\boldsymbol{X}^T\\boldsymbol{X}$ is a square matrix, our matrix may be singular. \n", + "\n", + "The pseudoinverse is the generalization of the matrix inverse for square matrices to\n", + "rectangular matrices where the number of rows and columns are not equal.\n", + "\n", + "It is also called the the Moore-Penrose Inverse after two independent discoverers of the method or the Generalized Inverse.\n", + "It is used for the calculation of the inverse for singular or near singular matrices and for rectangular matrices.\n", + "\n", + "Using the SVD we can obtain the pseudoinverse of a matrix $\\boldsymbol{A}$ (labeled here as $\\boldsymbol{A}_{\\mathrm{PI}}$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{A}_{\\mathrm{PI}}= \\boldsymbol{V}\\boldsymbol{D}_{\\mathrm{PI}}\\boldsymbol{U}^T,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $\\boldsymbol{D}_{\\mathrm{PI}}$ can be calculated by creating a diagonal matrix from $\\boldsymbol{Sigma}$ where we only keep the singular values (the non-zero values). The following code computes the pseudoinvers of the matrix based on the SVD." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "# SVD inversion\n", + "def SVDinv(A):\n", + " U, s, VT = np.linalg.svd(A)\n", + " # reciprocals of singular values of s\n", + " d = 1.0 / s\n", + " # create m x n D matrix\n", + " D = np.zeros(A.shape)\n", + " # populate D with n x n diagonal matrix\n", + " D[:A.shape[1], :A.shape[1]] = np.diag(d)\n", + " UT = np.transpose(U)\n", + " V = np.transpose(VT)\n", + " return np.matmul(V,np.matmul(D.T,UT))\n", + "\n", + "\n", + "A = np.array([ [0.3, 0.4], [0.5, 0.6], [0.7, 0.8],[0.9, 1.0]])\n", + "print(A)\n", + "# Brute force inversion of super-collinear matrix\n", + "B = np.linalg.pinv(A)\n", + "print(B)\n", + "# Compare our own algorithm with pinv\n", + "C = SVDinv(A)\n", + "print(np.abs(C-B))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As you can see from these examples, our own decomposition based on the SVD agrees the pseudoinverse algorithm provided by **Numpy**.\n", + "\n", + "\n", "\n", "\n", "\n", @@ -1740,535 +1877,8 @@ "\n", "\n", "\n", - "## Ridge and LASSO Regression\n", "\n", - "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n", - "our optimization problem is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "or we can state it as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we have used the definition of a norm-2 vector, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By minimizing the above equation with respect to the parameters\n", - "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n", - "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n", - "defining a new cost function to be optimized, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which leads to the Ridge regression minimization problem where we\n", - "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n", - "a finite number larger than zero. By defining" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we have a new optimization equation" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n", - "\n", - "Here we have defined the norm-1 as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and \n", - "taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n", - "a slightly modified matrix inversion problem which for finite values\n", - "of $\\lambda$ does not suffer from singularity problems. We obtain\n", - "the optimal parameters" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $t$ a finite positive number. \n", - "\n", - "When we compare this with the ordinary least squares result we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$.\n", - "\n", - "\n", - "We see that Ridge regression is nothing but the standard OLS with a\n", - "modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The consequences, in\n", - "particular for our discussion of the bias-variance tradeoff are rather\n", - "interesting. We will see that for specific values of $\\lambda$, we may\n", - "even reduce the variance of the optimal parameters $\\boldsymbol{\\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.\n", - "\n", - "Using our insights about the SVD of the design matrix $\\boldsymbol{X}$ \n", - "We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{y}}_{\\mathrm{OLS}}=\\boldsymbol{X}\\boldsymbol{\\beta} =\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For Ridge regression this becomes" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{y}}_{\\mathrm{Ridge}}=\\boldsymbol{X}\\boldsymbol{\\beta}_{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{\\Sigma}^2\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$ from the SVD of the matrix $\\boldsymbol{X}$. \n", - "\n", - "\n", - "Since $\\lambda \\geq 0$, it means that compared to OLS, we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n", - "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n", - "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n", - "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n", - "\\sigma_{i+1}$.\n", - "\n", - "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.\n", - "\n", - "\n", - "\n", - "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In this case the standard OLS results in" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n", - "the Ridge estimator converges to zero when the hyperparameter goes to\n", - "infinity.\n", - "\n", - "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n", - "\n", - "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n", - "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\n", - "\n", - "\n", - "Using the matrix-vector expression for Lasso regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have the following **cost** function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Taking the derivative with respect to $\\boldsymbol{\\beta}$ and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{d \\vert \\beta\\vert}{d \\boldsymbol{\\beta}}=\\mathrm{sgn}(\\boldsymbol{\\beta})=\\left\\{\\begin{array}{cc} 1 & \\beta > 0 \\\\ 0 & \\beta =0\\\\-1 & \\beta < 0, \\end{array}\\right.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we have that the derivative of the cost function is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{X},\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}=-2\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})+\\lambda sgn(\\boldsymbol{\\beta})=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and reordering we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta})+\\lambda sgn(\\boldsymbol{\\beta})=2\\boldsymbol{X}^T(\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This equation does not lead to a nice analytical equation as in either Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms using for example the Python package [CVXOPT](https://cvxopt.org/). We will discuss this later. \n", - "\n", - "## Code for SVD and Inversion of Matrices\n", - "\n", - "How do we use the SVD to invert a matrix $\\boldsymbol{X}^\\boldsymbol{X}$ which is singular or near singular?\n", - "The simple answer is to use the linear algebra function for the pseudoinverse, that is" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "#Ainv = np.linlag.pinv(A)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Let us first look at a matrix which does not causes problems and write our own function where we just use the SVD." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "# SVD inversion\n", - "def SVDinv(A):\n", - " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n", - " SVD is numerically more stable than the inversion algorithms provided by\n", - " numpy and scipy.linalg at the cost of being slower.\n", - " '''\n", - " U, s, VT = np.linalg.svd(A)\n", - " print('test U')\n", - " print( (np.transpose(U) @ U - U @np.transpose(U)))\n", - " print('test VT')\n", - " print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n", - "\n", - "\n", - " D = np.zeros((len(U),len(VT)))\n", - " D = np.diag(s)\n", - " UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)\n", - " return np.matmul(V,np.matmul(invD,UT))\n", - "\n", - "\n", - "#X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])\n", - "# Non-singular square matrix\n", - "X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])\n", - "print(X)\n", - "A = np.transpose(X) @ X\n", - "# Brute force inversion\n", - "B = np.linalg.inv(A) # here we could use np.linalg.pinv(A)\n", - "C = SVDinv(A)\n", - "print(np.abs(B-C))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Although our matrix to invert $\\boldsymbol{X}^T\\boldsymbol{X}$ is a square matrix, our matrix may be singular. \n", - "\n", - "The pseudoinverse is the generalization of the matrix inverse for square matrices to\n", - "rectangular matrices where the number of rows and columns are not equal.\n", - "\n", - "It is also called the the Moore-Penrose Inverse after two independent discoverers of the method or the Generalized Inverse.\n", - "It is used for the calculation of the inverse for singular or near singular matrices and for rectangular matrices.\n", - "\n", - "Using the SVD we can obtain the pseudoinverse of a matrix $\\boldsymbol{A}$ (labeled here as $\\boldsymbol{A}_{\\mathrm{PI}}$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{A}_{\\mathrm{PI}}= \\boldsymbol{V}\\boldsymbol{D}_{\\mathrm{PI}}\\boldsymbol{U}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\boldsymbol{D}_{\\mathrm{PI}}$ can be calculated by creating a diagonal matrix from $\\boldsymbol{Sigma}$ where we only keep the singular values (the non-zero values). The following code computes the pseudoinvers of the matrix based on the SVD." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "# SVD inversion\n", - "def SVDinv(A):\n", - " U, s, VT = np.linalg.svd(A)\n", - " # reciprocals of singular values of s\n", - " d = 1.0 / s\n", - " # create m x n D matrix\n", - " D = np.zeros(A.shape)\n", - " # populate D with n x n diagonal matrix\n", - " D[:A.shape[1], :A.shape[1]] = np.diag(d)\n", - " UT = np.transpose(U)\n", - " V = np.transpose(VT)\n", - " return np.matmul(V,np.matmul(D.T,UT))\n", - "\n", - "\n", - "A = np.array([ [0.3, 0.4], [0.5, 0.6], [0.7, 0.8],[0.9, 1.0]])\n", - "print(A)\n", - "# Brute force inversion of super-collinear matrix\n", - "B = np.linalg.pinv(A)\n", - "print(B)\n", - "# Compare our own algorithm with pinv\n", - "C = SVDinv(A)\n", - "print(np.abs(C-B))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "As you can see from this example, our own decomposition based on the SVD agrees the pseudoinverse algorithm provided by **Numpy**.\n", - "\n", - "\n", - "\n", - "## Deriving the Ridge Regression Equations\n", + "## 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" @@ -3089,7 +2699,8 @@ "\n", "Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of $\\lambda$, meaning that we need to perform a search in order to find the optimal values.\n", "\n", - "First we study and compare the OLS and Ridge results. The next code compares all three methods." + "First we study and compare the OLS and Ridge results. The next code compares all three methods.\n", + "We select values of the hyperparameter $\\lambda\\in [10^{-4},10^4]$ and compute the predicted values for ordinary least squares and Ridge regression." ] }, { @@ -3158,7 +2769,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We see here that we reach a plateau. What is actually happening?" + "We see here that we reach a plateau for the Ridge results. Writing out the coefficients $\\boldsymbol{\\beta}$, we that they are getting smaller and smaller and our error stabilizes since the predicted values of $\\tilde{\\boldsymbol{y}}$ approach zero.\n", + "\n", + "This happens also for Lasso regression, as seen from the next code\n", + "output. The difference is that Lasso shrinks the values of $\\beta$ to\n", + "zero at a much earlier stage and the results flatten out. We see that\n", + "Lasso gives also an excellent fit for small values of $\\lambda$ and\n", + "shows rthe best performance of the three regression methods." ] }, { @@ -3232,7 +2849,15 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Another Example, now with a polynomial fit." + "We bring then back our exponential function example and study all\n", + "three regression methods. Depending on the level of noise, we note\n", + "that for small values of the hyperparameter $\\lambda$ all three\n", + "methods produce the same mean squared error. Again, Lasso shrinks the\n", + "parameter values to zero much earlier than Ridge regression and the\n", + "Lasso results flatten out much earlier since all $\\beta_j=0$ (check\n", + "this by printing the values). This case is an example of where OLS\n", + "performs best. Lasso and Ridge reproduce the OLS results for a limited\n", + "set of $\\lambda$ values." ] }, { @@ -3324,6 +2949,311 @@ "plt.show()" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Both these example send a clear message. The addition of a\n", + "shrinkage/regularization term implies that we need to perform a search\n", + "for the optimal values of $\\lambda$. We will see this throughout these\n", + "series of lectures.\n", + "\n", + "\n", + "As a small addendum, we note that you can also solve this problem using the convex optimization package [CVXOPT](https://cvxopt.org/examples/mlbook/l1regls.html). This requires, in addition to having installed **CVXOPT**, you need to download the file *l1regl.py*.\n", + "The following code example solves the simpler problem we discussed above, where we have added the latter python file." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from cvxopt import matrix, spdiag, mul, div, sqrt, normal, setseed\n", + "from cvxopt import blas, lapack, solvers, sparse, spmatrix\n", + "import math\n", + "\n", + "try:\n", + " import mosek\n", + " import sys\n", + " __MOSEK = True\n", + "except: __MOSEK = False\n", + "\n", + "if __MOSEK:\n", + "\n", + " def l1regls_mosek(A, b):\n", + " \"\"\"\n", + "\n", + " Returns the solution of l1-norm regularized least-squares problem\n", + "\n", + " minimize || A*x - b ||_2^2 + e'*u\n", + "\n", + " subject to -u <= x <= u\n", + "\n", + " \"\"\"\n", + "\n", + " m, n = A.size\n", + "\n", + " env = mosek.Env()\n", + " task = env.Task(0,0)\n", + " task.set_Stream(mosek.streamtype.log, lambda x: sys.stdout.write(x))\n", + "\n", + " task.appendvars( 2*n) # number of variables\n", + " task.appendcons( 2*n) # number of constraints\n", + "\n", + " # input quadratic objective\n", + " Q = matrix(0.0, (n,n)) \n", + " blas.syrk(A, Q, alpha = 2.0, trans='T')\n", + "\n", + " I = []\n", + " for i in range(n):\n", + " I.extend(range(i,n))\n", + "\n", + " J = []\n", + " for i in range(n):\n", + " J.extend((n-i)*[i])\n", + "\n", + " task.putqobj(I, J, list(Q[matrix(I) + matrix(J)*n]))\n", + " task.putclist(range(2*n), list(-2*A.T*b) + n*[1.0]) # setup linear objective\n", + "\n", + " # input constraint matrix row by row\n", + " for i in range(n):\n", + " task.putarow( i, [i, n+i], [1.0, -1.0])\n", + " task.putarow( n+i, [i, n+i], [1.0, 1.0])\n", + "\n", + " # setup bounds on constraints\n", + " task.putboundslice(mosek.accmode.con,\n", + " 0, n, n*[mosek.boundkey.up], n*[0.0], n*[0.0])\n", + " task.putboundslice(mosek.accmode.con,\n", + " n, 2*n, n*[mosek.boundkey.lo], n*[0.0], n*[0.0])\n", + "\n", + " # setup variable bounds\n", + " task.putboundslice(mosek.accmode.var,\n", + " 0, 2*n, 2*n*[mosek.boundkey.fr], 2*n*[0.0], 2*n*[0.0])\n", + "\n", + " # optimize the task\n", + " task.putobjsense(mosek.objsense.minimize)\n", + " task.optimize()\n", + " task.solutionsummary(mosek.streamtype.log)\n", + " x = n*[0.0]\n", + " task.getsolutionslice(mosek.soltype.itr, mosek.solitem.xx, 0, n, x)\n", + "\n", + " return matrix(x)\n", + "\n", + " def l1regls_mosek2(A, b):\n", + " \"\"\"\n", + "\n", + " Returns the solution of l1-norm regularized least-squares problem\n", + "\n", + " minimize w'*w + e'*u\n", + "\n", + " subject to -u <= x <= u\n", + "\n", + " A*x - w = b\n", + "\n", + " \"\"\"\n", + "\n", + " m, n = A.size\n", + "\n", + " env = mosek.Env()\n", + " task = env.Task(0,0)\n", + " task.set_Stream(mosek.streamtype.log, lambda x: sys.stdout.write(x))\n", + "\n", + " task.appendvars(2*n + m) # number of variables\n", + " task.appendcons(2*n + m) # number of constraints\n", + "\n", + " # input quadratic objective\n", + " task.putqobj(range(2*n,2*n+m), range(2*n,2*n+m), m*[2.0])\n", + "\n", + " task.putclist(range(2*n+m), n*[0.0] + n*[1.0] + m*[0.0]) # setup linear objective\n", + "\n", + " # input constraint matrix row by row\n", + " for i in range(n):\n", + " task.putarow( i, [i, n+i], [1.0, -1.0])\n", + " task.putarow( n+i, [i, n+i], [1.0, 1.0])\n", + "\n", + " for i in range(m):\n", + " task.putarow( 2*n+i, range(n) + [2*n+i], list(A[i,:]) + [-1.0])\n", + "\n", + " # setup bounds on constraints\n", + " task.putboundslice(mosek.accmode.con,\n", + " 0, n, n*[mosek.boundkey.up], n*[0.0], n*[0.0])\n", + " task.putboundslice(mosek.accmode.con,\n", + " n, 2*n, n*[mosek.boundkey.lo], n*[0.0], n*[0.0])\n", + " task.putboundslice(mosek.accmode.con,\n", + " 2*n, 2*n+m, m*[mosek.boundkey.fx], list(b), list(b))\n", + "\n", + " # setup variable bounds\n", + " task.putboundslice(mosek.accmode.var, 0, 2*n+m, (2*n+m)*[mosek.boundkey.fr], \n", + " (2*n+m)*[0.0], (2*n+m)*[0.0])\n", + "\n", + " # optimize the task\n", + " task.putobjsense(mosek.objsense.minimize)\n", + " task.optimize()\n", + " task.solutionsummary(mosek.streamtype.log)\n", + " x = n*[0.0]\n", + " task.getsolutionslice(mosek.soltype.itr, mosek.solitem.xx, 0, n, x)\n", + "\n", + " return matrix(x)\n", + "\n", + "def l1regls(A, b):\n", + " \"\"\"\n", + " \n", + " Returns the solution of l1-norm regularized least-squares problem\n", + " \n", + " minimize || A*x - b ||_2^2 + || x ||_1.\n", + "\n", + " \"\"\"\n", + "\n", + " m, n = A.size\n", + " q = matrix(1.0, (2*n,1))\n", + " q[:n] = -2.0 * A.T * b\n", + "\n", + " def P(u, v, alpha = 1.0, beta = 0.0 ):\n", + " \"\"\"\n", + " v := alpha * 2.0 * [ A'*A, 0; 0, 0 ] * u + beta * v \n", + " \"\"\"\n", + " v *= beta\n", + " v[:n] += alpha * 2.0 * A.T * (A * u[:n])\n", + "\n", + "\n", + " def G(u, v, alpha=1.0, beta=0.0, trans='N'):\n", + " \"\"\"\n", + " v := alpha*[I, -I; -I, -I] * u + beta * v (trans = 'N' or 'T')\n", + " \"\"\"\n", + "\n", + " v *= beta\n", + " v[:n] += alpha*(u[:n] - u[n:])\n", + " v[n:] += alpha*(-u[:n] - u[n:])\n", + "\n", + " h = matrix(0.0, (2*n,1))\n", + "\n", + "\n", + " # Customized solver for the KKT system \n", + " #\n", + " # [ 2.0*A'*A 0 I -I ] [x[:n] ] [bx[:n] ]\n", + " # [ 0 0 -I -I ] [x[n:] ] = [bx[n:] ].\n", + " # [ I -I -D1^-1 0 ] [zl[:n]] [bzl[:n]]\n", + " # [ -I -I 0 -D2^-1 ] [zl[n:]] [bzl[n:]]\n", + " #\n", + " # where D1 = W['di'][:n]**2, D2 = W['di'][:n]**2.\n", + " # \n", + " # We first eliminate zl and x[n:]:\n", + " #\n", + " # ( 2*A'*A + 4*D1*D2*(D1+D2)^-1 ) * x[:n] = \n", + " # bx[:n] - (D2-D1)*(D1+D2)^-1 * bx[n:] + \n", + " # D1 * ( I + (D2-D1)*(D1+D2)^-1 ) * bzl[:n] - \n", + " # D2 * ( I - (D2-D1)*(D1+D2)^-1 ) * bzl[n:] \n", + " #\n", + " # x[n:] = (D1+D2)^-1 * ( bx[n:] - D1*bzl[:n] - D2*bzl[n:] ) \n", + " # - (D2-D1)*(D1+D2)^-1 * x[:n] \n", + " #\n", + " # zl[:n] = D1 * ( x[:n] - x[n:] - bzl[:n] )\n", + " # zl[n:] = D2 * (-x[:n] - x[n:] - bzl[n:] ).\n", + " #\n", + " # The first equation has the form\n", + " #\n", + " # (A'*A + D)*x[:n] = rhs\n", + " #\n", + " # and is equivalent to\n", + " #\n", + " # [ D A' ] [ x:n] ] = [ rhs ]\n", + " # [ A -I ] [ v ] [ 0 ].\n", + " #\n", + " # It can be solved as \n", + " #\n", + " # ( A*D^-1*A' + I ) * v = A * D^-1 * rhs\n", + " # x[:n] = D^-1 * ( rhs - A'*v ).\n", + "\n", + " S = matrix(0.0, (m,m))\n", + " Asc = matrix(0.0, (m,n))\n", + " v = matrix(0.0, (m,1))\n", + "\n", + " def Fkkt(W):\n", + "\n", + " # Factor \n", + " #\n", + " # S = A*D^-1*A' + I \n", + " #\n", + " # where D = 2*D1*D2*(D1+D2)^-1, D1 = d[:n]**-2, D2 = d[n:]**-2.\n", + "\n", + " d1, d2 = W['di'][:n]**2, W['di'][n:]**2\n", + "\n", + " # ds is square root of diagonal of D\n", + " ds = math.sqrt(2.0) * div( mul( W['di'][:n], W['di'][n:]), \n", + " sqrt(d1+d2) )\n", + " d3 = div(d2 - d1, d1 + d2)\n", + " \n", + " # Asc = A*diag(d)^-1/2\n", + " Asc = A * spdiag(ds**-1)\n", + "\n", + " # S = I + A * D^-1 * A'\n", + " blas.syrk(Asc, S)\n", + " S[::m+1] += 1.0 \n", + " lapack.potrf(S)\n", + "\n", + " def g(x, y, z):\n", + "\n", + " x[:n] = 0.5 * ( x[:n] - mul(d3, x[n:]) + \n", + " mul(d1, z[:n] + mul(d3, z[:n])) - mul(d2, z[n:] - \n", + " mul(d3, z[n:])) )\n", + " x[:n] = div( x[:n], ds) \n", + "\n", + " # Solve\n", + " #\n", + " # S * v = 0.5 * A * D^-1 * ( bx[:n] - \n", + " # (D2-D1)*(D1+D2)^-1 * bx[n:] + \n", + " # D1 * ( I + (D2-D1)*(D1+D2)^-1 ) * bzl[:n] - \n", + " # D2 * ( I - (D2-D1)*(D1+D2)^-1 ) * bzl[n:] )\n", + " \n", + " blas.gemv(Asc, x, v)\n", + " lapack.potrs(S, v)\n", + " \n", + " # x[:n] = D^-1 * ( rhs - A'*v ).\n", + " blas.gemv(Asc, v, x, alpha=-1.0, beta=1.0, trans='T')\n", + " x[:n] = div(x[:n], ds)\n", + "\n", + " # x[n:] = (D1+D2)^-1 * ( bx[n:] - D1*bzl[:n] - D2*bzl[n:] ) \n", + " # - (D2-D1)*(D1+D2)^-1 * x[:n] \n", + " x[n:] = div( x[n:] - mul(d1, z[:n]) - mul(d2, z[n:]), d1+d2 )\\\n", + " - mul( d3, x[:n] )\n", + " \n", + " # zl[:n] = D1^1/2 * ( x[:n] - x[n:] - bzl[:n] )\n", + " # zl[n:] = D2^1/2 * ( -x[:n] - x[n:] - bzl[n:] ).\n", + " z[:n] = mul( W['di'][:n], x[:n] - x[n:] - z[:n] ) \n", + " z[n:] = mul( W['di'][n:], -x[:n] - x[n:] - z[n:] ) \n", + "\n", + " return g\n", + "\n", + " return solvers.coneqp(P, q, G, h, kktsolver = Fkkt)['x'][:n]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Then we call the above functions and solve the problem, as done here" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from cvxopt import matrix, normal\n", + "\n", + "X = matrix( [ [ 2, 0, 1], [0, 1, 3]])\n", + "y = matrix( [4, 2, 3])\n", + "x = l1regls(X,y)" + ] + }, { "cell_type": "markdown", "metadata": {}, diff --git a/doc/LectureNotes/chapter3.ipynb b/doc/LectureNotes/chapter3.ipynb index ae2ca41df..d7f8222d5 100644 --- a/doc/LectureNotes/chapter3.ipynb +++ b/doc/LectureNotes/chapter3.ipynb @@ -4,3624 +4,66 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "# Ridge and Lasso Regression\n", + "# Resampling Methods\n", "\n", + "## Introduction\n", "\n", + "Resampling methods are an indispensable tool in modern\n", + "statistics. They involve repeatedly drawing samples from a training\n", + "set and refitting a model of interest on each sample in order to\n", + "obtain additional information about the fitted model. For example, in\n", + "order to estimate the variability of a linear regression fit, we can\n", + "repeatedly draw different samples from the training data, fit a linear\n", + "regression to each new sample, and then examine the extent to which\n", + "the resulting fits differ. Such an approach may allow us to obtain\n", + "information that would not be available from fitting the model only\n", + "once using the original training sample.\n", "\n", - "## Mathematical Interpretation of Ordinary Least Squares\n", + "Two resampling methods are often used in Machine Learning analyses,\n", + "1. The **bootstrap method**\n", "\n", - "What is presented here is a mathematical analysis of various regression algorithms (ordinary least squares, Ridge and Lasso Regression). The analysis is based on an important algorithm in linear algebra, the so-called Singular Value Decomposition (SVD). \n", + "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", - "We have shown that in ordinary least squares the optimal parameters $\\beta$ are given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The **hat** over $\\boldsymbol{\\beta}$ means we have the optimal parameters after minimization of the cost function.\n", "\n", - "This means that our best model is defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{y}}=\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}} = \\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now define a matrix" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{A}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can rewrite" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{y}}=\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}} = \\boldsymbol{A}\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The matrix $\\boldsymbol{A}$ has the important property that $\\boldsymbol{A}^2=\\boldsymbol{A}$. This is the definition of a projection matrix.\n", - "We can then interpret our optimal model $\\tilde{\\boldsymbol{y}}$ as being represented by an orthogonal projection of $\\boldsymbol{y}$ onto a space defined by the column vectors of $\\boldsymbol{X}$. In our case here the matrix $\\boldsymbol{A}$ is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix.\n", + "Resampling approaches can be computationally expensive, because they\n", + "involve fitting the same statistical method multiple times using\n", + "different subsets of the training data. However, due to recent\n", + "advances in computing power, the computational requirements of\n", + "resampling methods generally are not prohibitive. In this chapter, we\n", + "discuss two of the most commonly used resampling methods,\n", + "cross-validation and the bootstrap. Both methods are important tools\n", + "in the practical application of many statistical learning\n", + "procedures. For example, cross-validation can be used to estimate the\n", + "test error associated with a given statistical learning method in\n", + "order to evaluate its performance, or to select the appropriate level\n", + "of flexibility. The process of evaluating a model’s performance is\n", + "known as model assessment, whereas the process of selecting the proper\n", + "level of flexibility for a model is known as model selection. The\n", + "bootstrap is widely used.\n", "\n", "\n", + "* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods\n", "\n", + "* The results can be analysed with the same statistical tools as we would use analysing experimental data.\n", "\n", - "We have defined the residual error as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\epsilon}=\\boldsymbol{y}-\\tilde{\\boldsymbol{y}}=\\left[\\boldsymbol{I}-\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\right]\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The residual errors are then the projections of $\\boldsymbol{y}$ onto the orthogonal component of the space defined by the column vectors of $\\boldsymbol{X}$.\n", + "* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n", "\n", + "## Reminder on Statistics\n", "\n", - "If the matrix $\\boldsymbol{X}$ is an orthogonal (or unitary in case of complex values) matrix, we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{X}\\boldsymbol{X}^T = \\boldsymbol{I}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In this case the matrix $\\boldsymbol{A}$ becomes" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{A}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T)=\\boldsymbol{I},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and we have the obvious case" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\epsilon}=\\boldsymbol{y}-\\tilde{\\boldsymbol{y}}=0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This serves also as a useful test of our codes. \n", "\n", + "* As in other experiments, many numerical experiments have two classes of errors:\n", "\n", + " * Statistical errors\n", "\n", + " * Systematical errors\n", "\n", - "## The singular value decomposition\n", "\n", + "* Statistical errors can be estimated using standard tools from statistics\n", "\n", - "The examples we have looked at so far are cases where we normally can\n", - "invert the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$. Using a polynomial expansion where we fit of various functions leads to\n", - "row vectors of the design matrix which are essentially orthogonal due\n", - "to the polynomial character of our model. Obtaining the inverse of the\n", - "design matrix is then often done via a so-called LU, QR or Cholesky\n", - "decomposition.\n", - "\n", - "\n", - "As we will also see in the first project, \n", - "this may\n", - "however not the be case in general and a standard matrix inversion\n", - "algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.\n", - "\n", - "There is however a way to circumvent this problem and also\n", - "gain some insights about the ordinary least squares approach, and\n", - "later shrinkage methods like Ridge and Lasso regressions.\n", - "\n", - "This is given by the **Singular Value Decomposition** (SVD) algorithm,\n", - "perhaps the most powerful linear algebra algorithm. The SVD provides\n", - "a numerically stable matrix decomposition that is used in a large\n", - "swath oc applications and the decomposition is always stable\n", - "numerically.\n", - "\n", - "In machine learning it plays a central role in dealing with for\n", - "example design matrices that may be near singular or singular.\n", - "Furthermore, as we will see here, the singular values can be related\n", - "to the covariance matrix (and thereby the correlation matrix) and in\n", - "turn the variance of a given quantity. It plays also an important role\n", - "in the principal component analysis where high-dimensional data can be\n", - "reduced to the statistically relevant features.\n", - "\n", - "\n", - "\n", - "\n", - "One of the typical problems we encounter with linear regression, in particular \n", - "when the matrix $\\boldsymbol{X}$ (our so-called design matrix) is high-dimensional, \n", - "are problems with near singular or singular matrices. The column vectors of $\\boldsymbol{X}$ \n", - "may be linearly dependent, normally referred to as super-collinearity. \n", - "This means that the matrix may be rank deficient and it is basically impossible to \n", - "to model the data using linear regression. As an example, consider the matrix" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\\mathbf{X} & = \\left[\n", - "\\begin{array}{rrr}\n", - "1 & -1 & 2\n", - "\\\\\n", - "1 & 0 & 1\n", - "\\\\\n", - "1 & 2 & -1\n", - "\\\\\n", - "1 & 1 & 0\n", - "\\end{array} \\right]\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The columns of $\\boldsymbol{X}$ are linearly dependent. We see this easily since the \n", - "the first column is the row-wise sum of the other two columns. The rank (more correct,\n", - "the column rank) of a matrix is the dimension of the space spanned by the\n", - "column vectors. Hence, the rank of $\\mathbf{X}$ is equal to the number\n", - "of linearly independent columns. In this particular case the matrix has rank 2.\n", - "\n", - "Super-collinearity of an $(n \\times p)$-dimensional design matrix $\\mathbf{X}$ implies\n", - "that the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\\boldsymbol{X} & = \\left[\n", - "\\begin{array}{rr}\n", - "1 & -1\n", - "\\\\\n", - "1 & -1\n", - "\\end{array} \\right].\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We see easily that $\\mbox{det}(\\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \\times (-1) - 1 \\times (-1) = 0$. Hence, $\\mathbf{X}$ is singular and its inverse is undefined.\n", - "This is equivalent to saying that the matrix $\\boldsymbol{X}$ has at least an eigenvalue which is zero.\n", - "\n", - "\n", - "\n", - "If our design matrix $\\boldsymbol{X}$ which enters the linear regression problem" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\boldsymbol{\\beta} = (\\boldsymbol{X}^{T} \\boldsymbol{X})^{-1} \\boldsymbol{X}^{T} \\boldsymbol{y},\n", - "\\label{_auto1} \\tag{1}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "has linearly dependent column vectors, we will not be able to compute the inverse\n", - "of $\\boldsymbol{X}^T\\boldsymbol{X}$ and we cannot find the parameters (estimators) $\\beta_i$. \n", - "The estimators are only well-defined if $(\\boldsymbol{X}^{T}\\boldsymbol{X})^{-1}$ exits. \n", - "This is more likely to happen when the matrix $\\boldsymbol{X}$ is high-dimensional. In this case it is likely to encounter a situation where \n", - "the regression parameters $\\beta_i$ cannot be estimated.\n", - "\n", - "A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^{T} \\boldsymbol{X} \\rightarrow \\boldsymbol{X}^{T} \\boldsymbol{X}+\\lambda \\boldsymbol{I},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\boldsymbol{I}$ is the identity matrix. When we discuss **Ridge** regression this is actually what we end up evaluating. The parameter $\\lambda$ is called a hyperparameter. More about this later. \n", - "\n", - "\n", - "\n", - "\n", - "## Basic math of the SVD\n", - "\n", - "\n", - "From standard linear algebra we know that a square matrix $\\boldsymbol{X}$ can be diagonalized if and only it is \n", - "a so-called [normal matrix](https://en.wikipedia.org/wiki/Normal_matrix), that is if $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$\n", - "we have $\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ or if $\\boldsymbol{X}\\in {\\mathbb{C}}^{n\\times n}$ we have $\\boldsymbol{X}\\boldsymbol{X}^{\\dagger}=\\boldsymbol{X}^{\\dagger}\\boldsymbol{X}$.\n", - "The matrix has then a set of eigenpairs" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "(\\lambda_1,\\boldsymbol{u}_1),\\dots, (\\lambda_n,\\boldsymbol{u}_n),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and the eigenvalues are given by the diagonal matrix" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma}=\\mathrm{Diag}(\\lambda_1, \\dots,\\lambda_n).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The matrix $\\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\\boldsymbol{U}$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ or $\\boldsymbol{U}\\boldsymbol{U}^{\\dagger}=\\boldsymbol{I}$.\n", - "\n", - "Not all square matrices are diagonalizable. A matrix like the one discussed above" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X} = \\begin{bmatrix} \n", - "1& -1 \\\\\n", - "1& -1\\\\\n", - "\\end{bmatrix}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "is not diagonalizable, it is a so-called [defective matrix](https://en.wikipedia.org/wiki/Defective_matrix). It is easy to see that the condition\n", - "$\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ is not fulfilled. \n", - "\n", - "\n", - "\n", - "\n", - "\n", - "However, and this is the strength of the SVD algorithm, any general\n", - "matrix $\\boldsymbol{X}$ can be decomposed in terms of a diagonal matrix and\n", - "two orthogonal/unitary matrices. The [Singular Value Decompostion\n", - "(SVD) theorem](https://en.wikipedia.org/wiki/Singular_value_decomposition)\n", - "states that a general $m\\times n$ matrix $\\boldsymbol{X}$ can be written in\n", - "terms of a diagonal matrix $\\boldsymbol{\\Sigma}$ of dimensionality $m\\times n$\n", - "and two orthognal matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$, where the first has\n", - "dimensionality $m \\times m$ and the last dimensionality $n\\times n$.\n", - "We have then" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "As an example, the above defective matrix can be decomposed as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X} = \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& 1 \\\\ 1& -1\\\\ \\end{bmatrix} \\begin{bmatrix} 2& 0 \\\\ 0& 0\\\\ \\end{bmatrix} \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& -1 \\\\ 1& 1\\\\ \\end{bmatrix}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with eigenvalues $\\sigma_1=2$ and $\\sigma_2=0$. \n", - "The SVD exits always! \n", - "\n", - "The SVD\n", - "decomposition (singular values) gives eigenvalues \n", - "$\\sigma_i\\geq\\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=p$, the\n", - "eigenvalues (singular values) are zero.\n", - "\n", - "In the general case, where our design matrix $\\boldsymbol{X}$ has dimension\n", - "$n\\times p$, the matrix is thus decomposed into an $n\\times n$\n", - "orthogonal matrix $\\boldsymbol{U}$, a $p\\times p$ orthogonal matrix $\\boldsymbol{V}$\n", - "and a diagonal matrix $\\boldsymbol{\\Sigma}$ with $r=\\mathrm{min}(n,p)$\n", - "singular values $\\sigma_i\\geq 0$ on the main diagonal and zeros filling\n", - "the rest of the matrix. There are at most $p$ singular values\n", - "assuming that $n > p$. In our regression examples for the nuclear\n", - "masses and the equation of state this is indeed the case, while for\n", - "the Ising model we have $p > n$. These are often cases that lead to\n", - "near singular or singular matrices.\n", - "\n", - "The columns of $\\boldsymbol{U}$ are called the left singular vectors while the columns of $\\boldsymbol{V}$ are the right singular vectors.\n", - "\n", - "\n", - "If we assume that $n > p$, then our matrix $\\boldsymbol{U}$ has dimension $n\n", - "\\times n$. The last $n-p$ columns of $\\boldsymbol{U}$ become however\n", - "irrelevant in our calculations since they are multiplied with the\n", - "zeros in $\\boldsymbol{\\Sigma}$.\n", - "\n", - "The economy-size decomposition removes extra rows or columns of zeros\n", - "from the diagonal matrix of singular values, $\\boldsymbol{\\Sigma}$, along with the columns\n", - "in either $\\boldsymbol{U}$ or $\\boldsymbol{V}$ that multiply those zeros in the expression. \n", - "Removing these zeros and columns can improve execution time\n", - "and reduce storage requirements without compromising the accuracy of\n", - "the decomposition.\n", - "\n", - "If $n > p$, we keep only the first $p$ columns of $\\boldsymbol{U}$ and $\\boldsymbol{\\Sigma}$ has dimension $p\\times p$. \n", - "If $p > n$, then only the first $n$ columns of $\\boldsymbol{V}$ are computed and $\\boldsymbol{\\Sigma}$ has dimension $n\\times n$.\n", - "The $n=p$ case is obvious, we retain the full SVD. \n", - "In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.\n", - "\n", - "## Codes for the SVD" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "# SVD inversion\n", - "def SVD(A):\n", - " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n", - " SVD is numerically more stable than the inversion algorithms provided by\n", - " numpy and scipy.linalg at the cost of being slower.\n", - " '''\n", - " U, S, VT = np.linalg.svd(A,full_matrices=True)\n", - " print('test U')\n", - " print( (np.transpose(U) @ U - U @np.transpose(U)))\n", - " print('test VT')\n", - " print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n", - " print(U)\n", - " print(S)\n", - " print(VT)\n", - "\n", - " D = np.zeros((len(U),len(VT)))\n", - " for i in range(0,len(VT)):\n", - " D[i,i]=S[i]\n", - " return U @ D @ VT\n", - "\n", - "\n", - "X = np.array([ [1.0,-1.0], [1.0,-1.0]])\n", - "#X = np.array([[1, 2], [3, 4], [5, 6]])\n", - "\n", - "print(X)\n", - "C = SVD(X)\n", - "# Print the difference between the original matrix and the SVD one\n", - "print(C-X)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The matrix $\\boldsymbol{X}$ has columns that are linearly dependent. The first\n", - "column is the row-wise sum of the other two columns. The rank of a\n", - "matrix (the column rank) is the dimension of space spanned by the\n", - "column vectors. The rank of the matrix is the number of linearly\n", - "independent columns, in this case just $2$. We see this from the\n", - "singular values when running the above code. Running the standard\n", - "inversion algorithm for matrix inversion with $\\boldsymbol{X}^T\\boldsymbol{X}$ results\n", - "in the program terminating due to a singular matrix.\n", - "\n", - "\n", - "\n", - "The $U$, $S$, and $V$ matrices returned from the **svd()** function\n", - "cannot be multiplied directly.\n", - "\n", - "As you can see from the code, the $S$ vector must be converted into a\n", - "diagonal matrix. This may cause a problem as the size of the matrices\n", - "do not fit the rules of matrix multiplication, where the number of\n", - "columns in a matrix must match the number of rows in the subsequent\n", - "matrix.\n", - "\n", - "If you wish to include the zero singular values, you will need to\n", - "resize the matrices and set up a diagonal matrix as done in the above\n", - "example\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Mathematics of the SVD and implications\n", - "\n", - "Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies.\n", - "\n", - "Our starting point is our design matrix $\\boldsymbol{X}$ of dimension $n\\times p$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix}\n", - "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n", - "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n", - "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n", - "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n", - "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n", - "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n", - "\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can SVD decompose our matrix as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\boldsymbol{U}$ is an orthogonal matrix of dimension $n\\times n$, meaning that $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{U}^T\\boldsymbol{U}=\\boldsymbol{I}_n$. Here $\\boldsymbol{I}_n$ is the unit matrix of dimension $n \\times n$.\n", - "\n", - "Similarly, $\\boldsymbol{V}$ is an orthogonal matrix of dimension $p\\times p$, meaning that $\\boldsymbol{V}\\boldsymbol{V}^T=\\boldsymbol{V}^T\\boldsymbol{V}=\\boldsymbol{I}_p$. Here $\\boldsymbol{I}_n$ is the unit matrix of dimension $p \\times p$.\n", - "\n", - "Finally $\\boldsymbol{\\Sigma}$ contains the singular values $\\sigma_i$. This matrix has dimension $n\\times p$ and the singular values $\\sigma_i$ are all positive. The non-zero values are ordered in descending order, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma_0 > \\sigma_1 > \\sigma_2 > \\dots > \\sigma_{p-1} > 0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "All values beyond $p-1$ are all zero.\n", - "\n", - "\n", - "As an example, consider the following $3\\times 2$ example for the matrix $\\boldsymbol{\\Sigma}$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma}=\n", - "\\begin{bmatrix}\n", - "2& 0 \\\\\n", - "0 & 1 \\\\\n", - "0 & 0 \\\\\n", - "\\end{bmatrix}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The singular values are $\\sigma_0=2$ and $\\sigma_1=1$. It is common to rewrite the matrix $\\boldsymbol{\\Sigma}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma}=\n", - "\\begin{bmatrix}\n", - "\\boldsymbol{\\tilde{\\Sigma}}\\\\\n", - "\\boldsymbol{0}\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\tilde{\\Sigma}}=\n", - "\\begin{bmatrix}\n", - "2& 0 \\\\\n", - "0 & 1 \\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "contains only the singular values. Note also (and we will use this below) that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}=\n", - "\\begin{bmatrix}\n", - "4& 0 \\\\\n", - "0 & 1 \\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which is a $2\\times 2 $ matrix while" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T=\n", - "\\begin{bmatrix}\n", - "4& 0 & 0\\\\\n", - "0 & 1 & 0\\\\\n", - "0 & 0 & 0\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "is a $3\\times 3 $ matrix. The last row and column of this last matrix\n", - "contain only zeros. This will have important consequences for our SVD\n", - "decomposition of the design matrix.\n", - "\n", - "\n", - "\n", - "The matrix that may cause problems for us is $\\boldsymbol{X}^T\\boldsymbol{X}$. Using the SVD we can rewrite this matrix as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and using the orthogonality of the matrix $\\boldsymbol{U}$ we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We define $\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}=\\tilde{\\boldsymbol{\\Sigma}}^2$ which is a diagonal matrix containing only the singular values squared. It has dimensionality $p \\times p$.\n", - "\n", - "This means, using the orthogonality of $\\boldsymbol{V}$, that we get" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=\\tilde{\\boldsymbol{\\Sigma}}^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can now insert the result for the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ into our equation for ordinary least squares where" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and using our SVD decomposition of $\\boldsymbol{X}$ we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\tilde{\\boldsymbol{\\Sigma}}^{-2}\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which gives us, using the orthogonality of the matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$," - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_i\\boldsymbol{u}^T_j\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Note here that when we perform the multiplication of the various matrices, the orthogonal vectors of the matrix $\\boldsymbol{U}$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{U}=[\\boldsymbol{u}_0,\\boldsymbol{u}_1,\\dots,\\boldsymbol{u}_{n-1}],\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "that belong to $i>p-1$, result in only zeros when we perform the multiplications. This means that the sum above has non-zero elements only up to $i=p-1$. This corresponds also to the number of singular values (these are all non-zero).\n", - "\n", - "It means that the ordinary least square model (with the optimal parameters) $\\boldsymbol{\\tilde{y}}$, corresponds to an orthogonal transformation of the output (or target) vector $\\boldsymbol{y}$ by the vectors of the matrix $\\boldsymbol{U}$.\n", - "\n", - "\n", - "## Further properties (important for our analyses later)\n", - "\n", - "Let us study again $\\boldsymbol{X}^T\\boldsymbol{X}$ in terms of our SVD," - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If we now multiply from the right with $\\boldsymbol{V}$ (using the orthogonality of $\\boldsymbol{V}$) we get" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{V}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This means the vectors $\\boldsymbol{v}_i$ of the orthogonal matrix $\\boldsymbol{V}$ are the eigenvectors of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$\n", - "with eigenvalues given by the singular values squared, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{v}_i=\\boldsymbol{v}_i\\sigma_i^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Similarly, if we use the SVD decomposition for the matrix $\\boldsymbol{X}\\boldsymbol{X}^T$, we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If we now multiply from the right with $\\boldsymbol{U}$ (using the orthogonality of $\\boldsymbol{U}$) we get" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\left(\\boldsymbol{X}\\boldsymbol{X}^T\\right)\\boldsymbol{U}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This means the vectors $\\boldsymbol{u}_i$ of the orthogonal matrix $\\boldsymbol{U}$ are the eigenvectors of the matrix $\\boldsymbol{X}\\boldsymbol{X}^T$\n", - "with eigenvalues given by the singular values squared, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\left(\\boldsymbol{X}\\boldsymbol{X}^T\\right)\\boldsymbol{u}_i=\\boldsymbol{u}_i\\sigma_i^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Important note**: we have defined our design matrix $\\boldsymbol{X}$ to be an\n", - "$n\\times p$ matrix. In most supervised learning cases we have that $n\n", - "\\ge p$, and quite often we have $n >> p$. For linear algebra based methods like ordinary least squares or Ridge regression, this leads to a matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ which is small and thereby easier to handle from a computational point of view (in terms of number of floating point operations).\n", - "\n", - "In our lectures, the number of columns will\n", - "always refer to the number of features in our data set, while the\n", - "number of rows represents the number of data inputs. Note that in\n", - "other texts you may find the opposite notation. This has consequences\n", - "for the definition of for example the covariance matrix and its relation to the SVD.\n", - "\n", - "\n", - "## Meet the Covariance Matrix\n", - "\n", - "\n", - "Before we move on to a discussion of Ridge and Lasso regression, we want to show an important example of the above.\n", - "\n", - "We have already noted that the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ in ordinary\n", - "least squares is proportional to the second derivative of the cost\n", - "function, that is we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial^2 C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}^T\\partial \\boldsymbol{\\beta}} =\\frac{2}{n}\\boldsymbol{X}^T\\boldsymbol{X}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This quantity defines was what is called the Hessian matrix (the second derivative of a function we want to optimize).\n", - "\n", - "The Hessian matrix plays an important role and is defined in this course as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{H}=\\boldsymbol{X}^T\\boldsymbol{X}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The Hessian matrix for ordinary least squares is also proportional to\n", - "the covariance matrix. This means also that we can use the SVD to find\n", - "the eigenvalues of the covariance matrix and the Hessian matrix in\n", - "terms of the singular values. Let us develop these arguments, as they will play an important role in our machine learning studies.\n", - "\n", - "\n", - "\n", - "Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about\n", - "the definition of the covariance and the correlation function. These are quantities that play a central role in machine learning methods.\n", - "\n", - "Suppose we have defined two vectors\n", - "$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", - " \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where for example" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "With this definition and recalling that the variance is defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we can rewrite the covariance matrix as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", - " \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n", - " \\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Note:** we have used $1/n$ in the above definitions of the *sample* variance and covariance. We assume then that we can calculate the exact mean value. \n", - "What you will find in essentially all statistics texts are equations\n", - "with a factor $1/(n-1)$. This is called [Bessel's correction](https://mathworld.wolfram.com/BesselsCorrection.html). This\n", - "method corrects the bias in the estimation of the population variance\n", - "and covariance. It also partially corrects the bias in the estimation\n", - "of the population standard deviation. If you use a library like\n", - "**Scikit-Learn** or **nunmpy's** function calculate the covariance, this\n", - "quantity will be computed with a factor $1/(n-1)$.\n", - "\n", - "\n", - "The covariance takes values between zero and infinity and may thus\n", - "lead to problems with loss of numerical precision for particularly\n", - "large values. It is common to scale the covariance matrix by\n", - "introducing instead the correlation matrix defined via the so-called\n", - "correlation function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]=\\frac{\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}]}{\\sqrt{\\mathrm{var}[\\boldsymbol{x}] \\mathrm{var}[\\boldsymbol{y}]}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The correlation function is then given by values $\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]\n", - "\\in [-1,1]$. This avoids eventual problems with too large values. We\n", - "can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n", - "and $\\boldsymbol{y}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", - " \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the above example this is the function we constructed using **pandas**.\n", - "\n", - "\n", - "\n", - "In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**\n", - "we defined the design/feature matrix $\\boldsymbol{X}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix}\n", - "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n", - "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n", - "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n", - "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n", - "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n", - "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ refering to the column numbers and the\n", - "entries $n$ being the row elements.\n", - "We can rewrite the design/feature matrix in terms of its column vectors as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with a given vector" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{x}_i^T = \\begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \\dots & \\dots x_{n-1,i}\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "With these definitions, we can now rewrite our $2\\times 2$\n", - "correlation/covariance matrix in terms of a moe general design/feature\n", - "matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$\n", - "covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i=0,1,\\dots,p-1$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n", - "\\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & \\mathrm{var}[\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & \\mathrm{var}[\\boldsymbol{x}_{p-1}]\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and the correlation matrix" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n", - "1 & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & 1 & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & 1 & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & 1\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The Numpy function **np.cov** calculates the covariance elements using\n", - "the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n", - "the exact mean values. The following simple function uses the\n", - "**np.vstack** function which takes each vector of dimension $1\\times n$\n", - "and produces a $2\\times n$ matrix $\\boldsymbol{W}$\n", - "\n", - "Note that this assumes you have the features as the rows, and the inputs as columns, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{W} = \\begin{bmatrix} x_0 & x_1 & x_2 & \\dots & x_{n-2} & x_{n-1} \\\\\n", - " y_0 & y_1 & y_2 & \\dots & y_{n-2} & y_{n-1} \\\\\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which in turn is converted into into the $2\\times 2$ covariance matrix\n", - "$\\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate\n", - "the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n", - "function **np.mean(x)**. We can also extract the eigenvalues of the\n", - "covariance matrix through the **np.linalg.eig()** function." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Importing various packages\n", - "import numpy as np\n", - "n = 100\n", - "x = np.random.normal(size=n)\n", - "print(np.mean(x))\n", - "y = 4+3*x+np.random.normal(size=n)\n", - "print(np.mean(y))\n", - "W = np.vstack((x, y))\n", - "C = np.cov(W)\n", - "print(C)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The previous example can be converted into the correlation matrix by\n", - "simply scaling the matrix elements with the variances. We should also\n", - "subtract the mean values for each column. This leads to the following\n", - "code which sets up the correlations matrix for the previous example in\n", - "a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\\times 2$ correlation matrix (since we have only two vectors)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "n = 100\n", - "# define two vectors \n", - "x = np.random.random(size=n)\n", - "y = 4+3*x+np.random.normal(size=n)\n", - "#scaling the x and y vectors \n", - "x = x - np.mean(x)\n", - "y = y - np.mean(y)\n", - "variance_x = np.sum(x@x)/n\n", - "variance_y = np.sum(y@y)/n\n", - "print(variance_x)\n", - "print(variance_y)\n", - "cov_xy = np.sum(x@y)/n\n", - "cov_xx = np.sum(x@x)/n\n", - "cov_yy = np.sum(y@y)/n\n", - "C = np.zeros((2,2))\n", - "C[0,0]= cov_xx/variance_x\n", - "C[1,1]= cov_yy/variance_y\n", - "C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n", - "C[1,0]= C[0,1]\n", - "print(C)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We see that the matrix elements along the diagonal are one as they\n", - "should be and that the matrix is symmetric. Furthermore, diagonalizing\n", - "this matrix we easily see that it is a positive definite matrix.\n", - "\n", - "The above procedure with **numpy** can be made more compact if we use **pandas**.\n", - "\n", - "\n", - "\n", - "We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import pandas as pd\n", - "n = 10\n", - "x = np.random.normal(size=n)\n", - "x = x - np.mean(x)\n", - "y = 4+3*x+np.random.normal(size=n)\n", - "y = y - np.mean(y)\n", - "# Note that we transpose the matrix in order to stay with our ordering n x p\n", - "X = (np.vstack((x, y))).T\n", - "print(X)\n", - "Xpd = pd.DataFrame(X)\n", - "print(Xpd)\n", - "correlation_matrix = Xpd.corr()\n", - "print(correlation_matrix)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We expand this model to the Franke function discussed earlier." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import numpy as np\n", - "import pandas as pd\n", - "\n", - "\n", - "def FrankeFunction(x,y):\n", - "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n", - "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n", - "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n", - "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n", - "\treturn term1 + term2 + term3 + term4\n", - "\n", - "\n", - "def create_X(x, y, n ):\n", - "\tif len(x.shape) > 1:\n", - "\t\tx = np.ravel(x)\n", - "\t\ty = np.ravel(y)\n", - "\n", - "\tN = len(x)\n", - "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n", - "\tX = np.ones((N,l))\n", - "\n", - "\tfor i in range(1,n+1):\n", - "\t\tq = int((i)*(i+1)/2)\n", - "\t\tfor k in range(i+1):\n", - "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n", - "\n", - "\treturn X\n", - "\n", - "\n", - "# Making meshgrid of datapoints and compute Franke's function\n", - "n = 4\n", - "N = 100\n", - "x = np.sort(np.random.uniform(0, 1, N))\n", - "y = np.sort(np.random.uniform(0, 1, N))\n", - "z = FrankeFunction(x, y)\n", - "X = create_X(x, y, n=n) \n", - "\n", - "Xpd = pd.DataFrame(X)\n", - "# subtract the mean values and set up the covariance matrix\n", - "Xpd = Xpd - Xpd.mean()\n", - "covariance_matrix = Xpd.cov()\n", - "print(covariance_matrix)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We note here that the covariance is zero for the first rows and\n", - "columns since all matrix elements in the design matrix were set to one\n", - "(we are fitting the function in terms of a polynomial of degree $n$).\n", - "\n", - "This means that the variance for these elements will be zero and will\n", - "cause problems when we set up the correlation matrix. We can simply\n", - "drop these elements and construct a correlation\n", - "matrix without these elements. \n", - "\n", - "\n", - "\n", - "We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\\boldsymbol{X}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix}\n", - "x_{00} & x_{01}\\\\\n", - "x_{10} & x_{11}\\\\\n", - "\\end{bmatrix}=\\begin{bmatrix}\n", - "\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n", - "\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If we then compute the expectation value (note the $1/n$ factor instead of $1/(n-1)$)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}=\\frac{1}{n}\\begin{bmatrix}\n", - "x_{00}^2+x_{10}^2 & x_{00}x_{01}+x_{10}x_{11}\\\\\n", - "x_{01}x_{00}+x_{11}x_{10} & x_{01}^2+x_{11}^2\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which is just" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]=\\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] \\\\\n", - " \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we wrote $$\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]$$ to indicate that this is the covariance of the vectors $\\boldsymbol{x}$ of the design/feature matrix $\\boldsymbol{X}$.\n", - "\n", - "It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$.\n", - "\n", - "\n", - "\n", - "## Linking with the SVD\n", - "\n", - "We saw earlier that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Since the matrices here have dimension $p\\times p$, with $p$ corresponding to the singular values, we defined earlier the matrix" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma} = \\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0}\\\\ \\end{bmatrix}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\\\ \\boldsymbol{0}\\\\ \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where the tilde-matrix $\\tilde{\\boldsymbol{\\Sigma}}$ is a matrix of dimension $p\\times p$ containing only the singular values $\\sigma_i$, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{\\Sigma}}=\\begin{bmatrix} \\sigma_0 & 0 & 0 & \\dots & 0 & 0 \\\\\n", - " 0 & \\sigma_1 & 0 & \\dots & 0 & 0 \\\\\n", - "\t\t\t\t 0 & 0 & \\sigma_2 & \\dots & 0 & 0 \\\\\n", - "\t\t\t\t 0 & 0 & 0 & \\dots & \\sigma_{p-2} & 0 \\\\\n", - "\t\t\t\t 0 & 0 & 0 & \\dots & 0 & \\sigma_{p-1} \\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "meaning we can write" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\tilde{\\boldsymbol{\\Sigma}}^2\\boldsymbol{V}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Multiplying from the right with $\\boldsymbol{V}$ (using the orthogonality of $\\boldsymbol{V}$) we get" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{V}=\\boldsymbol{V}\\tilde{\\boldsymbol{\\Sigma}}^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This means the vectors $\\boldsymbol{v}_i$ of the orthogonal matrix $\\boldsymbol{V}$\n", - "are the eigenvectors of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ with eigenvalues\n", - "given by the singular values squared, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{v}_i=\\boldsymbol{v}_i\\sigma_i^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In other words, each non-zero singular value of $\\boldsymbol{X}$ is a positive\n", - "square root of an eigenvalue of $\\boldsymbol{X}^T\\boldsymbol{X}$. It means also that\n", - "the columns of $\\boldsymbol{V}$ are the eigenvectors of\n", - "$\\boldsymbol{X}^T\\boldsymbol{X}$. Since we have ordered the singular values of\n", - "$\\boldsymbol{X}$ in a descending order, it means that the column vectors\n", - "$\\boldsymbol{v}_i$ are hierarchically ordered by how much correlation they\n", - "encode from the columns of $\\boldsymbol{X}$. \n", - "\n", - "\n", - "Note that these are also the eigenvectors and eigenvalues of the\n", - "Hessian matrix.\n", - "\n", - "If we now recall the definition of the covariance matrix (not using\n", - "Bessel's correction) we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{X}]=\\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "meaning that every squared non-singular value of $\\boldsymbol{X}$ divided by $n$ (\n", - "the number of samples) are the eigenvalues of the covariance\n", - "matrix. Every singular value of $\\boldsymbol{X}$ is thus a positive square\n", - "root of an eigenvalue of $\\boldsymbol{X}^T\\boldsymbol{X}$. If the matrix $\\boldsymbol{X}$ is\n", - "self-adjoint, the singular values of $\\boldsymbol{X}$ are equal to the\n", - "absolute value of the eigenvalues of $\\boldsymbol{X}$.\n", - "\n", - "\n", - "For $\\boldsymbol{X}\\boldsymbol{X}^T$ we found" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{U}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Since the matrices here have dimension $n\\times n$, we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T = \\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\\\ \\boldsymbol{0}\\\\ \\end{bmatrix}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\boldsymbol{0}\\\\ \\end{bmatrix}=\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "leading to" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix}\\boldsymbol{U}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Multiplying with $\\boldsymbol{U}$ from the right gives us the eigenvalue problem" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U}=\\boldsymbol{U}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "It means that the eigenvalues of $\\boldsymbol{X}\\boldsymbol{X}^T$ are again given by\n", - "the non-zero singular values plus now a series of zeros. The column\n", - "vectors of $\\boldsymbol{U}$ are the eigenvectors of $\\boldsymbol{X}\\boldsymbol{X}^T$ and\n", - "measure how much correlations are contained in the rows of $\\boldsymbol{X}$.\n", - "\n", - "Since we will mainly be interested in the correlations among the features\n", - "of our data (the columns of $\\boldsymbol{X}$, the quantity of interest for us are the non-zero singular\n", - "values and the column vectors of $\\boldsymbol{V}$.\n", - "\n", - "\n", - "\n", - "## Ridge and LASSO Regression\n", - "\n", - "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n", - "our optimization problem is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "or we can state it as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we have used the definition of a norm-2 vector, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By minimizing the above equation with respect to the parameters\n", - "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n", - "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n", - "defining a new cost function to be optimized, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which leads to the Ridge regression minimization problem where we\n", - "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n", - "a finite number larger than zero. By defining" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we have a new optimization equation" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n", - "\n", - "Here we have defined the norm-1 as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and \n", - "taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n", - "a slightly modified matrix inversion problem which for finite values\n", - "of $\\lambda$ does not suffer from singularity problems. We obtain\n", - "the optimal parameters" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $t$ a finite positive number. \n", - "\n", - "When we compare this with the ordinary least squares result we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$.\n", - "\n", - "\n", - "We see that Ridge regression is nothing but the standard OLS with a\n", - "modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The consequences, in\n", - "particular for our discussion of the bias-variance tradeoff are rather\n", - "interesting. We will see that for specific values of $\\lambda$, we may\n", - "even reduce the variance of the optimal parameters $\\boldsymbol{\\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.\n", - "\n", - "Using our insights about the SVD of the design matrix $\\boldsymbol{X}$ \n", - "We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{y}}_{\\mathrm{OLS}}=\\boldsymbol{X}\\boldsymbol{\\beta} =\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For Ridge regression this becomes" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{y}}_{\\mathrm{Ridge}}=\\boldsymbol{X}\\boldsymbol{\\beta}_{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{\\Sigma}^2\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$ from the SVD of the matrix $\\boldsymbol{X}$. \n", - "\n", - "\n", - "Since $\\lambda \\geq 0$, it means that compared to OLS, we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n", - "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n", - "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n", - "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n", - "\\sigma_{i+1}$.\n", - "\n", - "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.\n", - "\n", - "\n", - "\n", - "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In this case the standard OLS results in" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n", - "the Ridge estimator converges to zero when the hyperparameter goes to\n", - "infinity.\n", - "\n", - "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n", - "\n", - "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n", - "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\n", - "\n", - "\n", - "Using the matrix-vector expression for Lasso regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have the following **cost** function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Taking the derivative with respect to $\\boldsymbol{\\beta}$ and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{d \\vert \\beta\\vert}{d \\boldsymbol{\\beta}}=\\mathrm{sgn}(\\boldsymbol{\\beta})=\\left\\{\\begin{array}{cc} 1 & \\beta > 0 \\\\ 0 & \\beta =0\\\\-1 & \\beta < 0, \\end{array}\\right.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we have that the derivative of the cost function is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{X},\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}=-2\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})+\\lambda sgn(\\boldsymbol{\\beta})=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and reordering we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta})+\\lambda sgn(\\boldsymbol{\\beta})=2\\boldsymbol{X}^T(\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This equation does not lead to a nice analytical equation as in either Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms using for example the Python package [CVXOPT](https://cvxopt.org/). We will discuss this below. \n", - "\n", - "## Code for SVD and Inversion of Matrices\n", - "\n", - "How do we use the SVD to invert a matrix $\\boldsymbol{X}^\\boldsymbol{X}$ which is singular or near singular?\n", - "The simple answer is to use the linear algebra function for the pseudoinverse, that is" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "#Ainv = np.linlag.pinv(A)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Let us first look at a matrix which does not causes problems and write our own function where we just use the SVD." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "# SVD inversion\n", - "def SVDinv(A):\n", - " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n", - " SVD is numerically more stable than the inversion algorithms provided by\n", - " numpy and scipy.linalg at the cost of being slower.\n", - " '''\n", - " U, s, VT = np.linalg.svd(A)\n", - " print('test U')\n", - " print( (np.transpose(U) @ U - U @np.transpose(U)))\n", - " print('test VT')\n", - " print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n", - "\n", - "\n", - " D = np.zeros((len(U),len(VT)))\n", - " D = np.diag(s)\n", - " UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)\n", - " return np.matmul(V,np.matmul(invD,UT))\n", - "\n", - "\n", - "#X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])\n", - "# Non-singular square matrix\n", - "X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])\n", - "print(X)\n", - "A = np.transpose(X) @ X\n", - "# Brute force inversion\n", - "B = np.linalg.inv(A) # here we could use np.linalg.pinv(A)\n", - "C = SVDinv(A)\n", - "print(np.abs(B-C))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Although our matrix to invert $\\boldsymbol{X}^T\\boldsymbol{X}$ is a square matrix, our matrix may be singular. \n", - "\n", - "The pseudoinverse is the generalization of the matrix inverse for square matrices to\n", - "rectangular matrices where the number of rows and columns are not equal.\n", - "\n", - "It is also called the the Moore-Penrose Inverse after two independent discoverers of the method or the Generalized Inverse.\n", - "It is used for the calculation of the inverse for singular or near singular matrices and for rectangular matrices.\n", - "\n", - "Using the SVD we can obtain the pseudoinverse of a matrix $\\boldsymbol{A}$ (labeled here as $\\boldsymbol{A}_{\\mathrm{PI}}$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{A}_{\\mathrm{PI}}= \\boldsymbol{V}\\boldsymbol{D}_{\\mathrm{PI}}\\boldsymbol{U}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\boldsymbol{D}_{\\mathrm{PI}}$ can be calculated by creating a diagonal matrix from $\\boldsymbol{Sigma}$ where we only keep the singular values (the non-zero values). The following code computes the pseudoinvers of the matrix based on the SVD." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "# SVD inversion\n", - "def SVDinv(A):\n", - " U, s, VT = np.linalg.svd(A)\n", - " # reciprocals of singular values of s\n", - " d = 1.0 / s\n", - " # create m x n D matrix\n", - " D = np.zeros(A.shape)\n", - " # populate D with n x n diagonal matrix\n", - " D[:A.shape[1], :A.shape[1]] = np.diag(d)\n", - " UT = np.transpose(U)\n", - " V = np.transpose(VT)\n", - " return np.matmul(V,np.matmul(D.T,UT))\n", - "\n", - "\n", - "A = np.array([ [0.3, 0.4], [0.5, 0.6], [0.7, 0.8],[0.9, 1.0]])\n", - "print(A)\n", - "# Brute force inversion of super-collinear matrix\n", - "B = np.linalg.pinv(A)\n", - "print(B)\n", - "# Compare our own algorithm with pinv\n", - "C = SVDinv(A)\n", - "print(np.abs(C-B))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "As you can see from this example, our own decomposition based on the SVD agrees the pseudoinverse algorithm provided by **Numpy**.\n", - "\n", - "\n", - "\n", - "## Deriving the Ridge Regression Equations\n", - "\n", - "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n", - "our optimization problem is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "or we can state it as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we have used the definition of a norm-2 vector, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By minimizing the above equation with respect to the parameters\n", - "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n", - "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n", - "defining a new cost function to be optimized, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which leads to the Ridge regression minimization problem where we\n", - "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n", - "a finite number larger than zero. By defining" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we have a new optimization equation" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n", - "\n", - "Here we have defined the norm-1 as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and \n", - "taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n", - "a slightly modified matrix inversion problem which for finite values\n", - "of $\\lambda$ does not suffer from singularity problems. We obtain\n", - "the optimal parameters" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $t$ a finite positive number. \n", - "\n", - "When we compare this with the ordinary least squares result we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$.\n", - "\n", - "\n", - "We see that Ridge regression is nothing but the standard OLS with a\n", - "modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The consequences, in\n", - "particular for our discussion of the bias-variance tradeoff are rather\n", - "interesting. We will see that for specific values of $\\lambda$, we may\n", - "even reduce the variance of the optimal parameters $\\boldsymbol{\\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.\n", - "\n", - "\n", - "\n", - "Using our insights about the SVD of the design matrix $\\boldsymbol{X}$ \n", - "We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{y}}_{\\mathrm{OLS}}=\\boldsymbol{X}\\boldsymbol{\\beta} =\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For Ridge regression this becomes" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{y}}_{\\mathrm{Ridge}}=\\boldsymbol{X}\\boldsymbol{\\beta}_{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{\\Sigma}^2\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$ from the SVD of the matrix $\\boldsymbol{X}$. \n", - "\n", - "\n", - "\n", - "Since $\\lambda \\geq 0$, it means that compared to OLS, we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n", - "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n", - "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n", - "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n", - "\\sigma_{i+1}$.\n", - "\n", - "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods.\n", - "\n", - "\n", - "\n", - "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In this case the standard OLS results in" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n", - "the Ridge estimator converges to zero when the hyperparameter goes to\n", - "infinity.\n", - "\n", - "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n", - "\n", - "\n", - "\n", - "Using the matrix-vector expression for Lasso regression and dropping the parameter $1/n$ in front of the standard mean squared error equation, we have the following **cost** function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Taking the derivative with respect to $\\boldsymbol{\\beta}$ and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{d \\vert \\beta\\vert}{d \\boldsymbol{\\beta}}=\\mathrm{sgn}(\\boldsymbol{\\beta})=\\left\\{\\begin{array}{cc} 1 & \\beta > 0 \\\\ 0 & \\beta =0\\\\-1 & \\beta < 0, \\end{array}\\right.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we have that the derivative of the cost function is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{X},\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}=-2\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})+\\lambda sgn(\\boldsymbol{\\beta})=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and reordering we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta}+\\lambda sgn(\\boldsymbol{\\beta})=2\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This equation does not lead to a nice analytical equation as in Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms using for example the Python package [CVXOPT](https://cvxopt.org/). We will discuss this later. \n", - "\n", - "\n", - "\n", - "\n", - "\n", - "Let us assume that our design matrix is given by unit (identity) matrix, that is a square diagonal matrix with ones only along the\n", - "diagonal. In this case we have an equal number of rows and columns $n=p$.\n", - "\n", - "Our model approximation is just $\\tilde{\\boldsymbol{y}}=\\boldsymbol{\\beta}$ and the mean squared error and thereby the cost function for ordinary least sqquares (OLS) is then (we drop the term $1/n$)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and minimizing we have that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\beta}_i^{\\mathrm{OLS}} = y_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For Ridge regression our cost function is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\beta_i^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and minimizing we have that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\beta}_i^{\\mathrm{Ridge}} = \\frac{y_i}{1+\\lambda}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For Lasso regression our cost function is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\vert\\beta_i\\vert=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\sqrt{\\beta_i^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and minimizing we have that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "-2\\sum_{i=0}^{p-1}(y_i-\\beta_i)+\\lambda \\sum_{i=0}^{p-1}\\frac{(\\beta_i)}{\\vert\\beta_i\\vert}=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which leads to" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_i^{\\mathrm{Lasso}} = \\left\\{\\begin{array}{ccc}y_i-\\frac{\\lambda}{2} &\\mathrm{if} & y_i> \\frac{\\lambda}{2}\\\\\n", - " y_i+\\frac{\\lambda}{2} &\\mathrm{if} & y_i< -\\frac{\\lambda}{2}\\\\\n", - "\t\t\t\t\t\t\t 0 &\\mathrm{if} & \\vert y_i\\vert\\le \\frac{\\lambda}{2}\\end{array}\\right.\\\\.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Plotting these results ([figure in handwritten notes for week 36](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2021/NotesSeptember9.pdf)) shows clearly that Lasso regression suppresses (sets to zero) values of $\\beta_i$ for specific values of $\\lambda$. Ridge regression reduces on the other hand the values of $\\beta_i$ as function of $\\lambda$.\n", - "\n", - "\n", - "As another examples, \n", - "let us assume we have a data set with outputs/targets given by the vector" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{y}=\\begin{bmatrix}4 \\\\ 2 \\\\3\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and our inputs as a $3\\times 2$ design matrix" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix}2 & 0\\\\ 0 & 1 \\\\ 0 & 0\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "meaning that we have two features and two unknown parameters $\\beta_0$ and $\\beta_1$ to be determined either by ordinary least squares, Ridge or Lasso regression.\n", - "\n", - "\n", - "For ordinary least squares (OLS) we know that the optimal solution is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\left( \\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Inserting the above values we obtain that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\begin{bmatrix}2 \\\\ 2\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The code which implements this simpler case is presented after the discussion of Ridge and Lasso.\n", - "\n", - "\n", - "For Ridge regression we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}}=\\left( \\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Inserting the above values we obtain that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}}=\\begin{bmatrix}\\frac{8}{4+\\lambda} \\\\ \\frac{2}{1+\\lambda}\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "There is normally a constraint on the value of $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2$ via the parameter $\\lambda$.\n", - "Let us for simplicity assume that $\\beta_0^2+\\beta_1^2=1$ as constraint. This will allow us to find an expression for the optimal values of $\\beta$ and $\\lambda$.\n", - "\n", - "To see this, let us write the cost function for Ridge regression. \n", - "\n", - "\n", - "\n", - "We define the MSE without the $1/n$ factor and have then, using that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}\\boldsymbol{\\beta}=\\begin{bmatrix} 2\\beta_0 \\\\ \\beta_1 \\\\0 \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=(4-2\\beta_0)^2+(2-\\beta_1)^2+\\lambda(\\beta_0^2+\\beta_1^2),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and taking the derivative with respect to $\\beta_0$ we get" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\beta_0=\\frac{8}{4+\\lambda},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and for $\\beta_1$ we obtain" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\beta_1=\\frac{2}{1+\\lambda},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Using the constraint for $\\beta_0^2+\\beta_1^2=1$ we can constrain $\\lambda$ by solving" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\left(\\frac{8}{4+\\lambda}\\right)^2+\\left(\\frac{2}{1+\\lambda}\\right)^2=1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which gives $\\lambda=4.571$ and $\\beta_0=0.933$ and $\\beta_1=0.359$.\n", - "\n", - "\n", - "For Lasso we need now, keeping a constraint on $\\vert\\beta_0\\vert+\\vert\\beta_1\\vert=1$, to take the derivative of the absolute values of $\\beta_0$\n", - "and $\\beta_1$. This gives us the following derivatives of the cost function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=(4-2\\beta_0)^2+(2-\\beta_1)^2+\\lambda(\\vert\\beta_0\\vert+\\vert\\beta_1\\vert),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_0}=-4(4-2\\beta_0)+\\lambda\\mathrm{sgn}(\\beta_0)=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_1}=-2(2-\\beta_1)+\\lambda\\mathrm{sgn}(\\beta_1)=0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We have now four cases to solve besides the trivial cases $\\beta_0$ and/or $\\beta_1$ are zero, namely\n", - "1. $\\beta_0 > 0$ and $\\beta_1 > 0$,\n", - "\n", - "2. $\\beta_0 > 0$ and $\\beta_1 < 0$,\n", - "\n", - "3. $\\beta_0 < 0$ and $\\beta_1 > 0$,\n", - "\n", - "4. $\\beta_0 < 0$ and $\\beta_1 < 0$.\n", - "\n", - "If we consider the first case, we have then" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "-4(4-2\\beta_0)+\\lambda=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "-2(2-\\beta_1)+\\lambda=0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which yields" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\beta_0=\\frac{16+\\lambda}{8},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\beta_1=\\frac{4+\\lambda}{2}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Using the constraint on $\\beta_0$ and $\\beta_1$ we can then find the optimal value of $\\lambda$ for the different cases. We leave this as an exercise to you.\n", - "\n", - "\n", - "Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of $\\lambda$, meaning that we need to perform a search in order to find the optimal values.\n", - "\n", - "First we study and compare the OLS and Ridge results. The next code compares all three methods." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "\n", - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "\n", - "X = np.array( [ [ 2, 0], [0, 1], [0,0]])\n", - "y = np.array( [4, 2, 3])\n", - "\n", - "\n", - "# matrix inversion to find beta\n", - "OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y\n", - "print(OLSbeta)\n", - "# and then make the prediction\n", - "ytildeOLS = X @ OLSbeta\n", - "print(\"Training MSE for OLS\")\n", - "print(MSE(y,ytildeOLS))\n", - "ypredictOLS = X @ OLSbeta\n", - "\n", - "# Repeat now for Ridge regression and various values of the regularization parameter\n", - "I = np.eye(2,2)\n", - "# Decide which values of lambda to use\n", - "nlambdas = 100\n", - "MSEPredict = np.zeros(nlambdas)\n", - "lambdas = np.logspace(-4, 4, nlambdas)\n", - "for i in range(nlambdas):\n", - " lmb = lambdas[i]\n", - " Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y\n", - "# print(Ridgebeta)\n", - " # and then make the prediction\n", - " ypredictRidge = X @ Ridgebeta\n", - " MSEPredict[i] = MSE(y,ypredictRidge)\n", - "# print(MSEPredict[i])\n", - " # Now plot the results\n", - "plt.figure()\n", - "plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Train')\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('MSE')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We see here that we reach a plateau. What is actually happening?" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn import linear_model\n", - "\n", - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "\n", - "X = np.array( [ [ 2, 0], [0, 1], [0,0]])\n", - "y = np.array( [4, 2, 3])\n", - "\n", - "\n", - "# matrix inversion to find beta\n", - "OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y\n", - "print(OLSbeta)\n", - "# and then make the prediction\n", - "ytildeOLS = X @ OLSbeta\n", - "print(\"Training MSE for OLS\")\n", - "print(MSE(y,ytildeOLS))\n", - "ypredictOLS = X @ OLSbeta\n", - "\n", - "# Repeat now for Ridge regression and various values of the regularization parameter\n", - "I = np.eye(2,2)\n", - "# Decide which values of lambda to use\n", - "nlambdas = 100\n", - "MSERidgePredict = np.zeros(nlambdas)\n", - "MSELassoPredict = np.zeros(nlambdas)\n", - "lambdas = np.logspace(-4, 4, nlambdas)\n", - "for i in range(nlambdas):\n", - " lmb = lambdas[i]\n", - " Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y\n", - " print(Ridgebeta)\n", - " # and then make the prediction\n", - " ypredictRidge = X @ Ridgebeta\n", - " MSERidgePredict[i] = MSE(y,ypredictRidge)\n", - " RegLasso = linear_model.Lasso(lmb)\n", - " RegLasso.fit(X,y)\n", - " ypredictLasso = RegLasso.predict(X)\n", - " print(RegLasso.coef_)\n", - " MSELassoPredict[i] = MSE(y,ypredictLasso)\n", - "# Now plot the results\n", - "plt.figure()\n", - "plt.plot(np.log10(lambdas), MSERidgePredict, 'r--', label = 'MSE Ridge Train')\n", - "plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Train')\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('MSE')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Another Example, now with a polynomial fit." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn import linear_model\n", - "\n", - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "np.random.seed(3155)\n", - "\n", - "x = np.random.rand(100)\n", - "y = 2.0+5*x*x+0.1*np.random.randn(100)\n", - "\n", - "# number of features p (here degree of polynomial\n", - "p = 3\n", - "# The design matrix now as function of a given polynomial\n", - "X = np.zeros((len(x),p))\n", - "X[:,0] = 1.0\n", - "X[:,1] = x\n", - "X[:,2] = x*x\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "\n", - "# matrix inversion to find beta\n", - "OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n", - "print(OLSbeta)\n", - "# and then make the prediction\n", - "ytildeOLS = X_train @ OLSbeta\n", - "print(\"Training MSE for OLS\")\n", - "print(MSE(y_train,ytildeOLS))\n", - "ypredictOLS = X_test @ OLSbeta\n", - "print(\"Test MSE OLS\")\n", - "print(MSE(y_test,ypredictOLS))\n", - "\n", - "# Repeat now for Lasso and Ridge regression and various values of the regularization parameter\n", - "I = np.eye(p,p)\n", - "# Decide which values of lambda to use\n", - "nlambdas = 100\n", - "MSEPredict = np.zeros(nlambdas)\n", - "MSETrain = np.zeros(nlambdas)\n", - "MSELassoPredict = np.zeros(nlambdas)\n", - "MSELassoTrain = np.zeros(nlambdas)\n", - "lambdas = np.logspace(-4, 4, nlambdas)\n", - "for i in range(nlambdas):\n", - " lmb = lambdas[i]\n", - " Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n", - " # include lasso using Scikit-Learn\n", - " RegLasso = linear_model.Lasso(lmb)\n", - " RegLasso.fit(X_train,y_train)\n", - " # and then make the prediction\n", - " ytildeRidge = X_train @ Ridgebeta\n", - " ypredictRidge = X_test @ Ridgebeta\n", - " ytildeLasso = RegLasso.predict(X_train)\n", - " ypredictLasso = RegLasso.predict(X_test)\n", - " MSEPredict[i] = MSE(y_test,ypredictRidge)\n", - " MSETrain[i] = MSE(y_train,ytildeRidge)\n", - " MSELassoPredict[i] = MSE(y_test,ypredictLasso)\n", - " MSELassoTrain[i] = MSE(y_train,ytildeLasso)\n", - "\n", - "# Now plot the results\n", - "plt.figure()\n", - "plt.plot(np.log10(lambdas), MSETrain, label = 'MSE Ridge train')\n", - "plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Test')\n", - "plt.plot(np.log10(lambdas), MSELassoTrain, label = 'MSE Lasso train')\n", - "plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Test')\n", - "\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('MSE')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "As a small addendum, we note that you can also solve this problem using the convex optimization package [CVXOPT](https://cvxopt.org/examples/mlbook/l1regls.html). This requires, in addition to having installed **CVXOPT**, you need to download the file *l1regl.py*.\n", - "The following code example solves the simpler problem we discussed above, where we have added the latter python file." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from l1regls import l1regls\n", - "from cvxopt import matrix, normal\n", - "import numpy as np\n", - "\n", - "X = matrix( [ [ 2, 0, 1], [0, 1, 3]])\n", - "y = matrix( [4, 2, 3])\n", - "x = l1regls(X,y)\n", - "\n", - "from cvxopt import matrix, spdiag, mul, div, sqrt, normal, setseed\n", - "from cvxopt import blas, lapack, solvers, sparse, spmatrix\n", - "import math\n", - "\n", - "try:\n", - " import mosek\n", - " import sys\n", - " __MOSEK = True\n", - "except: __MOSEK = False\n", - "\n", - "if __MOSEK:\n", - "\n", - " def l1regls_mosek(A, b):\n", - " \"\"\"\n", - "\n", - " Returns the solution of l1-norm regularized least-squares problem\n", - "\n", - " minimize || A*x - b ||_2^2 + e'*u\n", - "\n", - " subject to -u <= x <= u\n", - "\n", - " \"\"\"\n", - "\n", - " m, n = A.size\n", - "\n", - " env = mosek.Env()\n", - " task = env.Task(0,0)\n", - " task.set_Stream(mosek.streamtype.log, lambda x: sys.stdout.write(x))\n", - "\n", - " task.appendvars( 2*n) # number of variables\n", - " task.appendcons( 2*n) # number of constraints\n", - "\n", - " # input quadratic objective\n", - " Q = matrix(0.0, (n,n)) \n", - " blas.syrk(A, Q, alpha = 2.0, trans='T')\n", - "\n", - " I = []\n", - " for i in range(n):\n", - " I.extend(range(i,n))\n", - "\n", - " J = []\n", - " for i in range(n):\n", - " J.extend((n-i)*[i])\n", - "\n", - " task.putqobj(I, J, list(Q[matrix(I) + matrix(J)*n]))\n", - " task.putclist(range(2*n), list(-2*A.T*b) + n*[1.0]) # setup linear objective\n", - "\n", - " # input constraint matrix row by row\n", - " for i in range(n):\n", - " task.putarow( i, [i, n+i], [1.0, -1.0])\n", - " task.putarow( n+i, [i, n+i], [1.0, 1.0])\n", - "\n", - " # setup bounds on constraints\n", - " task.putboundslice(mosek.accmode.con,\n", - " 0, n, n*[mosek.boundkey.up], n*[0.0], n*[0.0])\n", - " task.putboundslice(mosek.accmode.con,\n", - " n, 2*n, n*[mosek.boundkey.lo], n*[0.0], n*[0.0])\n", - "\n", - " # setup variable bounds\n", - " task.putboundslice(mosek.accmode.var,\n", - " 0, 2*n, 2*n*[mosek.boundkey.fr], 2*n*[0.0], 2*n*[0.0])\n", - "\n", - " # optimize the task\n", - " task.putobjsense(mosek.objsense.minimize)\n", - " task.optimize()\n", - " task.solutionsummary(mosek.streamtype.log)\n", - " x = n*[0.0]\n", - " task.getsolutionslice(mosek.soltype.itr, mosek.solitem.xx, 0, n, x)\n", - "\n", - " return matrix(x)\n", - "\n", - " def l1regls_mosek2(A, b):\n", - " \"\"\"\n", - "\n", - " Returns the solution of l1-norm regularized least-squares problem\n", - "\n", - " minimize w'*w + e'*u\n", - "\n", - " subject to -u <= x <= u\n", - "\n", - " A*x - w = b\n", - "\n", - " \"\"\"\n", - "\n", - " m, n = A.size\n", - "\n", - " env = mosek.Env()\n", - " task = env.Task(0,0)\n", - " task.set_Stream(mosek.streamtype.log, lambda x: sys.stdout.write(x))\n", - "\n", - " task.appendvars(2*n + m) # number of variables\n", - " task.appendcons(2*n + m) # number of constraints\n", - "\n", - " # input quadratic objective\n", - " task.putqobj(range(2*n,2*n+m), range(2*n,2*n+m), m*[2.0])\n", - "\n", - " task.putclist(range(2*n+m), n*[0.0] + n*[1.0] + m*[0.0]) # setup linear objective\n", - "\n", - " # input constraint matrix row by row\n", - " for i in range(n):\n", - " task.putarow( i, [i, n+i], [1.0, -1.0])\n", - " task.putarow( n+i, [i, n+i], [1.0, 1.0])\n", - "\n", - " for i in range(m):\n", - " task.putarow( 2*n+i, range(n) + [2*n+i], list(A[i,:]) + [-1.0])\n", - "\n", - " # setup bounds on constraints\n", - " task.putboundslice(mosek.accmode.con,\n", - " 0, n, n*[mosek.boundkey.up], n*[0.0], n*[0.0])\n", - " task.putboundslice(mosek.accmode.con,\n", - " n, 2*n, n*[mosek.boundkey.lo], n*[0.0], n*[0.0])\n", - " task.putboundslice(mosek.accmode.con,\n", - " 2*n, 2*n+m, m*[mosek.boundkey.fx], list(b), list(b))\n", - "\n", - " # setup variable bounds\n", - " task.putboundslice(mosek.accmode.var, 0, 2*n+m, (2*n+m)*[mosek.boundkey.fr], \n", - " (2*n+m)*[0.0], (2*n+m)*[0.0])\n", - "\n", - " # optimize the task\n", - " task.putobjsense(mosek.objsense.minimize)\n", - " task.optimize()\n", - " task.solutionsummary(mosek.streamtype.log)\n", - " x = n*[0.0]\n", - " task.getsolutionslice(mosek.soltype.itr, mosek.solitem.xx, 0, n, x)\n", - "\n", - " return matrix(x)\n", - "\n", - "def l1regls(A, b):\n", - " \"\"\"\n", - " \n", - " Returns the solution of l1-norm regularized least-squares problem\n", - " \n", - " minimize || A*x - b ||_2^2 + || x ||_1.\n", - "\n", - " \"\"\"\n", - "\n", - " m, n = A.size\n", - " q = matrix(1.0, (2*n,1))\n", - " q[:n] = -2.0 * A.T * b\n", - "\n", - " def P(u, v, alpha = 1.0, beta = 0.0 ):\n", - " \"\"\"\n", - " v := alpha * 2.0 * [ A'*A, 0; 0, 0 ] * u + beta * v \n", - " \"\"\"\n", - " v *= beta\n", - " v[:n] += alpha * 2.0 * A.T * (A * u[:n])\n", - "\n", - "\n", - " def G(u, v, alpha=1.0, beta=0.0, trans='N'):\n", - " \"\"\"\n", - " v := alpha*[I, -I; -I, -I] * u + beta * v (trans = 'N' or 'T')\n", - " \"\"\"\n", - "\n", - " v *= beta\n", - " v[:n] += alpha*(u[:n] - u[n:])\n", - " v[n:] += alpha*(-u[:n] - u[n:])\n", - "\n", - " h = matrix(0.0, (2*n,1))\n", - "\n", - "\n", - " # Customized solver for the KKT system \n", - " #\n", - " # [ 2.0*A'*A 0 I -I ] [x[:n] ] [bx[:n] ]\n", - " # [ 0 0 -I -I ] [x[n:] ] = [bx[n:] ].\n", - " # [ I -I -D1^-1 0 ] [zl[:n]] [bzl[:n]]\n", - " # [ -I -I 0 -D2^-1 ] [zl[n:]] [bzl[n:]]\n", - " #\n", - " # where D1 = W['di'][:n]**2, D2 = W['di'][:n]**2.\n", - " # \n", - " # We first eliminate zl and x[n:]:\n", - " #\n", - " # ( 2*A'*A + 4*D1*D2*(D1+D2)^-1 ) * x[:n] = \n", - " # bx[:n] - (D2-D1)*(D1+D2)^-1 * bx[n:] + \n", - " # D1 * ( I + (D2-D1)*(D1+D2)^-1 ) * bzl[:n] - \n", - " # D2 * ( I - (D2-D1)*(D1+D2)^-1 ) * bzl[n:] \n", - " #\n", - " # x[n:] = (D1+D2)^-1 * ( bx[n:] - D1*bzl[:n] - D2*bzl[n:] ) \n", - " # - (D2-D1)*(D1+D2)^-1 * x[:n] \n", - " #\n", - " # zl[:n] = D1 * ( x[:n] - x[n:] - bzl[:n] )\n", - " # zl[n:] = D2 * (-x[:n] - x[n:] - bzl[n:] ).\n", - " #\n", - " # The first equation has the form\n", - " #\n", - " # (A'*A + D)*x[:n] = rhs\n", - " #\n", - " # and is equivalent to\n", - " #\n", - " # [ D A' ] [ x:n] ] = [ rhs ]\n", - " # [ A -I ] [ v ] [ 0 ].\n", - " #\n", - " # It can be solved as \n", - " #\n", - " # ( A*D^-1*A' + I ) * v = A * D^-1 * rhs\n", - " # x[:n] = D^-1 * ( rhs - A'*v ).\n", - "\n", - " S = matrix(0.0, (m,m))\n", - " Asc = matrix(0.0, (m,n))\n", - " v = matrix(0.0, (m,1))\n", - "\n", - " def Fkkt(W):\n", - "\n", - " # Factor \n", - " #\n", - " # S = A*D^-1*A' + I \n", - " #\n", - " # where D = 2*D1*D2*(D1+D2)^-1, D1 = d[:n]**-2, D2 = d[n:]**-2.\n", - "\n", - " d1, d2 = W['di'][:n]**2, W['di'][n:]**2\n", - "\n", - " # ds is square root of diagonal of D\n", - " ds = math.sqrt(2.0) * div( mul( W['di'][:n], W['di'][n:]), \n", - " sqrt(d1+d2) )\n", - " d3 = div(d2 - d1, d1 + d2)\n", - " \n", - " # Asc = A*diag(d)^-1/2\n", - " Asc = A * spdiag(ds**-1)\n", - "\n", - " # S = I + A * D^-1 * A'\n", - " blas.syrk(Asc, S)\n", - " S[::m+1] += 1.0 \n", - " lapack.potrf(S)\n", - "\n", - " def g(x, y, z):\n", - "\n", - " x[:n] = 0.5 * ( x[:n] - mul(d3, x[n:]) + \n", - " mul(d1, z[:n] + mul(d3, z[:n])) - mul(d2, z[n:] - \n", - " mul(d3, z[n:])) )\n", - " x[:n] = div( x[:n], ds) \n", - "\n", - " # Solve\n", - " #\n", - " # S * v = 0.5 * A * D^-1 * ( bx[:n] - \n", - " # (D2-D1)*(D1+D2)^-1 * bx[n:] + \n", - " # D1 * ( I + (D2-D1)*(D1+D2)^-1 ) * bzl[:n] - \n", - " # D2 * ( I - (D2-D1)*(D1+D2)^-1 ) * bzl[n:] )\n", - " \n", - " blas.gemv(Asc, x, v)\n", - " lapack.potrs(S, v)\n", - " \n", - " # x[:n] = D^-1 * ( rhs - A'*v ).\n", - " blas.gemv(Asc, v, x, alpha=-1.0, beta=1.0, trans='T')\n", - " x[:n] = div(x[:n], ds)\n", - "\n", - " # x[n:] = (D1+D2)^-1 * ( bx[n:] - D1*bzl[:n] - D2*bzl[n:] ) \n", - " # - (D2-D1)*(D1+D2)^-1 * x[:n] \n", - " x[n:] = div( x[n:] - mul(d1, z[:n]) - mul(d2, z[n:]), d1+d2 )\\\n", - " - mul( d3, x[:n] )\n", - " \n", - " # zl[:n] = D1^1/2 * ( x[:n] - x[n:] - bzl[:n] )\n", - " # zl[n:] = D2^1/2 * ( -x[:n] - x[n:] - bzl[n:] ).\n", - " z[:n] = mul( W['di'][:n], x[:n] - x[n:] - z[:n] ) \n", - " z[n:] = mul( W['di'][n:], -x[:n] - x[n:] - z[n:] ) \n", - "\n", - " return g\n", - "\n", - " return solvers.coneqp(P, q, G, h, kktsolver = Fkkt)['x'][:n]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Linking the regression analysis with a statistical interpretation\n", - "\n", - "We will now couple the discussions of ordinary least squares, Ridge\n", - "and Lasso regression with a statistical interpretation, that is we\n", - "move from a linear algebra analysis to a statistical analysis. In\n", - "particular, we will focus on what the regularization terms can result\n", - "in. We will amongst other things show that the regularization\n", - "parameter can reduce considerably the variance of the parameters\n", - "$\\beta$.\n", - "\n", + "* Systematical errors are method specific and must be treated differently from case to case. \n", "\n", "The\n", "advantage of doing linear regression is that we actually end up with\n", @@ -3665,7 +107,6 @@ "row number $i$ and perform a sum over all values $p$.\n", "\n", "\n", - "\n", "The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off)\n", "that there exists a function $f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim \\mathcal{N}(0, \\sigma^2)$\n", "which describe our data" @@ -3813,7 +254,8 @@ "\\sigma^2 \\, \\mathbf{I}_{nn}$. From $\\mbox{Var}(\\boldsymbol{\\beta}) = \\sigma^2\n", "\\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}$, one obtains an estimate of the\n", "variance of the estimate of the $j$-th regression coefficient:\n", - "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 [(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} $. This may be used to\n", + "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 \\sqrt{\n", + "[(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} }$. This may be used to\n", "construct a confidence interval for the estimates.\n", "\n", "\n", @@ -3880,20 +322,48 @@ "\n", "\n", "\n", - "## Deriving OLS from a probability distribution\n", + "## Resampling methods\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", + "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", - "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" + "One of the quantities we have discussed as a way to measure errors is\n", + "the mean-squared error (MSE), mainly used for fitting of continuous\n", + "functions. Another choice is the absolute error.\n", + "\n", + "In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,\n", + "we discuss the\n", + "1. prediction error or simply the **test error** $\\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the \n", + "\n", + "2. training error $\\mathrm{Err_{Train}}$, which is the average loss over the training data.\n", + "\n", + "As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.\n", + "For a certain level of complexity the test error will reach minimum, before starting to increase again. The\n", + "training error reaches a saturation.\n", + "\n", + "\n", + "\n", + "Two famous\n", + "resampling methods are the **independent bootstrap** and **the jackknife**. \n", + "\n", + "The jackknife is a special case of the independent bootstrap. Still, the jackknife was made\n", + "popular prior to the independent bootstrap. And as the popularity of\n", + "the independent bootstrap soared, new variants, such as **the dependent bootstrap**.\n", + "\n", + "The Jackknife and independent bootstrap work for\n", + "independent, identically distributed random variables.\n", + "If these conditions are not\n", + "satisfied, the methods will fail. Yet, it should be said that if the data are\n", + "independent, identically distributed, and we only want to estimate the\n", + "variance of $\\overline{X}$ (which often is the case), then there is no\n", + "need for bootstrapping. \n", + "\n", + "\n", + "The Jackknife works by making many replicas of the estimator $\\widehat{\\theta}$. \n", + "The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\\boldsymbol{x} = (x_1,x_2,\\cdots,X_n)$. \n", + "Let $\\boldsymbol{x}_i$ denote the vector" ] }, { @@ -3901,7 +371,7 @@ "metadata": {}, "source": [ "$$\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", + "\\boldsymbol{x}_i = (x_1,x_2,\\cdots,x_{i-1},x_{i+1},\\cdots,x_n),\n", "$$" ] }, @@ -3909,8 +379,229 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We assume now that the various $y_i$ values are stochastically distributed according to the above Gaussian distribution. \n", - "We define this distribution as" + "which equals the vector $\\boldsymbol{x}$ with the exception that observation\n", + "number $i$ is left out. Using this notation, define\n", + "$\\widehat{\\theta}_i$ to be the estimator\n", + "$\\widehat{\\theta}$ computed using $\\vec{X}_i$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from numpy import *\n", + "from numpy.random import randint, randn\n", + "from time import time\n", + "\n", + "def jackknife(data, stat):\n", + " n = len(data);t = zeros(n); inds = arange(n); t0 = time()\n", + " ## 'jackknifing' by leaving out an observation for each i \n", + " for i in range(n):\n", + " t[i] = stat(delete(data,i) )\n", + "\n", + " # analysis \n", + " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Jackknife Statistics :\")\n", + " print(\"original bias std. error\")\n", + " print(\"%8g %14g %15g\" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))\n", + "\n", + " return t\n", + "\n", + "\n", + "# Returns mean of data samples \n", + "def stat(data):\n", + " return mean(data)\n", + "\n", + "\n", + "mu, sigma = 100, 15\n", + "datapoints = 10000\n", + "x = mu + sigma*random.randn(datapoints)\n", + "# jackknife returns the data sample \n", + "t = jackknife(x, stat)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Bootstrap\n", + "\n", + "Bootstrapping is a nonparametric approach to statistical inference\n", + "that substitutes computation for more traditional distributional\n", + "assumptions and asymptotic results. Bootstrapping offers a number of\n", + "advantages: \n", + "1. The bootstrap is quite general, although there are some cases in which it fails. \n", + "\n", + "2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. \n", + "\n", + "3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. \n", + "\n", + "4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).\n", + "\n", + "Since $\\widehat{\\theta} = \\widehat{\\theta}(\\boldsymbol{X})$ is a function of random variables,\n", + "$\\widehat{\\theta}$ itself must be a random variable. Thus it has\n", + "a pdf, call this function $p(\\boldsymbol{t})$. The aim of the bootstrap is to\n", + "estimate $p(\\boldsymbol{t})$ by the relative frequency of\n", + "$\\widehat{\\theta}$. You can think of this as using a histogram\n", + "in the place of $p(\\boldsymbol{t})$. If the relative frequency closely\n", + "resembles $p(\\vec{t})$, then using numerics, it is straight forward to\n", + "estimate all the interesting parameters of $p(\\boldsymbol{t})$ using point\n", + "estimators. \n", + "\n", + "\n", + "\n", + "In the case that $\\widehat{\\theta}$ has\n", + "more than one component, and the components are independent, we use the\n", + "same estimator on each component separately. If the probability\n", + "density function of $X_i$, $p(x)$, had been known, then it would have\n", + "been straight forward to do this by: \n", + "1. Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \\cdots, X_n^*)$. \n", + "\n", + "2. Then using these numbers, we could compute a replica of $\\widehat{\\theta}$ called $\\widehat{\\theta}^*$. \n", + "\n", + "By repeated use of (1) and (2), many\n", + "estimates of $\\widehat{\\theta}$ could have been obtained. The\n", + "idea is to use the relative frequency of $\\widehat{\\theta}^*$\n", + "(think of a histogram) as an estimate of $p(\\boldsymbol{t})$.\n", + "\n", + "\n", + "But\n", + "unless there is enough information available about the process that\n", + "generated $X_1,X_2,\\cdots,X_n$, $p(x)$ is in general\n", + "unknown. Therefore, [Efron in 1979](https://projecteuclid.org/euclid.aos/1176344552) asked the\n", + "question: What if we replace $p(x)$ by the relative frequency\n", + "of the observation $X_i$; if we draw observations in accordance with\n", + "the relative frequency of the observations, will we obtain the same\n", + "result in some asymptotic sense? The answer is yes.\n", + "\n", + "\n", + "Instead of generating the histogram for the relative\n", + "frequency of the observation $X_i$, just draw the values\n", + "$(X_1^*,X_2^*,\\cdots,X_n^*)$ with replacement from the vector\n", + "$\\boldsymbol{X}$. \n", + "\n", + "\n", + "The independent bootstrap works like this: \n", + "\n", + "1. Draw with replacement $n$ numbers for the observed variables $\\boldsymbol{x} = (x_1,x_2,\\cdots,x_n)$. \n", + "\n", + "2. Define a vector $\\boldsymbol{x}^*$ containing the values which were drawn from $\\boldsymbol{x}$. \n", + "\n", + "3. Using the vector $\\boldsymbol{x}^*$ compute $\\widehat{\\theta}^*$ by evaluating $\\widehat \\theta$ under the observations $\\boldsymbol{x}^*$. \n", + "\n", + "4. Repeat this process $k$ times. \n", + "\n", + "When you are done, you can draw a histogram of the relative frequency\n", + "of $\\widehat \\theta^*$. This is your estimate of the probability\n", + "distribution $p(t)$. Using this probability distribution you can\n", + "estimate any statistics thereof. In principle you never draw the\n", + "histogram of the relative frequency of $\\widehat{\\theta}^*$. Instead\n", + "you use the estimators corresponding to the statistic of interest. For\n", + "example, if you are interested in estimating the variance of $\\widehat\n", + "\\theta$, apply the etsimator $\\widehat \\sigma^2$ to the values\n", + "$\\widehat \\theta ^*$.\n", + "\n", + "\n", + "\n", + "The following code starts with a Gaussian distribution with mean value\n", + "$\\mu =100$ and variance $\\sigma=15$. We use this to generate the data\n", + "used in the bootstrap analysis. The bootstrap analysis returns a data\n", + "set after a given number of bootstrap operations (as many as we have\n", + "data points). This data set consists of estimated mean values for each\n", + "bootstrap operation. The histogram generated by the bootstrap method\n", + "shows that the distribution for these mean values is also a Gaussian,\n", + "centered around the mean value $\\mu=100$ but with standard deviation\n", + "$\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in\n", + "this case the same as the number of original data points). The value\n", + "of the standard deviation is what we expect from the central limit\n", + "theorem." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "from numpy import *\n", + "from numpy.random import randint, randn\n", + "from time import time\n", + "import matplotlib.mlab as mlab\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Returns mean of bootstrap samples \n", + "def stat(data):\n", + " return mean(data)\n", + "\n", + "# Bootstrap algorithm\n", + "def bootstrap(data, statistic, R):\n", + " t = zeros(R); n = len(data); inds = arange(n); t0 = time()\n", + " # non-parametric bootstrap \n", + " for i in range(R):\n", + " t[i] = statistic(data[randint(0,n,n)])\n", + "\n", + " # analysis \n", + " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Bootstrap Statistics :\")\n", + " print(\"original bias std. error\")\n", + " print(\"%8g %8g %14g %15g\" % (statistic(data), std(data),mean(t),std(t)))\n", + " return t\n", + "\n", + "\n", + "mu, sigma = 100, 15\n", + "datapoints = 10000\n", + "x = mu + sigma*random.randn(datapoints)\n", + "# bootstrap returns the data sample \n", + "t = bootstrap(x, stat, datapoints)\n", + "# the histogram of the bootstrapped data \n", + "n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)\n", + "\n", + "# add a 'best fit' line \n", + "y = mlab.normpdf( binsboot, mean(t), std(t))\n", + "lt = plt.plot(binsboot, y, 'r--', linewidth=1)\n", + "plt.xlabel('Smarts')\n", + "plt.ylabel('Probability')\n", + "plt.axis([99.5, 100.6, 0, 3.0])\n", + "plt.grid(True)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Various steps in cross-validation\n", + "\n", + "When the repetitive splitting of the data set is done randomly,\n", + "samples may accidently end up in a fast majority of the splits in\n", + "either training or test set. Such samples may have an unbalanced\n", + "influence on either model building or prediction evaluation. To avoid\n", + "this $k$-fold cross-validation structures the data splitting. The\n", + "samples are divided into $k$ more or less equally sized exhaustive and\n", + "mutually exclusive subsets. In turn (at each split) one of these\n", + "subsets plays the role of the test set while the union of the\n", + "remaining subsets constitutes the training set. Such a splitting\n", + "warrants a balanced representation of each sample in both training and\n", + "test set over the splits. Still the division into the $k$ subsets\n", + "involves a degree of randomness. This may be fully excluded when\n", + "choosing $k=n$. This particular case is referred to as leave-one-out\n", + "cross-validation (LOOCV). \n", + "\n", + "\n", + "* Define a range of interest for the penalty parameter.\n", + "\n", + "* Divide the data set into training and test set comprising samples $\\{1, \\ldots, n\\} \\setminus i$ and $\\{ i \\}$, respectively.\n", + "\n", + "* Fit the linear regression model by means of ridge estimation for each $\\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\\boldsymbol{\\sigma}_{-i}^2(\\lambda)$, as" ] }, { @@ -3918,7 +609,11 @@ "metadata": {}, "source": [ "$$\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", + "\\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", "$$" ] }, @@ -3926,9 +621,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "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", + "* 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", - "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" + "* 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" ] }, { @@ -3936,7 +633,9 @@ "metadata": {}, "source": [ "$$\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", + "\\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", "$$" ] }, @@ -3944,360 +643,26 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We will write this in a more compact form reserving $\\boldsymbol{D}$ for the domain of events, including the ouputs (targets) and the inputs. That is\n", - "in case we have a simple one-dimensional input and output case" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the more general case the various inputs should be replaced by the possible features represented by the input data set $\\boldsymbol{X}$. \n", - "We can now rewrite the above probability as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "It is a conditional probability (see below) and reads as the likelihood of a domain of events $\\boldsymbol{D}$ given a set of parameters $\\boldsymbol{\\beta}$.\n", + "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", - "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", + "5. Summarize the model using the sample of model evaluation scores\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", - "\n", - "We could now define a new cost function to minimize, namely the negative logarithm of the above PDF" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}=-\\log{\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})}=-\\sum_{i=0}^{n-1}\\log{p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which becomes" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}=\\frac{n}{2}\\log{2\\pi\\sigma^2}+\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Taking the derivative of the *new* cost function with respect to the parameters $\\beta$ we recognize our familiar OLS equation, namely" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right) =0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which leads to the well-known OLS equation for the optimal paramters $\\beta$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}!\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics. \n", - "\n", - "\n", - "A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry.\n", - "Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics.\n", - "\n", - "Assume we have two domains of events $X=[x_0,x_1,\\dots,x_{n-1}]$ and $Y=[y_0,y_1,\\dots,y_{n-1}]$.\n", - "\n", - "We define also the likelihood for $X$ and $Y$ as $p(X)$ and $p(Y)$ respectively.\n", - "The likelihood of a specific event $x_i$ (or $y_i$) is then written as $p(X=x_i)$ or just $p(x_i)=p_i$. \n", - "\n", - "**Union of events is given by.**" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(X \\cup Y)= p(X)+p(Y)-p(X \\cap Y).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**The product rule (aka joint probability) is given by.**" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(X \\cup Y)= p(X,Y)= p(X\\vert Y)p(Y)=p(Y\\vert X)p(X),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we read $p(X\\vert Y)$ as the likelihood of obtaining $X$ given $Y$.\n", - "\n", - "\n", - "\n", - "If we have independent events then $p(X,Y)=p(X)p(Y)$.\n", - "\n", - "\n", - "\n", - "The marginal probability is defined in terms of only one of the set of variables $X,Y$. For a discrete probability we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(X)=\\sum_{i=0}^{n-1}p(X,Y=y_i)=\\sum_{i=0}^{n-1}p(X\\vert Y=y_i)p(Y=y_i)=\\sum_{i=0}^{n-1}p(X\\vert y_i)p(y_i).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The conditional probability, if $p(Y) > 0$, is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)}=\\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If we combine the conditional probability with the marginal probability and the standard product rule, we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which we can rewrite as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(X\\vert Y)= \\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}=\\frac{p(Y\\vert X)p(X)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which is Bayes' theorem. It allows us to evaluate the uncertainty in in $X$ after we have observed $Y$. We can easily interchange $X$ with $Y$. \n", - "\n", - "\n", - "The quantity $p(Y\\vert X)$ on the right-hand side of the theorem is\n", - "evaluated for the observed data $Y$ and can be viewed as a function of\n", - "the parameter space represented by $X$. This function is not\n", - "necesseraly normalized and is normally called the likelihood function.\n", - "\n", - "The function $p(X)$ on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution.\n", - "\n", - "Let us try to illustrate Bayes' theorem through an example.\n", - "\n", - "\n", - "Let us suppose that you are undergoing a series of mammography scans in\n", - "order to rule out possible breast cancer cases. We define the\n", - "sensitivity for a positive event by the variable $X$. It takes binary\n", - "values with $X=1$ representing a positive event and $X=0$ being a\n", - "negative event. We reserve $Y$ as a classification parameter for\n", - "either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing).\n", - "\n", - "We let $Y=1$ represent the the case of having breast cancer and $Y=0$ as not.\n", - "\n", - "Let us assume that if you have breast cancer, the test will be positive with a probability of $0.8$, that is we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(X=1\\vert Y=1) =0.8.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of $80\\%$ for having cancer.\n", - "It is however not correct, as the following Bayesian analysis shows.\n", - "\n", - "\n", - "If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number.\n", - "Let us assume that the prior probability in the population as a whole is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(Y=1) =0.004.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(X=1\\vert Y=0) =0.1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(Y=1\\vert X=1)=\\frac{p(X=1\\vert Y=1)p(Y=1)}{p(X=1\\vert Y=1)p(Y=1)+p(X=1\\vert Y=0)p(Y=0)}=\\frac{0.8\\times 0.004}{0.8\\times 0.004+0.1\\times 0.996}=0.031.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "That is, in case of a positive test, there is only a $3\\%$ chance of having breast cancer!\n", - "\n", - "\n", - "\n", - "## Bayes' Theorem and Ridge and Lasso Regression\n", - "\n", - "Hitherto we have discussed Ridge and Lasso regression in terms of a\n", - "linear analysis. This may to many of you feel rather technical and\n", - "perhaps not that intuitive. The question is whether we can develop a\n", - "more intuitive way of understanding what Ridge and Lasso express.\n", - "\n", - "Before we proceed let us perform a Ridge, Lasso and OLS analysis of a polynomial fit. \n", - "\n", - "\n", - "We will play around with a study of the values for the optimal\n", - "parameters $\\boldsymbol{\\beta}$ using OLS, Ridge and Lasso regression. For\n", - "OLS, you will notice as function of the noise and polynomial degree,\n", - "that the parameters $\\beta$ will fluctuate from order to order in the\n", - "polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS.\n", - "\n", - "For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one." + "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial." ] }, { @@ -4311,65 +676,339 @@ "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn import linear_model\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", - "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", + "# A seed just to ensure that the random numbers are the same for every run.\n", + "# Useful for eventual debugging.\n", + "np.random.seed(3155)\n", + "\n", + "# Generate the data.\n", + "nsamples = 100\n", + "x = np.random.randn(nsamples)\n", + "y = 3*x**2 + np.random.randn(nsamples)\n", + "\n", + "## Cross-validation on Ridge regression using KFold only\n", + "\n", + "# Decide degree on polynomial to fit\n", + "poly = PolynomialFeatures(degree = 6)\n", + "\n", + "# Decide which values of lambda to use\n", + "nlambdas = 500\n", + "lambdas = np.logspace(-3, 5, nlambdas)\n", + "\n", + "# Initialize a KFold instance\n", + "k = 5\n", + "kfold = KFold(n_splits = k)\n", + "\n", + "# Perform the cross-validation to estimate MSE\n", + "scores_KFold = np.zeros((nlambdas, k))\n", + "\n", + "i = 0\n", + "for lmb in lambdas:\n", + " ridge = Ridge(alpha = lmb)\n", + " j = 0\n", + " for train_inds, test_inds in kfold.split(x):\n", + " xtrain = x[train_inds]\n", + " ytrain = y[train_inds]\n", + "\n", + " xtest = x[test_inds]\n", + " ytest = y[test_inds]\n", + "\n", + " Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n", + " ridge.fit(Xtrain, ytrain[:, np.newaxis])\n", + "\n", + " Xtest = poly.fit_transform(xtest[:, np.newaxis])\n", + " ypred = ridge.predict(Xtest)\n", + "\n", + " scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n", + "\n", + " j += 1\n", + " i += 1\n", + "\n", + "\n", + "estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n", + "\n", + "## Cross-validation using cross_val_score from sklearn along with KFold\n", + "\n", + "# kfold is an instance initialized above as:\n", + "# kfold = KFold(n_splits = k)\n", + "\n", + "estimated_mse_sklearn = np.zeros(nlambdas)\n", + "i = 0\n", + "for lmb in lambdas:\n", + " ridge = Ridge(alpha = lmb)\n", + "\n", + " X = poly.fit_transform(x[:, np.newaxis])\n", + " estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n", + "\n", + " # cross_val_score return an array containing the estimated negative mse for every fold.\n", + " # we have to the the mean of every array in order to get an estimate of the mse of the model\n", + " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n", + "\n", + " i += 1\n", + "\n", + "## Plot and compare the slightly different ways to perform cross-validation\n", + "\n", + "plt.figure()\n", + "\n", + "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n", + "plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n", + "\n", + "plt.xlabel('log10(lambda)')\n", + "plt.ylabel('mse')\n", + "\n", + "plt.legend()\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The bias-variance tradeoff\n", + "\n", + "\n", + "We will discuss the bias-variance tradeoff in the context of\n", + "continuous predictions such as regression. However, many of the\n", + "intuitions and ideas discussed here also carry over to classification\n", + "tasks. Consider a dataset $\\mathcal{L}$ consisting of the data\n", + "$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$. \n", + "\n", + "Let us assume that the true data is generated from a noisy model" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $\\epsilon$ is normally distributed with mean zero and standard deviation $\\sigma^2$.\n", + "\n", + "In our derivation of the ordinary least squares method we defined then\n", + "an approximation to the function $f$ in terms of the parameters\n", + "$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n", + "that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$. \n", + "\n", + "Thereafter we found the parameters $\\boldsymbol{\\beta}$ by optimizing the means squared error via the so-called cost function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can rewrite this as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\frac{1}{n}\\sum_i(f_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\sigma^2.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The three terms represent the square of the bias of the learning\n", + "method, which can be thought of as the error caused by the simplifying\n", + "assumptions built into the method. The second term represents the\n", + "variance of the chosen model and finally the last terms is variance of\n", + "the error $\\boldsymbol{\\epsilon}$.\n", + "\n", + "To derive this equation, we need to recall that the variance of $\\boldsymbol{y}$ and $\\boldsymbol{\\epsilon}$ are both equal to $\\sigma^2$. The mean value of $\\boldsymbol{\\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\\boldsymbol{\\tilde{y}}$.\n", + "We use a more compact notation in terms of the expectation value" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}})^2\\right],\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and adding and subtracting $\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]$ we get" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}}+\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right],\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which, using the abovementioned expectation values can be rewritten as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right]+\\mathrm{Var}\\left[\\boldsymbol{\\tilde{y}}\\right]+\\sigma^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "that is the rewriting in terms of the so-called bias, the variance of the model $\\boldsymbol{\\tilde{y}}$ and the variance of $\\boldsymbol{\\epsilon}$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", + "from sklearn.preprocessing import PolynomialFeatures\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.pipeline import make_pipeline\n", + "from sklearn.utils import resample\n", + "\n", + "np.random.seed(2018)\n", + "\n", + "n = 500\n", + "n_boostraps = 100\n", + "degree = 18 # A quite high value, just to show.\n", + "noise = 0.1\n", "\n", "# Make data set.\n", - "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", + "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", - "Maxpolydegree = 5\n", - "X = np.zeros((len(x),Maxpolydegree))\n", - "X[:,0] = 1.0\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", - "for polydegree in range(1, Maxpolydegree):\n", - " for degree in range(polydegree):\n", - " X[:,degree] = x**(degree)\n", + "# Combine x transformation and model into one operation.\n", + "# Not neccesary, but convenient.\n", + "model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n", + "\n", + "# The following (m x n_bootstraps) matrix holds the column vectors y_pred\n", + "# for each bootstrap iteration.\n", + "y_pred = np.empty((y_test.shape[0], n_boostraps))\n", + "for i in range(n_boostraps):\n", + " x_, y_ = resample(x_train, y_train)\n", + "\n", + " # Evaluate the new model on the same test data each time.\n", + " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n", + "\n", + "# Note: Expectations and variances taken w.r.t. different training\n", + "# data sets, hence the axis=1. Subsequent means are taken across the test data\n", + "# set in order to obtain a total value, but before this we have error/bias/variance\n", + "# calculated per data point in the test set.\n", + "# Note 2: The use of keepdims=True is important in the calculation of bias as this \n", + "# maintains the column vector form. Dropping this yields very unexpected results.\n", + "error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", + "bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", + "variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", + "print('Error:', error)\n", + "print('Bias^2:', bias)\n", + "print('Var:', variance)\n", + "print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))\n", + "\n", + "plt.plot(x[::5, :], y[::5, :], label='f(x)')\n", + "plt.scatter(x_test, y_test, label='Data points')\n", + "plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')\n", + "plt.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", + "from sklearn.preprocessing import PolynomialFeatures\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.pipeline import make_pipeline\n", + "from sklearn.utils import resample\n", + "\n", + "np.random.seed(2018)\n", + "\n", + "n = 40\n", + "n_boostraps = 100\n", + "maxdegree = 14\n", "\n", "\n", - "# 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", + "# 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", - "# 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", + "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()" ] @@ -4378,221 +1017,332 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "How can we understand this? \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", - "Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression. \n", - "\n", - "For ordinary least squares we postulated that the maximum likelihood for the doamin of events $\\boldsymbol{D}$ (one-dimensional case)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})],\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "is given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set $\\boldsymbol{\\beta}$ given a domain of events $\\boldsymbol{D}$? That is, how can we define the posterior probability" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Bayes' theorem comes to our rescue here since (omitting the normalization constant)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})\\propto p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})p(\\boldsymbol{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We have a model for $p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})$ but need one for the **prior** $p(\\boldsymbol{\\beta}$! \n", + "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", - "\n", - "With the posterior probability defined by a likelihood which we have\n", - "already modeled and an unknown prior, we are now ready to make\n", - "additional models for the prior.\n", - "\n", - "We can, based on our discussions of the variance of $\\boldsymbol{\\beta}$ and the mean value, assume that the prior for the values $\\boldsymbol{\\beta}$ is given by a Gaussian with mean value zero and variance $\\tau^2$, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Our posterior probability becomes then (omitting the normalization factor which is just a constant)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta\\vert\\boldsymbol{D})}=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can now optimize this quantity with respect to $\\boldsymbol{\\beta}$. As we\n", - "did for OLS, this is most conveniently done by taking the negative\n", - "logarithm of the posterior probability. Doing so and leaving out the\n", - "constants terms that do not depend on $\\beta$, we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{2\\tau^2}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and replacing $1/2\\tau^2$ with $\\lambda$ we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which is our Ridge cost function! Nice, isn't it?\n", + "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", - "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" + "You may also find this recent [article](https://www.pnas.org/content/116/32/15849) of interest." ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ - "$$\n", - "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n", - "$$" + "\"\"\"\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": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ - "Our posterior probability becomes then (omitting the normalization factor which is just a constant)" + "# Common imports\n", + "import os\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.utils import resample\n", + "from sklearn.metrics import mean_squared_error\n", + "# Where to save the figures and data files\n", + "PROJECT_ROOT_DIR = \"Results\"\n", + "FIGURE_ID = \"Results/FigureFiles\"\n", + "DATA_ID = \"DataFiles/\"\n", + "\n", + "if not os.path.exists(PROJECT_ROOT_DIR):\n", + " os.mkdir(PROJECT_ROOT_DIR)\n", + "\n", + "if not os.path.exists(FIGURE_ID):\n", + " os.makedirs(FIGURE_ID)\n", + "\n", + "if not os.path.exists(DATA_ID):\n", + " os.makedirs(DATA_ID)\n", + "\n", + "def image_path(fig_id):\n", + " return os.path.join(FIGURE_ID, fig_id)\n", + "\n", + "def data_path(dat_id):\n", + " return os.path.join(DATA_ID, dat_id)\n", + "\n", + "def save_fig(fig_id):\n", + " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", + "\n", + "infile = open(data_path(\"EoS.csv\"),'r')\n", + "\n", + "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n", + "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n", + "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n", + "EoS = EoS.dropna()\n", + "Energies = EoS['Energy']\n", + "Density = EoS['Density']\n", + "# The design matrix now as function of various polytrops\n", + "\n", + "Maxpolydegree = 30\n", + "X = np.zeros((len(Density),Maxpolydegree))\n", + "X[:,0] = 1.0\n", + "testerror = np.zeros(Maxpolydegree)\n", + "trainingerror = np.zeros(Maxpolydegree)\n", + "polynomial = np.zeros(Maxpolydegree)\n", + "\n", + "trials = 100\n", + "for polydegree in range(1, Maxpolydegree):\n", + " polynomial[polydegree] = polydegree\n", + " for degree in range(polydegree):\n", + " X[:,degree] = Density**(degree/3.0)\n", + "\n", + "# loop over trials in order to estimate the expectation value of the MSE\n", + " testerror[polydegree] = 0.0\n", + " trainingerror[polydegree] = 0.0\n", + " for samples in range(trials):\n", + " x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n", + " model = LinearRegression(fit_intercept=True).fit(x_train, y_train)\n", + " ypred = model.predict(x_train)\n", + " ytilde = model.predict(x_test)\n", + " testerror[polydegree] += mean_squared_error(y_test, ytilde)\n", + " trainingerror[polydegree] += mean_squared_error(y_train, ypred) \n", + "\n", + " testerror[polydegree] /= trials\n", + " trainingerror[polydegree] /= trials\n", + " print(\"Degree of polynomial: %3d\"% polynomial[polydegree])\n", + " print(\"Mean squared error on training data: %.8f\" % trainingerror[polydegree])\n", + " print(\"Mean squared error on test data: %.8f\" % testerror[polydegree])\n", + "\n", + "plt.plot(polynomial, np.log10(trainingerror), label='Training Error')\n", + "plt.plot(polynomial, np.log10(testerror), label='Test Error')\n", + "plt.xlabel('Polynomial degree')\n", + "plt.ylabel('log10[MSE]')\n", + "plt.legend()\n", + "plt.show()" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ - "$$\n", - "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n", - "$$" + "# Common imports\n", + "import os\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", + "from sklearn.metrics import mean_squared_error\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.model_selection import cross_val_score\n", + "\n", + "\n", + "# Where to save the figures and data files\n", + "PROJECT_ROOT_DIR = \"Results\"\n", + "FIGURE_ID = \"Results/FigureFiles\"\n", + "DATA_ID = \"DataFiles/\"\n", + "\n", + "if not os.path.exists(PROJECT_ROOT_DIR):\n", + " os.mkdir(PROJECT_ROOT_DIR)\n", + "\n", + "if not os.path.exists(FIGURE_ID):\n", + " os.makedirs(FIGURE_ID)\n", + "\n", + "if not os.path.exists(DATA_ID):\n", + " os.makedirs(DATA_ID)\n", + "\n", + "def image_path(fig_id):\n", + " return os.path.join(FIGURE_ID, fig_id)\n", + "\n", + "def data_path(dat_id):\n", + " return os.path.join(DATA_ID, dat_id)\n", + "\n", + "def save_fig(fig_id):\n", + " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", + "\n", + "infile = open(data_path(\"EoS.csv\"),'r')\n", + "\n", + "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n", + "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n", + "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n", + "EoS = EoS.dropna()\n", + "Energies = EoS['Energy']\n", + "Density = EoS['Density']\n", + "# The design matrix now as function of various polytrops\n", + "\n", + "Maxpolydegree = 30\n", + "X = np.zeros((len(Density),Maxpolydegree))\n", + "X[:,0] = 1.0\n", + "estimated_mse_sklearn = np.zeros(Maxpolydegree)\n", + "polynomial = np.zeros(Maxpolydegree)\n", + "k =5\n", + "kfold = KFold(n_splits = k)\n", + "\n", + "for polydegree in range(1, Maxpolydegree):\n", + " polynomial[polydegree] = polydegree\n", + " for degree in range(polydegree):\n", + " X[:,degree] = Density**(degree/3.0)\n", + " OLS = LinearRegression()\n", + "# loop over trials in order to estimate the expectation value of the MSE\n", + " estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)\n", + "#[:, np.newaxis]\n", + " estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)\n", + "\n", + "plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')\n", + "plt.xlabel('Polynomial degree')\n", + "plt.ylabel('log10[MSE]')\n", + "plt.legend()\n", + "plt.show()" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ - "Taking the negative\n", - "logarithm of the posterior probability and leaving out the\n", - "constants terms that do not depend on $\\beta$, we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{\\tau}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and replacing $1/\\tau$ with $\\lambda$ we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which is our Lasso cost function!" + "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()" ] } ],