diff --git a/doc/pub/week35/html/._week35-bs000.html b/doc/pub/week35/html/._week35-bs000.html index bdf04332b..cf0fbd92a 100644 --- a/doc/pub/week35/html/._week35-bs000.html +++ b/doc/pub/week35/html/._week35-bs000.html @@ -99,6 +99,11 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Example 2', 2, None, 'example-2'), ('Example 3', 2, None, 'example-3'), ('Example 4', 2, None, 'example-4'), + ('The mean squared error and its derivative', + 2, + None, + 'the-mean-squared-error-and-its-derivative'), + ('Other useful relations', 2, None, 'other-useful-relations'), ('Meet the Hessian Matrix', 2, None, 'meet-the-hessian-matrix'), ('Interpretations and optimizing our parameters', 2, @@ -312,7 +317,7 @@ MathJax.Hub.Config({
Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \). -The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable. +The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable or simply the input.
A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with
The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{x} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.
@@ -435,7 +442,7 @@ The first variable is called the dependent, the outcome or theConsider an experiment in which \( p \) characteristics of \( n \) samples are -measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix +
Consider an experiment in which \( p \) characteristics (or features) of \( n \) samples are +measured. The data from this experiment, for various explanatory/feature variables \( p \) are normally represented by a matrix \( \mathbf{X} \).
@@ -444,7 +451,7 @@ the linear regression model where \( \boldsymbol{\beta} = [\beta_0, \ldIn order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), -consider the model we discussed for describing nuclear binding energies. -
- -There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. -Assuming +we condiser a simple polynomial fit. +We assume our data can represented by a fourth-order polynomial. For the $i$th component we have
$$ -BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, +\tilde{y}_i = \beta_0+\beta_1x_i+\beta_2x_i^2+\beta_3x_i^3+\beta_4x_i^4. $$ -we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms. +
we have five predictors, that is the intercept $\beta_0$and the other terms \( \beta_i \). This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a \( p\times n \) matrix \( \boldsymbol{X} \).
@@ -444,7 +448,7 @@ so-called 14For every set of values \( y_i,x_i \) we have thus the corresponding set of equations
$$ \begin{align*} @@ -411,8 +416,6 @@ y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\ \end{align*} $$ -@@ -437,7 +440,7 @@ $$
In our introductory notes we looked at the so-called liquid drop model. Let us remind ourselves about what we did by looking at the code.
- -We restate the parts of the code we are most interested in.
- - -# Common imports
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from IPython.display import display
-import os
-
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
- os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
- os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
- os.makedirs(DATA_ID)
-
-def image_path(fig_id):
- return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
- return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
-
-infile = open(data_path("MassEval2016.dat"),'r')
-
-
-# Read the experimental data with Pandas
-Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
- names=('N', 'Z', 'A', 'Element', 'Ebinding'),
- widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),
- header=39,
- index_col=False)
-
-# Extrapolated values are indicated by '#' in place of the decimal place, so
-# the Ebinding column won't be numeric. Coerce to float and drop these entries.
-Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')
-Masses = Masses.dropna()
-# Convert from keV to MeV.
-Masses['Ebinding'] /= 1000
-
-# Group the DataFrame by nucleon number, A.
-Masses = Masses.groupby('A')
-# Find the rows of the grouped DataFrame with the maximum binding energy.
-Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
-A = Masses['A']
-Z = Masses['Z']
-N = Masses['N']
-Element = Masses['Element']
-Energies = Masses['Ebinding']
-
-# Now we set up the design matrix X
-X = np.zeros((len(A),5))
-X[:,0] = 1
-X[:,1] = A
-X[:,2] = A**(2.0/3.0)
-X[:,3] = A**(-1.0/3.0)
-X[:,4] = A**(-1.0)
-# Then nice printout using pandas
-DesignMatrix = pd.DataFrame(X)
-DesignMatrix.index = A
-DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
-display(DesignMatrix)
-
-With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as
-$$ -\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, -$$ - -throughout these lectures.
-diff --git a/doc/pub/week35/html/._week35-bs013.html b/doc/pub/week35/html/._week35-bs013.html index 7a660cbad..7e522f78f 100644 --- a/doc/pub/week35/html/._week35-bs013.html +++ b/doc/pub/week35/html/._week35-bs013.html @@ -99,6 +99,11 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Example 2', 2, None, 'example-2'), ('Example 3', 2, None, 'example-3'), ('Example 4', 2, None, 'example-4'), + ('The mean squared error and its derivative', + 2, + None, + 'the-mean-squared-error-and-its-derivative'), + ('Other useful relations', 2, None, 'other-useful-relations'), ('Meet the Hessian Matrix', 2, None, 'meet-the-hessian-matrix'), ('Interpretations and optimizing our parameters', 2, @@ -312,7 +317,7 @@ MathJax.Hub.Config({
Since \( \alpha \) is a scalar we have \( \alpha =\alpha^T=\boldsymbol{x}^T\boldsymbol{A}^T\boldsymbol{y} \). Defining now \( \boldsymbol{z}=\boldsymbol{x}^T\boldsymbol{A}^T \) we find that
$$ -\frac{\partial \alpha}{\partial \boldsymbol{y}} = \boldsymbol{z}^T=\boldsymbol{x}^T\boldsymbol{A}^T.. +\frac{\partial \alpha}{\partial \boldsymbol{y}} = \boldsymbol{z}^T=\boldsymbol{x}^T\boldsymbol{A}^T. $$ @@ -452,7 +459,7 @@ $$and if \( \boldsymbol{y}=\boldsymbol{x} \) we have
$$ -\frac{\partial \alpha}{\partial \boldsymbol{z}} = \boldsymbol{x}^T\frac{\partial \boldsymbol{x}}{\partial \boldsymbol{z}}. +\frac{\partial \alpha}{\partial \boldsymbol{z}} = 2\boldsymbol{x}^T\frac{\partial \boldsymbol{x}}{\partial \boldsymbol{z}}. $$ -$$ -\frac{\partial (\boldsymbol{b}^T\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{b}, -$$ - -$$ -\frac{\partial (\boldsymbol{a}^T\boldsymbol{A}\boldsymbol{a})}{\partial \boldsymbol{a}} = (\boldsymbol{A}+\boldsymbol{A}^T)\boldsymbol{a}, -$$ - -$$ -\frac{\partial tr(\boldsymbol{B}\boldsymbol{A})}{\partial \boldsymbol{A}} = \boldsymbol{B}^T, -$$ - -$$ -\frac{\partial \log{\vert\boldsymbol{A}\vert}}{\partial \boldsymbol{A}} = (\boldsymbol{A}^{-1})^T. -$$ - -See the jupyter-book (complete lecture notes) for the derivations of these relations.
-diff --git a/doc/pub/week35/html/._week35-bs022.html b/doc/pub/week35/html/._week35-bs022.html index 254e37a0c..d25e7c17d 100644 --- a/doc/pub/week35/html/._week35-bs022.html +++ b/doc/pub/week35/html/._week35-bs022.html @@ -99,6 +99,11 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Example 2', 2, None, 'example-2'), ('Example 3', 2, None, 'example-3'), ('Example 4', 2, None, 'example-4'), + ('The mean squared error and its derivative', + 2, + None, + 'the-mean-squared-error-and-its-derivative'), + ('Other useful relations', 2, None, 'other-useful-relations'), ('Meet the Hessian Matrix', 2, None, 'meet-the-hessian-matrix'), ('Interpretations and optimizing our parameters', 2, @@ -312,7 +317,7 @@ MathJax.Hub.Config({
-
We defined earlier a possible cost function using the mean squared error
+$$ +C(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, +$$ -A very important matrix we will meet again and again in Machine -Learning is the Hessian. It is given by the second derivative of the -cost function with respect to the parameter \( \beta \). Using the above -expression for derivatives of vectors and matrices, we find that the -second derivative of the cost function is, +
or using the design/feature matrix \( \boldsymbol{X} \) we have the more compact matrix-vector
+$$ +C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}. +$$ + +We note that the design matrix \( \boldsymbol{X} \) does not depend on the unknown parameters defined by the vector \( \boldsymbol{\beta} \). +We are now interested in minimizing the cost function with respect to the unknown parameters \( \boldsymbol{\beta} \).
+The mean squared error is scalar and if we use the results from the last example, we define a new vector
$$ -\frac{\partial}{\partial \boldsymbol{\beta}^T}\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} =\frac{\partial}{\partial \boldsymbol{\beta}}\left[-\frac{2}{n}\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right]=\frac{2}{n}\boldsymbol{X}^T\boldsymbol{X}. +\boldsymbol{w}=\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}, $$ -The Hessian matrix plays an important role and is defined here as
- +which depends on \( \boldsymbol{\beta} \). We rewrite the cost function as
$$ -\boldsymbol{H}=\boldsymbol{X}^T\boldsymbol{X}. +C(\boldsymbol{\beta})=\frac{1}{n}\boldsymbol{w}^T\boldsymbol{w}, $$ -For ordinary least squares, it is inversely proportional (derivation -next week) with the variance of the optimal parameters -\( \hat{\boldsymbol{\beta}} \). Furthermore, we will see later this week that is -(beside \( 1/n \)) equal to the covariance matrix. It plays also a very -important role in optmization algorithms and Principal Component -Analysis as a way to reduce the dimensionality of a machine learning -problem. -
+with partial derivative
+$$ +\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}}=\frac{2}{n}\boldsymbol{w}^T\frac{\partial \boldsymbol{w}}{\partial \boldsymbol{\beta}}, +$$ + +and using that
+$$ +\frac{\partial \boldsymbol{w}}{\partial \boldsymbol{\beta}}=-\boldsymbol{X}, +$$ + +where we ued the results from example two. Inserting the last expression we obtain
+$$ +\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}}=-\frac{2}{n}\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\boldsymbol{X}, +$$ + +or as
+$$ +\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}^T}=-\frac{2}{n}\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right). +$$ -Linear algebra question: Can we use the Hessian matrix to say something about properties of the cost function (our optmization problem)? (hint: think about convex or concave problems and how to relate these to a matrix!).
@@ -452,7 +475,7 @@ problem.
-
The residuals \( \boldsymbol{\epsilon} \) are in turn given by
+We list here some other useful relations we may encounter (recall that vectors are defined by boldfaced low-key letters)
$$ -\boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}, +\frac{\partial (\boldsymbol{b}^T\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{b}, $$ -and with
$$ -\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, +\frac{\partial tr(\boldsymbol{B}\boldsymbol{A})}{\partial \boldsymbol{A}} = \boldsymbol{B}^T, $$ -we have
$$ -\boldsymbol{X}^T\boldsymbol{\epsilon}=\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, +\frac{\partial \log{\vert\boldsymbol{A}\vert}}{\partial \boldsymbol{A}} = (\boldsymbol{A}^{-1})^T. $$ -meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.
-@@ -446,7 +445,7 @@ $$
-
It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to -write +
A very important matrix we will meet again and again in Machine +Learning is the Hessian. It is given by the second derivative of the +cost function with respect to the parameter \( \beta \). Using the above +expression for derivatives of vectors and matrices, we find that the +second derivative of the mean squared error as cost function is,
- -# matrix inversion to find beta
-beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
-# and then make the prediction
-ytilde = X @ beta
-
-Alternatively, you can use the least squares functionality in Numpy as
+The Hessian matrix plays an important role and is defined here as
- -fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
-ytildenp = np.dot(fit,X.T)
-
-And finally we plot our fit with and compare with data
- - -Masses['Eapprox'] = ytilde
-# Generate a plot comparing the experimental with the fitted values values.
-fig, ax = plt.subplots()
-ax.set_xlabel(r'$A = N + Z$')
-ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$')
-ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,
- label='Ame2016')
-ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',
- label='Fit')
-ax.legend()
-save_fig("Masses2016OLS")
-plt.show()
-
-For ordinary least squares, it is inversely proportional (derivation +next week) with the variance of the optimal parameters +\( \hat{\boldsymbol{\beta}} \). Furthermore, we will see later this week that is +(beside \( 1/n \)) equal to the covariance matrix. It plays also a very +important role in optmization algorithms and Principal Component +Analysis as a way to reduce the dimensionality of a machine learning +problem. +
+Linear algebra question: Can we use the Hessian matrix to say something about properties of the cost function (our optmization problem)? (hint: think about convex or concave problems and how to relate these to a matrix!).
@@ -514,7 +459,7 @@ plt.show()
-
The residuals \( \boldsymbol{\epsilon} \) are in turn given by
+$$ +\boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}, +$$ -We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of Scikit-Learn in the introductory slides. -Since we are not using Scikit-Learn here we can define our own \( R2 \) function as -
+and with
+$$ +\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, +$$ - -def R2(y_data, y_model):
- return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
-
+we have
+$$ +\boldsymbol{X}^T\boldsymbol{\epsilon}=\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, +$$ + +meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.
and we would be using it as
- - -print(R2(Energies,ytilde))
-
-We can easily add our MSE score as
- - -def MSE(y_data,y_model):
- n = np.size(y_model)
- return np.sum((y_data-y_model)**2)/n
-
-print(MSE(Energies,ytilde))
-
-and finally the relative error as
- - -def RelativeError(y_data,y_model):
- return abs((y_data-y_model)/y_data)
-print(RelativeError(Energies, ytilde))
-
-
-
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. +
It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to +write
+ + +# matrix inversion to find beta
+beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
+# and then make the prediction
+ytilde = X @ beta
+
Alternatively, you can use the least squares functionality in Numpy as
+ + +fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
+ytildenp = np.dot(fit,X.T)
+
+And finally we plot our fit with and compare with data
+ + +Masses['Eapprox'] = ytilde
+# Generate a plot comparing the experimental with the fitted values values.
+fig, ax = plt.subplots()
+ax.set_xlabel(r'$A = N + Z$')
+ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$')
+ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,
+ label='Ame2016')
+ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',
+ label='Fit')
+ax.legend()
+save_fig("Masses2016OLS")
+plt.show()
+
+
-
We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of Scikit-Learn in the introductory slides. +Since we are not using Scikit-Learn here we can define our own \( R2 \) function as +
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):
+ 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):
+
+and we would be using it as
+ + +print(R2(Energies,ytilde))
+
+We can easily add our MSE score as
+ + +def MSE(y_data,y_model):
n = np.size(y_model)
return np.sum((y_data-y_model)**2)/n
-x = np.random.rand(100)
-y = 2.0+5*x*x+0.1*np.random.randn(100)
+print(MSE(Energies,ytilde))
+
+and finally the relative error as
-# 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)) + +def RelativeError(y_data,y_model):
+ return abs((y_data-y_model)/y_data)
+print(RelativeError(Energies, ytilde))
-
# 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
-
-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. +
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.
+@@ -465,7 +450,7 @@ normally recommend using the latter functionality.
- -
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))
+
+The Boston housing -data set was originally a part of UCI Machine Learning Repository -and has been removed now. The data set is now included in Scikit-Learn's -library. There are 506 samples and 13 feature (predictor) variables -in this data set. The objective is to predict the value of prices of -the house using the features (predictors) listed here. -
-The features/predictors are
-diff --git a/doc/pub/week35/html/._week35-bs030.html b/doc/pub/week35/html/._week35-bs030.html index 0f870e629..838e7b114 100644 --- a/doc/pub/week35/html/._week35-bs030.html +++ b/doc/pub/week35/html/._week35-bs030.html @@ -99,6 +99,11 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Example 2', 2, None, 'example-2'), ('Example 3', 2, None, 'example-3'), ('Example 4', 2, None, 'example-4'), + ('The mean squared error and its derivative', + 2, + None, + 'the-mean-squared-error-and-its-derivative'), + ('Other useful relations', 2, None, 'other-useful-relations'), ('Meet the Hessian Matrix', 2, None, 'meet-the-hessian-matrix'), ('Interpretations and optimizing our parameters', 2, @@ -312,7 +317,7 @@ MathJax.Hub.Config({
-
We start by importing the libraries
+import numpy as np
-import matplotlib.pyplot as plt
+ # 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()
-import pandas as pd
-import seaborn as sns
-
-and load the Boston Housing DataSet from Scikit-Learn
- - - -from sklearn.datasets import load_boston
-
-boston_dataset = load_boston()
-
-# boston_dataset is a dictionary
-# let's check what it contains
-boston_dataset.keys()
-
-Then we invoke Pandas
- - -boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)
-boston.head()
-boston['MEDV'] = boston_dataset.target
-
-and preprocess the data
- - -# check for missing values in all the columns
-boston.isnull().sum()
-
-We can then visualize the data
- - -# set the size of the figure
-sns.set(rc={'figure.figsize':(11.7,8.27)})
-
-# plot a histogram showing the distribution of the target values
-sns.distplot(boston['MEDV'], bins=30)
-plt.show()
-
-It is now useful to look at the correlation matrix
- - -# compute the pair wise correlation for all columns
-correlation_matrix = boston.corr().round(2)
-# use the heatmap function from seaborn to plot the correlation matrix
-# annot = True to print the values inside the square
-sns.heatmap(data=correlation_matrix, annot=True)
-
-From the above coorelation plot we can see that MEDV is strongly correlated to LSTAT and RM. We see also that RAD and TAX are stronly correlated, but we don't include this in our features together to avoid multi-colinearity
- - - -plt.figure(figsize=(20, 5))
-
-features = ['LSTAT', 'RM']
-target = boston['MEDV']
-
-for i, col in enumerate(features):
- plt.subplot(1, len(features) , i+1)
- x = boston[col]
- y = target
- plt.scatter(x, y, marker='o')
- plt.title(col)
- plt.xlabel(col)
- plt.ylabel('MEDV')
-
-Now we start training our model
- - -X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])
-Y = boston['MEDV']
-
-We split the data into training and test sets
- - - -from sklearn.model_selection import train_test_split
-
-# splits the training and test data set in 80% : 20%
-# assign random_state to any value.This ensures consistency.
-X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=5)
-print(X_train.shape)
-print(X_test.shape)
-print(Y_train.shape)
-print(Y_test.shape)
-
-Then we use the linear regression functionality from Scikit-Learn
- - -from sklearn.linear_model import LinearRegression
-from sklearn.metrics import mean_squared_error, r2_score
-
-lin_model = LinearRegression()
-lin_model.fit(X_train, Y_train)
-
-# model evaluation for training set
-
-y_train_predict = lin_model.predict(X_train)
-rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict)))
-r2 = r2_score(Y_train, y_train_predict)
-
-print("The model performance for training set")
-print("--------------------------------------")
-print('RMSE is {}'.format(rmse))
-print('R2 score is {}'.format(r2))
-print("\n")
-
-# model evaluation for testing set
-
-y_test_predict = lin_model.predict(X_test)
-# root mean square error of the model
-rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict)))
-
-# r-squared score of the model
-r2 = r2_score(Y_test, y_test_predict)
-
-print("The model performance for testing set")
-print("--------------------------------------")
-print('RMSE is {}'.format(rmse))
-print('R2 score is {}'.format(r2))
-
-# plotting the y_test vs y_pred
-# ideally should have been a straight line
-plt.scatter(Y_test, y_test_predict)
-plt.show()
+ 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
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. +
@@ -763,7 +472,7 @@ plt.show()
- -
Many Machine Learning problems involve thousands or even millions of -features for each training instance. Not only does this make training -extremely slow, it can also make it much harder to find a good -solution, as we will see. This problem is often referred to as the -curse of dimensionality. Fortunately, in real-world problems, it is -often possible to reduce the number of features considerably, turning -an intractable problem into a tractable one. +
The Boston housing +data set was originally a part of UCI Machine Learning Repository +and has been removed now. The data set is now included in Scikit-Learn's +library. There are 506 samples and 13 feature (predictor) variables +in this data set. The objective is to predict the value of prices of +the house using the features (predictors) listed here.
-Later we will discuss some of the most popular dimensionality reduction -techniques: the principal component analysis (PCA), Kernel PCA, and -Locally Linear Embedding (LLE). -
- -Principal component analysis and its various variants deal with the -problem of fitting a low-dimensional affine -subspace to a set of of -data points in a high-dimensional space. With its family of methods it -is one of the most used tools in data modeling, compression and -visualization. -
-The features/predictors are
+diff --git a/doc/pub/week35/html/._week35-bs032.html b/doc/pub/week35/html/._week35-bs032.html index 78af3c314..0f45d5f25 100644 --- a/doc/pub/week35/html/._week35-bs032.html +++ b/doc/pub/week35/html/._week35-bs032.html @@ -99,6 +99,11 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Example 2', 2, None, 'example-2'), ('Example 3', 2, None, 'example-3'), ('Example 4', 2, None, 'example-4'), + ('The mean squared error and its derivative', + 2, + None, + 'the-mean-squared-error-and-its-derivative'), + ('Other useful relations', 2, None, 'other-useful-relations'), ('Meet the Hessian Matrix', 2, None, 'meet-the-hessian-matrix'), ('Interpretations and optimizing our parameters', 2, @@ -312,7 +317,7 @@ MathJax.Hub.Config({
-
We start by importing the libraries
-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 -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. -
+ +import numpy as np
+import matplotlib.pyplot as plt
-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.
-
+import pandas as pd
+import seaborn as sns
+
and load the Boston Housing DataSet from Scikit-Learn
+ + + +from sklearn.datasets import load_boston
+
+boston_dataset = load_boston()
+
+# boston_dataset is a dictionary
+# let's check what it contains
+boston_dataset.keys()
+
+Then we invoke Pandas
+ + +boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)
+boston.head()
+boston['MEDV'] = boston_dataset.target
+
+and preprocess the data
+ + +# check for missing values in all the columns
+boston.isnull().sum()
+
+We can then visualize the data
+ + +# set the size of the figure
+sns.set(rc={'figure.figsize':(11.7,8.27)})
+
+# plot a histogram showing the distribution of the target values
+sns.distplot(boston['MEDV'], bins=30)
+plt.show()
+
+It is now useful to look at the correlation matrix
+ + +# compute the pair wise correlation for all columns
+correlation_matrix = boston.corr().round(2)
+# use the heatmap function from seaborn to plot the correlation matrix
+# annot = True to print the values inside the square
+sns.heatmap(data=correlation_matrix, annot=True)
+
+From the above coorelation plot we can see that MEDV is strongly correlated to LSTAT and RM. We see also that RAD and TAX are stronly correlated, but we don't include this in our features together to avoid multi-colinearity
+ + + +plt.figure(figsize=(20, 5))
+
+features = ['LSTAT', 'RM']
+target = boston['MEDV']
+
+for i, col in enumerate(features):
+ plt.subplot(1, len(features) , i+1)
+ x = boston[col]
+ y = target
+ plt.scatter(x, y, marker='o')
+ plt.title(col)
+ plt.xlabel(col)
+ plt.ylabel('MEDV')
+
+Now we start training our model
+ + +X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])
+Y = boston['MEDV']
+
+We split the data into training and test sets
+ + + +from sklearn.model_selection import train_test_split
+
+# splits the training and test data set in 80% : 20%
+# assign random_state to any value.This ensures consistency.
+X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=5)
+print(X_train.shape)
+print(X_test.shape)
+print(Y_train.shape)
+print(Y_test.shape)
+
+Then we use the linear regression functionality from Scikit-Learn
+ + +from sklearn.linear_model import LinearRegression
+from sklearn.metrics import mean_squared_error, r2_score
+
+lin_model = LinearRegression()
+lin_model.fit(X_train, Y_train)
+
+# model evaluation for training set
+
+y_train_predict = lin_model.predict(X_train)
+rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict)))
+r2 = r2_score(Y_train, y_train_predict)
+
+print("The model performance for training set")
+print("--------------------------------------")
+print('RMSE is {}'.format(rmse))
+print('R2 score is {}'.format(r2))
+print("\n")
+
+# model evaluation for testing set
+
+y_test_predict = lin_model.predict(X_test)
+# root mean square error of the model
+rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict)))
+
+# r-squared score of the model
+r2 = r2_score(Y_test, y_test_predict)
+
+print("The model performance for testing set")
+print("--------------------------------------")
+print('RMSE is {}'.format(rmse))
+print('R2 score is {}'.format(r2))
+
+# plotting the y_test vs y_pred
+# ideally should have been a straight line
+plt.scatter(Y_test, y_test_predict)
+plt.show()
+
+
-
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 -ensures that for each feature/predictor we study the mean value is -zero and the variance is one (every column in the design/feature -matrix). This scaling has the drawback that it does not ensure that -we have a particular maximum or minimum in our data set. Another -function included in Scikit-Learn is the MinMaxScaler which -ensures that all features are exactly between \( 0 \) and \( 1 \). The +
Many Machine Learning problems involve thousands or even millions of +features for each training instance. Not only does this make training +extremely slow, it can also make it much harder to find a good +solution, as we will see. This problem is often referred to as the +curse of dimensionality. Fortunately, in real-world problems, it is +often possible to reduce the number of features considerably, turning +an intractable problem into a tractable one.
+Later we will discuss some of the most popular dimensionality reduction +techniques: the principal component analysis (PCA), Kernel PCA, and +Locally Linear Embedding (LLE). +
+ +Principal component analysis and its various variants deal with the +problem of fitting a low-dimensional affine +subspace to a set of of +data points in a high-dimensional space. With its family of methods it +is one of the most used tools in data modeling, compression and +visualization. +
+
-
The Normalizer scales each data -point such that the feature vector has a euclidean length of one. In other words, it -projects a data point on the circle (or sphere in the case of higher dimensions) with a -radius of 1. This means every data point is scaled by a different number (by the -inverse of it’s length). -This normalization is often used when only the direction (or angle) of the data matters, -not the length of the feature vector. + +
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 +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.
-The RobustScaler works similarly to the StandardScaler in that it -ensures statistical properties for each feature that guarantee that -they are on the same scale. However, the RobustScaler uses the median -and quartiles, instead of mean and variance. This makes the -RobustScaler ignore data points that are very different from the rest -(like measurement errors). These odd data points are also called -outliers, and might often lead to trouble for other scaling -techniques. +
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.
-
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: -
- -$$ - x_j^{(i)} \rightarrow \frac{x_j^{(i)} - \overline{x}_j}{\sigma(x_j)}, -$$ - -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. +
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 +ensures that for each feature/predictor we study the mean value is +zero and the variance is one (every column in the design/feature +matrix). This scaling has the drawback that it does not ensure that +we have a particular maximum or minimum in our data set. Another +function included in Scikit-Learn is the MinMaxScaler which +ensures that all features are exactly between \( 0 \) and \( 1 \). The
@@ -436,7 +442,7 @@ This ensures that each feature has zero mean and unit standard deviation. For d
-
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. +
The Normalizer scales each data +point such that the feature vector has a euclidean length of one. In other words, it +projects a data point on the circle (or sphere in the case of higher dimensions) with a +radius of 1. This means every data point is scaled by a different number (by the +inverse of it’s length). +This normalization is often used when only the direction (or angle) of the data matters, +not the length of the feature vector.
- - -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
-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)
-
+The RobustScaler works similarly to the StandardScaler in that it +ensures statistical properties for each feature that guarantee that +they are on the same scale. However, the RobustScaler uses the median +and quartiles, instead of mean and variance. This makes the +RobustScaler ignore data points that are very different from the rest +(like measurement errors). These odd data points are also called +outliers, and might often lead to trouble for other scaling +techniques. +
Small exercise: perform the standard scaling by including the standard deviation and compare with what Scikit-Learn gives.
@@ -477,7 +456,7 @@ display(XPandas-Xscaled)
-
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 +
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:
$$ -x_j^{(i)} \rightarrow (b-a)\frac{x_j^{(i)} - \min(x_j)}{\max(x_j) - \min(x_j)} - a + x_j^{(i)} \rightarrow \frac{x_j^{(i)} - \overline{x}_j}{\sigma(x_j)}, $$ -where \( \min(x_j) \) and \( \max(x_j) \) return the minimum and maximum value of \( x_j \) over the data set, respectively.
+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. +
@@ -436,7 +443,7 @@ $$
-
One of -the aims is to reproduce Figure 2.11 of Hastie et al. -We will also use Ridge and Lasso regression. +
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.
-Our data is defined by \( x\in [-3,3] \) with a total of for example \( 100 \) data points.
np.random.seed()
-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)
-
-where \( y \) is the function we want to fit with a given polynomial.
- -Write a first code which sets up a design matrix \( X \) defined by a fifth-order polynomial. Scale your data and split it in training and test data.
- - -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
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 = 50
-maxdegree = 5
-# 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()
+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)
Small exercise: perform the standard scaling by including the standard deviation and compare with what Scikit-Learn gives.
@@ -519,7 +484,7 @@ plt.show()
-
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 +
- -# 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)))
-
-where \( \min(x_j) \) and \( \max(x_j) \) return the minimum and maximum value of \( x_j \) over the data set, respectively.
@@ -539,7 +443,7 @@ clf = skl.48
One of
+the aims is to reproduce Figure 2.11 of Hastie et al.
+We will also use Ridge and Lasso regression.
+ Our data is defined by \( x\in [-3,3] \) with a total of for example \( 100 \) data points. where \( y \) is the function we want to fit with a given polynomial. Write a first code which sets up a design matrix \( X \) defined by a fifth-order polynomial. Scale your data and split it in training and test data.
@@ -424,7 +526,7 @@ MathJax.Hub.Config({
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 The hat over \( \boldsymbol{\beta} \) means we have the optimal parameters after minimization of the cost function. This means that our best model is defined as We now define a matrix We can rewrite The matrix \( \boldsymbol{A} \) has the important property that \( \boldsymbol{A}^2=\boldsymbol{A} \). This is the definition of a projection matrix.
-We can then interpret our optimal model \( \tilde{\boldsymbol{y}} \) as being represented by an orthogonal projection of \( \boldsymbol{y} \) onto a space defined by the column vectors of \( \boldsymbol{X} \). In our case here the matrix \( \boldsymbol{A} \) is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix.
-
@@ -454,7 +546,7 @@ We can then interpret our optimal model \( \tilde{\boldsymbol{y}} \) as being re
We have defined the residual error as 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} \).
@@ -431,7 +431,7 @@ $$
If the matrix \( \boldsymbol{X} \) is an orthogonal (or unitary in case of complex values) matrix, we have 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 In this case the matrix \( \boldsymbol{A} \) becomes The hat over \( \boldsymbol{\beta} \) means we have the optimal parameters after minimization of the cost function. This means that our best model is defined as and we have the obvious case We now define a matrix This serves also as a useful test of our codes. We can rewrite The matrix \( \boldsymbol{A} \) has the important property that \( \boldsymbol{A}^2=\boldsymbol{A} \). This is the definition of a projection matrix.
+We can then interpret our optimal model \( \tilde{\boldsymbol{y}} \) as being represented by an orthogonal projection of \( \boldsymbol{y} \) onto a space defined by the column vectors of \( \boldsymbol{X} \). In our case here the matrix \( \boldsymbol{A} \) is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix.
+
@@ -442,7 +461,7 @@ $$
The examples we have looked at so far are cases where we normally can
-invert the matrix \( \boldsymbol{X}^T\boldsymbol{X} \). Using a polynomial expansion where we fit of various functions leads to
-row vectors of the design matrix which are essentially orthogonal due
-to the polynomial character of our model. Obtaining the inverse of the
-design matrix is then often done via a so-called LU, QR or Cholesky
-decomposition.
- As we will also see in the first project,
-this may
-however not the be case in general and a standard matrix inversion
-algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.
- There is however a way to circumvent this problem and also
-gain some insights about the ordinary least squares approach, and
-later shrinkage methods like Ridge and Lasso regressions.
- This is given by the Singular Value Decomposition (SVD) algorithm,
-perhaps the most powerful linear algebra algorithm. The SVD provides
-a numerically stable matrix decomposition that is used in a large
-swath oc applications and the decomposition is always stable
-numerically.
- In machine learning it plays a central role in dealing with for
-example design matrices that may be near singular or singular.
-Furthermore, as we will see here, the singular values can be related
-to the covariance matrix (and thereby the correlation matrix) and in
-turn the variance of a given quantity. It plays also an important role
-in the principal component analysis where high-dimensional data can be
-reduced to the statistically relevant features.
- We have defined the residual error as 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} \).
@@ -466,7 +438,7 @@ reduced to the statistically relevant features.
If the matrix \( \boldsymbol{X} \) is an orthogonal (or unitary in case of complex values) matrix, we have One of the typical problems we encounter with linear regression, in particular
-when the matrix \( \boldsymbol{X} \) (our so-called design matrix) is high-dimensional,
-are problems with near singular or singular matrices. The column vectors of \( \boldsymbol{X} \)
-may be linearly dependent, normally referred to as super-collinearity.
-This means that the matrix may be rank deficient and it is basically impossible to
-to model the data using linear regression. As an example, consider the matrix
- The columns of \( \boldsymbol{X} \) are linearly dependent. We see this easily since the
-the first column is the row-wise sum of the other two columns. The rank (more correct,
-the column rank) of a matrix is the dimension of the space spanned by the
-column vectors. Hence, the rank of \( \mathbf{X} \) is equal to the number
-of linearly independent columns. In this particular case the matrix has rank 2.
- Super-collinearity of an \( (n \times p) \)-dimensional design matrix \( \mathbf{X} \) implies
-that the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this
- In this case the matrix \( \boldsymbol{A} \) becomes We see easily that \( \mbox{det}(\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined.
-This is equivalent to saying that the matrix \( \boldsymbol{X} \) has at least an eigenvalue which is zero.
- and we have the obvious case This serves also as a useful test of our codes.
@@ -471,7 +449,7 @@ This is equivalent to saying that the matrix \( \boldsymbol{X} \) has at least a
If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem has linearly dependent column vectors, we will not be able to compute the inverse
-of \( \boldsymbol{X}^T\boldsymbol{X} \) and we cannot find the parameters (estimators) \( \beta_i \).
-The estimators are only well-defined if \( (\boldsymbol{X}^{T}\boldsymbol{X})^{-1} \) exits.
-This is more likely to happen when the matrix \( \boldsymbol{X} \) is high-dimensional. In this case it is likely to encounter a situation where
-the regression parameters \( \beta_i \) cannot be estimated.
+ The examples we have looked at so far are cases where we normally can
+invert the matrix \( \boldsymbol{X}^T\boldsymbol{X} \). Using a polynomial expansion where we fit of various functions leads to
+row vectors of the design matrix which are essentially orthogonal due
+to the polynomial character of our model. Obtaining the inverse of the
+design matrix is then often done via a so-called LU, QR or Cholesky
+decomposition.
A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change 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.
+ 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.
@@ -446,7 +473,7 @@ $$
From standard linear algebra we know that a square matrix \( \boldsymbol{X} \) can be diagonalized if and only it is
-a so-called normal matrix, that is if \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \)
-we have \( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) or if \( \boldsymbol{X}\in {\mathbb{C}}^{n\times n} \) we have \( \boldsymbol{X}\boldsymbol{X}^{\dagger}=\boldsymbol{X}^{\dagger}\boldsymbol{X} \).
-The matrix has then a set of eigenpairs
+ One of the typical problems we encounter with linear regression, in particular
+when the matrix \( \boldsymbol{X} \) (our so-called design matrix) is high-dimensional,
+are problems with near singular or singular matrices. The column vectors of \( \boldsymbol{X} \)
+may be linearly dependent, normally referred to as super-collinearity.
+This means that the matrix may be rank deficient and it is basically impossible to
+to model the data using linear regression. As an example, consider the matrix
+ The columns of \( \boldsymbol{X} \) are linearly dependent. We see this easily since the
+the first column is the row-wise sum of the other two columns. The rank (more correct,
+the column rank) of a matrix is the dimension of the space spanned by the
+column vectors. Hence, the rank of \( \mathbf{X} \) is equal to the number
+of linearly independent columns. In this particular case the matrix has rank 2.
Super-collinearity of an \( (n \times p) \)-dimensional design matrix \( \mathbf{X} \) implies
+that the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this
+ and the eigenvalues are given by the diagonal matrix The matrix \( \boldsymbol{X} \) can be written in terms of an orthogonal/unitary transformation \( \boldsymbol{U} \) with \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I} \) or \( \boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I} \). Not all square matrices are diagonalizable. A matrix like the one discussed above is not diagonalizable, it is a so-called defective matrix. It is easy to see that the condition
-\( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) is not fulfilled.
+ We see easily that \( \mbox{det}(\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined.
+This is equivalent to saying that the matrix \( \boldsymbol{X} \) has at least an eigenvalue which is zero.
@@ -458,7 +478,7 @@ $$
However, and this is the strength of the SVD algorithm, any general
-matrix \( \boldsymbol{X} \) can be decomposed in terms of a diagonal matrix and
-two orthogonal/unitary matrices. The Singular Value Decompostion
-(SVD) theorem
-states that a general \( m\times n \) matrix \( \boldsymbol{X} \) can be written in
-terms of a diagonal matrix \( \boldsymbol{\Sigma} \) of dimensionality \( m\times n \)
-and two orthognal matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \), where the first has
-dimensionality \( m \times m \) and the last dimensionality \( n\times n \).
-We have then
- If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem As an example, the above defective matrix can be decomposed as has linearly dependent column vectors, we will not be able to compute the inverse
+of \( \boldsymbol{X}^T\boldsymbol{X} \) and we cannot find the parameters (estimators) \( \beta_i \).
+The estimators are only well-defined if \( (\boldsymbol{X}^{T}\boldsymbol{X})^{-1} \) exits.
+This is more likely to happen when the matrix \( \boldsymbol{X} \) is high-dimensional. In this case it is likely to encounter a situation where
+the regression parameters \( \beta_i \) cannot be estimated.
+ A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change with eigenvalues \( \sigma_1=2 \) and \( \sigma_2=0 \).
-The SVD exits always!
- The SVD
-decomposition (singular values) gives eigenvalues
-\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=p \), the
-eigenvalues (singular values) are zero.
- In the general case, where our design matrix \( \boldsymbol{X} \) has dimension
-\( n\times p \), the matrix is thus decomposed into an \( n\times n \)
-orthogonal matrix \( \boldsymbol{U} \), a \( p\times p \) orthogonal matrix \( \boldsymbol{V} \)
-and a diagonal matrix \( \boldsymbol{\Sigma} \) with \( r=\mathrm{min}(n,p) \)
-singular values \( \sigma_i\geq 0 \) on the main diagonal and zeros filling
-the rest of the matrix. There are at most \( p \) singular values
-assuming that \( n > p \). In our regression examples for the nuclear
-masses and the equation of state this is indeed the case, while for
-the Ising model we have \( p > n \). These are often cases that lead to
-near singular or singular matrices.
- The columns of \( \boldsymbol{U} \) are called the left singular vectors while the columns of \( \boldsymbol{V} \) are the right singular vectors. 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.
@@ -469,7 +453,7 @@ near singular or singular matrices.
If we assume that \( n > p \), then our matrix \( \boldsymbol{U} \) has dimension \( n
-\times n \). The last \( n-p \) columns of \( \boldsymbol{U} \) become however
-irrelevant in our calculations since they are multiplied with the
-zeros in \( \boldsymbol{\Sigma} \).
+ From standard linear algebra we know that a square matrix \( \boldsymbol{X} \) can be diagonalized if and only it is
+a so-called normal matrix, that is if \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \)
+we have \( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) or if \( \boldsymbol{X}\in {\mathbb{C}}^{n\times n} \) we have \( \boldsymbol{X}\boldsymbol{X}^{\dagger}=\boldsymbol{X}^{\dagger}\boldsymbol{X} \).
+The matrix has then a set of eigenpairs
The economy-size decomposition removes extra rows or columns of zeros
-from the diagonal matrix of singular values, \( \boldsymbol{\Sigma} \), along with the columns
-in either \( \boldsymbol{U} \) or \( \boldsymbol{V} \) that multiply those zeros in the expression.
-Removing these zeros and columns can improve execution time
-and reduce storage requirements without compromising the accuracy of
-the decomposition.
- If \( n > p \), we keep only the first \( p \) columns of \( \boldsymbol{U} \) and \( \boldsymbol{\Sigma} \) has dimension \( p\times p \).
-If \( p > n \), then only the first \( n \) columns of \( \boldsymbol{V} \) are computed and \( \boldsymbol{\Sigma} \) has dimension \( n\times n \).
-The \( n=p \) case is obvious, we retain the full SVD.
-In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.
+ and the eigenvalues are given by the diagonal matrix The matrix \( \boldsymbol{X} \) can be written in terms of an orthogonal/unitary transformation \( \boldsymbol{U} \) with \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I} \) or \( \boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I} \). Not all square matrices are diagonalizable. A matrix like the one discussed above is not diagonalizable, it is a so-called defective matrix. It is easy to see that the condition
+\( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) is not fulfilled.
@@ -444,7 +465,7 @@ In general the economy-size SVD leads to less FLOPS and still conserving the des
The matrix \( \boldsymbol{X} \) has columns that are linearly dependent. The first
-column is the row-wise sum of the other two columns. The rank of a
-matrix (the column rank) is the dimension of space spanned by the
-column vectors. The rank of the matrix is the number of linearly
-independent columns, in this case just \( 2 \). We see this from the
-singular values when running the above code. Running the standard
-inversion algorithm for matrix inversion with \( \boldsymbol{X}^T\boldsymbol{X} \) results
-in the program terminating due to a singular matrix.
+ However, and this is the strength of the SVD algorithm, any general
+matrix \( \boldsymbol{X} \) can be decomposed in terms of a diagonal matrix and
+two orthogonal/unitary matrices. The Singular Value Decompostion
+(SVD) theorem
+states that a general \( m\times n \) matrix \( \boldsymbol{X} \) can be written in
+terms of a diagonal matrix \( \boldsymbol{\Sigma} \) of dimensionality \( m\times n \)
+and two orthognal matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \), where the first has
+dimensionality \( m \times m \) and the last dimensionality \( n\times n \).
+We have then
As an example, the above defective matrix can be decomposed as with eigenvalues \( \sigma_1=2 \) and \( \sigma_2=0 \).
+The SVD exits always!
+ The SVD
+decomposition (singular values) gives eigenvalues
+\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=p \), the
+eigenvalues (singular values) are zero.
+ In the general case, where our design matrix \( \boldsymbol{X} \) has dimension
+\( n\times p \), the matrix is thus decomposed into an \( n\times n \)
+orthogonal matrix \( \boldsymbol{U} \), a \( p\times p \) orthogonal matrix \( \boldsymbol{V} \)
+and a diagonal matrix \( \boldsymbol{\Sigma} \) with \( r=\mathrm{min}(n,p) \)
+singular values \( \sigma_i\geq 0 \) on the main diagonal and zeros filling
+the rest of the matrix. There are at most \( p \) singular values
+assuming that \( n > p \). In our regression examples for the nuclear
+masses and the equation of state this is indeed the case, while for
+the Ising model we have \( p > n \). These are often cases that lead to
+near singular or singular matrices.
+ The columns of \( \boldsymbol{U} \) are called the left singular vectors while the columns of \( \boldsymbol{V} \) are the right singular vectors.
The \( U \), \( S \), and \( V \) matrices returned from the svd() function
-cannot be multiplied directly.
+ If we assume that \( n > p \), then our matrix \( \boldsymbol{U} \) has dimension \( n
+\times n \). The last \( n-p \) columns of \( \boldsymbol{U} \) become however
+irrelevant in our calculations since they are multiplied with the
+zeros in \( \boldsymbol{\Sigma} \).
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.
+ The economy-size decomposition removes extra rows or columns of zeros
+from the diagonal matrix of singular values, \( \boldsymbol{\Sigma} \), along with the columns
+in either \( \boldsymbol{U} \) or \( \boldsymbol{V} \) that multiply those zeros in the expression.
+Removing these zeros and columns can improve execution time
+and reduce storage requirements without compromising the accuracy of
+the decomposition.
If 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
+ If \( n > p \), we keep only the first \( p \) columns of \( \boldsymbol{U} \) and \( \boldsymbol{\Sigma} \) has dimension \( p\times p \).
+If \( p > n \), then only the first \( n \) columns of \( \boldsymbol{V} \) are computed and \( \boldsymbol{\Sigma} \) has dimension \( n\times n \).
+The \( n=p \) case is obvious, we retain the full SVD.
+In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.
@@ -440,7 +451,7 @@ example
Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies. Our starting point is our design matrix \( \boldsymbol{X} \) of dimension \( n\times p \) We can SVD decompose our matrix as where \( \boldsymbol{U} \) is an orthogonal matrix of dimension \( n\times n \), meaning that \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{U}^T\boldsymbol{U}=\boldsymbol{I}_n \). Here \( \boldsymbol{I}_n \) is the unit matrix of dimension \( n \times n \). Similarly, \( \boldsymbol{V} \) is an orthogonal matrix of dimension \( p\times p \), meaning that \( \boldsymbol{V}\boldsymbol{V}^T=\boldsymbol{V}^T\boldsymbol{V}=\boldsymbol{I}_p \). Here \( \boldsymbol{I}_n \) is the unit matrix of dimension \( p \times p \). Finally \( \boldsymbol{\Sigma} \) contains the singular values \( \sigma_i \). This matrix has dimension \( n\times p \) and the singular values \( \sigma_i \) are all positive. The non-zero values are ordered in descending order, that is All values beyond \( p-1 \) are all zero. The matrix \( \boldsymbol{X} \) has columns that are linearly dependent. The first
+column is the row-wise sum of the other two columns. The rank of a
+matrix (the column rank) is the dimension of space spanned by the
+column vectors. The rank of the matrix is the number of linearly
+independent columns, in this case just \( 2 \). We see this from the
+singular values when running the above code. Running the standard
+inversion algorithm for matrix inversion with \( \boldsymbol{X}^T\boldsymbol{X} \) results
+in the program terminating due to a singular matrix.
+
@@ -455,7 +492,7 @@ $$
As an example, consider the following \( 3\times 2 \) example for the matrix \( \boldsymbol{\Sigma} \) 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.
+ The singular values are \( \sigma_0=2 \) and \( \sigma_1=1 \). It is common to rewrite the matrix \( \boldsymbol{\Sigma} \) as where contains only the singular values. Note also (and we will use this below) that which is a \( 2\times 2 \) matrix while 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.
+ 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
@@ -479,7 +447,7 @@ decomposition of the design matrix.
The matrix that may cause problems for us is \( \boldsymbol{X}^T\boldsymbol{X} \). Using the SVD we can rewrite this matrix as Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies. Our starting point is our design matrix \( \boldsymbol{X} \) of dimension \( n\times p \) and using the orthogonality of the matrix \( \boldsymbol{U} \) we have We can SVD decompose our matrix as 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 \). 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 \). We can now insert the result for the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) into our equation for ordinary least squares where Similarly, \( \boldsymbol{V} \) is an orthogonal matrix of dimension \( p\times p \), meaning that \( \boldsymbol{V}\boldsymbol{V}^T=\boldsymbol{V}^T\boldsymbol{V}=\boldsymbol{I}_p \). Here \( \boldsymbol{I}_n \) is the unit matrix of dimension \( p \times p \). Finally \( \boldsymbol{\Sigma} \) contains the singular values \( \sigma_i \). This matrix has dimension \( n\times p \) and the singular values \( \sigma_i \) are all positive. The non-zero values are ordered in descending order, that is and using our SVD decomposition of \( \boldsymbol{X} \) we have which gives us, using the orthogonality of the matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \), 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} \). Note that the summation ends at \( p-1 \),
-that is \( \boldsymbol{\tilde{y}}\ne \boldsymbol{y} \).
- All values beyond \( p-1 \) are all zero.
@@ -463,7 +462,7 @@ that is \( \boldsymbol{\tilde{y}}\ne \boldsymbol{y} \).
As an example, consider the following \( 3\times 2 \) example for the matrix \( \boldsymbol{\Sigma} \) Let us study again \( \boldsymbol{X}^T\boldsymbol{X} \) in terms of our SVD, If we now multiply from the right with \( \boldsymbol{V} \) (using the orthogonality of \( \boldsymbol{V} \)) we get The singular values are \( \sigma_0=2 \) and \( \sigma_1=1 \). It is common to rewrite the matrix \( \boldsymbol{\Sigma} \) as This means the vectors \( \boldsymbol{v}_i \) of the orthogonal matrix \( \boldsymbol{V} \) are the eigenvectors of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \)
-with eigenvalues given by the singular values squared, that is
- where Similarly, if we use the SVD decomposition for the matrix \( \boldsymbol{X}\boldsymbol{X}^T \), we have contains only the singular values. Note also (and we will use this below) that If we now multiply from the right with \( \boldsymbol{U} \) (using the orthogonality of \( \boldsymbol{U} \)) we get which is a \( 2\times 2 \) matrix while This means the vectors \( \boldsymbol{u}_i \) of the orthogonal matrix \( \boldsymbol{U} \) are the eigenvectors of the matrix \( \boldsymbol{X}\boldsymbol{X}^T \)
-with eigenvalues given by the singular values squared, that is
- Important note: we have defined our design matrix \( \boldsymbol{X} \) to be an
-\( n\times p \) matrix. In most supervised learning cases we have that \( n
-\ge p \), and quite often we have \( n >> p \). For linear algebra based methods like ordinary least squares or Ridge regression, this leads to a matrix \( \boldsymbol{X}^T\boldsymbol{X} \) which is small and thereby easier to handle from a computational point of view (in terms of number of floating point operations).
- In our lectures, the number of columns will
-always refer to the number of features in our data set, while the
-number of rows represents the number of data inputs. Note that in
-other texts you may find the opposite notation. This has consequences
-for the definition of for example the covariance matrix and its relation to the SVD.
+ 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.
@@ -470,7 +486,7 @@ for the definition of for example the covariance matrix and its relation to the
Before we move on to a discussion of Ridge and Lasso regression, we want to show an important example of the above. We have already noted that the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) in ordinary
-least squares is proportional to the second derivative of the cost
-function, that is we have
- The matrix that may cause problems for us is \( \boldsymbol{X}^T\boldsymbol{X} \). Using the SVD we can rewrite this matrix as 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 and using the orthogonality of the matrix \( \boldsymbol{U} \) we have 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.
+ 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 \). We can now insert the result for the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) into our equation for ordinary least squares where and using our SVD decomposition of \( \boldsymbol{X} \) we have which gives us, using the orthogonality of the matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \), 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} \). Note that the summation ends at \( p-1 \),
+that is \( \boldsymbol{\tilde{y}}\ne \boldsymbol{y} \).
@@ -449,7 +470,7 @@ terms of the singular values. Let us develop these arguments, as they will pla
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.
- Let us study again \( \boldsymbol{X}^T\boldsymbol{X} \) in terms of our SVD, Suppose we have defined two vectors
-\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as
+ If we now multiply from the right with \( \boldsymbol{V} \) (using the orthogonality of \( \boldsymbol{V} \)) we get This means the vectors \( \boldsymbol{v}_i \) of the orthogonal matrix \( \boldsymbol{V} \) are the eigenvectors of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \)
+with eigenvalues given by the singular values squared, that is
where for example Similarly, if we use the SVD decomposition for the matrix \( \boldsymbol{X}\boldsymbol{X}^T \), we have With this definition and recalling that the variance is defined as If we now multiply from the right with \( \boldsymbol{U} \) (using the orthogonality of \( \boldsymbol{U} \)) we get we can rewrite the covariance matrix as This means the vectors \( \boldsymbol{u}_i \) of the orthogonal matrix \( \boldsymbol{U} \) are the eigenvectors of the matrix \( \boldsymbol{X}\boldsymbol{X}^T \)
+with eigenvalues given by the singular values squared, that is
+ Note: we have used \( 1/n \) in the above definitions of the sample variance and covariance. We assume then that we can calculate the exact mean value.
-What you will find in essentially all statistics texts are equations
-with a factor \( 1/(n-1) \). This is called Bessel's correction. This
-method corrects the bias in the estimation of the population variance
-and covariance. It also partially corrects the bias in the estimation
-of the population standard deviation. If you use a library like
-Scikit-Learn or nunmpy's function calculate the covariance, this
-quantity will be computed with a factor \( 1/(n-1) \).
+ Important note: we have defined our design matrix \( \boldsymbol{X} \) to be an
+\( n\times p \) matrix. In most supervised learning cases we have that \( n
+\ge p \), and quite often we have \( n >> p \). For linear algebra based methods like ordinary least squares or Ridge regression, this leads to a matrix \( \boldsymbol{X}^T\boldsymbol{X} \) which is small and thereby easier to handle from a computational point of view (in terms of number of floating point operations).
+ In our lectures, the number of columns will
+always refer to the number of features in our data set, while the
+number of rows represents the number of data inputs. Note that in
+other texts you may find the opposite notation. This has consequences
+for the definition of for example the covariance matrix and its relation to the SVD.
@@ -464,7 +477,7 @@ 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
+ Before we move on to a discussion of Ridge and Lasso regression, we want to show an important example of the above. We have already noted that the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) in ordinary
+least squares is proportional to the second derivative of the cost
+function, that is we have
The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]
-\in [-1,1] \). This avoids eventual problems with too large values. We
-can then define the correlation matrix for the two vectors \( \boldsymbol{x} \)
-and \( \boldsymbol{y} \) as
+ 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 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.
In the above example this is the function we constructed using pandas.
In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression
-we defined the design/feature matrix \( \boldsymbol{X} \) as
+ 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.
with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the
-entries \( n \) being the row elements.
-We can rewrite the design/feature matrix in terms of its column vectors as
+ Suppose we have defined two vectors
+\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as
with a given vector where for example With these definitions, we can now rewrite our \( 2\times 2 \)
-correlation/covariance matrix in terms of a moe general design/feature
-matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \)
-covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \)
+ With this definition and recalling that the variance is defined as we can rewrite the covariance matrix as Note: we have used \( 1/n \) in the above definitions of the sample variance and covariance. We assume then that we can calculate the exact mean value.
+What you will find in essentially all statistics texts are equations
+with a factor \( 1/(n-1) \). This is called Bessel's correction. This
+method corrects the bias in the estimation of the population variance
+and covariance. It also partially corrects the bias in the estimation
+of the population standard deviation. If you use a library like
+Scikit-Learn or nunmpy's function calculate the covariance, this
+quantity will be computed with a factor \( 1/(n-1) \).
and the correlation matrix
The Numpy function np.cov calculates the covariance elements using
-the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have
-the exact mean values. The following simple function uses the
-np.vstack function which takes each vector of dimension \( 1\times n \)
-and produces a \( 2\times n \) matrix \( \boldsymbol{W} \)
+ 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
Note that this assumes you have the features as the rows, and the inputs as columns, that is The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]
+\in [-1,1] \). This avoids eventual problems with too large values. We
+can then define the correlation matrix for the two vectors \( \boldsymbol{x} \)
+and \( \boldsymbol{y} \) as
+ which in turn is converted into into the \( 2\times 2 \) covariance matrix
-\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate
-the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy
-function np.mean(x). We can also extract the eigenvalues of the
-covariance matrix through the np.linalg.eig() function.
- In the above example this is the function we constructed using pandas.
@@ -478,7 +456,7 @@ C = np.c
The previous example can be converted into the correlation matrix by
-simply scaling the matrix elements with the variances. We should also
-subtract the mean values for each column. This leads to the following
-code which sets up the correlations matrix for the previous example in
-a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors).
+ In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression
+we defined the design/feature matrix \( \boldsymbol{X} \) as
with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the
+entries \( n \) being the row elements.
+We can rewrite the design/feature matrix in terms of its column vectors as
+ We 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.
+ with a given vector With these definitions, we can now rewrite our \( 2\times 2 \)
+correlation/covariance matrix in terms of a moe general design/feature
+matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \)
+covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \)
The above procedure with numpy can be made more compact if we use pandas. and the correlation matrix
@@ -481,7 +489,7 @@ this matrix we easily see that it is a positive definite matrix.
The Numpy function np.cov calculates the covariance elements using
+the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have
+the exact mean values. The following simple function uses the
+np.vstack function which takes each vector of dimension \( 1\times n \)
+and produces a \( 2\times n \) matrix \( \boldsymbol{W} \)
+ Note that this assumes you have the features as the rows, and the inputs as columns, that is which in turn is converted into into the \( 2\times 2 \) covariance matrix
+\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate
+the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy
+function np.mean(x). We can also extract the eigenvalues of the
+covariance matrix through the np.linalg.eig() function.
+ We whow here how we can set up the correlation matrix using pandas, as done in this simple code The previous example can be converted into the correlation matrix by
+simply scaling the matrix elements with the variances. We should also
+subtract the mean values for each column. This leads to the following
+code which sets up the correlations matrix for the previous example in
+a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors).
+ We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as We whow here how we can set up the correlation matrix using pandas, as done in this simple code To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \) If we then compute the expectation value (note the \( 1/n \) factor instead of \( 1/(n-1) \)) which is just where we wrote $$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ to indicate that this is the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \). It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). We expand this model to the Franke function discussed above.
@@ -457,6 +469,8 @@ $$
We saw earlier that Since the matrices here have dimension \( p\times p \), with \( p \) corresponding to the singular values, we defined earlier the matrix where the tilde-matrix \( \tilde{\boldsymbol{\Sigma}} \) is a matrix of dimension \( p\times p \) containing only the singular values \( \sigma_i \), that is meaning we can write Multiplying from the right with \( \boldsymbol{V} \) (using the orthogonality of \( \boldsymbol{V} \)) we get 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.
+
@@ -454,6 +505,9 @@ $$
This means the vectors \( \boldsymbol{v}_i \) of the orthogonal matrix \( \boldsymbol{V} \)
-are the eigenvectors of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) with eigenvalues
-given by the singular values squared, that is
- We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as In other words, each non-zero singular value of \( \boldsymbol{X} \) is a positive
-square root of an eigenvalue of \( \boldsymbol{X}^T\boldsymbol{X} \). It means also that
-the columns of \( \boldsymbol{V} \) are the eigenvectors of
-\( \boldsymbol{X}^T\boldsymbol{X} \). Since we have ordered the singular values of
-\( \boldsymbol{X} \) in a descending order, it means that the column vectors
-\( \boldsymbol{v}_i \) are hierarchically ordered by how much correlation they
-encode from the columns of \( \boldsymbol{X} \).
- Note that these are also the eigenvectors and eigenvalues of the
-Hessian matrix.
- If we now recall the definition of the covariance matrix (not using
-Bessel's correction) we have
- To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \) meaning that every squared non-singular value of \( \boldsymbol{X} \) divided by \( n \) (
-the number of samples) are the eigenvalues of the covariance
-matrix. Every singular value of \( \boldsymbol{X} \) is thus a positive square
-root of an eigenvalue of \( \boldsymbol{X}^T\boldsymbol{X} \). If the matrix \( \boldsymbol{X} \) is
-self-adjoint, the singular values of \( \boldsymbol{X} \) are equal to the
-absolute value of the eigenvalues of \( \boldsymbol{X} \).
- If we then compute the expectation value (note the \( 1/n \) factor instead of \( 1/(n-1) \)) which is just where we wrote $$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ to indicate that this is the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \). It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \).
@@ -459,6 +462,8 @@ absolute value of the eigenvalues of \( \boldsymbol{X} \).
For \( \boldsymbol{X}\boldsymbol{X}^T \) we found We saw earlier that Since the matrices here have dimension \( n\times n \), we have Since the matrices here have dimension \( p\times p \), with \( p \) corresponding to the singular values, we defined earlier the matrix leading to where the tilde-matrix \( \tilde{\boldsymbol{\Sigma}} \) is a matrix of dimension \( p\times p \) containing only the singular values \( \sigma_i \), that is Multiplying with \( \boldsymbol{U} \) from the right gives us the eigenvalue problem meaning we can write It means that the eigenvalues of \( \boldsymbol{X}\boldsymbol{X}^T \) are again given by
-the non-zero singular values plus now a series of zeros. The column
-vectors of \( \boldsymbol{U} \) are the eigenvectors of \( \boldsymbol{X}\boldsymbol{X}^T \) and
-measure how much correlations are contained in the rows of \( \boldsymbol{X} \).
- Multiplying from the right with \( \boldsymbol{V} \) (using the orthogonality of \( \boldsymbol{V} \)) we get Since we will mainly be interested in the correlations among the features
-of our data (the columns of \( \boldsymbol{X} \), the quantity of interest for us are the non-zero singular
-values and the column vectors of \( \boldsymbol{V} \).
-
@@ -452,6 +459,8 @@ values and the column vectors of \( \boldsymbol{V} \).
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
- or we can state it as where we have used the definition of a norm-2 vector, that is By minimizing the above equation with respect to the parameters
-\( \boldsymbol{\beta} \) we could then obtain an analytical expression for the
-parameters \( \boldsymbol{\beta} \). We can add a regularization parameter \( \lambda \) by
-defining a new cost function to be optimized, that is
+ This means the vectors \( \boldsymbol{v}_i \) of the orthogonal matrix \( \boldsymbol{V} \)
+are the eigenvectors of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) with eigenvalues
+given by the singular values squared, that is
which leads to the Ridge regression minimization problem where we
-require that \( \vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t \), where \( t \) is
-a finite number larger than zero. By defining
+ In other words, each non-zero singular value of \( \boldsymbol{X} \) is a positive
+square root of an eigenvalue of \( \boldsymbol{X}^T\boldsymbol{X} \). It means also that
+the columns of \( \boldsymbol{V} \) are the eigenvectors of
+\( \boldsymbol{X}^T\boldsymbol{X} \). Since we have ordered the singular values of
+\( \boldsymbol{X} \) in a descending order, it means that the column vectors
+\( \boldsymbol{v}_i \) are hierarchically ordered by how much correlation they
+encode from the columns of \( \boldsymbol{X} \).
+ Note that these are also the eigenvectors and eigenvalues of the
+Hessian matrix.
+ If we now recall the definition of the covariance matrix (not using
+Bessel's correction) we have
we have a new optimization equation which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. Here we have defined the norm-1 as meaning that every squared non-singular value of \( \boldsymbol{X} \) divided by \( n \) (
+the number of samples) are the eigenvalues of the covariance
+matrix. Every singular value of \( \boldsymbol{X} \) is thus a positive square
+root of an eigenvalue of \( \boldsymbol{X}^T\boldsymbol{X} \). If the matrix \( \boldsymbol{X} \) is
+self-adjoint, the singular values of \( \boldsymbol{X} \) are equal to the
+absolute value of the eigenvalues of \( \boldsymbol{X} \).
+
@@ -471,6 +464,8 @@ $$
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 For \( \boldsymbol{X}\boldsymbol{X}^T \) we found and
-taking the derivatives with respect to \( \boldsymbol{\beta} \) we obtain then
-a slightly modified matrix inversion problem which for finite values
-of \( \lambda \) does not suffer from singularity problems. We obtain
-the optimal parameters
- Since the matrices here have dimension \( n\times n \), we have with \( \boldsymbol{I} \) being a \( p\times p \) identity matrix with the constraint that leading to with \( t \) a finite positive number. If we keep the \( 1/n \) factor, the equation for the optimal \( \beta \) changes to Multiplying with \( \boldsymbol{U} \) from the right gives us the eigenvalue problem In many textbooks the \( 1/n \) term is often omitted. Note that a library like Scikit-Learn does not include the \( 1/n \) factor in the setup of the cost function. When we compare this with the ordinary least squares result we have which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \). We see that Ridge regression is nothing but the standard OLS with a
-modified diagonal term added to \( \boldsymbol{X}^T\boldsymbol{X} \). The consequences, in
-particular for our discussion of the bias-variance tradeoff are rather
-interesting. We will see that for specific values of \( \lambda \), we may
-even reduce the variance of the optimal parameters \( \boldsymbol{\beta} \). These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.
+ It means that the eigenvalues of \( \boldsymbol{X}\boldsymbol{X}^T \) are again given by
+the non-zero singular values plus now a series of zeros. The column
+vectors of \( \boldsymbol{U} \) are the eigenvectors of \( \boldsymbol{X}\boldsymbol{X}^T \) and
+measure how much correlations are contained in the rows of \( \boldsymbol{X} \).
Using our insights about the SVD of the design matrix \( \boldsymbol{X} \)
-We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as
+ Since we will mainly be interested in the correlations among the features
+of our data (the columns of \( \boldsymbol{X} \), the quantity of interest for us are the non-zero singular
+values and the column vectors of \( \boldsymbol{V} \).
For Ridge regression this becomes with the vectors \( \boldsymbol{u}_j \) being the columns of \( \boldsymbol{U} \) from the SVD of the matrix \( \boldsymbol{X} \).
@@ -478,6 +457,8 @@ $$
Since \( \lambda \geq 0 \), it means that compared to OLS, we have Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is
+our optimization problem is
+ Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the
-orthonormal basis \( \boldsymbol{U} \), it then shrinks the coordinates by
-\( \frac{\sigma_j^2}{\sigma_j^2+\lambda} \). Recall that the SVD has
-eigenvalues ordered in a descending way, that is \( \sigma_i \geq
-\sigma_{i+1} \).
+ or we can state it as where we have used the definition of a norm-2 vector, that is By minimizing the above equation with respect to the parameters
+\( \boldsymbol{\beta} \) we could then obtain an analytical expression for the
+parameters \( \boldsymbol{\beta} \). We can add a regularization parameter \( \lambda \) by
+defining a new cost function to be optimized, that is
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. which leads to the Ridge regression minimization problem where we
+require that \( \vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t \), where \( t \) is
+a finite number larger than zero. By defining
+ we have a new optimization equation which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. Here we have defined the norm-1 as
@@ -432,6 +476,8 @@ eigenvalues ordered in a descending way, that is \( \sigma_i \geq
For the sake of simplicity, let us assume that the design matrix is orthonormal, that is 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 In this case the standard OLS results in and
+taking the derivatives with respect to \( \boldsymbol{\beta} \) we obtain then
+a slightly modified matrix inversion problem which for finite values
+of \( \lambda \) does not suffer from singularity problems. We obtain
+the optimal parameters
+ and with \( \boldsymbol{I} \) being a \( p\times p \) identity matrix with the constraint that 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.
+ with \( t \) a finite positive number. If we keep the \( 1/n \) factor, the equation for the optimal \( \beta \) changes to In many textbooks the \( 1/n \) term is often omitted. Note that a library like Scikit-Learn does not include the \( 1/n \) factor in the setup of the cost function. When we compare this with the ordinary least squares result we have which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \). We see that Ridge regression is nothing but the standard OLS with a
+modified diagonal term added to \( \boldsymbol{X}^T\boldsymbol{X} \). The consequences, in
+particular for our discussion of the bias-variance tradeoff are rather
+interesting. We will see that for specific values of \( \lambda \), we may
+even reduce the variance of the optimal parameters \( \boldsymbol{\beta} \). These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.
We will come back to more interpreations after we have gone through some of the statistical analysis part. For more discussions of Ridge and Lasso regression, Wessel van Wieringen's article is highly recommended.
-Similarly, Mehta et al's article is also recommended.
+ Using our insights about the SVD of the design matrix \( \boldsymbol{X} \)
+We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as
For Ridge regression this becomes with the vectors \( \boldsymbol{u}_j \) being the columns of \( \boldsymbol{U} \) from the SVD of the matrix \( \boldsymbol{X} \).
@@ -444,6 +483,8 @@ Similarly, Mehta et al
Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \).
-The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable.
+The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable or simply the input.
A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with
@@ -268,8 +268,8 @@ The first variable is called the dependent, the outcome or the
- Consider an experiment in which \( p \) characteristics of \( n \) samples are
-measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix
+ Consider an experiment in which \( p \) characteristics (or features) of \( n \) samples are
+measured. The data from this experiment, for various explanatory/feature variables \( p \) are normally represented by a matrix
\( \mathbf{X} \).
In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \),
-consider the model we discussed for describing nuclear binding energies.
- There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model.
-Assuming
+we condiser a simple polynomial fit.
+We assume our data can represented by a fourth-order polynomial. For the $i$th component we have
we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms.
+ we have five predictors, that is the intercept $\beta_0$and the other terms \( \beta_i \).
This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a
\( p\times n \) matrix \( \boldsymbol{X} \).
+
For every set of values \( y_i,x_i \) we have thus the corresponding set of equations In our introductory notes we looked at the so-called liquid drop model. Let us remind ourselves about what we did by looking at the code. We restate the parts of the code we are most interested in. With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as throughout these lectures. Since \( \alpha \) is a scalar we have \( \alpha =\alpha^T=\boldsymbol{x}^T\boldsymbol{A}^T\boldsymbol{y} \). Defining now \( \boldsymbol{z}=\boldsymbol{x}^T\boldsymbol{A}^T \) we find that and if \( \boldsymbol{y}=\boldsymbol{x} \) we have We defined earlier a possible cost function using the mean squared error or using the design/feature matrix \( \boldsymbol{X} \) we have the more compact matrix-vector We note that the design matrix \( \boldsymbol{X} \) does not depend on the unknown parameters defined by the vector \( \boldsymbol{\beta} \).
+We are now interested in minimizing the cost function with respect to the unknown parameters \( \boldsymbol{\beta} \).
+ The mean squared error is scalar and if we use the results from the last example, we define a new vector which depends on \( \boldsymbol{\beta} \). We rewrite the cost function as with partial derivative and using that where we ued the results from example two. Inserting the last expression we obtain or as We list here some other useful relations we may encounter (recall that vectors are defined by boldfaced low-key letters) See the jupyter-book (complete lecture notes) for the derivations of these relations.
Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \).
-The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable.
+The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable or simply the input.
A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{x} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.
- Consider an experiment in which \( p \) characteristics of \( n \) samples are
-measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix
+ Consider an experiment in which \( p \) characteristics (or features) of \( n \) samples are
+measured. The data from this experiment, for various explanatory/feature variables \( p \) are normally represented by a matrix
\( \mathbf{X} \).
In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \),
-consider the model we discussed for describing nuclear binding energies.
- There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model.
-Assuming
+we condiser a simple polynomial fit.
+We assume our data can represented by a fourth-order polynomial. For the $i$th component we have
we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms.
+ we have five predictors, that is the intercept $\beta_0$and the other terms \( \beta_i \).
This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a
\( p\times n \) matrix \( \boldsymbol{X} \).
+
For every set of values \( y_i,x_i \) we have thus the corresponding set of equations In our introductory notes we looked at the so-called liquid drop model. Let us remind ourselves about what we did by looking at the code. We restate the parts of the code we are most interested in. With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as throughout these lectures. Since \( \alpha \) is a scalar we have \( \alpha =\alpha^T=\boldsymbol{x}^T\boldsymbol{A}^T\boldsymbol{y} \). Defining now \( \boldsymbol{z}=\boldsymbol{x}^T\boldsymbol{A}^T \) we find that and if \( \boldsymbol{y}=\boldsymbol{x} \) we have We defined earlier a possible cost function using the mean squared error or using the design/feature matrix \( \boldsymbol{X} \) we have the more compact matrix-vector We note that the design matrix \( \boldsymbol{X} \) does not depend on the unknown parameters defined by the vector \( \boldsymbol{\beta} \).
+We are now interested in minimizing the cost function with respect to the unknown parameters \( \boldsymbol{\beta} \).
+ The mean squared error is scalar and if we use the results from the last example, we define a new vector which depends on \( \boldsymbol{\beta} \). We rewrite the cost function as with partial derivative and using that where we ued the results from example two. Inserting the last expression we obtain or as We list here some other useful relations we may encounter (recall that vectors are defined by boldfaced low-key letters) See the jupyter-book (complete lecture notes) for the derivations of these relations.
Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \).
-The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable.
+The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable or simply the input.
A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{x} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.
- Consider an experiment in which \( p \) characteristics of \( n \) samples are
-measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix
+ Consider an experiment in which \( p \) characteristics (or features) of \( n \) samples are
+measured. The data from this experiment, for various explanatory/feature variables \( p \) are normally represented by a matrix
\( \mathbf{X} \).
In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \),
-consider the model we discussed for describing nuclear binding energies.
- There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model.
-Assuming
+we condiser a simple polynomial fit.
+We assume our data can represented by a fourth-order polynomial. For the $i$th component we have
we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms.
+ we have five predictors, that is the intercept $\beta_0$and the other terms \( \beta_i \).
This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a
\( p\times n \) matrix \( \boldsymbol{X} \).
+
For every set of values \( y_i,x_i \) we have thus the corresponding set of equations In our introductory notes we looked at the so-called liquid drop model. Let us remind ourselves about what we did by looking at the code. We restate the parts of the code we are most interested in. With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as throughout these lectures. Since \( \alpha \) is a scalar we have \( \alpha =\alpha^T=\boldsymbol{x}^T\boldsymbol{A}^T\boldsymbol{y} \). Defining now \( \boldsymbol{z}=\boldsymbol{x}^T\boldsymbol{A}^T \) we find that and if \( \boldsymbol{y}=\boldsymbol{x} \) we have We defined earlier a possible cost function using the mean squared error or using the design/feature matrix \( \boldsymbol{X} \) we have the more compact matrix-vector We note that the design matrix \( \boldsymbol{X} \) does not depend on the unknown parameters defined by the vector \( \boldsymbol{\beta} \).
+We are now interested in minimizing the cost function with respect to the unknown parameters \( \boldsymbol{\beta} \).
+ The mean squared error is scalar and if we use the results from the last example, we define a new vector which depends on \( \boldsymbol{\beta} \). We rewrite the cost function as with partial derivative and using that where we ued the results from example two. Inserting the last expression we obtain or as We list here some other useful relations we may encounter (recall that vectors are defined by boldfaced low-key letters) See the jupyter-book (complete lecture notes) for the derivations of these relations.Material for lecture Thursday, August 31
+Testing the Means Squared Error as function of Complexity
+np.random.seed()
+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)
+
+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 = 50
+maxdegree = 5
+# 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()
+
+Mathematical Interpretation of Ordinary Least Squares
+More preprocessing examples, Franke function and regression
-# 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
-$$
-\hat{\boldsymbol{\beta}} = \left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
-$$
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
-
+Residual Error
-
-Material for lecture Thursday, August 31
Simple case
+Mathematical Interpretation of Ordinary Least Squares
-The singular value decomposition
+Residual Error
-Linear Regression Problems
+Simple case
+
+Fixing the singularity
+The singular value decomposition
-Basic math of the SVD
+Linear Regression Problems
-The SVD, a Fantastic Algorithm
+Fixing the singularity
-Economy-size SVD
+Basic math of the SVD
-Codes for the SVD
+The SVD, a Fantastic Algorithm
-
-
-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)
-
-Note about SVD Calculations
+Economy-size SVD
-Mathematics of the SVD and implications
+Codes for the SVD
-import numpy as np
+# SVD inversion
+def SVD(A):
+ ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).
+ SVD is numerically more stable than the inversion algorithms provided by
+ numpy and scipy.linalg at the cost of being slower.
+ '''
+ U, S, VT = np.linalg.svd(A,full_matrices=True)
+ print('test U')
+ print( (np.transpose(U) @ U - U @np.transpose(U)))
+ print('test VT')
+ print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))
+ print(U)
+ print(S)
+ print(VT)
-
+Example Matrix
+Note about SVD Calculations
-Setting up the Matrix to be inverted
+Mathematics of the SVD and implications
-Further properties (important for our analyses later)
+Example Matrix
+
+Meet the Covariance Matrix
+Setting up the Matrix to be inverted
-Introducing the Covariance and Correlation functions
+Further properties (important for our analyses later)
-Covariance and Correlation Matrix
+Meet the Covariance Matrix
-Correlation Function and Design/Feature Matrix
+Introducing the Covariance and Correlation functions
-Covariance Matrix Examples
+Covariance and Correlation Matrix
-# Importing various packages
-import numpy as np
-n = 100
-x = np.random.normal(size=n)
-print(np.mean(x))
-y = 4+3*x+np.random.normal(size=n)
-print(np.mean(y))
-W = np.vstack((x, y))
-C = np.cov(W)
-print(C)
-
-Correlation Matrix
+Correlation Function and Design/Feature Matrix
-import numpy as np
-n = 100
-# define two vectors
-x = np.random.random(size=n)
-y = 4+3*x+np.random.normal(size=n)
-#scaling the x and y vectors
-x = x - np.mean(x)
-y = y - np.mean(y)
-variance_x = np.sum(x@x)/n
-variance_y = np.sum(y@y)/n
-print(variance_x)
-print(variance_y)
-cov_xy = np.sum(x@y)/n
-cov_xx = np.sum(x@x)/n
-cov_yy = np.sum(y@y)/n
-C = np.zeros((2,2))
-C[0,0]= cov_xx/variance_x
-C[1,1]= cov_yy/variance_y
-C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
-C[1,0]= C[0,1]
-print(C)
-
-Correlation Matrix with Pandas
+Covariance Matrix Examples
+
+import numpy as np
-import pandas as pd
-n = 10
+
# Importing various packages
+import numpy as np
+n = 100
x = np.random.normal(size=n)
-x = x - np.mean(x)
+print(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)
+print(np.mean(y))
+W = np.vstack((x, y))
+C = np.cov(W)
+print(C)
Correlation Matrix with Pandas and the Franke function
+Correlation Matrix
+
+# 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)
+
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)
Rewriting the Covariance and/or Correlation Matrix
+Correlation Matrix with Pandas
-import numpy as np
+import pandas as pd
+n = 10
+x = np.random.normal(size=n)
+x = x - np.mean(x)
+y = 4+3*x+np.random.normal(size=n)
+y = y - np.mean(y)
+# 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)
+
+Linking with the SVD
+Correlation Matrix with Pandas and the Franke function
-# Common imports
+import numpy as np
+import pandas as pd
-
+What does it mean?
-
-Rewriting the Covariance and/or Correlation Matrix
+And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
-
-Linking with the SVD
+Ridge and LASSO Regression
+What does it mean?
-Deriving the Ridge Regression Equations
+And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
-Interpreting the Ridge results
-
-Ridge and LASSO Regression
+More interpretations
+Deriving the Ridge Regression Equations
-
$$
-BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1},
+\tilde{y}_i = \beta_0+\beta_1x_i+\beta_2x_i^2+\beta_3x_i^3+\beta_4x_i^4.
$$
-Rewriting the fitting procedure as a linear algebra problem
-
$$
@@ -354,7 +349,6 @@ y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1
\end{align*}
$$
-Examples relevant for the exercises
-
-# Common imports
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from IPython.display import display
-import os
-
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
- os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
- os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
- os.makedirs(DATA_ID)
-
-def image_path(fig_id):
- return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
- return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
-
-infile = open(data_path("MassEval2016.dat"),'r')
-
-
-# Read the experimental data with Pandas
-Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
- names=('N', 'Z', 'A', 'Element', 'Ebinding'),
- widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),
- header=39,
- index_col=False)
-
-# Extrapolated values are indicated by '#' in place of the decimal place, so
-# the Ebinding column won't be numeric. Coerce to float and drop these entries.
-Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')
-Masses = Masses.dropna()
-# Convert from keV to MeV.
-Masses['Ebinding'] /= 1000
-
-# Group the DataFrame by nucleon number, A.
-Masses = Masses.groupby('A')
-# Find the rows of the grouped DataFrame with the maximum binding energy.
-Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
-A = Masses['A']
-Z = Masses['Z']
-N = Masses['N']
-Element = Masses['Element']
-Energies = Masses['Ebinding']
-
-# Now we set up the design matrix X
-X = np.zeros((len(A),5))
-X[:,0] = 1
-X[:,1] = A
-X[:,2] = A**(2.0/3.0)
-X[:,3] = A**(-1.0/3.0)
-X[:,4] = A**(-1.0)
-# Then nice printout using pandas
-DesignMatrix = pd.DataFrame(X)
-DesignMatrix.index = A
-DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
-display(DesignMatrix)
-
-
-$$
-\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta},
-$$
-
-
-
$$
-\frac{\partial \alpha}{\partial \boldsymbol{y}} = \boldsymbol{z}^T=\boldsymbol{x}^T\boldsymbol{A}^T..
+\frac{\partial \alpha}{\partial \boldsymbol{y}} = \boldsymbol{z}^T=\boldsymbol{x}^T\boldsymbol{A}^T.
$$
$$
-\frac{\partial \alpha}{\partial \boldsymbol{z}} = \boldsymbol{x}^T\frac{\partial \boldsymbol{x}}{\partial \boldsymbol{z}}.
+\frac{\partial \alpha}{\partial \boldsymbol{z}} = 2\boldsymbol{x}^T\frac{\partial \boldsymbol{x}}{\partial \boldsymbol{z}}.
+$$
+
+The mean squared error and its derivative
+
+$$
+C(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\},
$$
+
+$$
+C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}.
+$$
+
+
+
+$$
+\boldsymbol{w}=\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta},
+$$
+
+
+
+$$
+C(\boldsymbol{\beta})=\frac{1}{n}\boldsymbol{w}^T\boldsymbol{w},
+$$
+
+
+
+$$
+\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}}=\frac{2}{n}\boldsymbol{w}^T\frac{\partial \boldsymbol{w}}{\partial \boldsymbol{\beta}},
+$$
+
+
+
+$$
+\frac{\partial \boldsymbol{w}}{\partial \boldsymbol{\beta}}=-\boldsymbol{X},
+$$
+
+
+
+$$
+\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}}=-\frac{2}{n}\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\boldsymbol{X},
+$$
+
+
+
+$$
+\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}^T}=-\frac{2}{n}\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right).
+$$
+
+Other useful relations
+
+
$$
\frac{\partial (\boldsymbol{b}^T\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{b},
$$
-
-$$
-\frac{\partial (\boldsymbol{a}^T\boldsymbol{A}\boldsymbol{a})}{\partial \boldsymbol{a}} = (\boldsymbol{A}+\boldsymbol{A}^T)\boldsymbol{a},
-$$
-
-
$$
\frac{\partial tr(\boldsymbol{B}\boldsymbol{A})}{\partial \boldsymbol{A}} = \boldsymbol{B}^T,
@@ -995,8 +948,6 @@ $$
\frac{\partial \log{\vert\boldsymbol{A}\vert}}{\partial \boldsymbol{A}} = (\boldsymbol{A}^{-1})^T.
$$
-
-
diff --git a/doc/pub/week35/html/week35-solarized.html b/doc/pub/week35/html/week35-solarized.html
index 45479b0dd..314f0ddf1 100644
--- a/doc/pub/week35/html/week35-solarized.html
+++ b/doc/pub/week35/html/week35-solarized.html
@@ -126,6 +126,11 @@ div.toc p,a {
('Example 2', 2, None, 'example-2'),
('Example 3', 2, None, 'example-3'),
('Example 4', 2, None, 'example-4'),
+ ('The mean squared error and its derivative',
+ 2,
+ None,
+ 'the-mean-squared-error-and-its-derivative'),
+ ('Other useful relations', 2, None, 'other-useful-relations'),
('Meet the Hessian Matrix', 2, None, 'meet-the-hessian-matrix'),
('Interpretations and optimizing our parameters',
2,
@@ -390,13 +395,13 @@ Similarly, Mehta et a
Rewriting the fitting procedure as a linear algebra problem
-
@@ -617,107 +616,6 @@ our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predict
Examples relevant for the exercises
-# Common imports
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from IPython.display import display
-import os
-
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
- os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
- os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
- os.makedirs(DATA_ID)
-
-def image_path(fig_id):
- return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
- return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
-
-infile = open(data_path("MassEval2016.dat"),'r')
-
-
-# Read the experimental data with Pandas
-Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
- names=('N', 'Z', 'A', 'Element', 'Ebinding'),
- widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),
- header=39,
- index_col=False)
-
-# Extrapolated values are indicated by '#' in place of the decimal place, so
-# the Ebinding column won't be numeric. Coerce to float and drop these entries.
-Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')
-Masses = Masses.dropna()
-# Convert from keV to MeV.
-Masses['Ebinding'] /= 1000
-
-# Group the DataFrame by nucleon number, A.
-Masses = Masses.groupby('A')
-# Find the rows of the grouped DataFrame with the maximum binding energy.
-Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
-A = Masses['A']
-Z = Masses['Z']
-N = Masses['N']
-Element = Masses['Element']
-Energies = Masses['Ebinding']
-
-# Now we set up the design matrix X
-X = np.zeros((len(A),5))
-X[:,0] = 1
-X[:,1] = A
-X[:,2] = A**(2.0/3.0)
-X[:,3] = A**(-1.0/3.0)
-X[:,4] = A**(-1.0)
-# Then nice printout using pandas
-DesignMatrix = pd.DataFrame(X)
-DesignMatrix.index = A
-DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
-display(DesignMatrix)
-
-
Optimizing our parameters, more details
+The mean squared error and its derivative
+
+Other useful relations
+
+
Meet the Hessian Matrix
@@ -1047,7 +991,7 @@ $$
Learning is the Hessian. It is given by the second derivative of the
cost function with respect to the parameter \( \beta \). Using the above
expression for derivatives of vectors and matrices, we find that the
-second derivative of the cost function is,
+second derivative of the mean squared error as cost function is,
$$
diff --git a/doc/pub/week35/html/week35.html b/doc/pub/week35/html/week35.html
index f55b0c431..fd376b6b6 100644
--- a/doc/pub/week35/html/week35.html
+++ b/doc/pub/week35/html/week35.html
@@ -203,6 +203,11 @@ div.toc p,a {
('Example 2', 2, None, 'example-2'),
('Example 3', 2, None, 'example-3'),
('Example 4', 2, None, 'example-4'),
+ ('The mean squared error and its derivative',
+ 2,
+ None,
+ 'the-mean-squared-error-and-its-derivative'),
+ ('Other useful relations', 2, None, 'other-useful-relations'),
('Meet the Hessian Matrix', 2, None, 'meet-the-hessian-matrix'),
('Interpretations and optimizing our parameters',
2,
@@ -467,13 +472,13 @@ Similarly, Mehta et a
Rewriting the fitting procedure as a linear algebra problem
-
@@ -694,107 +693,6 @@ our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predict
Examples relevant for the exercises
-# Common imports
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from IPython.display import display
-import os
-
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
- os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
- os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
- os.makedirs(DATA_ID)
-
-def image_path(fig_id):
- return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
- return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
-
-infile = open(data_path("MassEval2016.dat"),'r')
-
-
-# Read the experimental data with Pandas
-Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
- names=('N', 'Z', 'A', 'Element', 'Ebinding'),
- widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),
- header=39,
- index_col=False)
-
-# Extrapolated values are indicated by '#' in place of the decimal place, so
-# the Ebinding column won't be numeric. Coerce to float and drop these entries.
-Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')
-Masses = Masses.dropna()
-# Convert from keV to MeV.
-Masses['Ebinding'] /= 1000
-
-# Group the DataFrame by nucleon number, A.
-Masses = Masses.groupby('A')
-# Find the rows of the grouped DataFrame with the maximum binding energy.
-Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
-A = Masses['A']
-Z = Masses['Z']
-N = Masses['N']
-Element = Masses['Element']
-Energies = Masses['Ebinding']
-
-# Now we set up the design matrix X
-X = np.zeros((len(A),5))
-X[:,0] = 1
-X[:,1] = A
-X[:,2] = A**(2.0/3.0)
-X[:,3] = A**(-1.0/3.0)
-X[:,4] = A**(-1.0)
-# Then nice printout using pandas
-DesignMatrix = pd.DataFrame(X)
-DesignMatrix.index = A
-DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
-display(DesignMatrix)
-
-
Optimizing our parameters, more details
+The mean squared error and its derivative
+
+Other useful relations
+
+
Meet the Hessian Matrix
@@ -1124,7 +1068,7 @@ $$
Learning is the Hessian. It is given by the second derivative of the
cost function with respect to the parameter \( \beta \). Using the above
expression for derivatives of vectors and matrices, we find that the
-second derivative of the cost function is,
+second derivative of the mean squared error as cost function is,
$$
diff --git a/doc/pub/week35/ipynb/ipynb-week35-src.tar.gz b/doc/pub/week35/ipynb/ipynb-week35-src.tar.gz
index 307766163..773ec7395 100644
Binary files a/doc/pub/week35/ipynb/ipynb-week35-src.tar.gz and b/doc/pub/week35/ipynb/ipynb-week35-src.tar.gz differ
diff --git a/doc/pub/week35/ipynb/week35.ipynb b/doc/pub/week35/ipynb/week35.ipynb
index 43d1d2e25..1b07358f6 100644
--- a/doc/pub/week35/ipynb/week35.ipynb
+++ b/doc/pub/week35/ipynb/week35.ipynb
@@ -2,7 +2,7 @@
"cells": [
{
"cell_type": "markdown",
- "id": "169b9589",
+ "id": "4b5bc0b3",
"metadata": {
"editable": true
},
@@ -14,7 +14,7 @@
},
{
"cell_type": "markdown",
- "id": "bba74315",
+ "id": "c9874ce4",
"metadata": {
"editable": true
},
@@ -27,7 +27,7 @@
},
{
"cell_type": "markdown",
- "id": "961bf8f8",
+ "id": "d3a36d59",
"metadata": {
"editable": true
},
@@ -49,7 +49,7 @@
},
{
"cell_type": "markdown",
- "id": "7076c51b",
+ "id": "0cb4216c",
"metadata": {
"editable": true
},
@@ -69,7 +69,7 @@
},
{
"cell_type": "markdown",
- "id": "9603ced7",
+ "id": "11d9d728",
"metadata": {
"editable": true
},
@@ -103,7 +103,7 @@
},
{
"cell_type": "markdown",
- "id": "139a0534",
+ "id": "cd40f525",
"metadata": {
"editable": true
},
@@ -111,12 +111,12 @@
"## Regression analysis, overarching aims\n",
"\n",
"Regression modeling deals with the description of the sampling distribution of a given random variable $y$ and how it varies as function of another variable or a set of such variables $\\boldsymbol{x} =[x_0, x_1,\\dots, x_{n-1}]^T$. \n",
- "The first variable is called the **dependent**, the **outcome** or the **response** variable while the set of variables $\\boldsymbol{x}$ is called the independent variable, or the predictor variable or the explanatory variable. \n",
+ "The first variable is called the **dependent**, the **outcome** or the **response** variable while the set of variables $\\boldsymbol{x}$ is called the independent variable, or the predictor variable or the explanatory variable or simply the input. \n",
"\n",
"A regression model aims at finding a likelihood function $p(\\boldsymbol{y}\\vert \\boldsymbol{x})$, that is the conditional distribution for $\\boldsymbol{y}$ with a given $\\boldsymbol{x}$. The estimation of $p(\\boldsymbol{y}\\vert \\boldsymbol{x})$ is made using a data set with \n",
"* $n$ cases $i = 0, 1, 2, \\dots, n-1$ \n",
"\n",
- "* Response (target, dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \\dots, n-1$ \n",
+ "* Response, output, target, dependent or outcome variable $y_i$ with $i = 0, 1, 2, \\dots, n-1$ \n",
"\n",
"* $p$ so-called explanatory (independent or predictor) variables $\\boldsymbol{x}_i=[x_{i0}, x_{i1}, \\dots, x_{ip-1}]$ with $i = 0, 1, 2, \\dots, n-1$ and explanatory variables running from $0$ to $p-1$. See below for more explicit examples. \n",
"\n",
@@ -125,15 +125,15 @@
},
{
"cell_type": "markdown",
- "id": "0200271b",
+ "id": "fb7e454b",
"metadata": {
"editable": true
},
"source": [
"## Regression analysis, overarching aims II\n",
"\n",
- "Consider an experiment in which $p$ characteristics of $n$ samples are\n",
- "measured. The data from this experiment, for various explanatory variables $p$ are normally represented by a matrix \n",
+ "Consider an experiment in which $p$ characteristics (or features) of $n$ samples are\n",
+ "measured. The data from this experiment, for various explanatory/feature variables $p$ are normally represented by a matrix \n",
"$\\mathbf{X}$.\n",
"\n",
"The matrix $\\mathbf{X}$ is called the *design\n",
@@ -153,39 +153,37 @@
},
{
"cell_type": "markdown",
- "id": "ffc1341d",
+ "id": "975ee4ab",
"metadata": {
"editable": true
},
"source": [
"## Examples\n",
"In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\\boldsymbol{y}$,\n",
- "consider the model we discussed for describing nuclear binding energies. \n",
- "\n",
- "There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model.\n",
- "Assuming"
+ "we condiser a simple polynomial fit.\n",
+ "We assume our data can represented by a fourth-order polynomial. For the $i$th component we have"
]
},
{
"cell_type": "markdown",
- "id": "6ded52da",
+ "id": "9729a1b2",
"metadata": {
"editable": true
},
"source": [
"$$\n",
- "BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1},\n",
+ "\\tilde{y}_i = \\beta_0+\\beta_1x_i+\\beta_2x_i^2+\\beta_3x_i^3+\\beta_4x_i^4.\n",
"$$"
]
},
{
"cell_type": "markdown",
- "id": "0d077ef8",
+ "id": "7bb7c39d",
"metadata": {
"editable": true
},
"source": [
- "we have five predictors, that is the intercept, the $A$ dependent term, the $A^{2/3}$ term and the $A^{-1/3}$ and $A^{-1}$ terms.\n",
+ "we have five predictors, that is the intercept $\\beta_0$and the other terms $\\beta_i$.\n",
"This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a \n",
"$p\\times n$ matrix $\\boldsymbol{X}$.\n",
"\n",
@@ -195,7 +193,7 @@
},
{
"cell_type": "markdown",
- "id": "aece0a91",
+ "id": "62662997",
"metadata": {
"editable": true
},
@@ -208,7 +206,7 @@
},
{
"cell_type": "markdown",
- "id": "5b6ffade",
+ "id": "4c1cc9af",
"metadata": {
"editable": true
},
@@ -220,7 +218,7 @@
},
{
"cell_type": "markdown",
- "id": "46e19dcd",
+ "id": "afcdb8b5",
"metadata": {
"editable": true
},
@@ -230,18 +228,19 @@
},
{
"cell_type": "markdown",
- "id": "e7629822",
+ "id": "da7c9f51",
"metadata": {
"editable": true
},
"source": [
"## Rewriting the fitting procedure as a linear algebra problem\n",
+ "\n",
"For every set of values $y_i,x_i$ we have thus the corresponding set of equations"
]
},
{
"cell_type": "markdown",
- "id": "196fc987",
+ "id": "15fe832a",
"metadata": {
"editable": true
},
@@ -259,7 +258,7 @@
},
{
"cell_type": "markdown",
- "id": "b1d22515",
+ "id": "92dca125",
"metadata": {
"editable": true
},
@@ -270,7 +269,7 @@
},
{
"cell_type": "markdown",
- "id": "4e73f58b",
+ "id": "9cbc789b",
"metadata": {
"editable": true
},
@@ -282,7 +281,7 @@
},
{
"cell_type": "markdown",
- "id": "5b29430a",
+ "id": "ad0aa01e",
"metadata": {
"editable": true
},
@@ -292,7 +291,7 @@
},
{
"cell_type": "markdown",
- "id": "13ed19f0",
+ "id": "7cf0a3b2",
"metadata": {
"editable": true
},
@@ -304,7 +303,7 @@
},
{
"cell_type": "markdown",
- "id": "6bef0acc",
+ "id": "0b6704b0",
"metadata": {
"editable": true
},
@@ -314,7 +313,7 @@
},
{
"cell_type": "markdown",
- "id": "53bd46b4",
+ "id": "cb7633e5",
"metadata": {
"editable": true
},
@@ -326,7 +325,7 @@
},
{
"cell_type": "markdown",
- "id": "d6d2159b",
+ "id": "ea15a2b8",
"metadata": {
"editable": true
},
@@ -336,7 +335,7 @@
},
{
"cell_type": "markdown",
- "id": "bde35547",
+ "id": "d629bf1f",
"metadata": {
"editable": true
},
@@ -355,7 +354,7 @@
},
{
"cell_type": "markdown",
- "id": "5f7974ed",
+ "id": "d1a204c5",
"metadata": {
"editable": true
},
@@ -365,7 +364,7 @@
},
{
"cell_type": "markdown",
- "id": "9a422e44",
+ "id": "958844b3",
"metadata": {
"editable": true
},
@@ -377,7 +376,7 @@
},
{
"cell_type": "markdown",
- "id": "eded0e3c",
+ "id": "a79e47f8",
"metadata": {
"editable": true
},
@@ -387,7 +386,7 @@
},
{
"cell_type": "markdown",
- "id": "d8f07344",
+ "id": "abad3e82",
"metadata": {
"editable": true
},
@@ -403,7 +402,7 @@
},
{
"cell_type": "markdown",
- "id": "89b43979",
+ "id": "9d4a0dc5",
"metadata": {
"editable": true
},
@@ -423,7 +422,7 @@
},
{
"cell_type": "markdown",
- "id": "bcf6e4c5",
+ "id": "a39edcb5",
"metadata": {
"editable": true
},
@@ -433,7 +432,7 @@
},
{
"cell_type": "markdown",
- "id": "cb085f2b",
+ "id": "fbb1487e",
"metadata": {
"editable": true
},
@@ -444,7 +443,7 @@
},
{
"cell_type": "markdown",
- "id": "0aaa28b5",
+ "id": "33762c5b",
"metadata": {
"editable": true
},
@@ -463,7 +462,7 @@
},
{
"cell_type": "markdown",
- "id": "b4e73c82",
+ "id": "c746084a",
"metadata": {
"editable": true
},
@@ -473,7 +472,7 @@
},
{
"cell_type": "markdown",
- "id": "70af9d53",
+ "id": "43de7d96",
"metadata": {
"editable": true
},
@@ -485,7 +484,7 @@
},
{
"cell_type": "markdown",
- "id": "38b4bffa",
+ "id": "42381d73",
"metadata": {
"editable": true
},
@@ -495,7 +494,7 @@
},
{
"cell_type": "markdown",
- "id": "93616def",
+ "id": "f7b8ef0a",
"metadata": {
"editable": true
},
@@ -506,7 +505,7 @@
},
{
"cell_type": "markdown",
- "id": "a8d9f7f2",
+ "id": "3dfec84b",
"metadata": {
"editable": true
},
@@ -526,7 +525,7 @@
},
{
"cell_type": "markdown",
- "id": "953a982e",
+ "id": "3d29e773",
"metadata": {
"editable": true
},
@@ -538,136 +537,17 @@
},
{
"cell_type": "markdown",
- "id": "d22931ee",
+ "id": "607ec4f5",
"metadata": {
"editable": true
},
"source": [
- "## Examples relevant for the exercises\n",
- "\n",
- "In our [introductory notes](https://compphysics.github.io/MachineLearning/doc/pub/How2ReadData/html/How2ReadData.html) we looked at the so-called [liquid drop model](https://en.wikipedia.org/wiki/Semi-empirical_mass_formula). Let us remind ourselves about what we did by looking at the code.\n",
- "\n",
- "We restate the parts of the code we are most interested in."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "id": "7a6a3c55",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "%matplotlib inline\n",
- "\n",
- "# Common imports\n",
- "import numpy as np\n",
- "import pandas as pd\n",
- "import matplotlib.pyplot as plt\n",
- "from IPython.display import display\n",
- "import os\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(\"MassEval2016.dat\"),'r')\n",
- "\n",
- "\n",
- "# Read the experimental data with Pandas\n",
- "Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),\n",
- " names=('N', 'Z', 'A', 'Element', 'Ebinding'),\n",
- " widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),\n",
- " header=39,\n",
- " index_col=False)\n",
- "\n",
- "# Extrapolated values are indicated by '#' in place of the decimal place, so\n",
- "# the Ebinding column won't be numeric. Coerce to float and drop these entries.\n",
- "Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')\n",
- "Masses = Masses.dropna()\n",
- "# Convert from keV to MeV.\n",
- "Masses['Ebinding'] /= 1000\n",
- "\n",
- "# Group the DataFrame by nucleon number, A.\n",
- "Masses = Masses.groupby('A')\n",
- "# Find the rows of the grouped DataFrame with the maximum binding energy.\n",
- "Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])\n",
- "A = Masses['A']\n",
- "Z = Masses['Z']\n",
- "N = Masses['N']\n",
- "Element = Masses['Element']\n",
- "Energies = Masses['Ebinding']\n",
- "\n",
- "# Now we set up the design matrix X\n",
- "X = np.zeros((len(A),5))\n",
- "X[:,0] = 1\n",
- "X[:,1] = A\n",
- "X[:,2] = A**(2.0/3.0)\n",
- "X[:,3] = A**(-1.0/3.0)\n",
- "X[:,4] = A**(-1.0)\n",
- "# Then nice printout using pandas\n",
- "DesignMatrix = pd.DataFrame(X)\n",
- "DesignMatrix.index = A\n",
- "DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']\n",
- "display(DesignMatrix)"
+ "## Examples relevant for the exercises"
]
},
{
"cell_type": "markdown",
- "id": "2dff579b",
- "metadata": {
- "editable": true
- },
- "source": [
- "With $\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p\\times 1}$, it means that we will hereafter write our equations for the approximation as"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "eaa09b7c",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\beta},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "610fc42b",
- "metadata": {
- "editable": true
- },
- "source": [
- "throughout these lectures."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "65fbd86f",
+ "id": "13acad8b",
"metadata": {
"editable": true
},
@@ -678,7 +558,7 @@
},
{
"cell_type": "markdown",
- "id": "68d1e1ac",
+ "id": "8e99d3d7",
"metadata": {
"editable": true
},
@@ -690,7 +570,7 @@
},
{
"cell_type": "markdown",
- "id": "8377bb33",
+ "id": "ba67c623",
"metadata": {
"editable": true
},
@@ -700,7 +580,7 @@
},
{
"cell_type": "markdown",
- "id": "b7dcec96",
+ "id": "b725bcb9",
"metadata": {
"editable": true
},
@@ -712,7 +592,7 @@
},
{
"cell_type": "markdown",
- "id": "08085ea1",
+ "id": "53b5304f",
"metadata": {
"editable": true
},
@@ -722,7 +602,7 @@
},
{
"cell_type": "markdown",
- "id": "5f78bdc7",
+ "id": "fae1f33f",
"metadata": {
"editable": true
},
@@ -734,7 +614,7 @@
},
{
"cell_type": "markdown",
- "id": "388d605b",
+ "id": "6b2b2cb2",
"metadata": {
"editable": true
},
@@ -747,7 +627,7 @@
},
{
"cell_type": "markdown",
- "id": "606923b1",
+ "id": "8d63c69e",
"metadata": {
"editable": true
},
@@ -759,7 +639,7 @@
},
{
"cell_type": "markdown",
- "id": "4d95dc05",
+ "id": "f5ec2ec1",
"metadata": {
"editable": true
},
@@ -769,7 +649,7 @@
},
{
"cell_type": "markdown",
- "id": "8a9a55dd",
+ "id": "8405b259",
"metadata": {
"editable": true
},
@@ -781,7 +661,7 @@
},
{
"cell_type": "markdown",
- "id": "f573cf3e",
+ "id": "86502ef0",
"metadata": {
"editable": true
},
@@ -793,7 +673,7 @@
},
{
"cell_type": "markdown",
- "id": "1042018a",
+ "id": "8336a28d",
"metadata": {
"editable": true
},
@@ -804,7 +684,7 @@
},
{
"cell_type": "markdown",
- "id": "36fbaf10",
+ "id": "bbc3e1fa",
"metadata": {
"editable": true
},
@@ -816,7 +696,7 @@
},
{
"cell_type": "markdown",
- "id": "33952a94",
+ "id": "43db8fa4",
"metadata": {
"editable": true
},
@@ -835,7 +715,7 @@
},
{
"cell_type": "markdown",
- "id": "ad8053e3",
+ "id": "140f3abf",
"metadata": {
"editable": true
},
@@ -848,7 +728,7 @@
},
{
"cell_type": "markdown",
- "id": "26805917",
+ "id": "4b450af2",
"metadata": {
"editable": true
},
@@ -858,7 +738,7 @@
},
{
"cell_type": "markdown",
- "id": "ff12d01d",
+ "id": "b5332484",
"metadata": {
"editable": true
},
@@ -870,7 +750,7 @@
},
{
"cell_type": "markdown",
- "id": "25a68ca9",
+ "id": "7a4dfffa",
"metadata": {
"editable": true
},
@@ -880,7 +760,7 @@
},
{
"cell_type": "markdown",
- "id": "0d030955",
+ "id": "58541b07",
"metadata": {
"editable": true
},
@@ -892,7 +772,7 @@
},
{
"cell_type": "markdown",
- "id": "b88ca504",
+ "id": "007d9319",
"metadata": {
"editable": true
},
@@ -902,7 +782,7 @@
},
{
"cell_type": "markdown",
- "id": "2a93db7c",
+ "id": "180d0d61",
"metadata": {
"editable": true
},
@@ -914,7 +794,7 @@
},
{
"cell_type": "markdown",
- "id": "c82beba8",
+ "id": "f6b8bd1e",
"metadata": {
"editable": true
},
@@ -925,7 +805,7 @@
},
{
"cell_type": "markdown",
- "id": "052f84ee",
+ "id": "a1905702",
"metadata": {
"editable": true
},
@@ -937,7 +817,7 @@
},
{
"cell_type": "markdown",
- "id": "5b6dbca3",
+ "id": "f651601b",
"metadata": {
"editable": true
},
@@ -947,7 +827,7 @@
},
{
"cell_type": "markdown",
- "id": "3c089a7e",
+ "id": "2a73fe51",
"metadata": {
"editable": true
},
@@ -959,7 +839,7 @@
},
{
"cell_type": "markdown",
- "id": "497631f9",
+ "id": "2a91758d",
"metadata": {
"editable": true
},
@@ -969,7 +849,7 @@
},
{
"cell_type": "markdown",
- "id": "0d0427ce",
+ "id": "a8cb8c6f",
"metadata": {
"editable": true
},
@@ -981,7 +861,7 @@
},
{
"cell_type": "markdown",
- "id": "12caf768",
+ "id": "7fe73a06",
"metadata": {
"editable": true
},
@@ -1002,7 +882,7 @@
},
{
"cell_type": "markdown",
- "id": "af73bfc1",
+ "id": "03e64ae8",
"metadata": {
"editable": true
},
@@ -1029,7 +909,7 @@
},
{
"cell_type": "markdown",
- "id": "7e918d68",
+ "id": "312ef9f1",
"metadata": {
"editable": true
},
@@ -1041,7 +921,7 @@
},
{
"cell_type": "markdown",
- "id": "435841dd",
+ "id": "1cab784e",
"metadata": {
"editable": true
},
@@ -1053,7 +933,7 @@
},
{
"cell_type": "markdown",
- "id": "c09403d1",
+ "id": "9f973851",
"metadata": {
"editable": true
},
@@ -1069,7 +949,7 @@
},
{
"cell_type": "markdown",
- "id": "132d7e0f",
+ "id": "21b6c95f",
"metadata": {
"editable": true
},
@@ -1087,7 +967,7 @@
},
{
"cell_type": "markdown",
- "id": "98d5232d",
+ "id": "f197fdd5",
"metadata": {
"editable": true
},
@@ -1099,7 +979,7 @@
},
{
"cell_type": "markdown",
- "id": "7bf1d31f",
+ "id": "3314311c",
"metadata": {
"editable": true
},
@@ -1111,7 +991,7 @@
},
{
"cell_type": "markdown",
- "id": "aeff3e1a",
+ "id": "dcf23359",
"metadata": {
"editable": true
},
@@ -1122,7 +1002,7 @@
},
{
"cell_type": "markdown",
- "id": "69e46a72",
+ "id": "1bfea1bd",
"metadata": {
"editable": true
},
@@ -1134,7 +1014,7 @@
},
{
"cell_type": "markdown",
- "id": "be469be5",
+ "id": "cd61a0a7",
"metadata": {
"editable": true
},
@@ -1144,7 +1024,7 @@
},
{
"cell_type": "markdown",
- "id": "ffbdec49",
+ "id": "2278e5fb",
"metadata": {
"editable": true
},
@@ -1156,7 +1036,7 @@
},
{
"cell_type": "markdown",
- "id": "47a54f21",
+ "id": "2dda2da7",
"metadata": {
"editable": true
},
@@ -1170,7 +1050,7 @@
},
{
"cell_type": "markdown",
- "id": "234dd350",
+ "id": "52ef0184",
"metadata": {
"editable": true
},
@@ -1182,7 +1062,7 @@
},
{
"cell_type": "markdown",
- "id": "fa2cee4f",
+ "id": "4853eb9f",
"metadata": {
"editable": true
},
@@ -1194,7 +1074,7 @@
},
{
"cell_type": "markdown",
- "id": "b06c808a",
+ "id": "1c3d58ec",
"metadata": {
"editable": true
},
@@ -1206,7 +1086,7 @@
},
{
"cell_type": "markdown",
- "id": "eb44e21b",
+ "id": "ddb05243",
"metadata": {
"editable": true
},
@@ -1216,7 +1096,7 @@
},
{
"cell_type": "markdown",
- "id": "ef20ae29",
+ "id": "56a842ce",
"metadata": {
"editable": true
},
@@ -1228,7 +1108,7 @@
},
{
"cell_type": "markdown",
- "id": "386487f1",
+ "id": "25d58345",
"metadata": {
"editable": true
},
@@ -1238,19 +1118,19 @@
},
{
"cell_type": "markdown",
- "id": "369040d8",
+ "id": "de8752e6",
"metadata": {
"editable": true
},
"source": [
"$$\n",
- "\\frac{\\partial \\alpha}{\\partial \\boldsymbol{y}} = \\boldsymbol{z}^T=\\boldsymbol{x}^T\\boldsymbol{A}^T..\n",
+ "\\frac{\\partial \\alpha}{\\partial \\boldsymbol{y}} = \\boldsymbol{z}^T=\\boldsymbol{x}^T\\boldsymbol{A}^T.\n",
"$$"
]
},
{
"cell_type": "markdown",
- "id": "aec9cc7d",
+ "id": "5018ecd0",
"metadata": {
"editable": true
},
@@ -1264,7 +1144,7 @@
},
{
"cell_type": "markdown",
- "id": "02ac45d9",
+ "id": "ea00eb1a",
"metadata": {
"editable": true
},
@@ -1276,7 +1156,7 @@
},
{
"cell_type": "markdown",
- "id": "bd13b481",
+ "id": "0a2f1f2d",
"metadata": {
"editable": true
},
@@ -1288,7 +1168,7 @@
},
{
"cell_type": "markdown",
- "id": "187ca851",
+ "id": "37fd0c71",
"metadata": {
"editable": true
},
@@ -1300,7 +1180,7 @@
},
{
"cell_type": "markdown",
- "id": "d412b8b4",
+ "id": "8b1e2c84",
"metadata": {
"editable": true
},
@@ -1310,7 +1190,7 @@
},
{
"cell_type": "markdown",
- "id": "5d3cdbda",
+ "id": "95d86d4b",
"metadata": {
"editable": true
},
@@ -1322,7 +1202,7 @@
},
{
"cell_type": "markdown",
- "id": "14e05fd0",
+ "id": "21a858fa",
"metadata": {
"editable": true
},
@@ -1332,7 +1212,7 @@
},
{
"cell_type": "markdown",
- "id": "4cb66cf8",
+ "id": "7fc2df74",
"metadata": {
"editable": true
},
@@ -1344,7 +1224,7 @@
},
{
"cell_type": "markdown",
- "id": "aff8d4e2",
+ "id": "5e513d1d",
"metadata": {
"editable": true
},
@@ -1354,7 +1234,7 @@
},
{
"cell_type": "markdown",
- "id": "401edcd9",
+ "id": "bc7e53ea",
"metadata": {
"editable": true
},
@@ -1366,7 +1246,7 @@
},
{
"cell_type": "markdown",
- "id": "95af165d",
+ "id": "702ee7c2",
"metadata": {
"editable": true
},
@@ -1378,7 +1258,7 @@
},
{
"cell_type": "markdown",
- "id": "60495dae",
+ "id": "c76c4066",
"metadata": {
"editable": true
},
@@ -1390,7 +1270,7 @@
},
{
"cell_type": "markdown",
- "id": "1882cdc6",
+ "id": "c19e6b8b",
"metadata": {
"editable": true
},
@@ -1405,7 +1285,7 @@
},
{
"cell_type": "markdown",
- "id": "7f982ad6",
+ "id": "42aeda99",
"metadata": {
"editable": true
},
@@ -1417,7 +1297,7 @@
},
{
"cell_type": "markdown",
- "id": "aacdc2dc",
+ "id": "e82e3845",
"metadata": {
"editable": true
},
@@ -1427,7 +1307,7 @@
},
{
"cell_type": "markdown",
- "id": "9fd438c5",
+ "id": "8eae4e56",
"metadata": {
"editable": true
},
@@ -1439,7 +1319,7 @@
},
{
"cell_type": "markdown",
- "id": "85dad6ef",
+ "id": "519386b5",
"metadata": {
"editable": true
},
@@ -1449,7 +1329,7 @@
},
{
"cell_type": "markdown",
- "id": "9f483c00",
+ "id": "7ab149a3",
"metadata": {
"editable": true
},
@@ -1461,7 +1341,7 @@
},
{
"cell_type": "markdown",
- "id": "5dabf908",
+ "id": "89e73830",
"metadata": {
"editable": true
},
@@ -1471,19 +1351,211 @@
},
{
"cell_type": "markdown",
- "id": "19b12f64",
+ "id": "505c6f6e",
"metadata": {
"editable": true
},
"source": [
"$$\n",
- "\\frac{\\partial \\alpha}{\\partial \\boldsymbol{z}} = \\boldsymbol{x}^T\\frac{\\partial \\boldsymbol{x}}{\\partial \\boldsymbol{z}}.\n",
+ "\\frac{\\partial \\alpha}{\\partial \\boldsymbol{z}} = 2\\boldsymbol{x}^T\\frac{\\partial \\boldsymbol{x}}{\\partial \\boldsymbol{z}}.\n",
"$$"
]
},
{
"cell_type": "markdown",
- "id": "3bbfcddd",
+ "id": "3fecd0ad",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## The mean squared error and its derivative\n",
+ "We defined earlier a possible cost function using the mean squared error"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5fec2cb8",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)\\right\\},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "bb3237ca",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "or using the design/feature matrix $\\boldsymbol{X}$ we have the more compact matrix-vector"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9a54e245",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d78cab0a",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "We note that the design matrix $\\boldsymbol{X}$ does not depend on the unknown parameters defined by the vector $\\boldsymbol{\\beta}$.\n",
+ "We are now interested in minimizing the cost function with respect to the unknown parameters $\\boldsymbol{\\beta}$.\n",
+ "\n",
+ "The mean squared error is scalar and if we use the results from the last example, we define a new vector"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0f63a231",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\boldsymbol{w}=\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "16424b20",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "which depends on $\\boldsymbol{\\beta}$. We rewrite the cost function as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8cf337e7",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\boldsymbol{w}^T\\boldsymbol{w},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "59996e4b",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "with partial derivative"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6111dd9c",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}=\\frac{2}{n}\\boldsymbol{w}^T\\frac{\\partial \\boldsymbol{w}}{\\partial \\boldsymbol{\\beta}},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "81ca16ce",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "and using that"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "77d74ef6",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\frac{\\partial \\boldsymbol{w}}{\\partial \\boldsymbol{\\beta}}=-\\boldsymbol{X},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c5742e4c",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "where we ued the results from example two. Inserting the last expression we obtain"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "516debb1",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}=-\\frac{2}{n}\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\boldsymbol{X},\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "22c987bc",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "or as"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "248a0aa9",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "$$\n",
+ "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}^T}=-\\frac{2}{n}\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right).\n",
+ "$$"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f458b188",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "## Other useful relations\n",
+ "\n",
+ "We list here some other useful relations we may encounter (recall that vectors are defined by boldfaced low-key letters)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a1cf8131",
"metadata": {
"editable": true
},
@@ -1495,19 +1567,7 @@
},
{
"cell_type": "markdown",
- "id": "f9de57a3",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\frac{\\partial (\\boldsymbol{a}^T\\boldsymbol{A}\\boldsymbol{a})}{\\partial \\boldsymbol{a}} = (\\boldsymbol{A}+\\boldsymbol{A}^T)\\boldsymbol{a},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "3bbcdb89",
+ "id": "2688862c",
"metadata": {
"editable": true
},
@@ -1519,7 +1579,7 @@
},
{
"cell_type": "markdown",
- "id": "c49c52b1",
+ "id": "3da0030f",
"metadata": {
"editable": true
},
@@ -1531,17 +1591,7 @@
},
{
"cell_type": "markdown",
- "id": "beacc93a",
- "metadata": {
- "editable": true
- },
- "source": [
- "See the jupyter-book (complete lecture notes) for the derivations of these relations."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "a2e4613b",
+ "id": "0ae7f03b",
"metadata": {
"editable": true
},
@@ -1552,12 +1602,12 @@
"Learning is the Hessian. It is given by the second derivative of the\n",
"cost function with respect to the parameter $\\beta$. Using the above\n",
"expression for derivatives of vectors and matrices, we find that the\n",
- "second derivative of the cost function is,"
+ "second derivative of the mean squared error as cost function is,"
]
},
{
"cell_type": "markdown",
- "id": "3011429a",
+ "id": "1f559f6b",
"metadata": {
"editable": true
},
@@ -1569,7 +1619,7 @@
},
{
"cell_type": "markdown",
- "id": "041282da",
+ "id": "b7fddf1e",
"metadata": {
"editable": true
},
@@ -1579,7 +1629,7 @@
},
{
"cell_type": "markdown",
- "id": "f5051ef3",
+ "id": "ce41be61",
"metadata": {
"editable": true
},
@@ -1591,7 +1641,7 @@
},
{
"cell_type": "markdown",
- "id": "fdfa01f5",
+ "id": "ada0013a",
"metadata": {
"editable": true
},
@@ -1609,7 +1659,7 @@
},
{
"cell_type": "markdown",
- "id": "e74bc230",
+ "id": "b5d155f7",
"metadata": {
"editable": true
},
@@ -1620,7 +1670,7 @@
},
{
"cell_type": "markdown",
- "id": "96c09e60",
+ "id": "74e6d32a",
"metadata": {
"editable": true
},
@@ -1632,7 +1682,7 @@
},
{
"cell_type": "markdown",
- "id": "362dbaa7",
+ "id": "58f668d3",
"metadata": {
"editable": true
},
@@ -1642,7 +1692,7 @@
},
{
"cell_type": "markdown",
- "id": "ab94a197",
+ "id": "f6b8bccb",
"metadata": {
"editable": true
},
@@ -1654,7 +1704,7 @@
},
{
"cell_type": "markdown",
- "id": "607165ea",
+ "id": "d07b6a67",
"metadata": {
"editable": true
},
@@ -1664,7 +1714,7 @@
},
{
"cell_type": "markdown",
- "id": "3c71f913",
+ "id": "0b54b478",
"metadata": {
"editable": true
},
@@ -1676,7 +1726,7 @@
},
{
"cell_type": "markdown",
- "id": "62438ee3",
+ "id": "fa05b02c",
"metadata": {
"editable": true
},
@@ -1686,7 +1736,7 @@
},
{
"cell_type": "markdown",
- "id": "e3d54779",
+ "id": "40f81236",
"metadata": {
"editable": true
},
@@ -1699,8 +1749,8 @@
},
{
"cell_type": "code",
- "execution_count": 2,
- "id": "740c3328",
+ "execution_count": 1,
+ "id": "10c82fe6",
"metadata": {
"collapsed": false,
"editable": true
@@ -1715,7 +1765,7 @@
},
{
"cell_type": "markdown",
- "id": "371fb510",
+ "id": "cb8c9059",
"metadata": {
"editable": true
},
@@ -1725,8 +1775,8 @@
},
{
"cell_type": "code",
- "execution_count": 3,
- "id": "61aca815",
+ "execution_count": 2,
+ "id": "3a7fee84",
"metadata": {
"collapsed": false,
"editable": true
@@ -1739,7 +1789,7 @@
},
{
"cell_type": "markdown",
- "id": "bb527fb1",
+ "id": "5ba72437",
"metadata": {
"editable": true
},
@@ -1749,8 +1799,8 @@
},
{
"cell_type": "code",
- "execution_count": 4,
- "id": "32131dd7",
+ "execution_count": 3,
+ "id": "8d9d480f",
"metadata": {
"collapsed": false,
"editable": true
@@ -1773,7 +1823,7 @@
},
{
"cell_type": "markdown",
- "id": "b1d1974f",
+ "id": "cdb7ef56",
"metadata": {
"editable": true
},
@@ -1786,8 +1836,8 @@
},
{
"cell_type": "code",
- "execution_count": 5,
- "id": "f624ba9a",
+ "execution_count": 4,
+ "id": "ae78550a",
"metadata": {
"collapsed": false,
"editable": true
@@ -1800,7 +1850,7 @@
},
{
"cell_type": "markdown",
- "id": "be1087ad",
+ "id": "2a784ef4",
"metadata": {
"editable": true
},
@@ -1810,8 +1860,8 @@
},
{
"cell_type": "code",
- "execution_count": 6,
- "id": "cbb4f05a",
+ "execution_count": 5,
+ "id": "ba22c85c",
"metadata": {
"collapsed": false,
"editable": true
@@ -1823,7 +1873,7 @@
},
{
"cell_type": "markdown",
- "id": "6618c9ac",
+ "id": "2a1fb7d6",
"metadata": {
"editable": true
},
@@ -1833,8 +1883,8 @@
},
{
"cell_type": "code",
- "execution_count": 7,
- "id": "5d42836c",
+ "execution_count": 6,
+ "id": "86a8e7ff",
"metadata": {
"collapsed": false,
"editable": true
@@ -1850,7 +1900,7 @@
},
{
"cell_type": "markdown",
- "id": "4e05db4b",
+ "id": "608036a7",
"metadata": {
"editable": true
},
@@ -1860,8 +1910,8 @@
},
{
"cell_type": "code",
- "execution_count": 8,
- "id": "596771e9",
+ "execution_count": 7,
+ "id": "44a9ac4e",
"metadata": {
"collapsed": false,
"editable": true
@@ -1875,7 +1925,7 @@
},
{
"cell_type": "markdown",
- "id": "8e20961b",
+ "id": "e5ebc370",
"metadata": {
"editable": true
},
@@ -1896,7 +1946,7 @@
},
{
"cell_type": "markdown",
- "id": "f7e8ca15",
+ "id": "7716646d",
"metadata": {
"editable": true
},
@@ -1906,14 +1956,16 @@
},
{
"cell_type": "code",
- "execution_count": 9,
- "id": "7ff960a3",
+ "execution_count": 8,
+ "id": "1707bc68",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
+ "%matplotlib inline\n",
+ "\n",
"import os\n",
"import numpy as np\n",
"import pandas as pd\n",
@@ -1956,7 +2008,7 @@
},
{
"cell_type": "markdown",
- "id": "9bfd0944",
+ "id": "8c0c154a",
"metadata": {
"editable": true
},
@@ -1966,8 +2018,8 @@
},
{
"cell_type": "code",
- "execution_count": 10,
- "id": "d5658a55",
+ "execution_count": 9,
+ "id": "e287c7d8",
"metadata": {
"collapsed": false,
"editable": true
@@ -1992,7 +2044,7 @@
},
{
"cell_type": "markdown",
- "id": "911dca3d",
+ "id": "316f2613",
"metadata": {
"editable": true
},
@@ -2004,7 +2056,7 @@
},
{
"cell_type": "markdown",
- "id": "b9da2e78",
+ "id": "98415ea8",
"metadata": {
"editable": true
},
@@ -2048,7 +2100,7 @@
},
{
"cell_type": "markdown",
- "id": "26d7da85",
+ "id": "0142d1b3",
"metadata": {
"editable": true
},
@@ -2059,8 +2111,8 @@
},
{
"cell_type": "code",
- "execution_count": 11,
- "id": "e492a54e",
+ "execution_count": 10,
+ "id": "c51a1e1f",
"metadata": {
"collapsed": false,
"editable": true
@@ -2076,7 +2128,7 @@
},
{
"cell_type": "markdown",
- "id": "bb35f36a",
+ "id": "8ca465b9",
"metadata": {
"editable": true
},
@@ -2086,8 +2138,8 @@
},
{
"cell_type": "code",
- "execution_count": 12,
- "id": "7a08b583",
+ "execution_count": 11,
+ "id": "7a08d5ba",
"metadata": {
"collapsed": false,
"editable": true
@@ -2105,7 +2157,7 @@
},
{
"cell_type": "markdown",
- "id": "5ee6d242",
+ "id": "0de76bad",
"metadata": {
"editable": true
},
@@ -2115,8 +2167,8 @@
},
{
"cell_type": "code",
- "execution_count": 13,
- "id": "72589f20",
+ "execution_count": 12,
+ "id": "a35b91c5",
"metadata": {
"collapsed": false,
"editable": true
@@ -2130,7 +2182,7 @@
},
{
"cell_type": "markdown",
- "id": "87a58f5c",
+ "id": "7ec4da64",
"metadata": {
"editable": true
},
@@ -2140,8 +2192,8 @@
},
{
"cell_type": "code",
- "execution_count": 14,
- "id": "293c9899",
+ "execution_count": 13,
+ "id": "e34dc07b",
"metadata": {
"collapsed": false,
"editable": true
@@ -2154,7 +2206,7 @@
},
{
"cell_type": "markdown",
- "id": "09035343",
+ "id": "8a238d5a",
"metadata": {
"editable": true
},
@@ -2164,8 +2216,8 @@
},
{
"cell_type": "code",
- "execution_count": 15,
- "id": "9592e630",
+ "execution_count": 14,
+ "id": "c546acce",
"metadata": {
"collapsed": false,
"editable": true
@@ -2182,7 +2234,7 @@
},
{
"cell_type": "markdown",
- "id": "4e960a49",
+ "id": "5af6f212",
"metadata": {
"editable": true
},
@@ -2192,8 +2244,8 @@
},
{
"cell_type": "code",
- "execution_count": 16,
- "id": "6de32b29",
+ "execution_count": 15,
+ "id": "0e121333",
"metadata": {
"collapsed": false,
"editable": true
@@ -2209,7 +2261,7 @@
},
{
"cell_type": "markdown",
- "id": "73346949",
+ "id": "b1952d47",
"metadata": {
"editable": true
},
@@ -2219,8 +2271,8 @@
},
{
"cell_type": "code",
- "execution_count": 17,
- "id": "39c7ac51",
+ "execution_count": 16,
+ "id": "e94e0a02",
"metadata": {
"collapsed": false,
"editable": true
@@ -2244,7 +2296,7 @@
},
{
"cell_type": "markdown",
- "id": "21bd31b4",
+ "id": "e095b24e",
"metadata": {
"editable": true
},
@@ -2254,8 +2306,8 @@
},
{
"cell_type": "code",
- "execution_count": 18,
- "id": "09562f9a",
+ "execution_count": 17,
+ "id": "aa39b6c5",
"metadata": {
"collapsed": false,
"editable": true
@@ -2268,7 +2320,7 @@
},
{
"cell_type": "markdown",
- "id": "4536c7d4",
+ "id": "3a55baa9",
"metadata": {
"editable": true
},
@@ -2278,8 +2330,8 @@
},
{
"cell_type": "code",
- "execution_count": 19,
- "id": "dfc5c92b",
+ "execution_count": 18,
+ "id": "9296d9c8",
"metadata": {
"collapsed": false,
"editable": true
@@ -2299,7 +2351,7 @@
},
{
"cell_type": "markdown",
- "id": "c49ebc89",
+ "id": "79270137",
"metadata": {
"editable": true
},
@@ -2309,8 +2361,8 @@
},
{
"cell_type": "code",
- "execution_count": 20,
- "id": "808a3936",
+ "execution_count": 19,
+ "id": "4f106e9f",
"metadata": {
"collapsed": false,
"editable": true
@@ -2352,8 +2404,8 @@
},
{
"cell_type": "code",
- "execution_count": 21,
- "id": "05ad21d1",
+ "execution_count": 20,
+ "id": "483f05af",
"metadata": {
"collapsed": false,
"editable": true
@@ -2368,7 +2420,7 @@
},
{
"cell_type": "markdown",
- "id": "9b850e87",
+ "id": "3679cc9e",
"metadata": {
"editable": true
},
@@ -2397,7 +2449,7 @@
},
{
"cell_type": "markdown",
- "id": "5391a41f",
+ "id": "bafe3d78",
"metadata": {
"editable": true
},
@@ -2422,7 +2474,7 @@
},
{
"cell_type": "markdown",
- "id": "67941dc1",
+ "id": "d76ffb44",
"metadata": {
"editable": true
},
@@ -2442,7 +2494,7 @@
},
{
"cell_type": "markdown",
- "id": "a2de41c6",
+ "id": "3fbf964a",
"metadata": {
"editable": true
},
@@ -2469,7 +2521,7 @@
},
{
"cell_type": "markdown",
- "id": "013befe3",
+ "id": "2fdf6ed7",
"metadata": {
"editable": true
},
@@ -2482,7 +2534,7 @@
},
{
"cell_type": "markdown",
- "id": "d84bd7ca",
+ "id": "e83882f2",
"metadata": {
"editable": true
},
@@ -2494,7 +2546,7 @@
},
{
"cell_type": "markdown",
- "id": "62bcc439",
+ "id": "b799b457",
"metadata": {
"editable": true
},
@@ -2505,7 +2557,7 @@
},
{
"cell_type": "markdown",
- "id": "2e36c6c5",
+ "id": "57367fcf",
"metadata": {
"editable": true
},
@@ -2520,8 +2572,8 @@
},
{
"cell_type": "code",
- "execution_count": 22,
- "id": "eb82718d",
+ "execution_count": 21,
+ "id": "b63f87b3",
"metadata": {
"collapsed": false,
"editable": true
@@ -2555,7 +2607,7 @@
},
{
"cell_type": "markdown",
- "id": "10672749",
+ "id": "ca5fed2f",
"metadata": {
"editable": true
},
@@ -2565,7 +2617,7 @@
},
{
"cell_type": "markdown",
- "id": "627fdd21",
+ "id": "43e9c51e",
"metadata": {
"editable": true
},
@@ -2580,7 +2632,7 @@
},
{
"cell_type": "markdown",
- "id": "fabb593a",
+ "id": "8e2eef7a",
"metadata": {
"editable": true
},
@@ -2592,7 +2644,7 @@
},
{
"cell_type": "markdown",
- "id": "d4dda072",
+ "id": "aaf86ed6",
"metadata": {
"editable": true
},
@@ -2602,7 +2654,7 @@
},
{
"cell_type": "markdown",
- "id": "fdad2009",
+ "id": "e83de593",
"metadata": {
"editable": true
},
@@ -2617,8 +2669,8 @@
},
{
"cell_type": "code",
- "execution_count": 23,
- "id": "3994904b",
+ "execution_count": 22,
+ "id": "f91245a9",
"metadata": {
"collapsed": false,
"editable": true
@@ -2635,7 +2687,7 @@
},
{
"cell_type": "markdown",
- "id": "aa276983",
+ "id": "96060f84",
"metadata": {
"editable": true
},
@@ -2647,8 +2699,8 @@
},
{
"cell_type": "code",
- "execution_count": 24,
- "id": "6e935382",
+ "execution_count": 23,
+ "id": "77822e66",
"metadata": {
"collapsed": false,
"editable": true
@@ -2695,7 +2747,7 @@
},
{
"cell_type": "markdown",
- "id": "63698684",
+ "id": "3f2d5d5b",
"metadata": {
"editable": true
},
@@ -2705,8 +2757,8 @@
},
{
"cell_type": "code",
- "execution_count": 25,
- "id": "3c34e004",
+ "execution_count": 24,
+ "id": "ee12fcba",
"metadata": {
"collapsed": false,
"editable": true
@@ -2809,7 +2861,7 @@
},
{
"cell_type": "markdown",
- "id": "bbff0bb9",
+ "id": "64d839e1",
"metadata": {
"editable": true
},
@@ -2819,7 +2871,7 @@
},
{
"cell_type": "markdown",
- "id": "1f1864d4",
+ "id": "17717d0e",
"metadata": {
"editable": true
},
@@ -2833,7 +2885,7 @@
},
{
"cell_type": "markdown",
- "id": "11ffb735",
+ "id": "15413b2e",
"metadata": {
"editable": true
},
@@ -2845,7 +2897,7 @@
},
{
"cell_type": "markdown",
- "id": "1690e327",
+ "id": "f903bf87",
"metadata": {
"editable": true
},
@@ -2857,7 +2909,7 @@
},
{
"cell_type": "markdown",
- "id": "77edc6e5",
+ "id": "7acb0532",
"metadata": {
"editable": true
},
@@ -2869,7 +2921,7 @@
},
{
"cell_type": "markdown",
- "id": "8f8b8011",
+ "id": "bfddbabe",
"metadata": {
"editable": true
},
@@ -2879,7 +2931,7 @@
},
{
"cell_type": "markdown",
- "id": "8341188d",
+ "id": "b0bb99e0",
"metadata": {
"editable": true
},
@@ -2891,7 +2943,7 @@
},
{
"cell_type": "markdown",
- "id": "588b07b8",
+ "id": "078dcbad",
"metadata": {
"editable": true
},
@@ -2901,7 +2953,7 @@
},
{
"cell_type": "markdown",
- "id": "f8f2f728",
+ "id": "d916e2e1",
"metadata": {
"editable": true
},
@@ -2913,7 +2965,7 @@
},
{
"cell_type": "markdown",
- "id": "8530b420",
+ "id": "cbc84ca0",
"metadata": {
"editable": true
},
@@ -2924,7 +2976,7 @@
},
{
"cell_type": "markdown",
- "id": "475ec36c",
+ "id": "0aac1d9a",
"metadata": {
"editable": true
},
@@ -2936,7 +2988,7 @@
},
{
"cell_type": "markdown",
- "id": "ed608db1",
+ "id": "1f415b9a",
"metadata": {
"editable": true
},
@@ -2948,7 +3000,7 @@
},
{
"cell_type": "markdown",
- "id": "bd7fc3a1",
+ "id": "cc178968",
"metadata": {
"editable": true
},
@@ -2958,7 +3010,7 @@
},
{
"cell_type": "markdown",
- "id": "43262a06",
+ "id": "d3617f7e",
"metadata": {
"editable": true
},
@@ -2970,7 +3022,7 @@
},
{
"cell_type": "markdown",
- "id": "f78b19b7",
+ "id": "6053d4ef",
"metadata": {
"editable": true
},
@@ -2982,7 +3034,7 @@
},
{
"cell_type": "markdown",
- "id": "ef70a846",
+ "id": "9c173167",
"metadata": {
"editable": true
},
@@ -2992,7 +3044,7 @@
},
{
"cell_type": "markdown",
- "id": "73a86929",
+ "id": "0fc836a2",
"metadata": {
"editable": true
},
@@ -3004,7 +3056,7 @@
},
{
"cell_type": "markdown",
- "id": "57f70b0f",
+ "id": "29e20c00",
"metadata": {
"editable": true
},
@@ -3014,7 +3066,7 @@
},
{
"cell_type": "markdown",
- "id": "07f95f17",
+ "id": "61083d55",
"metadata": {
"editable": true
},
@@ -3026,7 +3078,7 @@
},
{
"cell_type": "markdown",
- "id": "7f6d313c",
+ "id": "e0b2a81f",
"metadata": {
"editable": true
},
@@ -3036,7 +3088,7 @@
},
{
"cell_type": "markdown",
- "id": "7df354ec",
+ "id": "cd355260",
"metadata": {
"editable": true
},
@@ -3076,7 +3128,7 @@
},
{
"cell_type": "markdown",
- "id": "30ad032e",
+ "id": "817065ea",
"metadata": {
"editable": true
},
@@ -3093,7 +3145,7 @@
},
{
"cell_type": "markdown",
- "id": "a10d6c71",
+ "id": "044b9dbe",
"metadata": {
"editable": true
},
@@ -3116,7 +3168,7 @@
},
{
"cell_type": "markdown",
- "id": "a6ca2ad0",
+ "id": "e11cd668",
"metadata": {
"editable": true
},
@@ -3133,7 +3185,7 @@
},
{
"cell_type": "markdown",
- "id": "7804638a",
+ "id": "6279d884",
"metadata": {
"editable": true
},
@@ -3152,7 +3204,7 @@
},
{
"cell_type": "markdown",
- "id": "28c5da08",
+ "id": "249b188f",
"metadata": {
"editable": true
},
@@ -3163,7 +3215,7 @@
},
{
"cell_type": "markdown",
- "id": "147c648a",
+ "id": "602722e8",
"metadata": {
"editable": true
},
@@ -3175,7 +3227,7 @@
},
{
"cell_type": "markdown",
- "id": "0fb2a050",
+ "id": "3c9a0686",
"metadata": {
"editable": true
},
@@ -3193,7 +3245,7 @@
},
{
"cell_type": "markdown",
- "id": "96350678",
+ "id": "8db94cb4",
"metadata": {
"editable": true
},
@@ -3209,7 +3261,7 @@
},
{
"cell_type": "markdown",
- "id": "eda258a9",
+ "id": "2518d21e",
"metadata": {
"editable": true
},
@@ -3221,7 +3273,7 @@
},
{
"cell_type": "markdown",
- "id": "fc22cae5",
+ "id": "c46aa72e",
"metadata": {
"editable": true
},
@@ -3231,7 +3283,7 @@
},
{
"cell_type": "markdown",
- "id": "2c6e3b32",
+ "id": "7af9a70f",
"metadata": {
"editable": true
},
@@ -3246,7 +3298,7 @@
},
{
"cell_type": "markdown",
- "id": "b8da41cd",
+ "id": "fd6756e4",
"metadata": {
"editable": true
},
@@ -3258,7 +3310,7 @@
},
{
"cell_type": "markdown",
- "id": "e2d4a8d4",
+ "id": "532b71ff",
"metadata": {
"editable": true
},
@@ -3268,7 +3320,7 @@
},
{
"cell_type": "markdown",
- "id": "bea62d6a",
+ "id": "fff72396",
"metadata": {
"editable": true
},
@@ -3280,7 +3332,7 @@
},
{
"cell_type": "markdown",
- "id": "9474fc66",
+ "id": "f8ffe252",
"metadata": {
"editable": true
},
@@ -3290,7 +3342,7 @@
},
{
"cell_type": "markdown",
- "id": "154a271e",
+ "id": "5addd04c",
"metadata": {
"editable": true
},
@@ -3302,7 +3354,7 @@
},
{
"cell_type": "markdown",
- "id": "e3b6c564",
+ "id": "38d0ed69",
"metadata": {
"editable": true
},
@@ -3314,7 +3366,7 @@
},
{
"cell_type": "markdown",
- "id": "84b6d915",
+ "id": "58155893",
"metadata": {
"editable": true
},
@@ -3329,7 +3381,7 @@
},
{
"cell_type": "markdown",
- "id": "c1b2c6df",
+ "id": "3dd04453",
"metadata": {
"editable": true
},
@@ -3340,7 +3392,7 @@
},
{
"cell_type": "markdown",
- "id": "5e5a8887",
+ "id": "5bf28f64",
"metadata": {
"editable": true
},
@@ -3360,7 +3412,7 @@
},
{
"cell_type": "markdown",
- "id": "e5091061",
+ "id": "b878a894",
"metadata": {
"editable": true
},
@@ -3372,7 +3424,7 @@
},
{
"cell_type": "markdown",
- "id": "ee9135cd",
+ "id": "11daed8b",
"metadata": {
"editable": true
},
@@ -3382,7 +3434,7 @@
},
{
"cell_type": "markdown",
- "id": "f73349af",
+ "id": "0212b20a",
"metadata": {
"editable": true
},
@@ -3394,7 +3446,7 @@
},
{
"cell_type": "markdown",
- "id": "520e32b6",
+ "id": "66cd4418",
"metadata": {
"editable": true
},
@@ -3423,7 +3475,7 @@
},
{
"cell_type": "markdown",
- "id": "997e0d93",
+ "id": "55f2558b",
"metadata": {
"editable": true
},
@@ -3450,7 +3502,7 @@
},
{
"cell_type": "markdown",
- "id": "ab0d18dd",
+ "id": "4f3efe0a",
"metadata": {
"editable": true
},
@@ -3460,8 +3512,8 @@
},
{
"cell_type": "code",
- "execution_count": 26,
- "id": "12eba95a",
+ "execution_count": 25,
+ "id": "afe81ed8",
"metadata": {
"collapsed": false,
"editable": true
@@ -3501,7 +3553,7 @@
},
{
"cell_type": "markdown",
- "id": "91d03de4",
+ "id": "93396e70",
"metadata": {
"editable": true
},
@@ -3518,7 +3570,7 @@
},
{
"cell_type": "markdown",
- "id": "32045d4c",
+ "id": "d83c5c51",
"metadata": {
"editable": true
},
@@ -3541,7 +3593,7 @@
},
{
"cell_type": "markdown",
- "id": "f3f43b2f",
+ "id": "ee8da503",
"metadata": {
"editable": true
},
@@ -3555,7 +3607,7 @@
},
{
"cell_type": "markdown",
- "id": "1d74a0f4",
+ "id": "a02404ed",
"metadata": {
"editable": true
},
@@ -3574,7 +3626,7 @@
},
{
"cell_type": "markdown",
- "id": "07afc819",
+ "id": "cd99939b",
"metadata": {
"editable": true
},
@@ -3584,7 +3636,7 @@
},
{
"cell_type": "markdown",
- "id": "400432ff",
+ "id": "57addf2c",
"metadata": {
"editable": true
},
@@ -3596,7 +3648,7 @@
},
{
"cell_type": "markdown",
- "id": "2baca504",
+ "id": "8025a8f0",
"metadata": {
"editable": true
},
@@ -3610,7 +3662,7 @@
},
{
"cell_type": "markdown",
- "id": "f1220e03",
+ "id": "dc22ff97",
"metadata": {
"editable": true
},
@@ -3622,7 +3674,7 @@
},
{
"cell_type": "markdown",
- "id": "ad2a18bd",
+ "id": "80984722",
"metadata": {
"editable": true
},
@@ -3632,7 +3684,7 @@
},
{
"cell_type": "markdown",
- "id": "dc956002",
+ "id": "ee1a461e",
"metadata": {
"editable": true
},
@@ -3644,7 +3696,7 @@
},
{
"cell_type": "markdown",
- "id": "71b1b61b",
+ "id": "67063363",
"metadata": {
"editable": true
},
@@ -3661,7 +3713,7 @@
},
{
"cell_type": "markdown",
- "id": "119a5ac5",
+ "id": "8977bf31",
"metadata": {
"editable": true
},
@@ -3671,7 +3723,7 @@
},
{
"cell_type": "markdown",
- "id": "b6786fb4",
+ "id": "44d8f4a5",
"metadata": {
"editable": true
},
@@ -3687,7 +3739,7 @@
},
{
"cell_type": "markdown",
- "id": "a4a97827",
+ "id": "2b0b6b67",
"metadata": {
"editable": true
},
@@ -3697,7 +3749,7 @@
},
{
"cell_type": "markdown",
- "id": "6827b736",
+ "id": "131f2998",
"metadata": {
"editable": true
},
@@ -3713,7 +3765,7 @@
},
{
"cell_type": "markdown",
- "id": "c7e1a4b8",
+ "id": "4d2c4d69",
"metadata": {
"editable": true
},
@@ -3723,7 +3775,7 @@
},
{
"cell_type": "markdown",
- "id": "26a509a4",
+ "id": "4337dd56",
"metadata": {
"editable": true
},
@@ -3739,7 +3791,7 @@
},
{
"cell_type": "markdown",
- "id": "3008a7cc",
+ "id": "e01c7967",
"metadata": {
"editable": true
},
@@ -3749,7 +3801,7 @@
},
{
"cell_type": "markdown",
- "id": "3352cd5e",
+ "id": "373ea9f7",
"metadata": {
"editable": true
},
@@ -3766,7 +3818,7 @@
},
{
"cell_type": "markdown",
- "id": "1d65545b",
+ "id": "e1703e60",
"metadata": {
"editable": true
},
@@ -3778,7 +3830,7 @@
},
{
"cell_type": "markdown",
- "id": "707eb252",
+ "id": "ab0f565b",
"metadata": {
"editable": true
},
@@ -3790,7 +3842,7 @@
},
{
"cell_type": "markdown",
- "id": "c505686c",
+ "id": "974d6f46",
"metadata": {
"editable": true
},
@@ -3802,7 +3854,7 @@
},
{
"cell_type": "markdown",
- "id": "cc5a0947",
+ "id": "728533d0",
"metadata": {
"editable": true
},
@@ -3812,7 +3864,7 @@
},
{
"cell_type": "markdown",
- "id": "cb22b694",
+ "id": "88b297be",
"metadata": {
"editable": true
},
@@ -3824,7 +3876,7 @@
},
{
"cell_type": "markdown",
- "id": "41855f9a",
+ "id": "4c0b5bad",
"metadata": {
"editable": true
},
@@ -3836,7 +3888,7 @@
},
{
"cell_type": "markdown",
- "id": "55b45cd9",
+ "id": "5d27849f",
"metadata": {
"editable": true
},
@@ -3848,7 +3900,7 @@
},
{
"cell_type": "markdown",
- "id": "1b0b21c1",
+ "id": "ce0224f0",
"metadata": {
"editable": true
},
@@ -3858,7 +3910,7 @@
},
{
"cell_type": "markdown",
- "id": "00835a4b",
+ "id": "42224bb1",
"metadata": {
"editable": true
},
@@ -3870,7 +3922,7 @@
},
{
"cell_type": "markdown",
- "id": "7af20f40",
+ "id": "93d127a3",
"metadata": {
"editable": true
},
@@ -3880,7 +3932,7 @@
},
{
"cell_type": "markdown",
- "id": "a52e3763",
+ "id": "db0ba692",
"metadata": {
"editable": true
},
@@ -3892,7 +3944,7 @@
},
{
"cell_type": "markdown",
- "id": "a0a96c5d",
+ "id": "bcd7992b",
"metadata": {
"editable": true
},
@@ -3906,7 +3958,7 @@
},
{
"cell_type": "markdown",
- "id": "24e12720",
+ "id": "1ee496de",
"metadata": {
"editable": true
},
@@ -3918,7 +3970,7 @@
},
{
"cell_type": "markdown",
- "id": "8d173baa",
+ "id": "e8215dbb",
"metadata": {
"editable": true
},
@@ -3930,7 +3982,7 @@
},
{
"cell_type": "markdown",
- "id": "2a54fa99",
+ "id": "ef2d8c78",
"metadata": {
"editable": true
},
@@ -3940,7 +3992,7 @@
},
{
"cell_type": "markdown",
- "id": "52545399",
+ "id": "f0f11c17",
"metadata": {
"editable": true
},
@@ -3952,7 +4004,7 @@
},
{
"cell_type": "markdown",
- "id": "1a33171f",
+ "id": "dda9921b",
"metadata": {
"editable": true
},
@@ -3963,7 +4015,7 @@
},
{
"cell_type": "markdown",
- "id": "2c0eca71",
+ "id": "152a8bd7",
"metadata": {
"editable": true
},
@@ -3975,7 +4027,7 @@
},
{
"cell_type": "markdown",
- "id": "010e06fe",
+ "id": "c465492c",
"metadata": {
"editable": true
},
@@ -3985,7 +4037,7 @@
},
{
"cell_type": "markdown",
- "id": "1f3a5397",
+ "id": "7767799f",
"metadata": {
"editable": true
},
@@ -3997,7 +4049,7 @@
},
{
"cell_type": "markdown",
- "id": "e24d416b",
+ "id": "353f8cdf",
"metadata": {
"editable": true
},
@@ -4007,7 +4059,7 @@
},
{
"cell_type": "markdown",
- "id": "1051f64e",
+ "id": "fb6ca205",
"metadata": {
"editable": true
},
@@ -4019,7 +4071,7 @@
},
{
"cell_type": "markdown",
- "id": "8fa79dbe",
+ "id": "19cd9668",
"metadata": {
"editable": true
},
@@ -4030,7 +4082,7 @@
},
{
"cell_type": "markdown",
- "id": "bdeb76a6",
+ "id": "25944bab",
"metadata": {
"editable": true
},
@@ -4042,7 +4094,7 @@
},
{
"cell_type": "markdown",
- "id": "14e82cd7",
+ "id": "712fb2fe",
"metadata": {
"editable": true
},
@@ -4060,7 +4112,7 @@
},
{
"cell_type": "markdown",
- "id": "673d3c02",
+ "id": "79f9c95a",
"metadata": {
"editable": true
},
@@ -4076,7 +4128,7 @@
},
{
"cell_type": "markdown",
- "id": "92bc7abd",
+ "id": "a468fbce",
"metadata": {
"editable": true
},
@@ -4088,7 +4140,7 @@
},
{
"cell_type": "markdown",
- "id": "384b8049",
+ "id": "cf18ad32",
"metadata": {
"editable": true
},
@@ -4100,7 +4152,7 @@
},
{
"cell_type": "markdown",
- "id": "888b2049",
+ "id": "e85c87e1",
"metadata": {
"editable": true
},
@@ -4112,7 +4164,7 @@
},
{
"cell_type": "markdown",
- "id": "6bec7731",
+ "id": "f62581d1",
"metadata": {
"editable": true
},
@@ -4125,7 +4177,7 @@
},
{
"cell_type": "markdown",
- "id": "9479c217",
+ "id": "3c9caf4c",
"metadata": {
"editable": true
},
@@ -4141,7 +4193,7 @@
},
{
"cell_type": "markdown",
- "id": "9310029c",
+ "id": "af361057",
"metadata": {
"editable": true
},
@@ -4155,7 +4207,7 @@
},
{
"cell_type": "markdown",
- "id": "2321672f",
+ "id": "4d3d1dbe",
"metadata": {
"editable": true
},
@@ -4165,7 +4217,7 @@
},
{
"cell_type": "markdown",
- "id": "7c614420",
+ "id": "042ac1c5",
"metadata": {
"editable": true
},
@@ -4177,7 +4229,7 @@
},
{
"cell_type": "markdown",
- "id": "1fa38fcd",
+ "id": "e2da8a5c",
"metadata": {
"editable": true
},
@@ -4187,7 +4239,7 @@
},
{
"cell_type": "markdown",
- "id": "90aa34de",
+ "id": "51ef4882",
"metadata": {
"editable": true
},
@@ -4199,7 +4251,7 @@
},
{
"cell_type": "markdown",
- "id": "cc9b078e",
+ "id": "22fcd4c4",
"metadata": {
"editable": true
},
@@ -4209,7 +4261,7 @@
},
{
"cell_type": "markdown",
- "id": "e9a62c9b",
+ "id": "d76d69f1",
"metadata": {
"editable": true
},
@@ -4223,7 +4275,7 @@
},
{
"cell_type": "markdown",
- "id": "a0d6822b",
+ "id": "070d9698",
"metadata": {
"editable": true
},
@@ -4240,7 +4292,7 @@
},
{
"cell_type": "markdown",
- "id": "25c75290",
+ "id": "397f3d35",
"metadata": {
"editable": true
},
@@ -4256,7 +4308,7 @@
},
{
"cell_type": "markdown",
- "id": "a5eb3c49",
+ "id": "d9244e73",
"metadata": {
"editable": true
},
@@ -4268,7 +4320,7 @@
},
{
"cell_type": "markdown",
- "id": "815d87f4",
+ "id": "b499e768",
"metadata": {
"editable": true
},
@@ -4281,7 +4333,7 @@
},
{
"cell_type": "markdown",
- "id": "0e4df8ec",
+ "id": "bbd060aa",
"metadata": {
"editable": true
},
@@ -4295,7 +4347,7 @@
},
{
"cell_type": "markdown",
- "id": "3c792318",
+ "id": "1bd717cb",
"metadata": {
"editable": true
},
@@ -4305,7 +4357,7 @@
},
{
"cell_type": "markdown",
- "id": "217715de",
+ "id": "a39907f5",
"metadata": {
"editable": true
},
@@ -4318,7 +4370,7 @@
},
{
"cell_type": "markdown",
- "id": "f0968a34",
+ "id": "31128531",
"metadata": {
"editable": true
},
@@ -4337,7 +4389,7 @@
},
{
"cell_type": "markdown",
- "id": "e38ae0b8",
+ "id": "e296367a",
"metadata": {
"editable": true
},
@@ -4349,7 +4401,7 @@
},
{
"cell_type": "markdown",
- "id": "a746900f",
+ "id": "2fa5d635",
"metadata": {
"editable": true
},
@@ -4361,7 +4413,7 @@
},
{
"cell_type": "markdown",
- "id": "ffdaa59f",
+ "id": "b78b10ce",
"metadata": {
"editable": true
},
@@ -4371,7 +4423,7 @@
},
{
"cell_type": "markdown",
- "id": "158ab641",
+ "id": "c356b0c1",
"metadata": {
"editable": true
},
@@ -4383,7 +4435,7 @@
},
{
"cell_type": "markdown",
- "id": "2559b777",
+ "id": "e5d6530d",
"metadata": {
"editable": true
},
@@ -4396,7 +4448,7 @@
},
{
"cell_type": "markdown",
- "id": "903f2c31",
+ "id": "0cbe90a4",
"metadata": {
"editable": true
},
@@ -4415,7 +4467,7 @@
},
{
"cell_type": "markdown",
- "id": "170c954a",
+ "id": "359625de",
"metadata": {
"editable": true
},
@@ -4425,7 +4477,7 @@
},
{
"cell_type": "markdown",
- "id": "25ef4f9b",
+ "id": "40cec646",
"metadata": {
"editable": true
},
@@ -4444,7 +4496,7 @@
},
{
"cell_type": "markdown",
- "id": "036a7a05",
+ "id": "3718bf7f",
"metadata": {
"editable": true
},
@@ -4462,7 +4514,7 @@
},
{
"cell_type": "markdown",
- "id": "4c9e5974",
+ "id": "c805927d",
"metadata": {
"editable": true
},
@@ -4476,7 +4528,7 @@
},
{
"cell_type": "markdown",
- "id": "ef4639f2",
+ "id": "afeaecde",
"metadata": {
"editable": true
},
@@ -4490,8 +4542,8 @@
},
{
"cell_type": "code",
- "execution_count": 27,
- "id": "680f5019",
+ "execution_count": 26,
+ "id": "767e11f2",
"metadata": {
"collapsed": false,
"editable": true
@@ -4512,7 +4564,7 @@
},
{
"cell_type": "markdown",
- "id": "5aa33454",
+ "id": "cdfb6d8f",
"metadata": {
"editable": true
},
@@ -4528,8 +4580,8 @@
},
{
"cell_type": "code",
- "execution_count": 28,
- "id": "fc958260",
+ "execution_count": 27,
+ "id": "284fdef4",
"metadata": {
"collapsed": false,
"editable": true
@@ -4561,7 +4613,7 @@
},
{
"cell_type": "markdown",
- "id": "d3c9fa59",
+ "id": "1c3c85b3",
"metadata": {
"editable": true
},
@@ -4575,7 +4627,7 @@
},
{
"cell_type": "markdown",
- "id": "a97c4502",
+ "id": "4359dd30",
"metadata": {
"editable": true
},
@@ -4587,8 +4639,8 @@
},
{
"cell_type": "code",
- "execution_count": 29,
- "id": "ba15cdd8",
+ "execution_count": 28,
+ "id": "30d6d2be",
"metadata": {
"collapsed": false,
"editable": true
@@ -4613,7 +4665,7 @@
},
{
"cell_type": "markdown",
- "id": "90a08c41",
+ "id": "5779d660",
"metadata": {
"editable": true
},
@@ -4623,7 +4675,7 @@
},
{
"cell_type": "markdown",
- "id": "7f2e922c",
+ "id": "a5ac4041",
"metadata": {
"editable": true
},
@@ -4633,8 +4685,8 @@
},
{
"cell_type": "code",
- "execution_count": 30,
- "id": "f5057ce4",
+ "execution_count": 29,
+ "id": "f6908e7f",
"metadata": {
"collapsed": false,
"editable": true
@@ -4688,7 +4740,7 @@
},
{
"cell_type": "markdown",
- "id": "44f24b59",
+ "id": "817f52dd",
"metadata": {
"editable": true
},
@@ -4705,7 +4757,7 @@
},
{
"cell_type": "markdown",
- "id": "9e485a48",
+ "id": "5c4d56c4",
"metadata": {
"editable": true
},
@@ -4717,7 +4769,7 @@
},
{
"cell_type": "markdown",
- "id": "08c33b9a",
+ "id": "97116142",
"metadata": {
"editable": true
},
@@ -4729,7 +4781,7 @@
},
{
"cell_type": "markdown",
- "id": "efea267e",
+ "id": "166236b3",
"metadata": {
"editable": true
},
@@ -4739,7 +4791,7 @@
},
{
"cell_type": "markdown",
- "id": "f57a6387",
+ "id": "e0caab2a",
"metadata": {
"editable": true
},
@@ -4756,7 +4808,7 @@
},
{
"cell_type": "markdown",
- "id": "09c3db2a",
+ "id": "fb7aa817",
"metadata": {
"editable": true
},
@@ -4766,7 +4818,7 @@
},
{
"cell_type": "markdown",
- "id": "711e451f",
+ "id": "32f6f52c",
"metadata": {
"editable": true
},
@@ -4781,7 +4833,7 @@
},
{
"cell_type": "markdown",
- "id": "38589835",
+ "id": "87975a84",
"metadata": {
"editable": true
},
@@ -4791,7 +4843,7 @@
},
{
"cell_type": "markdown",
- "id": "3a8e7b82",
+ "id": "e9c84304",
"metadata": {
"editable": true
},
@@ -4805,7 +4857,7 @@
},
{
"cell_type": "markdown",
- "id": "4f757a1c",
+ "id": "5e78394b",
"metadata": {
"editable": true
},
@@ -4817,7 +4869,7 @@
},
{
"cell_type": "markdown",
- "id": "066f04df",
+ "id": "ca40158a",
"metadata": {
"editable": true
},
@@ -4829,7 +4881,7 @@
},
{
"cell_type": "markdown",
- "id": "a22e87f9",
+ "id": "ccf5937c",
"metadata": {
"editable": true
},
@@ -4841,7 +4893,7 @@
},
{
"cell_type": "markdown",
- "id": "7bc40f35",
+ "id": "d7c41ee0",
"metadata": {
"editable": true
},
@@ -4851,7 +4903,7 @@
},
{
"cell_type": "markdown",
- "id": "6c483e27",
+ "id": "f1bd2ee0",
"metadata": {
"editable": true
},
@@ -4863,7 +4915,7 @@
},
{
"cell_type": "markdown",
- "id": "3a9be674",
+ "id": "b3d8b144",
"metadata": {
"editable": true
},
@@ -4873,7 +4925,7 @@
},
{
"cell_type": "markdown",
- "id": "10a80c63",
+ "id": "d8805b83",
"metadata": {
"editable": true
},
@@ -4890,7 +4942,7 @@
},
{
"cell_type": "markdown",
- "id": "768268fc",
+ "id": "06333d2c",
"metadata": {
"editable": true
},
@@ -4900,7 +4952,7 @@
},
{
"cell_type": "markdown",
- "id": "d8a28553",
+ "id": "b8e2990b",
"metadata": {
"editable": true
},
@@ -4912,7 +4964,7 @@
},
{
"cell_type": "markdown",
- "id": "051efbdb",
+ "id": "a0e4c642",
"metadata": {
"editable": true
},
@@ -4922,7 +4974,7 @@
},
{
"cell_type": "markdown",
- "id": "71c4d54c",
+ "id": "0ab4ad40",
"metadata": {
"editable": true
},
@@ -4934,7 +4986,7 @@
},
{
"cell_type": "markdown",
- "id": "21b2801f",
+ "id": "0d6677ca",
"metadata": {
"editable": true
},
@@ -4948,7 +5000,7 @@
},
{
"cell_type": "markdown",
- "id": "d9cffb92",
+ "id": "f7f5ef7e",
"metadata": {
"editable": true
},
@@ -4960,7 +5012,7 @@
},
{
"cell_type": "markdown",
- "id": "2891c07f",
+ "id": "b37a2bff",
"metadata": {
"editable": true
},
@@ -4982,7 +5034,7 @@
},
{
"cell_type": "markdown",
- "id": "828e0caa",
+ "id": "d8eacec8",
"metadata": {
"editable": true
},
@@ -4994,7 +5046,7 @@
},
{
"cell_type": "markdown",
- "id": "1e5233ac",
+ "id": "78d1afd1",
"metadata": {
"editable": true
},
@@ -5009,7 +5061,7 @@
},
{
"cell_type": "markdown",
- "id": "d70833ea",
+ "id": "b68ce8d8",
"metadata": {
"editable": true
},
@@ -5021,7 +5073,7 @@
},
{
"cell_type": "markdown",
- "id": "0cc382c9",
+ "id": "6067f514",
"metadata": {
"editable": true
},
@@ -5033,7 +5085,7 @@
},
{
"cell_type": "markdown",
- "id": "8b4e4c8b",
+ "id": "bb9b04b9",
"metadata": {
"editable": true
},
@@ -5043,7 +5095,7 @@
},
{
"cell_type": "markdown",
- "id": "37e0461d",
+ "id": "06c22319",
"metadata": {
"editable": true
},
@@ -5055,7 +5107,7 @@
},
{
"cell_type": "markdown",
- "id": "86425996",
+ "id": "c752319b",
"metadata": {
"editable": true
},
@@ -5065,7 +5117,7 @@
},
{
"cell_type": "markdown",
- "id": "73cfee47",
+ "id": "b150afd7",
"metadata": {
"editable": true
},
@@ -5077,7 +5129,7 @@
},
{
"cell_type": "markdown",
- "id": "23c7f0fe",
+ "id": "49b73489",
"metadata": {
"editable": true
},
@@ -5087,7 +5139,7 @@
},
{
"cell_type": "markdown",
- "id": "b85ca513",
+ "id": "8a0bfb75",
"metadata": {
"editable": true
},
@@ -5099,7 +5151,7 @@
},
{
"cell_type": "markdown",
- "id": "a087e802",
+ "id": "916133d6",
"metadata": {
"editable": true
},
@@ -5116,7 +5168,7 @@
},
{
"cell_type": "markdown",
- "id": "69a00905",
+ "id": "ca1af1e6",
"metadata": {
"editable": true
},
@@ -5129,7 +5181,7 @@
},
{
"cell_type": "markdown",
- "id": "797396b4",
+ "id": "0f51835e",
"metadata": {
"editable": true
},
@@ -5141,7 +5193,7 @@
},
{
"cell_type": "markdown",
- "id": "0066c61c",
+ "id": "7c8d7801",
"metadata": {
"editable": true
},
@@ -5151,7 +5203,7 @@
},
{
"cell_type": "markdown",
- "id": "7811843e",
+ "id": "6474eee8",
"metadata": {
"editable": true
},
@@ -5164,7 +5216,7 @@
},
{
"cell_type": "markdown",
- "id": "d56c9678",
+ "id": "b320c6a0",
"metadata": {
"editable": true
},
@@ -5174,7 +5226,7 @@
},
{
"cell_type": "markdown",
- "id": "d9a0d4bc",
+ "id": "c8c98cd9",
"metadata": {
"editable": true
},
@@ -5186,7 +5238,7 @@
},
{
"cell_type": "markdown",
- "id": "5d3a50c0",
+ "id": "45a8d145",
"metadata": {
"editable": true
},
@@ -5199,7 +5251,7 @@
},
{
"cell_type": "markdown",
- "id": "73d0d7d6",
+ "id": "36b24b03",
"metadata": {
"editable": true
},
@@ -5212,7 +5264,7 @@
},
{
"cell_type": "markdown",
- "id": "8020543a",
+ "id": "ca68239f",
"metadata": {
"editable": true
},
@@ -5224,7 +5276,7 @@
},
{
"cell_type": "markdown",
- "id": "928f95e5",
+ "id": "8b1612c5",
"metadata": {
"editable": true
},
@@ -5236,7 +5288,7 @@
},
{
"cell_type": "markdown",
- "id": "628cde38",
+ "id": "ff43b2cb",
"metadata": {
"editable": true
},
@@ -5246,7 +5298,7 @@
},
{
"cell_type": "markdown",
- "id": "6ec01d17",
+ "id": "c002ab21",
"metadata": {
"editable": true
},
@@ -5259,7 +5311,7 @@
},
{
"cell_type": "markdown",
- "id": "b2cbeb30",
+ "id": "fd0f5373",
"metadata": {
"editable": true
},
@@ -5271,7 +5323,7 @@
},
{
"cell_type": "markdown",
- "id": "0e072a14",
+ "id": "b89da53a",
"metadata": {
"editable": true
},
@@ -5283,7 +5335,7 @@
},
{
"cell_type": "markdown",
- "id": "f2bced99",
+ "id": "897cd222",
"metadata": {
"editable": true
},
@@ -5295,7 +5347,7 @@
},
{
"cell_type": "markdown",
- "id": "196f0b91",
+ "id": "ba95499c",
"metadata": {
"editable": true
},
@@ -5307,7 +5359,7 @@
},
{
"cell_type": "markdown",
- "id": "41b33e36",
+ "id": "1e464e23",
"metadata": {
"editable": true
},
@@ -5321,7 +5373,7 @@
},
{
"cell_type": "markdown",
- "id": "5cfb0632",
+ "id": "15305669",
"metadata": {
"editable": true
},
@@ -5333,7 +5385,7 @@
},
{
"cell_type": "markdown",
- "id": "3326a3f6",
+ "id": "1d575b03",
"metadata": {
"editable": true
},
@@ -5343,7 +5395,7 @@
},
{
"cell_type": "markdown",
- "id": "eccbd23e",
+ "id": "3fd51087",
"metadata": {
"editable": true
},
@@ -5355,7 +5407,7 @@
},
{
"cell_type": "markdown",
- "id": "74e5ff1b",
+ "id": "9413f993",
"metadata": {
"editable": true
},
@@ -5367,7 +5419,7 @@
},
{
"cell_type": "markdown",
- "id": "e958aa11",
+ "id": "a041156d",
"metadata": {
"editable": true
},
@@ -5379,7 +5431,7 @@
},
{
"cell_type": "markdown",
- "id": "6667494b",
+ "id": "d3e91cb3",
"metadata": {
"editable": true
},
@@ -5391,7 +5443,7 @@
},
{
"cell_type": "markdown",
- "id": "7fb73f59",
+ "id": "5671db98",
"metadata": {
"editable": true
},
@@ -5403,7 +5455,7 @@
},
{
"cell_type": "markdown",
- "id": "e6d40aa6",
+ "id": "c8043b14",
"metadata": {
"editable": true
},
@@ -5422,7 +5474,7 @@
},
{
"cell_type": "markdown",
- "id": "fc098d90",
+ "id": "5ec9cd91",
"metadata": {
"editable": true
},
@@ -5434,7 +5486,7 @@
},
{
"cell_type": "markdown",
- "id": "ffef2181",
+ "id": "189da76e",
"metadata": {
"editable": true
},
@@ -5444,7 +5496,7 @@
},
{
"cell_type": "markdown",
- "id": "f1696dc4",
+ "id": "ca7b749b",
"metadata": {
"editable": true
},
@@ -5456,7 +5508,7 @@
},
{
"cell_type": "markdown",
- "id": "f491ccde",
+ "id": "1c8c3e1e",
"metadata": {
"editable": true
},
@@ -5466,7 +5518,7 @@
},
{
"cell_type": "markdown",
- "id": "e0617e34",
+ "id": "ae844a17",
"metadata": {
"editable": true
},
@@ -5478,7 +5530,7 @@
},
{
"cell_type": "markdown",
- "id": "edbddbd6",
+ "id": "63e19830",
"metadata": {
"editable": true
},
@@ -5490,7 +5542,7 @@
},
{
"cell_type": "markdown",
- "id": "bbc87811",
+ "id": "499d302e",
"metadata": {
"editable": true
},
@@ -5506,7 +5558,7 @@
},
{
"cell_type": "markdown",
- "id": "d6e428e9",
+ "id": "36443fc6",
"metadata": {
"editable": true
},
@@ -5518,7 +5570,7 @@
},
{
"cell_type": "markdown",
- "id": "316a2617",
+ "id": "ab2295e1",
"metadata": {
"editable": true
},
@@ -5530,7 +5582,7 @@
},
{
"cell_type": "markdown",
- "id": "fddef515",
+ "id": "1a1cc0a7",
"metadata": {
"editable": true
},
@@ -5540,7 +5592,7 @@
},
{
"cell_type": "markdown",
- "id": "98420bf9",
+ "id": "398f7a40",
"metadata": {
"editable": true
},
@@ -5552,7 +5604,7 @@
},
{
"cell_type": "markdown",
- "id": "debdbf1f",
+ "id": "aaf84521",
"metadata": {
"editable": true
},
@@ -5562,7 +5614,7 @@
},
{
"cell_type": "markdown",
- "id": "8ef37d90",
+ "id": "5ce1ea1b",
"metadata": {
"editable": true
},
@@ -5574,7 +5626,7 @@
},
{
"cell_type": "markdown",
- "id": "0c15307d",
+ "id": "9306b2d0",
"metadata": {
"editable": true
},
@@ -5591,7 +5643,7 @@
},
{
"cell_type": "markdown",
- "id": "817c06bc",
+ "id": "17988afb",
"metadata": {
"editable": true
},
@@ -5603,7 +5655,7 @@
},
{
"cell_type": "markdown",
- "id": "a10e5c81",
+ "id": "3c67e79f",
"metadata": {
"editable": true
},
@@ -5615,7 +5667,7 @@
},
{
"cell_type": "markdown",
- "id": "516c862b",
+ "id": "25fe5f5c",
"metadata": {
"editable": true
},
@@ -5625,7 +5677,7 @@
},
{
"cell_type": "markdown",
- "id": "e2bab35f",
+ "id": "8610f237",
"metadata": {
"editable": true
},
@@ -5637,7 +5689,7 @@
},
{
"cell_type": "markdown",
- "id": "d8c16c3f",
+ "id": "f79ef3e0",
"metadata": {
"editable": true
},
@@ -5647,7 +5699,7 @@
},
{
"cell_type": "markdown",
- "id": "a3d7507d",
+ "id": "76d04b6a",
"metadata": {
"editable": true
},
@@ -5659,7 +5711,7 @@
},
{
"cell_type": "markdown",
- "id": "9a4ffcad",
+ "id": "e7af943c",
"metadata": {
"editable": true
},
@@ -5669,7 +5721,7 @@
},
{
"cell_type": "markdown",
- "id": "9385929e",
+ "id": "b92838b4",
"metadata": {
"editable": true
},
@@ -5681,7 +5733,7 @@
},
{
"cell_type": "markdown",
- "id": "72800402",
+ "id": "aac1fb1a",
"metadata": {
"editable": true
},
@@ -5691,7 +5743,7 @@
},
{
"cell_type": "markdown",
- "id": "dd626d5c",
+ "id": "92a2d46b",
"metadata": {
"editable": true
},
@@ -5703,7 +5755,7 @@
},
{
"cell_type": "markdown",
- "id": "40c04e33",
+ "id": "845870e3",
"metadata": {
"editable": true
},
@@ -5772,7 +5824,7 @@
},
{
"cell_type": "markdown",
- "id": "5e523954",
+ "id": "b591c6c5",
"metadata": {
"editable": true
},
@@ -5785,8 +5837,8 @@
},
{
"cell_type": "code",
- "execution_count": 31,
- "id": "69b55a1d",
+ "execution_count": 30,
+ "id": "f9b44c0f",
"metadata": {
"collapsed": false,
"editable": true
@@ -5799,7 +5851,7 @@
},
{
"cell_type": "markdown",
- "id": "f99ac231",
+ "id": "1b42b35a",
"metadata": {
"editable": true
},
@@ -5813,7 +5865,7 @@
},
{
"cell_type": "markdown",
- "id": "7c49fd2c",
+ "id": "faa55581",
"metadata": {
"editable": true
},
@@ -5826,7 +5878,7 @@
},
{
"cell_type": "markdown",
- "id": "ca45098a",
+ "id": "1394bc70",
"metadata": {
"editable": true
},
@@ -5837,7 +5889,7 @@
},
{
"cell_type": "markdown",
- "id": "23fcbb80",
+ "id": "93f60f80",
"metadata": {
"editable": true
},
@@ -5849,7 +5901,7 @@
},
{
"cell_type": "markdown",
- "id": "53aa2a60",
+ "id": "67a7e008",
"metadata": {
"editable": true
},
@@ -5859,7 +5911,7 @@
},
{
"cell_type": "markdown",
- "id": "decd4c10",
+ "id": "7fec62b9",
"metadata": {
"editable": true
},
@@ -5871,7 +5923,7 @@
},
{
"cell_type": "markdown",
- "id": "8bb37d97",
+ "id": "85069c06",
"metadata": {
"editable": true
},
@@ -5886,8 +5938,8 @@
},
{
"cell_type": "code",
- "execution_count": 32,
- "id": "ef3bd322",
+ "execution_count": 31,
+ "id": "ee0c256b",
"metadata": {
"collapsed": false,
"editable": true
@@ -5938,7 +5990,7 @@
},
{
"cell_type": "markdown",
- "id": "95259a2d",
+ "id": "e6619d74",
"metadata": {
"editable": true
},
@@ -5948,7 +6000,7 @@
},
{
"cell_type": "markdown",
- "id": "bcb2ed28",
+ "id": "497a8699",
"metadata": {
"editable": true
},
@@ -5993,8 +6045,8 @@
},
{
"cell_type": "code",
- "execution_count": 33,
- "id": "3ccfb2eb",
+ "execution_count": 32,
+ "id": "23eee3ba",
"metadata": {
"collapsed": false,
"editable": true
@@ -6007,7 +6059,7 @@
},
{
"cell_type": "markdown",
- "id": "ba70ba15",
+ "id": "b6fff09f",
"metadata": {
"editable": true
},
@@ -6017,8 +6069,8 @@
},
{
"cell_type": "code",
- "execution_count": 34,
- "id": "cd31a03b",
+ "execution_count": 33,
+ "id": "82cc69df",
"metadata": {
"collapsed": false,
"editable": true
@@ -6033,7 +6085,7 @@
},
{
"cell_type": "markdown",
- "id": "33c4444d",
+ "id": "a2ec0781",
"metadata": {
"editable": true
},
@@ -6050,8 +6102,8 @@
},
{
"cell_type": "code",
- "execution_count": 35,
- "id": "87d0904c",
+ "execution_count": 34,
+ "id": "41a345b6",
"metadata": {
"collapsed": false,
"editable": true
@@ -6068,7 +6120,7 @@
},
{
"cell_type": "markdown",
- "id": "028c49e7",
+ "id": "722bf3b7",
"metadata": {
"editable": true
},
@@ -6078,7 +6130,7 @@
},
{
"cell_type": "markdown",
- "id": "da7f752f",
+ "id": "d0b4246c",
"metadata": {
"editable": true
},
@@ -6089,7 +6141,7 @@
},
{
"cell_type": "markdown",
- "id": "2450f3aa",
+ "id": "af973883",
"metadata": {
"editable": true
},
@@ -6100,7 +6152,7 @@
},
{
"cell_type": "markdown",
- "id": "4e794dc7",
+ "id": "a1bd618f",
"metadata": {
"editable": true
},
@@ -6111,7 +6163,7 @@
},
{
"cell_type": "markdown",
- "id": "9c01a640",
+ "id": "6e8876e1",
"metadata": {
"editable": true
},
@@ -6133,8 +6185,8 @@
},
{
"cell_type": "code",
- "execution_count": 36,
- "id": "12fcf2c5",
+ "execution_count": 35,
+ "id": "c03964b8",
"metadata": {
"collapsed": false,
"editable": true
@@ -6147,7 +6199,7 @@
},
{
"cell_type": "markdown",
- "id": "5e24a8d5",
+ "id": "e4f6c095",
"metadata": {
"editable": true
},
@@ -6161,8 +6213,8 @@
},
{
"cell_type": "code",
- "execution_count": 37,
- "id": "2ec984bf",
+ "execution_count": 36,
+ "id": "50973f2d",
"metadata": {
"collapsed": false,
"editable": true
@@ -6242,7 +6294,7 @@
},
{
"cell_type": "markdown",
- "id": "b45dc03f",
+ "id": "632de72b",
"metadata": {
"editable": true
},
@@ -6257,7 +6309,7 @@
},
{
"cell_type": "markdown",
- "id": "423c5f28",
+ "id": "9ff88979",
"metadata": {
"editable": true
},
@@ -6270,7 +6322,7 @@
},
{
"cell_type": "markdown",
- "id": "754bf7b3",
+ "id": "0dac21b3",
"metadata": {
"editable": true
},
@@ -6281,7 +6333,7 @@
},
{
"cell_type": "markdown",
- "id": "db9d2e54",
+ "id": "fdca6da4",
"metadata": {
"editable": true
},
@@ -6293,7 +6345,7 @@
},
{
"cell_type": "markdown",
- "id": "60d95367",
+ "id": "ea1bf623",
"metadata": {
"editable": true
},
@@ -6303,7 +6355,7 @@
},
{
"cell_type": "markdown",
- "id": "6214cafb",
+ "id": "30af78a4",
"metadata": {
"editable": true
},
@@ -6315,7 +6367,7 @@
},
{
"cell_type": "markdown",
- "id": "78316757",
+ "id": "4da25080",
"metadata": {
"editable": true
},
@@ -6325,7 +6377,7 @@
},
{
"cell_type": "markdown",
- "id": "62368bb8",
+ "id": "f4782d60",
"metadata": {
"editable": true
},
@@ -6347,7 +6399,7 @@
},
{
"cell_type": "markdown",
- "id": "275badb6",
+ "id": "0b36e202",
"metadata": {
"editable": true
},
@@ -6359,7 +6411,7 @@
},
{
"cell_type": "markdown",
- "id": "4c1fbfe1",
+ "id": "bed13c6e",
"metadata": {
"editable": true
},
@@ -6369,7 +6421,7 @@
},
{
"cell_type": "markdown",
- "id": "b4006a85",
+ "id": "2b41c2f1",
"metadata": {
"editable": true
},
@@ -6381,7 +6433,7 @@
},
{
"cell_type": "markdown",
- "id": "c18344aa",
+ "id": "e455a8b3",
"metadata": {
"editable": true
},
@@ -6391,7 +6443,7 @@
},
{
"cell_type": "markdown",
- "id": "53f3bf6c",
+ "id": "02e54c79",
"metadata": {
"editable": true
},
@@ -6403,7 +6455,7 @@
},
{
"cell_type": "markdown",
- "id": "042559ff",
+ "id": "46754116",
"metadata": {
"editable": true
},
@@ -6416,7 +6468,7 @@
},
{
"cell_type": "markdown",
- "id": "c0c02fc5",
+ "id": "c5a2678c",
"metadata": {
"editable": true
},
@@ -6428,7 +6480,7 @@
},
{
"cell_type": "markdown",
- "id": "e6d241fb",
+ "id": "02687556",
"metadata": {
"editable": true
},
@@ -6438,7 +6490,7 @@
},
{
"cell_type": "markdown",
- "id": "d04eeebd",
+ "id": "c5506079",
"metadata": {
"editable": true
},
@@ -6450,7 +6502,7 @@
},
{
"cell_type": "markdown",
- "id": "80a04131",
+ "id": "672ced20",
"metadata": {
"editable": true
},
@@ -6460,7 +6512,7 @@
},
{
"cell_type": "markdown",
- "id": "9fe8b618",
+ "id": "10f3742a",
"metadata": {
"editable": true
},
@@ -6472,7 +6524,7 @@
},
{
"cell_type": "markdown",
- "id": "a96720f8",
+ "id": "2674dbe4",
"metadata": {
"editable": true
},
@@ -6482,7 +6534,7 @@
},
{
"cell_type": "markdown",
- "id": "cec8d943",
+ "id": "8cbb65cd",
"metadata": {
"editable": true
},
diff --git a/doc/src/week35/week35.do.txt b/doc/src/week35/week35.do.txt
index 6e962911f..61ff99179 100644
--- a/doc/src/week35/week35.do.txt
+++ b/doc/src/week35/week35.do.txt
@@ -56,11 +56,11 @@ Similarly, "Mehta et al's article":"https://arxiv.org/abs/1803.08823" is also re
!bblock
Regression modeling deals with the description of the sampling distribution of a given random variable $y$ and how it varies as function of another variable or a set of such variables $\bm{x} =[x_0, x_1,\dots, x_{n-1}]^T$.
-The first variable is called the _dependent_, the _outcome_ or the _response_ variable while the set of variables $\bm{x}$ is called the independent variable, or the predictor variable or the explanatory variable.
+The first variable is called the _dependent_, the _outcome_ or the _response_ variable while the set of variables $\bm{x}$ is called the independent variable, or the predictor variable or the explanatory variable or simply the input.
A regression model aims at finding a likelihood function $p(\bm{y}\vert \bm{x})$, that is the conditional distribution for $\bm{y}$ with a given $\bm{x}$. The estimation of $p(\bm{y}\vert \bm{x})$ is made using a data set with
* $n$ cases $i = 0, 1, 2, \dots, n-1$
-* Response (target, dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \dots, n-1$
+* Response, output, target, dependent or outcome variable $y_i$ with $i = 0, 1, 2, \dots, n-1$
* $p$ so-called explanatory (independent or predictor) variables $\bm{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip-1}]$ with $i = 0, 1, 2, \dots, n-1$ and explanatory variables running from $0$ to $p-1$. See below for more explicit examples.
The goal of the regression analysis is to extract/exploit relationship between $\bm{y}$ and $\bm{x}$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.
!eblock
@@ -70,8 +70,8 @@ A regression model aims at finding a likelihood function $p(\bm{y}\vert \bm{x})$
!bblock
-Consider an experiment in which $p$ characteristics of $n$ samples are
-measured. The data from this experiment, for various explanatory variables $p$ are normally represented by a matrix
+Consider an experiment in which $p$ characteristics (or features) of $n$ samples are
+measured. The data from this experiment, for various explanatory/feature variables $p$ are normally represented by a matrix
$\mathbf{X}$.
The matrix $\mathbf{X}$ is called the *design
@@ -96,16 +96,14 @@ Linear regression gives us a set of analytical equations for the parameters $\be
===== Examples =====
!bblock
In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\bm{y}$,
-consider the model we discussed for describing nuclear binding energies.
-
-There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model.
-Assuming
+we condiser a simple polynomial fit.
+We assume our data can represented by a fourth-order polynomial. For the $i$th component we have
!bt
\[
-BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1},
+\tilde{y}_i = \beta_0+\beta_1x_i+\beta_2x_i^2+\beta_3x_i^3+\beta_4x_i^4.
\]
!et
-we have five predictors, that is the intercept, the $A$ dependent term, the $A^{2/3}$ term and the $A^{-1/3}$ and $A^{-1}$ terms.
+we have five predictors, that is the intercept $\beta_0$and the other terms $\beta_i$.
This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a
$p\times n$ matrix $\bm{X}$.
@@ -136,7 +134,8 @@ where $\epsilon_i$ is the error in our approximation.
!split
===== Rewriting the fitting procedure as a linear algebra problem =====
-!bblock
+
+
For every set of values $y_i,x_i$ we have thus the corresponding set of equations
!bt
\begin{align*}
@@ -147,7 +146,7 @@ y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\
y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\
\end{align*}
!et
-!eblock
+
!split
@@ -272,89 +271,6 @@ our matrix as $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors refering
!split
===== Examples relevant for the exercises =====
-In our "introductory notes":"https://compphysics.github.io/MachineLearning/doc/pub/How2ReadData/html/How2ReadData.html" we looked at the so-called "liquid drop model":"https://en.wikipedia.org/wiki/Semi-empirical_mass_formula". Let us remind ourselves about what we did by looking at the code.
-
-We restate the parts of the code we are most interested in.
-!bc pycod
-# Common imports
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from IPython.display import display
-import os
-
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
-
-if not os.path.exists(PROJECT_ROOT_DIR):
- os.mkdir(PROJECT_ROOT_DIR)
-
-if not os.path.exists(FIGURE_ID):
- os.makedirs(FIGURE_ID)
-
-if not os.path.exists(DATA_ID):
- os.makedirs(DATA_ID)
-
-def image_path(fig_id):
- return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
- return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
-
-infile = open(data_path("MassEval2016.dat"),'r')
-
-
-# Read the experimental data with Pandas
-Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
- names=('N', 'Z', 'A', 'Element', 'Ebinding'),
- widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),
- header=39,
- index_col=False)
-
-# Extrapolated values are indicated by '#' in place of the decimal place, so
-# the Ebinding column won't be numeric. Coerce to float and drop these entries.
-Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')
-Masses = Masses.dropna()
-# Convert from keV to MeV.
-Masses['Ebinding'] /= 1000
-
-# Group the DataFrame by nucleon number, A.
-Masses = Masses.groupby('A')
-# Find the rows of the grouped DataFrame with the maximum binding energy.
-Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
-A = Masses['A']
-Z = Masses['Z']
-N = Masses['N']
-Element = Masses['Element']
-Energies = Masses['Ebinding']
-
-# Now we set up the design matrix X
-X = np.zeros((len(A),5))
-X[:,0] = 1
-X[:,1] = A
-X[:,2] = A**(2.0/3.0)
-X[:,3] = A**(-1.0/3.0)
-X[:,4] = A**(-1.0)
-# Then nice printout using pandas
-DesignMatrix = pd.DataFrame(X)
-DesignMatrix.index = A
-DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
-display(DesignMatrix)
-!ec
-
-With $\bm{\beta}\in {\mathbb{R}}^{p\times 1}$, it means that we will hereafter write our equations for the approximation as
-!bt
-\[
-\bm{\tilde{y}}= \bm{X}\bm{\beta},
-\]
-!et
-throughout these lectures.
-
!split
===== Optimizing our parameters, more details =====
@@ -597,7 +513,7 @@ which means that (using our previous example) we have
Since $\alpha$ is a scalar we have $\alpha =\alpha^T=\bm{x}^T\bm{A}^T\bm{y}$. Defining now $\bm{z}=\bm{x}^T\bm{A}^T$ we find that
!bt
\[
-\frac{\partial \alpha}{\partial \bm{y}} = \bm{z}^T=\bm{x}^T\bm{A}^T..
+\frac{\partial \alpha}{\partial \bm{y}} = \bm{z}^T=\bm{x}^T\bm{A}^T.
\]
!et
@@ -679,14 +595,71 @@ for $\forall k =0,1,2,\dots,n-1$. We can rewrite the partial derivative in a mor
and if $\bm{y}=\bm{x}$ we have
!bt
\[
-\frac{\partial \alpha}{\partial \bm{z}} = \bm{x}^T\frac{\partial \bm{x}}{\partial \bm{z}}.
+\frac{\partial \alpha}{\partial \bm{z}} = 2\bm{x}^T\frac{\partial \bm{x}}{\partial \bm{z}}.
+\]
+!et
+
+!split
+===== The mean squared error and its derivative =====
+We defined earlier a possible cost function using the mean squared error
+!bt
+\[
+C(\bm{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\bm{y}-\bm{\tilde{y}}\right)^T\left(\bm{y}-\bm{\tilde{y}}\right)\right\},
+\]
+!et
+or using the design/feature matrix $\bm{X}$ we have the more compact matrix-vector
+!bt
+\[
+C(\bm{\beta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}.
+\]
+!et
+
+We note that the design matrix $\bm{X}$ does not depend on the unknown parameters defined by the vector $\bm{\beta}$.
+We are now interested in minimizing the cost function with respect to the unknown parameters $\bm{\beta}$.
+
+The mean squared error is scalar and if we use the results from the last example, we define a new vector
+!bt
+\[
+\bm{w}=\bm{y}-\bm{X}\bm{\beta},
+\]
+!et
+which depends on $\bm{\beta}$. We rewrite the cost function as
+!bt
+\[
+C(\bm{\beta})=\frac{1}{n}\bm{w}^T\bm{w},
+\]
+!et
+with partial derivative
+!bt
+\[
+\frac{\partial C(\bm{\beta})}{\partial \bm{\beta}}=\frac{2}{n}\bm{w}^T\frac{\partial \bm{w}}{\partial \bm{\beta}},
+\]
+!et
+and using that
+!bt
+\[
+\frac{\partial \bm{w}}{\partial \bm{\beta}}=-\bm{X},
+\]
+!et
+where we ued the results from example two. Inserting the last expression we obtain
+!bt
+\[
+\frac{\partial C(\bm{\beta})}{\partial \bm{\beta}}=-\frac{2}{n}\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\bm{X},
+\]
+!et
+or as
+!bt
+\[
+\frac{\partial C(\bm{\beta})}{\partial \bm{\beta}^T}=-\frac{2}{n}\bm{X}^T\left(\bm{y}-\bm{X}\bm{\beta}\right).
\]
!et
+!split
+===== Other useful relations =====
-
+We list here some other useful relations we may encounter (recall that vectors are defined by boldfaced low-key letters)
!bt
\[
\frac{\partial (\bm{b}^T\bm{a})}{\partial \bm{a}} = \bm{b},
@@ -694,11 +667,6 @@ and if $\bm{y}=\bm{x}$ we have
!et
!bt
\[
-\frac{\partial (\bm{a}^T\bm{A}\bm{a})}{\partial \bm{a}} = (\bm{A}+\bm{A}^T)\bm{a},
-\]
-!et
-!bt
-\[
\frac{\partial tr(\bm{B}\bm{A})}{\partial \bm{A}} = \bm{B}^T,
\]
!et
@@ -708,8 +676,6 @@ and if $\bm{y}=\bm{x}$ we have
\]
!et
-See the jupyter-book (complete lecture notes) for the derivations of these relations.
-
!split
@@ -719,7 +685,7 @@ A very important matrix we will meet again and again in Machine
Learning is the Hessian. It is given by the second derivative of the
cost function with respect to the parameter $\beta$. Using the above
expression for derivatives of vectors and matrices, we find that the
-second derivative of the cost function is,
+second derivative of the mean squared error as cost function is,
!bt
\[