{ "cells": [ { "cell_type": "markdown", "id": "26ae76a1", "metadata": { "editable": true }, "source": [ "\n", "" ] }, { "cell_type": "markdown", "id": "890d8431", "metadata": { "editable": true }, "source": [ "# Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression\n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", "\n", "Date: **Nov 3, 2021**\n", "\n", "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license" ] }, { "cell_type": "markdown", "id": "434881ac", "metadata": { "editable": true }, "source": [ "## Plans for week 35, August 30 -September 3\n", "\n", "* Thursday: Review of ordinary Least Squares with applications and discussion of Ridge Regression and Singular Value Decomposition\n", "\n", "* [Video of lecture Thursday](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureSeptember2.mp4?vrtx=view-as-webpage).\n", "\n", "* Friday: Analysis of Ridge and Lasso Regression and links with Singular Value Decomposition\n", "\n", "* [Video of lecture Friday](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureSeptember3.mp4?vrtx=view-as-webpage)\n", "\n", "* [Video series on the SVD](http://databookuw.com/page-2/page-4/). Highly recommended." ] }, { "cell_type": "markdown", "id": "797fbc70", "metadata": { "editable": true }, "source": [ "## Thursday September 2\n", "\n", "The main topics on Thursday are:\n", "1. Repetition from last week on linear regression\n", "\n", "2. Discussion of how to prepare data and examples of applications of linear regression\n", "\n", "3. Mathematical interpretations of Linear Regression\n", "\n", "4. Start discussing Ridge and Lasso regression and Singular Value Decomposition" ] }, { "cell_type": "markdown", "id": "a28f0549", "metadata": { "editable": true }, "source": [ "## Why Linear Regression (aka Ordinary Least Squares and family), repeat from last week\n", "\n", "We need first a reminder from last week about linear regression. \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." ] }, { "cell_type": "markdown", "id": "9f12cdfb", "metadata": { "editable": true }, "source": [ "## 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." ] }, { "cell_type": "markdown", "id": "fe22bbd9", "metadata": { "editable": true }, "source": [ "## Regression analysis, overarching aims II\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$." ] }, { "cell_type": "markdown", "id": "88accdb4", "metadata": { "editable": true }, "source": [ "## 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", "id": "9e3bb9b4", "metadata": { "editable": true }, "source": [ "$$\n", "BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1},\n", "$$" ] }, { "cell_type": "markdown", "id": "e7cf3568", "metadata": { "editable": true }, "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." ] }, { "cell_type": "markdown", "id": "28d154ab", "metadata": { "editable": true }, "source": [ "## 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", "id": "471571ac", "metadata": { "editable": true }, "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", "id": "55f3ec65", "metadata": { "editable": true }, "source": [ "where $\\epsilon_i$ is the error in our approximation." ] }, { "cell_type": "markdown", "id": "a8364a31", "metadata": { "editable": true }, "source": [ "## 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", "id": "4a97ef95", "metadata": { "editable": true }, "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", "id": "f6fa4c72", "metadata": { "editable": true }, "source": [ "## Rewriting the fitting procedure as a linear algebra problem, more details\n", "Defining the vectors" ] }, { "cell_type": "markdown", "id": "c9ca1dc8", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{y} = [y_0,y_1, y_2,\\dots, y_{n-1}]^T,\n", "$$" ] }, { "cell_type": "markdown", "id": "8b769bbc", "metadata": { "editable": true }, "source": [ "and" ] }, { "cell_type": "markdown", "id": "1bb26ed0", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{\\beta} = [\\beta_0,\\beta_1, \\beta_2,\\dots, \\beta_{n-1}]^T,\n", "$$" ] }, { "cell_type": "markdown", "id": "9dda37f7", "metadata": { "editable": true }, "source": [ "and" ] }, { "cell_type": "markdown", "id": "01376567", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{\\epsilon} = [\\epsilon_0,\\epsilon_1, \\epsilon_2,\\dots, \\epsilon_{n-1}]^T,\n", "$$" ] }, { "cell_type": "markdown", "id": "6d470e53", "metadata": { "editable": true }, "source": [ "and the design matrix" ] }, { "cell_type": "markdown", "id": "923ff5eb", "metadata": { "editable": true }, "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", "id": "15ccdf9e", "metadata": { "editable": true }, "source": [ "we can rewrite our equations as" ] }, { "cell_type": "markdown", "id": "b7d4c290", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta}+\\boldsymbol{\\epsilon}.\n", "$$" ] }, { "cell_type": "markdown", "id": "27af50a7", "metadata": { "editable": true }, "source": [ "The above design matrix is called a [Vandermonde matrix](https://en.wikipedia.org/wiki/Vandermonde_matrix)." ] }, { "cell_type": "markdown", "id": "7dd2cd83", "metadata": { "editable": true }, "source": [ "## 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", "id": "635ecdc8", "metadata": { "editable": true }, "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", "id": "24e2fd35", "metadata": { "editable": true }, "source": [ "**Note that we have $p=n$ here. The matrix is symmetric. This is generally not the case!**" ] }, { "cell_type": "markdown", "id": "480d9d03", "metadata": { "editable": true }, "source": [ "## Generalizing the fitting procedure as a linear algebra problem\n", "We redefine in turn the matrix $\\boldsymbol{X}$ as" ] }, { "cell_type": "markdown", "id": "3d9b2af3", "metadata": { "editable": true }, "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", "id": "a3ced18b", "metadata": { "editable": true }, "source": [ "and without loss of generality we rewrite again our equations as" ] }, { "cell_type": "markdown", "id": "1f72e12d", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta}+\\boldsymbol{\\epsilon}.\n", "$$" ] }, { "cell_type": "markdown", "id": "47eda213", "metadata": { "editable": true }, "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?" ] }, { "cell_type": "markdown", "id": "169cfe9d", "metadata": { "editable": true }, "source": [ "## Optimizing our parameters\n", "We have defined the matrix $\\boldsymbol{X}$ via the equations" ] }, { "cell_type": "markdown", "id": "a2180298", "metadata": { "editable": true }, "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", "id": "d515ebce", "metadata": { "editable": true }, "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." ] }, { "cell_type": "markdown", "id": "7d67b025", "metadata": { "editable": true }, "source": [ "## 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, "id": "be62aa5c", "metadata": { "collapsed": false, "editable": true }, "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", "id": "3ae8b693", "metadata": { "editable": true }, "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", "id": "bbb85729", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\beta},\n", "$$" ] }, { "cell_type": "markdown", "id": "5acf922c", "metadata": { "editable": true }, "source": [ "throughout these lectures." ] }, { "cell_type": "markdown", "id": "919a84f2", "metadata": { "editable": true }, "source": [ "## 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", "id": "1b793777", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\beta},\n", "$$" ] }, { "cell_type": "markdown", "id": "7556c68c", "metadata": { "editable": true }, "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", "id": "aa335b7c", "metadata": { "editable": true }, "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", "id": "b33853bc", "metadata": { "editable": true }, "source": [ "or using the matrix $\\boldsymbol{X}$ and in a more compact matrix-vector notation as" ] }, { "cell_type": "markdown", "id": "b6930121", "metadata": { "editable": true }, "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", "id": "6fd23574", "metadata": { "editable": true }, "source": [ "This function is one possible way to define the so-called cost function.\n", "\n", "It is also common to define\n", "the function $C$ as" ] }, { "cell_type": "markdown", "id": "e1214ba2", "metadata": { "editable": true }, "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", "id": "c51c03b5", "metadata": { "editable": true }, "source": [ "since when taking the first derivative with respect to the unknown parameters $\\beta$, the factor of $2$ cancels out." ] }, { "cell_type": "markdown", "id": "fbeeb5c1", "metadata": { "editable": true }, "source": [ "## Interpretations and optimizing our parameters\n", "\n", "The function" ] }, { "cell_type": "markdown", "id": "bbf3d893", "metadata": { "editable": true }, "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", "id": "0ed621c2", "metadata": { "editable": true }, "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", "id": "9be95ee2", "metadata": { "editable": true }, "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", "id": "234ddf49", "metadata": { "editable": true }, "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", "id": "ef177e0d", "metadata": { "editable": true }, "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", "id": "066c1c10", "metadata": { "editable": true }, "source": [ "In practical terms it means we will require" ] }, { "cell_type": "markdown", "id": "e0e0d740", "metadata": { "editable": true }, "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", "id": "623edac9", "metadata": { "editable": true }, "source": [ "which results in" ] }, { "cell_type": "markdown", "id": "787d2117", "metadata": { "editable": true }, "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", "id": "877597cf", "metadata": { "editable": true }, "source": [ "or in a matrix-vector form as" ] }, { "cell_type": "markdown", "id": "8d770e9d", "metadata": { "editable": true }, "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", "id": "b1dfe8bf", "metadata": { "editable": true }, "source": [ "## Interpretations and optimizing our parameters\n", "We can rewrite" ] }, { "cell_type": "markdown", "id": "0c3505c9", "metadata": { "editable": true }, "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", "id": "6096739c", "metadata": { "editable": true }, "source": [ "as" ] }, { "cell_type": "markdown", "id": "435f4a55", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{X}^T\\boldsymbol{y} = \\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta},\n", "$$" ] }, { "cell_type": "markdown", "id": "dbf7ae4d", "metadata": { "editable": true }, "source": [ "and if the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ is invertible we have the solution" ] }, { "cell_type": "markdown", "id": "6745642f", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{\\beta} =\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", "$$" ] }, { "cell_type": "markdown", "id": "ddda6f20", "metadata": { "editable": true }, "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", "**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?" ] }, { "cell_type": "markdown", "id": "b9cf4eae", "metadata": { "editable": true }, "source": [ "## 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", "id": "be7471e0", "metadata": { "editable": true }, "source": [ "$$\n", "\\frac{\\partial (\\boldsymbol{b}^T\\boldsymbol{a})}{\\partial \\boldsymbol{a}} = \\boldsymbol{b},\n", "$$" ] }, { "cell_type": "markdown", "id": "345c6f7c", "metadata": { "editable": true }, "source": [ "$$\n", "\\frac{\\partial (\\boldsymbol{a}^T\\boldsymbol{A}\\boldsymbol{a})}{\\partial \\boldsymbol{a}} = (\\boldsymbol{A}+\\boldsymbol{A}^T)\\boldsymbol{a},\n", "$$" ] }, { "cell_type": "markdown", "id": "9fd2aec7", "metadata": { "editable": true }, "source": [ "$$\n", "\\frac{\\partial tr(\\boldsymbol{B}\\boldsymbol{A})}{\\partial \\boldsymbol{A}} = \\boldsymbol{B}^T,\n", "$$" ] }, { "cell_type": "markdown", "id": "8f327bae", "metadata": { "editable": true }, "source": [ "$$\n", "\\frac{\\partial \\log{\\vert\\boldsymbol{A}\\vert}}{\\partial \\boldsymbol{A}} = (\\boldsymbol{A}^{-1})^T.\n", "$$" ] }, { "cell_type": "markdown", "id": "37b8427f", "metadata": { "editable": true }, "source": [ "## Meet the Hessian Matrix\n", "\n", "A very important matrix we will meet again and again in Machine\n", "Learning is the Hessian. It is given by the second derivative of the\n", "cost function with respect to the parameter $\\beta$. Using the above\n", "expression for derivatives of vectors and matrices, we find that the\n", "second derivative of the cost function is," ] }, { "cell_type": "markdown", "id": "84f05dc0", "metadata": { "editable": true }, "source": [ "$$\n", "\\frac{\\partial}{\\partial \\boldsymbol{\\beta}^T}\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} =\\frac{\\partial}{\\partial \\boldsymbol{\\beta}}\\left[-\\frac{2}{n}\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right]=\\frac{2}{n}\\boldsymbol{X}^T\\boldsymbol{X}.\n", "$$" ] }, { "cell_type": "markdown", "id": "f6b69e17", "metadata": { "editable": true }, "source": [ "The Hessian matrix plays an important role and is defined here as" ] }, { "cell_type": "markdown", "id": "5ad43036", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{H}=\\boldsymbol{X}^T\\boldsymbol{X}.\n", "$$" ] }, { "cell_type": "markdown", "id": "e0697e67", "metadata": { "editable": true }, "source": [ "For ordinary least squares, it is inversely proportional (derivation\n", "next week) with the variance of the optimal parameters\n", "$\\hat{\\boldsymbol{\\beta}}$. Furthermore, we will see later this week that is\n", "(beside $1/n$) equal to the covariance matrix. It plays also a very\n", "important role in optmization algorithms and Principal Component\n", "Analysis as a way to reduce the dimensionality of a machine learning\n", "problem.\n", "\n", "**Linear algebra question:** Can we use the Hessian matrix to say something about properties of the cost function (our optmization problem)? (hint: think about convex or concave problems and how to relate these to a matrix!)." ] }, { "cell_type": "markdown", "id": "318716a4", "metadata": { "editable": true }, "source": [ "## Interpretations and optimizing our parameters\n", "The residuals $\\boldsymbol{\\epsilon}$ are in turn given by" ] }, { "cell_type": "markdown", "id": "9bf30c19", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{\\epsilon} = \\boldsymbol{y}-\\boldsymbol{\\tilde{y}} = \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta},\n", "$$" ] }, { "cell_type": "markdown", "id": "c6505dc1", "metadata": { "editable": true }, "source": [ "and with" ] }, { "cell_type": "markdown", "id": "1271eed1", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n", "$$" ] }, { "cell_type": "markdown", "id": "d38159b8", "metadata": { "editable": true }, "source": [ "we have" ] }, { "cell_type": "markdown", "id": "d7bb1d6d", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{X}^T\\boldsymbol{\\epsilon}=\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n", "$$" ] }, { "cell_type": "markdown", "id": "b7dd96c9", "metadata": { "editable": true }, "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." ] }, { "cell_type": "markdown", "id": "4b6e485f", "metadata": { "editable": true }, "source": [ "## 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, "id": "20e8cb33", "metadata": { "collapsed": false, "editable": true }, "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", "id": "77ef22e3", "metadata": { "editable": true }, "source": [ "Alternatively, you can use the least squares functionality in **Numpy** as" ] }, { "cell_type": "code", "execution_count": 3, "id": "0c7e2e85", "metadata": { "collapsed": false, "editable": true }, "outputs": [], "source": [ "fit = np.linalg.lstsq(X, Energies, rcond =None)[0]\n", "ytildenp = np.dot(fit,X.T)" ] }, { "cell_type": "markdown", "id": "776d3539", "metadata": { "editable": true }, "source": [ "And finally we plot our fit with and compare with data" ] }, { "cell_type": "code", "execution_count": 4, "id": "fe76261f", "metadata": { "collapsed": false, "editable": true }, "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", "id": "34d28ed3", "metadata": { "editable": true }, "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, "id": "46c39015", "metadata": { "collapsed": false, "editable": true }, "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", "id": "09150482", "metadata": { "editable": true }, "source": [ "and we would be using it as" ] }, { "cell_type": "code", "execution_count": 6, "id": "c60fc160", "metadata": { "collapsed": false, "editable": true }, "outputs": [], "source": [ "print(R2(Energies,ytilde))" ] }, { "cell_type": "markdown", "id": "ea9d7abe", "metadata": { "editable": true }, "source": [ "We can easily add our **MSE** score as" ] }, { "cell_type": "code", "execution_count": 7, "id": "7399848c", "metadata": { "collapsed": false, "editable": true }, "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", "id": "0ca43616", "metadata": { "editable": true }, "source": [ "and finally the relative error as" ] }, { "cell_type": "code", "execution_count": 8, "id": "602b9969", "metadata": { "collapsed": false, "editable": true }, "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", "id": "c6c9d23d", "metadata": { "editable": true }, "source": [ "## 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": "markdown", "id": "46f46d43", "metadata": { "editable": true }, "source": [ "## Examples" ] }, { "cell_type": "code", "execution_count": 9, "id": "dd175e90", "metadata": { "collapsed": false, "editable": true }, "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", "\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", "x = np.random.rand(100)\n", "y = 2.0+5*x*x+0.1*np.random.randn(100)\n", "\n", "\n", "# The design matrix now as function of a given polynomial\n", "X = np.zeros((len(x),3))\n", "X[:,0] = 1.0\n", "X[:,1] = x\n", "X[:,2] = x**2\n", "# We split the data in test and training data\n", "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", "# matrix inversion to find beta\n", "beta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n", "print(beta)\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", "id": "1afc59cc", "metadata": { "editable": true }, "source": [ "## Making your own test-train splitting" ] }, { "cell_type": "code", "execution_count": 10, "id": "ec006afe", "metadata": { "collapsed": false, "editable": true }, "outputs": [], "source": [ "# equivalently in numpy\n", "def train_test_split_numpy(inputs, labels, train_size, test_size):\n", " n_inputs = len(inputs)\n", " inputs_shuffled = inputs.copy()\n", " labels_shuffled = labels.copy()\n", "\n", " np.random.shuffle(inputs_shuffled)\n", " np.random.shuffle(labels_shuffled)\n", "\n", " train_end = int(n_inputs*train_size)\n", " X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]\n", " Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]\n", "\n", " return X_train, X_test, Y_train, Y_test" ] }, { "cell_type": "markdown", "id": "a7ec2fdb", "metadata": { "editable": true }, "source": [ "But since **scikit-learn** has its own function for doing this and since\n", "it interfaces easily with **tensorflow** and other libraries, we\n", "normally recommend using the latter functionality." ] }, { "cell_type": "markdown", "id": "875d7248", "metadata": { "editable": true }, "source": [ "## 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" ] }, { "cell_type": "markdown", "id": "c0f8545d", "metadata": { "editable": true }, "source": [ "## Housing data, the code\n", "We start by importing the libraries" ] }, { "cell_type": "code", "execution_count": 11, "id": "81237355", "metadata": { "collapsed": false, "editable": true }, "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", "id": "f1962254", "metadata": { "editable": true }, "source": [ "and load the Boston Housing DataSet from **Scikit-Learn**" ] }, { "cell_type": "code", "execution_count": 12, "id": "dee9e300", "metadata": { "collapsed": false, "editable": true }, "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", "id": "bef0eb82", "metadata": { "editable": true }, "source": [ "Then we invoke Pandas" ] }, { "cell_type": "code", "execution_count": 13, "id": "a29ff8af", "metadata": { "collapsed": false, "editable": true }, "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", "id": "8396e85f", "metadata": { "editable": true }, "source": [ "and preprocess the data" ] }, { "cell_type": "code", "execution_count": 14, "id": "16d25b94", "metadata": { "collapsed": false, "editable": true }, "outputs": [], "source": [ "# check for missing values in all the columns\n", "boston.isnull().sum()" ] }, { "cell_type": "markdown", "id": "2e90d9ef", "metadata": { "editable": true }, "source": [ "We can then visualize the data" ] }, { "cell_type": "code", "execution_count": 15, "id": "ac2fac03", "metadata": { "collapsed": false, "editable": true }, "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", "id": "b5cdd9d1", "metadata": { "editable": true }, "source": [ "It is now useful to look at the correlation matrix" ] }, { "cell_type": "code", "execution_count": 16, "id": "37a352c6", "metadata": { "collapsed": false, "editable": true }, "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", "id": "d43fa5cd", "metadata": { "editable": true }, "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, "id": "1fc2b42e", "metadata": { "collapsed": false, "editable": true }, "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", "id": "69cafd8a", "metadata": { "editable": true }, "source": [ "Now we start training our model" ] }, { "cell_type": "code", "execution_count": 18, "id": "48a04777", "metadata": { "collapsed": false, "editable": true }, "outputs": [], "source": [ "X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])\n", "Y = boston['MEDV']" ] }, { "cell_type": "markdown", "id": "e21c7f03", "metadata": { "editable": true }, "source": [ "We split the data into training and test sets" ] }, { "cell_type": "code", "execution_count": 19, "id": "fa0eca85", "metadata": { "collapsed": false, "editable": true }, "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", "id": "598473cc", "metadata": { "editable": true }, "source": [ "Then we use the linear regression functionality from **Scikit-Learn**" ] }, { "cell_type": "code", "execution_count": 20, "id": "adc72931", "metadata": { "collapsed": false, "editable": true }, "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, "id": "5bf0e806", "metadata": { "collapsed": false, "editable": true }, "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", "id": "115406d0", "metadata": { "editable": true }, "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", "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." ] }, { "cell_type": "markdown", "id": "98df56e6", "metadata": { "editable": true }, "source": [ "## 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", "For data sets gathered for real world applications, it is rather normal that\n", "different features have very different units and\n", "numerical scales. For example, a data set detailing health habits may include\n", "features such as **age** in the range $0-80$, and **caloric intake** of order $2000$.\n", "Many machine learning methods sensitive to the scales of the features and may perform poorly if they\n", "are very different scales. Therefore, it is typical to scale\n", "the features in a way to avoid such outlier values." ] }, { "cell_type": "markdown", "id": "1de59215", "metadata": { "editable": true }, "source": [ "## Functionality in Scikit-Learn\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" ] }, { "cell_type": "markdown", "id": "e1c1b7ee", "metadata": { "editable": true }, "source": [ "## More preprocessing\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." ] }, { "cell_type": "markdown", "id": "a35f95ed", "metadata": { "editable": true }, "source": [ "## Frequently used scaling functions\n", "\n", "Many features are often scaled using standardization to improve performance. In **Scikit-Learn** this is given by the **StandardScaler** function as discussed above. It is easy however to write your own. \n", "Mathematically, this involves subtracting the mean and divide by the standard deviation over the data set, for each feature:" ] }, { "cell_type": "markdown", "id": "804df448", "metadata": { "editable": true }, "source": [ "$$\n", "x_j^{(i)} \\rightarrow \\frac{x_j^{(i)} - \\overline{x}_j}{\\sigma(x_j)},\n", "$$" ] }, { "cell_type": "markdown", "id": "8495ae4c", "metadata": { "editable": true }, "source": [ "where $\\overline{x}_j$ and $\\sigma(x_j)$ are the mean and standard deviation, respectively, of the feature $x_j$.\n", "This ensures that each feature has zero mean and unit standard deviation. For data sets where we do not have the standard deviation or don't wish to calculate it, it is then common to simply set it to one." ] }, { "cell_type": "markdown", "id": "9ebd107f", "metadata": { "editable": true }, "source": [ "## Example of own Standard scaling\n", "\n", "Let us consider the following vanilla example where we use both\n", "**Scikit-Learn** and write our own function as well. We produce a\n", "simple test design matrix with random numbers. Each column could then\n", "represent a specific feature whose mean value is subracted." ] }, { "cell_type": "code", "execution_count": 22, "id": "8b62f35a", "metadata": { "collapsed": false, "editable": true }, "outputs": [], "source": [ "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", "import numpy as np\n", "import pandas as pd\n", "from IPython.display import display\n", "np.random.seed(100)\n", "# setting up a 10 x 5 matrix\n", "rows = 10\n", "cols = 5\n", "X = np.random.randn(rows,cols)\n", "XPandas = pd.DataFrame(X)\n", "display(XPandas)\n", "print(XPandas.mean())\n", "print(XPandas.std())\n", "XPandas = (XPandas -XPandas.mean())\n", "display(XPandas)\n", "# This option does not include the standard deviation\n", "scaler = StandardScaler(with_std=False)\n", "scaler.fit(X)\n", "Xscaled = scaler.transform(X)\n", "display(XPandas-Xscaled)" ] }, { "cell_type": "markdown", "id": "bbaf614f", "metadata": { "editable": true }, "source": [ "Small exercise: perform the standard scaling by including the standard deviation and compare with what Scikit-Learn gives." ] }, { "cell_type": "markdown", "id": "e297e64a", "metadata": { "editable": true }, "source": [ "## Min-Max Scaling\n", "\n", "Another commonly used scaling method is min-max scaling. This is very\n", "useful for when we want the features to lie in a certain interval. To\n", "scale the feature $x_j$ to the interval $[a, b]$, we can apply the\n", "transformation" ] }, { "cell_type": "markdown", "id": "3a48d095", "metadata": { "editable": true }, "source": [ "$$\n", "x_j^{(i)} \\rightarrow (b-a)\\frac{x_j^{(i)} - \\min(x_j)}{\\max(x_j) - \\min(x_j)} - a\n", "$$" ] }, { "cell_type": "markdown", "id": "b836623d", "metadata": { "editable": true }, "source": [ "where $\\min(x_j)$ and $\\max(x_j)$ return the minimum and maximum value of $x_j$ over the data set, respectively." ] }, { "cell_type": "markdown", "id": "0cf9ca3e", "metadata": { "editable": true }, "source": [ "## Testing the Means Squared Error as function of Complexity\n", "One of \n", "the aims is to reproduce Figure 2.11 of [Hastie et al](https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf).\n", "We will also use Ridge and Lasso regression. \n", "\n", "Our data is defined by $x\\in [-3,3]$ with a total of for example $100$ data points." ] }, { "cell_type": "code", "execution_count": 23, "id": "409e549f", "metadata": { "collapsed": false, "editable": true }, "outputs": [], "source": [ "np.random.seed()\n", "n = 100\n", "maxdegree = 14\n", "# Make data set.\n", "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)" ] }, { "cell_type": "markdown", "id": "ed762bab", "metadata": { "editable": true }, "source": [ "where $y$ is the function we want to fit with a given polynomial.\n", "\n", "Write a first code which sets up a design matrix $X$ defined by a fifth-order polynomial. Scale your data and split it in training and test data." ] }, { "cell_type": "code", "execution_count": 24, "id": "a2d186a5", "metadata": { "collapsed": false, "editable": true }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", "from sklearn.preprocessing import PolynomialFeatures\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.pipeline import make_pipeline\n", "\n", "\n", "np.random.seed(2018)\n", "n = 50\n", "maxdegree = 5\n", "# Make data set.\n", "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", "TestError = np.zeros(maxdegree)\n", "TrainError = np.zeros(maxdegree)\n", "polydegree = np.zeros(maxdegree)\n", "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", "scaler = StandardScaler()\n", "scaler.fit(x_train)\n", "x_train_scaled = scaler.transform(x_train)\n", "x_test_scaled = scaler.transform(x_test)\n", "\n", "for degree in range(maxdegree):\n", " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n", " clf = model.fit(x_train_scaled,y_train)\n", " y_fit = clf.predict(x_train_scaled)\n", " y_pred = clf.predict(x_test_scaled) \n", " polydegree[degree] = degree\n", " TestError[degree] = np.mean( np.mean((y_test - y_pred)**2) )\n", " TrainError[degree] = np.mean( np.mean((y_train - y_fit)**2) )\n", "\n", "plt.plot(polydegree, TestError, label='Test Error')\n", "plt.plot(polydegree, TrainError, label='Train Error')\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "8f34fae7", "metadata": { "editable": true }, "source": [ "## More preprocessing examples, Franke function and regression" ] }, { "cell_type": "code", "execution_count": 25, "id": "5fc132f0", "metadata": { "collapsed": false, "editable": true }, "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", "id": "ad5b41a1", "metadata": { "editable": true }, "source": [ "## Mathematical Interpretation of Ordinary Least Squares\n", "\n", "What is presented here is a mathematical analysis of various regression algorithms (ordinary least squares, Ridge and Lasso Regression). The analysis is based on an important algorithm in linear algebra, the so-called Singular Value Decomposition (SVD). \n", "\n", "We have shown that in ordinary least squares the optimal parameters $\\beta$ are given by" ] }, { "cell_type": "markdown", "id": "a93ce01c", "metadata": { "editable": true }, "source": [ "$$\n", "\\hat{\\boldsymbol{\\beta}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", "$$" ] }, { "cell_type": "markdown", "id": "2f89cf96", "metadata": { "editable": true }, "source": [ "The **hat** over $\\boldsymbol{\\beta}$ means we have the optimal parameters after minimization of the cost function.\n", "\n", "This means that our best model is defined as" ] }, { "cell_type": "markdown", "id": "1bdec2cd", "metadata": { "editable": true }, "source": [ "$$\n", "\\tilde{\\boldsymbol{y}}=\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}} = \\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", "$$" ] }, { "cell_type": "markdown", "id": "d6090b0f", "metadata": { "editable": true }, "source": [ "We now define a matrix" ] }, { "cell_type": "markdown", "id": "71edebd0", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{A}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T.\n", "$$" ] }, { "cell_type": "markdown", "id": "fc1b8e60", "metadata": { "editable": true }, "source": [ "We can rewrite" ] }, { "cell_type": "markdown", "id": "c407cc78", "metadata": { "editable": true }, "source": [ "$$\n", "\\tilde{\\boldsymbol{y}}=\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}} = \\boldsymbol{A}\\boldsymbol{y}.\n", "$$" ] }, { "cell_type": "markdown", "id": "e674f439", "metadata": { "editable": true }, "source": [ "The matrix $\\boldsymbol{A}$ has the important property that $\\boldsymbol{A}^2=\\boldsymbol{A}$. This is the definition of a projection matrix.\n", "We can then interpret our optimal model $\\tilde{\\boldsymbol{y}}$ as being represented by an orthogonal projection of $\\boldsymbol{y}$ onto a space defined by the column vectors of $\\boldsymbol{X}$. In our case here the matrix $\\boldsymbol{A}$ is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix." ] }, { "cell_type": "markdown", "id": "6b5a2484", "metadata": { "editable": true }, "source": [ "## Residual Error\n", "\n", "We have defined the residual error as" ] }, { "cell_type": "markdown", "id": "631571fe", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{\\epsilon}=\\boldsymbol{y}-\\tilde{\\boldsymbol{y}}=\\left[\\boldsymbol{I}-\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\right]\\boldsymbol{y}.\n", "$$" ] }, { "cell_type": "markdown", "id": "03e7938e", "metadata": { "editable": true }, "source": [ "The residual errors are then the projections of $\\boldsymbol{y}$ onto the orthogonal component of the space defined by the column vectors of $\\boldsymbol{X}$." ] }, { "cell_type": "markdown", "id": "89c1cbc1", "metadata": { "editable": true }, "source": [ "## Simple case\n", "\n", "If the matrix $\\boldsymbol{X}$ is an orthogonal (or unitary in case of complex values) matrix, we have" ] }, { "cell_type": "markdown", "id": "997c8992", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{X}\\boldsymbol{X}^T = \\boldsymbol{I}.\n", "$$" ] }, { "cell_type": "markdown", "id": "7c3ad56e", "metadata": { "editable": true }, "source": [ "In this case the matrix $\\boldsymbol{A}$ becomes" ] }, { "cell_type": "markdown", "id": "4cc0e3f1", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{A}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T)=\\boldsymbol{I},\n", "$$" ] }, { "cell_type": "markdown", "id": "7304c055", "metadata": { "editable": true }, "source": [ "and we have the obvious case" ] }, { "cell_type": "markdown", "id": "0a8db981", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{\\epsilon}=\\boldsymbol{y}-\\tilde{\\boldsymbol{y}}=0.\n", "$$" ] }, { "cell_type": "markdown", "id": "d04ddf92", "metadata": { "editable": true }, "source": [ "This serves also as a useful test of our codes." ] }, { "cell_type": "markdown", "id": "044bd0ca", "metadata": { "editable": true }, "source": [ "## The singular value decomposition\n", "\n", "The examples we have looked at so far are cases where we normally can\n", "invert the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$. Using a polynomial expansion where we fit of various functions leads to\n", "row vectors of the design matrix which are essentially orthogonal due\n", "to the polynomial character of our model. Obtaining the inverse of the\n", "design matrix is then often done via a so-called LU, QR or Cholesky\n", "decomposition.\n", "\n", "As we will also see in the first project, \n", "this may\n", "however not the be case in general and a standard matrix inversion\n", "algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.\n", "\n", "There is however a way to circumvent this problem and also\n", "gain some insights about the ordinary least squares approach, and\n", "later shrinkage methods like Ridge and Lasso regressions.\n", "\n", "This is given by the **Singular Value Decomposition** (SVD) algorithm,\n", "perhaps the most powerful linear algebra algorithm. The SVD provides\n", "a numerically stable matrix decomposition that is used in a large\n", "swath oc applications and the decomposition is always stable\n", "numerically.\n", "\n", "In machine learning it plays a central role in dealing with for\n", "example design matrices that may be near singular or singular.\n", "Furthermore, as we will see here, the singular values can be related\n", "to the covariance matrix (and thereby the correlation matrix) and in\n", "turn the variance of a given quantity. It plays also an important role\n", "in the principal component analysis where high-dimensional data can be\n", "reduced to the statistically relevant features." ] }, { "cell_type": "markdown", "id": "ef9e05c1", "metadata": { "editable": true }, "source": [ "## Linear Regression Problems\n", "\n", "One of the typical problems we encounter with linear regression, in particular \n", "when the matrix $\\boldsymbol{X}$ (our so-called design matrix) is high-dimensional, \n", "are problems with near singular or singular matrices. The column vectors of $\\boldsymbol{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", "id": "d63adf14", "metadata": { "editable": true }, "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", "id": "5e78a531", "metadata": { "editable": true }, "source": [ "The columns of $\\boldsymbol{X}$ are linearly dependent. We see 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 $\\boldsymbol{X}^T\\boldsymbol{X}$ (the matrix we need to 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", "id": "2744881a", "metadata": { "editable": true }, "source": [ "$$\n", "\\begin{align*}\n", "\\boldsymbol{X} & = \\left[\n", "\\begin{array}{rr}\n", "1 & -1\n", "\\\\\n", "1 & -1\n", "\\end{array} \\right].\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "id": "037e81db", "metadata": { "editable": true }, "source": [ "We see easily that $\\mbox{det}(\\boldsymbol{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 $\\boldsymbol{X}$ has at least an eigenvalue which is zero." ] }, { "cell_type": "markdown", "id": "f21e5f16", "metadata": { "editable": true }, "source": [ "## Fixing the singularity\n", "\n", "If our design matrix $\\boldsymbol{X}$ which enters the linear regression problem" ] }, { "cell_type": "markdown", "id": "46f92b4a", "metadata": { "editable": true }, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\boldsymbol{\\beta} = (\\boldsymbol{X}^{T} \\boldsymbol{X})^{-1} \\boldsymbol{X}^{T} \\boldsymbol{y},\n", "\\label{_auto1} \\tag{1}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "id": "30476b84", "metadata": { "editable": true }, "source": [ "has linearly dependent column vectors, we will not be able to compute the inverse\n", "of $\\boldsymbol{X}^T\\boldsymbol{X}$ and we cannot find the parameters (estimators) $\\beta_i$. \n", "The estimators are only well-defined if $(\\boldsymbol{X}^{T}\\boldsymbol{X})^{-1}$ exits. \n", "This is more likely to happen when the matrix $\\boldsymbol{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", "A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change" ] }, { "cell_type": "markdown", "id": "36716f3b", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{X}^{T} \\boldsymbol{X} \\rightarrow \\boldsymbol{X}^{T} \\boldsymbol{X}+\\lambda \\boldsymbol{I},\n", "$$" ] }, { "cell_type": "markdown", "id": "a56a9662", "metadata": { "editable": true }, "source": [ "where $\\boldsymbol{I}$ is the identity matrix. When we discuss **Ridge** regression this is actually what we end up evaluating. The parameter $\\lambda$ is called a hyperparameter. More about this later." ] }, { "cell_type": "markdown", "id": "9484e1b3", "metadata": { "editable": true }, "source": [ "## Basic math of the SVD\n", "\n", "From standard linear algebra we know that a square matrix $\\boldsymbol{X}$ can be diagonalized if and only it is \n", "a so-called [normal matrix](https://en.wikipedia.org/wiki/Normal_matrix), that is if $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$\n", "we have $\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ or if $\\boldsymbol{X}\\in {\\mathbb{C}}^{n\\times n}$ we have $\\boldsymbol{X}\\boldsymbol{X}^{\\dagger}=\\boldsymbol{X}^{\\dagger}\\boldsymbol{X}$.\n", "The matrix has then a set of eigenpairs" ] }, { "cell_type": "markdown", "id": "7d0e79fd", "metadata": { "editable": true }, "source": [ "$$\n", "(\\lambda_1,\\boldsymbol{u}_1),\\dots, (\\lambda_n,\\boldsymbol{u}_n),\n", "$$" ] }, { "cell_type": "markdown", "id": "957d1974", "metadata": { "editable": true }, "source": [ "and the eigenvalues are given by the diagonal matrix" ] }, { "cell_type": "markdown", "id": "4da24ddd", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{\\Sigma}=\\mathrm{Diag}(\\lambda_1, \\dots,\\lambda_n).\n", "$$" ] }, { "cell_type": "markdown", "id": "63934409", "metadata": { "editable": true }, "source": [ "The matrix $\\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\\boldsymbol{U}$" ] }, { "cell_type": "markdown", "id": "3710e8a3", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", "$$" ] }, { "cell_type": "markdown", "id": "6fc2de6c", "metadata": { "editable": true }, "source": [ "with $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ or $\\boldsymbol{U}\\boldsymbol{U}^{\\dagger}=\\boldsymbol{I}$.\n", "\n", "Not all square matrices are diagonalizable. A matrix like the one discussed above" ] }, { "cell_type": "markdown", "id": "5c7cbfc4", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{X} = \\begin{bmatrix} \n", "1& -1 \\\\\n", "1& -1\\\\\n", "\\end{bmatrix}\n", "$$" ] }, { "cell_type": "markdown", "id": "30e83681", "metadata": { "editable": true }, "source": [ "is not diagonalizable, it is a so-called [defective matrix](https://en.wikipedia.org/wiki/Defective_matrix). It is easy to see that the condition\n", "$\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ is not fulfilled." ] }, { "cell_type": "markdown", "id": "10f85da7", "metadata": { "editable": true }, "source": [ "## The SVD, a Fantastic Algorithm\n", "\n", "However, and this is the strength of the SVD algorithm, any general\n", "matrix $\\boldsymbol{X}$ can be decomposed in terms of a diagonal matrix and\n", "two orthogonal/unitary matrices. The [Singular Value Decompostion\n", "(SVD) theorem](https://en.wikipedia.org/wiki/Singular_value_decomposition)\n", "states that a general $m\\times n$ matrix $\\boldsymbol{X}$ can be written in\n", "terms of a diagonal matrix $\\boldsymbol{\\Sigma}$ of dimensionality $m\\times n$\n", "and two orthognal matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$, where the first has\n", "dimensionality $m \\times m$ and the last dimensionality $n\\times n$.\n", "We have then" ] }, { "cell_type": "markdown", "id": "f9269daa", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\n", "$$" ] }, { "cell_type": "markdown", "id": "558c53b6", "metadata": { "editable": true }, "source": [ "As an example, the above defective matrix can be decomposed as" ] }, { "cell_type": "markdown", "id": "5f32a26d", "metadata": { "editable": true }, "source": [ "$$\n", "\\boldsymbol{X} = \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& 1 \\\\ 1& -1\\\\ \\end{bmatrix} \\begin{bmatrix} 2& 0 \\\\ 0& 0\\\\ \\end{bmatrix} \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& -1 \\\\ 1& 1\\\\ \\end{bmatrix}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", "$$" ] }, { "cell_type": "markdown", "id": "42617846", "metadata": { "editable": true }, "source": [ "with eigenvalues $\\sigma_1=2$ and $\\sigma_2=0$. \n", "The SVD exits always! \n", "\n", "The SVD\n", "decomposition (singular values) gives eigenvalues \n", "$\\sigma_i\\geq\\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=p$, the\n", "eigenvalues (singular values) are zero.\n", "\n", "In the general case, where our design matrix $\\boldsymbol{X}$ has dimension\n", "$n\\times p$, the matrix is thus decomposed into an $n\\times n$\n", "orthogonal matrix $\\boldsymbol{U}$, a $p\\times p$ orthogonal matrix $\\boldsymbol{V}$\n", "and a diagonal matrix $\\boldsymbol{\\Sigma}$ with $r=\\mathrm{min}(n,p)$\n", "singular values $\\sigma_i\\geq 0$ on the main diagonal and zeros filling\n", "the rest of the matrix. There are at most $p$ singular values\n", "assuming that $n > p$. In our regression examples for the nuclear\n", "masses and the equation of state this is indeed the case, while for\n", "the Ising model we have $p > n$. These are often cases that lead to\n", "near singular or singular matrices.\n", "\n", "The columns of $\\boldsymbol{U}$ are called the left singular vectors while the columns of $\\boldsymbol{V}$ are the right singular vectors." ] }, { "cell_type": "markdown", "id": "cc45bdee", "metadata": { "editable": true }, "source": [ "## Economy-size SVD\n", "\n", "If we assume that $n > p$, then our matrix $\\boldsymbol{U}$ has dimension $n\n", "\\times n$. The last $n-p$ columns of $\\boldsymbol{U}$ become however\n", "irrelevant in our calculations since they are multiplied with the\n", "zeros in $\\boldsymbol{\\Sigma}$.\n", "\n", "The economy-size decomposition removes extra rows or columns of zeros\n", "from the diagonal matrix of singular values, $\\boldsymbol{\\Sigma}$, along with the columns\n", "in either $\\boldsymbol{U}$ or $\\boldsymbol{V}$ that multiply those zeros in the expression. \n", "Removing these zeros and columns can improve execution time\n", "and reduce storage requirements without compromising the accuracy of\n", "the decomposition.\n", "\n", "If $n > p$, we keep only the first $p$ columns of $\\boldsymbol{U}$ and $\\boldsymbol{\\Sigma}$ has dimension $p\\times p$. \n", "If $p > n$, then only the first $n$ columns of $\\boldsymbol{V}$ are computed and $\\boldsymbol{\\Sigma}$ has dimension $n\\times n$.\n", "The $n=p$ case is obvious, we retain the full SVD. \n", "In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy." ] }, { "cell_type": "markdown", "id": "f77eda9e", "metadata": { "editable": true }, "source": [ "## Codes for the SVD" ] }, { "cell_type": "code", "execution_count": 26, "id": "87edcbe8", "metadata": { "collapsed": false, "editable": true }, "outputs": [], "source": [ "import numpy as np\n", "# SVD inversion\n", "def SVD(A):\n", " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n", " SVD is numerically more stable than the inversion algorithms provided by\n", " numpy and scipy.linalg at the cost of being slower.\n", " '''\n", " U, S, VT = np.linalg.svd(A,full_matrices=True)\n", " print('test U')\n", " print( (np.transpose(U) @ U - U @np.transpose(U)))\n", " print('test VT')\n", " print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n", " print(U)\n", " print(S)\n", " print(VT)\n", "\n", " D = np.zeros((len(U),len(VT)))\n", " for i in range(0,len(VT)):\n", " D[i,i]=S[i]\n", " return U @ D @ VT\n", "\n", "\n", "X = np.array([ [1.0,-1.0], [1.0,-1.0]])\n", "#X = np.array([[1, 2], [3, 4], [5, 6]])\n", "\n", "print(X)\n", "C = SVD(X)\n", "# Print the difference between the original matrix and the SVD one\n", "print(C-X)" ] }, { "cell_type": "markdown", "id": "9594d07b", "metadata": { "editable": true }, "source": [ "The matrix $\\boldsymbol{X}$ has columns that are linearly dependent. The first\n", "column is the row-wise sum of the other two columns. The rank of a\n", "matrix (the column rank) is the dimension of space spanned by the\n", "column vectors. The rank of the matrix is the number of linearly\n", "independent columns, in this case just $2$. We see this from the\n", "singular values when running the above code. Running the standard\n", "inversion algorithm for matrix inversion with $\\boldsymbol{X}^T\\boldsymbol{X}$ results\n", "in the program terminating due to a singular matrix." ] }, { "cell_type": "markdown", "id": "83495077", "metadata": { "editable": true }, "source": [ "## Note about SVD Calculations\n", "\n", "The $U$, $S$, and $V$ matrices returned from the **svd()** function\n", "cannot be multiplied directly.\n", "\n", "As you can see from the code, the $S$ vector must be converted into a\n", "diagonal matrix. This may cause a problem as the size of the matrices\n", "do not fit the rules of matrix multiplication, where the number of\n", "columns in a matrix must match the number of rows in the subsequent\n", "matrix.\n", "\n", "If you wish to include the zero singular values, you will need to\n", "resize the matrices and set up a diagonal matrix as done in the above\n", "example" ] }, { "cell_type": "markdown", "id": "1f811c23", "metadata": { "editable": true }, "source": [ "## Friday September 3\n", "\n", "[Video of Lecture from 2020](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember11.mp4?vrtx=view-as-webpage) and [handwritten notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/NotesSeptember11.pdf)\n", "\n", "More material will be added here, see handwritten notes also. Note that this material will be cleaned up after the lecture of Friday September 3. See the handwritten notes from Friday's lecture at