Files
FYS-STK4155/doc/pub/Regression/ipynb/Regression.ipynb
T
2018-09-06 11:28:45 +02:00

2147 lines
67 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- dom:TITLE: Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis -->\n",
"# Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis\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 6, 2018**\n",
"\n",
"Copyright 1999-2018, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
"\n",
"\n",
"\n",
"\n",
"## Regression analysis, overarching aims\n",
"\n",
"Regression modeling deals with the description of the sampling distribution of a given random variable $y$ varies as function of another variable or a set of such variables $\\hat{x} =[x_0, x_1,\\dots, x_p]^T$. \n",
"The first variable is called the **dependent**, the **outcome** or the **response** variable while the set of variables $\\hat{x}$ is called the independent variable, or the predictor variable or the explanatory variable. \n",
"\n",
"A regression model aims at finding a likelihood function $p(y\\vert \\hat{x})$, that is the conditional distribution for $y$ with a given $\\hat{x}$. The estimation of $p(y\\vert \\hat{x})$ is made using a data set with \n",
"* $n$ cases $i = 0, 1, 2, \\dots, n-1$ \n",
"\n",
"* Response (dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \\dots, n-1$ \n",
"\n",
"* $p$ Explanatory (independent or predictor) variables $\\hat{x}_i=[x_{i0}, x_{i1}, \\dots, x_{ip}]$ with $i = 0, 1, 2, \\dots, n-1$ \n",
"\n",
" The goal of the regression analysis is to extract/exploit relationship between $y_i$ and $\\hat{x}_i$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions .\n",
"\n",
"\n",
"\n",
"## Regression analysis, overarching aims II\n",
"\n",
"\n",
"Consider an experiment in which $p$ characteristics of $n$ samples are\n",
"measured. The data from this experiment are denoted $\\mathbf{X}$, with\n",
"$\\mathbf{X}$ as above. The matrix $\\mathbf{X}$ is called the *design\n",
"matrix*. Additional information of the samples is available in the\n",
"form of $\\mathbf{Y}$ (also as above). The variable $\\mathbf{Y}$ is\n",
"generally referred to as the *response variable*. The aim of\n",
"regression analysis is to explain $\\mathbf{Y}$ in terms of\n",
"$\\mathbf{X}$ through a functional relationship like $Y_i =\n",
"f(\\mathbf{X}_{i,\\ast})$. When no prior knowledge on the form of\n",
"$f(\\cdot)$ is available, it is common to assume a linear relationship\n",
"between $\\mathbf{X}$ and $\\mathbf{Y}$. This assumption gives rise to\n",
"the *linear regression model* where $\\beta = (\\beta_1, \\ldots,\n",
"\\beta_p)^{\\top}$ is the *regression parameter*. The parameter\n",
"$\\beta_j$, $j=1, \\ldots, p$, represents the effect size of covariate\n",
"$j$ on the response. That is, for each unit change in covariate $j$\n",
"(while keeping the other covariates fixed) the observed change in the\n",
"response is equal to $\\beta_j$.\n",
"\n",
"\n",
"\n",
"## General linear models\n",
"Before we proceed let us study a case from linear algebra where we aim at fitting a set of data $\\hat{y}=[y_0,y_1,\\dots,y_{n-1}]$. We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables $\\hat{x}=[x_0,x_1,\\dots,x_{n-1}]$, that is $y_i = y(x_i)$ with $i=0,1,2,\\dots,n-1$. The variables $x_i$ could represent physical quantities like time, temperature, position etc. We assume that $y(x)$ is a smooth function. \n",
"\n",
"Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of $y$ which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree $n-1$ with $n$ points, that is"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"y=y(x) \\rightarrow y(x_i)=\\tilde{y}_i+\\epsilon_i=\\sum_{j=0}^{n-1} \\beta_i x_i^j+\\epsilon_i,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $\\epsilon_i$ is the error in our approximation.\n",
"\n",
"\n",
"\n",
"\n",
"## Rewriting the fitting procedure as a linear algebra problem\n",
"For every set of values $y_i,x_i$ we have thus the corresponding set of equations"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{align*}\n",
"y_0&=\\beta_0+\\beta_1x_0^1+\\beta_2x_0^2+\\dots+\\beta_{n-1}x_0^{n-1}+\\epsilon_0\\\\\n",
"y_1&=\\beta_0+\\beta_1x_1^1+\\beta_2x_1^2+\\dots+\\beta_{n-1}x_1^{n-1}+\\epsilon_1\\\\\n",
"y_2&=\\beta_0+\\beta_1x_2^1+\\beta_2x_2^2+\\dots+\\beta_{n-1}x_2^{n-1}+\\epsilon_2\\\\\n",
"\\dots & \\dots \\\\\n",
"y_{n-1}&=\\beta_0+\\beta_1x_{n-1}^1+\\beta_2x_{n-1}^2+\\dots+\\beta_1x_{n-1}^{n-1}+\\epsilon_{n-1}.\\\\\n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Rewriting the fitting procedure as a linear algebra problem, follows\n",
"Defining the vectors"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\hat{y} = [y_0,y_1, y_2,\\dots, y_{n-1}]^T,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\hat{\\epsilon} = [\\epsilon_0,\\epsilon_1, \\epsilon_2,\\dots, \\epsilon_{n-1}]^T,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and the matrix"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\hat{X}=\n",
"\\begin{bmatrix} \n",
"1& x_{0}^1 &x_{0}^2& \\dots & \\dots &x_{0}^{n-1}\\\\\n",
"1& x_{1}^1 &x_{1}^2& \\dots & \\dots &x_{1}^{n-1}\\\\\n",
"1& x_{2}^1 &x_{2}^2& \\dots & \\dots &x_{2}^{n-1}\\\\ \n",
"\\dots& \\dots &\\dots& \\dots & \\dots &\\dots\\\\\n",
"1& x_{n-1}^1 &x_{n-1}^2& \\dots & \\dots &x_{n-1}^{n-1}\\\\\n",
"\\end{bmatrix}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"we can rewrite our equations as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\hat{y} = \\hat{X}\\hat{\\beta}+\\hat{\\epsilon}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Generalizing the fitting procedure as a linear algebra problem\n",
"We are obviously not limited to the above polynomial. We could replace the various powers of $x$ with elements of Fourier series, that is, instead of $x_i^j$ we could have $\\cos{(j x_i)}$ or $\\sin{(j x_i)}$, or time series or other orthogonal functions.\n",
"For every set of values $y_i,x_i$ we can then generalize the equations to"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{align*}\n",
"y_0&=\\beta_0x_{00}+\\beta_1x_{01}+\\beta_2x_{02}+\\dots+\\beta_{n-1}x_{0n-1}+\\epsilon_0\\\\\n",
"y_1&=\\beta_0x_{10}+\\beta_1x_{11}+\\beta_2x_{12}+\\dots+\\beta_{n-1}x_{1n-1}+\\epsilon_1\\\\\n",
"y_2&=\\beta_0x_{20}+\\beta_1x_{21}+\\beta_2x_{22}+\\dots+\\beta_{n-1}x_{2n-1}+\\epsilon_2\\\\\n",
"\\dots & \\dots \\\\\n",
"y_{i}&=\\beta_0x_{i0}+\\beta_1x_{i1}+\\beta_2x_{i2}+\\dots+\\beta_{n-1}x_{in-1}+\\epsilon_i\\\\\n",
"\\dots & \\dots \\\\\n",
"y_{n-1}&=\\beta_0x_{n-1,0}+\\beta_1x_{n-1,2}+\\beta_2x_{n-1,2}+\\dots+\\beta_1x_{n-1,n-1}+\\epsilon_{n-1}.\\\\\n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Generalizing the fitting procedure as a linear algebra problem\n",
"We redefine in turn the matrix $\\hat{X}$ as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\hat{X}=\n",
"\\begin{bmatrix} \n",
"x_{00}& x_{01} &x_{02}& \\dots & \\dots &x_{0,n-1}\\\\\n",
"x_{10}& x_{11} &x_{12}& \\dots & \\dots &x_{1,n-1}\\\\\n",
"x_{20}& x_{21} &x_{22}& \\dots & \\dots &x_{2,n-1}\\\\ \n",
"\\dots& \\dots &\\dots& \\dots & \\dots &\\dots\\\\\n",
"x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \\dots & \\dots &x_{n-1,n-1}\\\\\n",
"\\end{bmatrix}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and without loss of generality we rewrite again our equations as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\hat{y} = \\hat{X}\\hat{\\beta}+\\hat{\\epsilon}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The left-hand side of this equation forms know. Our error vector $\\hat{\\epsilon}$ and the parameter vector $\\hat{\\beta}$ are our unknow quantities. How can we obtain the optimal set of $\\beta_i$ values?\n",
"\n",
"\n",
"\n",
"\n",
"## Optimizing our parameters\n",
"We have defined the matrix $\\hat{X}$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{align*}\n",
"y_0&=\\beta_0x_{00}+\\beta_1x_{01}+\\beta_2x_{02}+\\dots+\\beta_{n-1}x_{0n-1}+\\epsilon_0\\\\\n",
"y_1&=\\beta_0x_{10}+\\beta_1x_{11}+\\beta_2x_{12}+\\dots+\\beta_{n-1}x_{1n-1}+\\epsilon_1\\\\\n",
"y_2&=\\beta_0x_{20}+\\beta_1x_{21}+\\beta_2x_{22}+\\dots+\\beta_{n-1}x_{2n-1}+\\epsilon_1\\\\\n",
"\\dots & \\dots \\\\\n",
"y_{i}&=\\beta_0x_{i0}+\\beta_1x_{i1}+\\beta_2x_{i2}+\\dots+\\beta_{n-1}x_{in-1}+\\epsilon_1\\\\\n",
"\\dots & \\dots \\\\\n",
"y_{n-1}&=\\beta_0x_{n-1,0}+\\beta_1x_{n-1,2}+\\beta_2x_{n-1,2}+\\dots+\\beta_1x_{n-1,n-1}+\\epsilon_{n-1}.\\\\\n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Optimizing our parameters, more details\n",
"We well use this matrix to define the approximation $\\hat{\\tilde{y}}$ via the unknown quantity $\\hat{\\beta}$ as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\hat{\\tilde{y}}= \\hat{X}\\hat{\\beta},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and in order to find the optimal parameters $\\beta_i$ instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values $y_i$ (which represent hopefully the exact values) and the parametrized values $\\tilde{y}_i$, namely"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"Q(\\hat{\\beta})=\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\left(\\hat{y}-\\hat{\\tilde{y}}\\right)^T\\left(\\hat{y}-\\hat{\\tilde{y}}\\right),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"or using the matrix $\\hat{X}$ as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"Q(\\hat{\\beta})=\\left(\\hat{y}-\\hat{X}\\hat{\\beta}\\right)^T\\left(\\hat{y}-\\hat{X}\\hat{\\beta}\\right).\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Interpretations and optimizing our parameters\n",
"The function"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"Q(\\hat{\\beta})=\\left(\\hat{y}-\\hat{X}\\hat{\\beta}\\right)^T\\left(\\hat{y}-\\hat{X}\\hat{\\beta}\\right),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value of for example a numerical experiment. When linking below with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"y_{i}=\\langle y_i \\rangle = \\beta_0x_{i,0}+\\beta_1x_{i,1}+\\beta_2x_{i,2}+\\dots+\\beta_{n-1}x_{i,n-1}+\\epsilon_i,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $\\langle y_i \\rangle$ is the mean value. Keep in mind also that till now we have treated $y_i$ as the exact value. 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",
"\n",
"In order to find the parameters $\\beta_i$ we will then minimize the spread of $Q(\\hat{\\beta})$ by requiring"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\frac{\\partial Q(\\hat{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\sum_{i=0}^{n-1}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)^2\\right]=0,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which results in"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\frac{\\partial Q(\\hat{\\beta})}{\\partial \\beta_j} = -2\\left[ \\sum_{i=0}^{n-1}x_{ij}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)\\right]=0,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"or in a matrix-vector form as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\frac{\\partial Q(\\hat{\\beta})}{\\partial \\hat{\\beta}} = 0 = \\hat{X}^T\\left( \\hat{y}-\\hat{X}\\hat{\\beta}\\right).\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Interpretations and optimizing our parameters\n",
"We can rewrite"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\frac{\\partial Q(\\hat{\\beta})}{\\partial \\hat{\\beta}} = 0 = \\hat{X}^T\\left( \\hat{y}-\\hat{X}\\hat{\\beta}\\right),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\hat{X}^T\\hat{y} = \\hat{X}^T\\hat{X}\\hat{\\beta},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and if the matrix $\\hat{X}^T\\hat{X}$ is invertible we have the solution"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\hat{\\beta} =\\left(\\hat{X}^T\\hat{X}\\right)^{-1}\\hat{X}^T\\hat{y}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Interpretations and optimizing our parameters\n",
"The residuals $\\hat{\\epsilon}$ are in turn given by"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\hat{\\epsilon} = \\hat{y}-\\hat{\\tilde{y}} = \\hat{y}-\\hat{X}\\hat{\\beta},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and with"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\hat{X}^T\\left( \\hat{y}-\\hat{X}\\hat{\\beta}\\right)= 0,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"we have"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\hat{X}^T\\hat{\\epsilon}=\\hat{X}^T\\left( \\hat{y}-\\hat{X}\\hat{\\beta}\\right)= 0,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"meaning that the solution for $\\hat{\\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.\n",
"\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",
"\n",
"Introducing the standard deviation $\\sigma_i$ for each measurement $y_i$, we define now the $\\chi^2$ function as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\chi^2(\\hat{\\beta})=\\sum_{i=0}^{n-1}\\frac{\\left(y_i-\\tilde{y}_i\\right)^2}{\\sigma_i^2}=\\left(\\hat{y}-\\hat{\\tilde{y}}\\right)^T\\frac{1}{\\hat{\\Sigma^2}}\\left(\\hat{y}-\\hat{\\tilde{y}}\\right),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where the matrix $\\hat{\\Sigma}$ is a diagonal matrix with $\\sigma_i$ as matrix elements.\n",
"\n",
"\n",
"\n",
"## The $\\chi^2$ function\n",
"\n",
"In order to find the parameters $\\beta_i$ we will then minimize the spread of $\\chi^2(\\hat{\\beta})$ by requiring"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\sum_{i=0}^{n-1}\\left(\\frac{y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}}{\\sigma_i}\\right)^2\\right]=0,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which results in"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\beta_j} = -2\\left[ \\sum_{i=0}^{n-1}\\frac{x_{ij}}{\\sigma_i}\\left(\\frac{y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}}{\\sigma_i}\\right)\\right]=0,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"or in a matrix-vector form as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\hat{\\beta}} = 0 = \\hat{A}^T\\left( \\hat{b}-\\hat{A}\\hat{\\beta}\\right).\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where we have defined the matrix $\\hat{A} =\\hat{X}/\\hat{\\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\\sigma_i$ and the vector $\\hat{b}$ with elements $b_i = y_i/\\sigma_i$.\n",
"\n",
"\n",
"\n",
"## The $\\chi^2$ function\n",
"\n",
"We can rewrite"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\hat{\\beta}} = 0 = \\hat{A}^T\\left( \\hat{b}-\\hat{A}\\hat{\\beta}\\right),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\hat{A}^T\\hat{b} = \\hat{A}^T\\hat{A}\\hat{\\beta},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and if the matrix $\\hat{A}^T\\hat{A}$ is invertible we have the solution"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\hat{\\beta} =\\left(\\hat{A}^T\\hat{A}\\right)^{-1}\\hat{A}^T\\hat{b}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The $\\chi^2$ function\n",
"\n",
"If we then introduce the matrix"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\hat{H} = \\left(\\hat{A}^T\\hat{A}\\right)^{-1},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"we have then the following expression for the parameters $\\beta_j$ (the matrix elements of $\\hat{H}$ are $h_{ij}$)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\beta_j = \\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}\\frac{y_i}{\\sigma_i}\\frac{x_{ik}}{\\sigma_i} = \\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}b_ia_{ik}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We state without proof the expression for the uncertainty in the parameters $\\beta_j$ as (we leave this as an exercise)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\sigma^2(\\beta_j) = \\sum_{i=0}^{n-1}\\sigma_i^2\\left( \\frac{\\partial \\beta_j}{\\partial y_i}\\right)^2,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"resulting in"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\sigma^2(\\beta_j) = \\left(\\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}a_{ik}\\right)\\left(\\sum_{l=0}^{p-1}h_{jl}\\sum_{m=0}^{n-1}a_{ml}\\right) = h_{jj}!\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The $\\chi^2$ function\n",
"The first step here is to approximate the function $y$ with a first-order polynomial, that is we write"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"y=y(x) \\rightarrow y(x_i) \\approx \\beta_0+\\beta_1 x_i.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"By computing the derivatives of $\\chi^2$ with respect to $\\beta_0$ and $\\beta_1$ show that these are given by"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\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",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\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",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The $\\chi^2$ function\n",
"\n",
"For a linear fit we don't need to invert a matrix!! \n",
"Defining"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\gamma = \\sum_{i=0}^{n-1}\\frac{1}{\\sigma_i^2},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"4\n",
"0\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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"4\n",
"1\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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"4\n",
"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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\gamma_{xy} = \\sum_{i=0}^{n-1}\\frac{y_ix_{i}}{\\sigma_i^2},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"we obtain"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"4\n",
"4\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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\beta_1 = \\frac{\\gamma_{xy}\\gamma-\\gamma_x\\gamma_y}{\\gamma\\gamma_{xx}-\\gamma_x^2}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This approach (different linear and non-linear regression) 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. \n",
"Add description of the various python commands."
]
},
{
"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": [
"Using **R**, we can perform similar studies. \n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## Polynomial Regression"
]
},
{
"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",
"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": [
"<!-- !split -->\n",
"## Linking the regression analysis with a statistical interpretation\n",
"\n",
"Before we proceed, and to link with our discussions of Bayesian statistics to come, it is useful the derive the standard regression analysis equations using a statistical interpretation. This allows us also to derive quantities like the variance and other expectation values in a rather straightforward way. \n",
"\n",
"It is assumed that $\\varepsilon_i\n",
"\\sim \\mathcal{N}(0, \\sigma^2)$ and the $\\varepsilon_{i}$ are\n",
"independent, i.e.:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{align*} \n",
"\\mbox{Cov}(\\varepsilon_{i_1},\n",
"\\varepsilon_{i_2}) & = \\left\\{ \\begin{array}{lcc} \\sigma^2 & \\mbox{if}\n",
"& i_1 = i_2, \\\\ 0 & \\mbox{if} & i_1 \\not= i_2. \\end{array} \\right.\n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The randomness of $\\varepsilon_i$ implies that\n",
"$\\mathbf{Y}_i$ is also a random variable. In particular,\n",
"$\\mathbf{Y}_i$ is normally distributed, because $\\varepsilon_i \\sim\n",
"\\mathcal{N}(0, \\sigma^2)$ and $\\mathbf{X}_{i,\\ast} \\, \\beta$ is a\n",
"non-random scalar. To specify the parameters of the distribution of\n",
"$\\mathbf{Y}_i$ we need to calculate its first two moments. \n",
"\n",
"## Expectation value and variance\n",
"\n",
"Its expectation equals:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{align*} \n",
"\\mathbb{E}(Y_i) & =\n",
"\\mathbb{E}(\\mathbf{X}_{i, \\ast} \\, \\beta) + \\mathbb{E}(\\varepsilon_i)\n",
"\\, \\, \\, = \\, \\, \\, \\mathbf{X}_{i, \\ast} \\, \\beta, \n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"while\n",
"its variance is"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{align*} \\mbox{Var}(Y_i) & = \\mathbb{E} \\{ [Y_i\n",
"- \\mathbb{E}(Y_i)]^2 \\} \\, \\, \\, = \\, \\, \\, \\mathbb{E} ( Y_i^2 ) -\n",
"[\\mathbb{E}(Y_i)]^2 \\\\ & = \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\,\n",
"\\beta + \\varepsilon_i )^2] - ( \\mathbf{X}_{i, \\ast} \\, \\beta)^2 \\\\ &\n",
"= \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\, \\beta)^2 + 2 \\varepsilon_i\n",
"\\mathbf{X}_{i, \\ast} \\, \\beta + \\varepsilon_i^2 ] - ( \\mathbf{X}_{i,\n",
"\\ast} \\, \\beta)^2 \\\\ & = ( \\mathbf{X}_{i, \\ast} \\, \\beta)^2 + 2\n",
"\\mathbb{E}(\\varepsilon_i) \\mathbf{X}_{i, \\ast} \\, \\beta +\n",
"\\mathbb{E}(\\varepsilon_i^2 ) - ( \\mathbf{X}_{i, \\ast} \\, \\beta)^2 \n",
"\\\\ & = \\mathbb{E}(\\varepsilon_i^2 ) \\, \\, \\, = \\, \\, \\,\n",
"\\mbox{Var}(\\varepsilon_i) \\, \\, \\, = \\, \\, \\, \\sigma^2. \n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Hence, $Y_i \\sim \\mathcal{N}( \\mathbf{X}_{i, \\ast} \\, \\beta, \\sigma^2)$. \n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## The singular value decompostion\n",
"\n",
"\n",
"A general\n",
"$m\\times n$ matrix $\\hat{A}$ can be written in terms of a diagonal\n",
"matrix $\\hat{D}$ of dimensionality $n\\times n$ and two orthognal\n",
"matrices $\\hat{U}$ and $\\hat{V}$, where the first has dimensionality\n",
"$m \\times m$ and the last dimensionality $n\\times n$. \n",
"We have then"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\hat{A} = \\hat{U}\\hat{D}\\hat{V}^T\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code examples for Ridge and Lasso Regression"
]
},
{
"cell_type": "code",
"execution_count": 9,
"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": [
"## From standard regression to Ridge regressions\n",
"\n",
"One of the typical problems we encounter with linear regression, in particular \n",
"when the matrix $\\hat{X}$ (our so-called design matrix) is high-dimensional, \n",
"are problems with near singular or singular matrices. The column vectors of $\\hat{X}$ \n",
"may be linearly dependent, normally referred to as super-collinearity. \n",
"This means that the matrix may be rank deficient and it is basically impossible to \n",
"to model the data using linear regression. As an example, consider the matrix"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{align*}\n",
"\\mathbf{X} & = \\left[\n",
"\\begin{array}{rrr}\n",
"1 & -1 & 2\n",
"\\\\\n",
"1 & 0 & 1\n",
"\\\\\n",
"1 & 2 & -1\n",
"\\\\\n",
"1 & 1 & 0\n",
"\\end{array} \\right]\n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The columns of $\\hat{X}$ are linearly dependent. We se this easily since the \n",
"the first column is the row-wise sum of the other two columns. The rank (more correct,\n",
"the column rank) of a matrix is the dimension of the space spanned by the\n",
"column vectors. Hence, the rank of $\\mathbf{X}$ is equal to the number\n",
"of linearly independent columns. In this particular case the matrix has rank 2.\n",
"\n",
"Super-collinearity of an $(n \\times p)$-dimensional design matrix $\\mathbf{X}$ implies\n",
"that the inverse of the matrix $\\hat{X}^T\\hat{x}$ (the matrix we needto invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{align*}\n",
"\\hat{X} & = \\left[\n",
"\\begin{array}{rr}\n",
"1 & -1\n",
"\\\\\n",
"1 & -1\n",
"\\end{array} \\right].\n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We see easily that $\\mbox{det}(\\hat{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \\times (-1) - 1 \\times (-1) = 0$. Hence, $\\mathbf{X}$ is singular and its inverse is undefined.\n",
"This is equivalent to saying that the matrix $\\hat{X}$ has at least an eigenvalue which is zero.\n",
"\n",
"## Fixing the singularity\n",
"\n",
"If our design matrix $\\hat{X}$ which enters the linear regression problem"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"_auto1\"></div>\n",
"\n",
"$$\n",
"\\begin{equation}\n",
"\\hat{\\beta} = (\\hat{X}^{T} \\hat{X})^{-1} \\hat{X}^{T} \\hat{y},\n",
"\\label{_auto1} \\tag{1}\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"has linearly dependent column vectors, we will not be able to compute the inverse\n",
"of $\\hat{X}^T\\hat{X}$ and we cannot find the parameters (estimators) $\\beta_i$. \n",
"The estimators are only well-defined if $(\\hat{X}^{T}\\hat{X})^{-1}$ exits. \n",
"This is more likely to happen when the matrix $\\hat{X}$ is high-dimensional. In this case it is likely to encounter a situation where \n",
"the regression parameters $\\beta_i$ cannot be estimated.\n",
"\n",
"The *ad hoc* approach which was introduced in the 70s was simply to add a diagonal component to the matrix to invert, that is we change"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\hat{X}^{T} \\hat{X} \\rightarrow \\hat{X}^{T} \\hat{X}+\\lambda \\hat{I},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $\\hat{I}$ is the identity matrix.\n",
"\n",
"\n",
"\n",
"## A second-order polynomial with Ridge and Lasso"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from sklearn.linear_model import Ridge\n",
"from sklearn.metrics import r2_score\n",
"\n",
"np.random.seed(4155)\n",
"\n",
"n_samples = 100\n",
"\n",
"x = np.random.rand(n_samples,1)\n",
"y = 5*x*x + 0.1*np.random.rand(n_samples,1)\n",
"\n",
"# Centering x and y.\n",
"x_ = x - np.mean(x)\n",
"y_ = y - np.mean(y) # beta_0 = mean(y)\n",
"\n",
"X = np.c_[np.ones((n_samples,1)), x, x**2]\n",
"X_ = np.c_[x_, x_**2]\n",
"\n",
"\n",
"### 1.\n",
"lmb_values = [1e-4, 1e-3, 1e-2, 10, 1e2, 1e4]\n",
"num_values = len(lmb_values)\n",
"\n",
"## Ridge-regression of centered and not centered data\n",
"beta_ridge = np.zeros((3,num_values))\n",
"beta_ridge_centered = np.zeros((3,num_values))\n",
"\n",
"I3 = np.eye(3)\n",
"I2 = np.eye(2)\n",
"\n",
"for i,lmb in enumerate(lmb_values):\n",
" beta_ridge[:,i] = (np.linalg.inv( X.T @ X + lmb*I3) @ X.T @ y).flatten()\n",
" beta_ridge_centered[1:,i] = (np.linalg.inv( X_.T @ X_ + lmb*I2) @ X_.T @ y_).flatten()\n",
"\n",
"# sett beta_0 = np.mean(y)\n",
"beta_ridge_centered[0,:] = np.mean(y)\n",
"\n",
"## OLS (ordinary least squares) solution \n",
"beta_ls = np.linalg.inv( X.T @ X ) @ X.T @ y\n",
"\n",
"## Evaluate the models\n",
"pred_ls = X @ beta_ls\n",
"pred_ridge = X @ beta_ridge\n",
"pred_ridge_centered = X_ @ beta_ridge_centered[1:] + beta_ridge_centered[0,:]\n",
"\n",
"## Plot the results\n",
"\n",
"# Sorting\n",
"sort_ind = np.argsort(x[:,0])\n",
"\n",
"x_plot = x[sort_ind,0]\n",
"x_centered_plot = x_[sort_ind,0]\n",
"\n",
"pred_ls_plot = pred_ls[sort_ind,0]\n",
"pred_ridge_plot = pred_ridge[sort_ind,:]\n",
"pred_ridge_centered_plot = pred_ridge_centered[sort_ind,:]\n",
"\n",
"# Plott not centered\n",
"plt.plot(x_plot,pred_ls_plot,label='ls')\n",
"\n",
"for i in range(num_values):\n",
" plt.plot(x_plot,pred_ridge_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])\n",
"\n",
"plt.plot(x,y,'ro')\n",
"\n",
"plt.title('linear regression on un-centered data')\n",
"plt.legend()\n",
"\n",
"# Plott centered\n",
"plt.figure()\n",
"\n",
"for i in range(num_values):\n",
" plt.plot(x_centered_plot,pred_ridge_centered_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])\n",
"\n",
"plt.plot(x_,y,'ro')\n",
"\n",
"plt.title('linear regression on centered data')\n",
"plt.legend()\n",
"\n",
"\n",
"# 2.\n",
"\n",
"pred_ridge_scikit = np.zeros((n_samples,num_values))\n",
"for i,lmb in enumerate(lmb_values):\n",
" pred_ridge_scikit[:,i] = (Ridge(alpha=lmb,fit_intercept=False).fit(X,y).predict(X)).flatten() # fit_intercept=False fordi bias er allerede i X\n",
"\n",
"plt.figure()\n",
"\n",
"plt.plot(x_plot,pred_ls_plot,label='ls')\n",
"\n",
"for i in range(num_values):\n",
" plt.plot(x_plot,pred_ridge_scikit[sort_ind,i],label='scikit-ridge, lmb=%g'%lmb_values[i])\n",
"\n",
"plt.plot(x,y,'ro')\n",
"plt.legend()\n",
"plt.title('linear regression using scikit')\n",
"\n",
"plt.show()\n",
"\n",
"### R2-score of the results\n",
"for i in range(num_values):\n",
" print('lambda = %g'%lmb_values[i])\n",
" print('r2 for scikit: %g'%r2_score(y,pred_ridge_scikit[:,i]))\n",
" print('r2 for own code, not centered: %g'%r2_score(y,pred_ridge[:,i]))\n",
" print('r2 for own, centered: %g\\n'%r2_score(y,pred_ridge_centered[:,i]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Fitting vs. predicting when data is in the model class\n",
"\n",
"We start by considering the case\n",
"$f(x)=2x$.\n",
"\n",
"Then the data is clearly generated by a model that is contained within\n",
"all three model classes we are using to make predictions (linear\n",
"models, third order polynomials, and tenth order polynomials).\n",
"\n",
"Run the code for the following cases:\n",
"\n",
"1. For $f(x)=2x$ , $Ntrain=10$ and $\\sigma =0$ (noiseless case), train the three classes of models (linear, third-order polynomial, and tenth order polynomial) for a training set when $x \\in [0,1]$ . Make graphs comparing fits for different order of polynomials. Which model fits the data the best?\n",
"\n",
"2. Do you think that the data that has the least error on the training set will also make the best predictions? Why or why not? Can you try to discuss and formalize your intuition? What can go right and what can go wrong?\n",
"\n",
"3. Check your answer by seeing how well your fits predict newly generated test data (including on data outside the range you fit on, for example $x \\in [0,1.2]$ ) using the code below. How well do you do on points in the range of x where you trained the model? How about points outside the original training data set?\n",
"\n",
"4. Repeat the above for $f(x)=2x$ , $Ntrain=10$ , and $\\sigma=1$ . What changes?\n",
"\n",
"Repeat the exercises above for $f(x)=2x$ , $Ntrain=100$ , and $\\sigma=1$ . What changes?\n",
"Summarize what you have learned about the relationship between model complexity (number of parameters), goodness of fit on training data, and the ability to predict well.\n",
"\n",
"\n",
"## Fitting versus predicting when data is not in the model class\n",
"\n",
"Thus far, we have considered the case where the data is generated using a model contained in the model class. Now consider $f(x)=2x-10x^5+15x^{10}$ . Notice that the for linear and third-order polynomial the true model $f(x)$ is not contained in model class.\n",
"\n",
"1. Do better fits lead to better predictions?\n",
"\n",
"2. What is the relationship between the true model for generating the data and the model class that has the most predictive power? How is this related to the model complexity? How does this depend on the number of data points $Ntrain$ and $\\sigma$?\n",
"\n",
"Summarize what you think you learned about the relationship of knowing the true model class and predictive power.\n",
"\n",
"## The code"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"import sklearn as sk\n",
"from sklearn import datasets, linear_model\n",
"from sklearn.preprocessing import PolynomialFeatures\n",
"\n",
"import matplotlib as mpl\n",
"from matplotlib import pyplot as plt\n",
"\n",
"%matplotlib notebook\n",
"\n",
"# The Training Data\n",
"\n",
"N_train=100\n",
"\n",
"sigma_train=1;\n",
"\n",
"# Train on integers\n",
"x=np.linspace(0.05,0.95,N_train)\n",
"# Draw random noise\n",
"s = sigma_train*np.random.randn(N_train)\n",
"\n",
"#linear\n",
"y=2*x+s\n",
"\n",
"#Tenth Order\n",
"#y=2*x-10*x**5+15*x**10+s\n",
"\n",
"p1=plt.plot(x,y, \"o\",ms=15, label='Training')\n",
"\n",
"#Linear Regression\n",
"# Create linear regression object\n",
"clf = linear_model.LinearRegression()\n",
"\n",
"# Train the model using the training sets\n",
"clf.fit(x[:, np.newaxis], y)\n",
"# The coefficients\n",
"\n",
"xplot=np.linspace(0.02,0.98,200)\n",
"linear_plot=plt.plot(xplot, clf.predict(xplot[:, np.newaxis]),label='Linear')\n",
"\n",
"#Polynomial Regression\n",
"\n",
"\n",
"poly3 = PolynomialFeatures(degree=3)\n",
"X = poly3.fit_transform(x[:,np.newaxis])\n",
"clf3 = linear_model.LinearRegression()\n",
"clf3.fit(X,y)\n",
"\n",
"\n",
"Xplot=poly3.fit_transform(xplot[:,np.newaxis])\n",
"poly3_plot=plt.plot(xplot, clf3.predict(Xplot), label='Poly 3')\n",
"\n",
"\n",
"\n",
"#poly5 = PolynomialFeatures(degree=5)\n",
"#X = poly5.fit_transform(x[:,np.newaxis])\n",
"#clf5 = linear_model.LinearRegression()\n",
"#clf5.fit(X,y)\n",
"\n",
"#Xplot=poly5.fit_transform(xplot[:,np.newaxis])\n",
"#plt.plot(xplot, clf5.predict(Xplot), 'r--',linewidth=1)\n",
"\n",
"poly10 = PolynomialFeatures(degree=10)\n",
"X = poly10.fit_transform(x[:,np.newaxis])\n",
"clf10 = linear_model.LinearRegression()\n",
"clf10.fit(X,y)\n",
"\n",
"Xplot=poly10.fit_transform(xplot[:,np.newaxis])\n",
"poly10_plot=plt.plot(xplot, clf10.predict(Xplot), label='Poly 10')\n",
"\n",
"axes = plt.gca()\n",
"axes.set_ylim([-7,7])\n",
"\n",
"handles, labels=axes.get_legend_handles_labels()\n",
"plt.legend(handles,labels, loc='lower center')\n",
"plt.xlabel(\"$x$\")\n",
"plt.ylabel(\"$y$\")\n",
"Title=\"$N=$\"+str(N_train)+\", $\\sigma=$\"+str(sigma_train)\n",
"plt.title(Title+\" (train)\")\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- !split -->\n",
"## Generating test data"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Generate Test Data\n",
"\n",
"#Number of test data\n",
"N_test=20\n",
"\n",
"sigma_test=sigma_train\n",
"\n",
"max_x=1.2\n",
"x_test=max_x*np.random.random(N_test)\n",
"# Draw random noise\n",
"s_test = sigma_test*np.random.randn(N_test)\n",
"\n",
"#Linear\n",
"y_test=2*x_test+s_test\n",
"#Tenth order\n",
"#y_test=2*x_test-10*x_test**5+15*x_test**10+s_test\n",
"\n",
"#Make design matrices for prediction\n",
"x_plot=np.linspace(0,max_x, 200)\n",
"X3 = poly3.fit_transform(x_plot[:,np.newaxis])\n",
"X10 = poly10.fit_transform(x_plot[:,np.newaxis])\n",
"\n",
"%matplotlib notebook\n",
"\n",
"fig = plt.figure() \n",
"p1=plt.plot(x_test,y_test.transpose(), 'o', ms=12, label='data')\n",
"p2=plt.plot(x_plot,clf.predict(x_plot[:,np.newaxis]), label='linear')\n",
"p3=plt.plot(x_plot,clf3.predict(X3), label='3rd order')\n",
"p10=plt.plot(x_plot,clf10.predict(X10), label='10th order')\n",
"\n",
"\n",
"plt.legend(loc=2)\n",
"plt.xlabel('$x$')\n",
"plt.ylabel('$y$')\n",
"plt.legend(loc='best')\n",
"plt.title(Title+\" (pred.)\")\n",
"plt.tight_layout()\n",
"plt.show()\n",
"\n",
"#Linear Filename\n",
"#filename_test=Title+\"pred-linear.pdf\"\n",
"#Tenth Order Filename\n",
"#filename_test=Title+\"pred-o10.pdf\"\n",
"#plt.savefig(filename_test)\n",
"#plt.ylim((-6,12))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Lasso regression\n",
"\n",
"\n",
"## Logistic regression"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}