updated book
This commit is contained in:
@@ -1282,6 +1282,433 @@
|
||||
"plt.legend()\n",
|
||||
"plt.show()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Exercises and Projects\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"The main aim of this project is to study in more detail various\n",
|
||||
"regression methods, including the Ordinary Least Squares (OLS) method,\n",
|
||||
"The total score is **100** points. Each subtask has its own final score.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"We will first study how to fit polynomials to a specific\n",
|
||||
"two-dimensional function called [Franke's\n",
|
||||
"function](http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf). This\n",
|
||||
"is a function which has been widely used when testing various\n",
|
||||
"interpolation and fitting algorithms. Furthermore, after having\n",
|
||||
"established the model and the method, we will employ resamling\n",
|
||||
"techniques such as cross-validation and/or bootstrap in order to perform a\n",
|
||||
"proper assessment of our models. We will also study in detail the\n",
|
||||
"so-called Bias-Variance trade off.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"The Franke function, which is a weighted sum of four exponentials reads as follows"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\begin{align*}\n",
|
||||
"f(x,y) &= \\frac{3}{4}\\exp{\\left(-\\frac{(9x-2)^2}{4} - \\frac{(9y-2)^2}{4}\\right)}+\\frac{3}{4}\\exp{\\left(-\\frac{(9x+1)^2}{49}- \\frac{(9y+1)}{10}\\right)} \\\\\n",
|
||||
"&+\\frac{1}{2}\\exp{\\left(-\\frac{(9x-7)^2}{4} - \\frac{(9y-3)^2}{4}\\right)} -\\frac{1}{5}\\exp{\\left(-(9x-4)^2 - (9y-7)^2\\right) }.\n",
|
||||
"\\end{align*}\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"The function will be defined for $x,y\\in [0,1]$. Our first step will\n",
|
||||
"be to perform an OLS regression analysis of this function, trying out\n",
|
||||
"a polynomial fit with an $x$ and $y$ dependence of the form $[x, y,\n",
|
||||
"x^2, y^2, xy, \\dots]$. We will also include bootstrap first as\n",
|
||||
"a resampling technique. After that we will include the cross-validation technique. As in homeworks 1 and 2, we can use a uniform\n",
|
||||
"distribution to set up the arrays of values for $x$ and $y$, or as in\n",
|
||||
"the example below just a set of fixed \n",
|
||||
"values for $x$ and $y$ with a given step\n",
|
||||
"size. We will fit a\n",
|
||||
"function (for example a polynomial) of $x$ and $y$. Thereafter we\n",
|
||||
"will repeat much of the same procedure using the Ridge and Lasso\n",
|
||||
"regression methods, introducing thus a dependence on the bias\n",
|
||||
"(penalty) $\\lambda$.\n",
|
||||
"\n",
|
||||
"Finally we are going to use (real) digital terrain data and try to\n",
|
||||
"reproduce these data using the same methods. We will also try to go\n",
|
||||
"beyond the second-order polynomials metioned above and explore \n",
|
||||
"which polynomial fits the data best.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"The Python code for the Franke function is included here (it performs also a three-dimensional plot of it)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"collapsed": false,
|
||||
"editable": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from mpl_toolkits.mplot3d import Axes3D\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"from matplotlib import cm\n",
|
||||
"from matplotlib.ticker import LinearLocator, FormatStrFormatter\n",
|
||||
"import numpy as np\n",
|
||||
"from random import random, seed\n",
|
||||
"\n",
|
||||
"fig = plt.figure()\n",
|
||||
"ax = fig.gca(projection='3d')\n",
|
||||
"\n",
|
||||
"# Make data.\n",
|
||||
"x = np.arange(0, 1, 0.05)\n",
|
||||
"y = np.arange(0, 1, 0.05)\n",
|
||||
"x, y = np.meshgrid(x,y)\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def FrankeFunction(x,y):\n",
|
||||
" term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
|
||||
" term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
|
||||
" term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
|
||||
" term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
|
||||
" return term1 + term2 + term3 + term4\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"z = FrankeFunction(x, y)\n",
|
||||
"\n",
|
||||
"# Plot the surface.\n",
|
||||
"surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,\n",
|
||||
" linewidth=0, antialiased=False)\n",
|
||||
"\n",
|
||||
"# Customize the z axis.\n",
|
||||
"ax.set_zlim(-0.10, 1.40)\n",
|
||||
"ax.zaxis.set_major_locator(LinearLocator(10))\n",
|
||||
"ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n",
|
||||
"\n",
|
||||
"# Add a color bar which maps values to colors.\n",
|
||||
"fig.colorbar(surf, shrink=0.5, aspect=5)\n",
|
||||
"\n",
|
||||
"plt.show()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Exercise: Ordinary Least Square (OLS) on the Franke function\n",
|
||||
"\n",
|
||||
"We will generate our own dataset for a function\n",
|
||||
"$\\mathrm{FrankeFunction}(x,y)$ with $x,y \\in [0,1]$. The function\n",
|
||||
"$f(x,y)$ is the Franke function. You should explore also the addition\n",
|
||||
"of an added stochastic noise to this function using the normal\n",
|
||||
"distribution $N(0,1)$.\n",
|
||||
"\n",
|
||||
"*Write your own code* (using either a matrix inversion or a singular\n",
|
||||
"value decomposition from e.g., **numpy** ) or use your code from\n",
|
||||
"homeworks 1 and 2 and perform a standard least square regression\n",
|
||||
"analysis using polynomials in $x$ and $y$ up to fifth order. Find the\n",
|
||||
"[confidence intervals](https://en.wikipedia.org/wiki/Confidence_interval) of the parameters (estimators) $\\beta$ by computing their\n",
|
||||
"variances, evaluate the Mean Squared error (MSE)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"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",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"and the $R^2$ score function. If $\\tilde{\\hat{y}}_i$ is the predicted\n",
|
||||
"value of the $i-th$ sample and $y_i$ is the corresponding true value,\n",
|
||||
"then the score $R^2$ is defined as"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"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",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"where we have defined the mean value of $\\hat{y}$ as"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Your code has to include a scaling of the data (for example by\n",
|
||||
"subtracting the mean value), and\n",
|
||||
"a split of the data in training and test data. For this exercise you can\n",
|
||||
"either write your own code or use for example the function for\n",
|
||||
"splitting training data provided by the library **Scikit-Learn** (make\n",
|
||||
"sure you have installed it). This function is called\n",
|
||||
"$train\\_test\\_split$. **You should present a critical discussion of why and how you have scaled or not scaled the data**.\n",
|
||||
"\n",
|
||||
"It is normal in essentially all Machine Learning studies to split the\n",
|
||||
"data in a training set and a test set (eventually also an additional\n",
|
||||
"validation set). There\n",
|
||||
"is no explicit recipe for how much data should be included as training\n",
|
||||
"data and say test data. An accepted rule of thumb is to use\n",
|
||||
"approximately $2/3$ to $4/5$ of the data as training data.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"You can easily reuse the solutions to your exercises from week 35 and week 36.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"### Exercise: Bias-variance trade-off and resampling techniques\n",
|
||||
"\n",
|
||||
"Our aim here is to study the bias-variance trade-off by implementing the **bootstrap** resampling technique.\n",
|
||||
"\n",
|
||||
"With a code which does OLS and includes resampling techniques, \n",
|
||||
"we will now discuss the bias-variance trade-off in the context of\n",
|
||||
"continuous predictions such as regression. However, many of the\n",
|
||||
"intuitions and ideas discussed here also carry over to classification\n",
|
||||
"tasks and basically all Machine Learning algorithms. \n",
|
||||
"\n",
|
||||
"Before you perform an analysis of the bias-variance trade-off on your test data, make\n",
|
||||
"first a figure similar to Fig. 2.11 of Hastie, Tibshirani, and\n",
|
||||
"Friedman. Figure 2.11 of this reference displays only the test and training MSEs. The test MSE can be used to \n",
|
||||
"indicate possible regions of low/high bias and variance. You will most likely not get an\n",
|
||||
"equally smooth curve!\n",
|
||||
"\n",
|
||||
"With this result we move on to the bias-variance trade-off analysis.\n",
|
||||
"\n",
|
||||
"Consider a\n",
|
||||
"dataset $\\mathcal{L}$ consisting of the data\n",
|
||||
"$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$.\n",
|
||||
"\n",
|
||||
"Let us assume that the true data is generated from a noisy model"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}.\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Here $\\epsilon$ is normally distributed with mean zero and standard\n",
|
||||
"deviation $\\sigma^2$.\n",
|
||||
"\n",
|
||||
"In our derivation of the ordinary least squares method we defined then\n",
|
||||
"an approximation to the function $f$ in terms of the parameters\n",
|
||||
"$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n",
|
||||
"that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$.\n",
|
||||
"\n",
|
||||
"The parameters $\\boldsymbol{\\beta}$ are in turn found by optimizing the means\n",
|
||||
"squared error via the so-called cost function"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Here the expected value $\\mathbb{E}$ is the sample value. \n",
|
||||
"\n",
|
||||
"Show that you can rewrite this as"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"$$\n",
|
||||
"\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\frac{1}{n}\\sum_i(f_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\sigma^2.\n",
|
||||
"$$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Explain what the terms mean, which one is the bias and which one is\n",
|
||||
"the variance and discuss their interpretations.\n",
|
||||
"\n",
|
||||
"Perform then a bias-variance analysis of the Franke function by\n",
|
||||
"studying the MSE value as function of the complexity of your model.\n",
|
||||
"\n",
|
||||
"Discuss the bias and variance trade-off as function\n",
|
||||
"of your model complexity (the degree of the polynomial) and the number\n",
|
||||
"of data points, and possibly also your training and test data using the **bootstrap** resampling method.\n",
|
||||
"\n",
|
||||
"Note also that when you calculate the bias, in all applications you don't know the function values $f_i$. You would hence replace them with the actual data points $y_i$.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"### Exercise: Cross-validation as resampling techniques, adding more complexity\n",
|
||||
"\n",
|
||||
"The aim here is to write your own code for another widely popular\n",
|
||||
"resampling technique, the so-called cross-validation method. Again,\n",
|
||||
"before you start with cross-validation approach, you should scale your\n",
|
||||
"data.\n",
|
||||
"\n",
|
||||
"Implement the $k$-fold cross-validation algorithm (write your own\n",
|
||||
"code) and evaluate again the MSE function resulting\n",
|
||||
"from the test folds. You can compare your own code with that from\n",
|
||||
"**Scikit-Learn** if needed. \n",
|
||||
"\n",
|
||||
"Compare the MSE you get from your cross-validation code with the one\n",
|
||||
"you got from your **bootstrap** code. Comment your results. Try $5-10$\n",
|
||||
"folds. You can also compare your own cross-validation code with the\n",
|
||||
"one provided by **Scikit-Learn**.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"### Exercise: Ridge Regression on the Franke function with resampling\n",
|
||||
"\n",
|
||||
"Write your own code for the Ridge method, either using matrix\n",
|
||||
"inversion or the singular value decomposition as done in the previous\n",
|
||||
"exercise. Perform the same bootstrap analysis as in the\n",
|
||||
"Exercise 2 (for the same polynomials) and the cross-validation in exercise 3 but now for different values of $\\lambda$. Compare and\n",
|
||||
"analyze your results with those obtained in exercises 1-3. Study the\n",
|
||||
"dependence on $\\lambda$.\n",
|
||||
"\n",
|
||||
"Study also the bias-variance trade-off as function of various values of\n",
|
||||
"the parameter $\\lambda$. For the bias-variance trade-off, use the **bootstrap** resampling method. Comment your results. \n",
|
||||
"\n",
|
||||
"### Exercise: Lasso Regression on the Franke function with resampling\n",
|
||||
"\n",
|
||||
"This exercise is essentially a repeat of the previous two ones, but now\n",
|
||||
"with Lasso regression. Write either your own code (difficult and optional) or, in this case,\n",
|
||||
"you can also use the functionalities of **Scikit-Learn** (recommended). \n",
|
||||
"Give a\n",
|
||||
"critical discussion of the three methods and a judgement of which\n",
|
||||
"model fits the data best. Perform here as well an analysis of the bias-variance trade-off using the **bootstrap** resampling technique and an analysis of the mean squared error using cross-validation. \n",
|
||||
"\n",
|
||||
"### Exercise: Analysis of real data\n",
|
||||
"\n",
|
||||
"With our codes functioning and having been tested properly on a\n",
|
||||
"simpler function we are now ready to look at real data. We will\n",
|
||||
"essentially repeat in this exercise what was done in exercises 1-5. However, we\n",
|
||||
"need first to download the data and prepare properly the inputs to our\n",
|
||||
"codes. We are going to download digital terrain data from the website\n",
|
||||
"<https://earthexplorer.usgs.gov/>,\n",
|
||||
"\n",
|
||||
"Or, if you prefer, we have placed selected datafiles at <https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects/2021/Project1/DataFiles>\n",
|
||||
"\n",
|
||||
"In order to obtain data for a specific region, you need to register as\n",
|
||||
"a user (free) at this website and then decide upon which area you want\n",
|
||||
"to fetch the digital terrain data from. In order to be able to read\n",
|
||||
"the data properly, you need to specify that the format should be **SRTM\n",
|
||||
"Arc-Second Global** and download the data as a **GeoTIF** file. The\n",
|
||||
"files are then stored in *tif* format which can be imported into a\n",
|
||||
"Python program using"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"collapsed": false,
|
||||
"editable": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"scipy.misc.imread"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Here is a simple part of a Python code which reads and plots the data\n",
|
||||
"from such files"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"collapsed": false,
|
||||
"editable": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import numpy as np\n",
|
||||
"from imageio import imread\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"from mpl_toolkits.mplot3d import Axes3D\n",
|
||||
"from matplotlib import cm\n",
|
||||
"\n",
|
||||
"# Load the terrain\n",
|
||||
"terrain1 = imread('SRTM_data_Norway_1.tif')\n",
|
||||
"# Show the terrain\n",
|
||||
"plt.figure()\n",
|
||||
"plt.title('Terrain over Norway 1')\n",
|
||||
"plt.imshow(terrain1, cmap='gray')\n",
|
||||
"plt.xlabel('X')\n",
|
||||
"plt.ylabel('Y')\n",
|
||||
"plt.show()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"If you should have problems in downloading the digital terrain data,\n",
|
||||
"we provide two examples under the data folder of project 1. One is\n",
|
||||
"from a region close to Stavanger in Norway and the other Møsvatn\n",
|
||||
"Austfjell, again in Norway.\n",
|
||||
"Feel free to produce your own terrain data.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"Alternatively, if you would like to use another data set, feel free to do so. This could be data close to your reseach area or simply a data set you found interesting. See for example [kaggle.com](https://www.kaggle.com/datasets) for examples.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"Our final part deals with the parameterization of your digital terrain\n",
|
||||
"data (or your own data). We will apply all three methods for linear regression, the same type (or higher order) of polynomial\n",
|
||||
"approximation and cross-validation as resampling technique to evaluate which\n",
|
||||
"model fits the data best.\n",
|
||||
"\n",
|
||||
"At the end, you should present a critical evaluation of your results\n",
|
||||
"and discuss the applicability of these regression methods to the type\n",
|
||||
"of data presented here (either the terrain data we propose or other data sets)."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {},
|
||||
|
||||
Reference in New Issue
Block a user