From db75cfcd73aebf438e597bd8a25df7e069d3549a Mon Sep 17 00:00:00 2001 From: Morten Hjorth-Jensen Date: Tue, 30 Aug 2022 17:25:35 +0200 Subject: [PATCH] update --- .../Projects/Exercises/Exercisesweek35.do.txt | 527 ++++++++ .../Projects/Exercises/Exercisesweek35.ipynb | 1061 +++++++++++++++++ .../Exercisesweek35-checkpoint.ipynb | 814 +++++++++++++ 3 files changed, 2402 insertions(+) create mode 100644 doc/src/Projects/Exercises/Exercisesweek35.do.txt create mode 100644 doc/src/Projects/Exercises/Exercisesweek35.ipynb create mode 100644 doc/src/week35/.ipynb_checkpoints/Exercisesweek35-checkpoint.ipynb diff --git a/doc/src/Projects/Exercises/Exercisesweek35.do.txt b/doc/src/Projects/Exercises/Exercisesweek35.do.txt new file mode 100644 index 000000000..b156f23a1 --- /dev/null +++ b/doc/src/Projects/Exercises/Exercisesweek35.do.txt @@ -0,0 +1,527 @@ +TITLE: Exercises week 35 +AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +DATE: today + + +!split +===== Exercises for week 35 ===== + +The exercises here are meant to prepare you for work with project 1. The first exercise is a follow-up of exercise 2 from week 35 August 30-September 3). + +===== 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". +* Install various Python packages + +We will make extensive use of Python as programming language and its +myriad of available libraries. You will find +IPython/Jupyter notebooks invaluable in your work. You can run _R_ +codes in the Jupyter/IPython notebooks, with the immediate benefit of +visualizing your data. You can also use compiled languages like C++, +Rust, Fortran etc if you prefer. The focus in these lectures will be +on Python. + +If you have Python installed (we recommend Python3) and you feel +pretty familiar with installing different packages, we recommend that +you install the following Python packages via _pip_ as + +o pip install numpy scipy matplotlib ipython scikit-learn sympy pandas pillow + +For _Tensorflow_, we recommend following the instructions in the text of +"Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly":"http://shop.oreilly.com/product/0636920052289.do" + +We will come back to _tensorflow_ later. + +For Python3, replace _pip_ with _pip3_. + +For OSX users we recommend, after having installed Xcode, to +install _brew_. Brew allows for a seamless installation of additional +software via for example + +o brew install python3 + +For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution, +you can use _pip_ as well and simply install Python as + +o sudo apt-get install python3 (or python for Python2.7) + +If you don't want to perform these operations separately and venture +into the hassle of exploring how to set up dependencies and paths, we +recommend two widely used distrubutions which set up all relevant +dependencies for Python, namely + +* "Anaconda":"https://docs.anaconda.com/", + +which is an open source +distribution of the Python and R programming languages for large-scale +data processing, predictive analytics, and scientific computing, that +aims to simplify package management and deployment. Package versions +are managed by the package management system _conda_. + +* "Enthought canopy":"https://www.enthought.com/product/canopy/" + +is a Python +distribution for scientific and analytic computing distribution and +analysis environment, available for free and under a commercial +license. + +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 ===== + + +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). +!bc pycod +x = np.random.rand(100,1) +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. 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} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\] +!et +and the $R^2$ score function. +If $\tilde{\bm{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(\bm{y}, \tilde{\bm{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 $\bm{y}$ as +!bt +\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\] +!et +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 ===== + + +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 +suitable for the algorithms we want to employ. + +_Scikit-Learn_ has several functions which allow us to rescale the +data, normally resulting in much better results in terms of various +accuracy scores. The _StandardScaler_ function in _Scikit-Learn_ +ensures that for each feature/predictor we study the mean value is +zero and the variance is one (every column in the design/feature +matrix). This scaling has the drawback that it does not ensure that +we have a particular maximum or minimum in our data set. Another +function included in _Scikit-Learn_ is the _MinMaxScaler_ which +ensures that all features are exactly between $0$ and $1$. The + + +The _Normalizer_ scales each data +point such that the feature vector has a euclidean length of one. In other words, it +projects a data point on the circle (or sphere in the case of higher dimensions) with a +radius of 1. This means every data point is scaled by a different number (by the +inverse of it’s length). +This normalization is often used when only the direction (or angle) of the data matters, +not the length of the feature vector. + +The _RobustScaler_ works similarly to the StandardScaler in that it +ensures statistical properties for each feature that guarantee that +they are on the same scale. However, the RobustScaler uses the median +and quartiles, instead of mean and variance. This makes the +RobustScaler ignore data points that are very different from the rest +(like measurement errors). These odd data points are also called +outliers, and might often lead to trouble for other scaling +techniques. + + +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 $\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) +!ec +Then we can use the standard scaler to scale our data as +!bc pycod +scaler = StandardScaler() +scaler.fit(X_train) +X_train_scaled = scaler.transform(X_train) +X_test_scaled = scaler.transform(X_test) +!ec + + +In this exercise we want you to to compute the MSE for the training +data and the test data as function of the complexity of a polynomial, +that is the degree of a given polynomial. We want you also to compute the $R2$ score as function of the complexity of the model for both training data and test data. You should also run the calculation with and without scaling. + +One of +the aims is to reproduce Figure 2.11 of "Hastie et al":"https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf". + + + +Our data is defined by $x\in [-3,3]$ with a total of for example $100$ data points. +!bc pycod +np.random.seed() +n = 100 +maxdegree = 14 +# Make data set. +x = np.linspace(-3, 3, n).reshape(-1, 1) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) +!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 + + +!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 + + + + +===== 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. + + + +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}+\bm{A}^T)\bm{a}, +\] +!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}$. + +_Hint_: 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 +!bsol +For the first derivative +!bt +\[ +\frac{\partial (\bm{b}^T\bm{a})}{\partial \bm{a}} = \bm{b}, +\] +!et +we can write out the inner product as (assuming all elements are real) +!bt +\[ +\bm{b}^T\bm{a}=\sum_i b_ia_i, +\] +!et +taking the derivative +!bt +\[ +\frac{\partial \left( \sum_i b_ia_i\right)}{\partial a_k}= b_k, +\] +!et +leading to +!bt +\[ +\frac{\partial \bm{b}^T\bm{a}}{\partial \bm{a}}= \begin{bmatrix} b_0 \\ b_1 \\ b_2 \\ \dots \\ \dots \\ b_{n-1}\end{bmatrix} = \bm{b}. +\] +!et + +For the second exercise we have +!bt +\[ +\frac{\partial (\bm{a}^T\bm{A}\bm{a})}{\partial \bm{a}}. +\] +!et +Defining a vector $\bm{f}=\bm{A}\bm{a}$ with components $f_i=\sum_ja_{ij}a_i$ we have +!bt +\[ +\frac{\partial (\bm{a}^T\bm{f})}{\partial \bm{a}}=\bm{a}^T\bm{A}+\bm{f}^T=\bm{a}^T\left(\bm{A}+\bm{A}^T\right), +\] +!et +since $f$ depends on $a$ and we have used the chain rule for derivatives on the derivative of $f$ with respect to $a$. + + +!esol diff --git a/doc/src/Projects/Exercises/Exercisesweek35.ipynb b/doc/src/Projects/Exercises/Exercisesweek35.ipynb new file mode 100644 index 000000000..ef70778f8 --- /dev/null +++ b/doc/src/Projects/Exercises/Exercisesweek35.ipynb @@ -0,0 +1,1061 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "183246e3", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "b8ef9d73", + "metadata": { + "editable": true + }, + "source": [ + "# Exercises week 35\n", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", + "\n", + "Date: **Aug 30, 2022**\n", + "\n", + "Copyright 1999-2022, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license" + ] + }, + { + "cell_type": "markdown", + "id": "2d7ab0d9", + "metadata": { + "editable": true + }, + "source": [ + "## Exercises for week 35\n", + "\n", + "The exercises here are meant to prepare you for work with project 1. The first exercise is a follow-up of exercise 2 from week 35 August 30-September 3)." + ] + }, + { + "cell_type": "markdown", + "id": "90896979", + "metadata": { + "editable": true + }, + "source": [ + "## Exercise 1: Setting up various Python environments\n", + "\n", + "The first exercise here is of a mere technical art. We want you to have \n", + "* git as a version control software and to establish a user account on a provider like GitHub. Other providers like GitLab etc are equally fine. You can also use the University of Oslo [GitHub facilities](https://www.uio.no/tjenester/it/maskin/filer/versjonskontroll/github.html). \n", + "\n", + "* Install various Python packages\n", + "\n", + "We will make extensive use of Python as programming language and its\n", + "myriad of available libraries. You will find\n", + "IPython/Jupyter notebooks invaluable in your work. You can run **R**\n", + "codes in the Jupyter/IPython notebooks, with the immediate benefit of\n", + "visualizing your data. You can also use compiled languages like C++,\n", + "Rust, Fortran etc if you prefer. The focus in these lectures will be\n", + "on Python.\n", + "\n", + "If you have Python installed (we recommend Python3) and you feel\n", + "pretty familiar with installing different packages, we recommend that\n", + "you install the following Python packages via **pip** as \n", + "\n", + "1. pip install numpy scipy matplotlib ipython scikit-learn sympy pandas pillow \n", + "\n", + "For **Tensorflow**, we recommend following the instructions in the text of \n", + "[Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly](http://shop.oreilly.com/product/0636920052289.do)\n", + "\n", + "We will come back to **tensorflow** later. \n", + "\n", + "For Python3, replace **pip** with **pip3**.\n", + "\n", + "For OSX users we recommend, after having installed Xcode, to\n", + "install **brew**. Brew allows for a seamless installation of additional\n", + "software via for example \n", + "\n", + "1. brew install python3\n", + "\n", + "For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\n", + "you can use **pip** as well and simply install Python as \n", + "\n", + "1. sudo apt-get install python3 (or python for Python2.7)\n", + "\n", + "If you don't want to perform these operations separately and venture\n", + "into the hassle of exploring how to set up dependencies and paths, we\n", + "recommend two widely used distrubutions which set up all relevant\n", + "dependencies for Python, namely \n", + "\n", + "* [Anaconda](https://docs.anaconda.com/), \n", + "\n", + "which is an open source\n", + "distribution of the Python and R programming languages for large-scale\n", + "data processing, predictive analytics, and scientific computing, that\n", + "aims to simplify package management and deployment. Package versions\n", + "are managed by the package management system **conda**. \n", + "\n", + "* [Enthought canopy](https://www.enthought.com/product/canopy/) \n", + "\n", + "is a Python\n", + "distribution for scientific and analytic computing distribution and\n", + "analysis environment, available for free and under a commercial\n", + "license.\n", + "\n", + "We recommend using **Anaconda** if you are not too familiar with setting paths in a terminal environment." + ] + }, + { + "cell_type": "markdown", + "id": "39c71fe5", + "metadata": { + "editable": true + }, + "source": [ + "## Exercise 2: making your own data and exploring scikit-learn\n", + "\n", + "We will generate our own dataset for a function $y(x)$ where $x \\in [0,1]$ and defined by random numbers computed with the uniform distribution. The function $y$ is a quadratic polynomial in $x$ with added stochastic noise according to the normal distribution $\\cal {N}(0,1)$.\n", + "The following simple Python instructions define our $x$ and $y$ values (with 100 data points)." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "0f45655d", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "x = np.random.rand(100,1)\n", + "y = 2.0+5*x*x+0.1*np.random.randn(100,1)" + ] + }, + { + "cell_type": "markdown", + "id": "40d6fa8a", + "metadata": { + "editable": true + }, + "source": [ + "1. Write your own code (following the examples under the [regression notes](https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter1.html)) for computing the parametrization of the data set fitting a second-order polynomial. \n", + "\n", + "2. Use thereafter **scikit-learn** (see again the examples in the regression slides) and compare with your own code. When compairing with _scikit_learn_, make sure you set the option for the intercept to **FALSE**, see . This feature will be explained in more detail during the lectures of week 35 and week 36. You can find more in .\n", + "\n", + "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" + ] + }, + { + "cell_type": "markdown", + "id": "6e4b8013", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "MSE(\\boldsymbol{y},\\boldsymbol{\\tilde{y}}) = \\frac{1}{n}\n", + "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "a719548d", + "metadata": { + "editable": true + }, + "source": [ + "and the $R^2$ score function.\n", + "If $\\tilde{\\boldsymbol{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" + ] + }, + { + "cell_type": "markdown", + "id": "6b7a2f27", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "R^2(\\boldsymbol{y}, \\tilde{\\boldsymbol{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "50431786", + "metadata": { + "editable": true + }, + "source": [ + "where we have defined the mean value of $\\boldsymbol{y}$ as" + ] + }, + { + "cell_type": "markdown", + "id": "c423648a", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7de4c37a", + "metadata": { + "editable": true + }, + "source": [ + "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. \n", + "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.\n", + "\n", + "\n", + "**Solution.**\n", + "The code here is an example of where we define our own design matrix and fit parameters $\\beta$." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "5877919e", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "import os\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "def save_fig(fig_id):\n", + " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", + "\n", + "def R2(y_data, y_model):\n", + " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", + "def MSE(y_data,y_model):\n", + " n = np.size(y_model)\n", + " return np.sum((y_data-y_model)**2)/n\n", + "\n", + "x = np.random.rand(100)\n", + "y = 2.0+5*x*x+0.1*np.random.randn(100)\n", + "\n", + "\n", + "# The design matrix now as function of a given polynomial\n", + "X = np.zeros((len(x),3))\n", + "X[:,0] = 1.0\n", + "X[:,1] = x\n", + "X[:,2] = x**2\n", + "# We split the data in test and training data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", + "# matrix inversion to find beta\n", + "beta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n", + "print(beta)\n", + "# and then make the prediction\n", + "ytilde = X_train @ beta\n", + "print(\"Training R2\")\n", + "print(R2(y_train,ytilde))\n", + "print(\"Training MSE\")\n", + "print(MSE(y_train,ytilde))\n", + "ypredict = X_test @ beta\n", + "print(\"Test R2\")\n", + "print(R2(y_test,ypredict))\n", + "print(\"Test MSE\")\n", + "print(MSE(y_test,ypredict))" + ] + }, + { + "cell_type": "markdown", + "id": "d5c46a53", + "metadata": { + "editable": true + }, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "id": "2c9cf150", + "metadata": { + "editable": true + }, + "source": [ + "## Exercise 3: Normalizing our data\n", + "\n", + "A much used approach before starting to train the data is to preprocess our\n", + "data. Normally the data may need a rescaling and/or may be sensitive\n", + "to extreme values. Scaling the data renders our inputs much more\n", + "suitable for the algorithms we want to employ.\n", + "\n", + "**Scikit-Learn** has several functions which allow us to rescale the\n", + "data, normally resulting in much better results in terms of various\n", + "accuracy scores. The **StandardScaler** function in **Scikit-Learn**\n", + "ensures that for each feature/predictor we study the mean value is\n", + "zero and the variance is one (every column in the design/feature\n", + "matrix). This scaling has the drawback that it does not ensure that\n", + "we have a particular maximum or minimum in our data set. Another\n", + "function included in **Scikit-Learn** is the **MinMaxScaler** which\n", + "ensures that all features are exactly between $0$ and $1$. The\n", + "\n", + "The **Normalizer** scales each data\n", + "point such that the feature vector has a euclidean length of one. In other words, it\n", + "projects a data point on the circle (or sphere in the case of higher dimensions) with a\n", + "radius of 1. This means every data point is scaled by a different number (by the\n", + "inverse of it’s length).\n", + "This normalization is often used when only the direction (or angle) of the data matters,\n", + "not the length of the feature vector.\n", + "\n", + "The **RobustScaler** works similarly to the StandardScaler in that it\n", + "ensures statistical properties for each feature that guarantee that\n", + "they are on the same scale. However, the RobustScaler uses the median\n", + "and quartiles, instead of mean and variance. This makes the\n", + "RobustScaler ignore data points that are very different from the rest\n", + "(like measurement errors). These odd data points are also called\n", + "outliers, and might often lead to trouble for other scaling\n", + "techniques.\n", + "\n", + "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\n", + "for testing. This can be done as follows with our design matrix $\\boldsymbol{X}$ and data $\\boldsymbol{y}$ (remember to import **scikit-learn**)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "1e944be7", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# split in training and test data\n", + "X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)" + ] + }, + { + "cell_type": "markdown", + "id": "9ceecc12", + "metadata": { + "editable": true + }, + "source": [ + "Then we can use the standard scaler to scale our data as" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "f85e4fc8", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)" + ] + }, + { + "cell_type": "markdown", + "id": "88b49308", + "metadata": { + "editable": true + }, + "source": [ + "In this exercise we want you to to compute the MSE for the training\n", + "data and the test data as function of the complexity of a polynomial,\n", + "that is the degree of a given polynomial. We want you also to compute the $R2$ score as function of the complexity of the model for both training data and test data. You should also run the calculation with and without scaling. \n", + "\n", + "One of \n", + "the aims is to reproduce Figure 2.11 of [Hastie et al](https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf).\n", + "\n", + "Our data is defined by $x\\in [-3,3]$ with a total of for example $100$ data points." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "1e7aff9c", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "np.random.seed()\n", + "n = 100\n", + "maxdegree = 14\n", + "# Make data set.\n", + "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", + "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)" + ] + }, + { + "cell_type": "markdown", + "id": "e814b9ad", + "metadata": { + "editable": true + }, + "source": [ + "where $y$ is the function we want to fit with a given polynomial.\n", + "\n", + "\n", + "**Solution.**\n", + "We present here the solution for the last exercise. All elements here can be used to solve exercises a) and b) as well.\n", + "Note that in this example we have used the polynomial fitting functions of **scikit-learn**." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "f2f3f2a6", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", + "from sklearn.preprocessing import PolynomialFeatures\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.pipeline import make_pipeline\n", + "\n", + "\n", + "np.random.seed(2018)\n", + "n = 30\n", + "maxdegree = 14\n", + "# Make data set.\n", + "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", + "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", + "TestError = np.zeros(maxdegree)\n", + "TrainError = np.zeros(maxdegree)\n", + "polydegree = np.zeros(maxdegree)\n", + "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", + "\n", + "\n", + "for degree in range(maxdegree):\n", + " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n", + " clf = model.fit(x_train,y_train)\n", + " y_fit = clf.predict(x_train)\n", + " y_pred = clf.predict(x_test) \n", + " polydegree[degree] = degree\n", + " TestError[degree] = np.mean( np.mean((y_test - y_pred)**2) )\n", + " TrainError[degree] = np.mean( np.mean((y_train - y_fit)**2) )\n", + "\n", + "plt.plot(polydegree, TestError, label='Test Error')\n", + "plt.plot(polydegree, TrainError, label='Train Error')\n", + "plt.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "579a3858", + "metadata": { + "editable": true + }, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "id": "43068ed2", + "metadata": { + "editable": true + }, + "source": [ + "**a)**\n", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "64cbbec3", + "metadata": { + "editable": true + }, + "source": [ + "**b)**\n", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "f5a10c8c", + "metadata": { + "editable": true + }, + "source": [ + "**c)**\n", + "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)?" + ] + }, + { + "cell_type": "markdown", + "id": "e65d87f6", + "metadata": { + "editable": true + }, + "source": [ + "## Exercise 4: Adding Ridge Regression\n", + "\n", + "This exercise is a continuation of exercise 2. We will use the same function to\n", + "generate our data set, still staying with a simple function $y(x)$\n", + "which we want to fit using linear regression, but now extending the\n", + "analysis to include the Ridge regression method.\n", + "\n", + "We will thus again generate our own dataset for a function $y(x)$ where \n", + "$x \\in [0,1]$ and defined by random numbers computed with the uniform\n", + "distribution. The function $y$ is a quadratic polynomial in $x$ with\n", + "added stochastic noise according to the normal distribution $\\cal{N}(0,1)$.\n", + "\n", + "The following simple Python instructions define our $x$ and $y$ values (with 100 data points)." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "90c894cc", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "x = np.random.rand(100)\n", + "y = 2.0+5*x*x+0.1*np.random.randn(100)" + ] + }, + { + "cell_type": "markdown", + "id": "2972685a", + "metadata": { + "editable": true + }, + "source": [ + "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)$. \n", + "\n", + "Repeat the above but using the functionality of\n", + "**Scikit-Learn**. Compare your code with the results from\n", + "**Scikit-Learn**. Remember to run with the same random numbers for\n", + "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.\n", + "\n", + "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" + ] + }, + { + "cell_type": "markdown", + "id": "f7dc6da2", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n", + "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "e1b8dd61", + "metadata": { + "editable": true + }, + "source": [ + "and the $R^2$ score function.\n", + "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" + ] + }, + { + "cell_type": "markdown", + "id": "29ad51e4", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "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},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "634d4494", + "metadata": { + "editable": true + }, + "source": [ + "where we have defined the mean value of $\\hat{y}$ as" + ] + }, + { + "cell_type": "markdown", + "id": "5b9c856a", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5d4c2d5a", + "metadata": { + "editable": true + }, + "source": [ + "Discuss these quantities as functions of the variable $\\lambda$ in Ridge regression.\n", + "\n", + "\n", + "**Solution.**\n", + "The code here allows you to perform your own Ridge calculation and\n", + "perform calculations for various values of the regularization\n", + "parameter $\\lambda$. This program can easily be extended upon." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "87b8b63e", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import os\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn import linear_model\n", + "\n", + "def R2(y_data, y_model):\n", + " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", + "def MSE(y_data,y_model):\n", + " n = np.size(y_model)\n", + " return np.sum((y_data-y_model)**2)/n\n", + "\n", + "\n", + "# A seed just to ensure that the random numbers are the same for every run.\n", + "# Useful for eventual debugging.\n", + "np.random.seed(3155)\n", + "\n", + "x = np.random.rand(100)\n", + "y = 2.0+5*x*x+0.1*np.random.randn(100)\n", + "\n", + "# number of features p (here degree of polynomial\n", + "p = 3\n", + "# The design matrix now as function of a given polynomial\n", + "X = np.zeros((len(x),p))\n", + "X[:,0] = 1.0\n", + "X[:,1] = x\n", + "X[:,2] = x*x\n", + "# We split the data in test and training data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", + "\n", + "# matrix inversion to find beta\n", + "OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n", + "print(OLSbeta)\n", + "# and then make the prediction\n", + "ytildeOLS = X_train @ OLSbeta\n", + "print(\"Training R2 for OLS\")\n", + "print(R2(y_train,ytildeOLS))\n", + "print(\"Training MSE for OLS\")\n", + "print(MSE(y_train,ytildeOLS))\n", + "ypredictOLS = X_test @ OLSbeta\n", + "print(\"Test R2 for OLS\")\n", + "print(R2(y_test,ypredictOLS))\n", + "print(\"Test MSE OLS\")\n", + "print(MSE(y_test,ypredictOLS))\n", + "\n", + "\n", + "# Repeat now for Ridge regression and various values of the regularization parameter\n", + "I = np.eye(p,p)\n", + "# Decide which values of lambda to use\n", + "nlambdas = 20\n", + "OwnMSEPredict = np.zeros(nlambdas)\n", + "OwnMSETrain = np.zeros(nlambdas)\n", + "MSERidgePredict = np.zeros(nlambdas)\n", + "lambdas = np.logspace(-4, 1, nlambdas)\n", + "for i in range(nlambdas):\n", + " lmb = lambdas[i]\n", + " OwnRidgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n", + " # and then make the prediction\n", + " OwnytildeRidge = X_train @ OwnRidgebeta\n", + " OwnypredictRidge = X_test @ OwnRidgebeta\n", + " OwnMSEPredict[i] = MSE(y_test,OwnypredictRidge)\n", + " OwnMSETrain[i] = MSE(y_train,OwnytildeRidge)\n", + " # Make the fit using Ridge from Sklearn\n", + " RegRidge = linear_model.Ridge(lmb,fit_intercept=False)\n", + " RegRidge.fit(X_train,y_train)\n", + " # and then make the prediction\n", + " ypredictRidge = RegRidge.predict(X_test)\n", + " # Compute the MSE and print it\n", + " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n", + "\n", + "# Now plot the results\n", + "plt.figure()\n", + "plt.plot(np.log10(lambdas), OwnMSETrain, label = 'MSE Ridge train, Own code')\n", + "plt.plot(np.log10(lambdas), OwnMSEPredict, 'r--', label = 'MSE Ridge Test, Own code')\n", + "plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE Ridge Test, Sklearn code')\n", + "plt.xlabel('log10(lambda)')\n", + "plt.ylabel('MSE')\n", + "plt.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "c3d52c72", + "metadata": { + "editable": true + }, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "id": "75f051f8", + "metadata": { + "editable": true + }, + "source": [ + "## Exercise 5: Analytical exercises\n", + "\n", + "In this exercise we derive the expressions for various derivatives of\n", + "products of vectors and matrices. Such derivatives are central to the\n", + "optimization of various cost functions. Although we will often use\n", + "automatic differentiation in actual calculations, to be able to have\n", + "analytical expressions is extremely helpful in case we have simpler\n", + "derivatives as well as when we analyze various properties (like second\n", + "derivatives) of the chosen cost functions. Vectors are always written\n", + "as boldfaced lower case letters and matrices as upper case boldfaced\n", + "letters.\n", + "\n", + "Show that" + ] + }, + { + "cell_type": "markdown", + "id": "83557a92", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{\\partial (\\boldsymbol{b}^T\\boldsymbol{a})}{\\partial \\boldsymbol{a}} = \\boldsymbol{b},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c89e2123", + "metadata": { + "editable": true + }, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "3879d604", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{\\partial (\\boldsymbol{a}^T\\boldsymbol{A}\\boldsymbol{a})}{\\partial \\boldsymbol{a}} = (\\boldsymbol{A}+\\boldsymbol{A}^T)\\boldsymbol{a},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "e1d2f8f4", + "metadata": { + "editable": true + }, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "164cfcc4", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{\\partial \\left(\\boldsymbol{x}-\\boldsymbol{A}\\boldsymbol{s}\\right)^T\\left(\\boldsymbol{x}-\\boldsymbol{A}\\boldsymbol{s}\\right)}{\\partial \\boldsymbol{s}} = -2\\left(\\boldsymbol{x}-\\boldsymbol{A}\\boldsymbol{s}\\right)^T\\boldsymbol{A},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c7581bc8", + "metadata": { + "editable": true + }, + "source": [ + "and finally find the second derivative of this function with respect to the vector $\\boldsymbol{s}$.\n", + "\n", + "**Hint**: In these exercises it is always useful to write out with summation indices the various quantities.\n", + "As an example, consider the function" + ] + }, + { + "cell_type": "markdown", + "id": "ba345019", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "f(\\boldsymbol{x}) =\\boldsymbol{A}\\boldsymbol{x},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "83752696", + "metadata": { + "editable": true + }, + "source": [ + "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$)" + ] + }, + { + "cell_type": "markdown", + "id": "b1127005", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "f_i =\\sum_{j=0}^{n-1}a_{ij}x_j,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "73536022", + "metadata": { + "editable": true + }, + "source": [ + "which leads to" + ] + }, + { + "cell_type": "markdown", + "id": "f691f124", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{\\partial f_i}{\\partial x_j}= a_{ij},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "accc72b6", + "metadata": { + "editable": true + }, + "source": [ + "and written out in terms of the vector $\\boldsymbol{x}$ we have" + ] + }, + { + "cell_type": "markdown", + "id": "80706772", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{\\partial f(\\boldsymbol{x})}{\\partial \\boldsymbol{x}}= \\boldsymbol{A}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "e0ba2b0d", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "**Solution.**\n", + "For the first derivative" + ] + }, + { + "cell_type": "markdown", + "id": "0b5678a9", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{\\partial (\\boldsymbol{b}^T\\boldsymbol{a})}{\\partial \\boldsymbol{a}} = \\boldsymbol{b},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "50be3447", + "metadata": { + "editable": true + }, + "source": [ + "we can write out the inner product as (assuming all elements are real)" + ] + }, + { + "cell_type": "markdown", + "id": "6d0d4080", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{b}^T\\boldsymbol{a}=\\sum_i b_ia_i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "0f018905", + "metadata": { + "editable": true + }, + "source": [ + "taking the derivative" + ] + }, + { + "cell_type": "markdown", + "id": "a613eb18", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{\\partial \\left( \\sum_i b_ia_i\\right)}{\\partial a_k}= b_k,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "0f20f0a3", + "metadata": { + "editable": true + }, + "source": [ + "leading to" + ] + }, + { + "cell_type": "markdown", + "id": "fa37e6ce", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\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}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "46b416e7", + "metadata": { + "editable": true + }, + "source": [ + "For the second exercise we have" + ] + }, + { + "cell_type": "markdown", + "id": "2ca90f81", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{\\partial (\\boldsymbol{a}^T\\boldsymbol{A}\\boldsymbol{a})}{\\partial \\boldsymbol{a}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "9e3cadb3", + "metadata": { + "editable": true + }, + "source": [ + "Defining a vector $\\boldsymbol{f}=\\boldsymbol{A}\\boldsymbol{a}$ with components $f_i=\\sum_ja_{ij}a_i$ we have" + ] + }, + { + "cell_type": "markdown", + "id": "c8cf6b64", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\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),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "0a20a20f", + "metadata": { + "editable": true + }, + "source": [ + "since $f$ depends on $a$ and we have used the chain rule for derivatives on the derivative of $f$ with respect to $a$.\n", + "\n", + "" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/doc/src/week35/.ipynb_checkpoints/Exercisesweek35-checkpoint.ipynb b/doc/src/week35/.ipynb_checkpoints/Exercisesweek35-checkpoint.ipynb new file mode 100644 index 000000000..a1b60c2f1 --- /dev/null +++ b/doc/src/week35/.ipynb_checkpoints/Exercisesweek35-checkpoint.ipynb @@ -0,0 +1,814 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "a3922707", + "metadata": {}, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "27f03cf5", + "metadata": {}, + "source": [ + "# Exercises week 35\n", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", + "\n", + "Date: **Aug 30, 2022**\n", + "\n", + "Copyright 1999-2022, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license" + ] + }, + { + "cell_type": "markdown", + "id": "a7a36181", + "metadata": {}, + "source": [ + "## Exercises for week 35\n", + "\n", + "The exercises here are meant to prepare you for work with project 1. The first exercise is a follow-up of exercise 2 from week 35 August 30-September 3)." + ] + }, + { + "cell_type": "markdown", + "id": "f0299eb0", + "metadata": {}, + "source": [ + "## Exercise 1: Setting up various Python environments\n", + "\n", + "The first exercise here is of a mere technical art. We want you to have \n", + "* git as a version control software and to establish a user account on a provider like GitHub. Other providers like GitLab etc are equally fine. You can also use the University of Oslo [GitHub facilities](https://www.uio.no/tjenester/it/maskin/filer/versjonskontroll/github.html). \n", + "\n", + "* Install various Python packages\n", + "\n", + "We will make extensive use of Python as programming language and its\n", + "myriad of available libraries. You will find\n", + "IPython/Jupyter notebooks invaluable in your work. You can run **R**\n", + "codes in the Jupyter/IPython notebooks, with the immediate benefit of\n", + "visualizing your data. You can also use compiled languages like C++,\n", + "Rust, Fortran etc if you prefer. The focus in these lectures will be\n", + "on Python.\n", + "\n", + "If you have Python installed (we recommend Python3) and you feel\n", + "pretty familiar with installing different packages, we recommend that\n", + "you install the following Python packages via **pip** as \n", + "\n", + "1. pip install numpy scipy matplotlib ipython scikit-learn sympy pandas pillow \n", + "\n", + "For **Tensorflow**, we recommend following the instructions in the text of \n", + "[Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly](http://shop.oreilly.com/product/0636920052289.do)\n", + "\n", + "We will come back to **tensorflow** later. \n", + "\n", + "For Python3, replace **pip** with **pip3**.\n", + "\n", + "For OSX users we recommend, after having installed Xcode, to\n", + "install **brew**. Brew allows for a seamless installation of additional\n", + "software via for example \n", + "\n", + "1. brew install python3\n", + "\n", + "For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\n", + "you can use **pip** as well and simply install Python as \n", + "\n", + "1. sudo apt-get install python3 (or python for Python2.7)\n", + "\n", + "If you don't want to perform these operations separately and venture\n", + "into the hassle of exploring how to set up dependencies and paths, we\n", + "recommend two widely used distrubutions which set up all relevant\n", + "dependencies for Python, namely \n", + "\n", + "* [Anaconda](https://docs.anaconda.com/), \n", + "\n", + "which is an open source\n", + "distribution of the Python and R programming languages for large-scale\n", + "data processing, predictive analytics, and scientific computing, that\n", + "aims to simplify package management and deployment. Package versions\n", + "are managed by the package management system **conda**. \n", + "\n", + "* [Enthought canopy](https://www.enthought.com/product/canopy/) \n", + "\n", + "is a Python\n", + "distribution for scientific and analytic computing distribution and\n", + "analysis environment, available for free and under a commercial\n", + "license.\n", + "\n", + "We recommend using **Anaconda** if you are not too familiar with setting paths in a terminal environment." + ] + }, + { + "cell_type": "markdown", + "id": "b895521b", + "metadata": {}, + "source": [ + "## Exercise 2: making your own data and exploring scikit-learn\n", + "\n", + "We will generate our own dataset for a function $y(x)$ where $x \\in [0,1]$ and defined by random numbers computed with the uniform distribution. The function $y$ is a quadratic polynomial in $x$ with added stochastic noise according to the normal distribution $\\cal {N}(0,1)$.\n", + "The following simple Python instructions define our $x$ and $y$ values (with 100 data points)." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "5cd360ac", + "metadata": {}, + "outputs": [], + "source": [ + "x = np.random.rand(100,1)\n", + "y = 2.0+5*x*x+0.1*np.random.randn(100,1)" + ] + }, + { + "cell_type": "markdown", + "id": "8692db31", + "metadata": {}, + "source": [ + "1. Write your own code (following the examples under the [regression notes](https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter1.html)) for computing the parametrization of the data set fitting a second-order polynomial. \n", + "\n", + "2. Use thereafter **scikit-learn** (see again the examples in the regression slides) and compare with your own code. When compairing with _scikit_learn_, make sure you set the option for the intercept to **FALSE**, see . This feature will be explained in more detail during the lectures of week 35 and week 36. You can find more in .\n", + "\n", + "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" + ] + }, + { + "cell_type": "markdown", + "id": "c1cd3889", + "metadata": {}, + "source": [ + "$$\n", + "MSE(\\boldsymbol{y},\\boldsymbol{\\tilde{y}}) = \\frac{1}{n}\n", + "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "75b41875", + "metadata": {}, + "source": [ + "and the $R^2$ score function.\n", + "If $\\tilde{\\boldsymbol{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" + ] + }, + { + "cell_type": "markdown", + "id": "df0ab656", + "metadata": {}, + "source": [ + "$$\n", + "R^2(\\boldsymbol{y}, \\tilde{\\boldsymbol{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2a6855ca", + "metadata": {}, + "source": [ + "where we have defined the mean value of $\\boldsymbol{y}$ as" + ] + }, + { + "cell_type": "markdown", + "id": "3b8613b2", + "metadata": {}, + "source": [ + "$$\n", + "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5e196d9d", + "metadata": {}, + "source": [ + "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. \n", + "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.\n", + "\n", + "\n", + "**Solution.**\n", + "The code here is an example of where we define our own design matrix and fit parameters $\\beta$." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "7fea7f0d", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1.98074191 0.11515918 4.92363317]\n", + "Training R2\n", + "0.9933364772853098\n", + "Training MSE\n", + "0.011606852536304387\n", + "Test R2\n", + "0.9930306664090155\n", + "Test MSE\n", + "0.015064614059685105\n" + ] + } + ], + "source": [ + "%matplotlib inline\n", + "\n", + "import os\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "def save_fig(fig_id):\n", + " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", + "\n", + "def R2(y_data, y_model):\n", + " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", + "def MSE(y_data,y_model):\n", + " n = np.size(y_model)\n", + " return np.sum((y_data-y_model)**2)/n\n", + "\n", + "x = np.random.rand(100)\n", + "y = 2.0+5*x*x+0.1*np.random.randn(100)\n", + "\n", + "\n", + "# The design matrix now as function of a given polynomial\n", + "X = np.zeros((len(x),3))\n", + "X[:,0] = 1.0\n", + "X[:,1] = x\n", + "X[:,2] = x**2\n", + "# We split the data in test and training data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", + "# matrix inversion to find beta\n", + "beta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n", + "print(beta)\n", + "# and then make the prediction\n", + "ytilde = X_train @ beta\n", + "print(\"Training R2\")\n", + "print(R2(y_train,ytilde))\n", + "print(\"Training MSE\")\n", + "print(MSE(y_train,ytilde))\n", + "ypredict = X_test @ beta\n", + "print(\"Test R2\")\n", + "print(R2(y_test,ypredict))\n", + "print(\"Test MSE\")\n", + "print(MSE(y_test,ypredict))" + ] + }, + { + "cell_type": "markdown", + "id": "b9db8693", + "metadata": {}, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "id": "320fbafb", + "metadata": {}, + "source": [ + "## Exercise 3: Normalizing our data\n", + "\n", + "A much used approach before starting to train the data is to preprocess our\n", + "data. Normally the data may need a rescaling and/or may be sensitive\n", + "to extreme values. Scaling the data renders our inputs much more\n", + "suitable for the algorithms we want to employ.\n", + "\n", + "**Scikit-Learn** has several functions which allow us to rescale the\n", + "data, normally resulting in much better results in terms of various\n", + "accuracy scores. The **StandardScaler** function in **Scikit-Learn**\n", + "ensures that for each feature/predictor we study the mean value is\n", + "zero and the variance is one (every column in the design/feature\n", + "matrix). This scaling has the drawback that it does not ensure that\n", + "we have a particular maximum or minimum in our data set. Another\n", + "function included in **Scikit-Learn** is the **MinMaxScaler** which\n", + "ensures that all features are exactly between $0$ and $1$. The\n", + "\n", + "The **Normalizer** scales each data\n", + "point such that the feature vector has a euclidean length of one. In other words, it\n", + "projects a data point on the circle (or sphere in the case of higher dimensions) with a\n", + "radius of 1. This means every data point is scaled by a different number (by the\n", + "inverse of it’s length).\n", + "This normalization is often used when only the direction (or angle) of the data matters,\n", + "not the length of the feature vector.\n", + "\n", + "The **RobustScaler** works similarly to the StandardScaler in that it\n", + "ensures statistical properties for each feature that guarantee that\n", + "they are on the same scale. However, the RobustScaler uses the median\n", + "and quartiles, instead of mean and variance. This makes the\n", + "RobustScaler ignore data points that are very different from the rest\n", + "(like measurement errors). These odd data points are also called\n", + "outliers, and might often lead to trouble for other scaling\n", + "techniques.\n", + "\n", + "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\n", + "for testing. This can be done as follows with our design matrix $\\boldsymbol{X}$ and data $\\boldsymbol{y}$ (remember to import **scikit-learn**)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "c066fcad", + "metadata": {}, + "outputs": [], + "source": [ + "# split in training and test data\n", + "X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)" + ] + }, + { + "cell_type": "markdown", + "id": "eab220fb", + "metadata": {}, + "source": [ + "Then we can use the standard scaler to scale our data as" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "ecd474f8", + "metadata": {}, + "outputs": [], + "source": [ + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)" + ] + }, + { + "cell_type": "markdown", + "id": "deecfa98", + "metadata": {}, + "source": [ + "In this exercise we want you to to compute the MSE for the training\n", + "data and the test data as function of the complexity of a polynomial,\n", + "that is the degree of a given polynomial. We want you also to compute the $R2$ score as function of the complexity of the model for both training data and test data. You should also run the calculation with and without scaling. \n", + "\n", + "One of \n", + "the aims is to reproduce Figure 2.11 of [Hastie et al](https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf).\n", + "\n", + "Our data is defined by $x\\in [-3,3]$ with a total of for example $100$ data points." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "4a18cc79", + "metadata": {}, + "outputs": [], + "source": [ + "np.random.seed()\n", + "n = 100\n", + "maxdegree = 14\n", + "# Make data set.\n", + "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", + "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)" + ] + }, + { + "cell_type": "markdown", + "id": "f172b979", + "metadata": {}, + "source": [ + "where $y$ is the function we want to fit with a given polynomial." + ] + }, + { + "cell_type": "markdown", + "id": "d1475ab4", + "metadata": {}, + "source": [ + "**a)**\n", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "e3160984", + "metadata": {}, + "source": [ + "**b)**\n", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "8c6fdc1d", + "metadata": {}, + "source": [ + "**c)**\n", + "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)?" + ] + }, + { + "cell_type": "markdown", + "id": "7878f903", + "metadata": {}, + "source": [ + "## Exercise 4: Adding Ridge Regression\n", + "\n", + "This exercise is a continuation of exercise 2. We will use the same function to\n", + "generate our data set, still staying with a simple function $y(x)$\n", + "which we want to fit using linear regression, but now extending the\n", + "analysis to include the Ridge regression method.\n", + "\n", + "We will thus again generate our own dataset for a function $y(x)$ where \n", + "$x \\in [0,1]$ and defined by random numbers computed with the uniform\n", + "distribution. The function $y$ is a quadratic polynomial in $x$ with\n", + "added stochastic noise according to the normal distribution $\\cal{N}(0,1)$.\n", + "\n", + "The following simple Python instructions define our $x$ and $y$ values (with 100 data points)." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "62745162", + "metadata": {}, + "outputs": [], + "source": [ + "x = np.random.rand(100)\n", + "y = 2.0+5*x*x+0.1*np.random.randn(100)" + ] + }, + { + "cell_type": "markdown", + "id": "695a78cc", + "metadata": {}, + "source": [ + "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)$. \n", + "\n", + "Repeat the above but using the functionality of\n", + "**Scikit-Learn**. Compare your code with the results from\n", + "**Scikit-Learn**. Remember to run with the same random numbers for\n", + "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.\n", + "\n", + "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" + ] + }, + { + "cell_type": "markdown", + "id": "d518cb53", + "metadata": {}, + "source": [ + "$$\n", + "MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n", + "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "1e5794c0", + "metadata": {}, + "source": [ + "and the $R^2$ score function.\n", + "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" + ] + }, + { + "cell_type": "markdown", + "id": "7789fbed", + "metadata": {}, + "source": [ + "$$\n", + "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},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "41ff7108", + "metadata": {}, + "source": [ + "where we have defined the mean value of $\\hat{y}$ as" + ] + }, + { + "cell_type": "markdown", + "id": "d6f48f75", + "metadata": {}, + "source": [ + "$$\n", + "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "d56187f2", + "metadata": {}, + "source": [ + "Discuss these quantities as functions of the variable $\\lambda$ in Ridge regression.\n", + "\n", + "\n", + "**Solution.**\n", + "The code here allows you to perform your own Ridge calculation and\n", + "perform calculations for various values of the regularization\n", + "parameter $\\lambda$. This program can easily be extended upon." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "8ede789d", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[ 2.03099776 -0.17917768 5.18029127]\n", + "Training R2 for OLS\n", + "0.9947777005941899\n", + "Training MSE for OLS\n", + "0.00916347050835222\n", + "Test R2 for OLS\n", + "0.9959114574014767\n", + "Test MSE OLS\n", + "0.008675369724976584\n" + ] + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYgAAAEGCAYAAAB/+QKOAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/MnkTPAAAACXBIWXMAAAsTAAALEwEAmpwYAAA+QUlEQVR4nO3dd3xUVfr48c+T0HtXIFRFIIE0QqSjiKCiFMsqyC6Ia1lF3N+uLrK66lrWwn51LayCK4riggVFREQRRcBK7zUhhABSQhJKEtKe3x93MjtJJg0ymZTn/XrNa+7cc+695444T8499z5HVBVjjDEmvwB/N8AYY0zFZAHCGGOMVxYgjDHGeGUBwhhjj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syz/ptvviE1NRWAU6dOERMTQ/v27Uu9fxHhySef5KeffmLnzp15ygYNGsTChQtJS0vj1KlTfPbZZwA0adKEhg0b8vPPPwMwf/589zbDhw/ntddeIzMzE4Ddu3dz5syZPPtt2LAhp06dKrRNKSkpNG3alHr16rFz505++umnUp3Tq6++yquvvlpg/QMPPMAzzzzj7mnExcXxj3/8gz//+c8ADBw4kLlz59KlSxcCAgJo1qwZS5YsYcCAASU+9pAhQ/jwww/dwTz3ElO/fv3c39N7773n7pX0798/z/pcw4cPZ/bs2Zw+fRqAgwcPcvTo0dJ8DcYUrmNHcI33+UK16UH4W1BQEFOmTCmwft26dUyePJkaNWqQk5PD73//e3r37k1cXFyBMYhJkyZ53UeuunXr8uc//5np06fz5ptvutdHRkZy8803ExYWRqtWrejdu7e77M033+SOO+4gICCAwYMH07hxYwB+//vfExcXR2RkJKpKy5YtC9xK2rx5c/r370+PHj24+uqr8/yFDnDVVVfx+uuv0717d7p27UqfPn1K85Wxc+dO+vfvX2B9eHg4zz33HNdddx2ZmZnUrFmT559/3v1ddezYEVV1X8YZMGAACQkJNG3atMTHDgkJ4eGHH2bw4MEEBgYSERHB22+/zSuvvMJtt93G9OnTadmyJW+99RYAL730EuPGjeO5555jlMf14GHDhrFjxw73ZbwGDRowd+5cWrVqVarvwpgCYmIgO9sJEj4iZdW99reoqCjNP2HQjh076N69u59aVDmcPn3afc/+s88+y+HDh3nppZf83CrHtddey8cff0ytWrX83ZQKx/5tG154Af78Z3jqKXj44XPejYisU9Uob2XWg6jmPv/8c5555hmysrLo0KEDb7/9tr+b5JY7YG6M8cJ1JyTXXeezQ1iAqOZuvvlmbr75Zn83wxhTWlu3QkAA+PDhUAsQxhhTGd16K+ze7dND+PQuJhG5SkR2icheEXnIS/ndIrJFRDaKyGoRCXat7ygiaa71G0XkdV+20xhjKp3HH4f//tenh/BZgBCRQGAGcDUQDIzNDQAe/quqPVU1HHgeeMGjLEZVw12vu33VTmOMqXRiYmDePHDdIu8rvuxBRA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Jigb04dyzdA6CqZ4AYEbnYy/GfB54RkQ2c+yXddNf2rwO52Tr/DgwSkW04l5py51FfCtQQkR3AszjTqubqBfzkMeWqMUWybK6m2hKRBqp62jVo+wvQ/1wniHJd8++lqo+UaSPLkIi8BCxS1eX+boupHGyQ2lRni10DvrWAJ89n9kBV/aQS3B201YKDKQ3rQRhjjPHKxiCMMcZ4ZQHCGGOMVxYgjDHGeGUBwhhjjFcWIIwxxnj1/wFxbTrz85YbjgAAAABJRU5ErkJggg==\n", + "text/plain": [ + "
" + ] + }, + "metadata": { + "needs_background": "light" + }, + "output_type": "display_data" + } + ], + "source": [ + "import os\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn import linear_model\n", + "\n", + "def R2(y_data, y_model):\n", + " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", + "def MSE(y_data,y_model):\n", + " n = np.size(y_model)\n", + " return np.sum((y_data-y_model)**2)/n\n", + "\n", + "\n", + "# A seed just to ensure that the random numbers are the same for every run.\n", + "# Useful for eventual debugging.\n", + "np.random.seed(3155)\n", + "\n", + "x = np.random.rand(100)\n", + "y = 2.0+5*x*x+0.1*np.random.randn(100)\n", + "\n", + "# number of features p (here degree of polynomial\n", + "p = 3\n", + "# The design matrix now as function of a given polynomial\n", + "X = np.zeros((len(x),p))\n", + "X[:,0] = 1.0\n", + "X[:,1] = x\n", + "X[:,2] = x*x\n", + "# We split the data in test and training data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", + "\n", + "# matrix inversion to find beta\n", + "OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n", + "print(OLSbeta)\n", + "# and then make the prediction\n", + "ytildeOLS = X_train @ OLSbeta\n", + "print(\"Training R2 for OLS\")\n", + "print(R2(y_train,ytildeOLS))\n", + "print(\"Training MSE for OLS\")\n", + "print(MSE(y_train,ytildeOLS))\n", + "ypredictOLS = X_test @ OLSbeta\n", + "print(\"Test R2 for OLS\")\n", + "print(R2(y_test,ypredictOLS))\n", + "print(\"Test MSE OLS\")\n", + "print(MSE(y_test,ypredictOLS))\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "# Repeat now for Ridge regression and various values of the regularization parameter\n", + "I = np.eye(p,p)\n", + "# Decide which values of lambda to use\n", + "nlambdas = 20\n", + "OwnMSEPredict = np.zeros(nlambdas)\n", + "OwnMSETrain = np.zeros(nlambdas)\n", + "MSERidgePredict = np.zeros(nlambdas)\n", + "lambdas = np.logspace(-4, 1, nlambdas)\n", + "for i in range(nlambdas):\n", + " lmb = lambdas[i]\n", + " OwnRidgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n", + " # and then make the prediction\n", + " OwnytildeRidge = X_train @ OwnRidgebeta\n", + " OwnypredictRidge = X_test @ OwnRidgebeta\n", + " OwnMSEPredict[i] = MSE(y_test,OwnypredictRidge)\n", + " OwnMSETrain[i] = MSE(y_train,OwnytildeRidge)\n", + " # Make the fit using Ridge from Sklearn\n", + " RegRidge = linear_model.Ridge(lmb,fit_intercept=False)\n", + " RegRidge.fit(X_train,y_train)\n", + " # and then make the prediction\n", + " ypredictRidge = RegRidge.predict(X_test)\n", + " # Compute the MSE and print it\n", + " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n", + "\n", + "# Now plot the results\n", + "plt.figure()\n", + "plt.plot(np.log10(lambdas), OwnMSETrain, label = 'MSE Ridge train, Own code')\n", + "plt.plot(np.log10(lambdas), OwnMSEPredict, 'r--', label = 'MSE Ridge Test, Own code')\n", + "plt.plot(np.log10(lambdas), MSERidgePredict, 'r--', label = 'MSE Ridge Test, Sklearn code')\n", + "plt.xlabel('log10(lambda)')\n", + "plt.ylabel('MSE')\n", + "plt.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "d5245d5d", + "metadata": {}, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "id": "fd674bbc", + "metadata": {}, + "source": [ + "## Exercise 5: Analytical exercises\n", + "\n", + "In this exercise we derive the expressions for various derivatives of\n", + "products of vectors and matrices. Such derivatives are central to the\n", + "optimization of various cost functions. Although we will often use\n", + "automatic differentiation in actual calculations, to be able to have\n", + "analytical expressions is extremely helpful in case we have simpler\n", + "derivatives as well as when we analyze various properties (like second\n", + "derivatives) of the chosen cost functions. Vectors are always written\n", + "as boldfaced lower case letters and matrices as upper case boldfaced\n", + "letters.\n", + "\n", + "Show that" + ] + }, + { + "cell_type": "markdown", + "id": "4efd73f6", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial (\\boldsymbol{b}^T\\boldsymbol{a})}{\\partial \\boldsymbol{a}} = \\boldsymbol{b},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "faaaee3f", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "5aec3987", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial (\\boldsymbol{a}^T\\boldsymbol{A}\\boldsymbol{a})}{\\partial \\boldsymbol{a}} = (\\boldsymbol{A}+\\boldsymbol{A}^T)\\boldsymbol{a},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2afcd257", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "5a9ff7ea", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial \\left(\\boldsymbol{x}-\\boldsymbol{A}\\boldsymbol{s}\\right)^T\\left(\\boldsymbol{x}-\\boldsymbol{A}\\boldsymbol{s}\\right)}{\\partial \\boldsymbol{s}} = -2\\left(\\boldsymbol{x}-\\boldsymbol{A}\\boldsymbol{s}\\right)^T\\boldsymbol{A},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "e4ba8b3b", + "metadata": {}, + "source": [ + "and finally find the second derivative of this function with respect to the vector $\\boldsymbol{s}$.\n", + "\n", + "**Hint**: In these exercises it is always useful to write out with summation indices the various quantities.\n", + "As an example, consider the function" + ] + }, + { + "cell_type": "markdown", + "id": "717984d7", + "metadata": {}, + "source": [ + "$$\n", + "f(\\boldsymbol{x}) =\\boldsymbol{A}\\boldsymbol{x},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2a067da2", + "metadata": {}, + "source": [ + "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$)" + ] + }, + { + "cell_type": "markdown", + "id": "e57dd4ce", + "metadata": {}, + "source": [ + "$$\n", + "f_i =\\sum_{j=0}^{n-1}a_{ij}x_j,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7e5c8c5a", + "metadata": {}, + "source": [ + "which leads to" + ] + }, + { + "cell_type": "markdown", + "id": "a3a3bd01", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f_i}{\\partial x_j}= a_{ij},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "6f54347b", + "metadata": {}, + "source": [ + "and written out in terms of the vector $\\boldsymbol{x}$ we have" + ] + }, + { + "cell_type": "markdown", + "id": "6ed514b3", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f(\\boldsymbol{x})}{\\partial \\boldsymbol{x}}= \\boldsymbol{A}.\n", + "$$" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.12" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}