diff --git a/doc/BookChapters/chapter1.dlog b/doc/BookChapters/chapter1.dlog
index 7a39c150c..0e51fe222 100644
--- a/doc/BookChapters/chapter1.dlog
+++ b/doc/BookChapters/chapter1.dlog
@@ -57,3 +57,13 @@ Translating doconce text in chapter1.do.txt to ipynb
*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments.
output in chapter1.ipynb
+Translating doconce text in chapter1.do.txt to ipynb
+*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax)
+found info about 5 exercises
+
+*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments.
+
+*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments.
+
+*** warning: latex envir \begin{bmatrix} does not work well in Markdown. Stick to \[ ... \], equation, equation*, align, or align* environments in math environments.
+output in chapter1.ipynb
diff --git a/doc/BookChapters/chapter1.do.txt b/doc/BookChapters/chapter1.do.txt
index 1a13c52b6..7995dcd7e 100644
--- a/doc/BookChapters/chapter1.do.txt
+++ b/doc/BookChapters/chapter1.do.txt
@@ -1292,25 +1292,23 @@ matrices as upper case boldfaced letters.
!bt
\[
-\frac{\partial\bm{b}^T\bm{a}}{\partial\bm{a}}=\bm{b},
+\frac{\partial (\bm{b}^T\bm{a})}{\partial \bm{a}} = \bm{b},
\]
!et
+and
!bt
\[
-\frac{\partial\bm{a}^T\bm{A}\bm{a}}{\partial\bm{a}}=(\bm{A}+\bm{A}^T)\bm{a},
+\frac{\partial (\bm{a}^T\bm{A}\bm{a})}{\partial \bm{a}} = \bm{a}^T(\bm{A}+\bm{A}^T),
\]
!et
+and
!bt
\[
-\frac{\partial tr(\bm{B}\bm{A})}{\partial\bm{A}}=\bm{B}^T,
+\frac{\partial \left(\bm{x}-\bm{A}\bm{s}\right)^T\left(\bm{x}-\bm{A}\bm{s}\right)}{\partial \bm{s}} = -2\left(\bm{x}-\bm{A}\bm{s}\right)^T\bm{A},
\]
!et
-!bt
-\[
-\frac{\partial\log{\vert\bm{A}\vert}}{\partial \bm{A}}=(\bm{A}^{-1})^T.
-\]
-!et
-
+These and other relations are discussed in the exercises following this chapter (see the end of the chapter).
+The latter equation is similar to the equation for the mean-squared error function we have been discussing.
We can then compute the second derivative of the cost function, which in our case is the second derivative
of the means squared error. This leads to
@@ -1319,7 +1317,7 @@ of the means squared error. This leads to
\frac{\partial^2 C(\bm{\beta})}{\partial \bm{\beta}^T\partial \bm{\beta}} =\frac{2}{n}\bm{X}^T\bm{X}.
\]
!et
-This quantity defines was what is called the Hessian matrix (the second derivative of a function we want to optimize).
+This quantity defines the so- called the Hessian matrix.
The Hessian matrix plays an important role and is defined for the mean squared error as
@@ -2187,7 +2185,8 @@ plt.show()
===== Exercises =====
-=== Exercise: Setting up various Python environments ===
+
+===== Exercise: Setting up various Python environments =====
The first exercise here is of a mere technical art. We want you to have
* git as a version control software and to establish a user account on a provider like GitHub. Other providers like GitLab etc are equally fine. You can also use the University of Oslo "GitHub facilities":"https://www.uio.no/tjenester/it/maskin/filer/versjonskontroll/github.html".
@@ -2250,7 +2249,7 @@ We recommend using _Anaconda_ if you are not too familiar with setting paths in
-=== Exercise: making your own data and exploring scikit-learn ===
+===== Exercise: making your own data and exploring scikit-learn =====
We will generate our own dataset for a function $y(x)$ where $x \in [0,1]$ and defined by random numbers computed with the uniform distribution. The function $y$ is a quadratic polynomial in $x$ with added stochastic noise according to the normal distribution $\cal {N}(0,1)$.
@@ -2261,7 +2260,7 @@ y = 2.0+5*x*x+0.1*np.random.randn(100,1)
!ec
o Write your own code (following the examples under the "regression notes":"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter1.html") for computing the parametrization of the data set fitting a second-order polynomial.
-o Use thereafter _scikit-learn_ (see again the examples in the regression slides) and compare with your own code.
+o Use thereafter _scikit-learn_ (see again the examples in the regression slides) and compare with your own code. When compairing with _scikit_learn_, make sure you set the option for the intercept to _FALSE_, see URL:"https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html". This feature will be explained in more detail during the lectures of week 35 and week 36. You can find more in URL:"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#more-on-rescaling-data".
o Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
!bt
\[ MSE(\bm{y},\bm{\tilde{y}}) = \frac{1}{n}
@@ -2284,10 +2283,55 @@ where we have defined the mean value of $\bm{y}$ as
You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions.
Discuss the meaning of these results. Try also to vary the coefficient in front of the added stochastic noise term and discuss the quality of the fits.
+!bsol
+The code here is an example of where we define our own design matrix and fit parameters $\beta$.
+!bc pycod
+import os
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.model_selection import train_test_split
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+x = np.random.rand(100)
+y = 2.0+5*x*x+0.1*np.random.randn(100)
+
+
+# The design matrix now as function of a given polynomial
+X = np.zeros((len(x),3))
+X[:,0] = 1.0
+X[:,1] = x
+X[:,2] = x**2
+# We split the data in test and training data
+X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
+# matrix inversion to find beta
+beta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train
+print(beta)
+# and then make the prediction
+ytilde = X_train @ beta
+print("Training R2")
+print(R2(y_train,ytilde))
+print("Training MSE")
+print(MSE(y_train,ytilde))
+ypredict = X_test @ beta
+print("Test R2")
+print(R2(y_test,ypredict))
+print("Test MSE")
+print(MSE(y_test,ypredict))
+!ec
+!esol
-=== Exercise: Normalizing our data ===
+===== Exercise: Normalizing our data =====
A much used approach before starting to train the data is to preprocess our
@@ -2328,7 +2372,7 @@ It also common to split the data in a _training_ set and a _testing_ set. A typi
for testing. This can be done as follows with our design matrix $\bm{X}$ and data $\bm{y}$ (remember to import _scikit-learn_)
!bc pycod
# split in training and test data
-# X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)
+X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)
!ec
Then we can use the standard scaler to scale our data as
!bc pycod
@@ -2358,28 +2402,308 @@ 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)
!ec
where $y$ is the function we want to fit with a given polynomial.
+!bsubex
+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.
+!esubex
+
+!bsubex
+Perform an ordinary least squares and compute the means squared error and the $R2$ factor for the training data and the test data, with and without scaling.
+!esubex
+
+!bsubex
+Add now a model which allows you to make polynomials up to degree $15$. Perform a standard OLS fitting of the training data and compute the MSE and $R2$ for the training and test data and plot both test and training data MSE and $R2$ as functions of the polynomial degree. Compare what you see with Figure 2.11 of Hastie et al. Comment your results. For which polynomial degree do you find an optimal MSE (smallest value)?
+
+!esubex
-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.
+!bsol
+We present here the solution for the last exercise. All elements here can be used to solve exercises a) and b) as well.
+Note that in this example we have used the polynomial fitting functions of _scikit-learn_.
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.linear_model import LinearRegression, Ridge, Lasso
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+
+
+np.random.seed(2018)
+n = 30
+maxdegree = 14
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+TestError = np.zeros(maxdegree)
+TrainError = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+
+for degree in range(maxdegree):
+ model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
+ clf = model.fit(x_train,y_train)
+ y_fit = clf.predict(x_train)
+ y_pred = clf.predict(x_test)
+ polydegree[degree] = degree
+ TestError[degree] = np.mean( np.mean((y_test - y_pred)**2) )
+ TrainError[degree] = np.mean( np.mean((y_train - y_fit)**2) )
+
+plt.plot(polydegree, TestError, label='Test Error')
+plt.plot(polydegree, TrainError, label='Train Error')
+plt.legend()
+plt.show()
+!ec
+!esol
-Perform an ordinary least squares and compute the means squared error
-and the $R2$ factor for the training data and the test data, with and
-without scaling.
+
+===== Exercise: Adding Ridge Regression =====
+
+
+This exercise is a continuation of exercise 2. We will use the same function to
+generate our data set, still staying with a simple function $y(x)$
+which we want to fit using linear regression, but now extending the
+analysis to include the Ridge regression method.
+
+We will thus again generate our own dataset for a function $y(x)$ where
+$x \in [0,1]$ and defined by random numbers computed with the uniform
+distribution. The function $y$ is a quadratic polynomial in $x$ with
+added stochastic noise according to the normal distribution $\cal{N}(0,1)$.
+
+The following simple Python instructions define our $x$ and $y$ values (with 100 data points).
+!bc pycod
+x = np.random.rand(100)
+y = 2.0+5*x*x+0.1*np.random.randn(100)
+!ec
+
+
+Write your own code for the Ridge method (see chapter 3.4 of Hastie *et al.*, equations (3.43) and (3.44)) and compute the parametrization for different values of $\lambda$. Compare and analyze your results with those from exercise 3. Study the dependence on $\lambda$ while also varying the strength of the noise in your expression for $y(x)$.
+
+
+Repeat the above but using the functionality of
+_Scikit-Learn_. Compare your code with the results from
+_Scikit-Learn_. Remember to run with the same random numbers for
+generating $x$ and $y$. Observe also that when you compare with _Scikit-Learn_, you need to pay attention to how the intercept is dealt with.
-Add now a model which allows you to make polynomials up to degree
-$15$. Perform a standard OLS fitting of the training data and compute
-the MSE and $R2$ for the training and test data and plot both test and
-training data MSE and $R2$ as functions of the polynomial
-degree. Compare what you see with Figure 2.11 of Hastie et al. Comment
-your results. For which polynomial degree do you find an optimal MSE
-(smallest value)?
-
+Finally, using _Scikit-Learn_ or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
+!bt
+\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
+\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
+\]
+!et
+and the $R^2$ score function.
+If $\tilde{\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as
+!bt
+\[
+R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
+\]
+!et
+where we have defined the mean value of $\hat{y}$ as
+!bt
+\[
+\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
+\]
+!et
+Discuss these quantities as functions of the variable $\lambda$ in Ridge regression.
+
+
+!bsol
+The code here allows you to perform your own Ridge calculation and
+perform calculations for various values of the regularization
+parameter $\lambda$. This program can easily be extended upon.
+
+!bc pycod
+import os
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.model_selection import train_test_split
+from sklearn.preprocessing import StandardScaler
+from sklearn import linear_model
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+
+# A seed just to ensure that the random numbers are the same for every run.
+# Useful for eventual debugging.
+np.random.seed(3155)
+
+x = np.random.rand(100)
+y = 2.0+5*x*x+0.1*np.random.randn(100)
+
+# number of features p (here degree of polynomial
+p = 3
+# The design matrix now as function of a given polynomial
+X = np.zeros((len(x),p))
+X[:,0] = 1.0
+X[:,1] = x
+X[:,2] = x*x
+# We split the data in test and training data
+X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
+
+# matrix inversion to find beta
+OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train
+print(OLSbeta)
+# and then make the prediction
+ytildeOLS = X_train @ OLSbeta
+print("Training R2 for OLS")
+print(R2(y_train,ytildeOLS))
+print("Training MSE for OLS")
+print(MSE(y_train,ytildeOLS))
+ypredictOLS = X_test @ OLSbeta
+print("Test R2 for OLS")
+print(R2(y_test,ypredictOLS))
+print("Test MSE OLS")
+print(MSE(y_test,ypredictOLS))
+
+
+# Repeat now for Ridge regression and various values of the regularization parameter
+I = np.eye(p,p)
+# Decide which values of lambda to use
+nlambdas = 20
+OwnMSEPredict = np.zeros(nlambdas)
+OwnMSETrain = np.zeros(nlambdas)
+MSERidgePredict = np.zeros(nlambdas)
+lambdas = np.logspace(-4, 1, nlambdas)
+for i in range(nlambdas):
+ lmb = lambdas[i]
+ OwnRidgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train
+ # and then make the prediction
+ OwnytildeRidge = X_train @ OwnRidgebeta
+ OwnypredictRidge = X_test @ OwnRidgebeta
+ OwnMSEPredict[i] = MSE(y_test,OwnypredictRidge)
+ OwnMSETrain[i] = MSE(y_train,OwnytildeRidge)
+ # Make the fit using Ridge from Sklearn
+ RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
+ RegRidge.fit(X_train,y_train)
+ # and then make the prediction
+ ypredictRidge = RegRidge.predict(X_test)
+ # Compute the MSE and print it
+ MSERidgePredict[i] = MSE(y_test,ypredictRidge)
+
+# Now plot the results
+plt.figure()
+plt.plot(np.log10(lambdas), OwnMSETrain, label = 'MSE Ridge train, Own code')
+plt.plot(np.log10(lambdas), OwnMSEPredict, 'r--', label = 'MSE Ridge Test, Own code')
+plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE Ridge Test, Sklearn code')
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
+!ec
+!esol
+
+
+===== Exercise: Analytical exercises =====
+
+In this exercise we derive the expressions for various derivatives of
+products of vectors and matrices. Such derivatives are central to the
+optimization of various cost functions. Although we will often use
+automatic differentiation in actual calculations, to be able to have
+analytical expressions is extremely helpful in case we have simpler
+derivatives as well as when we analyze various properties (like second
+derivatives) of the chosen cost functions. Vectors are always written
+as boldfaced lower case letters and matrices as upper case boldfaced
+letters.
+
+Show that
+!bt
+\[
+\frac{\partial (\bm{b}^T\bm{a})}{\partial \bm{a}} = \bm{b},
+\]
+!et
+and
+!bt
+\[
+\frac{\partial (\bm{a}^T\bm{A}\bm{a})}{\partial \bm{a}} = \bm{a}^T(\bm{A}+\bm{A}^T),
+\]
+!et
+and
+!bt
+\[
+\frac{\partial \left(\bm{x}-\bm{A}\bm{s}\right)^T\left(\bm{x}-\bm{A}\bm{s}\right)}{\partial \bm{s}} = -2\left(\bm{x}-\bm{A}\bm{s}\right)^T\bm{A},
+\]
+!et
+and finally find the second derivative of this function with respect to the vector $\bm{s}$.
+
+!bsol
+In these exercises it is always useful to write out with summation indices the various quantities.
+As an example, consider the function
+
+!bt
+\[
+f(\bm{x}) =\bm{A}\bm{x},
+\]
+!et
+which reads for a specific component $f_i$ (we define the matrix $\bm{A}$ to have dimension $n\times n$ and the vector $\bm{x}$ to have length $n$)
+
+!bt
+\[
+f_i =\sum_{j=0}^{n-1}a_{ij}x_j,
+\]
+!et
+which leads to
+!bt
+\[
+\frac{\partial f_i}{\partial x_j}= a_{ij},
+\]
+!et
+and written out in terms of the vector $\bm{x}$ we have
+!bt
+\[
+\frac{\partial f(\bm{x})}{\partial \bm{x}}= \bm{A}.
+\]
+!et
+
+For the first derivative
+!bt
+\[
+\frac{\partial (\bm{b}^T\bm{a})}{\partial \bm{a}} = \bm{b},
+\]
+!et
+we can write out the inner product as (assuming all elements are real)
+!bt
+\[
+\bm{b}^T\bm{a}=\sum_i b_ia_i,
+\]
+!et
+taking the derivative
+!bt
+\[
+\frac{\partial \left( \sum_i b_ia_i\right)}{\partial a_k}= b_k,
+\]
+!et
+leading to
+!bt
+\[
+\frac{\partial \bm{b}^T\bm{a}}{\partial \bm{a}}= \begin{bmatrix} b_0 \\ b_1 \\ b_2 \\ \dots \\ \dots \\ b_{n-1}\end{bmatrix} = \bm{b}.
+\]
+!et
+
+For the second exercise we have
+!bt
+\[
+\frac{\partial (\bm{a}^T\bm{A}\bm{a})}{\partial \bm{a}}.
+\]
+!et
+Defining a vector $\bm{f}=\bm{A}\bm{a}$ with components $f_i=\sum_ja_{ij}a_i$ we have
+!bt
+\[
+\frac{\partial (\bm{a}^T\bm{f})}{\partial \bm{a}}=\bm{a}^T\bm{A}+\bm{f}^T=\bm{a}^T\left(\bm{A}+\bm{A}^T\right),
+\]
+!et
+since $f$ depends on $a$ and we have used the chain rule for derivatives on the derivative of $f$ with respect to $a$.
+
+
+!esol
diff --git a/doc/LectureNotes/_build/.doctrees/chapter1.doctree b/doc/LectureNotes/_build/.doctrees/chapter1.doctree
index f3c5d6c3b..94ea5642e 100644
Binary files a/doc/LectureNotes/_build/.doctrees/chapter1.doctree and b/doc/LectureNotes/_build/.doctrees/chapter1.doctree differ
diff --git a/doc/LectureNotes/_build/.doctrees/environment.pickle b/doc/LectureNotes/_build/.doctrees/environment.pickle
index 159ef1a28..931160255 100644
Binary files a/doc/LectureNotes/_build/.doctrees/environment.pickle and b/doc/LectureNotes/_build/.doctrees/environment.pickle differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_17_0.png b/doc/LectureNotes/_build/html/_images/chapter1_17_0.png
index d26235a3f..a06f1e3f9 100644
Binary files a/doc/LectureNotes/_build/html/_images/chapter1_17_0.png and b/doc/LectureNotes/_build/html/_images/chapter1_17_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_19_1.png b/doc/LectureNotes/_build/html/_images/chapter1_19_1.png
index 1b03052ec..1c9a4899a 100644
Binary files a/doc/LectureNotes/_build/html/_images/chapter1_19_1.png and b/doc/LectureNotes/_build/html/_images/chapter1_19_1.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_33_0.png b/doc/LectureNotes/_build/html/_images/chapter1_33_0.png
index 20dc30277..37bbb1c40 100644
Binary files a/doc/LectureNotes/_build/html/_images/chapter1_33_0.png and b/doc/LectureNotes/_build/html/_images/chapter1_33_0.png differ
diff --git a/doc/LectureNotes/_build/html/_images/chapter1_9_0.png b/doc/LectureNotes/_build/html/_images/chapter1_9_0.png
index 272f89f57..6b6183312 100644
Binary files a/doc/LectureNotes/_build/html/_images/chapter1_9_0.png and b/doc/LectureNotes/_build/html/_images/chapter1_9_0.png differ
diff --git a/doc/LectureNotes/_build/html/_sources/chapter1.ipynb b/doc/LectureNotes/_build/html/_sources/chapter1.ipynb
index 9d5a99f5f..74e22cf88 100644
--- a/doc/LectureNotes/_build/html/_sources/chapter1.ipynb
+++ b/doc/LectureNotes/_build/html/_sources/chapter1.ipynb
@@ -2,7 +2,7 @@
"cells": [
{
"cell_type": "markdown",
- "id": "abf0787a",
+ "id": "d9b4c9c8",
"metadata": {
"editable": true
},
@@ -13,7 +13,7 @@
},
{
"cell_type": "markdown",
- "id": "8675dd19",
+ "id": "65e44d92",
"metadata": {
"editable": true
},
@@ -23,7 +23,7 @@
},
{
"cell_type": "markdown",
- "id": "90d6f1f0",
+ "id": "06b62649",
"metadata": {
"editable": true
},
@@ -65,7 +65,7 @@
},
{
"cell_type": "markdown",
- "id": "7b60b0a7",
+ "id": "8de26fd1",
"metadata": {
"editable": true
},
@@ -167,7 +167,7 @@
},
{
"cell_type": "markdown",
- "id": "eef76920",
+ "id": "1ff6afb4",
"metadata": {
"editable": true
},
@@ -202,7 +202,7 @@
},
{
"cell_type": "markdown",
- "id": "74b45ee0",
+ "id": "98d9014b",
"metadata": {
"editable": true
},
@@ -253,7 +253,7 @@
},
{
"cell_type": "markdown",
- "id": "51c84b1e",
+ "id": "4214f050",
"metadata": {
"editable": true
},
@@ -286,7 +286,7 @@
},
{
"cell_type": "markdown",
- "id": "4779803a",
+ "id": "827d0b8e",
"metadata": {
"editable": true
},
@@ -298,7 +298,7 @@
},
{
"cell_type": "markdown",
- "id": "b2f47871",
+ "id": "860f3619",
"metadata": {
"editable": true
},
@@ -335,7 +335,7 @@
{
"cell_type": "code",
"execution_count": 1,
- "id": "1cdef5c4",
+ "id": "b9b8fe1b",
"metadata": {
"collapsed": false,
"editable": true
@@ -368,7 +368,7 @@
},
{
"cell_type": "markdown",
- "id": "d07dd09e",
+ "id": "97a78fd5",
"metadata": {
"editable": true
},
@@ -385,7 +385,7 @@
},
{
"cell_type": "markdown",
- "id": "6f6e8bb4",
+ "id": "5036f5a0",
"metadata": {
"editable": true
},
@@ -397,7 +397,7 @@
},
{
"cell_type": "markdown",
- "id": "b2b85fd5",
+ "id": "0e276aea",
"metadata": {
"editable": true
},
@@ -418,7 +418,7 @@
},
{
"cell_type": "markdown",
- "id": "329ad4bb",
+ "id": "66f6fd13",
"metadata": {
"editable": true
},
@@ -431,7 +431,7 @@
},
{
"cell_type": "markdown",
- "id": "f3e5c4ad",
+ "id": "f29b024f",
"metadata": {
"editable": true
},
@@ -462,7 +462,7 @@
},
{
"cell_type": "markdown",
- "id": "b0ffe38f",
+ "id": "dcce4d43",
"metadata": {
"editable": true
},
@@ -474,7 +474,7 @@
},
{
"cell_type": "markdown",
- "id": "bfdd9400",
+ "id": "20cd881f",
"metadata": {
"editable": true
},
@@ -492,7 +492,7 @@
{
"cell_type": "code",
"execution_count": 2,
- "id": "f3a56404",
+ "id": "aca4204c",
"metadata": {
"collapsed": false,
"editable": true
@@ -520,7 +520,7 @@
},
{
"cell_type": "markdown",
- "id": "b77ca4ff",
+ "id": "9925c6cb",
"metadata": {
"editable": true
},
@@ -542,7 +542,7 @@
{
"cell_type": "code",
"execution_count": 3,
- "id": "7c53db00",
+ "id": "5f927fc2",
"metadata": {
"collapsed": false,
"editable": true
@@ -580,7 +580,7 @@
},
{
"cell_type": "markdown",
- "id": "289acdad",
+ "id": "3c238d46",
"metadata": {
"editable": true
},
@@ -591,7 +591,7 @@
},
{
"cell_type": "markdown",
- "id": "ed56c208",
+ "id": "428d6164",
"metadata": {
"editable": true
},
@@ -604,7 +604,7 @@
},
{
"cell_type": "markdown",
- "id": "a2774f06",
+ "id": "a4046ea1",
"metadata": {
"editable": true
},
@@ -625,7 +625,7 @@
},
{
"cell_type": "markdown",
- "id": "1360472a",
+ "id": "3c665298",
"metadata": {
"editable": true
},
@@ -637,7 +637,7 @@
},
{
"cell_type": "markdown",
- "id": "777f7aad",
+ "id": "dff6fbc4",
"metadata": {
"editable": true
},
@@ -647,7 +647,7 @@
},
{
"cell_type": "markdown",
- "id": "b0182619",
+ "id": "81466e4e",
"metadata": {
"editable": true
},
@@ -659,7 +659,7 @@
},
{
"cell_type": "markdown",
- "id": "925427a2",
+ "id": "40f0760e",
"metadata": {
"editable": true
},
@@ -671,7 +671,7 @@
},
{
"cell_type": "markdown",
- "id": "4e1404d3",
+ "id": "2489c24a",
"metadata": {
"editable": true
},
@@ -683,7 +683,7 @@
},
{
"cell_type": "markdown",
- "id": "07fcae5f",
+ "id": "3f625a67",
"metadata": {
"editable": true
},
@@ -694,7 +694,7 @@
},
{
"cell_type": "markdown",
- "id": "ad8627ec",
+ "id": "6608f259",
"metadata": {
"editable": true
},
@@ -706,7 +706,7 @@
},
{
"cell_type": "markdown",
- "id": "02d8662a",
+ "id": "d63ae4a9",
"metadata": {
"editable": true
},
@@ -728,7 +728,7 @@
},
{
"cell_type": "markdown",
- "id": "d6c17489",
+ "id": "ba2ac7cd",
"metadata": {
"editable": true
},
@@ -740,7 +740,7 @@
},
{
"cell_type": "markdown",
- "id": "7c75b052",
+ "id": "31861c56",
"metadata": {
"editable": true
},
@@ -755,7 +755,7 @@
{
"cell_type": "code",
"execution_count": 4,
- "id": "6c136271",
+ "id": "e2e82632",
"metadata": {
"collapsed": false,
"editable": true
@@ -796,7 +796,7 @@
},
{
"cell_type": "markdown",
- "id": "bd2f6e5a",
+ "id": "9f77ad8a",
"metadata": {
"editable": true
},
@@ -811,7 +811,7 @@
},
{
"cell_type": "markdown",
- "id": "1bc85e33",
+ "id": "79ba67a3",
"metadata": {
"editable": true
},
@@ -823,7 +823,7 @@
},
{
"cell_type": "markdown",
- "id": "70c5d807",
+ "id": "6ed1b749",
"metadata": {
"editable": true
},
@@ -833,7 +833,7 @@
},
{
"cell_type": "markdown",
- "id": "8ad3a692",
+ "id": "7f1a81f1",
"metadata": {
"editable": true
},
@@ -845,7 +845,7 @@
},
{
"cell_type": "markdown",
- "id": "c885dbac",
+ "id": "3a92d75a",
"metadata": {
"editable": true
},
@@ -855,7 +855,7 @@
},
{
"cell_type": "markdown",
- "id": "753ce14d",
+ "id": "2717347f",
"metadata": {
"editable": true
},
@@ -867,7 +867,7 @@
},
{
"cell_type": "markdown",
- "id": "0aada199",
+ "id": "96b2d4fb",
"metadata": {
"editable": true
},
@@ -877,7 +877,7 @@
},
{
"cell_type": "markdown",
- "id": "8f72f12c",
+ "id": "c7705b30",
"metadata": {
"editable": true
},
@@ -889,7 +889,7 @@
},
{
"cell_type": "markdown",
- "id": "ffd008d4",
+ "id": "4e679c00",
"metadata": {
"editable": true
},
@@ -905,7 +905,7 @@
},
{
"cell_type": "markdown",
- "id": "7cab8713",
+ "id": "e5e89d2d",
"metadata": {
"editable": true
},
@@ -917,7 +917,7 @@
},
{
"cell_type": "markdown",
- "id": "f5ab1ec7",
+ "id": "d17826c1",
"metadata": {
"editable": true
},
@@ -928,7 +928,7 @@
},
{
"cell_type": "markdown",
- "id": "76247038",
+ "id": "8cc3306a",
"metadata": {
"editable": true
},
@@ -940,7 +940,7 @@
},
{
"cell_type": "markdown",
- "id": "ead3a52e",
+ "id": "b2ba5419",
"metadata": {
"editable": true
},
@@ -954,7 +954,7 @@
},
{
"cell_type": "markdown",
- "id": "00776fb1",
+ "id": "a94d4658",
"metadata": {
"editable": true
},
@@ -966,7 +966,7 @@
},
{
"cell_type": "markdown",
- "id": "be5156b5",
+ "id": "0c7a9577",
"metadata": {
"editable": true
},
@@ -991,7 +991,7 @@
},
{
"cell_type": "markdown",
- "id": "fdcb3ae8",
+ "id": "acb382a9",
"metadata": {
"editable": true
},
@@ -1008,7 +1008,7 @@
{
"cell_type": "code",
"execution_count": 5,
- "id": "44191ff4",
+ "id": "828ac44b",
"metadata": {
"collapsed": false,
"editable": true
@@ -1052,7 +1052,7 @@
},
{
"cell_type": "markdown",
- "id": "e704ea13",
+ "id": "12105e10",
"metadata": {
"editable": true
},
@@ -1063,7 +1063,7 @@
{
"cell_type": "code",
"execution_count": 6,
- "id": "083ef002",
+ "id": "f3512753",
"metadata": {
"collapsed": false,
"editable": true
@@ -1085,7 +1085,7 @@
},
{
"cell_type": "markdown",
- "id": "b052d9d1",
+ "id": "8d18c1cd",
"metadata": {
"editable": true
},
@@ -1102,7 +1102,7 @@
{
"cell_type": "code",
"execution_count": 7,
- "id": "0f34c048",
+ "id": "9b164e78",
"metadata": {
"collapsed": false,
"editable": true
@@ -1123,7 +1123,7 @@
},
{
"cell_type": "markdown",
- "id": "807d6c8f",
+ "id": "f812fd67",
"metadata": {
"editable": true
},
@@ -1137,7 +1137,7 @@
{
"cell_type": "code",
"execution_count": 8,
- "id": "f8861251",
+ "id": "56d7b683",
"metadata": {
"collapsed": false,
"editable": true
@@ -1166,7 +1166,7 @@
},
{
"cell_type": "markdown",
- "id": "a8743cbd",
+ "id": "247978a1",
"metadata": {
"editable": true
},
@@ -1186,7 +1186,7 @@
{
"cell_type": "code",
"execution_count": 9,
- "id": "61461479",
+ "id": "f62c82f4",
"metadata": {
"collapsed": false,
"editable": true
@@ -1203,7 +1203,7 @@
},
{
"cell_type": "markdown",
- "id": "bf880ec9",
+ "id": "17ef28cf",
"metadata": {
"editable": true
},
@@ -1215,7 +1215,7 @@
{
"cell_type": "code",
"execution_count": 10,
- "id": "9ec9ba03",
+ "id": "261f54be",
"metadata": {
"collapsed": false,
"editable": true
@@ -1233,7 +1233,7 @@
},
{
"cell_type": "markdown",
- "id": "7c67387f",
+ "id": "e22ef3d0",
"metadata": {
"editable": true
},
@@ -1249,7 +1249,7 @@
{
"cell_type": "code",
"execution_count": 11,
- "id": "2a5aa5e9",
+ "id": "952c162e",
"metadata": {
"collapsed": false,
"editable": true
@@ -1262,7 +1262,7 @@
},
{
"cell_type": "markdown",
- "id": "2ea94fce",
+ "id": "d73978fc",
"metadata": {
"editable": true
},
@@ -1274,7 +1274,7 @@
{
"cell_type": "code",
"execution_count": 12,
- "id": "4c136044",
+ "id": "600af054",
"metadata": {
"collapsed": false,
"editable": true
@@ -1304,7 +1304,7 @@
},
{
"cell_type": "markdown",
- "id": "5dfc3135",
+ "id": "a10883fb",
"metadata": {
"editable": true
},
@@ -1315,7 +1315,7 @@
{
"cell_type": "code",
"execution_count": 13,
- "id": "abbc4dbd",
+ "id": "0f967044",
"metadata": {
"collapsed": false,
"editable": true
@@ -1356,7 +1356,7 @@
},
{
"cell_type": "markdown",
- "id": "db107026",
+ "id": "12cfe86f",
"metadata": {
"editable": true
},
@@ -1378,7 +1378,7 @@
{
"cell_type": "code",
"execution_count": 14,
- "id": "86dcf5be",
+ "id": "75baf4ec",
"metadata": {
"collapsed": false,
"editable": true
@@ -1418,7 +1418,7 @@
},
{
"cell_type": "markdown",
- "id": "16a42333",
+ "id": "11e6623d",
"metadata": {
"editable": true
},
@@ -1488,7 +1488,7 @@
},
{
"cell_type": "markdown",
- "id": "ed7f6b48",
+ "id": "1d144bd9",
"metadata": {
"editable": true
},
@@ -1500,7 +1500,7 @@
},
{
"cell_type": "markdown",
- "id": "c621708d",
+ "id": "83596488",
"metadata": {
"editable": true
},
@@ -1519,7 +1519,7 @@
},
{
"cell_type": "markdown",
- "id": "9e26b3b1",
+ "id": "0d0443e0",
"metadata": {
"editable": true
},
@@ -1531,7 +1531,7 @@
},
{
"cell_type": "markdown",
- "id": "7ecf2445",
+ "id": "09b0cf81",
"metadata": {
"editable": true
},
@@ -1543,7 +1543,7 @@
},
{
"cell_type": "markdown",
- "id": "4e3f8091",
+ "id": "a0877d1e",
"metadata": {
"editable": true
},
@@ -1561,7 +1561,7 @@
},
{
"cell_type": "markdown",
- "id": "e0de360e",
+ "id": "3a067e9a",
"metadata": {
"editable": true
},
@@ -1571,7 +1571,7 @@
},
{
"cell_type": "markdown",
- "id": "0d25d3da",
+ "id": "4e083f08",
"metadata": {
"editable": true
},
@@ -1583,7 +1583,7 @@
},
{
"cell_type": "markdown",
- "id": "57956772",
+ "id": "e1fa2d76",
"metadata": {
"editable": true
},
@@ -1593,7 +1593,7 @@
},
{
"cell_type": "markdown",
- "id": "5cb1e06d",
+ "id": "c33752b2",
"metadata": {
"editable": true
},
@@ -1605,7 +1605,7 @@
},
{
"cell_type": "markdown",
- "id": "b52c9a04",
+ "id": "8ea0d39b",
"metadata": {
"editable": true
},
@@ -1615,7 +1615,7 @@
},
{
"cell_type": "markdown",
- "id": "7d521fbe",
+ "id": "2c4dbdc3",
"metadata": {
"editable": true
},
@@ -1627,7 +1627,7 @@
},
{
"cell_type": "markdown",
- "id": "49a4e3f2",
+ "id": "13be3123",
"metadata": {
"editable": true
},
@@ -1637,7 +1637,7 @@
},
{
"cell_type": "markdown",
- "id": "562f4b4f",
+ "id": "c548ec0c",
"metadata": {
"editable": true
},
@@ -1656,7 +1656,7 @@
},
{
"cell_type": "markdown",
- "id": "d979cd1c",
+ "id": "64ab4abc",
"metadata": {
"editable": true
},
@@ -1666,7 +1666,7 @@
},
{
"cell_type": "markdown",
- "id": "93f2605f",
+ "id": "cacc8343",
"metadata": {
"editable": true
},
@@ -1678,7 +1678,7 @@
},
{
"cell_type": "markdown",
- "id": "20c52a36",
+ "id": "8270eaa5",
"metadata": {
"editable": true
},
@@ -1694,7 +1694,7 @@
},
{
"cell_type": "markdown",
- "id": "6c5b9800",
+ "id": "154017fc",
"metadata": {
"editable": true
},
@@ -1714,7 +1714,7 @@
},
{
"cell_type": "markdown",
- "id": "97c9a717",
+ "id": "0053d6cc",
"metadata": {
"editable": true
},
@@ -1726,7 +1726,7 @@
},
{
"cell_type": "markdown",
- "id": "58f60d8c",
+ "id": "65929876",
"metadata": {
"editable": true
},
@@ -1745,7 +1745,7 @@
},
{
"cell_type": "markdown",
- "id": "eb681436",
+ "id": "1b28cdfa",
"metadata": {
"editable": true
},
@@ -1755,7 +1755,7 @@
},
{
"cell_type": "markdown",
- "id": "0d2fd026",
+ "id": "35773b63",
"metadata": {
"editable": true
},
@@ -1767,7 +1767,7 @@
},
{
"cell_type": "markdown",
- "id": "82ee72a3",
+ "id": "bf783586",
"metadata": {
"editable": true
},
@@ -1779,7 +1779,7 @@
},
{
"cell_type": "markdown",
- "id": "bb867a75",
+ "id": "8da3867f",
"metadata": {
"editable": true
},
@@ -1799,7 +1799,7 @@
},
{
"cell_type": "markdown",
- "id": "177a56b6",
+ "id": "927facb3",
"metadata": {
"editable": true
},
@@ -1816,7 +1816,7 @@
{
"cell_type": "code",
"execution_count": 15,
- "id": "639eab41",
+ "id": "7aca7c7a",
"metadata": {
"collapsed": false,
"editable": true
@@ -1896,7 +1896,7 @@
},
{
"cell_type": "markdown",
- "id": "e2f934a2",
+ "id": "c1260224",
"metadata": {
"editable": true
},
@@ -1906,7 +1906,7 @@
},
{
"cell_type": "markdown",
- "id": "270fcf49",
+ "id": "a9549e65",
"metadata": {
"editable": true
},
@@ -1918,7 +1918,7 @@
},
{
"cell_type": "markdown",
- "id": "c6217145",
+ "id": "29c67e39",
"metadata": {
"editable": true
},
@@ -1930,7 +1930,7 @@
},
{
"cell_type": "markdown",
- "id": "40ea3dc2",
+ "id": "7fe12004",
"metadata": {
"editable": true
},
@@ -1942,7 +1942,7 @@
},
{
"cell_type": "markdown",
- "id": "6eb268f2",
+ "id": "a974412a",
"metadata": {
"editable": true
},
@@ -1952,7 +1952,7 @@
},
{
"cell_type": "markdown",
- "id": "30d15d84",
+ "id": "03241cbf",
"metadata": {
"editable": true
},
@@ -1964,7 +1964,7 @@
},
{
"cell_type": "markdown",
- "id": "0092f5fc",
+ "id": "bb96d559",
"metadata": {
"editable": true
},
@@ -1974,7 +1974,7 @@
},
{
"cell_type": "markdown",
- "id": "f0e3eaab",
+ "id": "108c564b",
"metadata": {
"editable": true
},
@@ -1986,7 +1986,7 @@
},
{
"cell_type": "markdown",
- "id": "ba3587ca",
+ "id": "041588ea",
"metadata": {
"editable": true
},
@@ -1999,7 +1999,7 @@
},
{
"cell_type": "markdown",
- "id": "f18299b6",
+ "id": "2c2ac147",
"metadata": {
"editable": true
},
@@ -2011,7 +2011,7 @@
},
{
"cell_type": "markdown",
- "id": "67284093",
+ "id": "f4155adc",
"metadata": {
"editable": true
},
@@ -2023,7 +2023,7 @@
},
{
"cell_type": "markdown",
- "id": "5f555cfc",
+ "id": "f7a73ebb",
"metadata": {
"editable": true
},
@@ -2035,7 +2035,7 @@
},
{
"cell_type": "markdown",
- "id": "8ac974cb",
+ "id": "058f09a6",
"metadata": {
"editable": true
},
@@ -2046,7 +2046,7 @@
},
{
"cell_type": "markdown",
- "id": "f1559872",
+ "id": "dcdfbbc5",
"metadata": {
"editable": true
},
@@ -2058,7 +2058,7 @@
},
{
"cell_type": "markdown",
- "id": "8e63a36c",
+ "id": "206a6652",
"metadata": {
"editable": true
},
@@ -2077,7 +2077,7 @@
},
{
"cell_type": "markdown",
- "id": "9954810b",
+ "id": "84f4071a",
"metadata": {
"editable": true
},
@@ -2090,7 +2090,7 @@
},
{
"cell_type": "markdown",
- "id": "910c87ca",
+ "id": "aec4af35",
"metadata": {
"editable": true
},
@@ -2100,7 +2100,7 @@
},
{
"cell_type": "markdown",
- "id": "693ad55a",
+ "id": "de7dcc20",
"metadata": {
"editable": true
},
@@ -2112,7 +2112,7 @@
},
{
"cell_type": "markdown",
- "id": "781244b4",
+ "id": "ce6f83f2",
"metadata": {
"editable": true
},
@@ -2122,7 +2122,7 @@
},
{
"cell_type": "markdown",
- "id": "ae61b535",
+ "id": "1780e810",
"metadata": {
"editable": true
},
@@ -2134,7 +2134,7 @@
},
{
"cell_type": "markdown",
- "id": "2d8201cc",
+ "id": "6b4d0be0",
"metadata": {
"editable": true
},
@@ -2144,7 +2144,7 @@
},
{
"cell_type": "markdown",
- "id": "e323d90a",
+ "id": "021fe0da",
"metadata": {
"editable": true
},
@@ -2156,7 +2156,7 @@
},
{
"cell_type": "markdown",
- "id": "14394cc1",
+ "id": "90bf5b47",
"metadata": {
"editable": true
},
@@ -2166,7 +2166,7 @@
},
{
"cell_type": "markdown",
- "id": "090b82c7",
+ "id": "15e45481",
"metadata": {
"editable": true
},
@@ -2178,7 +2178,7 @@
},
{
"cell_type": "markdown",
- "id": "311ca5e8",
+ "id": "d758a151",
"metadata": {
"editable": true
},
@@ -2188,7 +2188,7 @@
},
{
"cell_type": "markdown",
- "id": "b4b47e6f",
+ "id": "c5a05d3f",
"metadata": {
"editable": true
},
@@ -2200,7 +2200,7 @@
},
{
"cell_type": "markdown",
- "id": "8a49c9ff",
+ "id": "f57d857f",
"metadata": {
"editable": true
},
@@ -2210,7 +2210,7 @@
},
{
"cell_type": "markdown",
- "id": "744a34c9",
+ "id": "7e7c11cc",
"metadata": {
"editable": true
},
@@ -2222,7 +2222,7 @@
},
{
"cell_type": "markdown",
- "id": "d2f65ed3",
+ "id": "6d0438bc",
"metadata": {
"editable": true
},
@@ -2246,66 +2246,76 @@
},
{
"cell_type": "markdown",
- "id": "ca450475",
+ "id": "81350349",
"metadata": {
"editable": true
},
"source": [
"$$\n",
- "\\frac{\\partial\\boldsymbol{b}^T\\boldsymbol{a}}{\\partial\\boldsymbol{a}}=\\boldsymbol{b},\n",
+ "\\frac{\\partial (\\boldsymbol{b}^T\\boldsymbol{a})}{\\partial \\boldsymbol{a}} = \\boldsymbol{b},\n",
"$$"
]
},
{
"cell_type": "markdown",
- "id": "ff7b8b4f",
+ "id": "470abb5b",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e49b3680",
"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",
+ "\\frac{\\partial (\\boldsymbol{a}^T\\boldsymbol{A}\\boldsymbol{a})}{\\partial \\boldsymbol{a}} = \\boldsymbol{a}^T(\\boldsymbol{A}+\\boldsymbol{A}^T),\n",
"$$"
]
},
{
"cell_type": "markdown",
- "id": "13df1ee1",
+ "id": "71cc2366",
+ "metadata": {
+ "editable": true
+ },
+ "source": [
+ "and"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "494e1da4",
"metadata": {
"editable": true
},
"source": [
"$$\n",
- "\\frac{\\partial tr(\\boldsymbol{B}\\boldsymbol{A})}{\\partial\\boldsymbol{A}}=\\boldsymbol{B}^T,\n",
+ "\\frac{\\partial \\left(\\boldsymbol{x}-\\boldsymbol{A}\\boldsymbol{s}\\right)^T\\left(\\boldsymbol{x}-\\boldsymbol{A}\\boldsymbol{s}\\right)}{\\partial \\boldsymbol{s}} = -2\\left(\\boldsymbol{x}-\\boldsymbol{A}\\boldsymbol{s}\\right)^T\\boldsymbol{A},\n",
"$$"
]
},
{
"cell_type": "markdown",
- "id": "36a0b11e",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\frac{\\partial\\log{\\vert\\boldsymbol{A}\\vert}}{\\partial \\boldsymbol{A}}=(\\boldsymbol{A}^{-1})^T.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "73c64903",
+ "id": "88fa8938",
"metadata": {
"editable": true
},
"source": [
+ "These and other relations are discussed in the exercises following this chapter (see the end of the chapter).\n",
+ "The latter equation is similar to the equation for the mean-squared error function we have been discussing. \n",
"We can then compute the second derivative of the cost function, which in our case is the second derivative\n",
"of the means squared error. This leads to"
]
},
{
"cell_type": "markdown",
- "id": "4602f620",
+ "id": "f2886bf5",
"metadata": {
"editable": true
},
@@ -2317,19 +2327,19 @@
},
{
"cell_type": "markdown",
- "id": "51e19903",
+ "id": "2b2dc285",
"metadata": {
"editable": true
},
"source": [
- "This quantity defines was what is called the Hessian matrix (the second derivative of a function we want to optimize).\n",
+ "This quantity defines the so- called the Hessian matrix.\n",
"\n",
"The Hessian matrix plays an important role and is defined for the mean squared error as"
]
},
{
"cell_type": "markdown",
- "id": "e6b248c3",
+ "id": "762f5b0f",
"metadata": {
"editable": true
},
@@ -2341,7 +2351,7 @@
},
{
"cell_type": "markdown",
- "id": "91b60702",
+ "id": "66c7bf97",
"metadata": {
"editable": true
},
@@ -2356,7 +2366,7 @@
},
{
"cell_type": "markdown",
- "id": "26a256b3",
+ "id": "c57edc78",
"metadata": {
"editable": true
},
@@ -2368,7 +2378,7 @@
},
{
"cell_type": "markdown",
- "id": "af338ef6",
+ "id": "6d750248",
"metadata": {
"editable": true
},
@@ -2378,7 +2388,7 @@
},
{
"cell_type": "markdown",
- "id": "fecef307",
+ "id": "ae22e8f6",
"metadata": {
"editable": true
},
@@ -2390,7 +2400,7 @@
},
{
"cell_type": "markdown",
- "id": "d895336c",
+ "id": "70c9ad4d",
"metadata": {
"editable": true
},
@@ -2400,7 +2410,7 @@
},
{
"cell_type": "markdown",
- "id": "a1de6a4a",
+ "id": "02fec10f",
"metadata": {
"editable": true
},
@@ -2412,7 +2422,7 @@
},
{
"cell_type": "markdown",
- "id": "15669251",
+ "id": "8e2a2e61",
"metadata": {
"editable": true
},
@@ -2428,7 +2438,7 @@
{
"cell_type": "code",
"execution_count": 16,
- "id": "ab885c31",
+ "id": "9f6f9239",
"metadata": {
"collapsed": false,
"editable": true
@@ -2443,7 +2453,7 @@
},
{
"cell_type": "markdown",
- "id": "ded01eba",
+ "id": "604dbc32",
"metadata": {
"editable": true
},
@@ -2454,7 +2464,7 @@
{
"cell_type": "code",
"execution_count": 17,
- "id": "14561b3b",
+ "id": "00a1ced4",
"metadata": {
"collapsed": false,
"editable": true
@@ -2467,7 +2477,7 @@
},
{
"cell_type": "markdown",
- "id": "d6abfb9b",
+ "id": "7ceb5efd",
"metadata": {
"editable": true
},
@@ -2478,7 +2488,7 @@
{
"cell_type": "code",
"execution_count": 18,
- "id": "b9e5c460",
+ "id": "e462c872",
"metadata": {
"collapsed": false,
"editable": true
@@ -2501,7 +2511,7 @@
},
{
"cell_type": "markdown",
- "id": "698df560",
+ "id": "e0ef3a79",
"metadata": {
"editable": true
},
@@ -2513,7 +2523,7 @@
{
"cell_type": "code",
"execution_count": 19,
- "id": "9dbe859a",
+ "id": "1f66c40c",
"metadata": {
"collapsed": false,
"editable": true
@@ -2526,7 +2536,7 @@
},
{
"cell_type": "markdown",
- "id": "74c9d52f",
+ "id": "e46854b6",
"metadata": {
"editable": true
},
@@ -2537,7 +2547,7 @@
{
"cell_type": "code",
"execution_count": 20,
- "id": "e8c140e8",
+ "id": "ec1fee3e",
"metadata": {
"collapsed": false,
"editable": true
@@ -2549,7 +2559,7 @@
},
{
"cell_type": "markdown",
- "id": "c131f9a3",
+ "id": "5a3558b1",
"metadata": {
"editable": true
},
@@ -2560,7 +2570,7 @@
{
"cell_type": "code",
"execution_count": 21,
- "id": "00c1307d",
+ "id": "4aae389c",
"metadata": {
"collapsed": false,
"editable": true
@@ -2576,7 +2586,7 @@
},
{
"cell_type": "markdown",
- "id": "afcf6b4d",
+ "id": "a04587b4",
"metadata": {
"editable": true
},
@@ -2587,7 +2597,7 @@
{
"cell_type": "code",
"execution_count": 22,
- "id": "30ce0766",
+ "id": "19a649a5",
"metadata": {
"collapsed": false,
"editable": true
@@ -2601,7 +2611,7 @@
},
{
"cell_type": "markdown",
- "id": "208f6b70",
+ "id": "4e526f30",
"metadata": {
"editable": true
},
@@ -2623,7 +2633,7 @@
},
{
"cell_type": "markdown",
- "id": "76ab8d32",
+ "id": "f55ada0e",
"metadata": {
"editable": true
},
@@ -2635,7 +2645,7 @@
},
{
"cell_type": "markdown",
- "id": "d9ad3f4d",
+ "id": "b58ad660",
"metadata": {
"editable": true
},
@@ -2647,7 +2657,7 @@
},
{
"cell_type": "markdown",
- "id": "5f8ad792",
+ "id": "3e135503",
"metadata": {
"editable": true
},
@@ -2659,7 +2669,7 @@
},
{
"cell_type": "markdown",
- "id": "c9685750",
+ "id": "1a659dc5",
"metadata": {
"editable": true
},
@@ -2669,7 +2679,7 @@
},
{
"cell_type": "markdown",
- "id": "96b044c3",
+ "id": "e66bd75c",
"metadata": {
"editable": true
},
@@ -2681,7 +2691,7 @@
},
{
"cell_type": "markdown",
- "id": "683761fd",
+ "id": "4d6a21c9",
"metadata": {
"editable": true
},
@@ -2691,7 +2701,7 @@
},
{
"cell_type": "markdown",
- "id": "e93b0c33",
+ "id": "31ca7b17",
"metadata": {
"editable": true
},
@@ -2703,7 +2713,7 @@
},
{
"cell_type": "markdown",
- "id": "a15143d4",
+ "id": "66443630",
"metadata": {
"editable": true
},
@@ -2715,7 +2725,7 @@
},
{
"cell_type": "markdown",
- "id": "ec94fb14",
+ "id": "28f84c45",
"metadata": {
"editable": true
},
@@ -2727,7 +2737,7 @@
},
{
"cell_type": "markdown",
- "id": "6e7a8085",
+ "id": "7a292188",
"metadata": {
"editable": true
},
@@ -2737,7 +2747,7 @@
},
{
"cell_type": "markdown",
- "id": "a093d2a1",
+ "id": "19acde5f",
"metadata": {
"editable": true
},
@@ -2749,7 +2759,7 @@
},
{
"cell_type": "markdown",
- "id": "32189c08",
+ "id": "f4bfc2ba",
"metadata": {
"editable": true
},
@@ -2759,7 +2769,7 @@
},
{
"cell_type": "markdown",
- "id": "042085f9",
+ "id": "ffe9cdc3",
"metadata": {
"editable": true
},
@@ -2771,7 +2781,7 @@
},
{
"cell_type": "markdown",
- "id": "2a711c1a",
+ "id": "e6cd175c",
"metadata": {
"editable": true
},
@@ -2781,7 +2791,7 @@
},
{
"cell_type": "markdown",
- "id": "4c082c12",
+ "id": "4520bd32",
"metadata": {
"editable": true
},
@@ -2793,7 +2803,7 @@
},
{
"cell_type": "markdown",
- "id": "3ef9c8f8",
+ "id": "018f1bcc",
"metadata": {
"editable": true
},
@@ -2803,7 +2813,7 @@
},
{
"cell_type": "markdown",
- "id": "7d779743",
+ "id": "657cad6a",
"metadata": {
"editable": true
},
@@ -2815,7 +2825,7 @@
},
{
"cell_type": "markdown",
- "id": "b9f180ff",
+ "id": "24fe79df",
"metadata": {
"editable": true
},
@@ -2825,7 +2835,7 @@
},
{
"cell_type": "markdown",
- "id": "4bd7ff7a",
+ "id": "6c7db826",
"metadata": {
"editable": true
},
@@ -2837,7 +2847,7 @@
},
{
"cell_type": "markdown",
- "id": "5a9a0e2a",
+ "id": "1927e34a",
"metadata": {
"editable": true
},
@@ -2847,7 +2857,7 @@
},
{
"cell_type": "markdown",
- "id": "43526b6e",
+ "id": "406ca333",
"metadata": {
"editable": true
},
@@ -2859,7 +2869,7 @@
},
{
"cell_type": "markdown",
- "id": "45c0e8b1",
+ "id": "6acb7f48",
"metadata": {
"editable": true
},
@@ -2869,7 +2879,7 @@
},
{
"cell_type": "markdown",
- "id": "396a1bce",
+ "id": "7cf70bf5",
"metadata": {
"editable": true
},
@@ -2881,7 +2891,7 @@
},
{
"cell_type": "markdown",
- "id": "c10268e7",
+ "id": "b0413ba5",
"metadata": {
"editable": true
},
@@ -2891,7 +2901,7 @@
},
{
"cell_type": "markdown",
- "id": "10c2e68c",
+ "id": "b613c67c",
"metadata": {
"editable": true
},
@@ -2903,7 +2913,7 @@
},
{
"cell_type": "markdown",
- "id": "4fe24ad6",
+ "id": "85693726",
"metadata": {
"editable": true
},
@@ -2913,7 +2923,7 @@
},
{
"cell_type": "markdown",
- "id": "2383a935",
+ "id": "64582090",
"metadata": {
"editable": true
},
@@ -2925,7 +2935,7 @@
},
{
"cell_type": "markdown",
- "id": "1e3c0203",
+ "id": "061bb39a",
"metadata": {
"editable": true
},
@@ -2936,7 +2946,7 @@
},
{
"cell_type": "markdown",
- "id": "1c9dbe17",
+ "id": "c750e91e",
"metadata": {
"editable": true
},
@@ -2948,7 +2958,7 @@
},
{
"cell_type": "markdown",
- "id": "35dc4610",
+ "id": "28124d83",
"metadata": {
"editable": true
},
@@ -2960,7 +2970,7 @@
},
{
"cell_type": "markdown",
- "id": "66b6c18d",
+ "id": "d7128979",
"metadata": {
"editable": true
},
@@ -2972,7 +2982,7 @@
},
{
"cell_type": "markdown",
- "id": "def0d04b",
+ "id": "ec2f92ad",
"metadata": {
"editable": true
},
@@ -2984,7 +2994,7 @@
},
{
"cell_type": "markdown",
- "id": "7d6af2ed",
+ "id": "b0ac5589",
"metadata": {
"editable": true
},
@@ -2996,7 +3006,7 @@
},
{
"cell_type": "markdown",
- "id": "02db20b1",
+ "id": "b8de935b",
"metadata": {
"editable": true
},
@@ -3006,7 +3016,7 @@
},
{
"cell_type": "markdown",
- "id": "323f21f3",
+ "id": "ffb07e70",
"metadata": {
"editable": true
},
@@ -3018,7 +3028,7 @@
},
{
"cell_type": "markdown",
- "id": "03a686e4",
+ "id": "f52a2b52",
"metadata": {
"editable": true
},
@@ -3030,7 +3040,7 @@
},
{
"cell_type": "markdown",
- "id": "1239edc3",
+ "id": "21d55a92",
"metadata": {
"editable": true
},
@@ -3044,7 +3054,7 @@
},
{
"cell_type": "markdown",
- "id": "de3dc052",
+ "id": "35eff2a6",
"metadata": {
"editable": true
},
@@ -3070,7 +3080,7 @@
{
"cell_type": "code",
"execution_count": 23,
- "id": "755ebe55",
+ "id": "28b5fe82",
"metadata": {
"collapsed": false,
"editable": true
@@ -3152,7 +3162,7 @@
},
{
"cell_type": "markdown",
- "id": "fb8d2943",
+ "id": "2b3abee3",
"metadata": {
"editable": true
},
@@ -3163,7 +3173,7 @@
},
{
"cell_type": "markdown",
- "id": "84aa3cb0",
+ "id": "1b449839",
"metadata": {
"editable": true
},
@@ -3191,7 +3201,7 @@
{
"cell_type": "code",
"execution_count": 24,
- "id": "31887c07",
+ "id": "d99bbcf6",
"metadata": {
"collapsed": false,
"editable": true
@@ -3240,7 +3250,7 @@
},
{
"cell_type": "markdown",
- "id": "0b2ef393",
+ "id": "2e67c926",
"metadata": {
"editable": true
},
@@ -3251,7 +3261,7 @@
{
"cell_type": "code",
"execution_count": 25,
- "id": "5c347db2",
+ "id": "72bf715e",
"metadata": {
"collapsed": false,
"editable": true
@@ -3276,7 +3286,7 @@
},
{
"cell_type": "markdown",
- "id": "1c394fbb",
+ "id": "7cea6c55",
"metadata": {
"editable": true
},
@@ -3293,7 +3303,7 @@
{
"cell_type": "code",
"execution_count": 26,
- "id": "ae5eb741",
+ "id": "32a2c51d",
"metadata": {
"collapsed": false,
"editable": true
@@ -3368,7 +3378,7 @@
},
{
"cell_type": "markdown",
- "id": "dbe0c366",
+ "id": "988b4c3c",
"metadata": {
"editable": true
},
@@ -3412,7 +3422,7 @@
},
{
"cell_type": "markdown",
- "id": "2a9cc829",
+ "id": "b08e5c3f",
"metadata": {
"editable": true
},
@@ -3424,7 +3434,7 @@
{
"cell_type": "code",
"execution_count": 27,
- "id": "a8843592",
+ "id": "3b5864e7",
"metadata": {
"collapsed": false,
"editable": true
@@ -3440,7 +3450,7 @@
},
{
"cell_type": "markdown",
- "id": "9abbc574",
+ "id": "f96254bd",
"metadata": {
"editable": true
},
@@ -3451,7 +3461,7 @@
{
"cell_type": "code",
"execution_count": 28,
- "id": "50b5d160",
+ "id": "784aee0c",
"metadata": {
"collapsed": false,
"editable": true
@@ -3469,7 +3479,7 @@
},
{
"cell_type": "markdown",
- "id": "00dfdd50",
+ "id": "d5616e2a",
"metadata": {
"editable": true
},
@@ -3480,7 +3490,7 @@
{
"cell_type": "code",
"execution_count": 29,
- "id": "ba5c8bb2",
+ "id": "8d91d13b",
"metadata": {
"collapsed": false,
"editable": true
@@ -3494,7 +3504,7 @@
},
{
"cell_type": "markdown",
- "id": "ee060a44",
+ "id": "f81c3406",
"metadata": {
"editable": true
},
@@ -3505,7 +3515,7 @@
{
"cell_type": "code",
"execution_count": 30,
- "id": "7cd7e1ee",
+ "id": "434d4f3c",
"metadata": {
"collapsed": false,
"editable": true
@@ -3518,7 +3528,7 @@
},
{
"cell_type": "markdown",
- "id": "11cf13f4",
+ "id": "c1bf7530",
"metadata": {
"editable": true
},
@@ -3529,7 +3539,7 @@
{
"cell_type": "code",
"execution_count": 31,
- "id": "c75837e3",
+ "id": "7fd8c004",
"metadata": {
"collapsed": false,
"editable": true
@@ -3546,7 +3556,7 @@
},
{
"cell_type": "markdown",
- "id": "e5f7bd90",
+ "id": "a1b4260a",
"metadata": {
"editable": true
},
@@ -3557,7 +3567,7 @@
{
"cell_type": "code",
"execution_count": 32,
- "id": "1a5ec28f",
+ "id": "e5303f58",
"metadata": {
"collapsed": false,
"editable": true
@@ -3573,7 +3583,7 @@
},
{
"cell_type": "markdown",
- "id": "82358b49",
+ "id": "2a9b8649",
"metadata": {
"editable": true
},
@@ -3584,7 +3594,7 @@
{
"cell_type": "code",
"execution_count": 33,
- "id": "870190cd",
+ "id": "c16b948c",
"metadata": {
"collapsed": false,
"editable": true
@@ -3608,7 +3618,7 @@
},
{
"cell_type": "markdown",
- "id": "c7628b09",
+ "id": "e16e8946",
"metadata": {
"editable": true
},
@@ -3619,7 +3629,7 @@
{
"cell_type": "code",
"execution_count": 34,
- "id": "3b1fe034",
+ "id": "b9fe4c39",
"metadata": {
"collapsed": false,
"editable": true
@@ -3632,7 +3642,7 @@
},
{
"cell_type": "markdown",
- "id": "9f864351",
+ "id": "91b51561",
"metadata": {
"editable": true
},
@@ -3643,7 +3653,7 @@
{
"cell_type": "code",
"execution_count": 35,
- "id": "9dd326a0",
+ "id": "e3b9fbd9",
"metadata": {
"collapsed": false,
"editable": true
@@ -3663,7 +3673,7 @@
},
{
"cell_type": "markdown",
- "id": "8bc24ccc",
+ "id": "f4c894b3",
"metadata": {
"editable": true
},
@@ -3674,7 +3684,7 @@
{
"cell_type": "code",
"execution_count": 36,
- "id": "f04e7787",
+ "id": "b879380d",
"metadata": {
"collapsed": false,
"editable": true
@@ -3717,7 +3727,7 @@
{
"cell_type": "code",
"execution_count": 37,
- "id": "e64f0d66",
+ "id": "5c646824",
"metadata": {
"collapsed": false,
"editable": true
@@ -3732,7 +3742,7 @@
},
{
"cell_type": "markdown",
- "id": "d376f62d",
+ "id": "fcbd54b7",
"metadata": {
"editable": true
},
@@ -3809,7 +3819,7 @@
},
{
"cell_type": "markdown",
- "id": "353f7dc0",
+ "id": "dc5eefba",
"metadata": {
"editable": true
},
@@ -3821,7 +3831,7 @@
},
{
"cell_type": "markdown",
- "id": "5e1aa076",
+ "id": "74092b8e",
"metadata": {
"editable": true
},
@@ -3841,7 +3851,7 @@
{
"cell_type": "code",
"execution_count": 38,
- "id": "b9b91c02",
+ "id": "29a1b167",
"metadata": {
"collapsed": false,
"editable": true
@@ -3875,7 +3885,7 @@
},
{
"cell_type": "markdown",
- "id": "90353e0c",
+ "id": "ae1b0689",
"metadata": {
"editable": true
},
@@ -3890,7 +3900,7 @@
},
{
"cell_type": "markdown",
- "id": "eb29b406",
+ "id": "ce25e983",
"metadata": {
"editable": true
},
@@ -3902,7 +3912,7 @@
},
{
"cell_type": "markdown",
- "id": "36c1a91c",
+ "id": "48a5391f",
"metadata": {
"editable": true
},
@@ -3912,7 +3922,7 @@
},
{
"cell_type": "markdown",
- "id": "4fd47015",
+ "id": "cce21123",
"metadata": {
"editable": true
},
@@ -3936,7 +3946,7 @@
{
"cell_type": "code",
"execution_count": 39,
- "id": "8c7dcd78",
+ "id": "6e847f61",
"metadata": {
"collapsed": false,
"editable": true
@@ -3980,7 +3990,7 @@
},
{
"cell_type": "markdown",
- "id": "22ef09fb",
+ "id": "0020a5f3",
"metadata": {
"editable": true
},
@@ -3990,12 +4000,12 @@
},
{
"cell_type": "markdown",
- "id": "c81539de",
+ "id": "a226cdd9",
"metadata": {
"editable": true
},
"source": [
- "### Exercise: Setting up various Python environments\n",
+ "## Exercise 1: Setting up various Python environments\n",
"\n",
"The first exercise here is of a mere technical art. We want you to have \n",
"* git as a version control software and to establish a user account on a provider like GitHub. Other providers like GitLab etc are equally fine. You can also use the University of Oslo [GitHub facilities](https://www.uio.no/tjenester/it/maskin/filer/versjonskontroll/github.html). \n",
@@ -4059,12 +4069,12 @@
},
{
"cell_type": "markdown",
- "id": "b7cbad15",
+ "id": "9fc89d8c",
"metadata": {
"editable": true
},
"source": [
- "### Exercise: making your own data and exploring scikit-learn\n",
+ "## Exercise 2: making your own data and exploring scikit-learn\n",
"\n",
"We will generate our own dataset for a function $y(x)$ where $x \\in [0,1]$ and defined by random numbers computed with the uniform distribution. The function $y$ is a quadratic polynomial in $x$ with added stochastic noise according to the normal distribution $\\cal {N}(0,1)$.\n",
"The following simple Python instructions define our $x$ and $y$ values (with 100 data points)."
@@ -4073,7 +4083,7 @@
{
"cell_type": "code",
"execution_count": 40,
- "id": "aec3d518",
+ "id": "e417626d",
"metadata": {
"collapsed": false,
"editable": true
@@ -4086,21 +4096,21 @@
},
{
"cell_type": "markdown",
- "id": "0e5cd05f",
+ "id": "cf385569",
"metadata": {
"editable": true
},
"source": [
"1. Write your own code (following the examples under the [regression notes](https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter1.html)) for computing the parametrization of the data set fitting a second-order polynomial. \n",
"\n",
- "2. Use thereafter **scikit-learn** (see again the examples in the regression slides) and compare with your own code. \n",
+ "2. Use thereafter **scikit-learn** (see again the examples in the regression slides) and compare with your own code. When compairing with _scikit_learn_, make sure you set the option for the intercept to **FALSE**, see
The intercept alpha:
- [1.92272314]
+ [1.99274513]
Coefficient beta :
- [[5.13117061]]
-Mean squared error: 0.21
-Variance score: 0.92
+ [[5.03570747]]
+Mean squared error: 0.27
+Variance score: 0.88
Mean squared log error: 0.01
-Mean absolute error: 0.36
+Mean absolute error: 0.42
@@ -1044,7 +1060,7 @@ a linear \(x\)-dependence we s
-0.004999999999999996
+0.005000000000000011
and
and
We can then compute the second derivative of the cost function, which in our case is the second derivative +
These and other relations are discussed in the exercises following this chapter (see the end of the chapter). +The latter equation is similar to the equation for the mean-squared error function we have been discussing. +We can then compute the second derivative of the cost function, which in our case is the second derivative of the means squared error. This leads to
This quantity defines was what is called the Hessian matrix (the second derivative of a function we want to optimize).
+This quantity defines the so- called the Hessian matrix.
The Hessian matrix plays an important role and is defined for the mean squared error as
The first exercise here is of a mere technical art. We want you to have
git as a version control software and to establish a user account on a provider like GitHub. Other providers like GitLab etc are equally fine. You can also use the University of Oslo GitHub facilities.
We recommend using Anaconda if you are not too familiar with setting paths in a terminal environment.
We will generate our own dataset for a function \(y(x)\) where \(x \in [0,1]\) and defined by random numbers computed with the uniform distribution. The function \(y\) is a quadratic polynomial in \(x\) with added stochastic noise according to the normal distribution \(\cal {N}(0,1)\). The following simple Python instructions define our \(x\) and \(y\) values (with 100 data points).
Write your own code (following the examples under the regression notes) for computing the parametrization of the data set fitting a second-order polynomial.
Use thereafter scikit-learn (see again the examples in the regression slides) and compare with your own code.
Use thereafter scikit-learn (see again the examples in the regression slides) and compare with your own code. When compairing with scikit_learn, make sure you set the option for the intercept to FALSE, see https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html. This feature will be explained in more detail during the lectures of week 35 and week 36. You can find more in https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#more-on-rescaling-data.
Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions. Discuss the meaning of these results. Try also to vary the coefficient in front of the added stochastic noise term and discuss the quality of the fits.
+ +Solution. +The code here is an example of where we define our own design matrix and fit parameters \(\beta\).
+import os
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.model_selection import train_test_split
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_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))
+A much used approach before starting to train the data is to preprocess 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
@@ -2733,7 +2799,7 @@ for testing. This can be done as follows with our design matrix
# split in training and test data
-# X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)
+X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)
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.
-Perform an ordinary least squares and compute the means squared error -and the \(R2\) factor for the training data and the test data, with and -without scaling.
-Add now a model which allows you to make polynomials up to degree -\(15\). Perform a standard OLS fitting of the training data and compute -the MSE and \(R2\) for the training and test data and plot both test and -training data MSE and \(R2\) as functions of the polynomial -degree. Compare what you see with Figure 2.11 of Hastie et al. Comment -your results. For which polynomial degree do you find an optimal MSE -(smallest value)?
+ +Solution. +We present here the solution for the last exercise. All elements here can be used to solve exercises a) and b) as well. +Note that in this example we have used the polynomial fitting functions of scikit-learn.
+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 = 30
+maxdegree = 14
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+TestError = np.zeros(maxdegree)
+TrainError = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+
+for degree in range(maxdegree):
+ model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
+ clf = model.fit(x_train,y_train)
+ y_fit = clf.predict(x_train)
+ y_pred = clf.predict(x_test)
+ 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()
+a) +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.
+b) +Perform an ordinary least squares and compute the means squared error and the \(R2\) factor for the training data and the test data, with and without scaling.
+c) +Add now a model which allows you to make polynomials up to degree \(15\). Perform a standard OLS fitting of the training data and compute the MSE and \(R2\) for the training and test data and plot both test and training data MSE and \(R2\) as functions of the polynomial degree. Compare what you see with Figure 2.11 of Hastie et al. Comment your results. For which polynomial degree do you find an optimal MSE (smallest value)?
+This exercise is a continuation of exercise 2. We will use the same function to +generate our data set, still staying with a simple function \(y(x)\) +which we want to fit using linear regression, but now extending the +analysis to include the Ridge regression method.
+We will thus again generate our own dataset for a function \(y(x)\) where +\(x \in [0,1]\) and defined by random numbers computed with the uniform +distribution. The function \(y\) is a quadratic polynomial in \(x\) with +added stochastic noise according to the normal distribution \(\cal{N}(0,1)\).
+The following simple Python instructions define our \(x\) and \(y\) values (with 100 data points).
+x = np.random.rand(100)
+y = 2.0+5*x*x+0.1*np.random.randn(100)
+Write your own code for the Ridge method (see chapter 3.4 of Hastie et al., equations (3.43) and (3.44)) and compute the parametrization for different values of \(\lambda\). Compare and analyze your results with those from exercise 3. Study the dependence on \(\lambda\) while also varying the strength of the noise in your expression for \(y(x)\).
+Repeat the above but using the functionality of +Scikit-Learn. Compare your code with the results from +Scikit-Learn. Remember to run with the same random numbers for +generating \(x\) and \(y\). Observe also that when you compare with Scikit-Learn, you need to pay attention to how the intercept is dealt with.
+Finally, using Scikit-Learn or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
+and the \(R^2\) score function. +If \(\tilde{\hat{y}}_i\) is the predicted value of the \(i-th\) sample and \(y_i\) is the corresponding true value, then the score \(R^2\) is defined as
+where we have defined the mean value of \(\hat{y}\) as
+Discuss these quantities as functions of the variable \(\lambda\) in Ridge regression.
+ +Solution. +The code here allows you to perform your own Ridge calculation and +perform calculations for various values of the regularization +parameter \(\lambda\). This program can easily be extended upon.
+import os
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.model_selection import train_test_split
+from sklearn.preprocessing import StandardScaler
+from sklearn import linear_model
+
+def R2(y_data, y_model):
+ return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
+def MSE(y_data,y_model):
+ n = np.size(y_model)
+ return np.sum((y_data-y_model)**2)/n
+
+
+# A seed just to ensure that the random numbers are the same for every run.
+# Useful for eventual debugging.
+np.random.seed(3155)
+
+x = np.random.rand(100)
+y = 2.0+5*x*x+0.1*np.random.randn(100)
+
+# number of features p (here degree of polynomial
+p = 3
+# The design matrix now as function of a given polynomial
+X = np.zeros((len(x),p))
+X[:,0] = 1.0
+X[:,1] = x
+X[:,2] = x*x
+# We split the data in test and training data
+X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
+
+# matrix inversion to find beta
+OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train
+print(OLSbeta)
+# and then make the prediction
+ytildeOLS = X_train @ OLSbeta
+print("Training R2 for OLS")
+print(R2(y_train,ytildeOLS))
+print("Training MSE for OLS")
+print(MSE(y_train,ytildeOLS))
+ypredictOLS = X_test @ OLSbeta
+print("Test R2 for OLS")
+print(R2(y_test,ypredictOLS))
+print("Test MSE OLS")
+print(MSE(y_test,ypredictOLS))
+
+
+# Repeat now for Ridge regression and various values of the regularization parameter
+I = np.eye(p,p)
+# Decide which values of lambda to use
+nlambdas = 20
+OwnMSEPredict = np.zeros(nlambdas)
+OwnMSETrain = np.zeros(nlambdas)
+MSERidgePredict = np.zeros(nlambdas)
+lambdas = np.logspace(-4, 1, nlambdas)
+for i in range(nlambdas):
+ lmb = lambdas[i]
+ OwnRidgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train
+ # and then make the prediction
+ OwnytildeRidge = X_train @ OwnRidgebeta
+ OwnypredictRidge = X_test @ OwnRidgebeta
+ OwnMSEPredict[i] = MSE(y_test,OwnypredictRidge)
+ OwnMSETrain[i] = MSE(y_train,OwnytildeRidge)
+ # Make the fit using Ridge from Sklearn
+ RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
+ RegRidge.fit(X_train,y_train)
+ # and then make the prediction
+ ypredictRidge = RegRidge.predict(X_test)
+ # Compute the MSE and print it
+ MSERidgePredict[i] = MSE(y_test,ypredictRidge)
+
+# Now plot the results
+plt.figure()
+plt.plot(np.log10(lambdas), OwnMSETrain, label = 'MSE Ridge train, Own code')
+plt.plot(np.log10(lambdas), OwnMSEPredict, 'r--', label = 'MSE Ridge Test, Own code')
+plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE Ridge Test, Sklearn code')
+plt.xlabel('log10(lambda)')
+plt.ylabel('MSE')
+plt.legend()
+plt.show()
+In this exercise we derive the expressions for various derivatives of +products of vectors and matrices. Such derivatives are central to the +optimization of various cost functions. Although we will often use +automatic differentiation in actual calculations, to be able to have +analytical expressions is extremely helpful in case we have simpler +derivatives as well as when we analyze various properties (like second +derivatives) of the chosen cost functions. Vectors are always written +as boldfaced lower case letters and matrices as upper case boldfaced +letters.
+Show that
+and
+and
+and finally find the second derivative of this function with respect to the vector \(\boldsymbol{s}\).
+ +Solution. +In these exercises it is always useful to write out with summation indices the various quantities. +As an example, consider the function
+which reads for a specific component \(f_i\) (we define the matrix \(\boldsymbol{A}\) to have dimension \(n\times n\) and the vector \(\boldsymbol{x}\) to have length \(n\))
+which leads to
+and written out in terms of the vector \(\boldsymbol{x}\) we have
+For the first derivative
+we can write out the inner product as (assuming all elements are real)
+taking the derivative
+leading to
+For the second exercise we have
+Defining a vector \(\boldsymbol{f}=\boldsymbol{A}\boldsymbol{a}\) with components \(f_i=\sum_ja_{ij}a_i\) we have
+since \(f\) depends on \(a\) and we have used the chain rule for derivatives on the derivative of \(f\) with respect to \(a\).
+