2244 lines
141 KiB
Plaintext
2244 lines
141 KiB
Plaintext
{
|
||
"cells": [
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- dom:TITLE: Week 37: Summary of Ridge and Lasso Regression and Resampling Methods -->\n",
|
||
"# Week 37: Summary of Ridge and Lasso Regression and Resampling Methods\n",
|
||
"<!-- dom:AUTHOR: Morten Hjorth-Jensen at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University -->\n",
|
||
"<!-- Author: --> \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: **Sep 28, 2021**\n",
|
||
"\n",
|
||
"Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Plans for week 37\n",
|
||
"\n",
|
||
"* Thursday September 16: Summary of Ridge and Lasso with examples and start resampling techniques\n",
|
||
"\n",
|
||
"a. [Video of Lecture, first part](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureSeptember16Firstpart.mp4?vrtx=view-as-webpage)\n",
|
||
"\n",
|
||
"b. [Video of Lecture, second part](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureSeptember16SecondPart.mp4?vrtx=view-as-webpage)\n",
|
||
"\n",
|
||
"\n",
|
||
"* Friday September 17: Resampling methods, Cross-validation, Bootstrapping and jackknife\n",
|
||
"\n",
|
||
"a. [Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureSeptember17.mp4?vrtx=view-as-webpage)\n",
|
||
"\n",
|
||
"\n",
|
||
"Recommended Reading:\n",
|
||
"1. Lectures on Resampling methods (these lectures)\n",
|
||
"\n",
|
||
"2. Bishop 1.3 (cross-validation) and 3.2 (bias-variance tradeoff)\n",
|
||
"\n",
|
||
"3. Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap). This chapter is better than Bishop's on these topics. Goodfellow et al discuss this in a superficial way in sections 5.2-5.5.\n",
|
||
"\n",
|
||
"## Thursday September 16, Summary of Ridge and Lasso Regression and start Resampling methods\n",
|
||
"\n",
|
||
"\n",
|
||
"## Deriving OLS from a probability distribution\n",
|
||
"\n",
|
||
"Our basic assumption when we derived the OLS equations was to assume\n",
|
||
"that our output is determined by a given continuous function\n",
|
||
"$f(\\boldsymbol{x})$ and a random noise $\\boldsymbol{\\epsilon}$ given by the normal\n",
|
||
"distribution with zero mean value and an undetermined variance\n",
|
||
"$\\sigma^2$.\n",
|
||
"\n",
|
||
"We found above that the outputs $\\boldsymbol{y}$ have a mean value given by\n",
|
||
"$\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$ and variance $\\sigma^2$. Since the entries to\n",
|
||
"the design matrix are not stochastic variables, we can assume that the\n",
|
||
"probability distribution of our targets is also a normal distribution\n",
|
||
"but now with mean value $\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$. This means that a\n",
|
||
"single output $y_i$ is given by the Gaussian distribution"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"y_i\\sim \\mathcal{N}(\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta}, \\sigma^2)=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Independent and Identically Distrubuted (iid)\n",
|
||
"\n",
|
||
"We assume now that the various $y_i$ values are stochastically distributed according to the above Gaussian distribution. \n",
|
||
"We define this distribution as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"p(y_i, \\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"which reads as finding the likelihood of an event $y_i$ with the input variables $\\boldsymbol{X}$ given the parameters (to be determined) $\\boldsymbol{\\beta}$.\n",
|
||
"\n",
|
||
"Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event $\\boldsymbol{y}$ as the product of the single events, that is we have"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"p(\\boldsymbol{y},\\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}=\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta}).\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"We will write this in a more compact form reserving $\\boldsymbol{D}$ for the domain of events, including the ouputs (targets) and the inputs. That is\n",
|
||
"in case we have a simple one-dimensional input and output case"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})].\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"In the more general case the various inputs should be replaced by the possible features represented by the input data set $\\boldsymbol{X}$. \n",
|
||
"We can now rewrite the above probability as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"It is a conditional probability (see below) and reads as the likelihood of a domain of events $\\boldsymbol{D}$ given a set of parameters $\\boldsymbol{\\beta}$.\n",
|
||
"\n",
|
||
"## Maximum Likelihood Estimation (MLE)\n",
|
||
"\n",
|
||
"In statistics, maximum likelihood estimation (MLE) is a method of\n",
|
||
"estimating the parameters of an assumed probability distribution,\n",
|
||
"given some observed data. This is achieved by maximizing a likelihood\n",
|
||
"function so that, under the assumed statistical model, the observed\n",
|
||
"data is the most probable. \n",
|
||
"\n",
|
||
"\n",
|
||
"We will assume here that our events are given by the above Gaussian\n",
|
||
"distribution and we will determine the optimal parameters $\\beta$ by\n",
|
||
"maximizing the above PDF. However, computing the derivatives of a\n",
|
||
"product function is cumbersome and can easily lead to overflow and/or\n",
|
||
"underflowproblems, with potentials for loss of numerical precision.\n",
|
||
"\n",
|
||
"\n",
|
||
"In practice, it is more convenient to maximize the logarithm of the\n",
|
||
"PDF because it is a monotonically increasing function of the argument.\n",
|
||
"Alternatively, and this will be our option, we will minimize the\n",
|
||
"negative of the logarithm since this is a monotonically decreasing\n",
|
||
"function.\n",
|
||
"\n",
|
||
"Note also that maximization/minimization of the logarithm of the PDF\n",
|
||
"is equivalent to the maximization/minimization of the function itself.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## A new Cost Function\n",
|
||
"\n",
|
||
"We could now define a new cost function to minimize, namely the negative logarithm of the above PDF"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"C(\\boldsymbol{\\beta}=-\\log{\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})}=-\\sum_{i=0}^{n-1}\\log{p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"which becomes"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"C(\\boldsymbol{\\beta}=\\frac{n}{2}\\log{2\\pi\\sigma^2}+\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"Taking the derivative of the *new* cost function with respect to the parameters $\\beta$ we recognize our familiar OLS equation, namely"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right) =0,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"which leads to the well-known OLS equation for the optimal paramters $\\beta$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}!\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Bayes' Theorem\n",
|
||
"\n",
|
||
"If we combine the conditional probability with the marginal probability and the standard product rule, we have"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"which we can rewrite as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"p(X\\vert Y)= \\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}=\\frac{p(Y\\vert X)p(X)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"which is Bayes' theorem. It allows us to evaluate the uncertainty in in $X$ after we have observed $Y$. We can easily interchange $X$ with $Y$. \n",
|
||
"\n",
|
||
"## Interpretations of Bayes' Theorem\n",
|
||
"\n",
|
||
"The quantity $p(Y\\vert X)$ on the right-hand side of the theorem is\n",
|
||
"evaluated for the observed data $Y$ and can be viewed as a function of\n",
|
||
"the parameter space represented by $X$. This function is not\n",
|
||
"necesseraly normalized and is normally called the likelihood function.\n",
|
||
"\n",
|
||
"The function $p(X)$ on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution.\n",
|
||
"\n",
|
||
"## Test Function for what happens with OLS, Ridge and Lasso\n",
|
||
"\n",
|
||
"We will play around with a study of the values for the optimal\n",
|
||
"parameters $\\boldsymbol{\\beta}$ using OLS, Ridge and Lasso regression. For\n",
|
||
"OLS, you will notice as function of the noise and polynomial degree,\n",
|
||
"that the parameters $\\beta$ will fluctuate from order to order in the\n",
|
||
"polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS.\n",
|
||
"\n",
|
||
"For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"%matplotlib inline\n",
|
||
"\n",
|
||
"import numpy as np\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from sklearn.model_selection import train_test_split\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",
|
||
"# Make data set.\n",
|
||
"n = 10000\n",
|
||
"x = np.random.rand(n)\n",
|
||
"y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n",
|
||
"\n",
|
||
"Maxpolydegree = 5\n",
|
||
"X = np.zeros((len(x),Maxpolydegree))\n",
|
||
"X[:,0] = 1.0\n",
|
||
"\n",
|
||
"for polydegree in range(1, Maxpolydegree):\n",
|
||
" for degree in range(polydegree):\n",
|
||
" X[:,degree] = x**(degree)\n",
|
||
"\n",
|
||
"\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.pinv(X_train.T @ X_train) @ X_train.T @ y_train\n",
|
||
"print(OLSbeta)\n",
|
||
"ypredictOLS = X_test @ OLSbeta\n",
|
||
"print(\"Test MSE OLS\")\n",
|
||
"print(MSE(y_test,ypredictOLS))\n",
|
||
"# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn\n",
|
||
"# Decide which values of lambda to use\n",
|
||
"nlambdas = 4\n",
|
||
"MSERidgePredict = np.zeros(nlambdas)\n",
|
||
"MSELassoPredict = np.zeros(nlambdas)\n",
|
||
"lambdas = np.logspace(-3, 1, nlambdas)\n",
|
||
"for i in range(nlambdas):\n",
|
||
" lmb = lambdas[i]\n",
|
||
" # Make the fit using Ridge and Lasso\n",
|
||
" RegRidge = linear_model.Ridge(lmb,fit_intercept=False)\n",
|
||
" RegRidge.fit(X_train,y_train)\n",
|
||
" RegLasso = linear_model.Lasso(lmb,fit_intercept=False)\n",
|
||
" RegLasso.fit(X_train,y_train)\n",
|
||
" # and then make the prediction\n",
|
||
" ypredictRidge = RegRidge.predict(X_test)\n",
|
||
" ypredictLasso = RegLasso.predict(X_test)\n",
|
||
" # Compute the MSE and print it\n",
|
||
" MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n",
|
||
" MSELassoPredict[i] = MSE(y_test,ypredictLasso)\n",
|
||
" print(lmb,RegRidge.coef_)\n",
|
||
" print(lmb,RegLasso.coef_)\n",
|
||
"# Now plot the results\n",
|
||
"plt.figure()\n",
|
||
"plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')\n",
|
||
"plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')\n",
|
||
"plt.xlabel('log10(lambda)')\n",
|
||
"plt.ylabel('MSE')\n",
|
||
"plt.legend()\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"How can we understand this? \n",
|
||
"\n",
|
||
"\n",
|
||
"## Rerunning the above code\n",
|
||
"\n",
|
||
"Let us write out the values of the coefficients $\\beta_i$ as functions\n",
|
||
"of the polynomial degree and noise. We will focus only on the Ridge\n",
|
||
"results and some few selected values of the hyperparameter $\\lambda$.\n",
|
||
"\n",
|
||
"If we don't include any noise and run this code for different values\n",
|
||
"of the polynomial degree, we notice that the results for $\\beta_i$ do\n",
|
||
"not show great changes from one order to the next. This is an\n",
|
||
"indication that for higher polynomial orders, our parameters become\n",
|
||
"less important.\n",
|
||
"\n",
|
||
"If we however add noise, what happens is that the polynomial fit is\n",
|
||
"trying to adjust the fit to traverse in the best possible way all data\n",
|
||
"points. This can lead to large fluctuations in the parameters\n",
|
||
"$\\beta_i$ as functions of polynomial order. It will also be reflected\n",
|
||
"in a larger value of the variance of each parameter $\\beta_i$. What\n",
|
||
"Ridge regression (and Lasso as well) are doing then is to try to\n",
|
||
"quench the fluctuations in the parameters of $\\beta_i$ which have a\n",
|
||
"large variance (normally for higher orders in the polynomial)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"import numpy as np\n",
|
||
"import pandas as pd\n",
|
||
"from IPython.display import display\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from sklearn.model_selection import train_test_split\n",
|
||
"from sklearn import linear_model\n",
|
||
"\n",
|
||
"# Make data set.\n",
|
||
"n = 1000\n",
|
||
"x = np.random.rand(n)\n",
|
||
"y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n",
|
||
"\n",
|
||
"Maxpolydegree = 5\n",
|
||
"X = np.zeros((len(x),Maxpolydegree))\n",
|
||
"X[:,0] = 1.0\n",
|
||
"\n",
|
||
"for polydegree in range(1, Maxpolydegree):\n",
|
||
" for degree in range(polydegree):\n",
|
||
" X[:,degree] = x**(degree)\n",
|
||
"\n",
|
||
"\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",
|
||
"# Decide which values of lambda to use\n",
|
||
"nlambdas = 5\n",
|
||
"lambdas = np.logspace(-3, 2, nlambdas)\n",
|
||
"for i in range(nlambdas):\n",
|
||
" lmb = lambdas[i]\n",
|
||
" # Make the fit using Ridge only\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",
|
||
" Coeffs = np.array(RegRidge.coef_)\n",
|
||
" BetaValues = pd.DataFrame(Coeffs)\n",
|
||
" BetaValues.columns = ['beta']\n",
|
||
" display(BetaValues)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Invoking Bayes' theorem\n",
|
||
"\n",
|
||
"Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression. \n",
|
||
"\n",
|
||
"For ordinary least squares we postulated that the maximum likelihood for the doamin of events $\\boldsymbol{D}$ (one-dimensional case)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})],\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"is given by"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set $\\boldsymbol{\\beta}$ given a domain of events $\\boldsymbol{D}$? That is, how can we define the posterior probability"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D}).\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"Bayes' theorem comes to our rescue here since (omitting the normalization constant)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})\\propto p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})p(\\boldsymbol{\\beta}).\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"We have a model for $p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})$ but need one for the **prior** $p(\\boldsymbol{\\beta}$! \n",
|
||
"\n",
|
||
"\n",
|
||
"## Ridge and Bayes\n",
|
||
"\n",
|
||
"With the posterior probability defined by a likelihood which we have\n",
|
||
"already modeled and an unknown prior, we are now ready to make\n",
|
||
"additional models for the prior.\n",
|
||
"\n",
|
||
"We can, based on our discussions of the variance of $\\boldsymbol{\\beta}$ and the mean value, assume that the prior for the values $\\boldsymbol{\\beta}$ is given by a Gaussian with mean value zero and variance $\\tau^2$, that is"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"Our posterior probability becomes then (omitting the normalization factor which is just a constant)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"p(\\boldsymbol{\\beta\\vert\\boldsymbol{D})}=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"We can now optimize this quantity with respect to $\\boldsymbol{\\beta}$. As we\n",
|
||
"did for OLS, this is most conveniently done by taking the negative\n",
|
||
"logarithm of the posterior probability. Doing so and leaving out the\n",
|
||
"constants terms that do not depend on $\\beta$, we have"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{2\\tau^2}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"and replacing $1/2\\tau^2$ with $\\lambda$ we have"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"which is our Ridge cost function! Nice, isn't it?\n",
|
||
"\n",
|
||
"## Lasso and Bayes\n",
|
||
"\n",
|
||
"To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution ([Laplace in this case](https://en.wikipedia.org/wiki/Laplace_distribution)) with zero mean value, that is"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"Our posterior probability becomes then (omitting the normalization factor which is just a constant)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"Taking the negative\n",
|
||
"logarithm of the posterior probability and leaving out the\n",
|
||
"constants terms that do not depend on $\\beta$, we have"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{\\tau}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"and replacing $1/\\tau$ with $\\lambda$ we have"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"which is our Lasso cost function! \n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Why resampling methods\n",
|
||
"\n",
|
||
"Before we proceed, we need to rethink what we have been doing. In our\n",
|
||
"eager to fit the data, we have omitted several important elements in\n",
|
||
"our regression analysis. In what follows we will\n",
|
||
"1. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff\n",
|
||
"\n",
|
||
"2. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more\n",
|
||
"\n",
|
||
"and discuss how to select a given model (one of the difficult parts in machine learning).\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Resampling methods\n",
|
||
"Resampling methods are an indispensable tool in modern\n",
|
||
"statistics. They involve repeatedly drawing samples from a training\n",
|
||
"set and refitting a model of interest on each sample in order to\n",
|
||
"obtain additional information about the fitted model. For example, in\n",
|
||
"order to estimate the variability of a linear regression fit, we can\n",
|
||
"repeatedly draw different samples from the training data, fit a linear\n",
|
||
"regression to each new sample, and then examine the extent to which\n",
|
||
"the resulting fits differ. Such an approach may allow us to obtain\n",
|
||
"information that would not be available from fitting the model only\n",
|
||
"once using the original training sample.\n",
|
||
"\n",
|
||
"Two resampling methods are often used in Machine Learning analyses,\n",
|
||
"1. The **bootstrap method**\n",
|
||
"\n",
|
||
"2. and **Cross-Validation**\n",
|
||
"\n",
|
||
"In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular\n",
|
||
"cross-validation and the bootstrap method.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Resampling approaches can be computationally expensive\n",
|
||
"\n",
|
||
"Resampling approaches can be computationally expensive, because they\n",
|
||
"involve fitting the same statistical method multiple times using\n",
|
||
"different subsets of the training data. However, due to recent\n",
|
||
"advances in computing power, the computational requirements of\n",
|
||
"resampling methods generally are not prohibitive. In this chapter, we\n",
|
||
"discuss two of the most commonly used resampling methods,\n",
|
||
"cross-validation and the bootstrap. Both methods are important tools\n",
|
||
"in the practical application of many statistical learning\n",
|
||
"procedures. For example, cross-validation can be used to estimate the\n",
|
||
"test error associated with a given statistical learning method in\n",
|
||
"order to evaluate its performance, or to select the appropriate level\n",
|
||
"of flexibility. The process of evaluating a model’s performance is\n",
|
||
"known as model assessment, whereas the process of selecting the proper\n",
|
||
"level of flexibility for a model is known as model selection. The\n",
|
||
"bootstrap is widely used.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Why resampling methods ?\n",
|
||
"**Statistical analysis.**\n",
|
||
"\n",
|
||
"\n",
|
||
"* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods which are widely used in statistical analyses.\n",
|
||
"\n",
|
||
"* The results can be analysed with the same statistical tools as we would use when analysing experimental data.\n",
|
||
"\n",
|
||
"* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n",
|
||
"\n",
|
||
" \n",
|
||
"\n",
|
||
"## Statistical analysis\n",
|
||
"\n",
|
||
"* As in other experiments, many numerical experiments have two classes of errors:\n",
|
||
"\n",
|
||
" * Statistical errors\n",
|
||
"\n",
|
||
" * Systematical errors\n",
|
||
"\n",
|
||
"\n",
|
||
"* Statistical errors can be estimated using standard tools from statistics\n",
|
||
"\n",
|
||
"* Systematical errors are method specific and must be treated differently from case to case.\n",
|
||
"\n",
|
||
" \n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Resampling methods\n",
|
||
"\n",
|
||
"With all these analytical equations for both the OLS and Ridge\n",
|
||
"regression, we will now outline how to assess a given model. This will\n",
|
||
"lead to a discussion of the so-called bias-variance tradeoff (see\n",
|
||
"below) and so-called resampling methods.\n",
|
||
"\n",
|
||
"One of the quantities we have discussed as a way to measure errors is\n",
|
||
"the mean-squared error (MSE), mainly used for fitting of continuous\n",
|
||
"functions. Another choice is the absolute error.\n",
|
||
"\n",
|
||
"In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,\n",
|
||
"we discuss the\n",
|
||
"1. prediction error or simply the **test error** $\\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the \n",
|
||
"\n",
|
||
"2. training error $\\mathrm{Err_{Train}}$, which is the average loss over the training data.\n",
|
||
"\n",
|
||
"As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.\n",
|
||
"For a certain level of complexity the test error will reach minimum, before starting to increase again. The\n",
|
||
"training error reaches a saturation.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Resampling methods: Jackknife and Bootstrap\n",
|
||
"\n",
|
||
"Two famous\n",
|
||
"resampling methods are the **independent bootstrap** and **the jackknife**. \n",
|
||
"\n",
|
||
"The jackknife is a special case of the independent bootstrap. Still, the jackknife was made\n",
|
||
"popular prior to the independent bootstrap. And as the popularity of\n",
|
||
"the independent bootstrap soared, new variants, such as **the dependent bootstrap** have also been developed..\n",
|
||
"\n",
|
||
"The Jackknife and independent bootstrap work for\n",
|
||
"independent, identically distributed random variables.\n",
|
||
"If these conditions are not\n",
|
||
"satisfied, the methods will fail. Yet, it should be said that if the data are\n",
|
||
"independent, identically distributed, and we only want to estimate the\n",
|
||
"variance of $\\overline{X}$ (which often is the case), then there is no\n",
|
||
"need for bootstrapping. \n",
|
||
"\n",
|
||
"## Resampling methods: Jackknife\n",
|
||
"\n",
|
||
"The Jackknife works by making many replicas of the estimator $\\widehat{\\beta}$. \n",
|
||
"The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\\boldsymbol{x} = (x_1,x_2,\\cdots,X_n)$. \n",
|
||
"Let $\\boldsymbol{x}_i$ denote the vector"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{x}_i = (x_1,x_2,\\cdots,x_{i-1},x_{i+1},\\cdots,x_n),\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"which equals the vector $\\boldsymbol{x}$ with the exception that observation\n",
|
||
"number $i$ is left out. Using this notation, define\n",
|
||
"$\\widehat{\\beta}_i$ to be the estimator\n",
|
||
"$\\widehat{\\beta}$ computed using $\\vec{X}_i$. \n",
|
||
"\n",
|
||
"\n",
|
||
"## Jackknife code example"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"from numpy import *\n",
|
||
"from numpy.random import randint, randn\n",
|
||
"from time import time\n",
|
||
"\n",
|
||
"def jackknife(data, stat):\n",
|
||
" n = len(data);t = zeros(n); inds = arange(n); t0 = time()\n",
|
||
" ## 'jackknifing' by leaving out an observation for each i \n",
|
||
" for i in range(n):\n",
|
||
" t[i] = stat(delete(data,i) )\n",
|
||
"\n",
|
||
" # analysis \n",
|
||
" print(\"Runtime: %g sec\" % (time()-t0)); print(\"Jackknife Statistics :\")\n",
|
||
" print(\"original bias std. error\")\n",
|
||
" print(\"%8g %14g %15g\" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))\n",
|
||
"\n",
|
||
" return t\n",
|
||
"\n",
|
||
"\n",
|
||
"# Returns mean of data samples \n",
|
||
"def stat(data):\n",
|
||
" return mean(data)\n",
|
||
"\n",
|
||
"\n",
|
||
"mu, sigma = 100, 15\n",
|
||
"datapoints = 10000\n",
|
||
"x = mu + sigma*random.randn(datapoints)\n",
|
||
"# jackknife returns the data sample \n",
|
||
"t = jackknife(x, stat)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Resampling methods: Bootstrap\n",
|
||
"Bootstrapping is a non-parametric approach to statistical inference\n",
|
||
"that substitutes computation for more traditional distributional\n",
|
||
"assumptions and asymptotic results. Bootstrapping offers a number of\n",
|
||
"advantages: \n",
|
||
"1. The bootstrap is quite general, although there are some cases in which it fails. \n",
|
||
"\n",
|
||
"2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. \n",
|
||
"\n",
|
||
"3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. \n",
|
||
"\n",
|
||
"4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"The textbook by [Davison on the Bootstrap Methods and their Applications](https://www.cambridge.org/core/books/bootstrap-methods-and-their-application/ED2FD043579F27952363566DC09CBD6A) provides many more insights and proofs. In this course we will take a more practical approach and use the results and theorems provided in the literature. For those interested in reading more about the bootstrap methods, we recommend the above text and the one by [Efron and Tibshirani](https://www.routledge.com/An-Introduction-to-the-Bootstrap/Efron-Tibshirani/p/book/9780412042317).\n",
|
||
"\n",
|
||
"\n",
|
||
"Before we proceed however, we need to remind ourselves about a central theorem in statistics, namely the so-called **central limit theorem**.\n",
|
||
"\n",
|
||
"## The Central Limit Theorem\n",
|
||
"\n",
|
||
"\n",
|
||
"Suppose we have a PDF $p(x)$ from which we generate a series $N$\n",
|
||
"of averages $\\mathbb{E}[x_i]$. Each mean value $\\mathbb{E}[x_i]$\n",
|
||
"is viewed as the average of a specific measurement, e.g., throwing \n",
|
||
"dice 100 times and then taking the average value, or producing a certain\n",
|
||
"amount of random numbers. \n",
|
||
"For notational ease, we set $\\mathbb{E}[x_i]=x_i$ in the discussion\n",
|
||
"which follows. We do the same for $\\mathbb{E}[z]=z$.\n",
|
||
"\n",
|
||
"If we compute the mean $z$ of $m$ such mean values $x_i$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"z=\\frac{x_1+x_2+\\dots+x_m}{m},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"the question we pose is which is the PDF of the new variable $z$.\n",
|
||
"\n",
|
||
"## Finding the Limit\n",
|
||
"\n",
|
||
"The probability of obtaining an average value $z$ is the product of the \n",
|
||
"probabilities of obtaining arbitrary individual mean values $x_i$,\n",
|
||
"but with the constraint that the average is $z$. We can express this through\n",
|
||
"the following expression"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\tilde{p}(z)=\\int dx_1p(x_1)\\int dx_2p(x_2)\\dots\\int dx_mp(x_m)\n",
|
||
" \\delta(z-\\frac{x_1+x_2+\\dots+x_m}{m}),\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"where the $\\delta$-function enbodies the constraint that the mean is $z$.\n",
|
||
"All measurements that lead to each individual $x_i$ are expected to\n",
|
||
"be independent, which in turn means that we can express $\\tilde{p}$ as the \n",
|
||
"product of individual $p(x_i)$. The independence assumption is important in the derivation of the central limit theorem.\n",
|
||
"\n",
|
||
"\n",
|
||
"## Rewriting the $\\delta$-function\n",
|
||
"\n",
|
||
"If we use the integral expression for the $\\delta$-function"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\delta(z-\\frac{x_1+x_2+\\dots+x_m}{m})=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty}\n",
|
||
" dq\\exp{\\left(iq(z-\\frac{x_1+x_2+\\dots+x_m}{m})\\right)},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"and inserting $e^{i\\mu q-i\\mu q}$ where $\\mu$ is the mean value\n",
|
||
"we arrive at"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\tilde{p}(z)=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty}\n",
|
||
" dq\\exp{\\left(iq(z-\\mu)\\right)}\\left[\\int_{-\\infty}^{\\infty}\n",
|
||
" dxp(x)\\exp{\\left(iq(\\mu-x)/m\\right)}\\right]^m,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"with the integral over $x$ resulting in"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\int_{-\\infty}^{\\infty}dxp(x)\\exp{\\left(iq(\\mu-x)/m\\right)}=\n",
|
||
" \\int_{-\\infty}^{\\infty}dxp(x)\n",
|
||
" \\left[1+\\frac{iq(\\mu-x)}{m}-\\frac{q^2(\\mu-x)^2}{2m^2}+\\dots\\right].\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Identifying Terms\n",
|
||
"\n",
|
||
"The second term on the rhs disappears since this is just the mean and \n",
|
||
"employing the definition of $\\sigma^2$ we have"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\int_{-\\infty}^{\\infty}dxp(x)e^{\\left(iq(\\mu-x)/m\\right)}=\n",
|
||
" 1-\\frac{q^2\\sigma^2}{2m^2}+\\dots,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"resulting in"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\left[\\int_{-\\infty}^{\\infty}dxp(x)\\exp{\\left(iq(\\mu-x)/m\\right)}\\right]^m\\approx\n",
|
||
" \\left[1-\\frac{q^2\\sigma^2}{2m^2}+\\dots \\right]^m,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"and in the limit $m\\rightarrow \\infty$ we obtain"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\tilde{p}(z)=\\frac{1}{\\sqrt{2\\pi}(\\sigma/\\sqrt{m})}\n",
|
||
" \\exp{\\left(-\\frac{(z-\\mu)^2}{2(\\sigma/\\sqrt{m})^2}\\right)},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"which is the normal distribution with variance\n",
|
||
"$\\sigma^2_m=\\sigma^2/m$, where $\\sigma$ is the variance of the PDF $p(x)$\n",
|
||
"and $\\mu$ is also the mean of the PDF $p(x)$. \n",
|
||
"\n",
|
||
"## Wrapping it up\n",
|
||
"\n",
|
||
"Thus, the central limit theorem states that the PDF $\\tilde{p}(z)$ of\n",
|
||
"the average of $m$ random values corresponding to a PDF $p(x)$ \n",
|
||
"is a normal distribution whose mean is the \n",
|
||
"mean value of the PDF $p(x)$ and whose variance is the variance\n",
|
||
"of the PDF $p(x)$ divided by $m$, the number of values used to compute $z$.\n",
|
||
"\n",
|
||
"The central limit theorem leads to the well-known expression for the\n",
|
||
"standard deviation, given by"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\sigma_m=\n",
|
||
"\\frac{\\sigma}{\\sqrt{m}}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"The latter is true only if the average value is known exactly. This is obtained in the limit\n",
|
||
"$m\\rightarrow \\infty$ only. Because the mean and the variance are measured quantities we obtain \n",
|
||
"the familiar expression in statistics (the so-called Bessel correction)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\sigma_m\\approx \n",
|
||
"\\frac{\\sigma}{\\sqrt{m-1}}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"In many cases however the above estimate for the standard deviation,\n",
|
||
"in particular if correlations are strong, may be too simplistic. Keep\n",
|
||
"in mind that we have assumed that the variables $x$ are independent\n",
|
||
"and identically distributed. This is obviously not always the\n",
|
||
"case. For example, the random numbers (or better pseudorandom numbers)\n",
|
||
"we generate in various calculations do always exhibit some\n",
|
||
"correlations.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"The theorem is satisfied by a large class of PDFs. Note however that for a\n",
|
||
"finite $m$, it is not always possible to find a closed form /analytic expression for\n",
|
||
"$\\tilde{p}(x)$.\n",
|
||
"\n",
|
||
"\n",
|
||
"## Confidence Intervals\n",
|
||
"\n",
|
||
"Confidence intervals are used in statistics and represent a type of estimate\n",
|
||
"computed from the observed data. This gives a range of values for an\n",
|
||
"unknown parameter such as the parameters $\\boldsymbol{\\beta}$ from linear regression.\n",
|
||
"\n",
|
||
"With the OLS expressions for the parameters $\\boldsymbol{\\beta}$ we found \n",
|
||
"$\\mathbb{E}(\\boldsymbol{\\beta}) = \\boldsymbol{\\beta}$, which means that the estimator of the regression parameters is unbiased.\n",
|
||
"\n",
|
||
"We found also that the variance of the estimate of the $j$-th regression coefficient is\n",
|
||
"$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 [(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} $.\n",
|
||
"\n",
|
||
"This quantity will be used to\n",
|
||
"construct a confidence interval for the estimates.\n",
|
||
"\n",
|
||
"\n",
|
||
"## Standard Approach based on the Normal Distribution\n",
|
||
"\n",
|
||
"We will assume that the parameters $\\beta$ follow a normal\n",
|
||
"distribution. We can then define the confidence interval. Here we will be using as\n",
|
||
"shorthands $\\mu_{\\beta}$ for the above mean value and $\\sigma_{\\beta}$\n",
|
||
"for the standard deviation. We have then a confidence interval"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\left(\\mu_{\\beta}\\pm \\frac{z\\sigma_{\\beta}}{\\sqrt{n}}\\right),\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"where $z$ defines the level of certainty (or confidence). For a normal\n",
|
||
"distribution typical parameters are $z=2.576$ which corresponds to a\n",
|
||
"confidence of $99\\%$ while $z=1.96$ corresponds to a confidence of\n",
|
||
"$95\\%$. A confidence level of $95\\%$ is commonly used and it is\n",
|
||
"normally referred to as a *two-sigmas* confidence level, that is we\n",
|
||
"approximate $z\\approx 2$.\n",
|
||
"\n",
|
||
"For more discussions of confidence intervals (and in particular linked with a discussion of the bootstrap method), see chapter 5 of the textbook by [Davison on the Bootstrap Methods and their Applications](https://www.cambridge.org/core/books/bootstrap-methods-and-their-application/ED2FD043579F27952363566DC09CBD6A)\n",
|
||
"\n",
|
||
"In this text you will also find an in-depth discussion of the\n",
|
||
"Bootstrap method, why it works and various theorems related to it. \n",
|
||
"\n",
|
||
"## Resampling methods: Bootstrap background\n",
|
||
"\n",
|
||
"Since $\\widehat{\\beta} = \\widehat{\\beta}(\\boldsymbol{X})$ is a function of random variables,\n",
|
||
"$\\widehat{\\beta}$ itself must be a random variable. Thus it has\n",
|
||
"a pdf, call this function $p(\\boldsymbol{t})$. The aim of the bootstrap is to\n",
|
||
"estimate $p(\\boldsymbol{t})$ by the relative frequency of\n",
|
||
"$\\widehat{\\beta}$. You can think of this as using a histogram\n",
|
||
"in the place of $p(\\boldsymbol{t})$. If the relative frequency closely\n",
|
||
"resembles $p(\\vec{t})$, then using numerics, it is straight forward to\n",
|
||
"estimate all the interesting parameters of $p(\\boldsymbol{t})$ using point\n",
|
||
"estimators. \n",
|
||
"\n",
|
||
"\n",
|
||
"## Resampling methods: More Bootstrap background\n",
|
||
"\n",
|
||
"In the case that $\\widehat{\\beta}$ has\n",
|
||
"more than one component, and the components are independent, we use the\n",
|
||
"same estimator on each component separately. If the probability\n",
|
||
"density function of $X_i$, $p(x)$, had been known, then it would have\n",
|
||
"been straightforward to do this by: \n",
|
||
"1. Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \\cdots, X_n^*)$. \n",
|
||
"\n",
|
||
"2. Then using these numbers, we could compute a replica of $\\widehat{\\beta}$ called $\\widehat{\\beta}^*$. \n",
|
||
"\n",
|
||
"By repeated use of the above two points, many\n",
|
||
"estimates of $\\widehat{\\beta}$ can be obtained. The\n",
|
||
"idea is to use the relative frequency of $\\widehat{\\beta}^*$\n",
|
||
"(think of a histogram) as an estimate of $p(\\boldsymbol{t})$.\n",
|
||
"\n",
|
||
"## Resampling methods: Bootstrap approach\n",
|
||
"\n",
|
||
"But\n",
|
||
"unless there is enough information available about the process that\n",
|
||
"generated $X_1,X_2,\\cdots,X_n$, $p(x)$ is in general\n",
|
||
"unknown. Therefore, [Efron in 1979](https://projecteuclid.org/euclid.aos/1176344552) asked the\n",
|
||
"question: What if we replace $p(x)$ by the relative frequency\n",
|
||
"of the observation $X_i$?\n",
|
||
"\n",
|
||
"If we draw observations in accordance with\n",
|
||
"the relative frequency of the observations, will we obtain the same\n",
|
||
"result in some asymptotic sense? The answer is yes.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Resampling methods: Bootstrap steps\n",
|
||
"\n",
|
||
"The independent bootstrap works like this: \n",
|
||
"\n",
|
||
"1. Draw with replacement $n$ numbers for the observed variables $\\boldsymbol{x} = (x_1,x_2,\\cdots,x_n)$. \n",
|
||
"\n",
|
||
"2. Define a vector $\\boldsymbol{x}^*$ containing the values which were drawn from $\\boldsymbol{x}$. \n",
|
||
"\n",
|
||
"3. Using the vector $\\boldsymbol{x}^*$ compute $\\widehat{\\beta}^*$ by evaluating $\\widehat \\beta$ under the observations $\\boldsymbol{x}^*$. \n",
|
||
"\n",
|
||
"4. Repeat this process $k$ times. \n",
|
||
"\n",
|
||
"When you are done, you can draw a histogram of the relative frequency\n",
|
||
"of $\\widehat \\beta^*$. This is your estimate of the probability\n",
|
||
"distribution $p(t)$. Using this probability distribution you can\n",
|
||
"estimate any statistics thereof. In principle you never draw the\n",
|
||
"histogram of the relative frequency of $\\widehat{\\beta}^*$. Instead\n",
|
||
"you use the estimators corresponding to the statistic of interest. For\n",
|
||
"example, if you are interested in estimating the variance of $\\widehat\n",
|
||
"\\beta$, apply the etsimator $\\widehat \\sigma^2$ to the values\n",
|
||
"$\\widehat \\beta^*$.\n",
|
||
"\n",
|
||
"\n",
|
||
"## Code example for the Bootstrap method\n",
|
||
"\n",
|
||
"The following code starts with a Gaussian distribution with mean value\n",
|
||
"$\\mu =100$ and variance $\\sigma=15$. We use this to generate the data\n",
|
||
"used in the bootstrap analysis. The bootstrap analysis returns a data\n",
|
||
"set after a given number of bootstrap operations (as many as we have\n",
|
||
"data points). This data set consists of estimated mean values for each\n",
|
||
"bootstrap operation. The histogram generated by the bootstrap method\n",
|
||
"shows that the distribution for these mean values is also a Gaussian,\n",
|
||
"centered around the mean value $\\mu=100$ but with standard deviation\n",
|
||
"$\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in\n",
|
||
"this case the same as the number of original data points). The value\n",
|
||
"of the standard deviation is what we expect from the central limit\n",
|
||
"theorem."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"import numpy as np\n",
|
||
"from time import time\n",
|
||
"from scipy.stats import norm\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"\n",
|
||
"# Returns mean of bootstrap samples \n",
|
||
"# Bootstrap algorithm\n",
|
||
"def bootstrap(data, datapoints):\n",
|
||
" t = np.zeros(datapoints)\n",
|
||
" n = len(data)\n",
|
||
" # non-parametric bootstrap \n",
|
||
" for i in range(datapoints):\n",
|
||
" t[i] = np.mean(data[np.random.randint(0,n,n)])\n",
|
||
" # analysis \n",
|
||
" print(\"Bootstrap Statistics :\")\n",
|
||
" print(\"original bias std. error\")\n",
|
||
" print(\"%8g %8g %14g %15g\" % (np.mean(data), np.std(data),np.mean(t),np.std(t)))\n",
|
||
" return t\n",
|
||
"\n",
|
||
"# We set the mean value to 100 and the standard deviation to 15\n",
|
||
"mu, sigma = 100, 15\n",
|
||
"datapoints = 10000\n",
|
||
"# We generate random numbers according to the normal distribution\n",
|
||
"x = mu + sigma*np.random.randn(datapoints)\n",
|
||
"# bootstrap returns the data sample \n",
|
||
"t = bootstrap(x, datapoints)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"We see that our new variance and from that the standard deviation, agrees with the central limit theorem.\n",
|
||
"\n",
|
||
"## Plotting the Histogram"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# the histogram of the bootstrapped data (normalized data if density = True)\n",
|
||
"n, binsboot, patches = plt.hist(t, 50, density=True, facecolor='red', alpha=0.75)\n",
|
||
"# add a 'best fit' line \n",
|
||
"y = norm.pdf(binsboot, np.mean(t), np.std(t))\n",
|
||
"lt = plt.plot(binsboot, y, 'b', linewidth=1)\n",
|
||
"plt.xlabel('x')\n",
|
||
"plt.ylabel('Probability')\n",
|
||
"plt.grid(True)\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## The bias-variance tradeoff\n",
|
||
"\n",
|
||
"\n",
|
||
"We will discuss the bias-variance tradeoff 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. Consider a dataset $\\mathcal{D}$ consisting of the data\n",
|
||
"$\\mathbf{X}_\\mathcal{D}=\\{(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": [
|
||
"where $\\epsilon$ is normally distributed with mean zero and standard 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",
|
||
"Thereafter we found the parameters $\\boldsymbol{\\beta}$ by optimizing the means 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": [
|
||
"We 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": [
|
||
"The three terms represent the square of the bias of the learning\n",
|
||
"method, which can be thought of as the error caused by the simplifying\n",
|
||
"assumptions built into the method. The second term represents the\n",
|
||
"variance of the chosen model and finally the last terms is variance of\n",
|
||
"the error $\\boldsymbol{\\epsilon}$.\n",
|
||
"\n",
|
||
"To derive this equation, we need to recall that the variance of $\\boldsymbol{y}$ and $\\boldsymbol{\\epsilon}$ are both equal to $\\sigma^2$. The mean value of $\\boldsymbol{\\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\\boldsymbol{\\tilde{y}}$.\n",
|
||
"We use a more compact notation in terms of the expectation value"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}})^2\\right],\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"and adding and subtracting $\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]$ we get"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}}+\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right],\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"which, using the abovementioned expectation values can be rewritten as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right]+\\mathrm{Var}\\left[\\boldsymbol{\\tilde{y}}\\right]+\\sigma^2,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"that is the rewriting in terms of the so-called bias, the variance of the model $\\boldsymbol{\\tilde{y}}$ and the variance of $\\boldsymbol{\\epsilon}$.\n",
|
||
"\n",
|
||
"\n",
|
||
"## A way to Read the Bias-Variance Tradeoff\n",
|
||
"\n",
|
||
"<!-- dom:FIGURE: [figures/BiasVariance.png, width=600 frac=0.9] -->\n",
|
||
"<!-- begin figure -->\n",
|
||
"<img src=\"figures/BiasVariance.png\" width=600><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p><!-- end figure -->\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Example code for Bias-Variance tradeoff"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"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",
|
||
"from sklearn.utils import resample\n",
|
||
"\n",
|
||
"np.random.seed(2018)\n",
|
||
"\n",
|
||
"n = 500\n",
|
||
"n_boostraps = 100\n",
|
||
"degree = 18 # A quite high value, just to show.\n",
|
||
"noise = 0.1\n",
|
||
"\n",
|
||
"# Make data set.\n",
|
||
"x = np.linspace(-1, 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",
|
||
"\n",
|
||
"# Hold out some test data that is never used in training.\n",
|
||
"x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
|
||
"\n",
|
||
"# Combine x transformation and model into one operation.\n",
|
||
"# Not neccesary, but convenient.\n",
|
||
"model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
|
||
"\n",
|
||
"# The following (m x n_bootstraps) matrix holds the column vectors y_pred\n",
|
||
"# for each bootstrap iteration.\n",
|
||
"y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
|
||
"for i in range(n_boostraps):\n",
|
||
" x_, y_ = resample(x_train, y_train)\n",
|
||
"\n",
|
||
" # Evaluate the new model on the same test data each time.\n",
|
||
" y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
|
||
"\n",
|
||
"# Note: Expectations and variances taken w.r.t. different training\n",
|
||
"# data sets, hence the axis=1. Subsequent means are taken across the test data\n",
|
||
"# set in order to obtain a total value, but before this we have error/bias/variance\n",
|
||
"# calculated per data point in the test set.\n",
|
||
"# Note 2: The use of keepdims=True is important in the calculation of bias as this \n",
|
||
"# maintains the column vector form. Dropping this yields very unexpected results.\n",
|
||
"error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
|
||
"bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
|
||
"variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
|
||
"print('Error:', error)\n",
|
||
"print('Bias^2:', bias)\n",
|
||
"print('Var:', variance)\n",
|
||
"print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))\n",
|
||
"\n",
|
||
"plt.plot(x[::5, :], y[::5, :], label='f(x)')\n",
|
||
"plt.scatter(x_test, y_test, label='Data points')\n",
|
||
"plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')\n",
|
||
"plt.legend()\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Understanding what happens"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"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",
|
||
"from sklearn.utils import resample\n",
|
||
"\n",
|
||
"np.random.seed(2018)\n",
|
||
"\n",
|
||
"n = 40\n",
|
||
"n_boostraps = 100\n",
|
||
"maxdegree = 14\n",
|
||
"\n",
|
||
"\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",
|
||
"error = np.zeros(maxdegree)\n",
|
||
"bias = np.zeros(maxdegree)\n",
|
||
"variance = 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",
|
||
"for degree in range(maxdegree):\n",
|
||
" model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
|
||
" y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
|
||
" for i in range(n_boostraps):\n",
|
||
" x_, y_ = resample(x_train, y_train)\n",
|
||
" y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
|
||
"\n",
|
||
" polydegree[degree] = degree\n",
|
||
" error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
|
||
" bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
|
||
" variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
|
||
" print('Polynomial degree:', degree)\n",
|
||
" print('Error:', error[degree])\n",
|
||
" print('Bias^2:', bias[degree])\n",
|
||
" print('Var:', variance[degree])\n",
|
||
" print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n",
|
||
"\n",
|
||
"plt.plot(polydegree, error, label='Error')\n",
|
||
"plt.plot(polydegree, bias, label='bias')\n",
|
||
"plt.plot(polydegree, variance, label='Variance')\n",
|
||
"plt.legend()\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- !split -->\n",
|
||
"## Summing up\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"The bias-variance tradeoff summarizes the fundamental tension in\n",
|
||
"machine learning, particularly supervised learning, between the\n",
|
||
"complexity of a model and the amount of training data needed to train\n",
|
||
"it. Since data is often limited, in practice it is often useful to\n",
|
||
"use a less-complex model with higher bias, that is a model whose asymptotic\n",
|
||
"performance is worse than another model because it is easier to\n",
|
||
"train and less sensitive to sampling noise arising from having a\n",
|
||
"finite-sized training dataset (smaller variance). \n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"The above equations tell us that in\n",
|
||
"order to minimize the expected test error, we need to select a\n",
|
||
"statistical learning method that simultaneously achieves low variance\n",
|
||
"and low bias. Note that variance is inherently a nonnegative quantity,\n",
|
||
"and squared bias is also nonnegative. Hence, we see that the expected\n",
|
||
"test MSE can never lie below $Var(\\epsilon)$, the irreducible error.\n",
|
||
"\n",
|
||
"\n",
|
||
"What do we mean by the variance and bias of a statistical learning\n",
|
||
"method? The variance refers to the amount by which our model would change if we\n",
|
||
"estimated it using a different training data set. Since the training\n",
|
||
"data are used to fit the statistical learning method, different\n",
|
||
"training data sets will result in a different estimate. But ideally the\n",
|
||
"estimate for our model should not vary too much between training\n",
|
||
"sets. However, if a method has high variance then small changes in\n",
|
||
"the training data can result in large changes in the model. In general, more\n",
|
||
"flexible statistical methods have higher variance.\n",
|
||
"\n",
|
||
"\n",
|
||
"You may also find this recent [article](https://www.pnas.org/content/116/32/15849) of interest.\n",
|
||
"\n",
|
||
"## Another Example from Scikit-Learn's Repository"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"\"\"\"\n",
|
||
"============================\n",
|
||
"Underfitting vs. Overfitting\n",
|
||
"============================\n",
|
||
"\n",
|
||
"This example demonstrates the problems of underfitting and overfitting and\n",
|
||
"how we can use linear regression with polynomial features to approximate\n",
|
||
"nonlinear functions. The plot shows the function that we want to approximate,\n",
|
||
"which is a part of the cosine function. In addition, the samples from the\n",
|
||
"real function and the approximations of different models are displayed. The\n",
|
||
"models have polynomial features of different degrees. We can see that a\n",
|
||
"linear function (polynomial with degree 1) is not sufficient to fit the\n",
|
||
"training samples. This is called **underfitting**. A polynomial of degree 4\n",
|
||
"approximates the true function almost perfectly. However, for higher degrees\n",
|
||
"the model will **overfit** the training data, i.e. it learns the noise of the\n",
|
||
"training data.\n",
|
||
"We evaluate quantitatively **overfitting** / **underfitting** by using\n",
|
||
"cross-validation. We calculate the mean squared error (MSE) on the validation\n",
|
||
"set, the higher, the less likely the model generalizes correctly from the\n",
|
||
"training data.\n",
|
||
"\"\"\"\n",
|
||
"\n",
|
||
"print(__doc__)\n",
|
||
"\n",
|
||
"import numpy as np\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from sklearn.pipeline import Pipeline\n",
|
||
"from sklearn.preprocessing import PolynomialFeatures\n",
|
||
"from sklearn.linear_model import LinearRegression\n",
|
||
"from sklearn.model_selection import cross_val_score\n",
|
||
"\n",
|
||
"\n",
|
||
"def true_fun(X):\n",
|
||
" return np.cos(1.5 * np.pi * X)\n",
|
||
"\n",
|
||
"np.random.seed(0)\n",
|
||
"\n",
|
||
"n_samples = 30\n",
|
||
"degrees = [1, 4, 15]\n",
|
||
"\n",
|
||
"X = np.sort(np.random.rand(n_samples))\n",
|
||
"y = true_fun(X) + np.random.randn(n_samples) * 0.1\n",
|
||
"\n",
|
||
"plt.figure(figsize=(14, 5))\n",
|
||
"for i in range(len(degrees)):\n",
|
||
" ax = plt.subplot(1, len(degrees), i + 1)\n",
|
||
" plt.setp(ax, xticks=(), yticks=())\n",
|
||
"\n",
|
||
" polynomial_features = PolynomialFeatures(degree=degrees[i],\n",
|
||
" include_bias=False)\n",
|
||
" linear_regression = LinearRegression()\n",
|
||
" pipeline = Pipeline([(\"polynomial_features\", polynomial_features),\n",
|
||
" (\"linear_regression\", linear_regression)])\n",
|
||
" pipeline.fit(X[:, np.newaxis], y)\n",
|
||
"\n",
|
||
" # Evaluate the models using crossvalidation\n",
|
||
" scores = cross_val_score(pipeline, X[:, np.newaxis], y,\n",
|
||
" scoring=\"neg_mean_squared_error\", cv=10)\n",
|
||
"\n",
|
||
" X_test = np.linspace(0, 1, 100)\n",
|
||
" plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label=\"Model\")\n",
|
||
" plt.plot(X_test, true_fun(X_test), label=\"True function\")\n",
|
||
" plt.scatter(X, y, edgecolor='b', s=20, label=\"Samples\")\n",
|
||
" plt.xlabel(\"x\")\n",
|
||
" plt.ylabel(\"y\")\n",
|
||
" plt.xlim((0, 1))\n",
|
||
" plt.ylim((-2, 2))\n",
|
||
" plt.legend(loc=\"best\")\n",
|
||
" plt.title(\"Degree {}\\nMSE = {:.2e}(+/- {:.2e})\".format(\n",
|
||
" degrees[i], -scores.mean(), scores.std()))\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- !split -->\n",
|
||
"## Various steps in cross-validation\n",
|
||
"\n",
|
||
"When the repetitive splitting of the data set is done randomly,\n",
|
||
"samples may accidently end up in a fast majority of the splits in\n",
|
||
"either training or test set. Such samples may have an unbalanced\n",
|
||
"influence on either model building or prediction evaluation. To avoid\n",
|
||
"this $k$-fold cross-validation structures the data splitting. The\n",
|
||
"samples are divided into $k$ more or less equally sized exhaustive and\n",
|
||
"mutually exclusive subsets. In turn (at each split) one of these\n",
|
||
"subsets plays the role of the test set while the union of the\n",
|
||
"remaining subsets constitutes the training set. Such a splitting\n",
|
||
"warrants a balanced representation of each sample in both training and\n",
|
||
"test set over the splits. Still the division into the $k$ subsets\n",
|
||
"involves a degree of randomness. This may be fully excluded when\n",
|
||
"choosing $k=n$. This particular case is referred to as leave-one-out\n",
|
||
"cross-validation (LOOCV). \n",
|
||
"\n",
|
||
"<!-- !split -->\n",
|
||
"## How to set up the cross-validation for Ridge and/or Lasso\n",
|
||
"\n",
|
||
"* Define a range of interest for the penalty parameter.\n",
|
||
"\n",
|
||
"* Divide the data set into training and test set comprising samples $\\{1, \\ldots, n\\} \\setminus i$ and $\\{ i \\}$, respectively.\n",
|
||
"\n",
|
||
"* Fit the linear regression model by means of ridge estimation for each $\\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\\boldsymbol{\\sigma}_{-i}^2(\\lambda)$, as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\begin{align*}\n",
|
||
"\\boldsymbol{\\beta}_{-i}(\\lambda) & = ( \\boldsymbol{X}_{-i, \\ast}^{T}\n",
|
||
"\\boldsymbol{X}_{-i, \\ast} + \\lambda \\boldsymbol{I}_{pp})^{-1}\n",
|
||
"\\boldsymbol{X}_{-i, \\ast}^{T} \\boldsymbol{y}_{-i}\n",
|
||
"\\end{align*}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"* Evaluate the prediction performance of these models on the test set by $[y_i, \\boldsymbol{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]$. Or, by the prediction error $|y_i - \\boldsymbol{X}_{i, \\ast} \\boldsymbol{\\beta}_{-i}(\\lambda)|$, the relative error, the error squared or the R2 score function.\n",
|
||
"\n",
|
||
"* Repeat the first three steps such that each sample plays the role of the test set once.\n",
|
||
"\n",
|
||
"* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\begin{align*}\n",
|
||
"\\frac{1}{n} \\sum_{i = 1}^n \\log\\{L[y_i, \\mathbf{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}.\n",
|
||
"\\end{align*}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Cross-validation in brief\n",
|
||
"\n",
|
||
"For the various values of $k$\n",
|
||
"\n",
|
||
"1. shuffle the dataset randomly.\n",
|
||
"\n",
|
||
"2. Split the dataset into $k$ groups.\n",
|
||
"\n",
|
||
"3. For each unique group:\n",
|
||
"\n",
|
||
"a. Decide which group to use as set for test data\n",
|
||
"\n",
|
||
"b. Take the remaining groups as a training data set\n",
|
||
"\n",
|
||
"c. Fit a model on the training set and evaluate it on the test set\n",
|
||
"\n",
|
||
"d. Retain the evaluation score and discard the model\n",
|
||
"\n",
|
||
"\n",
|
||
"5. Summarize the model using the sample of model evaluation scores\n",
|
||
"\n",
|
||
"## Code Example for Cross-validation and $k$-fold Cross-validation\n",
|
||
"\n",
|
||
"The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 5,
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"data": {
|
||
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXgAAAEGCAYAAABvtY4XAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/Il7ecAAAACXBIWXMAAAsTAAALEwEAmpwYAAA3c0lEQVR4nO3dd3gU5fr/8fedRhIICYRQQwmdAKEX6UUpggLiEURQ0CMqKvaf7dg5ikeP9SiKigVRiiIioIBUkRpa6D20UBJKII2UfX5/ZOGLECCJmZ3dzf26rlwkO7NzfzYhd2afmXlGjDEopZTyPj52B1BKKWUNbfBKKeWltMErpZSX0gavlFJeShu8Ukp5KT+7A1ysXLlypkaNGnbHUEopj7F27dokY0xEXsvcqsHXqFGD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L/zxhzlNx50A8BW4FvgXVAMoCIjHbOkhkJxDkPYkLu/QH2ArvJPWNmFIAxJhXYIyK186j/H+ANEVlP4Yc0M5zP/wQ4PxvlK0AnEdlC7lDNAefjvwF+IrINGEvuLR7PawGsvOj2j0pdlc4mqTyWiJQyxqQ4DzquBto7m39htjUAaGGM+VeRhixCIvI+MNMYs8DuLMoz6EFW5clmOQ9YBgCvFba5AxhjfvKAs1M2a3NXBaF78Eop5aV0DF4ppbyUNnillPJS2uCVUspLaYNXSikvpQ1eKaW81P8HIT4w0H032FcAAAAASUVORK5CYII=\n",
|
||
"text/plain": [
|
||
"<Figure size 432x288 with 1 Axes>"
|
||
]
|
||
},
|
||
"metadata": {
|
||
"needs_background": "light"
|
||
},
|
||
"output_type": "display_data"
|
||
}
|
||
],
|
||
"source": [
|
||
"import numpy as np\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from sklearn.model_selection import KFold\n",
|
||
"from sklearn.linear_model import Ridge\n",
|
||
"from sklearn.model_selection import cross_val_score\n",
|
||
"from sklearn.preprocessing import PolynomialFeatures\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",
|
||
"# Generate the data.\n",
|
||
"nsamples = 100\n",
|
||
"x = np.random.randn(nsamples)\n",
|
||
"y = 3*x**2 + np.random.randn(nsamples)\n",
|
||
"\n",
|
||
"## Cross-validation on Ridge regression using KFold only\n",
|
||
"\n",
|
||
"# Decide degree on polynomial to fit\n",
|
||
"poly = PolynomialFeatures(degree = 6)\n",
|
||
"\n",
|
||
"# Decide which values of lambda to use\n",
|
||
"nlambdas = 500\n",
|
||
"lambdas = np.logspace(-3, 5, nlambdas)\n",
|
||
"\n",
|
||
"# Initialize a KFold instance\n",
|
||
"k = 5\n",
|
||
"kfold = KFold(n_splits = k)\n",
|
||
"\n",
|
||
"# Perform the cross-validation to estimate MSE\n",
|
||
"scores_KFold = np.zeros((nlambdas, k))\n",
|
||
"\n",
|
||
"i = 0\n",
|
||
"for lmb in lambdas:\n",
|
||
" ridge = Ridge(alpha = lmb)\n",
|
||
" j = 0\n",
|
||
" for train_inds, test_inds in kfold.split(x):\n",
|
||
" xtrain = x[train_inds]\n",
|
||
" ytrain = y[train_inds]\n",
|
||
"\n",
|
||
" xtest = x[test_inds]\n",
|
||
" ytest = y[test_inds]\n",
|
||
"\n",
|
||
" Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n",
|
||
" ridge.fit(Xtrain, ytrain[:, np.newaxis])\n",
|
||
"\n",
|
||
" Xtest = poly.fit_transform(xtest[:, np.newaxis])\n",
|
||
" ypred = ridge.predict(Xtest)\n",
|
||
"\n",
|
||
" scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n",
|
||
"\n",
|
||
" j += 1\n",
|
||
" i += 1\n",
|
||
"\n",
|
||
"\n",
|
||
"estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n",
|
||
"\n",
|
||
"## Cross-validation using cross_val_score from sklearn along with KFold\n",
|
||
"\n",
|
||
"# kfold is an instance initialized above as:\n",
|
||
"# kfold = KFold(n_splits = k)\n",
|
||
"\n",
|
||
"estimated_mse_sklearn = np.zeros(nlambdas)\n",
|
||
"i = 0\n",
|
||
"for lmb in lambdas:\n",
|
||
" ridge = Ridge(alpha = lmb)\n",
|
||
"\n",
|
||
" X = poly.fit_transform(x[:, np.newaxis])\n",
|
||
" estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n",
|
||
"\n",
|
||
" # cross_val_score return an array containing the estimated negative mse for every fold.\n",
|
||
" # we have to the the mean of every array in order to get an estimate of the mse of the model\n",
|
||
" estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n",
|
||
"\n",
|
||
" i += 1\n",
|
||
"\n",
|
||
"## Plot and compare the slightly different ways to perform cross-validation\n",
|
||
"\n",
|
||
"plt.figure()\n",
|
||
"\n",
|
||
"plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n",
|
||
"plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n",
|
||
"\n",
|
||
"plt.xlabel('log10(lambda)')\n",
|
||
"plt.ylabel('mse')\n",
|
||
"\n",
|
||
"plt.legend()\n",
|
||
"\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## More examples on bootstrap and cross-validation and errors"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 6,
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"name": "stdout",
|
||
"output_type": "stream",
|
||
"text": [
|
||
"Degree of polynomial: 1\n",
|
||
"Mean squared error on training data: 446033.51374050\n",
|
||
"Mean squared error on test data: 455173.80460179\n",
|
||
"Degree of polynomial: 2\n",
|
||
"Mean squared error on training data: 114550.54637219\n",
|
||
"Mean squared error on test data: 129963.83146596\n",
|
||
"Degree of polynomial: 3\n",
|
||
"Mean squared error on training data: 9054.61775176\n",
|
||
"Mean squared error on test data: 10572.87627342\n",
|
||
"Degree of polynomial: 4\n",
|
||
"Mean squared error on training data: 302.15313054\n",
|
||
"Mean squared error on test data: 433.26292364\n",
|
||
"Degree of polynomial: 5\n",
|
||
"Mean squared error on training data: 3.64316192\n",
|
||
"Mean squared error on test data: 7.23528337\n",
|
||
"Degree of polynomial: 6\n",
|
||
"Mean squared error on training data: 3.56589683\n",
|
||
"Mean squared error on test data: 10.50427787\n",
|
||
"Degree of polynomial: 7\n",
|
||
"Mean squared error on training data: 0.47313680\n",
|
||
"Mean squared error on test data: 1.53738247\n",
|
||
"Degree of polynomial: 8\n",
|
||
"Mean squared error on training data: 0.04926746\n",
|
||
"Mean squared error on test data: 0.14629156\n",
|
||
"Degree of polynomial: 9\n",
|
||
"Mean squared error on training data: 0.02546675\n",
|
||
"Mean squared error on test data: 0.11202337\n",
|
||
"Degree of polynomial: 10\n",
|
||
"Mean squared error on training data: 0.02424794\n",
|
||
"Mean squared error on test data: 0.22467274\n",
|
||
"Degree of polynomial: 11\n",
|
||
"Mean squared error on training data: 0.01594452\n",
|
||
"Mean squared error on test data: 1.07641937\n",
|
||
"Degree of polynomial: 12\n",
|
||
"Mean squared error on training data: 0.00805074\n",
|
||
"Mean squared error on test data: 0.04295757\n",
|
||
"Degree of polynomial: 13\n",
|
||
"Mean squared error on training data: 0.00781918\n",
|
||
"Mean squared error on test data: 0.56965674\n",
|
||
"Degree of polynomial: 14\n",
|
||
"Mean squared error on training data: 0.00465099\n",
|
||
"Mean squared error on test data: 0.28443037\n",
|
||
"Degree of polynomial: 15\n",
|
||
"Mean squared error on training data: 0.00420072\n",
|
||
"Mean squared error on test data: 568.46764611\n",
|
||
"Degree of polynomial: 16\n",
|
||
"Mean squared error on training data: 0.00325450\n",
|
||
"Mean squared error on test data: 48.97816846\n",
|
||
"Degree of polynomial: 17\n",
|
||
"Mean squared error on training data: 0.00242954\n",
|
||
"Mean squared error on test data: 2.52781930\n",
|
||
"Degree of polynomial: 18\n",
|
||
"Mean squared error on training data: 0.00219194\n",
|
||
"Mean squared error on test data: 429.08472112\n",
|
||
"Degree of polynomial: 19\n",
|
||
"Mean squared error on training data: 0.00154858\n",
|
||
"Mean squared error on test data: 243.07381539\n",
|
||
"Degree of polynomial: 20\n",
|
||
"Mean squared error on training data: 0.00140907\n",
|
||
"Mean squared error on test data: 1345.82751541\n",
|
||
"Degree of polynomial: 21\n",
|
||
"Mean squared error on training data: 0.00119942\n",
|
||
"Mean squared error on test data: 1836.90791879\n",
|
||
"Degree of polynomial: 22\n",
|
||
"Mean squared error on training data: 0.00092941\n",
|
||
"Mean squared error on test data: 1186.40097146\n",
|
||
"Degree of polynomial: 23\n",
|
||
"Mean squared error on training data: 0.00089187\n",
|
||
"Mean squared error on test data: 3897.46661311\n",
|
||
"Degree of polynomial: 24\n",
|
||
"Mean squared error on training data: 0.00083294\n",
|
||
"Mean squared error on test data: 1373.69301339\n",
|
||
"Degree of polynomial: 25\n",
|
||
"Mean squared error on training data: 0.00079928\n",
|
||
"Mean squared error on test data: 7803.21490115\n",
|
||
"Degree of polynomial: 26\n",
|
||
"Mean squared error on training data: 0.00075608\n",
|
||
"Mean squared error on test data: 1099.96635131\n",
|
||
"Degree of polynomial: 27\n",
|
||
"Mean squared error on training data: 0.00068344\n",
|
||
"Mean squared error on test data: 3165.69836349\n",
|
||
"Degree of polynomial: 28\n",
|
||
"Mean squared error on training data: 0.00063301\n",
|
||
"Mean squared error on test data: 545.87095029\n",
|
||
"Degree of polynomial: 29\n",
|
||
"Mean squared error on training data: 0.00063870\n",
|
||
"Mean squared error on test data: 3115.85424414\n"
|
||
]
|
||
},
|
||
{
|
||
"name": "stderr",
|
||
"output_type": "stream",
|
||
"text": [
|
||
"<ipython-input-6-40a38ad763f1>:73: RuntimeWarning: divide by zero encountered in log10\n",
|
||
" plt.plot(polynomial, np.log10(trainingerror), label='Training Error')\n",
|
||
"<ipython-input-6-40a38ad763f1>:74: RuntimeWarning: divide by zero encountered in log10\n",
|
||
" plt.plot(polynomial, np.log10(testerror), label='Test Error')\n"
|
||
]
|
||
},
|
||
{
|
||
"data": {
|
||
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAYIAAAEICAYAAABS0fM3AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/Il7ecAAAACXBIWXMAAAsTAAALEwEAmpwYAAA/YElEQVR4nO3dd3xUZfb48c/JpFdICDUIBJAOAUIXKYqKlVUsWNa2K1ZcXdct6ner+1vLuruuq65dXAsqKmJHBelC6B0pQQIIIUCAkDrz/P54JhAwyUySSW4mc96v17wyc2fm3nMdmTP3KecRYwxKKaVCV5jTASillHKWJgKllApxmgiUUirEaSJQSqkQp4lAKaVCnCYCpZQKcY4mAhFpJiLv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KNMYO8x/65iHTyxtIR6Alch60nU1Get1jhl8CDwNnex1nAvd4E+W9gojFmIPCS97yUItz3S5RqcDHesrpgrwhexJY5uAzAGPO1iKSISOIp73sBuB9bxuJG4OcVnisvoLYM+4UKcAb2yxFjzEYR2QGc7n1utje5HBGRfGCmd/sa4KSrEa8xInI/EIud1r+uwntO4q0N08y7rgHAa9iEB7a+VN8K/QpJQFdvrO94C6T9ICKzT9ntNO/fodhkscB7URKJTV7dsMltlne7C1txUylNBKpRKvSW1T3OR0sLAMaYBd6O19GAyxhTsQO2vM6KG//+v69Yl8VT4bHn1Pd7ryKexq4st1PsamXR1I5grxQ+P+UYvpZRLKjw/lnGmEmnvL8PsM4Yc+qVhFLaNKSCxjzgGgDvF/3+U2vle00F3sA2vdRkn6dji6ptqkVs5V/6+73t8dWOEvKWCz7kLYZGeQxenwO3VejrOF1sJdoFwGXevoJW2CJ3lVkMjBCRLt73x3nPbROQKiLDvNsjRKRXDc9TNVF6RaCCxR+Al0RkNXCME2WRT/U68BfgTT/2+TTwjIisAcqAG4wxxf5cfVRkjDkkIs9jyxj/gC2T7suN2PMxwBcVtr+Abbpa7u1wzsUuMzgdOAtYj12dbzmQX0ksuSJyA/CmiER5Nz9ojNnsbW56UkSSsP/2/4ltwlIhTquPqibF+2V3iTHmOqdjCTQRifcuUp4CLAFGGGN+cDouFfz0ikA1GSLyb2ynq6/29GD1kbejORL4syYBFSh6RaCUUiFOO4uVUirEaSJQSqkQp4lAKaVCnCYCpZQKcZoIlFIqxGkiUEqpEPf/Ae1K/neJ7iLqAAAAAElFTkSuQmCC\n",
|
||
"text/plain": [
|
||
"<Figure size 432x288 with 1 Axes>"
|
||
]
|
||
},
|
||
"metadata": {
|
||
"needs_background": "light"
|
||
},
|
||
"output_type": "display_data"
|
||
}
|
||
],
|
||
"source": [
|
||
"# Common imports\n",
|
||
"import os\n",
|
||
"import numpy as np\n",
|
||
"import pandas as pd\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
|
||
"from sklearn.model_selection import train_test_split\n",
|
||
"from sklearn.utils import resample\n",
|
||
"from sklearn.metrics import mean_squared_error\n",
|
||
"# Where to save the figures and data files\n",
|
||
"PROJECT_ROOT_DIR = \"Results\"\n",
|
||
"FIGURE_ID = \"Results/FigureFiles\"\n",
|
||
"DATA_ID = \"DataFiles/\"\n",
|
||
"\n",
|
||
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
|
||
" os.mkdir(PROJECT_ROOT_DIR)\n",
|
||
"\n",
|
||
"if not os.path.exists(FIGURE_ID):\n",
|
||
" os.makedirs(FIGURE_ID)\n",
|
||
"\n",
|
||
"if not os.path.exists(DATA_ID):\n",
|
||
" os.makedirs(DATA_ID)\n",
|
||
"\n",
|
||
"def image_path(fig_id):\n",
|
||
" return os.path.join(FIGURE_ID, fig_id)\n",
|
||
"\n",
|
||
"def data_path(dat_id):\n",
|
||
" return os.path.join(DATA_ID, dat_id)\n",
|
||
"\n",
|
||
"def save_fig(fig_id):\n",
|
||
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
|
||
"\n",
|
||
"infile = open(data_path(\"EoS.csv\"),'r')\n",
|
||
"\n",
|
||
"# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
|
||
"EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
|
||
"EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
|
||
"EoS = EoS.dropna()\n",
|
||
"Energies = EoS['Energy']\n",
|
||
"Density = EoS['Density']\n",
|
||
"# The design matrix now as function of various polytrops\n",
|
||
"\n",
|
||
"Maxpolydegree = 30\n",
|
||
"X = np.zeros((len(Density),Maxpolydegree))\n",
|
||
"X[:,0] = 1.0\n",
|
||
"testerror = np.zeros(Maxpolydegree)\n",
|
||
"trainingerror = np.zeros(Maxpolydegree)\n",
|
||
"polynomial = np.zeros(Maxpolydegree)\n",
|
||
"\n",
|
||
"trials = 100\n",
|
||
"for polydegree in range(1, Maxpolydegree):\n",
|
||
" polynomial[polydegree] = polydegree\n",
|
||
" for degree in range(polydegree):\n",
|
||
" X[:,degree] = Density**(degree/3.0)\n",
|
||
"\n",
|
||
"# loop over trials in order to estimate the expectation value of the MSE\n",
|
||
" testerror[polydegree] = 0.0\n",
|
||
" trainingerror[polydegree] = 0.0\n",
|
||
" for samples in range(trials):\n",
|
||
" x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n",
|
||
" model = LinearRegression(fit_intercept=False).fit(x_train, y_train)\n",
|
||
" ypred = model.predict(x_train)\n",
|
||
" ytilde = model.predict(x_test)\n",
|
||
" testerror[polydegree] += mean_squared_error(y_test, ytilde)\n",
|
||
" trainingerror[polydegree] += mean_squared_error(y_train, ypred) \n",
|
||
"\n",
|
||
" testerror[polydegree] /= trials\n",
|
||
" trainingerror[polydegree] /= trials\n",
|
||
" print(\"Degree of polynomial: %3d\"% polynomial[polydegree])\n",
|
||
" print(\"Mean squared error on training data: %.8f\" % trainingerror[polydegree])\n",
|
||
" print(\"Mean squared error on test data: %.8f\" % testerror[polydegree])\n",
|
||
"\n",
|
||
"plt.plot(polynomial, np.log10(trainingerror), label='Training Error')\n",
|
||
"plt.plot(polynomial, np.log10(testerror), label='Test Error')\n",
|
||
"plt.xlabel('Polynomial degree')\n",
|
||
"plt.ylabel('log10[MSE]')\n",
|
||
"plt.legend()\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"Note that we kept the intercept column in the fitting here. This means that we need to set the **intercept** in the call to the **Scikit-Learn** function as **False**. Alternatively, we could have set up the design matrix $X$ without the first column of ones.\n",
|
||
"\n",
|
||
"<!-- !split -->\n",
|
||
"## The same example but now with cross-validation\n",
|
||
"\n",
|
||
"In this example we keep the intercept column again but add cross-validation in order to estimate the best possible value of the means squared error."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 4,
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"name": "stderr",
|
||
"output_type": "stream",
|
||
"text": [
|
||
"<ipython-input-4-6e75736fdab1>:63: RuntimeWarning: divide by zero encountered in log10\n",
|
||
" plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')\n"
|
||
]
|
||
},
|
||
{
|
||
"data": {
|
||
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAYAAAAEGCAYAAABsLkJ6AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/Il7ecAAAACXBIWXMAAAsTAAALEwEAmpwYAAAvfklEQVR4nO3dd3wUdfrA8c+TTkIgBEJNIPTeA1JFROwFzwK2U9RDPcud3unp6et3nnfe2U49xHKoiFiQIvYKCtKFUAOhCCSQBFJISAiB1P3+/tgBY0yyKbuZbPZ5v1682Jmd2XmG1Xl2vt/5Pl8xxqCUUsr3+NkdgFJKKXtoAlBKKR+lCUAppXyUJgCllPJRmgCUUspHBdgdQE20adPGxMbG2h2GUkp5lU2bNh01xkRV9b5XJIDY2Fji4+PtDkMppbyKiBys7n1tAlJKKR+lCUAppXyUJgCllPJRXtEHUJmSkhJSU1MpLCy0OxSvFhISQnR0NIGBgXaHopRqYF6bAFJTUwkPDyc2NhYRsTscr2SMITs7m9TUVLp27Wp3OEqpBua1TUCFhYW0bt1aL/71ICK0bt1a76KU8lFemwAAvfi7gf4bKuW7vDoBKKVUU5VTUMzfP9vJ8cISjx3Da/sA7Jadnc2kSZMASE9Px9/fn6go54C7DRs2EBQUVO3+K1asICgoiDFjxvzqvblz5/Lggw/SqVOnM+vef/99+vXr58YzUEo1RsYYlmxO459fJJJfWMrY7m04r187jxxLE0AdtW7dmq1btwLw+OOP07x5c/785z/XeP8VK1bQvHnzShMAwNSpU5k1a1aV+5eWlhIQEFDlck33U0o1HklHC3js4wTW7MtmeJdW/OvKgfRuH+6x42kTkBtt2rSJC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HW+kAR6V/L81RNlN4BqMbucWCOiGwHTvJzeeKK3gP+CcyvwWe+ArwqIglAKXCLMaaoJncb5RljckXkdZzlhNNxlit3ZTrO8zHAt+XWv4GziWqz1ZGchXM6vw+BSUAiztnwNgN5lcSSJSK3APNFJNha/ZgxZq/VrDRTRFri/H/+RZxNVcrHaTVQ1SRYF7krjDE32R2Lu4lIc2vy79bABmCsMSbd7riU99M7AOX1ROQlnJ2prtrLvdXnVgdyEPAPvfgrd9E7AKWU8lHaCayUUj5KE4BSSvkoTQBKKeWjNAEopZSP0gSglFI+6v8BGJYmwBdsB44AAAAASUVORK5CYII=\n",
|
||
"text/plain": [
|
||
"<Figure size 432x288 with 1 Axes>"
|
||
]
|
||
},
|
||
"metadata": {
|
||
"needs_background": "light"
|
||
},
|
||
"output_type": "display_data"
|
||
}
|
||
],
|
||
"source": [
|
||
"# Common imports\n",
|
||
"import os\n",
|
||
"import numpy as np\n",
|
||
"import pandas as pd\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
|
||
"from sklearn.metrics import mean_squared_error\n",
|
||
"from sklearn.model_selection import KFold\n",
|
||
"from sklearn.model_selection import cross_val_score\n",
|
||
"\n",
|
||
"\n",
|
||
"# Where to save the figures and data files\n",
|
||
"PROJECT_ROOT_DIR = \"Results\"\n",
|
||
"FIGURE_ID = \"Results/FigureFiles\"\n",
|
||
"DATA_ID = \"DataFiles/\"\n",
|
||
"\n",
|
||
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
|
||
" os.mkdir(PROJECT_ROOT_DIR)\n",
|
||
"\n",
|
||
"if not os.path.exists(FIGURE_ID):\n",
|
||
" os.makedirs(FIGURE_ID)\n",
|
||
"\n",
|
||
"if not os.path.exists(DATA_ID):\n",
|
||
" os.makedirs(DATA_ID)\n",
|
||
"\n",
|
||
"def image_path(fig_id):\n",
|
||
" return os.path.join(FIGURE_ID, fig_id)\n",
|
||
"\n",
|
||
"def data_path(dat_id):\n",
|
||
" return os.path.join(DATA_ID, dat_id)\n",
|
||
"\n",
|
||
"def save_fig(fig_id):\n",
|
||
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
|
||
"\n",
|
||
"infile = open(data_path(\"EoS.csv\"),'r')\n",
|
||
"\n",
|
||
"# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
|
||
"EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
|
||
"EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
|
||
"EoS = EoS.dropna()\n",
|
||
"Energies = EoS['Energy']\n",
|
||
"Density = EoS['Density']\n",
|
||
"# The design matrix now as function of various polytrops\n",
|
||
"\n",
|
||
"Maxpolydegree = 30\n",
|
||
"X = np.zeros((len(Density),Maxpolydegree))\n",
|
||
"X[:,0] = 1.0\n",
|
||
"estimated_mse_sklearn = np.zeros(Maxpolydegree)\n",
|
||
"polynomial = np.zeros(Maxpolydegree)\n",
|
||
"k =5\n",
|
||
"kfold = KFold(n_splits = k)\n",
|
||
"\n",
|
||
"for polydegree in range(1, Maxpolydegree):\n",
|
||
" polynomial[polydegree] = polydegree\n",
|
||
" for degree in range(polydegree):\n",
|
||
" X[:,degree] = Density**(degree/3.0)\n",
|
||
" OLS = LinearRegression(fit_intercept=False)\n",
|
||
"# loop over trials in order to estimate the expectation value of the MSE\n",
|
||
" estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)\n",
|
||
"#[:, np.newaxis]\n",
|
||
" estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)\n",
|
||
"\n",
|
||
"plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')\n",
|
||
"plt.xlabel('Polynomial degree')\n",
|
||
"plt.ylabel('log10[MSE]')\n",
|
||
"plt.legend()\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": []
|
||
}
|
||
],
|
||
"metadata": {
|
||
"kernelspec": {
|
||
"display_name": "Python 3",
|
||
"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.8.5"
|
||
}
|
||
},
|
||
"nbformat": 4,
|
||
"nbformat_minor": 4
|
||
}
|