update chapter 1
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 6.4 KiB After Width: | Height: | Size: 6.4 KiB |
|
Before Width: | Height: | Size: 9.2 KiB After Width: | Height: | Size: 9.3 KiB |
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 9.3 KiB After Width: | Height: | Size: 9.8 KiB |
@@ -396,23 +396,31 @@ const thebe_selector_output = ".output, .cell_output"
|
||||
<a class="reference internal nav-link" href="#exercises">
|
||||
3.10. Exercises
|
||||
</a>
|
||||
<ul class="nav section-nav flex-column">
|
||||
<li class="toc-h3 nav-item toc-entry">
|
||||
<a class="reference internal nav-link" href="#exercise-setting-up-various-python-environments">
|
||||
3.10.1. Exercise: Setting up various Python environments
|
||||
</a>
|
||||
</li>
|
||||
<li class="toc-h3 nav-item toc-entry">
|
||||
<a class="reference internal nav-link" href="#exercise-making-your-own-data-and-exploring-scikit-learn">
|
||||
3.10.2. Exercise: making your own data and exploring scikit-learn
|
||||
</a>
|
||||
</li>
|
||||
<li class="toc-h3 nav-item toc-entry">
|
||||
<a class="reference internal nav-link" href="#exercise-normalizing-our-data">
|
||||
3.10.3. Exercise: Normalizing our data
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toc-h2 nav-item toc-entry">
|
||||
<a class="reference internal nav-link" href="#exercise-1-setting-up-various-python-environments">
|
||||
3.11. Exercise 1: Setting up various Python environments
|
||||
</a>
|
||||
</li>
|
||||
<li class="toc-h2 nav-item toc-entry">
|
||||
<a class="reference internal nav-link" href="#exercise-2-making-your-own-data-and-exploring-scikit-learn">
|
||||
3.12. Exercise 2: making your own data and exploring scikit-learn
|
||||
</a>
|
||||
</li>
|
||||
<li class="toc-h2 nav-item toc-entry">
|
||||
<a class="reference internal nav-link" href="#exercise-3-normalizing-our-data">
|
||||
3.13. Exercise 3: Normalizing our data
|
||||
</a>
|
||||
</li>
|
||||
<li class="toc-h2 nav-item toc-entry">
|
||||
<a class="reference internal nav-link" href="#exercise-4-adding-ridge-regression">
|
||||
3.14. Exercise 4: Adding Ridge Regression
|
||||
</a>
|
||||
</li>
|
||||
<li class="toc-h2 nav-item toc-entry">
|
||||
<a class="reference internal nav-link" href="#exercise-5-analytical-exercises">
|
||||
3.15. Exercise 5: Analytical exercises
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
@@ -521,23 +529,31 @@ const thebe_selector_output = ".output, .cell_output"
|
||||
<a class="reference internal nav-link" href="#exercises">
|
||||
3.10. Exercises
|
||||
</a>
|
||||
<ul class="nav section-nav flex-column">
|
||||
<li class="toc-h3 nav-item toc-entry">
|
||||
<a class="reference internal nav-link" href="#exercise-setting-up-various-python-environments">
|
||||
3.10.1. Exercise: Setting up various Python environments
|
||||
</a>
|
||||
</li>
|
||||
<li class="toc-h3 nav-item toc-entry">
|
||||
<a class="reference internal nav-link" href="#exercise-making-your-own-data-and-exploring-scikit-learn">
|
||||
3.10.2. Exercise: making your own data and exploring scikit-learn
|
||||
</a>
|
||||
</li>
|
||||
<li class="toc-h3 nav-item toc-entry">
|
||||
<a class="reference internal nav-link" href="#exercise-normalizing-our-data">
|
||||
3.10.3. Exercise: Normalizing our data
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toc-h2 nav-item toc-entry">
|
||||
<a class="reference internal nav-link" href="#exercise-1-setting-up-various-python-environments">
|
||||
3.11. Exercise 1: Setting up various Python environments
|
||||
</a>
|
||||
</li>
|
||||
<li class="toc-h2 nav-item toc-entry">
|
||||
<a class="reference internal nav-link" href="#exercise-2-making-your-own-data-and-exploring-scikit-learn">
|
||||
3.12. Exercise 2: making your own data and exploring scikit-learn
|
||||
</a>
|
||||
</li>
|
||||
<li class="toc-h2 nav-item toc-entry">
|
||||
<a class="reference internal nav-link" href="#exercise-3-normalizing-our-data">
|
||||
3.13. Exercise 3: Normalizing our data
|
||||
</a>
|
||||
</li>
|
||||
<li class="toc-h2 nav-item toc-entry">
|
||||
<a class="reference internal nav-link" href="#exercise-4-adding-ridge-regression">
|
||||
3.14. Exercise 4: Adding Ridge Regression
|
||||
</a>
|
||||
</li>
|
||||
<li class="toc-h2 nav-item toc-entry">
|
||||
<a class="reference internal nav-link" href="#exercise-5-analytical-exercises">
|
||||
3.15. Exercise 5: Analytical exercises
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
@@ -938,13 +954,13 @@ example of the functionality of <strong>Scikit-Learn</strong>.</p>
|
||||
</div>
|
||||
<div class="cell_output docutils container">
|
||||
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>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
|
||||
</pre></div>
|
||||
</div>
|
||||
<img alt="_images/chapter1_19_1.png" src="_images/chapter1_19_1.png" />
|
||||
@@ -1044,7 +1060,7 @@ a linear <span class="math notranslate nohighlight">\(x\)</span>-dependence we s
|
||||
</div>
|
||||
<div class="cell_output docutils container">
|
||||
<img alt="_images/chapter1_33_0.png" src="_images/chapter1_33_0.png" />
|
||||
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>0.004999999999999996
|
||||
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>0.005000000000000011
|
||||
</pre></div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1748,27 +1764,27 @@ allow for the usage of direct linear algebra methods such as <strong>LU</strong>
|
||||
matrices as upper case boldfaced letters.</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
\frac{\partial\boldsymbol{b}^T\boldsymbol{a}}{\partial\boldsymbol{a}}=\boldsymbol{b},
|
||||
\frac{\partial (\boldsymbol{b}^T\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{b},
|
||||
\]</div>
|
||||
<p>and</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
\frac{\partial\boldsymbol{a}^T\boldsymbol{A}\boldsymbol{a}}{\partial\boldsymbol{a}}=(\boldsymbol{A}+\boldsymbol{A}^T)\boldsymbol{a},
|
||||
\frac{\partial (\boldsymbol{a}^T\boldsymbol{A}\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{a}^T(\boldsymbol{A}+\boldsymbol{A}^T),
|
||||
\]</div>
|
||||
<p>and</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
\frac{\partial tr(\boldsymbol{B}\boldsymbol{A})}{\partial\boldsymbol{A}}=\boldsymbol{B}^T,
|
||||
\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},
|
||||
\]</div>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
\frac{\partial\log{\vert\boldsymbol{A}\vert}}{\partial \boldsymbol{A}}=(\boldsymbol{A}^{-1})^T.
|
||||
\]</div>
|
||||
<p>We can then compute the second derivative of the cost function, which in our case is the second derivative
|
||||
<p>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</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
\frac{\partial^2 C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}^T\partial \boldsymbol{\beta}} =\frac{2}{n}\boldsymbol{X}^T\boldsymbol{X}.
|
||||
\]</div>
|
||||
<p>This quantity defines was what is called the Hessian matrix (the second derivative of a function we want to optimize).</p>
|
||||
<p>This quantity defines the so- called the Hessian matrix.</p>
|
||||
<p>The Hessian matrix plays an important role and is defined for the mean squared error as</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
@@ -2606,8 +2622,9 @@ ourmodel (here in terms of the polynomial degree of the model).</p>
|
||||
</div>
|
||||
<div class="section" id="exercises">
|
||||
<h2><span class="section-number">3.10. </span>Exercises<a class="headerlink" href="#exercises" title="Permalink to this headline">¶</a></h2>
|
||||
<div class="section" id="exercise-setting-up-various-python-environments">
|
||||
<h3><span class="section-number">3.10.1. </span>Exercise: Setting up various Python environments<a class="headerlink" href="#exercise-setting-up-various-python-environments" title="Permalink to this headline">¶</a></h3>
|
||||
</div>
|
||||
<div class="section" id="exercise-1-setting-up-various-python-environments">
|
||||
<h2><span class="section-number">3.11. </span>Exercise 1: Setting up various Python environments<a class="headerlink" href="#exercise-1-setting-up-various-python-environments" title="Permalink to this headline">¶</a></h2>
|
||||
<p>The first exercise here is of a mere technical art. We want you to have</p>
|
||||
<ul class="simple">
|
||||
<li><p>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 <a class="reference external" href="https://www.uio.no/tjenester/it/maskin/filer/versjonskontroll/github.html">GitHub facilities</a>.</p></li>
|
||||
@@ -2662,8 +2679,8 @@ analysis environment, available for free and under a commercial
|
||||
license.</p>
|
||||
<p>We recommend using <strong>Anaconda</strong> if you are not too familiar with setting paths in a terminal environment.</p>
|
||||
</div>
|
||||
<div class="section" id="exercise-making-your-own-data-and-exploring-scikit-learn">
|
||||
<h3><span class="section-number">3.10.2. </span>Exercise: making your own data and exploring scikit-learn<a class="headerlink" href="#exercise-making-your-own-data-and-exploring-scikit-learn" title="Permalink to this headline">¶</a></h3>
|
||||
<div class="section" id="exercise-2-making-your-own-data-and-exploring-scikit-learn">
|
||||
<h2><span class="section-number">3.12. </span>Exercise 2: making your own data and exploring scikit-learn<a class="headerlink" href="#exercise-2-making-your-own-data-and-exploring-scikit-learn" title="Permalink to this headline">¶</a></h2>
|
||||
<p>We will generate our own dataset for a function <span class="math notranslate nohighlight">\(y(x)\)</span> where <span class="math notranslate nohighlight">\(x \in [0,1]\)</span> and defined by random numbers computed with the uniform distribution. The function <span class="math notranslate nohighlight">\(y\)</span> is a quadratic polynomial in <span class="math notranslate nohighlight">\(x\)</span> with added stochastic noise according to the normal distribution <span class="math notranslate nohighlight">\(\cal {N}(0,1)\)</span>.
|
||||
The following simple Python instructions define our <span class="math notranslate nohighlight">\(x\)</span> and <span class="math notranslate nohighlight">\(y\)</span> values (with 100 data points).</p>
|
||||
<div class="cell docutils container">
|
||||
@@ -2676,7 +2693,7 @@ The following simple Python instructions define our <span class="math notranslat
|
||||
</div>
|
||||
<ol class="simple">
|
||||
<li><p>Write your own code (following the examples under the <a class="reference external" href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter1.html">regression notes</a>) for computing the parametrization of the data set fitting a second-order polynomial.</p></li>
|
||||
<li><p>Use thereafter <strong>scikit-learn</strong> (see again the examples in the regression slides) and compare with your own code.</p></li>
|
||||
<li><p>Use thereafter <strong>scikit-learn</strong> (see again the examples in the regression slides) and compare with your own code. When compairing with <em>scikit_learn</em>, make sure you set the option for the intercept to <strong>FALSE</strong>, see <a class="reference external" href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html">https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html</a>. This feature will be explained in more detail during the lectures of week 35 and week 36. You can find more in <a class="reference external" href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#more-on-rescaling-data">https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#more-on-rescaling-data</a>.</p></li>
|
||||
<li><p>Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as</p></li>
|
||||
</ol>
|
||||
<div class="math notranslate nohighlight">
|
||||
@@ -2697,9 +2714,58 @@ R^2(\boldsymbol{y}, \tilde{\boldsymbol{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i
|
||||
\]</div>
|
||||
<p>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.</p>
|
||||
<!-- --- begin solution of exercise --- -->
|
||||
<p><strong>Solution.</strong>
|
||||
The code here is an example of where we define our own design matrix and fit parameters <span class="math notranslate nohighlight">\(\beta\)</span>.</p>
|
||||
<div class="cell docutils container">
|
||||
<div class="cell_input docutils container">
|
||||
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>
|
||||
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
|
||||
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
|
||||
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>
|
||||
<span class="kn">from</span> <span class="nn">sklearn.model_selection</span> <span class="kn">import</span> <span class="n">train_test_split</span>
|
||||
|
||||
<span class="k">def</span> <span class="nf">save_fig</span><span class="p">(</span><span class="n">fig_id</span><span class="p">):</span>
|
||||
<span class="n">plt</span><span class="o">.</span><span class="n">savefig</span><span class="p">(</span><span class="n">image_path</span><span class="p">(</span><span class="n">fig_id</span><span class="p">)</span> <span class="o">+</span> <span class="s2">".png"</span><span class="p">,</span> <span class="nb">format</span><span class="o">=</span><span class="s1">'png'</span><span class="p">)</span>
|
||||
|
||||
<span class="k">def</span> <span class="nf">R2</span><span class="p">(</span><span class="n">y_data</span><span class="p">,</span> <span class="n">y_model</span><span class="p">):</span>
|
||||
<span class="k">return</span> <span class="mi">1</span> <span class="o">-</span> <span class="n">np</span><span class="o">.</span><span class="n">sum</span><span class="p">((</span><span class="n">y_data</span> <span class="o">-</span> <span class="n">y_model</span><span class="p">)</span> <span class="o">**</span> <span class="mi">2</span><span class="p">)</span> <span class="o">/</span> <span class="n">np</span><span class="o">.</span><span class="n">sum</span><span class="p">((</span><span class="n">y_data</span> <span class="o">-</span> <span class="n">np</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">y_data</span><span class="p">))</span> <span class="o">**</span> <span class="mi">2</span><span class="p">)</span>
|
||||
<span class="k">def</span> <span class="nf">MSE</span><span class="p">(</span><span class="n">y_data</span><span class="p">,</span><span class="n">y_model</span><span class="p">):</span>
|
||||
<span class="n">n</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">size</span><span class="p">(</span><span class="n">y_model</span><span class="p">)</span>
|
||||
<span class="k">return</span> <span class="n">np</span><span class="o">.</span><span class="n">sum</span><span class="p">((</span><span class="n">y_data</span><span class="o">-</span><span class="n">y_model</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span><span class="o">/</span><span class="n">n</span>
|
||||
|
||||
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">rand</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
|
||||
<span class="n">y</span> <span class="o">=</span> <span class="mf">2.0</span><span class="o">+</span><span class="mi">5</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">+</span><span class="mf">0.1</span><span class="o">*</span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randn</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
|
||||
|
||||
|
||||
<span class="c1"># The design matrix now as function of a given polynomial</span>
|
||||
<span class="n">X</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">((</span><span class="nb">len</span><span class="p">(</span><span class="n">x</span><span class="p">),</span><span class="mi">3</span><span class="p">))</span>
|
||||
<span class="n">X</span><span class="p">[:,</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="mf">1.0</span>
|
||||
<span class="n">X</span><span class="p">[:,</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="n">x</span>
|
||||
<span class="n">X</span><span class="p">[:,</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="n">x</span><span class="o">**</span><span class="mi">2</span>
|
||||
<span class="c1"># We split the data in test and training data</span>
|
||||
<span class="n">X_train</span><span class="p">,</span> <span class="n">X_test</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">y_test</span> <span class="o">=</span> <span class="n">train_test_split</span><span class="p">(</span><span class="n">X</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">test_size</span><span class="o">=</span><span class="mf">0.2</span><span class="p">)</span>
|
||||
<span class="c1"># matrix inversion to find beta</span>
|
||||
<span class="n">beta</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">linalg</span><span class="o">.</span><span class="n">inv</span><span class="p">(</span><span class="n">X_train</span><span class="o">.</span><span class="n">T</span> <span class="o">@</span> <span class="n">X_train</span><span class="p">)</span> <span class="o">@</span> <span class="n">X_train</span><span class="o">.</span><span class="n">T</span> <span class="o">@</span> <span class="n">y_train</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="n">beta</span><span class="p">)</span>
|
||||
<span class="c1"># and then make the prediction</span>
|
||||
<span class="n">ytilde</span> <span class="o">=</span> <span class="n">X_train</span> <span class="o">@</span> <span class="n">beta</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="s2">"Training R2"</span><span class="p">)</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="n">R2</span><span class="p">(</span><span class="n">y_train</span><span class="p">,</span><span class="n">ytilde</span><span class="p">))</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="s2">"Training MSE"</span><span class="p">)</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="n">MSE</span><span class="p">(</span><span class="n">y_train</span><span class="p">,</span><span class="n">ytilde</span><span class="p">))</span>
|
||||
<span class="n">ypredict</span> <span class="o">=</span> <span class="n">X_test</span> <span class="o">@</span> <span class="n">beta</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="s2">"Test R2"</span><span class="p">)</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="n">R2</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span><span class="n">ypredict</span><span class="p">))</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="s2">"Test MSE"</span><span class="p">)</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="n">MSE</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span><span class="n">ypredict</span><span class="p">))</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<div class="section" id="exercise-normalizing-our-data">
|
||||
<h3><span class="section-number">3.10.3. </span>Exercise: Normalizing our data<a class="headerlink" href="#exercise-normalizing-our-data" title="Permalink to this headline">¶</a></h3>
|
||||
</div>
|
||||
</div>
|
||||
<!-- --- end solution of exercise --- --></div>
|
||||
<div class="section" id="exercise-3-normalizing-our-data">
|
||||
<h2><span class="section-number">3.13. </span>Exercise 3: Normalizing our data<a class="headerlink" href="#exercise-3-normalizing-our-data" title="Permalink to this headline">¶</a></h2>
|
||||
<p>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 <span class="mat
|
||||
<div class="cell docutils container">
|
||||
<div class="cell_input docutils container">
|
||||
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># split in training and test data</span>
|
||||
<span class="c1"># X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)</span>
|
||||
<span class="n">X_train</span><span class="p">,</span> <span class="n">X_test</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">y_test</span> <span class="o">=</span> <span class="n">train_test_split</span><span class="p">(</span><span class="n">X</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="n">test_size</span><span class="o">=</span><span class="mf">0.2</span><span class="p">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -2768,21 +2834,273 @@ the aims is to reproduce Figure 2.11 of <a class="reference external" href="http
|
||||
</div>
|
||||
</div>
|
||||
<p>where <span class="math notranslate nohighlight">\(y\)</span> is the function we want to fit with a given polynomial.</p>
|
||||
<p>Write a first code which sets up a design matrix <span class="math notranslate nohighlight">\(X\)</span> defined by a
|
||||
fifth-order polynomial. Scale your data and split it in training and
|
||||
test data.</p>
|
||||
<p>Perform an ordinary least squares and compute the means squared error
|
||||
and the <span class="math notranslate nohighlight">\(R2\)</span> factor for the training data and the test data, with and
|
||||
without scaling.</p>
|
||||
<p>Add now a model which allows you to make polynomials up to degree
|
||||
<span class="math notranslate nohighlight">\(15\)</span>. Perform a standard OLS fitting of the training data and compute
|
||||
the MSE and <span class="math notranslate nohighlight">\(R2\)</span> for the training and test data and plot both test and
|
||||
training data MSE and <span class="math notranslate nohighlight">\(R2\)</span> 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)?</p>
|
||||
<!-- --- begin solution of exercise --- -->
|
||||
<p><strong>Solution.</strong>
|
||||
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 <strong>scikit-learn</strong>.</p>
|
||||
<div class="cell docutils container">
|
||||
<div class="cell_input docutils container">
|
||||
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>
|
||||
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
|
||||
<span class="kn">from</span> <span class="nn">sklearn.linear_model</span> <span class="kn">import</span> <span class="n">LinearRegression</span><span class="p">,</span> <span class="n">Ridge</span><span class="p">,</span> <span class="n">Lasso</span>
|
||||
<span class="kn">from</span> <span class="nn">sklearn.preprocessing</span> <span class="kn">import</span> <span class="n">PolynomialFeatures</span>
|
||||
<span class="kn">from</span> <span class="nn">sklearn.model_selection</span> <span class="kn">import</span> <span class="n">train_test_split</span>
|
||||
<span class="kn">from</span> <span class="nn">sklearn.pipeline</span> <span class="kn">import</span> <span class="n">make_pipeline</span>
|
||||
|
||||
|
||||
<span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">2018</span><span class="p">)</span>
|
||||
<span class="n">n</span> <span class="o">=</span> <span class="mi">30</span>
|
||||
<span class="n">maxdegree</span> <span class="o">=</span> <span class="mi">14</span>
|
||||
<span class="c1"># Make data set.</span>
|
||||
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">linspace</span><span class="p">(</span><span class="o">-</span><span class="mi">3</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="n">n</span><span class="p">)</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
|
||||
<span class="n">y</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="o">-</span><span class="n">x</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span> <span class="o">+</span> <span class="mf">1.5</span> <span class="o">*</span> <span class="n">np</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="o">-</span><span class="p">(</span><span class="n">x</span><span class="o">-</span><span class="mi">2</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span><span class="o">+</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">normal</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mf">0.1</span><span class="p">,</span> <span class="n">x</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span>
|
||||
<span class="n">TestError</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">maxdegree</span><span class="p">)</span>
|
||||
<span class="n">TrainError</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">maxdegree</span><span class="p">)</span>
|
||||
<span class="n">polydegree</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">maxdegree</span><span class="p">)</span>
|
||||
<span class="n">x_train</span><span class="p">,</span> <span class="n">x_test</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">y_test</span> <span class="o">=</span> <span class="n">train_test_split</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">test_size</span><span class="o">=</span><span class="mf">0.2</span><span class="p">)</span>
|
||||
|
||||
|
||||
<span class="k">for</span> <span class="n">degree</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">maxdegree</span><span class="p">):</span>
|
||||
<span class="n">model</span> <span class="o">=</span> <span class="n">make_pipeline</span><span class="p">(</span><span class="n">PolynomialFeatures</span><span class="p">(</span><span class="n">degree</span><span class="o">=</span><span class="n">degree</span><span class="p">),</span> <span class="n">LinearRegression</span><span class="p">(</span><span class="n">fit_intercept</span><span class="o">=</span><span class="kc">False</span><span class="p">))</span>
|
||||
<span class="n">clf</span> <span class="o">=</span> <span class="n">model</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">x_train</span><span class="p">,</span><span class="n">y_train</span><span class="p">)</span>
|
||||
<span class="n">y_fit</span> <span class="o">=</span> <span class="n">clf</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">x_train</span><span class="p">)</span>
|
||||
<span class="n">y_pred</span> <span class="o">=</span> <span class="n">clf</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">x_test</span><span class="p">)</span>
|
||||
<span class="n">polydegree</span><span class="p">[</span><span class="n">degree</span><span class="p">]</span> <span class="o">=</span> <span class="n">degree</span>
|
||||
<span class="n">TestError</span><span class="p">[</span><span class="n">degree</span><span class="p">]</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span> <span class="n">np</span><span class="o">.</span><span class="n">mean</span><span class="p">((</span><span class="n">y_test</span> <span class="o">-</span> <span class="n">y_pred</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span> <span class="p">)</span>
|
||||
<span class="n">TrainError</span><span class="p">[</span><span class="n">degree</span><span class="p">]</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span> <span class="n">np</span><span class="o">.</span><span class="n">mean</span><span class="p">((</span><span class="n">y_train</span> <span class="o">-</span> <span class="n">y_fit</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span> <span class="p">)</span>
|
||||
|
||||
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">polydegree</span><span class="p">,</span> <span class="n">TestError</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s1">'Test Error'</span><span class="p">)</span>
|
||||
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">polydegree</span><span class="p">,</span> <span class="n">TrainError</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s1">'Train Error'</span><span class="p">)</span>
|
||||
<span class="n">plt</span><span class="o">.</span><span class="n">legend</span><span class="p">()</span>
|
||||
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- --- end solution of exercise --- --><p><strong>a)</strong>
|
||||
Write a first code which sets up a design matrix <span class="math notranslate nohighlight">\(X\)</span> defined by a fifth-order polynomial. Scale your data and split it in training and test data.</p>
|
||||
<p><strong>b)</strong>
|
||||
Perform an ordinary least squares and compute the means squared error and the <span class="math notranslate nohighlight">\(R2\)</span> factor for the training data and the test data, with and without scaling.</p>
|
||||
<p><strong>c)</strong>
|
||||
Add now a model which allows you to make polynomials up to degree <span class="math notranslate nohighlight">\(15\)</span>. Perform a standard OLS fitting of the training data and compute the MSE and <span class="math notranslate nohighlight">\(R2\)</span> for the training and test data and plot both test and training data MSE and <span class="math notranslate nohighlight">\(R2\)</span> 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)?</p>
|
||||
</div>
|
||||
<div class="section" id="exercise-4-adding-ridge-regression">
|
||||
<h2><span class="section-number">3.14. </span>Exercise 4: Adding Ridge Regression<a class="headerlink" href="#exercise-4-adding-ridge-regression" title="Permalink to this headline">¶</a></h2>
|
||||
<p>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 <span class="math notranslate nohighlight">\(y(x)\)</span>
|
||||
which we want to fit using linear regression, but now extending the
|
||||
analysis to include the Ridge regression method.</p>
|
||||
<p>We will thus again generate our own dataset for a function <span class="math notranslate nohighlight">\(y(x)\)</span> where
|
||||
<span class="math notranslate nohighlight">\(x \in [0,1]\)</span> and defined by random numbers computed with the uniform
|
||||
distribution. The function <span class="math notranslate nohighlight">\(y\)</span> is a quadratic polynomial in <span class="math notranslate nohighlight">\(x\)</span> with
|
||||
added stochastic noise according to the normal distribution <span class="math notranslate nohighlight">\(\cal{N}(0,1)\)</span>.</p>
|
||||
<p>The following simple Python instructions define our <span class="math notranslate nohighlight">\(x\)</span> and <span class="math notranslate nohighlight">\(y\)</span> values (with 100 data points).</p>
|
||||
<div class="cell docutils container">
|
||||
<div class="cell_input docutils container">
|
||||
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">rand</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
|
||||
<span class="n">y</span> <span class="o">=</span> <span class="mf">2.0</span><span class="o">+</span><span class="mi">5</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">+</span><span class="mf">0.1</span><span class="o">*</span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randn</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p>Write your own code for the Ridge method (see chapter 3.4 of Hastie <em>et al.</em>, equations (3.43) and (3.44)) and compute the parametrization for different values of <span class="math notranslate nohighlight">\(\lambda\)</span>. Compare and analyze your results with those from exercise 3. Study the dependence on <span class="math notranslate nohighlight">\(\lambda\)</span> while also varying the strength of the noise in your expression for <span class="math notranslate nohighlight">\(y(x)\)</span>.</p>
|
||||
<p>Repeat the above but using the functionality of
|
||||
<strong>Scikit-Learn</strong>. Compare your code with the results from
|
||||
<strong>Scikit-Learn</strong>. Remember to run with the same random numbers for
|
||||
generating <span class="math notranslate nohighlight">\(x\)</span> and <span class="math notranslate nohighlight">\(y\)</span>. Observe also that when you compare with <strong>Scikit-Learn</strong>, you need to pay attention to how the intercept is dealt with.</p>
|
||||
<p>Finally, using <strong>Scikit-Learn</strong> 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</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
|
||||
\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
|
||||
\]</div>
|
||||
<p>and the <span class="math notranslate nohighlight">\(R^2\)</span> score function.
|
||||
If <span class="math notranslate nohighlight">\(\tilde{\hat{y}}_i\)</span> is the predicted value of the <span class="math notranslate nohighlight">\(i-th\)</span> sample and <span class="math notranslate nohighlight">\(y_i\)</span> is the corresponding true value, then the score <span class="math notranslate nohighlight">\(R^2\)</span> is defined as</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
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},
|
||||
\]</div>
|
||||
<p>where we have defined the mean value of <span class="math notranslate nohighlight">\(\hat{y}\)</span> as</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
|
||||
\]</div>
|
||||
<p>Discuss these quantities as functions of the variable <span class="math notranslate nohighlight">\(\lambda\)</span> in Ridge regression.</p>
|
||||
<!-- --- begin solution of exercise --- -->
|
||||
<p><strong>Solution.</strong>
|
||||
The code here allows you to perform your own Ridge calculation and
|
||||
perform calculations for various values of the regularization
|
||||
parameter <span class="math notranslate nohighlight">\(\lambda\)</span>. This program can easily be extended upon.</p>
|
||||
<div class="cell docutils container">
|
||||
<div class="cell_input docutils container">
|
||||
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>
|
||||
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
|
||||
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
|
||||
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>
|
||||
<span class="kn">from</span> <span class="nn">sklearn.model_selection</span> <span class="kn">import</span> <span class="n">train_test_split</span>
|
||||
<span class="kn">from</span> <span class="nn">sklearn.preprocessing</span> <span class="kn">import</span> <span class="n">StandardScaler</span>
|
||||
<span class="kn">from</span> <span class="nn">sklearn</span> <span class="kn">import</span> <span class="n">linear_model</span>
|
||||
|
||||
<span class="k">def</span> <span class="nf">R2</span><span class="p">(</span><span class="n">y_data</span><span class="p">,</span> <span class="n">y_model</span><span class="p">):</span>
|
||||
<span class="k">return</span> <span class="mi">1</span> <span class="o">-</span> <span class="n">np</span><span class="o">.</span><span class="n">sum</span><span class="p">((</span><span class="n">y_data</span> <span class="o">-</span> <span class="n">y_model</span><span class="p">)</span> <span class="o">**</span> <span class="mi">2</span><span class="p">)</span> <span class="o">/</span> <span class="n">np</span><span class="o">.</span><span class="n">sum</span><span class="p">((</span><span class="n">y_data</span> <span class="o">-</span> <span class="n">np</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">y_data</span><span class="p">))</span> <span class="o">**</span> <span class="mi">2</span><span class="p">)</span>
|
||||
<span class="k">def</span> <span class="nf">MSE</span><span class="p">(</span><span class="n">y_data</span><span class="p">,</span><span class="n">y_model</span><span class="p">):</span>
|
||||
<span class="n">n</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">size</span><span class="p">(</span><span class="n">y_model</span><span class="p">)</span>
|
||||
<span class="k">return</span> <span class="n">np</span><span class="o">.</span><span class="n">sum</span><span class="p">((</span><span class="n">y_data</span><span class="o">-</span><span class="n">y_model</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span><span class="o">/</span><span class="n">n</span>
|
||||
|
||||
|
||||
<span class="c1"># A seed just to ensure that the random numbers are the same for every run.</span>
|
||||
<span class="c1"># Useful for eventual debugging.</span>
|
||||
<span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">3155</span><span class="p">)</span>
|
||||
|
||||
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">rand</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
|
||||
<span class="n">y</span> <span class="o">=</span> <span class="mf">2.0</span><span class="o">+</span><span class="mi">5</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">+</span><span class="mf">0.1</span><span class="o">*</span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randn</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
|
||||
|
||||
<span class="c1"># number of features p (here degree of polynomial</span>
|
||||
<span class="n">p</span> <span class="o">=</span> <span class="mi">3</span>
|
||||
<span class="c1"># The design matrix now as function of a given polynomial</span>
|
||||
<span class="n">X</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">((</span><span class="nb">len</span><span class="p">(</span><span class="n">x</span><span class="p">),</span><span class="n">p</span><span class="p">))</span>
|
||||
<span class="n">X</span><span class="p">[:,</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="mf">1.0</span>
|
||||
<span class="n">X</span><span class="p">[:,</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="n">x</span>
|
||||
<span class="n">X</span><span class="p">[:,</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span>
|
||||
<span class="c1"># We split the data in test and training data</span>
|
||||
<span class="n">X_train</span><span class="p">,</span> <span class="n">X_test</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">y_test</span> <span class="o">=</span> <span class="n">train_test_split</span><span class="p">(</span><span class="n">X</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">test_size</span><span class="o">=</span><span class="mf">0.2</span><span class="p">)</span>
|
||||
|
||||
<span class="c1"># matrix inversion to find beta</span>
|
||||
<span class="n">OLSbeta</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">linalg</span><span class="o">.</span><span class="n">inv</span><span class="p">(</span><span class="n">X_train</span><span class="o">.</span><span class="n">T</span> <span class="o">@</span> <span class="n">X_train</span><span class="p">)</span> <span class="o">@</span> <span class="n">X_train</span><span class="o">.</span><span class="n">T</span> <span class="o">@</span> <span class="n">y_train</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="n">OLSbeta</span><span class="p">)</span>
|
||||
<span class="c1"># and then make the prediction</span>
|
||||
<span class="n">ytildeOLS</span> <span class="o">=</span> <span class="n">X_train</span> <span class="o">@</span> <span class="n">OLSbeta</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="s2">"Training R2 for OLS"</span><span class="p">)</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="n">R2</span><span class="p">(</span><span class="n">y_train</span><span class="p">,</span><span class="n">ytildeOLS</span><span class="p">))</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="s2">"Training MSE for OLS"</span><span class="p">)</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="n">MSE</span><span class="p">(</span><span class="n">y_train</span><span class="p">,</span><span class="n">ytildeOLS</span><span class="p">))</span>
|
||||
<span class="n">ypredictOLS</span> <span class="o">=</span> <span class="n">X_test</span> <span class="o">@</span> <span class="n">OLSbeta</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="s2">"Test R2 for OLS"</span><span class="p">)</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="n">R2</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span><span class="n">ypredictOLS</span><span class="p">))</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="s2">"Test MSE OLS"</span><span class="p">)</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="n">MSE</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span><span class="n">ypredictOLS</span><span class="p">))</span>
|
||||
|
||||
|
||||
<span class="c1"># Repeat now for Ridge regression and various values of the regularization parameter</span>
|
||||
<span class="n">I</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">eye</span><span class="p">(</span><span class="n">p</span><span class="p">,</span><span class="n">p</span><span class="p">)</span>
|
||||
<span class="c1"># Decide which values of lambda to use</span>
|
||||
<span class="n">nlambdas</span> <span class="o">=</span> <span class="mi">20</span>
|
||||
<span class="n">OwnMSEPredict</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">nlambdas</span><span class="p">)</span>
|
||||
<span class="n">OwnMSETrain</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">nlambdas</span><span class="p">)</span>
|
||||
<span class="n">MSERidgePredict</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">nlambdas</span><span class="p">)</span>
|
||||
<span class="n">lambdas</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">logspace</span><span class="p">(</span><span class="o">-</span><span class="mi">4</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">nlambdas</span><span class="p">)</span>
|
||||
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">nlambdas</span><span class="p">):</span>
|
||||
<span class="n">lmb</span> <span class="o">=</span> <span class="n">lambdas</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
|
||||
<span class="n">OwnRidgebeta</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">linalg</span><span class="o">.</span><span class="n">inv</span><span class="p">(</span><span class="n">X_train</span><span class="o">.</span><span class="n">T</span> <span class="o">@</span> <span class="n">X_train</span><span class="o">+</span><span class="n">lmb</span><span class="o">*</span><span class="n">I</span><span class="p">)</span> <span class="o">@</span> <span class="n">X_train</span><span class="o">.</span><span class="n">T</span> <span class="o">@</span> <span class="n">y_train</span>
|
||||
<span class="c1"># and then make the prediction</span>
|
||||
<span class="n">OwnytildeRidge</span> <span class="o">=</span> <span class="n">X_train</span> <span class="o">@</span> <span class="n">OwnRidgebeta</span>
|
||||
<span class="n">OwnypredictRidge</span> <span class="o">=</span> <span class="n">X_test</span> <span class="o">@</span> <span class="n">OwnRidgebeta</span>
|
||||
<span class="n">OwnMSEPredict</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">MSE</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span><span class="n">OwnypredictRidge</span><span class="p">)</span>
|
||||
<span class="n">OwnMSETrain</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">MSE</span><span class="p">(</span><span class="n">y_train</span><span class="p">,</span><span class="n">OwnytildeRidge</span><span class="p">)</span>
|
||||
<span class="c1"># Make the fit using Ridge from Sklearn</span>
|
||||
<span class="n">RegRidge</span> <span class="o">=</span> <span class="n">linear_model</span><span class="o">.</span><span class="n">Ridge</span><span class="p">(</span><span class="n">lmb</span><span class="p">,</span><span class="n">fit_intercept</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
|
||||
<span class="n">RegRidge</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X_train</span><span class="p">,</span><span class="n">y_train</span><span class="p">)</span>
|
||||
<span class="c1"># and then make the prediction</span>
|
||||
<span class="n">ypredictRidge</span> <span class="o">=</span> <span class="n">RegRidge</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">X_test</span><span class="p">)</span>
|
||||
<span class="c1"># Compute the MSE and print it</span>
|
||||
<span class="n">MSERidgePredict</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">MSE</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span><span class="n">ypredictRidge</span><span class="p">)</span>
|
||||
|
||||
<span class="c1"># Now plot the results</span>
|
||||
<span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">()</span>
|
||||
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">log10</span><span class="p">(</span><span class="n">lambdas</span><span class="p">),</span> <span class="n">OwnMSETrain</span><span class="p">,</span> <span class="n">label</span> <span class="o">=</span> <span class="s1">'MSE Ridge train, Own code'</span><span class="p">)</span>
|
||||
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">log10</span><span class="p">(</span><span class="n">lambdas</span><span class="p">),</span> <span class="n">OwnMSEPredict</span><span class="p">,</span> <span class="s1">'r--'</span><span class="p">,</span> <span class="n">label</span> <span class="o">=</span> <span class="s1">'MSE Ridge Test, Own code'</span><span class="p">)</span>
|
||||
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">log10</span><span class="p">(</span><span class="n">lambdas</span><span class="p">),</span> <span class="n">MSERidgePredict</span><span class="p">,</span> <span class="s1">'g--'</span><span class="p">,</span> <span class="n">label</span> <span class="o">=</span> <span class="s1">'MSE Ridge Test, Sklearn code'</span><span class="p">)</span>
|
||||
<span class="n">plt</span><span class="o">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s1">'log10(lambda)'</span><span class="p">)</span>
|
||||
<span class="n">plt</span><span class="o">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s1">'MSE'</span><span class="p">)</span>
|
||||
<span class="n">plt</span><span class="o">.</span><span class="n">legend</span><span class="p">()</span>
|
||||
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- --- end solution of exercise --- --></div>
|
||||
<div class="section" id="exercise-5-analytical-exercises">
|
||||
<h2><span class="section-number">3.15. </span>Exercise 5: Analytical exercises<a class="headerlink" href="#exercise-5-analytical-exercises" title="Permalink to this headline">¶</a></h2>
|
||||
<p>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.</p>
|
||||
<p>Show that</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
\frac{\partial (\boldsymbol{b}^T\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{b},
|
||||
\]</div>
|
||||
<p>and</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
\frac{\partial (\boldsymbol{a}^T\boldsymbol{A}\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{a}^T(\boldsymbol{A}+\boldsymbol{A}^T),
|
||||
\]</div>
|
||||
<p>and</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
\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},
|
||||
\]</div>
|
||||
<p>and finally find the second derivative of this function with respect to the vector <span class="math notranslate nohighlight">\(\boldsymbol{s}\)</span>.</p>
|
||||
<!-- --- begin solution of exercise --- -->
|
||||
<p><strong>Solution.</strong>
|
||||
In these exercises it is always useful to write out with summation indices the various quantities.
|
||||
As an example, consider the function</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
f(\boldsymbol{x}) =\boldsymbol{A}\boldsymbol{x},
|
||||
\]</div>
|
||||
<p>which reads for a specific component <span class="math notranslate nohighlight">\(f_i\)</span> (we define the matrix <span class="math notranslate nohighlight">\(\boldsymbol{A}\)</span> to have dimension <span class="math notranslate nohighlight">\(n\times n\)</span> and the vector <span class="math notranslate nohighlight">\(\boldsymbol{x}\)</span> to have length <span class="math notranslate nohighlight">\(n\)</span>)</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
f_i =\sum_{j=0}^{n-1}a_{ij}x_j,
|
||||
\]</div>
|
||||
<p>which leads to</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
\frac{\partial f_i}{\partial x_j}= a_{ij},
|
||||
\]</div>
|
||||
<p>and written out in terms of the vector <span class="math notranslate nohighlight">\(\boldsymbol{x}\)</span> we have</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
\frac{\partial f(\boldsymbol{x})}{\partial \boldsymbol{x}}= \boldsymbol{A}.
|
||||
\]</div>
|
||||
<p>For the first derivative</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
\frac{\partial (\boldsymbol{b}^T\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{b},
|
||||
\]</div>
|
||||
<p>we can write out the inner product as (assuming all elements are real)</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
\boldsymbol{b}^T\boldsymbol{a}=\sum_i b_ia_i,
|
||||
\]</div>
|
||||
<p>taking the derivative</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
\frac{\partial \left( \sum_i b_ia_i\right)}{\partial a_k}= b_k,
|
||||
\]</div>
|
||||
<p>leading to</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[\begin{split}
|
||||
\frac{\partial \boldsymbol{b}^T\boldsymbol{a}}{\partial \boldsymbol{a}}= \begin{bmatrix} b_0 \\ b_1 \\ b_2 \\ \dots \\ \dots \\ b_{n-1}\end{bmatrix} = \boldsymbol{b}.
|
||||
\end{split}\]</div>
|
||||
<p>For the second exercise we have</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
\frac{\partial (\boldsymbol{a}^T\boldsymbol{A}\boldsymbol{a})}{\partial \boldsymbol{a}}.
|
||||
\]</div>
|
||||
<p>Defining a vector <span class="math notranslate nohighlight">\(\boldsymbol{f}=\boldsymbol{A}\boldsymbol{a}\)</span> with components <span class="math notranslate nohighlight">\(f_i=\sum_ja_{ij}a_i\)</span> we have</p>
|
||||
<div class="math notranslate nohighlight">
|
||||
\[
|
||||
\frac{\partial (\boldsymbol{a}^T\boldsymbol{f})}{\partial \boldsymbol{a}}=\boldsymbol{a}^T\boldsymbol{A}+\boldsymbol{f}^T=\boldsymbol{a}^T\left(\boldsymbol{A}+\boldsymbol{A}^T\right),
|
||||
\]</div>
|
||||
<p>since <span class="math notranslate nohighlight">\(f\)</span> depends on <span class="math notranslate nohighlight">\(a\)</span> and we have used the chain rule for derivatives on the derivative of <span class="math notranslate nohighlight">\(f\)</span> with respect to <span class="math notranslate nohighlight">\(a\)</span>.</p>
|
||||
<!-- --- end solution of exercise --- --></div>
|
||||
</div>
|
||||
|
||||
<script type="text/x-thebe-config">
|
||||
|
||||
@@ -1269,21 +1269,23 @@ display(DesignMatrix)
|
||||
# matrices as upper case boldfaced letters.
|
||||
|
||||
# $$
|
||||
# \frac{\partial\boldsymbol{b}^T\boldsymbol{a}}{\partial\boldsymbol{a}}=\boldsymbol{b},
|
||||
# \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},
|
||||
# $$
|
||||
# and
|
||||
|
||||
# $$
|
||||
# \frac{\partial tr(\boldsymbol{B}\boldsymbol{A})}{\partial\boldsymbol{A}}=\boldsymbol{B}^T,
|
||||
# \frac{\partial (\boldsymbol{a}^T\boldsymbol{A}\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{a}^T(\boldsymbol{A}+\boldsymbol{A}^T),
|
||||
# $$
|
||||
|
||||
# and
|
||||
|
||||
# $$
|
||||
# \frac{\partial\log{\vert\boldsymbol{A}\vert}}{\partial \boldsymbol{A}}=(\boldsymbol{A}^{-1})^T.
|
||||
# \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},
|
||||
# $$
|
||||
|
||||
# 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
|
||||
|
||||
@@ -1291,7 +1293,7 @@ display(DesignMatrix)
|
||||
# \frac{\partial^2 C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}^T\partial \boldsymbol{\beta}} =\frac{2}{n}\boldsymbol{X}^T\boldsymbol{X}.
|
||||
# $$
|
||||
|
||||
# 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
|
||||
|
||||
@@ -2180,7 +2182,7 @@ plt.show()
|
||||
|
||||
# ## Exercises
|
||||
|
||||
# ### Exercise: Setting up various Python environments
|
||||
# ## Exercise 1: 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).
|
||||
@@ -2241,7 +2243,7 @@ plt.show()
|
||||
#
|
||||
# We recommend using **Anaconda** if you are not too familiar with setting paths in a terminal environment.
|
||||
|
||||
# ### Exercise: making your own data and exploring scikit-learn
|
||||
# ## Exercise 2: 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)$.
|
||||
# The following simple Python instructions define our $x$ and $y$ values (with 100 data points).
|
||||
@@ -2255,7 +2257,7 @@ y = 2.0+5*x*x+0.1*np.random.randn(100,1)
|
||||
|
||||
# 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.
|
||||
#
|
||||
# 2. Use thereafter **scikit-learn** (see again the examples in the regression slides) and compare with your own code.
|
||||
# 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 <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>.
|
||||
#
|
||||
# 3. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
|
||||
|
||||
@@ -2279,8 +2281,59 @@ y = 2.0+5*x*x+0.1*np.random.randn(100,1)
|
||||
|
||||
# You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions.
|
||||
# Discuss the meaning of these results. Try also to vary the coefficient in front of the added stochastic noise term and discuss the quality of the fits.
|
||||
#
|
||||
# <!-- --- begin solution of exercise --- -->
|
||||
# **Solution.**
|
||||
# The code here is an example of where we define our own design matrix and fit parameters $\beta$.
|
||||
|
||||
# ### Exercise: Normalizing our data
|
||||
# In[41]:
|
||||
|
||||
|
||||
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))
|
||||
|
||||
|
||||
# <!-- --- end solution of exercise --- -->
|
||||
|
||||
# ## Exercise 3: Normalizing our data
|
||||
#
|
||||
# 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
|
||||
@@ -2317,16 +2370,16 @@ y = 2.0+5*x*x+0.1*np.random.randn(100,1)
|
||||
# It also common to split the data in a **training** set and a **testing** set. A typical split is to use $80\%$ of the data for training and the rest
|
||||
# for testing. This can be done as follows with our design matrix $\boldsymbol{X}$ and data $\boldsymbol{y}$ (remember to import **scikit-learn**)
|
||||
|
||||
# In[41]:
|
||||
# In[42]:
|
||||
|
||||
|
||||
# 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)
|
||||
|
||||
|
||||
# Then we can use the standard scaler to scale our data as
|
||||
|
||||
# In[42]:
|
||||
# In[43]:
|
||||
|
||||
|
||||
scaler = StandardScaler()
|
||||
@@ -2344,7 +2397,7 @@ X_test_scaled = scaler.transform(X_test)
|
||||
#
|
||||
# Our data is defined by $x\in [-3,3]$ with a total of for example $100$ data points.
|
||||
|
||||
# In[43]:
|
||||
# In[44]:
|
||||
|
||||
|
||||
np.random.seed()
|
||||
@@ -2357,18 +2410,299 @@ 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.
|
||||
# <!-- --- begin solution of exercise --- -->
|
||||
# **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**.
|
||||
|
||||
# In[45]:
|
||||
|
||||
|
||||
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()
|
||||
|
||||
|
||||
# <!-- --- end solution of exercise --- -->
|
||||
|
||||
# **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)?
|
||||
|
||||
# ## Exercise 4: Adding Ridge Regression
|
||||
#
|
||||
# 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.
|
||||
# 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.
|
||||
#
|
||||
# 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)?
|
||||
# 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).
|
||||
|
||||
# In[46]:
|
||||
|
||||
|
||||
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
|
||||
|
||||
# $$
|
||||
# MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
|
||||
# \sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
|
||||
# $$
|
||||
|
||||
# and the $R^2$ score function.
|
||||
# If $\tilde{\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as
|
||||
|
||||
# $$
|
||||
# R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},
|
||||
# $$
|
||||
|
||||
# where we have defined the mean value of $\hat{y}$ as
|
||||
|
||||
# $$
|
||||
# \bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
|
||||
# $$
|
||||
|
||||
# Discuss these quantities as functions of the variable $\lambda$ in Ridge regression.
|
||||
#
|
||||
# <!-- --- begin solution of exercise --- -->
|
||||
# **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.
|
||||
|
||||
# In[47]:
|
||||
|
||||
|
||||
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()
|
||||
|
||||
|
||||
# <!-- --- end solution of exercise --- -->
|
||||
|
||||
# ## Exercise 5: 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
|
||||
|
||||
# $$
|
||||
# \frac{\partial (\boldsymbol{b}^T\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{b},
|
||||
# $$
|
||||
|
||||
# and
|
||||
|
||||
# $$
|
||||
# \frac{\partial (\boldsymbol{a}^T\boldsymbol{A}\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{a}^T(\boldsymbol{A}+\boldsymbol{A}^T),
|
||||
# $$
|
||||
|
||||
# and
|
||||
|
||||
# $$
|
||||
# \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},
|
||||
# $$
|
||||
|
||||
# and finally find the second derivative of this function with respect to the vector $\boldsymbol{s}$.
|
||||
#
|
||||
# <!-- --- begin solution of exercise --- -->
|
||||
# **Solution.**
|
||||
# In these exercises it is always useful to write out with summation indices the various quantities.
|
||||
# As an example, consider the function
|
||||
|
||||
# $$
|
||||
# f(\boldsymbol{x}) =\boldsymbol{A}\boldsymbol{x},
|
||||
# $$
|
||||
|
||||
# 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$)
|
||||
|
||||
# $$
|
||||
# f_i =\sum_{j=0}^{n-1}a_{ij}x_j,
|
||||
# $$
|
||||
|
||||
# which leads to
|
||||
|
||||
# $$
|
||||
# \frac{\partial f_i}{\partial x_j}= a_{ij},
|
||||
# $$
|
||||
|
||||
# and written out in terms of the vector $\boldsymbol{x}$ we have
|
||||
|
||||
# $$
|
||||
# \frac{\partial f(\boldsymbol{x})}{\partial \boldsymbol{x}}= \boldsymbol{A}.
|
||||
# $$
|
||||
|
||||
# For the first derivative
|
||||
|
||||
# $$
|
||||
# \frac{\partial (\boldsymbol{b}^T\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{b},
|
||||
# $$
|
||||
|
||||
# we can write out the inner product as (assuming all elements are real)
|
||||
|
||||
# $$
|
||||
# \boldsymbol{b}^T\boldsymbol{a}=\sum_i b_ia_i,
|
||||
# $$
|
||||
|
||||
# taking the derivative
|
||||
|
||||
# $$
|
||||
# \frac{\partial \left( \sum_i b_ia_i\right)}{\partial a_k}= b_k,
|
||||
# $$
|
||||
|
||||
# leading to
|
||||
|
||||
# $$
|
||||
# \frac{\partial \boldsymbol{b}^T\boldsymbol{a}}{\partial \boldsymbol{a}}= \begin{bmatrix} b_0 \\ b_1 \\ b_2 \\ \dots \\ \dots \\ b_{n-1}\end{bmatrix} = \boldsymbol{b}.
|
||||
# $$
|
||||
|
||||
# For the second exercise we have
|
||||
|
||||
# $$
|
||||
# \frac{\partial (\boldsymbol{a}^T\boldsymbol{A}\boldsymbol{a})}{\partial \boldsymbol{a}}.
|
||||
# $$
|
||||
|
||||
# Defining a vector $\boldsymbol{f}=\boldsymbol{A}\boldsymbol{a}$ with components $f_i=\sum_ja_{ij}a_i$ we have
|
||||
|
||||
# $$
|
||||
# \frac{\partial (\boldsymbol{a}^T\boldsymbol{f})}{\partial \boldsymbol{a}}=\boldsymbol{a}^T\boldsymbol{A}+\boldsymbol{f}^T=\boldsymbol{a}^T\left(\boldsymbol{A}+\boldsymbol{A}^T\right),
|
||||
# $$
|
||||
|
||||
# since $f$ depends on $a$ and we have used the chain rule for derivatives on the derivative of $f$ with respect to $a$.
|
||||
#
|
||||
# <!-- --- end solution of exercise --- -->
|
||||
|
||||
|
Before Width: | Height: | Size: 6.4 KiB After Width: | Height: | Size: 6.4 KiB |
|
Before Width: | Height: | Size: 9.2 KiB After Width: | Height: | Size: 9.3 KiB |
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 9.3 KiB After Width: | Height: | Size: 9.8 KiB |