741 lines
28 KiB
Plaintext
741 lines
28 KiB
Plaintext
{
|
||
"cells": [
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- dom:TITLE: Homework 2, weeks 36 and 37 -->\n",
|
||
"# Homework 2, weeks 36 and 37\n",
|
||
"<!-- dom:AUTHOR: [Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html) at Department of Physics, University of Oslo, Norway -->\n",
|
||
"<!-- Author: --> \n",
|
||
"**[Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html)**, Department of Physics, University of Oslo, Norway\n",
|
||
"\n",
|
||
"Date: **Sep 8, 2020**\n",
|
||
"\n",
|
||
"Copyright 1999-2020, [Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html). Released under CC Attribution-NonCommercial 4.0 license\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"<!-- --- begin exercise --- -->\n",
|
||
"\n",
|
||
"## Exercise 1: Adding Ridge and Lasso Regression\n",
|
||
"\n",
|
||
"This exercise is a continuation of exercise 3 from exercise set 1 (week 35). We will\n",
|
||
"use the same function to generate our data set, still staying with a\n",
|
||
"simple function $y(x)$ which we want to fit using linear regression,\n",
|
||
"but now extending the analysis to include the Ridge and the Lasso\n",
|
||
"regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods, see the [regression slides](https://compphysics.github.io/MachineLearning/doc/pub/Regression/html/Regression-bs.html)). \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": 1,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"x = np.random.rand(100)\n",
|
||
"y = 2.0+5*x*x+0.1*np.random.randn(100)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"**a)**\n",
|
||
"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",
|
||
"\n",
|
||
"<!-- --- begin solution of exercise --- -->\n",
|
||
"**Solution.**\n",
|
||
"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."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 2,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"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",
|
||
"from sklearn.preprocessing import StandardScaler\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",
|
||
"scaler = StandardScaler()\n",
|
||
"scaler.fit(X_train)\n",
|
||
"X_train_scaled = scaler.transform(X_train)\n",
|
||
"X_test_scaled = scaler.transform(X_test)\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",
|
||
"# 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",
|
||
"MSEPredict = np.zeros(nlambdas)\n",
|
||
"MSETrain = np.zeros(nlambdas)\n",
|
||
"lambdas = np.logspace(-4, 1, nlambdas)\n",
|
||
"for i in range(nlambdas):\n",
|
||
" lmb = lambdas[i]\n",
|
||
" Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n",
|
||
" # and then make the prediction\n",
|
||
" ytildeRidge = X_train @ Ridgebeta\n",
|
||
" ypredictRidge = X_test @ Ridgebeta\n",
|
||
" MSEPredict[i] = MSE(y_test,ypredictRidge)\n",
|
||
" MSETrain[i] = MSE(y_train,ytildeRidge)\n",
|
||
"# Now plot the results\n",
|
||
"plt.figure()\n",
|
||
"plt.plot(np.log10(lambdas), MSETrain, label = 'MSE Ridge train')\n",
|
||
"plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Test')\n",
|
||
"plt.xlabel('log10(lambda)')\n",
|
||
"plt.ylabel('MSE')\n",
|
||
"plt.legend()\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- --- end solution of exercise --- -->\n",
|
||
"\n",
|
||
"**b)**\n",
|
||
"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$.\n",
|
||
"\n",
|
||
"\n",
|
||
"<!-- --- begin solution of exercise --- -->\n",
|
||
"**Solution.**\n",
|
||
"To use **scikit-learn** with Ridge, we simply need to add the relevant function **Ridge()**, as done in the code here."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 3,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"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",
|
||
"import sklearn.linear_model as skl\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",
|
||
"scaler = StandardScaler()\n",
|
||
"scaler.fit(X_train)\n",
|
||
"X_train_scaled = scaler.transform(X_train)\n",
|
||
"X_test_scaled = scaler.transform(X_test)\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",
|
||
"# 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 = 100\n",
|
||
"MSEPredict = np.zeros(nlambdas)\n",
|
||
"MSEPredictSKL = np.zeros(nlambdas)\n",
|
||
"MSETrain = np.zeros(nlambdas)\n",
|
||
"lambdas = np.logspace(-4, 0, nlambdas)\n",
|
||
"for i in range(nlambdas):\n",
|
||
" lmb = lambdas[i]\n",
|
||
" # add ridge\n",
|
||
" clf_ridge = skl.Ridge(alpha=lmb).fit(X_train, y_train)\n",
|
||
" yridge = clf_ridge.predict(X_test)\n",
|
||
" Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n",
|
||
" # and then make the prediction\n",
|
||
" ytildeRidge = X_train @ Ridgebeta\n",
|
||
" ypredictRidge = X_test @ Ridgebeta\n",
|
||
" MSEPredict[i] = MSE(y_test,ypredictRidge)\n",
|
||
" MSEPredictSKL[i] = MSE(y_test,yridge)\n",
|
||
" MSETrain[i] = MSE(y_train,ytildeRidge)\n",
|
||
"#then plot the results\n",
|
||
"plt.figure()\n",
|
||
"plt.plot(np.log10(lambdas), MSETrain, label = 'MSE Ridge train')\n",
|
||
"plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Test')\n",
|
||
"plt.plot(np.log10(lambdas), MSEPredictSKL, 'g--', label = 'MSE Ridge sickit-learn Test')\n",
|
||
"plt.xlabel('log10(lambda)')\n",
|
||
"plt.ylabel('MSE')\n",
|
||
"plt.legend()\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- --- end solution of exercise --- -->\n",
|
||
"\n",
|
||
"**c)**\n",
|
||
"Our next step is to study the variance of the parameters $\\beta_1$ and $\\beta_2$ (assuming that we are parameterizing our function with a second-order polynomial). We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function or using **Scikit-Learn** to find the parameters $\\beta$. From your results calculate the variance of these parameters (recall that this is equal to the diagonal elements of the matrix $(\\hat{X}^T\\hat{X})+\\lambda\\hat{I})^{-1}$). Discuss the results of these variances as functions of $\\lambda$. In particular, try to link your discussion with the discussion in Hastie *et al.* and their figures 3.10 and 3.11. **Scikit-Learn** may not provide the variance of the parameters $\\beta$. This needs to be checked. With your own code you can however do so.\n",
|
||
"\n",
|
||
"\n",
|
||
"<!-- --- begin solution of exercise --- -->\n",
|
||
"**Solution.**"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 4,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"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",
|
||
"import sklearn.linear_model as skl\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",
|
||
"scaler = StandardScaler()\n",
|
||
"scaler.fit(X_train)\n",
|
||
"X_train_scaled = scaler.transform(X_train)\n",
|
||
"X_test_scaled = scaler.transform(X_test)\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",
|
||
"# The variance is given by the inverse of the matrix X^TX\n",
|
||
"print(np.linalg.inv(X_train.T @ X_train))\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 = 10\n",
|
||
"MSEPredict = np.zeros(nlambdas)\n",
|
||
"MSEPredictSKL = np.zeros(nlambdas)\n",
|
||
"MSETrain = np.zeros(nlambdas)\n",
|
||
"lambdas = np.logspace(-4, 0, nlambdas)\n",
|
||
"for i in range(nlambdas):\n",
|
||
" lmb = lambdas[i]\n",
|
||
" Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n",
|
||
" print(np.linalg.inv(X_train.T @ X_train+lmb*I))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- --- end solution of exercise --- -->\n",
|
||
"\n",
|
||
"**d)**\n",
|
||
"Repeat the previous step but add now the Lasso method, see equation (3.53) of Hastie *et al.*. Discuss your results and compare with standard regression and the Ridge regression results. You can write your own code or use the functionality of **scikit-learn**. We recommend the latter since we have not yet discussed how to solve the Lasso equations numerically. Also, you do not need to compute the variance of the parameters $\\beta$ but you can extract their values and study their behavior as functions of the regularization parameter $\\lambda$.\n",
|
||
"\n",
|
||
"\n",
|
||
"<!-- --- begin solution of exercise --- -->\n",
|
||
"**Solution.**"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 5,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"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",
|
||
"import sklearn.linear_model as skl\n",
|
||
"#from sklearn.linear_model import LinearRegression, Ridge, Lasso\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",
|
||
"scaler = StandardScaler()\n",
|
||
"scaler.fit(X_train)\n",
|
||
"X_train_scaled = scaler.transform(X_train)\n",
|
||
"X_test_scaled = scaler.transform(X_test)\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",
|
||
"# 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 = 100\n",
|
||
"MSEPredictLasso = np.zeros(nlambdas)\n",
|
||
"MSEPredictRidge = np.zeros(nlambdas)\n",
|
||
"lambdas = np.logspace(-4, 0, nlambdas)\n",
|
||
"for i in range(nlambdas):\n",
|
||
" lmb = lambdas[i]\n",
|
||
" # add ridge\n",
|
||
" clf_ridge = skl.Ridge(alpha=lmb).fit(X_train, y_train)\n",
|
||
" clf_lasso = skl.Lasso(alpha=lmb).fit(X_train, y_train)\n",
|
||
" yridge = clf_ridge.predict(X_test)\n",
|
||
" ylasso = clf_lasso.predict(X_test)\n",
|
||
" MSEPredictLasso[i] = MSE(y_test,ylasso)\n",
|
||
" MSEPredictRidge[i] = MSE(y_test,yridge)\n",
|
||
"#then plot the results\n",
|
||
"plt.figure()\n",
|
||
"plt.plot(np.log10(lambdas), MSEPredictRidge, 'r--', label = 'MSE Ridge Test')\n",
|
||
"plt.plot(np.log10(lambdas), MSEPredictLasso, 'g--', label = 'MSE Lasso Test')\n",
|
||
"plt.xlabel('log10(lambda)')\n",
|
||
"plt.ylabel('MSE')\n",
|
||
"plt.legend()\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- --- end solution of exercise --- -->\n",
|
||
"\n",
|
||
"**e)**\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",
|
||
"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.\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",
|
||
"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": [
|
||
"Discuss these quantities as functions of the variable $\\lambda$ in the Ridge and Lasso regression methods.\n",
|
||
"\n",
|
||
"\n",
|
||
"<!-- --- begin solution of exercise --- -->\n",
|
||
"**Solution.**\n",
|
||
"These results can all be studied with the codes we have above. These scores are included in the codes above.\n",
|
||
"\n",
|
||
"<!-- --- end solution of exercise --- -->\n",
|
||
"\n",
|
||
"\n",
|
||
"<!-- --- end exercise --- -->\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"<!-- --- begin exercise --- -->\n",
|
||
"\n",
|
||
"## Exercise 2: 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",
|
||
"\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",
|
||
"\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": 6,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"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",
|
||
"metadata": {},
|
||
"source": [
|
||
"Then we can use the standard scaler to scale our data as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 7,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"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",
|
||
"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",
|
||
"We will also use Ridge and Lasso regression. \n",
|
||
"\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": 8,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"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",
|
||
"metadata": {},
|
||
"source": [
|
||
"where $y$ is the function we want to fit with a given polynomial.\n",
|
||
"\n",
|
||
"\n",
|
||
"**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.\n",
|
||
"\n",
|
||
"\n",
|
||
"<!-- --- begin solution of exercise --- -->\n",
|
||
"**Solution.**"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 9,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"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 = 50\n",
|
||
"maxdegree = 5\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",
|
||
"scaler = StandardScaler()\n",
|
||
"scaler.fit(X_train)\n",
|
||
"x_train_scaled = scaler.transform(x_train)\n",
|
||
"x_test_scaled = scaler.transform(x_test)\n",
|
||
"\n",
|
||
"for degree in range(maxdegree):\n",
|
||
" model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
|
||
" clf = model.fit(x_train_scale,y_train)\n",
|
||
" y_fit = clf.predict(x_train_scaled)\n",
|
||
" y_pred = clf.predict(x_test_scaled) \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",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- --- end solution of exercise --- -->\n",
|
||
"\n",
|
||
"**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.\n",
|
||
"\n",
|
||
"\n",
|
||
"<!-- --- begin solution of exercise --- -->\n",
|
||
"**Solution.**\n",
|
||
"This requires a simple extension to the above code where you simply add a statement calling the $R2$ function included in the same code.\n",
|
||
"\n",
|
||
"<!-- --- end solution of exercise --- -->\n",
|
||
"\n",
|
||
"**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)?\n",
|
||
"\n",
|
||
"\n",
|
||
"<!-- --- begin solution of exercise --- -->\n",
|
||
"**Solution.**\n",
|
||
"Here you simply need to change the degree of the polynomial in the above code to $n=15$.\n",
|
||
"\n",
|
||
"<!-- --- end solution of exercise --- -->\n",
|
||
"\n",
|
||
"**d)**\n",
|
||
"Repeat part (2c) but now using Ridge regressions with various hyperparameters $\\lambda$. Make the same plots for the optimal $\\lambda$ value for each polynomial degree. Compare these results with those from the standard OLS approach.\n",
|
||
"\n",
|
||
"\n",
|
||
"<!-- --- begin solution of exercise --- -->\n",
|
||
"**Solution.**\n",
|
||
"Here you need to add for example the same loop over the parameters $\\lambda$ as you did in the first exercise, that is add"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 10,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"nlambdas = 100\n",
|
||
"MSEPredictRidge = np.zeros(nlambdas)\n",
|
||
"lambdas = np.logspace(-4, 0, nlambdas)\n",
|
||
"for i in range(nlambdas):\n",
|
||
" lmb = lambdas[i]\n",
|
||
" # add ridge\n",
|
||
" clf_ridge = skl.Ridge(alpha=lmb).fit(X_train_scaled, y_train)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"The plotting functionality of the first exercise can be reused here as well.\n",
|
||
"\n",
|
||
"<!-- --- end solution of exercise --- -->\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"<!-- --- end exercise --- -->"
|
||
]
|
||
}
|
||
],
|
||
"metadata": {},
|
||
"nbformat": 4,
|
||
"nbformat_minor": 2
|
||
}
|