diff --git a/doc/pub/Regression/html/._Regression-bs004.html b/doc/pub/Regression/html/._Regression-bs004.html index d3f378b54..2140156d2 100644 --- a/doc/pub/Regression/html/._Regression-bs004.html +++ b/doc/pub/Regression/html/._Regression-bs004.html @@ -212,10 +212,12 @@ $$ \hat{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, $$ +and $$ \hat{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, $$ +and $$ \hat{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, $$ diff --git a/doc/pub/Regression/html/._Regression-bs017.html b/doc/pub/Regression/html/._Regression-bs017.html index 1ba836c85..a5524d1e6 100644 --- a/doc/pub/Regression/html/._Regression-bs017.html +++ b/doc/pub/Regression/html/._Regression-bs017.html @@ -209,9 +209,9 @@ MathJax.Hub.Config({

-We define then +For a linear fit we don't need to invert a matrix!! $$ -\gamma = \sum_{i=0}^{1}\frac{n-1}{\sigma_i^2}, +\gamma = \sum_{i=0}^{n-1}\frac{n-1}{\sigma_i^2}, $$ @@ -241,7 +241,7 @@ $$ $$

-The LSM suffers often from both being underdetermined and overdetermined in the unknown coefficients \( \beta_i \). A better approach is to use the Singular Value Decomposition (SVD) method discussed below. +The LSM suffers often from both being underdetermined and overdetermined in the unknown coefficients \( \beta_i \). A better approach is to use the Singular Value Decomposition (SVD) method discussed below. Or using Lasso and Ridge regression. See below. diff --git a/doc/pub/Regression/html/Regression-reveal.html b/doc/pub/Regression/html/Regression-reveal.html index 2e93e3ddc..c43d7c5b4 100644 --- a/doc/pub/Regression/html/Regression-reveal.html +++ b/doc/pub/Regression/html/Regression-reveal.html @@ -236,12 +236,14 @@ $$ $$

 
+and

 
$$ \hat{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, $$

 
+and

 
$$ \hat{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, @@ -644,10 +646,11 @@ $$

-We define then +For a linear fit we don't need to invert a matrix!! +

 
$$ -\gamma = \sum_{i=0}^{1}\frac{n-1}{\sigma_i^2}, +\gamma = \sum_{i=0}^{n-1}\frac{n-1}{\sigma_i^2}, $$

 
@@ -689,7 +692,7 @@ $$

 

-The LSM suffers often from both being underdetermined and overdetermined in the unknown coefficients \( \beta_i \). A better approach is to use the Singular Value Decomposition (SVD) method discussed below. +The LSM suffers often from both being underdetermined and overdetermined in the unknown coefficients \( \beta_i \). A better approach is to use the Singular Value Decomposition (SVD) method discussed below. Or using Lasso and Ridge regression. See below.

diff --git a/doc/pub/Regression/html/Regression-solarized.html b/doc/pub/Regression/html/Regression-solarized.html index 69c12c250..a6c79bb33 100644 --- a/doc/pub/Regression/html/Regression-solarized.html +++ b/doc/pub/Regression/html/Regression-solarized.html @@ -255,10 +255,12 @@ $$ \hat{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, $$ +and $$ \hat{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, $$ +and $$ \hat{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, $$ @@ -613,9 +615,9 @@ $$

-We define then +For a linear fit we don't need to invert a matrix!! $$ -\gamma = \sum_{i=0}^{1}\frac{n-1}{\sigma_i^2}, +\gamma = \sum_{i=0}^{n-1}\frac{n-1}{\sigma_i^2}, $$ @@ -645,7 +647,7 @@ $$ $$

-The LSM suffers often from both being underdetermined and overdetermined in the unknown coefficients \( \beta_i \). A better approach is to use the Singular Value Decomposition (SVD) method discussed below. +The LSM suffers often from both being underdetermined and overdetermined in the unknown coefficients \( \beta_i \). A better approach is to use the Singular Value Decomposition (SVD) method discussed below. Or using Lasso and Ridge regression. See below. diff --git a/doc/pub/Regression/html/Regression.html b/doc/pub/Regression/html/Regression.html index c55ca0610..854e388de 100644 --- a/doc/pub/Regression/html/Regression.html +++ b/doc/pub/Regression/html/Regression.html @@ -260,10 +260,12 @@ $$ \hat{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, $$ +and $$ \hat{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, $$ +and $$ \hat{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, $$ @@ -618,9 +620,9 @@ $$

-We define then +For a linear fit we don't need to invert a matrix!! $$ -\gamma = \sum_{i=0}^{1}\frac{n-1}{\sigma_i^2}, +\gamma = \sum_{i=0}^{n-1}\frac{n-1}{\sigma_i^2}, $$ @@ -650,7 +652,7 @@ $$ $$

-The LSM suffers often from both being underdetermined and overdetermined in the unknown coefficients \( \beta_i \). A better approach is to use the Singular Value Decomposition (SVD) method discussed below. +The LSM suffers often from both being underdetermined and overdetermined in the unknown coefficients \( \beta_i \). A better approach is to use the Singular Value Decomposition (SVD) method discussed below. Or using Lasso and Ridge regression. See below. diff --git a/doc/pub/Regression/ipynb/Regression.ipynb b/doc/pub/Regression/ipynb/Regression.ipynb index 29137fca4..e58efcf70 100644 --- a/doc/pub/Regression/ipynb/Regression.ipynb +++ b/doc/pub/Regression/ipynb/Regression.ipynb @@ -10,9 +10,9 @@ " \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: **Nov 21, 2017**\n", + "Date: **Aug 24, 2018**\n", "\n", - "Copyright 1999-2017, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", + "Copyright 1999-2018, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", "\n", "\n", "\n", @@ -89,46 +89,32 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "2\n", - " \n", - "<\n", - "<\n", - "<\n", - "!\n", - "!\n", - "M\n", - "A\n", - "T\n", - "H\n", - "_\n", - "B\n", - "L\n", - "O\n", - "C\n", - "K" + "$$\n", + "\\hat{y} = [y_0,y_1, y_2,\\dots, y_{n-1}]^T,\n", + "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "3\n", - " \n", - "<\n", - "<\n", - "<\n", - "!\n", - "!\n", - "M\n", - "A\n", - "T\n", - "H\n", - "_\n", - "B\n", - "L\n", - "O\n", - "C\n", - "K" + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{\\beta} = [\\beta_0,\\beta_1, \\beta_2,\\dots, \\beta_{n-1}]^T,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" ] }, { @@ -513,6 +499,7 @@ "\n", "\n", "\n", + "\n", "## The $\\chi^2$ function\n", "\n", "Normally, the response (dependent or outcome) variable $y_i$ the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat $y_i$ as our exact value for the response variable.\n", @@ -651,7 +638,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{H} = \\hat{A}^T\\hat{A},\n", + "\\hat{H} = \\left(\\hat{A}^T\\hat{A}\\right)^{-1},\n", "$$" ] }, @@ -675,7 +662,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We state without proof the expression for the uncertainty in the parameters $\\beta_j$ as" + "We state without proof the expression for the uncertainty in the parameters $\\beta_j$ as (we leave this as an exercise)" ] }, { @@ -732,7 +719,7 @@ "metadata": {}, "source": [ "$$\n", - "\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\beta_0} = -2\\left[ \\sum_{i=0}^{1}\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0,\n", + "\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\beta_0} = -2\\left[ \\sum_{i=0}^{n-1}\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0,\n", "$$" ] }, @@ -748,7 +735,7 @@ "metadata": {}, "source": [ "$$\n", - "\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\beta_0} = -2\\left[ \\sum_{i=0}^{1}x_i\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0.\n", + "\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\beta_0} = -2\\left[ \\sum_{i=0}^{n-1}x_i\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0.\n", "$$" ] }, @@ -758,7 +745,7 @@ "source": [ "## The $\\chi^2$ function\n", "\n", - "We define then" + "For a linear fit we don't need to invert a matrix!!" ] }, { @@ -766,7 +753,7 @@ "metadata": {}, "source": [ "$$\n", - "\\gamma = \\sum_{i=0}^{1}\\frac{1}{\\sigma_i^2},\n", + "\\gamma = \\sum_{i=0}^{n-1}\\frac{n-1}{\\sigma_i^2},\n", "$$" ] }, @@ -847,7 +834,7 @@ "metadata": {}, "source": [ "$$\n", - "\\gamma_{xy} = \\sum_{i=0}^{1}\\frac{y_ix_{i}}{\\sigma_i^2},\n", + "\\gamma_{xy} = \\sum_{i=0}^{n-1}\\frac{y_ix_{i}}{\\sigma_i^2},\n", "$$" ] }, @@ -895,12 +882,778 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The LSM suffers often from both being underdetermined and overdetermined in the unknown coefficients $\\beta_i$. A better approach is to use the Singular Value Decomposition (SVD) method discussed below.\n", + "The LSM suffers often from both being underdetermined and overdetermined in the unknown coefficients $\\beta_i$. A better approach is to use the Singular Value Decomposition (SVD) method discussed below. Or using Lasso and Ridge regression. See below.\n", "\n", "\n", "\n", "\n", "\n", + "\n", + "## Simple regression model\n", + "We are now ready to write our first program which aims at solving the above linear regression equations. We start with data we have produced ourselves, in this case normally distributed random numbers along the $x$-axis. These numbers define then the value of a function $y(x)=4+3x+N(0,1)$. Thereafter we order the $x$ values and employ our linear regression algorithm to set up the best fit. Here we find it useful to use the numpy function $c\\_$ arrays where arrays are stacked along their last axis after being upgraded to at least two dimensions with ones post-pended to the shape. The following examples help in understanding what happens" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "print(np.c_[np.array([1,2,3]), np.array([4,5,6])])\n", + "print(np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])])" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "# Importing various packages\n", + "from random import random, seed\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "x = 2*np.random.rand(100,1)\n", + "y = 4+3*x+np.random.randn(100,1)\n", + "\n", + "xb = np.c_[np.ones((100,1)), x]\n", + "beta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\n", + "xnew = np.array([[0],[2]])\n", + "xbnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = xbnew.dot(beta)\n", + "\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Linear Regression')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We see that, as expected, a linear fit gives a seemingly (from the graph) good representation of the data.\n", + "\n", + "\n", + "\n", + "\n", + "## Simple regression model, now using **scikit-learn**\n", + "\n", + "\n", + "We can repeat the above algorithm using **scikit-learn** as follows" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Importing various packages\n", + "from random import random, seed\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.linear_model import LinearRegression\n", + "\n", + "x = 2*np.random.rand(100,1)\n", + "y = 4+3*x+np.random.randn(100,1)\n", + "linreg = LinearRegression()\n", + "linreg.fit(x,y)\n", + "xnew = np.array([[0],[2]])\n", + "ypredict = linreg.predict(xnew)\n", + "\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Random numbers ')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Simple linear regression model using **scikit-learn**\n", + "\n", + "We start with perhaps our simplest possible example, using **scikit-learn** to perform linear regression analysis on a data set produced by us. \n", + "What follows is a simple Python code where we have defined function $y$ in terms of the variable $x$. Both are defined as vectors of dimension $1\\times 100$. The entries to the vector $\\hat{x}$ are given by random numbers generated with a uniform distribution with entries $x_i \\in [0,1]$ (more about probability distribution functions later). These values are then used to define a function $y(x)$ (tabulated again as a vector) with a linear dependence on $x$ plus a random noise added via the normal distribution.\n", + "\n", + "\n", + "The Numpy functions are imported used the **import numpy as np**\n", + "statement and the random number generator for the uniform distribution\n", + "is called using the function **np.random.rand()**, where we specificy\n", + "that we want $100$ random variables. Using Numpy we define\n", + "automatically an array with the specified number of elements, $100$ in\n", + "our case. With the Numpy function **randn()** we can compute random\n", + "numbers with the normal distribution (mean value $\\mu$ equal to zero and\n", + "variance $\\sigma^2$ set to one) and produce the values of $y$ assuming a linear\n", + "dependence as function of $x$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y = 2x+N(0,1),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $N(0,1)$ represents random numbers generated by the normal\n", + "distribution. From **scikit-learn** we import then the\n", + "**LinearRegression** functionality and make a prediction $\\tilde{y} =\n", + "\\alpha + \\beta x$ using the function **fit(x,y)**. We call the set of\n", + "data $(\\hat{x},\\hat{y})$ for our training data. The Python package\n", + "**scikit-learn** has also a functionality which extracts the above\n", + "fitting parameters $\\alpha$ and $\\beta$ (see below). Later we will\n", + "distinguish between training data and test data.\n", + "\n", + "For plotting we use the Python package\n", + "[matplotlib](https://matplotlib.org/) which produces publication\n", + "quality figures. Feel free to explore the extensive\n", + "[gallery](https://matplotlib.org/gallery/index.html) of examples. In\n", + "this example we plot our original values of $x$ and $y$ as well as the\n", + "prediction **ypredict** ($\\tilde{y}$), which attempts at fitting our\n", + "data with a straight line.\n", + "\n", + "The Python code follows here." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Importing various packages\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.linear_model import LinearRegression\n", + "\n", + "x = np.random.rand(100,1)\n", + "y = 2*x+np.random.randn(100,1)\n", + "linreg = LinearRegression()\n", + "linreg.fit(x,y)\n", + "xnew = np.array([[0],[1]])\n", + "ypredict = linreg.predict(xnew)\n", + "\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,1.0,0, 5.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Simple Linear Regression')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Simple linear regression model\n", + "\n", + "This example serves several aims. It allows us to demonstrate several\n", + "aspects of data analysis and later machine learning algorithms. The\n", + "immediate visualization shows that our linear fit is not\n", + "impressive. It goes through the data points, but there are many\n", + "outliers which are not reproduced by our linear regression. We could\n", + "now play around with this small program and change for example the\n", + "factor in front of $x$ and the normal distribution. Try to change the\n", + "function $y$ to" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y = 10x+0.01 \\times N(0,1),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $x$ is defined as before. \n", + "\n", + "\n", + "## Less noise\n", + "\n", + "Does the fit look better? Indeed, by\n", + "reducing the role of the normal distribution we see immediately that\n", + "our linear prediction seemingly reproduces better the training\n", + "set. However, this testing 'by the eye' is obviouly not satisfactory in the\n", + "long run. Here we have only defined the training data and our model, and \n", + "have not discussed a more rigorous approach to the **cost** function.\n", + "\n", + "\n", + "## How to study our fits\n", + "\n", + "We need more rigorous criteria in defining whether we have succeeded or\n", + "not in modeling our training data. You will be surprised to see that\n", + "many scientists seldomly venture beyond this 'by the eye' approach. A\n", + "standard approach for the *cost* function is the so-called $\\chi^2$\n", + "function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\chi^2 = \\frac{1}{n}\n", + "\\sum_{i=0}^{n-1}\\frac{(y_i-\\tilde{y}_i)^2}{\\sigma_i^2},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $\\sigma_i^2$ is the variance (to be defined later) of the entry\n", + "$y_i$. We may not know the explicit value of $\\sigma_i^2$, it serves\n", + "however the aim of scaling the equations and make the cost function\n", + "dimensionless. \n", + "\n", + "\n", + "## Minimizing the cost function\n", + "\n", + "Minimizing the cost function is a central aspect of\n", + "our discussions to come. Finding its minima as function of the model\n", + "parameters ($\\alpha$ and $\\beta$ in our case) will be a recurring\n", + "theme in these series of lectures. Essentially all machine learning\n", + "algorithms we will discuss center around the minimization of the\n", + "chosen cost function. This depends in turn on our specific\n", + "model for describing the data, a typical situation in supervised\n", + "learning. Automatizing the search for the minima of the cost function is a\n", + "central ingredient in all algorithms. Typical methods which are\n", + "employed are various variants of **gradient** methods. These will be\n", + "discussed in more detail later. Again, you'll be surprised to hear that\n", + "many practitioners minimize the above function ''by the eye', popularly dubbed as \n", + "'chi by the eye'. That is, change a parameter and see (visually and numerically) that \n", + "the $\\chi^2$ function becomes smaller. \n", + "\n", + "## Relative error\n", + "\n", + "There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define \n", + "the relative error as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\epsilon_{\\mathrm{relative}}= \\frac{\\vert \\hat{y} -\\hat{\\tilde{y}}\\vert}{\\vert \\hat{y}\\vert}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can modify easily the above Python code and plot the relative error instead" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.linear_model import LinearRegression\n", + "\n", + "x = np.random.rand(100,1)\n", + "y = 5*x+0.01*np.random.randn(100,1)\n", + "linreg = LinearRegression()\n", + "linreg.fit(x,y)\n", + "ypredict = linreg.predict(x)\n", + "\n", + "plt.plot(x, np.abs(ypredict-y)/abs(y), \"ro\")\n", + "plt.axis([0,1.0,0.0, 0.5])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$\\epsilon_{\\mathrm{relative}}$')\n", + "plt.title(r'Relative error')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Depending on the parameter in front of the normal distribution, we may\n", + "have a small or larger relative error. Try to play around with\n", + "different training data sets and study (graphically) the value of the\n", + "relative error.\n", + "\n", + "\n", + "## The richness of **scikit-learn**\n", + "\n", + "As mentioned above, **scikit-learn** has an impressive functionality.\n", + "We can for example extract the values of $\\alpha$ and $\\beta$ and\n", + "their error estimates, or the variance and standard deviation and many\n", + "other properties from the statistical data analysis. \n", + "\n", + "Here we show an\n", + "example of the functionality of scikit-learn." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np \n", + "import matplotlib.pyplot as plt \n", + "from sklearn.linear_model import LinearRegression \n", + "from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error\n", + "\n", + "x = np.random.rand(100,1)\n", + "y = 2.0+ 5*x+0.5*np.random.randn(100,1)\n", + "linreg = LinearRegression()\n", + "linreg.fit(x,y)\n", + "ypredict = linreg.predict(x)\n", + "print('The intercept alpha: \\n', linreg.intercept_)\n", + "print('Coefficient beta : \\n', linreg.coef_)\n", + "# The mean squared error \n", + "print(\"Mean squared error: %.2f\" % mean_squared_error(y, ypredict))\n", + "# Explained variance score: 1 is perfect prediction \n", + "print('Variance score: %.2f' % r2_score(y, ypredict))\n", + "# Mean squared log error \n", + "print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) )\n", + "# Mean absolute error \n", + "print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict))\n", + "plt.plot(x, ypredict, \"r-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0.0,1.0,1.5, 7.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Linear Regression fit ')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Functions in **scikit-learn**\n", + "\n", + "The function **coef** gives us the parameter $\\beta$ of our fit while **intercept** yields \n", + "$\\alpha$. Depending on the constant in front of the normal distribution, we get values near or far from $alpha =2$ and $\\beta =5$. Try to play around with different parameters in front of the normal distribution. The function **meansquarederror** gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n", + "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The smaller the value, the better the fit. Ideally we would like to\n", + "have an MSE equal zero. The attentive reader has probably recognized\n", + "this function as being similar to the $\\chi^2$ function defined above.\n", + "\n", + "## Other functions in **scikit-learn**\n", + "\n", + "The **r2score** function computes $R^2$, the coefficient of\n", + "determination. It provides a measure of how well future samples are\n", + "likely to be predicted by the model. Best possible score is 1.0 and it\n", + "can be negative (because the model can be arbitrarily worse). A\n", + "constant model that always predicts the expected value of $\\hat{y}$,\n", + "disregarding the input features, would get a $R^2$ score of $0.0$.\n", + "\n", + "If $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "R^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we have defined the mean value of $\\hat{y}$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The mean absolute error and other functions in **scikit-learn**\n", + "\n", + "Another quantity will meet again in our discussions of regression analysis is \n", + " mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the $l1$-norm loss. In our discussion above we presented the relative error.\n", + "The MAE is defined as follows" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\text{MAE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n-1} \\left| y_i - \\tilde{y}_i \\right|.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Finally we present the \n", + "squared logarithmic (quadratic) error" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\text{MSLE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n - 1} (\\log_e (1 + y_i) - \\log_e (1 + \\tilde{y}_i) )^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $\\log_e (x)$ stands for the natural logarithm of $x$. This error\n", + "estimate is best to use when targets having exponential growth, such\n", + "as population counts, average sales of a commodity over a span of\n", + "years etc. \n", + "\n", + "\n", + "## Cubic polynomial in **scikit-learn**\n", + "\n", + "We will discuss in more\n", + "detail these and other functions in the various lectures. We conclude this part with another example. Instead of \n", + "a linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "import random\n", + "from sklearn.linear_model import Ridge\n", + "from sklearn.preprocessing import PolynomialFeatures\n", + "from sklearn.pipeline import make_pipeline\n", + "from sklearn.linear_model import LinearRegression\n", + "\n", + "x=np.linspace(0.02,0.98,200)\n", + "noise = np.asarray(random.sample((range(200)),200))\n", + "y=x**3*noise\n", + "yn=x**3*100\n", + "poly3 = PolynomialFeatures(degree=3)\n", + "X = poly3.fit_transform(x[:,np.newaxis])\n", + "clf3 = LinearRegression()\n", + "clf3.fit(X,y)\n", + "\n", + "Xplot=poly3.fit_transform(x[:,np.newaxis])\n", + "poly3_plot=plt.plot(x, clf3.predict(Xplot), label='Cubic Fit')\n", + "plt.plot(x,yn, color='red', label=\"True Cubic\")\n", + "plt.scatter(x, y, label='Data', color='orange', s=15)\n", + "plt.legend()\n", + "plt.show()\n", + "\n", + "def error(a):\n", + " for i in y:\n", + " err=(y-yn)/yn\n", + " return abs(np.sum(err))/len(err)\n", + "\n", + "print (error(y))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Similarly, using **R**, we can perform similar studies. \n", + "(more details on **R** will be inserted later).\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "## Simple regression model with gradient descent\n", + "Add info about the equations, play around with different learning rates" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Importing various packages\n", + "from math import exp, sqrt\n", + "from random import random, seed\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "x = 2*np.random.rand(100,1)\n", + "y = 4+3*x+np.random.randn(100,1)\n", + "\n", + "xb = np.c_[np.ones((100,1)), x]\n", + "theta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\n", + "print(theta_linreg)\n", + "theta = np.random.randn(2,1)\n", + "\n", + "eta = 0.1\n", + "Niterations = 1000\n", + "m = 100\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = 2.0/m*xb.T.dot(xb.dot(theta)-y)\n", + " theta -= eta*gradients\n", + "\n", + "print(theta)\n", + "xnew = np.array([[0],[2]])\n", + "xbnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = xbnew.dot(theta)\n", + "ypredict2 = xbnew.dot(theta_linreg)\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(xnew, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Random numbers ')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Simple regression model with stochastic gradient descent\n", + "Add info about the equations, play around with different learning rates" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Importing various packages\n", + "from math import exp, sqrt\n", + "from random import random, seed\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.linear_model import SGDRegressor\n", + "\n", + "x = 2*np.random.rand(100,1)\n", + "y = 4+3*x+np.random.randn(100,1)\n", + "\n", + "xb = np.c_[np.ones((100,1)), x]\n", + "theta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\n", + "print(theta_linreg)\n", + "sgdreg = SGDRegressor(n_iter = 50, penalty=None, eta0=0.1)\n", + "sgdreg.fit(x,y.ravel())\n", + "print(sgdreg.intercept_, sgdreg.coef_)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Polynomial Regression" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Importing various packages\n", + "from math import exp, sqrt\n", + "from random import random, seed\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "m = 100\n", + "x = 2*np.random.rand(m,1)+4.\n", + "y = 4+3*x*x+ +x-np.random.randn(m,1)\n", + "\n", + "xb = np.c_[np.ones((m,1)), x]\n", + "theta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\n", + "xnew = np.array([[0],[2]])\n", + "xbnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = xbnew.dot(theta)\n", + "\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Random numbers ')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Ridge and Lasso Regression" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn import linear_model\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.metrics import mean_squared_error, r2_score\n", + "\n", + "#creating data with random noise\n", + "x=np.arange(50)\n", + "\n", + "delta=np.random.uniform(-2.5,2.5, size=(50))\n", + "np.random.shuffle(delta)\n", + "y =0.5*x+5+delta\n", + "\n", + "#arranging data into 2x50 matrix\n", + "a=np.array(x) #inputs\n", + "b=np.array(y) #outputs\n", + "\n", + "#Split into training and test\n", + "X_train=a[:37, np.newaxis]\n", + "X_test=a[37:, np.newaxis]\n", + "y_train=b[:37]\n", + "y_test=b[37:]\n", + "\n", + "print (\"X_train: \", X_train.shape)\n", + "print (\"y_train: \", y_train.shape)\n", + "print (\"X_test: \", X_test.shape)\n", + "print (\"y_test: \", y_test.shape)\n", + "\n", + "print (\"------------------------------------\")\n", + "\n", + "print (\"Ordinary Least Squares\")\n", + "#Add Ordinary Least Squares fit\n", + "reg=LinearRegression()\n", + "reg.fit(X_train, y_train)\n", + "pred=reg.predict(X_test)\n", + "print (\"Prediction Shape: \", pred.shape)\n", + "\n", + "print('Coefficients: \\n', reg.coef_)\n", + "# The mean squared error\n", + "print(\"Mean squared error: %.2f\"\n", + " % mean_squared_error(y_test, pred))\n", + "# Explained variance score: 1 is perfect prediction\n", + "print('Variance score: %.2f' % r2_score(y_test, pred))\n", + "\n", + "#plot\n", + "plt.scatter(X_test,y_test,color='green', label=\"Training Data\")\n", + "plt.plot(X_test, pred, color='black', label=\"Fit Line\")\n", + "plt.legend()\n", + "plt.show()\n", + "\n", + "print (\"------------------------------------\")\n", + "\n", + "print (\"Ridge Regression\")\n", + "\n", + "ridge=linear_model.RidgeCV(alphas=[0.1,1.0,10.0])\n", + "ridge.fit(X_train,y_train)\n", + "print (\"Ridge Coefficient: \",ridge.coef_)\n", + "print (\"Ridge Intercept: \", ridge.intercept_)\n", + "#Look into graphing with Ridge fit\n", + "\n", + "print (\"------------------------------------\")\n", + "\n", + "print (\"Lasso\")\n", + "lasso=linear_model.Lasso(alpha=0.1)\n", + "lasso.fit(X_train,y_train)\n", + "predl=lasso.predict(X_test)\n", + "print(\"Lasso Coefficient: \", lasso.coef_)\n", + "print(\"Lasso Intercept: \", lasso.intercept_)\n", + "plt.scatter(X_test,y_test,color='green', label=\"Training Data\")\n", + "plt.plot(X_test, predl, color='blue', label=\"Lasso\")\n", + "plt.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ "## The singular value decompostion\n", "How can we use the singular value decomposition to find the parameters $\\beta_j$? More details will come. We first note that a general $m\\times n$ matrix $\\hat{A}$ can be written in terms of a diagonal matrix $\\hat{\\Sigma}$ of dimensionality $n\\times n$ and two orthognal matrices $\\hat{U}$ and $\\hat{V}$, where the first has dimensionality $m \\times n$ and the last dimensionality $n\\times n$. We have then" ] @@ -913,27 +1666,26 @@ "\\hat{A} = \\hat{U}\\hat{\\Sigma}\\hat{V}\n", "$$" ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Add codes and discuss this in connection with lasso and ridge, show example where the standard inversion of a matrix fails and where SVD comes to rescue\n", + "\n", + "\n", + "## Lasso and Ridge regression\n", + "\n", + "Discuss the mathematics here\n", + "\n", + "## Logistic regression\n", + "Add discussion about classification versus regression, show examples of more than two cases and why regression is not the best approach. Motivate for k-nearest neighbors\n", + "\n", + "Add examples on classification problems" + ] } ], - "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.6.5" - } - }, + "metadata": {}, "nbformat": 4, "nbformat_minor": 2 } diff --git a/doc/pub/Regression/ipynb/ipynb-Regression-src.tar.gz b/doc/pub/Regression/ipynb/ipynb-Regression-src.tar.gz index ec5a99105..193056ca4 100644 Binary files a/doc/pub/Regression/ipynb/ipynb-Regression-src.tar.gz and b/doc/pub/Regression/ipynb/ipynb-Regression-src.tar.gz differ diff --git a/doc/pub/Regression/pdf/Regression-beamer-handouts2x3.pdf b/doc/pub/Regression/pdf/Regression-beamer-handouts2x3.pdf index 2298c24e0..17fab86a4 100644 Binary files a/doc/pub/Regression/pdf/Regression-beamer-handouts2x3.pdf and b/doc/pub/Regression/pdf/Regression-beamer-handouts2x3.pdf differ diff --git a/doc/pub/Regression/pdf/Regression-beamer.pdf b/doc/pub/Regression/pdf/Regression-beamer.pdf index 8c2c84883..1d9c4a61d 100644 Binary files a/doc/pub/Regression/pdf/Regression-beamer.pdf and b/doc/pub/Regression/pdf/Regression-beamer.pdf differ diff --git a/doc/pub/Regression/pdf/Regression-minted.pdf b/doc/pub/Regression/pdf/Regression-minted.pdf index 57767b543..2bfce68d9 100644 Binary files a/doc/pub/Regression/pdf/Regression-minted.pdf and b/doc/pub/Regression/pdf/Regression-minted.pdf differ diff --git a/doc/src/Regression/Regression.do.txt b/doc/src/Regression/Regression.do.txt index b0c6e086f..1dbd42d63 100644 --- a/doc/src/Regression/Regression.do.txt +++ b/doc/src/Regression/Regression.do.txt @@ -59,11 +59,13 @@ Defining the vectors \hat{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, \] !et +and !bt \[ \hat{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, \] !et +and !bt \[ \hat{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, @@ -390,7 +392,7 @@ and ===== The $\chi^2$ function ===== !bblock -We define then +For a linear fit we don't need to invert a matrix!! !bt \[ \gamma = \sum_{i=0}^{n-1}\frac{n-1}{\sigma_i^2}, @@ -429,7 +431,7 @@ and show that \] !et -The LSM suffers often from both being underdetermined and overdetermined in the unknown coefficients $\beta_i$. A better approach is to use the Singular Value Decomposition (SVD) method discussed below. +The LSM suffers often from both being underdetermined and overdetermined in the unknown coefficients $\beta_i$. A better approach is to use the Singular Value Decomposition (SVD) method discussed below. Or using Lasso and Ridge regression. See below. !eblock diff --git a/doc/src/Regression/make.sh b/doc/src/Regression/make.sh index 0671a98d3..edfed7c87 100755 --- a/doc/src/Regression/make.sh +++ b/doc/src/Regression/make.sh @@ -47,7 +47,7 @@ system doconce format html $name --html_style=bootstrap --pygments_html_style=de system doconce split_html $html.html --method=split --pagination --nav_button=bottom # IPython notebook -#system doconce format ipynb $name $opt +system doconce format ipynb $name $opt # LaTeX Beamer slides beamertheme=red_plain