2098 lines
66 KiB
Plaintext
2098 lines
66 KiB
Plaintext
{
|
||
"cells": [
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- dom:TITLE: Week 35: Linear Regression and Review of Statistical Analysis and Probability Theory -->\n",
|
||
"# Week 35: Linear Regression and Review of Statistical Analysis and Probability Theory\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 16, 2020**\n",
|
||
"\n",
|
||
"Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Plans for week 35, August 24-28\n",
|
||
"\n",
|
||
"* Thursday: Introduction to ordinary Least Squares and derivation of basic equation\n",
|
||
"\n",
|
||
"* Friday: Linear regression and statistical analysis and probability theory\n",
|
||
"\n",
|
||
"## Thursday August 27\n",
|
||
"\n",
|
||
"[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureAug27.mp4?vrtx=view-as-webpage).\n",
|
||
"\n",
|
||
"\n",
|
||
"## Why Linear Regression (aka Ordinary Least Squares and family)\n",
|
||
"\n",
|
||
"Fitting a continuous function with linear parameterization in terms of the parameters $\\boldsymbol{\\beta}$.\n",
|
||
"* Method of choice for fitting a continuous function!\n",
|
||
"\n",
|
||
"* Gives an excellent introduction to central Machine Learning features with **understandable pedagogical** links to other methods like **Neural Networks**, **Support Vector Machines** etc\n",
|
||
"\n",
|
||
"* Analytical expression for the fitting parameters $\\boldsymbol{\\beta}$\n",
|
||
"\n",
|
||
"* Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more\n",
|
||
"\n",
|
||
"* Analytical relation with probabilistic interpretations \n",
|
||
"\n",
|
||
"* Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics\n",
|
||
"\n",
|
||
"* Easy to code! And links well with classification problems and logistic regression and neural networks\n",
|
||
"\n",
|
||
"* Allows for **easy** hands-on understanding of gradient descent methods\n",
|
||
"\n",
|
||
"* and many more features\n",
|
||
"\n",
|
||
"For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n",
|
||
"Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\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$ and how it varies as function of another variable or a set of such variables $\\boldsymbol{x} =[x_0, x_1,\\dots, x_{n-1}]^T$. \n",
|
||
"The first variable is called the **dependent**, the **outcome** or the **response** variable while the set of variables $\\boldsymbol{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(\\boldsymbol{y}\\vert \\boldsymbol{x})$, that is the conditional distribution for $\\boldsymbol{y}$ with a given $\\boldsymbol{x}$. The estimation of $p(\\boldsymbol{y}\\vert \\boldsymbol{x})$ is made using a data set with \n",
|
||
"* $n$ cases $i = 0, 1, 2, \\dots, n-1$ \n",
|
||
"\n",
|
||
"* Response (target, dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \\dots, n-1$ \n",
|
||
"\n",
|
||
"* $p$ so-called explanatory (independent or predictor) variables $\\boldsymbol{x}_i=[x_{i0}, x_{i1}, \\dots, x_{ip-1}]$ with $i = 0, 1, 2, \\dots, n-1$ and explanatory variables running from $0$ to $p-1$. See below for more explicit examples. \n",
|
||
"\n",
|
||
" The goal of the regression analysis is to extract/exploit relationship between $\\boldsymbol{y}$ and $\\boldsymbol{x}$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.\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, for various explanatory variables $p$ are normally represented by a matrix \n",
|
||
"$\\mathbf{X}$.\n",
|
||
"\n",
|
||
"The matrix $\\mathbf{X}$ is called the *design\n",
|
||
"matrix*. Additional information of the samples is available in the\n",
|
||
"form of $\\boldsymbol{y}$ (also as above). The variable $\\boldsymbol{y}$ is\n",
|
||
"generally referred to as the *response variable*. The aim of\n",
|
||
"regression analysis is to explain $\\boldsymbol{y}$ in terms of\n",
|
||
"$\\boldsymbol{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 $\\boldsymbol{X}$ and $\\boldsymbol{y}$. This assumption gives rise to\n",
|
||
"the *linear regression model* where $\\boldsymbol{\\beta} = [\\beta_0, \\ldots,\n",
|
||
"\\beta_{p-1}]^{T}$ are the *regression parameters*. \n",
|
||
"\n",
|
||
"Linear regression gives us a set of analytical equations for the parameters $\\beta_j$.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Examples\n",
|
||
"In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\\boldsymbol{y}$,\n",
|
||
"consider the model we discussed for describing nuclear binding energies. \n",
|
||
"\n",
|
||
"There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model.\n",
|
||
"Assuming"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"we have five predictors, that is the intercept, the $A$ dependent term, the $A^{2/3}$ term and the $A^{-1/3}$ and $A^{-1}$ terms.\n",
|
||
"This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a \n",
|
||
"$p\\times n$ matrix $\\boldsymbol{X}$.\n",
|
||
"\n",
|
||
"Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the\n",
|
||
"so-called [credit card default data from Taiwan](https://www.sciencedirect.com/science/article/pii/S0957417407006719?via%3Dihub). The data set contains data on $n=30000$ credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are $24$ such predictors or attributes leading to a design matrix of dimensionality $24 \\times 30000$. This is however a classification problem and we will come back to it when we discuss Logistic Regression.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\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 $\\boldsymbol{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 $\\boldsymbol{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_j 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_{n-1}x_{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, more details\n",
|
||
"Defining the vectors"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{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",
|
||
"\\boldsymbol{\\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",
|
||
"\\boldsymbol{\\epsilon} = [\\epsilon_0,\\epsilon_1, \\epsilon_2,\\dots, \\epsilon_{n-1}]^T,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"and the design matrix"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{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",
|
||
"\\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta}+\\boldsymbol{\\epsilon}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"The above design matrix is called a [Vandermonde matrix](https://en.wikipedia.org/wiki/Vandermonde_matrix).\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Generalizing the fitting procedure as a linear algebra problem\n",
|
||
"\n",
|
||
"We are obviously not limited to the above polynomial expansions. We\n",
|
||
"could replace the various powers of $x$ with elements of Fourier\n",
|
||
"series or instead of $x_i^j$ we could have $\\cos{(j x_i)}$ or $\\sin{(j\n",
|
||
"x_i)}$, or time series or other orthogonal functions. For every set\n",
|
||
"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_{n-1}x_{n-1,n-1}+\\epsilon_{n-1}.\\\\\n",
|
||
"\\end{align*}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"**Note that we have $p=n$ here. The matrix is symmetric. This is generally not the case!**\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Generalizing the fitting procedure as a linear algebra problem\n",
|
||
"We redefine in turn the matrix $\\boldsymbol{X}$ as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{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",
|
||
"\\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta}+\\boldsymbol{\\epsilon}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"The left-hand side of this equation is kwown. Our error vector $\\boldsymbol{\\epsilon}$ and the parameter vector $\\boldsymbol{\\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 $\\boldsymbol{X}$ via the equations"
|
||
]
|
||
},
|
||
{
|
||
"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_{n-1}x_{n-1,n-1}+\\epsilon_{n-1}.\\\\\n",
|
||
"\\end{align*}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"As we noted above, we stayed with a system with the design matrix \n",
|
||
" $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$, that is we have $p=n$. For reasons to come later (algorithmic arguments) we will hereafter define \n",
|
||
"our matrix as $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors refering to the column numbers and the entries $n$ being the row elements.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Our model for the nuclear binding energies\n",
|
||
"\n",
|
||
"In our [introductory notes](https://compphysics.github.io/MachineLearning/doc/pub/How2ReadData/html/How2ReadData.html) we looked at the so-called [liquid drop model](https://en.wikipedia.org/wiki/Semi-empirical_mass_formula). Let us remind ourselves about what we did by looking at the code.\n",
|
||
"\n",
|
||
"We restate the parts of the code we are most interested in."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 1,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"%matplotlib inline\n",
|
||
"\n",
|
||
"# Common imports\n",
|
||
"import numpy as np\n",
|
||
"import pandas as pd\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from IPython.display import display\n",
|
||
"import os\n",
|
||
"\n",
|
||
"# Where to save the figures and data files\n",
|
||
"PROJECT_ROOT_DIR = \"Results\"\n",
|
||
"FIGURE_ID = \"Results/FigureFiles\"\n",
|
||
"DATA_ID = \"DataFiles/\"\n",
|
||
"\n",
|
||
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
|
||
" os.mkdir(PROJECT_ROOT_DIR)\n",
|
||
"\n",
|
||
"if not os.path.exists(FIGURE_ID):\n",
|
||
" os.makedirs(FIGURE_ID)\n",
|
||
"\n",
|
||
"if not os.path.exists(DATA_ID):\n",
|
||
" os.makedirs(DATA_ID)\n",
|
||
"\n",
|
||
"def image_path(fig_id):\n",
|
||
" return os.path.join(FIGURE_ID, fig_id)\n",
|
||
"\n",
|
||
"def data_path(dat_id):\n",
|
||
" return os.path.join(DATA_ID, dat_id)\n",
|
||
"\n",
|
||
"def save_fig(fig_id):\n",
|
||
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
|
||
"\n",
|
||
"infile = open(data_path(\"MassEval2016.dat\"),'r')\n",
|
||
"\n",
|
||
"\n",
|
||
"# Read the experimental data with Pandas\n",
|
||
"Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),\n",
|
||
" names=('N', 'Z', 'A', 'Element', 'Ebinding'),\n",
|
||
" widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),\n",
|
||
" header=39,\n",
|
||
" index_col=False)\n",
|
||
"\n",
|
||
"# Extrapolated values are indicated by '#' in place of the decimal place, so\n",
|
||
"# the Ebinding column won't be numeric. Coerce to float and drop these entries.\n",
|
||
"Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')\n",
|
||
"Masses = Masses.dropna()\n",
|
||
"# Convert from keV to MeV.\n",
|
||
"Masses['Ebinding'] /= 1000\n",
|
||
"\n",
|
||
"# Group the DataFrame by nucleon number, A.\n",
|
||
"Masses = Masses.groupby('A')\n",
|
||
"# Find the rows of the grouped DataFrame with the maximum binding energy.\n",
|
||
"Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])\n",
|
||
"A = Masses['A']\n",
|
||
"Z = Masses['Z']\n",
|
||
"N = Masses['N']\n",
|
||
"Element = Masses['Element']\n",
|
||
"Energies = Masses['Ebinding']\n",
|
||
"\n",
|
||
"# Now we set up the design matrix X\n",
|
||
"X = np.zeros((len(A),5))\n",
|
||
"X[:,0] = 1\n",
|
||
"X[:,1] = A\n",
|
||
"X[:,2] = A**(2.0/3.0)\n",
|
||
"X[:,3] = A**(-1.0/3.0)\n",
|
||
"X[:,4] = A**(-1.0)\n",
|
||
"# Then nice printout using pandas\n",
|
||
"DesignMatrix = pd.DataFrame(X)\n",
|
||
"DesignMatrix.index = A\n",
|
||
"DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']\n",
|
||
"display(DesignMatrix)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"With $\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p\\times 1}$, it means that we will hereafter write our equations for the approximation as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\beta},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"throughout these lectures. \n",
|
||
"\n",
|
||
"\n",
|
||
"## Optimizing our parameters, more details\n",
|
||
"With the above we use the design matrix to define the approximation $\\boldsymbol{\\tilde{y}}$ via the unknown quantity $\\boldsymbol{\\beta}$ as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\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 parameterized values $\\tilde{y}_i$, namely"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"C(\\boldsymbol{\\beta})=\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)\\right\\},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"or using the matrix $\\boldsymbol{X}$ and in a more compact matrix-vector notation as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"C(\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"This function is one possible way to define the so-called cost function.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"It is also common to define\n",
|
||
"the function $C$ as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"C(\\boldsymbol{\\beta})=\\frac{1}{2n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"since when taking the first derivative with respect to the unknown parameters $\\beta$, the factor of $2$ cancels out.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Interpretations and optimizing our parameters\n",
|
||
"\n",
|
||
"The function"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"C(\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\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. \n",
|
||
"When linking (see the discussion 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\n",
|
||
"till now we have treated $y_i$ as the exact value. Normally, the\n",
|
||
"response (dependent or outcome) variable $y_i$ the outcome of a\n",
|
||
"numerical experiment or another type of experiment and is thus only an\n",
|
||
"approximation to the true value. It is then always accompanied by an\n",
|
||
"error estimate, often limited to a statistical error estimate given by\n",
|
||
"the standard deviation discussed earlier. In the discussion here we\n",
|
||
"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 $C(\\boldsymbol{\\beta})$, that is we are going to solve the problem"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n",
|
||
"{\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"In practical terms it means we will require"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\frac{1}{n}\\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 C(\\boldsymbol{\\beta})}{\\partial \\beta_j} = -\\frac{2}{n}\\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 C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\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 C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right),\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{X}^T\\boldsymbol{y} = \\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"and if the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ is invertible we have the solution"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{\\beta} =\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"We note also that since our design matrix is defined as $\\boldsymbol{X}\\in\n",
|
||
"{\\mathbb{R}}^{n\\times p}$, the product $\\boldsymbol{X}^T\\boldsymbol{X} \\in\n",
|
||
"{\\mathbb{R}}^{p\\times p}$. In the above case we have that $p \\ll n$,\n",
|
||
"in our case $p=5$ meaning that we end up with inverting a small\n",
|
||
"$5\\times 5$ matrix. This is a rather common situation, in many cases we end up with low-dimensional\n",
|
||
"matrices to invert. The methods discussed here and for many other\n",
|
||
"supervised learning algorithms like classification with logistic\n",
|
||
"regression or support vector machines, exhibit dimensionalities which\n",
|
||
"allow for the usage of direct linear algebra methods such as **LU** decomposition or **Singular Value Decomposition** (SVD) for finding the inverse of the matrix\n",
|
||
"$\\boldsymbol{X}^T\\boldsymbol{X}$.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"**Small question**: Do you think the example we have at hand here (the nuclear binding energies) can lead to problems in inverting the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$? What kind of problems can we expect?\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Some useful matrix and vector expressions\n",
|
||
"\n",
|
||
"The following matrix and vector relation will be useful here and for the rest of the course. Vectors are always written as boldfaced lower case letters and \n",
|
||
"matrices as upper case boldfaced letters."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"2\n",
|
||
"6\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": [
|
||
"2\n",
|
||
"7\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": [
|
||
"2\n",
|
||
"8\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",
|
||
"\\frac{\\partial \\log{\\vert\\boldsymbol{A}\\vert}}{\\partial \\boldsymbol{A}} = (\\boldsymbol{A}^{-1})^T.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Interpretations and optimizing our parameters\n",
|
||
"The residuals $\\boldsymbol{\\epsilon}$ are in turn given by"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{\\epsilon} = \\boldsymbol{y}-\\boldsymbol{\\tilde{y}} = \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"and with"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"we have"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{X}^T\\boldsymbol{\\epsilon}=\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"meaning that the solution for $\\boldsymbol{\\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"Let us now return to our nuclear binding energies and simply code the above equations. \n",
|
||
"\n",
|
||
"## Own code for Ordinary Least Squares\n",
|
||
"\n",
|
||
"It is rather straightforward to implement the matrix inversion and obtain the parameters $\\boldsymbol{\\beta}$. After having defined the matrix $\\boldsymbol{X}$ we simply need to \n",
|
||
"write"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 2,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# matrix inversion to find beta\n",
|
||
"beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)\n",
|
||
"# and then make the prediction\n",
|
||
"ytilde = X @ beta"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"Alternatively, you can use the least squares functionality in **Numpy** as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 3,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"fit = np.linalg.lstsq(X, Energies, rcond =None)[0]\n",
|
||
"ytildenp = np.dot(fit,X.T)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"And finally we plot our fit with and compare with data"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 4,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"Masses['Eapprox'] = ytilde\n",
|
||
"# Generate a plot comparing the experimental with the fitted values values.\n",
|
||
"fig, ax = plt.subplots()\n",
|
||
"ax.set_xlabel(r'$A = N + Z$')\n",
|
||
"ax.set_ylabel(r'$E_\\mathrm{bind}\\,/\\mathrm{MeV}$')\n",
|
||
"ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,\n",
|
||
" label='Ame2016')\n",
|
||
"ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',\n",
|
||
" label='Fit')\n",
|
||
"ax.legend()\n",
|
||
"save_fig(\"Masses2016OLS\")\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Adding error analysis and training set up\n",
|
||
"\n",
|
||
"We can easily test our fit by computing the $R2$ score that we discussed in connection with the functionality of **Scikit-Learn** in the introductory slides.\n",
|
||
"Since we are not using **Scikit-Learn** here we can define our own $R2$ function as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 5,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"def R2(y_data, y_model):\n",
|
||
" return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"and we would be using it as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 6,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"print(R2(Energies,ytilde))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"We can easily add our **MSE** score as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 7,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"def MSE(y_data,y_model):\n",
|
||
" n = np.size(y_model)\n",
|
||
" return np.sum((y_data-y_model)**2)/n\n",
|
||
"\n",
|
||
"print(MSE(Energies,ytilde))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"and finally the relative error as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 8,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"def RelativeError(y_data,y_model):\n",
|
||
" return abs((y_data-y_model)/y_data)\n",
|
||
"print(RelativeError(Energies, ytilde))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## The $\\chi^2$ function\n",
|
||
"\n",
|
||
"Normally, the response (dependent or outcome) variable $y_i$ is the\n",
|
||
"outcome of a numerical experiment or another type of experiment and is\n",
|
||
"thus only an approximation to the true value. It is then always\n",
|
||
"accompanied by an error estimate, often limited to a statistical error\n",
|
||
"estimate given by the standard deviation discussed earlier. In the\n",
|
||
"discussion here we will treat $y_i$ as our exact value for the\n",
|
||
"response variable.\n",
|
||
"\n",
|
||
"Introducing the standard deviation $\\sigma_i$ for each measurement\n",
|
||
"$y_i$, we define now the $\\chi^2$ function (omitting the $1/n$ term)\n",
|
||
"as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\chi^2(\\boldsymbol{\\beta})=\\frac{1}{n}\\sum_{i=0}^{n-1}\\frac{\\left(y_i-\\tilde{y}_i\\right)^2}{\\sigma_i^2}=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)^T\\frac{1}{\\boldsymbol{\\Sigma^2}}\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)\\right\\},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"where the matrix $\\boldsymbol{\\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(\\boldsymbol{\\beta})$ by requiring"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\frac{1}{n}\\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(\\boldsymbol{\\beta})}{\\partial \\beta_j} = -\\frac{2}{n}\\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(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{A}^T\\left( \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{\\beta}\\right).\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"where we have defined the matrix $\\boldsymbol{A} =\\boldsymbol{X}/\\boldsymbol{\\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\\sigma_i$ and the vector $\\boldsymbol{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(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{A}^T\\left( \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{\\beta}\\right),\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{A}^T\\boldsymbol{b} = \\boldsymbol{A}^T\\boldsymbol{A}\\boldsymbol{\\beta},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"and if the matrix $\\boldsymbol{A}^T\\boldsymbol{A}$ is invertible we have the solution"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{\\beta} =\\left(\\boldsymbol{A}^T\\boldsymbol{A}\\right)^{-1}\\boldsymbol{A}^T\\boldsymbol{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",
|
||
"\\boldsymbol{H} = \\left(\\boldsymbol{A}^T\\boldsymbol{A}\\right)^{-1},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"we have then the following expression for the parameters $\\beta_j$ (the matrix elements of $\\boldsymbol{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(\\boldsymbol{\\beta})}{\\partial \\beta_0} = -2\\left[ \\frac{1}{n}\\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(\\boldsymbol{\\beta})}{\\partial \\beta_1} = -\\frac{2}{n}\\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 (a first-order polynomial) 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": [
|
||
"$$\n",
|
||
"\\gamma_x = \\sum_{i=0}^{n-1}\\frac{x_{i}}{\\sigma_i^2},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\gamma_y = \\sum_{i=0}^{n-1}\\left(\\frac{y_i}{\\sigma_i^2}\\right),\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\gamma_{xx} = \\sum_{i=0}^{n-1}\\frac{x_ix_{i}}{\\sigma_i^2},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"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": [
|
||
"$$\n",
|
||
"\\beta_0 = \\frac{\\gamma_{xx}\\gamma_y-\\gamma_x\\gamma_y}{\\gamma\\gamma_{xx}-\\gamma_x^2},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"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\n",
|
||
"often from both being underdetermined and overdetermined in the\n",
|
||
"unknown coefficients $\\beta_i$. A better approach is to use the\n",
|
||
"Singular Value Decomposition (SVD) method discussed below. Or using\n",
|
||
"Lasso and Ridge regression. See below.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Fitting an Equation of State for Dense Nuclear Matter\n",
|
||
"\n",
|
||
"Before we continue, let us introduce yet another example. We are going to fit the\n",
|
||
"nuclear equation of state using results from many-body calculations.\n",
|
||
"The equation of state we have made available here, as function of\n",
|
||
"density, has been derived using modern nucleon-nucleon potentials with\n",
|
||
"[the addition of three-body\n",
|
||
"forces](https://www.sciencedirect.com/science/article/pii/S0370157399001106). This\n",
|
||
"time the file is presented as a standard **csv** file.\n",
|
||
"\n",
|
||
"The beginning of the Python code here is similar to what you have seen\n",
|
||
"before, with the same initializations and declarations. We use also\n",
|
||
"**pandas** again, rather extensively in order to organize our data.\n",
|
||
"\n",
|
||
"The difference now is that we use **Scikit-Learn's** regression tools\n",
|
||
"instead of our own matrix inversion implementation. Furthermore, we\n",
|
||
"sneak in **Ridge** regression (to be discussed below) which includes a\n",
|
||
"hyperparameter $\\lambda$, also to be explained below.\n",
|
||
"\n",
|
||
"## The code"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 9,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Common imports\n",
|
||
"import os\n",
|
||
"import numpy as np\n",
|
||
"import pandas as pd\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"import sklearn.linear_model as skl\n",
|
||
"from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\n",
|
||
"\n",
|
||
"# Where to save the figures and data files\n",
|
||
"PROJECT_ROOT_DIR = \"Results\"\n",
|
||
"FIGURE_ID = \"Results/FigureFiles\"\n",
|
||
"DATA_ID = \"DataFiles/\"\n",
|
||
"\n",
|
||
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
|
||
" os.mkdir(PROJECT_ROOT_DIR)\n",
|
||
"\n",
|
||
"if not os.path.exists(FIGURE_ID):\n",
|
||
" os.makedirs(FIGURE_ID)\n",
|
||
"\n",
|
||
"if not os.path.exists(DATA_ID):\n",
|
||
" os.makedirs(DATA_ID)\n",
|
||
"\n",
|
||
"def image_path(fig_id):\n",
|
||
" return os.path.join(FIGURE_ID, fig_id)\n",
|
||
"\n",
|
||
"def data_path(dat_id):\n",
|
||
" return os.path.join(DATA_ID, dat_id)\n",
|
||
"\n",
|
||
"def save_fig(fig_id):\n",
|
||
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
|
||
"\n",
|
||
"infile = open(data_path(\"EoS.csv\"),'r')\n",
|
||
"\n",
|
||
"# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
|
||
"EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
|
||
"EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
|
||
"EoS = EoS.dropna()\n",
|
||
"Energies = EoS['Energy']\n",
|
||
"Density = EoS['Density']\n",
|
||
"# The design matrix now as function of various polytrops\n",
|
||
"X = np.zeros((len(Density),4))\n",
|
||
"X[:,3] = Density**(4.0/3.0)\n",
|
||
"X[:,2] = Density\n",
|
||
"X[:,1] = Density**(2.0/3.0)\n",
|
||
"X[:,0] = 1\n",
|
||
"\n",
|
||
"# We use now Scikit-Learn's linear regressor and ridge regressor\n",
|
||
"# OLS part\n",
|
||
"clf = skl.LinearRegression().fit(X, Energies)\n",
|
||
"ytilde = clf.predict(X)\n",
|
||
"EoS['Eols'] = ytilde\n",
|
||
"# The mean squared error \n",
|
||
"print(\"Mean squared error: %.2f\" % mean_squared_error(Energies, ytilde))\n",
|
||
"# Explained variance score: 1 is perfect prediction \n",
|
||
"print('Variance score: %.2f' % r2_score(Energies, ytilde))\n",
|
||
"# Mean absolute error \n",
|
||
"print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))\n",
|
||
"print(clf.coef_, clf.intercept_)\n",
|
||
"\n",
|
||
"# The Ridge regression with a hyperparameter lambda = 0.1\n",
|
||
"_lambda = 0.1\n",
|
||
"clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies)\n",
|
||
"yridge = clf_ridge.predict(X)\n",
|
||
"EoS['Eridge'] = yridge\n",
|
||
"# The mean squared error \n",
|
||
"print(\"Mean squared error: %.2f\" % mean_squared_error(Energies, yridge))\n",
|
||
"# Explained variance score: 1 is perfect prediction \n",
|
||
"print('Variance score: %.2f' % r2_score(Energies, yridge))\n",
|
||
"# Mean absolute error \n",
|
||
"print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))\n",
|
||
"print(clf_ridge.coef_, clf_ridge.intercept_)\n",
|
||
"\n",
|
||
"fig, ax = plt.subplots()\n",
|
||
"ax.set_xlabel(r'$\\rho[\\mathrm{fm}^{-3}]$')\n",
|
||
"ax.set_ylabel(r'Energy per particle')\n",
|
||
"ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2,\n",
|
||
" label='Theoretical data')\n",
|
||
"ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',\n",
|
||
" label='OLS')\n",
|
||
"ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g',\n",
|
||
" label='Ridge $\\lambda = 0.1$')\n",
|
||
"ax.legend()\n",
|
||
"save_fig(\"EoSfitting\")\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"The above simple polynomial in density $\\rho$ gives an excellent fit\n",
|
||
"to the data. \n",
|
||
"\n",
|
||
"We note also that there is a small deviation between the\n",
|
||
"standard OLS and the Ridge regression at higher densities. We discuss this in more detail\n",
|
||
"below.\n",
|
||
"\n",
|
||
"\n",
|
||
"## Splitting our Data in Training and Test data\n",
|
||
"\n",
|
||
"It is normal in essentially all Machine Learning studies to split the\n",
|
||
"data in a training set and a test set (sometimes also an additional\n",
|
||
"validation set). **Scikit-Learn** has an own function for this. There\n",
|
||
"is no explicit recipe for how much data should be included as training\n",
|
||
"data and say test data. An accepted rule of thumb is to use\n",
|
||
"approximately $2/3$ to $4/5$ of the data as training data. We will\n",
|
||
"postpone a discussion of this splitting to the end of these notes and\n",
|
||
"our discussion of the so-called **bias-variance** tradeoff. Here we\n",
|
||
"limit ourselves to repeat the above equation of state fitting example\n",
|
||
"but now splitting the data into a training set and a test set."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 10,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"import os\n",
|
||
"import numpy as np\n",
|
||
"import pandas as pd\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from sklearn.model_selection import train_test_split\n",
|
||
"# Where to save the figures and data files\n",
|
||
"PROJECT_ROOT_DIR = \"Results\"\n",
|
||
"FIGURE_ID = \"Results/FigureFiles\"\n",
|
||
"DATA_ID = \"DataFiles/\"\n",
|
||
"\n",
|
||
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
|
||
" os.mkdir(PROJECT_ROOT_DIR)\n",
|
||
"\n",
|
||
"if not os.path.exists(FIGURE_ID):\n",
|
||
" os.makedirs(FIGURE_ID)\n",
|
||
"\n",
|
||
"if not os.path.exists(DATA_ID):\n",
|
||
" os.makedirs(DATA_ID)\n",
|
||
"\n",
|
||
"def image_path(fig_id):\n",
|
||
" return os.path.join(FIGURE_ID, fig_id)\n",
|
||
"\n",
|
||
"def data_path(dat_id):\n",
|
||
" return os.path.join(DATA_ID, dat_id)\n",
|
||
"\n",
|
||
"def save_fig(fig_id):\n",
|
||
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
|
||
"\n",
|
||
"def R2(y_data, y_model):\n",
|
||
" return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
|
||
"def MSE(y_data,y_model):\n",
|
||
" n = np.size(y_model)\n",
|
||
" return np.sum((y_data-y_model)**2)/n\n",
|
||
"\n",
|
||
"infile = open(data_path(\"EoS.csv\"),'r')\n",
|
||
"\n",
|
||
"# Read the EoS data as csv file and organized into two arrays with density and energies\n",
|
||
"EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
|
||
"EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
|
||
"EoS = EoS.dropna()\n",
|
||
"Energies = EoS['Energy']\n",
|
||
"Density = EoS['Density']\n",
|
||
"# The design matrix now as function of various polytrops\n",
|
||
"X = np.zeros((len(Density),5))\n",
|
||
"X[:,0] = 1\n",
|
||
"X[:,1] = Density**(2.0/3.0)\n",
|
||
"X[:,2] = Density\n",
|
||
"X[:,3] = Density**(4.0/3.0)\n",
|
||
"X[:,4] = Density**(5.0/3.0)\n",
|
||
"# We split the data in test and training data\n",
|
||
"X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n",
|
||
"# matrix inversion to find beta\n",
|
||
"beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)\n",
|
||
"# and then make the prediction\n",
|
||
"ytilde = X_train @ beta\n",
|
||
"print(\"Training R2\")\n",
|
||
"print(R2(y_train,ytilde))\n",
|
||
"print(\"Training MSE\")\n",
|
||
"print(MSE(y_train,ytilde))\n",
|
||
"ypredict = X_test @ beta\n",
|
||
"print(\"Test R2\")\n",
|
||
"print(R2(y_test,ypredict))\n",
|
||
"print(\"Test MSE\")\n",
|
||
"print(MSE(y_test,ypredict))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- !split -->\n",
|
||
"## The Boston housing data example\n",
|
||
"\n",
|
||
"The Boston housing \n",
|
||
"data set was originally a part of UCI Machine Learning Repository\n",
|
||
"and has been removed now. The data set is now included in **Scikit-Learn**'s \n",
|
||
"library. There are 506 samples and 13 feature (predictor) variables\n",
|
||
"in this data set. The objective is to predict the value of prices of\n",
|
||
"the house using the features (predictors) listed here.\n",
|
||
"\n",
|
||
"The features/predictors are\n",
|
||
"1. CRIM: Per capita crime rate by town\n",
|
||
"\n",
|
||
"2. ZN: Proportion of residential land zoned for lots over 25000 square feet\n",
|
||
"\n",
|
||
"3. INDUS: Proportion of non-retail business acres per town\n",
|
||
"\n",
|
||
"4. CHAS: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)\n",
|
||
"\n",
|
||
"5. NOX: Nitric oxide concentration (parts per 10 million)\n",
|
||
"\n",
|
||
"6. RM: Average number of rooms per dwelling\n",
|
||
"\n",
|
||
"7. AGE: Proportion of owner-occupied units built prior to 1940\n",
|
||
"\n",
|
||
"8. DIS: Weighted distances to five Boston employment centers\n",
|
||
"\n",
|
||
"9. RAD: Index of accessibility to radial highways\n",
|
||
"\n",
|
||
"10. TAX: Full-value property tax rate per USD10000\n",
|
||
"\n",
|
||
"11. B: $1000(Bk - 0.63)^2$, where $Bk$ is the proportion of [people of African American descent] by town\n",
|
||
"\n",
|
||
"12. LSTAT: Percentage of lower status of the population\n",
|
||
"\n",
|
||
"13. MEDV: Median value of owner-occupied homes in USD 1000s\n",
|
||
"\n",
|
||
"## Housing data, the code\n",
|
||
"We start by importing the libraries"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 11,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"import numpy as np\n",
|
||
"import matplotlib.pyplot as plt \n",
|
||
"\n",
|
||
"import pandas as pd \n",
|
||
"import seaborn as sns"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"and load the Boston Housing DataSet from **Scikit-Learn**"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 12,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"from sklearn.datasets import load_boston\n",
|
||
"\n",
|
||
"boston_dataset = load_boston()\n",
|
||
"\n",
|
||
"# boston_dataset is a dictionary\n",
|
||
"# let's check what it contains\n",
|
||
"boston_dataset.keys()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"Then we invoke Pandas"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 13,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)\n",
|
||
"boston.head()\n",
|
||
"boston['MEDV'] = boston_dataset.target"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"and preprocess the data"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 14,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# check for missing values in all the columns\n",
|
||
"boston.isnull().sum()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"We can then visualize the data"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 15,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# set the size of the figure\n",
|
||
"sns.set(rc={'figure.figsize':(11.7,8.27)})\n",
|
||
"\n",
|
||
"# plot a histogram showing the distribution of the target values\n",
|
||
"sns.distplot(boston['MEDV'], bins=30)\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"It is now useful to look at the correlation matrix"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 16,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# compute the pair wise correlation for all columns \n",
|
||
"correlation_matrix = boston.corr().round(2)\n",
|
||
"# use the heatmap function from seaborn to plot the correlation matrix\n",
|
||
"# annot = True to print the values inside the square\n",
|
||
"sns.heatmap(data=correlation_matrix, annot=True)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"From the above coorelation plot we can see that **MEDV** is strongly correlated to **LSTAT** and **RM**. We see also that **RAD** and **TAX** are stronly correlated, but we don't include this in our features together to avoid multi-colinearity"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 17,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"plt.figure(figsize=(20, 5))\n",
|
||
"\n",
|
||
"features = ['LSTAT', 'RM']\n",
|
||
"target = boston['MEDV']\n",
|
||
"\n",
|
||
"for i, col in enumerate(features):\n",
|
||
" plt.subplot(1, len(features) , i+1)\n",
|
||
" x = boston[col]\n",
|
||
" y = target\n",
|
||
" plt.scatter(x, y, marker='o')\n",
|
||
" plt.title(col)\n",
|
||
" plt.xlabel(col)\n",
|
||
" plt.ylabel('MEDV')"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"Now we start training our model"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 18,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])\n",
|
||
"Y = boston['MEDV']"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"We split the data into training and test sets"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 19,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"from sklearn.model_selection import train_test_split\n",
|
||
"\n",
|
||
"# splits the training and test data set in 80% : 20%\n",
|
||
"# assign random_state to any value.This ensures consistency.\n",
|
||
"X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=5)\n",
|
||
"print(X_train.shape)\n",
|
||
"print(X_test.shape)\n",
|
||
"print(Y_train.shape)\n",
|
||
"print(Y_test.shape)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"Then we use the linear regression functionality from **Scikit-Learn**"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 20,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"from sklearn.linear_model import LinearRegression\n",
|
||
"from sklearn.metrics import mean_squared_error, r2_score\n",
|
||
"\n",
|
||
"lin_model = LinearRegression()\n",
|
||
"lin_model.fit(X_train, Y_train)\n",
|
||
"\n",
|
||
"# model evaluation for training set\n",
|
||
"\n",
|
||
"y_train_predict = lin_model.predict(X_train)\n",
|
||
"rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict)))\n",
|
||
"r2 = r2_score(Y_train, y_train_predict)\n",
|
||
"\n",
|
||
"print(\"The model performance for training set\")\n",
|
||
"print(\"--------------------------------------\")\n",
|
||
"print('RMSE is {}'.format(rmse))\n",
|
||
"print('R2 score is {}'.format(r2))\n",
|
||
"print(\"\\n\")\n",
|
||
"\n",
|
||
"# model evaluation for testing set\n",
|
||
"\n",
|
||
"y_test_predict = lin_model.predict(X_test)\n",
|
||
"# root mean square error of the model\n",
|
||
"rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict)))\n",
|
||
"\n",
|
||
"# r-squared score of the model\n",
|
||
"r2 = r2_score(Y_test, y_test_predict)\n",
|
||
"\n",
|
||
"print(\"The model performance for testing set\")\n",
|
||
"print(\"--------------------------------------\")\n",
|
||
"print('RMSE is {}'.format(rmse))\n",
|
||
"print('R2 score is {}'.format(r2))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 21,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# plotting the y_test vs y_pred\n",
|
||
"# ideally should have been a straight line\n",
|
||
"plt.scatter(Y_test, y_test_predict)\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Reducing the number of degrees of freedom, overarching view\n",
|
||
"\n",
|
||
"Many Machine Learning problems involve thousands or even millions of\n",
|
||
"features for each training instance. Not only does this make training\n",
|
||
"extremely slow, it can also make it much harder to find a good\n",
|
||
"solution, as we will see. This problem is often referred to as the\n",
|
||
"curse of dimensionality. Fortunately, in real-world problems, it is\n",
|
||
"often possible to reduce the number of features considerably, turning\n",
|
||
"an intractable problem into a tractable one.\n",
|
||
"\n",
|
||
"Later we will discuss some of the most popular dimensionality reduction\n",
|
||
"techniques: the principal component analysis (PCA), Kernel PCA, and\n",
|
||
"Locally Linear Embedding (LLE). \n",
|
||
"\n",
|
||
"\n",
|
||
"Principal component analysis and its various variants deal with the\n",
|
||
"problem of fitting a low-dimensional [affine\n",
|
||
"subspace](https://en.wikipedia.org/wiki/Affine_space) to a set of of\n",
|
||
"data points in a high-dimensional space. With its family of methods it\n",
|
||
"is one of the most used tools in data modeling, compression and\n",
|
||
"visualization.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Preprocessing our data\n",
|
||
"\n",
|
||
"Before we proceed however, we will discuss how to preprocess our\n",
|
||
"data. Till now and in connection with our previous examples we have\n",
|
||
"not met so many cases where we are too sensitive to the scaling of our\n",
|
||
"data. Normally the data may need a rescaling and/or may be sensitive\n",
|
||
"to extreme values. Scaling the data renders our inputs much more\n",
|
||
"suitable for the algorithms we want to employ.\n",
|
||
"\n",
|
||
"**Scikit-Learn** has several functions which allow us to rescale the\n",
|
||
"data, normally resulting in much better results in terms of various\n",
|
||
"accuracy scores. The **StandardScaler** function in **Scikit-Learn**\n",
|
||
"ensures that for each feature/predictor we study the mean value is\n",
|
||
"zero and the variance is one (every column in the design/feature\n",
|
||
"matrix). This scaling has the drawback that it does not ensure that\n",
|
||
"we have a particular maximum or minimum in our data set. Another\n",
|
||
"function included in **Scikit-Learn** is the **MinMaxScaler** which\n",
|
||
"ensures that all features are exactly between $0$ and $1$. The\n",
|
||
"\n",
|
||
"## More preprocessing\n",
|
||
"\n",
|
||
"\n",
|
||
"The **Normalizer** scales each data\n",
|
||
"point such that the feature vector has a euclidean length of one. In other words, it\n",
|
||
"projects a data point on the circle (or sphere in the case of higher dimensions) with a\n",
|
||
"radius of 1. This means every data point is scaled by a different number (by the\n",
|
||
"inverse of it’s length).\n",
|
||
"This normalization is often used when only the direction (or angle) of the data matters,\n",
|
||
"not the length of the feature vector.\n",
|
||
"\n",
|
||
"The **RobustScaler** works similarly to the StandardScaler in that it\n",
|
||
"ensures statistical properties for each feature that guarantee that\n",
|
||
"they are on the same scale. However, the RobustScaler uses the median\n",
|
||
"and quartiles, instead of mean and variance. This makes the\n",
|
||
"RobustScaler ignore data points that are very different from the rest\n",
|
||
"(like measurement errors). These odd data points are also called\n",
|
||
"outliers, and might often lead to trouble for other scaling\n",
|
||
"techniques.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"## Simple preprocessing examples, Franke function and regression"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 22,
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Common imports\n",
|
||
"import os\n",
|
||
"import numpy as np\n",
|
||
"import pandas as pd\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"import sklearn.linear_model as skl\n",
|
||
"from sklearn.metrics import mean_squared_error\n",
|
||
"from sklearn.model_selection import train_test_split\n",
|
||
"from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer\n",
|
||
"\n",
|
||
"# Where to save the figures and data files\n",
|
||
"PROJECT_ROOT_DIR = \"Results\"\n",
|
||
"FIGURE_ID = \"Results/FigureFiles\"\n",
|
||
"DATA_ID = \"DataFiles/\"\n",
|
||
"\n",
|
||
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
|
||
" os.mkdir(PROJECT_ROOT_DIR)\n",
|
||
"\n",
|
||
"if not os.path.exists(FIGURE_ID):\n",
|
||
" os.makedirs(FIGURE_ID)\n",
|
||
"\n",
|
||
"if not os.path.exists(DATA_ID):\n",
|
||
" os.makedirs(DATA_ID)\n",
|
||
"\n",
|
||
"def image_path(fig_id):\n",
|
||
" return os.path.join(FIGURE_ID, fig_id)\n",
|
||
"\n",
|
||
"def data_path(dat_id):\n",
|
||
" return os.path.join(DATA_ID, dat_id)\n",
|
||
"\n",
|
||
"def save_fig(fig_id):\n",
|
||
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
|
||
"\n",
|
||
"\n",
|
||
"def FrankeFunction(x,y):\n",
|
||
"\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
|
||
"\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
|
||
"\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
|
||
"\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
|
||
"\treturn term1 + term2 + term3 + term4\n",
|
||
"\n",
|
||
"\n",
|
||
"def create_X(x, y, n ):\n",
|
||
"\tif len(x.shape) > 1:\n",
|
||
"\t\tx = np.ravel(x)\n",
|
||
"\t\ty = np.ravel(y)\n",
|
||
"\n",
|
||
"\tN = len(x)\n",
|
||
"\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n",
|
||
"\tX = np.ones((N,l))\n",
|
||
"\n",
|
||
"\tfor i in range(1,n+1):\n",
|
||
"\t\tq = int((i)*(i+1)/2)\n",
|
||
"\t\tfor k in range(i+1):\n",
|
||
"\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n",
|
||
"\n",
|
||
"\treturn X\n",
|
||
"\n",
|
||
"\n",
|
||
"# Making meshgrid of datapoints and compute Franke's function\n",
|
||
"n = 5\n",
|
||
"N = 1000\n",
|
||
"x = np.sort(np.random.uniform(0, 1, N))\n",
|
||
"y = np.sort(np.random.uniform(0, 1, N))\n",
|
||
"z = FrankeFunction(x, y)\n",
|
||
"X = create_X(x, y, n=n) \n",
|
||
"# split in training and test data\n",
|
||
"X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=0.2)\n",
|
||
"\n",
|
||
"\n",
|
||
"clf = skl.LinearRegression().fit(X_train, y_train)\n",
|
||
"\n",
|
||
"# The mean squared error and R2 score\n",
|
||
"print(\"MSE before scaling: {:.2f}\".format(mean_squared_error(clf.predict(X_test), y_test)))\n",
|
||
"print(\"R2 score before scaling {:.2f}\".format(clf.score(X_test,y_test)))\n",
|
||
"\n",
|
||
"scaler = StandardScaler()\n",
|
||
"scaler.fit(X_train)\n",
|
||
"X_train_scaled = scaler.transform(X_train)\n",
|
||
"X_test_scaled = scaler.transform(X_test)\n",
|
||
"\n",
|
||
"print(\"Feature min values before scaling:\\n {}\".format(X_train.min(axis=0)))\n",
|
||
"print(\"Feature max values before scaling:\\n {}\".format(X_train.max(axis=0)))\n",
|
||
"\n",
|
||
"print(\"Feature min values after scaling:\\n {}\".format(X_train_scaled.min(axis=0)))\n",
|
||
"print(\"Feature max values after scaling:\\n {}\".format(X_train_scaled.max(axis=0)))\n",
|
||
"\n",
|
||
"clf = skl.LinearRegression().fit(X_train_scaled, y_train)\n",
|
||
"\n",
|
||
"\n",
|
||
"print(\"MSE after scaling: {:.2f}\".format(mean_squared_error(clf.predict(X_test_scaled), y_test)))\n",
|
||
"print(\"R2 score for scaled data: {:.2f}\".format(clf.score(X_test_scaled,y_test)))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Friday August 28\n",
|
||
"\n",
|
||
"[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureAug28.mp4?vrtx=view-as-webpage) and [handwritten notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/NotesAugust28.pdf)\n",
|
||
"\n",
|
||
"More material will be added here, see handwritten notes also."
|
||
]
|
||
}
|
||
],
|
||
"metadata": {},
|
||
"nbformat": 4,
|
||
"nbformat_minor": 2
|
||
}
|