<jupyter_start><jupyter_text>Project 1 on Machine Learning, deadline October 4, 2020  **[Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html)**, University of Oslo, NorwayDate: **Sep 10, 2021** Regression analysis and resampling methodsThe main aim of this project is to study in more detail variousregression methods, including the Ordinary Least Squares (OLS) method,The total score is **100** points. Each subtask has its own final score.We will first study how to **fit polynomials to a specifictwo-dimensional function called [Franke'sfunction](http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf)**.  Thisis a function which has been widely used when testing variousinterpolation and fitting algorithms. Furthermore, after havingestablished the model and the method, we will **employ resamplingtechniques such as cross-validation and/or bootstrap** in order to perform aproper assessment of our models. We will also study in detail theso-called **Bias-Variance trade off**.The Franke function, which is a weighted sum of four exponentials reads as follows $$\begin{align*}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)} \\&+\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) }.\end{align*}$$ The function will be defined for $x,y\in [0,1]$.  Our first step willbe to perform an OLS regression analysis of this function, trying outa polynomial fit with an $x$ and $y$ dependence of the form $[x, y,x^2, y^2, xy, \dots]$. We will also include bootstrap first asa resampling technique.  After that we will include the cross-validation technique. As in homeworks 1 and 2, we can use a uniformdistribution to set up the arrays of values for $x$ and $y$, or as inthe example below just a set of fixed values for $x$ and $y$ with a given stepsize.  We will fit afunction (for example a polynomial) of $x$ and $y$.  Thereafter wewill repeat much of the same procedure using the Ridge and Lassoregression methods, introducing thus a dependence on the bias(penalty) $\lambda$.Finally we are going to use (real) digital terrain data and try toreproduce these data using the same methods. We will also try to gobeyond the second-order polynomials metioned above and explore which polynomial fits the data best.The Python code for the Franke function is included here (it performs also a three-dimensional plot of it)<jupyter_code>%matplotlib inline

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
from random import random, seed

fig=plt.figure(figsize=(8, 7))
ax = fig.gca(projection='3d')

# Make data.
x = np.arange(0, 1, 0.05)
y = np.arange(0, 1, 0.05)
x, y = np.meshgrid(x,y)
title="Franke Function"


def FrankeFunction(x,y):
    term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
    term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
    term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
    term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
    return term1 + term2 + term3 + term4


#z = FrankeFunction(x, y)
#print(z.size)

np.random.seed(1234)

n = 25

x = np.linspace(0,1,n)
y = np.linspace(0,1,n) 
x, y = np.meshgrid(x,y)

sigma_N = 0.1; mu_N = 0 #change for value of sigma_N to appropriate values
z = FrankeFunction(x,y) +mu_N+sigma_N*np.random.randn(n,n)
title="Original vanilla dataset:\nFranke Function with stochastic noise"

####################################################################
# Plot the surface.

surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)

# Customize the z axis.
ax.set_zlim(-0.10, 1.40)
#ax.zaxis.set_major_locator(LinearLocator(15))
ax.set_xlabel(r"$x$")
ax.set_ylabel(r"$y$")
ax.set_zlabel(r"$z$")
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
ax.set_title(title)

# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()<jupyter_output><empty_output><jupyter_text>Exercise 1: Ordinary Least Square (OLS) on the Franke function (score 10 points)We will generate our own dataset for a function$\mathrm{FrankeFunction}(x,y)$ with $x,y \in [0,1]$. The function$f(x,y)$ is the Franke function. You should explore also the additionof an added stochastic noise to this function using the normaldistribution $\cal{N}(0,1)$.*Write your own code* (using either a matrix inversion or a singularvalue decomposition from e.g., **numpy** ) or use your code fromhomeworks 1 and 2 and perform a standard least square regressionanalysis using polynomials in $x$ and $y$ up to fifth order. Find the[confidence intervals](https://en.wikipedia.org/wiki/Confidence_interval) of the parameters (estimators) $\beta$ by computing theirvariances, evaluate the Mean Squared error (MSE) $$MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,$$ and the $R^2$ score function.  If $\tilde{\hat{y}}_i$ is the predictedvalue of the $i-th$ sample and $y_i$ is the corresponding true value,then the score $R^2$ is defined as $$R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2},$$ where we have defined the mean value  of $\hat{y}$ as $$\bar{y} =  \frac{1}{n} \sum_{i=0}^{n - 1} y_i.$$ Your code has to include a scaling of the data (for example bysubtracting the mean value), anda split of the data in training and test data. For this exercise you caneither write your own code or use for example the function forsplitting training data provided by the library **Scikit-Learn** (makesure you have installed it).  This function is called$train\_test\_split$.  **You should present a critical discussion of why and how you have scaled or not scaled the data**.It is normal in essentially all Machine Learning studies to split thedata in a training set and a test set (eventually  also an additionalvalidation set).  Thereis no explicit recipe for how much data should be included as trainingdata and say test data.  An accepted rule of thumb is to useapproximately $2/3$ to $4/5$ of the data as training data.You can easily reuse the solutions to your exercises from week 35 and week 36. Exercise 2: Bias-variance trade-off and resampling techniques (score 15 points)Our aim here is to study the bias-variance trade-off by implementing the **bootstrap** resampling technique.With a code which does OLS and includes resampling techniques, we will now discuss the bias-variance trade-off in the context ofcontinuous predictions such as regression. However, many of theintuitions and ideas discussed here also carry over to classificationtasks and basically all Machine Learning algorithms.  ––––––––––––––––––––––––––––––––––––––––1) Before you perform an analysis of the bias-variance trade-off on your test data, makefirst a **figure similar** to Fig. 2.11 of Hastie, Tibshirani, andFriedman. Figure 2.11 of this reference **displays only the test and training MSEs**. The test MSE can be used to **indicate possible regions of low/high bias and variance**. *You will most likely not get anequally smooth curve!* ––––––––––––––––––––––––––––––––––––––––With this result we move on to the bias-variance trade-off analysis.Consider adataset $\mathcal{L}$ consisting of the data$\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}$.Let us assume that the true data is generated from a noisy model $$\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon}.$$ Here $\epsilon$ is normally distributed with mean zero and standarddeviation $\sigma^2$.In our derivation of the ordinary least squares method we defined thenan approximation to the function $f$ in terms of the parameters$\boldsymbol{\beta}$ and the design matrix $\boldsymbol{X}$ which embody our model,that is $\boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta}$.The parameters $\boldsymbol{\beta}$ are in turn found by optimizing the meanssquared error via the so-called cost function $$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].$$ Here the expected value $\mathbb{E}$ is the sample value. 2) **Show that you can rewrite** this as $$\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.$$ **Explain what the terms mean, which one is the bias and which one isthe variance and discuss their interpretations.** ––––––––––––––––––––––––––––––––––––––––3) **Perform then a bias-variance analysis of the Franke function bystudying the MSE value as function of the complexity of your model.****Discuss the bias and variance trade-off as functionof your model complexity (the degree of the polynomial) and the numberof data points**, and possibly also your training and test data using the **bootstrap** resampling method.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$. Exercise 3:  Cross-validation as resampling techniques, adding more complexity (score 15 points)The aim here is to write your own code for another widely popularresampling technique, the so-called cross-validation method.  Again,before you start with cross-validation approach, you should scale yourdata.Implement the $k$-fold cross-validation algorithm (write your owncode) and evaluate again the MSE function resultingfrom the test folds. You can compare your own code with that from**Scikit-Learn** if needed. Compare the MSE you get from your cross-validation code with the oneyou got from your **bootstrap** code. Comment your results. Try $5-10$folds.  You can also compare your own cross-validation code with theone provided by **Scikit-Learn**. Exercise 4: Ridge Regression on the Franke function  with resampling (score 20 points)Write your own code for the Ridge method, either using matrixinversion or the singular value decomposition as done in the previousexercise. Perform the same bootstrap analysis as in theExercise 2  (for the same polynomials) and the cross-validation  in exercise 3 but now for different values of $\lambda$. Compare andanalyze your results with those obtained in exercises 1-3. Study thedependence on $\lambda$.Study also the bias-variance trade-off as function of various values ofthe parameter $\lambda$. For the bias-variance trade-off, use the **bootstrap** resampling method. Comment your results.  Exercise 5: Lasso Regression on the Franke function  with resampling (Score 10 points))This exercise is essentially a repeat of the previous two ones, but nowwith Lasso regression. Write either your own code (difficult and optional) or, in this case,you can also use the functionalities of **Scikit-Learn** (recommended). Give acritical discussion of the three methods and a judgement of whichmodel 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.  Exercise 6: Analysis of real data  (score 30 points)With our codes functioning and having been tested properly on asimpler function we are now ready to look at real data. We willessentially repeat in this exercise what was done in exercises 1-5. However, weneed first to download the data and prepare properly the inputs to ourcodes.  We are going to download digital terrain data from the website,Or, if you prefer, we have placed selected datafiles at In order to obtain data for a specific region, you need to register asa user (free) at this website and then decide upon which area you wantto fetch the digital terrain data from.  In order to be able to readthe data properly, you need to specify that the format should be **SRTMArc-Second Global** and download the data as a **GeoTIF** file.  Thefiles are then stored in *tif* format which can be imported into aPython program using<jupyter_code>scipy.misc.imread<jupyter_output><empty_output><jupyter_text>Here is a simple part of a Python code which reads and plots the datafrom such files<jupyter_code>import numpy as np
from imageio import imread
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm

# Load the terrain
terrain1 = imread('SRTM_data_Norway_1.tif')
# Show the terrain
plt.figure()
plt.title('Terrain over Norway 1')
plt.imshow(terrain1, cmap='gray')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11894925559279756, 'fraction_numerical': 0.020656325512510718, 'mean_word_length': 5.026303428839831, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 1, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '141707', 'license': 'MIT', 'n_tokens_mistral': 4006, 'n_tokens_neox': 3684, 'n_words': 1605, 'path': 'Projects/Project1/Project1.ipynb', 'repo_name': 'adelezaini/MachineLearning', 'size': '12829'}